Tuesday, November 18, 2014

Asp.net Binding


Asp.net Data binding that provides much easy way to manipulate data to the control eg.gridview,dropdownlist etc
I’ve notice when we are binding there are some unnecessary codes
 Dropdownlist1.DataTextField = "JObName";
 Dropdownlist1.DataValueField = "JobID"
 Dropdownlist1.DataSource = lstJobs;
 Dropdownlist1.DataBind();
We’re calling DataBind() method to asking to binding.totaly 4 lines of codes is required to bind dropdownlist.what is if we have common method to call to binding.
to find a way to overcome this issue in mind, I thought to create common method to bind it .oh no situation getting will be worsen , have to be specified to each of the  control to bind. Generic is there to solve my issue.
I wrote generic extension method to bind all controls…..
Here is the code…
    public static class EasyBinds
    {
        public static void EasyBind<T>(this Control ct, T t,   string ValueMember = "", string DisplayMember = "")
        {
            Utility<T>.CustomBind(ct, t,  ValueMember, DisplayMember);
        }
    }

    public static class Utility <T2>
    {
        public static void CustomBind(Control gv, T2 lst, string display = null, string value = null)
        {
            if (gv is GridView)
            {
                ((GridView)gv).DataSource = lst;
                ((GridView)gv).DataBind();
            }
            else if (gv is DropDownList)
            {
                ((DropDownList)gv).DataTextField = display;
                ((DropDownList)gv).DataValueField = value;
                ((DropDownList)gv).DataSource = lst;
                ((DropDownList)gv).DataBind();
            }
            else if(gv is ListBox)
            {
                ((ListBox)gv).DataTextField = display;
                ((ListBox)gv).DataValueField = value;
                ((ListBox)gv).DataSource = lst;
                ((ListBox)gv).DataBind();
            }
            else
            {
                throw new Exception("Invalid control to bind");
            }
        }
    }

Calling to method
GridView1.EasyBind<List<Employee>>(lst);
DropDownList2.EasyBind<List<Job>>(lstJobs, "JObName", "JobID");
ListBox1.EasyBind<List<Job>>(lstJobs, "JObName", "JobID");

Happy coding...

Monday, November 17, 2014

Working With Asp.net GRIDVIEW

Lets play with asp.net GRIDVIEW
hi guys, today I’m going to demonstrate working with grid view with different situations.asp.net provides much more flexible way to (tabular) to represent data  .keep it mind what every server tags finally converted to the classical html code (GRIDview to html table).
What is the easiest way to bind grid view?
1)Using Automaically Genarated columns
This method directly bind all the data source columns into grid.(good for only display data)
2)BoundField
If you’re not working data key fields in bound filed then you can’t able to get the selected cell value using column name , have to work with index?
Working with index like calling to trouble????????????????????
So what is the better way?
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  DataKeyNames="EmpNo,EmpName"
        ShowHeaderWhenEmpty="True">
        <Columns>
            <asp:BoundField HeaderText="EmpNO" DataField="EmpNO" />
            <asp:BoundField HeaderText="EmpName" DataField="EmpName" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:DropDownList ID="DropDownList1" runat="server"        >
                    </asp:DropDownList>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>
            [Data not found]
        </EmptyDataTemplate>
    </asp:GridView>
Above code snippet shows in yellow color, to mark the column name as data key names. Then we can access the columns using data key names.
Eg. Int empID=(int)GridView1.DataKeys[0]["EmpNo"];

3)Template Filed
If we are using totally template fieds like lable,textbox it also very secure (can access data via its id) way to working with data, but it take times to develop. In exceptional scenario like add dropdown list then you’ll have to use it.

Here with I’ve attached code which contained working with selected dropdown item in grid view and events.

Happy coding.
(thre're more alternative way can find on internet)

Sunday, September 28, 2014

Jquery Number to Word alert

Hi guys, today I’m going to demonstrate jquery alert box. Recently I was received a project by manager and that is invoicing and payment system and i pointed out sometimes I also bit difficultly to entering the prices. , Because sometime I enter values incoreclty.to avoid the same issue to users, I decided to build the alert box to display the value in the text box.
 easy configuration , just need to add the  class="WordToNum" to textbox

Entire code snippt:
<style type="text/css">
        #xx a IMG
        {
            display: none;
        }
     
        #PageDiv
        {
        }
        .bubble
        {
            background-color: #F2F2F2;
            border-radius: 5px;
            box-shadow: 0 0 6px #B2B2B2;
            display: inline-block;
            padding: 10px;
            position: relative;
            vertical-align: top;
            background: #e14f1c url(images/ui-bg_gloss-wave_45_e14f1c_500x100.png) 50% top repeat-x;
        }
     
        .bubble::before
        {
            background: #e14f1c url(images/ui-bg_gloss-wave_45_e14f1c_500x100.png) 50% top repeat-x;
            content: "\00a0";
            display: block;
            position: absolute;
            transform: rotate( 29deg ) skew( -35deg );
            -moz-transform: rotate( 29deg ) skew( -35deg );
            -ms-transform: rotate( 29deg ) skew( -35deg );
            -o-transform: rotate( 29deg ) skew( -35deg );
            -webkit-transform: rotate( 29deg ) skew( -35deg );
            width: 20px;
        }
     
        .me
        {
            float: left;
            background: #e14f1c url(images/ui-bg_gloss-wave_45_e14f1c_500x100.png) 50% top repeat-x;
        }
     
        .me::before
        {
            background: #e14f1c url(images/ui-bg_gloss-wave_45_e14f1c_500x100.png) 50% top repeat-x;
            left: -10px;
            top: 2px;
        }
    </style>

 <script src="https://code.jquery.com/jquery-git1.min.js"></script>
<script type="text/javascript">
var th = ['', 'thousand', 'million', 'billion', 'trillion'];
// uncomment this line for English Number System
// var th = ['','thousand','million', 'milliard','billion'];

var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']; var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']; function toWords(s) { s = s.toString(); s = s.replace(/[\, ]/g, ''); if (s != parseFloat(s)) return 'not a number'; var x = s.indexOf('.'); if (x == -1) x = s.length; if (x > 15) return 'too big'; var n = s.split(''); var str = ''; var sk = 0; for (var i = 0; i < x; i++) { if ((x - i) % 3 == 2) { if (n[i] == '1') { str += tn[Number(n[i + 1])] + ' '; i++; sk = 1; } else if (n[i] != 0) { str += tw[n[i] - 2] + ' '; sk = 1; } } else if (n[i] != 0) { str += dg[n[i]] + ' '; if ((x - i) % 3 == 0) str += 'hundred '; sk = 1; } if ((x - i) % 3 == 1) { if (sk) str += th[(x - i - 1) / 3] + ' '; sk = 0; } } if (x != s.length) { var y = s.length; str += 'point '; for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' '; } return str.replace(/\s+/g, ' '); }

</script>

<script type="text/javascript">
$(document).ready(function(evt) {




                $('.WordToNum').on('keyup', function (evst) {
                 
                 //if ($(this).val().length == 0) return;
 var words = toWords($(this).val());
                    //if (words.length == 0) return;
                    //alert($(this).attr("id"));
                    JqueryAlertJS(words, $(this).attr("id"));
                 
                });


                 $('#ff').click(function(eeee) {
alert('xx');
                   // $('#ff').remove();
                });

         
$( ".WordToNum" )
  .focusout(function() {
      $('#ff').remove();
  })
   .focus(function() {

var words = toWords($(this).val());

     JqueryAlertJS(words , $(this).attr("id"));
  })

});

        function JqueryAlertJS(message, id) {
            $('#ff').remove();

            var position = $('#' + id).position();
            var top = position.top;
            var l = position.left + $('#' + id).width() + 20;
            // alert(l);
div = $("<div id='ff' class='ui-corner-all bubble me towords'   style='color:white;z-index:500500;                                    background-color:#e14f1c;position:absolute;top:" + position.top + "px;left:" + l + "px;'>").html(message);
            //$("#numm").prepend(div);
 $( "#numm" ).append(div );

            return false;

        }

</script>

<br />
<div id="numm"></div>
<input class="WordToNum" id="MainContent_TextBox1" name="ctl00MainContentTextBox1" type="text" />

Sunday, August 31, 2014

Populate asp.net gridview when data is empty

Asp.net that doesn't provide to display grid-view in empty. :)
Let’s explain it in example
//dt=DataTable which is empty .
Gridview1.DataSource=dt;
GridView1.DataBind();
Above mentioned code, that will not displayed gridview, because of it is empty.to overcome to this issue we can use  EmptyDataText="Data Not Found" propery in gridview.
it's better than displaying invisible gridview to user.



another option (much user friendly)
Binding user define datatable with one datarow.
 DataTable dt = new DataTable();
dt.Columns.Add("Name");
 dt.Columns.Add("ID");                                                   
 DataRow dr;
dr = dt.NewRow();
dr["Name"] = "xx";
dr["ID"] = "xx";
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();

more efficient way
ShowHeaderWhenEmpty="true" property in gridview set to true.
and set the emptydataTemplate
            <EmptyDataTemplate>
                Data Not Found
            </EmptyDataTemplate>
advantage : no need work with the datatable to display empty row.

happy coding Download

Friday, June 6, 2014

avoid fire selected index change event while data binding in combo box (windows application)

Rain rain go away come aging another day oh no please don’t come again. Rainy session has begun and flooded everywhere.
Today I’m going discuss about another issue in combobox (windows app)
The problem was when we’re binding combobox , if there’re combo selected index change event it will be triggered while data binding.to avoid the issue , attach and detached the event handler.
this.cmbDyeJob.SelectedIndexChanged += new System.EventHandler(this.cmbDyeJob_SelectedIndexChanged);

cmb.DataSource = lst;

this.cmbDyeJob.SelectedIndexChanged -= new System.EventHandler(this.cmbDyeJob_SelectedIndexChanged);

Solution 
Add SelectionChangeCommitted instead of SelectedIndexChanged Event.

Solution 2 (Tricky got form stackoverflow)
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!((ComboBox)sender).Focused) return;
        }
In the 2nd solution, it fires the selected index change event but it’ll return after first line is executed.(noted combobox should not be focused while binding)


Happy Coding…..

Monday, May 26, 2014

Coding tricks in .net part 01

In this post i'm going to discuss some of the tricks in .net application that I've used.to avoid unnecessary code lines , defensive programming are the required talent of the programmer.

1)Error handling with showing message
always write your code starting point within try catch block. eg. only for raise it event root (button click event)
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtName.Text.Trim().Length == 0)
                {
                    MessageBox.Show("Name is required");
                    return;
                }
                /// do some coding here
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error");
            }
        }.
above code is nothing wrong, but it used unnecessary return statements.
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtName.Text.Trim().Length == 0)
                {
                    throw new ApplicationException("Name is required");
                }
                /// do some coding here
            }
            catch (ApplicationException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error");
            }
        }
Application level errors is captured by ApplicationException class.there're no any return and more clear and specific.

2) Windows application Stores object in textbox (suppose you want to display Employee name in text box and also required to hide Employee id form the screen.one textbox for employee and lable for empid which is invisible)
in Textbox has property called Tag , that can hold required data invisibly.
            Employee emp = new Employee() { ID = 11, Name = "NImal" };
            //Assing
            txtName.Text = emp.Name;
            txtName.Tag = emp;//obj is employee related data eg.ID,DateJoind etc

            //retrive
            Employee empObje =(Employee) txtName.Tag;

////////////////////////////////////
    public class Employee
    {
        public string Name { get; set; }
        public int ID { get; set; }

    }

3) add rows to DataGridView
           int i= dataGridView1.Rows.Add();
           dataGridView1.Rows[i].Cells["Column1"].Value = 22;

           dataGridView1.Rows[i].Cells["Column2"].Value = "SSS";
above code is to add new row to datagridview (which has 2 columns).nothing wrong it.what will happen if column names are changed.code will be complied at run time will be caused an error .because column names are not strongly type. dataGridView1.Rows is duplication among the code.to alternative this issue , here code snippet.

           DataGridViewRow gr =dataGridView1.Rows[dataGridView1.Rows.Add()];
           gr.Cells[Column1.Name].Value = 22;

           gr.Cells[Column2.Name].Value = "SSS";

4)strongly type session and viewstate (asp.net)
in asp.net application we stored data as globally (session) and page level (view state).
eg. Session["abc"]=1500;
      ViewState["aa"]="xx";
these are not strongly types ,only accept object and we have cast it before use it.
        //Session
        public int sEmpID
        {
            get {
                if ((Session["empID"] == null))
                {
                    return 0;//throw new applicationException("Session expired");
                }
                else
                {
                    return Convert.ToInt16(Session["empID"]);
                }
            }
            set { Session["empID"] = value; }
        }

        //ViewState
        public bool vsIsEdit
        {
            get { return Convert.ToBoolean(ViewState["IsEdit"]); }
                               set { ViewState["IsEdit"] = value; }
        }

/////////////// assign values
            sEmpID = 22;


            vsIsEdit = true;

happy coding.........

Sunday, May 25, 2014

Table value parameter with .net (real world example) Part 01

hi all
these days dark clouds gives free bath chance while are traveling by bike. Happy feeling when my boots are getting wet.
In this post that I'm going to demonstrate another cool feature of .net with sql server. how to send bulk of data (ado.net) as parameter to stored procedure?  is it clear about the topic. if it's not here the scenario.

Suppose we're developing procurement systems which generate the purchase order .I'll take a small part of the system.There're lot of article in internet about the topic but I wanted to give it with real life example to get the idea.



In above has mentioned the tables which has one to - many relationship, it means one po has many items (simple example).in earlier what I did was when saving po , one sp for po and another sp for po details.
here is the code snippet c#.
first fill the user objects 
            List<PODetails> lstOfPoDetails = new List<PODetails>();
            PODetails pod;
            pod = new PODetails() {POItem="ABC",Qty=22 };
            lstOfPoDetails.Add(pod);

            pod = new PODetails() { POItem = "xyz",Qty=4 };
            lstOfPoDetails.Add(pod);

            PO po = new PO()
            {
                PODate = DateTime.Now,
                CreatedUser = 33,
                lstPODetails = lstOfPoDetails
            };

Save user objects to database

 using (var Ts=new  TransactionScope())
            {
                using (var con=new SqlConnection("con is here"))
                {
                    //First Save po get the po id to pass the po deatils
                    SqlCommand com;
                    com = new SqlCommand("InsertPO", con);
                    com.Parameters.AddWithValue("@podate", po.PODate);
                    com.Parameters.AddWithValue("@user", po.CreatedUser);

                    #region Get the POID to pass the po detils
                    SqlParameter para = new SqlParameter("@poid", 0);
                    para.Direction = ParameterDirection.InputOutput;
                    com.Parameters.Add(para);
                    com.ExecuteNonQuery();
                    int poID = (int)com.Parameters["@poid"].Value;//Task one completed

                    //Save po details with po id
                    foreach (PODetails p in po.lstPODetails)
                    {
                        com = new SqlCommand("InsertPODetails", con);
                        com.Parameters.AddWithValue("@poid", poID);
                        com.Parameters.AddWithValue("@item", p.POItem);
                        com.Parameters.AddWithValue("@Qty", p.Qty);
                        com.ExecuteNonQuery();
                    }

                    #endregion
                    Ts.Complete();
                }
            }

nothing wrong above code   ,but we have to specifically work with the stored procs, one for po and another for podetails.podeatils has iteration that calls to proc for its each iterations. This is a disadvantage of this method (performance issue).to alternative to this approach , sql serer database has table value parameter to accomplish this task it provides more efficient and less code approach.
accomplish this task in Table Type parameter in sql server.

In Sql server database under the programmability -> Types has User Defined Table Types

here are the script for the table
CREATE TYPE [dbo].[type_po] AS TABLE(
[poID] [int] NULL,
[CreatedDate] [datetime] NULL,
[poDetID] [int] NULL,
[Item] [varchar](50) NULL,
[qty] [decimal](18, 4) NULL
)

we have to use the create type script to create type table.
here are the script of insert po & podetails
create proc InsertPOs
-- which accepts one table value parameter. 
-- It should be noted that the parameter is readonly
@poType   dbo.typepo readonly

as
begin
declare @poID int

--Insert PO record and get poid
INSERT INTO  [dbo].[PO]  ([CreatedDate])    
(select top 1 [CreatedDate] from @poType)

set @poID=(select IDENT_CURRENT('PO'))

-- Insert PODetail reference with poid
INSERT INTO  [dbo].[PODetails] (poID,Item,qty)
select  @poID,Item,qty  from @poType
end

database part is done.
1)create type table
2)using that type table create proc to insert po

now we'll move on to c# side.now create DataTable (C#) mapping to typepo Type table.

//Create DataTable matching with the Type Table column names and data types
            //CREATE TYPE type_po AS TABLE 
            //(
            // [poID] [int]  ,
            // [CreatedDate] [datetime] ,
            // [poDetID] [int]  ,
            // [Item] [varchar](50) ,
            // [qty] [decimal](18, 4) 
            //)

            DataTable type_po = new DataTable();
            type_po.Columns.Add("poID", typeof(int));
            type_po.Columns.Add("CreatedDate", typeof(DateTime));
            type_po.Columns.Add("poDetID", typeof(int));
            type_po.Columns.Add("Item", typeof(string));
            type_po.Columns.Add("qty", typeof(decimal));

            DataRow dr;
            dr = type_po.NewRow();
            dr["poid"] = 0;
            dr["CreatedDate"] = DateTime.Now;
            dr["podetid"] = 0;
            dr["item"] = "ABC";
            dr["qty"] = 100;
            type_po.Rows.Add(dr);

            dr = type_po.NewRow();
            dr["poid"] = 0;
            dr["CreatedDate"] = DateTime.Now;
            dr["podetid"] = 0;
            dr["item"] = "xyz";
            dr["qty"] = 200;
            type_po.Rows.Add(dr);

pass data table to sp
                using (var ts = new TransactionScope())
                {
                    using (var con = new SqlConnection(Con))
                    {
                        con.Open();
                        SqlCommand com = new SqlCommand("DBO.InsertPOs", con);
                        com.Parameters.AddWithValue("@poType", t);
                        com.CommandType = CommandType.StoredProcedure;
                        int x = com.ExecuteNonQuery();
                    }
                    ts.Complete();
                }
that's all.this is much easy way to handle one to many scenario.
Advantages :round trip to the database is minimized(only one)
                   less coding and all logic in one place .

Disadvantage : can't alter type table and can't delete when have reference it.(solution : one type table to one sp )

in this part 01 , only demonstrate it's basic functionality of Table value parameters.in part 02 i intend to disuses some of the advance features of it (eg : debugging ).
download script
happy coding

Thursday, May 22, 2014

Jquery Message box in asp.net application

In asp.net application, there is not any inbuilt message box feature .what developers do is display message to the Label. It’s not much get attention from the user because, not focused like windows application message box.
In java scripts alerts is one of the way display message, its ok but not much user friendly.
jquery (Java script library), that provides more facility to handle client side effects and data manipulations (calling to web services).In this post I’m going to demonstrate prompt message box using jquery UI library.cool feature is we can process server side codes and then we can display message. Click button1 and save and display message box.
        protected void Button1_Click(object sender, EventArgs e)
        {
            // do what ever task in asp.net (Server side coding)
            //save data to database and dispay message
            //
            //
            SiteMaster.NewMessageBox(" Data Saved", SiteMaster.ErrorType.Information, this);
        }

here is project structure;












happy coding....

Wednesday, May 21, 2014

Crystal Reports & Stored Proc in Visual Studio

Today I’m going talk about the reporting issues which I have been faced. In .net we can design crystal report in different ways. Using XML Schema, Dataset component some of methods which I’ve used, are much difficult to maintain. Suppose you have to change the report field, then you have to change xml or dataset by manually and after that refresh the report. Other disadvantage is, we have to provide the data source (DataTable,DataSet or List of objects)

Here is the eg.
this is method return data to display . tblReport datatable column names should be match with the xml or dataset columns names (mapping).
DataTable tblReport=GetAllDetails();
ReportDocument rptDoc = new ReportDocument();
rptViewWorkOrderDetailsWithYC rpt = new rptViewWorkOrderDetailsWithYC();
rptDoc = rpt;
rptDoc.SetDataSource(tblReport);
rpt.SetParameterValue("@@@Company", "cc");//Pameters passing to the report
rpt.SetParameterValue("@@@Heading", "cccc”);
crystalReportViewer1.ReportSource = rptDoc;  //Display report in Report Viewer


Above code is well running code, but it has to lot of mapping things.

with Proc as data source:

Design crystal reports with stored procedure are more efficiency way to build reports. It is not needed any data sources. We can use ado data provider to access the store proc in database. If proc has any parameters then it will be added automatically to report.

here are the steps :
Step 1:Make the connection to the crystal report.add crystal report to project and using selection expert set the connection (ole db - ado).


Step 2:after completing step 1, then (Assume we already have created a proc in database)add proc to report.         
Developer PC1 and DatabaseServer DevelopementServer1 (discuss later )

Test is the SP that i used.
create proc [dbo].[Test]
@UserName varchar(50)
as
select 'MYPC ' + @UserName as test

In Test sp has parameter as @Username, it will be automatically added to the report.
 report desining part is done.here code snippet to run the report.
        ReportDocument rptDoc = new ReportDocument();
        Report.TEST rpt = new Report.TEST();
        rptDoc = rpt;
        rpt.SetParameterValue("@UserName", "cc");//Pameters passing to the report
        crystalReportViewer1.ReportSource = rptDoc;

how easy it is.no any column mapping & only need proc that's all.this will be displayed report as you wished in production (in pc1 with DevelopementServer1 )
when this report is hosted into live system , there no errors but data will be wrong .because it will be displayed records in pc & DevelopementServer1 machines.
here is the issue.


PC01 is the pc which is developed, remember report is added to proc in this (pc01)machine database.now it has changed to new server.got the point.
now it is needed to change the server name as according to environment.in .net windows or web application we used file called app or web configuration file to share common-thing through out application.database connection is usually stored in this config file , we change it according to development environment.

  <connectionStrings>
    <add name="con" connectionString="Data Source=pc01;Initial Catalog=Teset;User ID=sa" providerName="System.Data.SqlClient" />
  </connectionStrings>

how do we overcome the these situation in crystal report with proc in .net.
simple thing, have to change the connection string in reprot dynamically according to config file connection string.

        #region change the report data server according to app.config
        ConnectionInfo getConnectionInfo()
        {
            ConnectionInfo ConnInfo = new ConnectionInfo();
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString.ToString());
            ConnInfo.UserID = "sa";
            ConnInfo.Password = "";
            ConnInfo.ServerName = con.DataSource;
            ConnInfo.DatabaseName = con.Database;
            return ConnInfo;
        }
        private void SetDBLogonForReport(ReportDocument reportDocument)
        {
            ConnectionInfo connectionInfo = getConnectionInfo();
            Tables tables = reportDocument.Database.Tables;
            foreach (CrystalDecisions.CrystalReports.Engine.Table table in tables)
            {
                TableLogOnInfo tableLogonInfo = table.LogOnInfo;
                tableLogonInfo.ConnectionInfo = connectionInfo;
                table.ApplyLogOnInfo(tableLogonInfo);
            }
        }
        #endregion
here are the two method it changes the connection using connection in config file.
before set the crystalreportviewer1 report source add SetDBLogonForReport with report document parameter.

            SetDBLogonForReport(rptReportDocument);
            crystalReportViewer1.ReportSource = rptReportDocument;


that's all.hope this will help to all guys.

happy coding...