Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, October 20, 2013

getting basic data types using reflection than nullable

While using class properties to use for data base connectivity, i.e. LINQ TO SQL, I was facing issue for nullable types. I was using Reflection to fetch property type names, but for NULLABLE properties it use to send me property type name as NULLABLE`1. I was suppose to use following switch case (Determine Nullable properties via reflection)
public static string getJSType(PropertyInfo propertyinfo)
        {

//GetCoreType function returns Property type.
switch (GetCoreType(propertyinfo.PropertyType).Name.ToUpper())
                {
                    case "INT16":
                        return "number";
                    case "UINT16":
                        return "number";
                    case "SHORT":
                        return "number";
                    case "USHORT":
                        return "number";
                    case "INT32":
                        return "number";
                    case "UINT32":
                        return "number";
                    case "INT":
                        return "number";
                    case "UINT":
                        return "number";
                    case "INT64":
                        return "longnumber";
                    case "UINT64":
                        return "longnumber";
                    case "LONG":
                        return "longnumber";
                    case "ULONG":
                        return "longnumber";
                    case "DECIMAL":
                        return "decimal";
                    case "DOUBLE":
                        return "float";
                    case "BIGINT":
                        return "longnumber";
                    case "STRING":
                        return "text";
                    case "DATETIME":
                        return "datepicker";
                    case "BOOLEAN":
                        return "flag";
                }
            //}
            return "text";
        }
To determine type of NULLABLE properties via reflection, I used following function GetCoreType
 private Type GetCoreType(Type type)
        {
            if (type.IsGenericType &&
                type.GetGenericTypeDefinition() == typeof(Nullable<>))
                return Nullable.GetUnderlyingType(type);
            else
                return type;
        }
Find Type of Nullable Properties via Reflection. Determine type of Nullable properties view Relection. While using reflection get core property type of nullable properties.
Submit this story to DotNetKicks

Read more...

Saturday, September 21, 2013

Remove Double Quotes From String

To Strip double Quotes from string use following code

Lets say s is out string
string newstr = string.Empty
s = s.Replace("""", "");
OR
string newstr = string.Empty
s = s.Replace("\"", "");

Submit this story to DotNetKicks

Read more...

Monday, February 4, 2013

The 'System.Web.Security.SqlMembershipProvider' requires a database schema compatible with schema version '1'. Solved...

While working with Asp.NET and Membership, using MS SQL 2008 R2 I came across following error. My web application was working perfect on my local machine but when I hosted it on remote server I got following error.
The 'System.Web.Security.SqlMembershipProvider' requires a database schema compatible with schema version '1'. However, the current database schema is not compatible with this version. You may need to either install a compatible schema with aspnet_regsql.exe (available in the framework installation directory), or upgrade the provider to a newer version.
After R&D I had came across three possible solutions "WHICH I THINK ARE RIGHT, AS THEY WORKED FOR ME IN DIFFERENT SCENARIOS."

  1. Check "aspnet_SchemaVersions" table in database and make sure CompatibleSchemaVersion is set to "1" for all the Features (e.g. common, membership, role manager etc) available in table. Also make sure IsCurrentVersion column values are set to 'True" for all Features.
  2. In Web.Config, and aspnet_Applications table check if application Name is matching or not. Application name in web.config's Membership>Providers, Profile>Providers, RoleManager>Providers are matching with application name in database.
  3. In Membership>Provider I had "AspNetSqlMembershipProvider" type as type="System.Web.Security.SqlMembershipProvider" which I modified (after referring to some articles online) to type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Application worked for me when I checked all these things and made changes in my application.
Submit this story to DotNetKicks

Read more...

Wednesday, January 9, 2013

ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized

ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized

While using transaction in Asp.net/C# I got above error.

To solve this error I simply added Transaction object in SqlCommand like below
SqlTransaction Transaction;
conn.Open();
Transaction = conn.BeginTransaction(); 
SqlCommand cmd = new SqlCommand(sql, conn, Transaction);

Submit this story to DotNetKicks

Read more...

Tuesday, July 31, 2012

Form Authentication Is Not Working

Form Authentication Is Not Working in IE 8. I am working on one web based project where I started with user management and struggled to make Form Authentication work... :( without testing it on other browsers. I had following settings in web.config...

      
    

After struggling for the day on "Form Authentication Is Not Working" and to Make it work... I tested it in Firefox and Google Crome and it did work very well :(, without any error. What I realized is, there is some Issue with IE 8 and Cookies we are using for Form authentication, so I made following change in Web.Config Setting.

      
    

Which in turn changed URL for IE 8 by adding some encoded information as a part of URL (going cookie-less), and in other browsers it allowed cookies and URL was without any Encoding added i.e. it was using Cookies. I hope this piece of Information will be Useful.
Submit this story to DotNetKicks

Read more...

Getting session state in httphandlers - ashx files

To do session state handling in Generic handlers or ashx files, there are two possibilities Readonly session state: we need to implement IReadOnlySessionsState interface, usefollowing demo code.
using System;
using System;
using System.Web;
using System.Web.SessionState;

public class Handler : IHttpHandler, IReadOnlySessionState
{

    public void ProcessRequest(HttpContext context)
    {
    if (HttpContext.Current.Session["SessionsName"] != null)
     {
      context.Response.Write(HttpContext.Current.Session["SessionsName"]);
     }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}
Read and Write Access to state: we need to implement IRequiresSessionState interface, usefollowing demo code.
using System;
using System.Web;
using System.Web.SessionState;

public class Handler : IHttpHandler, IRequiresSessionState
{

 public void ProcessRequest(HttpContext context)
  {
   if (HttpContext.Current.Session["SessionsName"] != null)
    {
      HttpContext.Current.Session["SessionsName"] = "Demo Session";
     }
   }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}
Submit this story to DotNetKicks

Read more...

Saturday, August 6, 2011

Facebook like Autosuggest in Asp.net

This article is about using AjaxToolKit AutoCompleteExtender, to make Facebook like Autosuggest in asp.net. To use AutoCompleteExtender is simple, but we can modify the code little bit and make it more user friendly. Check out following Image. (Download Demo code for better understanding.)

Note: Democode is developed in VS2010 and .net framework 4.0

AutoComplete extender can be used to extend behaviour of any ASP.NET TextBox control. Ajaxtoolkit autocomplete extender associates textbox control with a popup panel to display words which begins with the prefix that is entered into the text box. We can define the minimum length of charachters, after which extender displays a popup containing words or phrases that start with that value.

</div> </div><h2> AutoComplete Demonstration</h2> Type some characters in this textbox. The web service returns names which contains text you have typed. <table> <tbody> <tr> <td> <asp:textbox autocomplete="off" id="txtAutoComplete" runat="server" width="300"></asp:textbox></td> <td><div id="divLoading" style="display: none;"> Loading...</div> </td> </tr> </tbody></table> <ajaxtoolkit:autocompleteextender behaviorid="AutoCompleteEx" completioninterval="500" completionlistcssclass="completionListClass" completionlisthighlighteditemcssclass="CompletionListHighlightedItemClass" completionlistitemcssclass="completionlistItemClass" completionsetcount="0" delimitercharacters=";, :" enablecaching="true" id="autoComplete1" minimumprefixlength="2" onclienthidden="ListPopulated" onclientitemselected="onSelection" onclientpopulated="ItemSelected" onclientpopulating="ListPopulating" runat="server" servicemethod="GetCompletionList" servicepath="AutoComplete.asmx" showonlycurrentwordincompletionlistitem="true" targetcontrolid="txtAutoComplete"> <animations> <onshow> <sequence> <%-- Make the completion list transparent and then show it --%> <opacityaction opacity="0"> <hideaction visible="true"> <%--Cache the original size of the completion list the first time the animation is played and then set it to zero --%> <scriptaction script=" // Cache the size and setup the initial size var behavior = $find('AutoCompleteEx'); if (!behavior._height) { var target = behavior.get_completionList(); behavior._height = target.offsetHeight - 2; target.style.height = '0px'; }"> <%-- Expand from 0px to the appropriate size while fading in --%> <parallel duration=".4"> <fadein> <length endvaluescript="$find('AutoCompleteEx')._height" propertykey="height" startvalue="0"> </length></fadein></parallel> </scriptaction></hideaction></opacityaction></sequence> </onshow> <onhide> <;%-- Collapse down to 0px and fade out --%>; <parallel duration=".4"> <fadeout> <length endvalue="0" propertykey="height" startvaluescript="$find('AutoCompleteEx')._height"> </length></fadeout></parallel> </onhide> </animations> </ajaxtoolkit:autocompleteextender> <%-- Prevent enter in textbox from causing the collapsible panel from operating --%> <input style="display: none;" type="submit" /> <div id="divAddressDetails"> </div> </div>

To Make AutoExtender work, we need to define certain properties.
  1. TargetControlID: The TextBox control where the user types content to be automatically completed.
  2. ServicePath: The path to the web service that the extender will pull the word\sentence completions from. If this is not provided, the service method should be a page method.
  3. ServiceMethod - The web service method to be called. The signature of this method must match the following:
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public string[] YourFunctionName(string prefixText,int count)
    

    Syntax of the function should remain same.
  4. CompletionListCssClass - Css Class that will be used to style the completion list flyout.
  5. CompletionListItemCssClass - Css Class that will be used to style an item in the AutoComplete list flyout.
  6. CompletionListHighlightedItemCssClass - Css Class that will be used to style a highlighted item in the AutoComplete list flyout.
(Refer DEMO CODE for better Understanding...)

In above HTML Autocompletete extender; we can display loading image; this will make user understand that something is happening behind the screen. We have used three properties to display & Hide loading image and to display YELLOW background for the text as in above screen shot...
  1. OnClientPopulating: This adds event handler to Client side populating event. In our demo we have used ListPopulating function as event handler, we use this handler to display loading image, which is as follows.

    function ListPopulating(source, e) {
       window.document.getElementById('divLoading').style.display = "";
      
       var textboxControl = window.document.getElementById(source.get_element().id);
       // Get the textbox control.
      
       textboxControl.style.background = "url(Images/loader.gif) no-repeat right";
      //Above code displays loading image inside text box...
                    }
    
  2. OnClientHidden: This adds event handler to Client side hidden event of AutoExtentender. This handler gets fired when Autocomplete popup goes hidden. We have used ListPopulated function to handle this event. We use this event to hide loading image.

    function ListPopulated(source, e) {
    
      window.document.getElementById('divLoading').style.display = "none";
                        
      var textboxControl = window.document.getElementById(source.get_element().id); 
      // Get the textbox control.
                        
      textboxControl.style.background = "";
      }


  3. OnClientPopulated: This event handler can be used when Autosuggest list is populated. We have used this event handler to display YELLOW background in typed text. Check out above screenshot. Function name for this event is ItemSelected, this JavaScript function is as follows.

    function ItemSelected(source, e) {
       window.document.getElementById('divLoading').style.display = "none";
       var customers = source.get_completionList().childNodes;
       var searchText = source.get_element().value;
    
       for (var i = 0; i < customers.length; i++) {
    
       var customer;//  eval('(' + customers[i]._value + ')');
    
       customers[i].innerHTML = customers[i].innerHTML.replace(new RegExp('(' + searchText + ')', 'gi'), "$1");
    
       //We can modify the innerHTML if we want to display more information.
       // e.g. some logo or image
            }  
       }
    

Apart from HTML and javascript we used a webmethod naming GetCompletionList which is as follows


[WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {

        //string sql = "WRITE SQL QUERY with Like Statement and use prefix text e.g. PartnerName like '%" + prefixText + "%'";

        //SqlDataAdapter da = new SqlDataAdapter(sql, "ConnectionString");
       
        DataTable dt = DT;// new DataTable();
        DataRow [] dr = dt.Select("Name LIKE '%" + prefixText + "%'");
        //    da.Fill(dt);
        //    da.Dispose();
        
        if (count == 0)
        {
            count = dr.Length;
            //count = dt.Rows.Count;
        }

       
        List items = new List(count);
        for (int i = 0; i < count; i++)
        {
            string value = dr[i]["City"].ToString() + "|" + dr[i]["State"].ToString() + "|" + dr[i]["Country"].ToString() + "|" + dr[i]["PostalCode"].ToString();
            var Items = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr[i]["Name"].ToString(), value);
            //Using this we can send Name, Value pair client side. 
            //Value can be used to display related data of selected Name.

            //string value = dt.Rows[i]["City"].ToString() + "|" + dt.Rows[i]["State"].ToString() + "|" + dt.Rows[i]["Country"].ToString() + "|" + dt.Rows[i]["PostalCode"].ToString();
            //var items1 = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dt.Rows[i]["Name"].ToString(), value);

            items.Add(Items);
        }
        

        return items.ToArray();
    }

//Ignore above string string tag it is coming due to some editor issue of auto completing tags, some syntax issue.

Check out follwing screen shot, on selection of User we are displaying his/her information. (Note that we have created Name-Value pair in above code to display the information in following screen shot format.)


Now to display Selected User related address information as in the Screen shot, we used event handler of AutoCompleteExtender naming OnClientItemSelected
  • OnClientItemSelected: Handler to attach to the client-side itemSelected event. We used function naming onSelection to display Address details, this JavaScript function is as follows
function onSelection(source, e) {

var htmlString = "
Address Details " + "
City" + e._value.split("|")[0] + "
State" + e._value.split("|")[1] + "
Country" + e._value.split("|")[2] + "
Postal Code" + e._value.split("|")[3] + "
"; // Above alignement might disorder due to HTML rules of blogger, make sure in coding you handle it. window.document.getElementById('divAddressDetails').innerHTML = htmlString; var customers = source.get_completionList().childNodes; //Following is used to put value in Textbox, as we are overriding it to display address. if (document.all) { window.document.getElementById(source.get_element().id).value = e._item.innerText; } else window.document.getElementById(source.get_element().id).value = e._item.textContent; }

We are done with development of Facebook Like Autosuggest in Asp.net.
Donwload demo code here --> Facebook Like AutoSuggest in Asp.net.zip
Submit this story to DotNetKicks

Read more...

Tuesday, July 19, 2011

Send Email In Asp.net Using Gmail

We can use Gmail smtp server to send email, using Asp.Net. Before we start developing Asp.net code, make sure POP is enabled in your Gmail's mail setting.






Once you done with this step SAVE your Gmail settings....

To do Email sending in Asp.net we need "System.Net.Mail" namespace.

public static Boolean SendEmail()
{
  MailMessage mail = new MailMessage();

mail.From = new MailAddress("YOUR FROM EMAIL ADDRESS");
mail.To.Add(new MailAddress("YOUR TO EMAIL ADDRESS"));            
mail.Bcc.Add(new MailAddress("YOUR BCC EMAIL"));
            
  mail.Subject = "Email using Gmail";

  string Body = "Put your Email Body TEXT here"; 
// Here you can put HTML string if you want email to be sent in HTML format.
  mail.Body = Body;

  mail.IsBodyHtml = true;
  SmtpClient smtp = new SmtpClient();
  smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
  smtp.Credentials = new System.Net.NetworkCredential
       ("Username@gmail.com","GmailPassword");
//Or your Smtp Email ID and Password
  smtp.EnableSsl = true;
  smtp.Send(mail);
}

This is simple function to send email in Asp.net using Gmail account.
You can also find Copy of this email in Your SENT items. Submit this story to DotNetKicks

Read more...

Saturday, April 30, 2011

Add Update Delete in Gridview Asp.net

This article is about simple way to Add Update and Delete records using asp.net GridView using Dataset or Datatable. We shall update the database table naming (Download Demo)

"UserTable".

Schema for UserTable is as follows
Note:I have used SqlServer 2008
For this article we are going to fill GridView by data from database.
We are going to make perform following operations on data using GridView
  1. Add New record into database; here data will directly be added into database table
  2. Update Records into database, using edit link.
  3. Delete Records using delete link
To make Add Update Delete in Gridview more user friendly; make sure your website is Ajax Enabled and Gridview is put under UpdatePanel. This will avoid unnecessary

postback and Gridview control will look smart.

Before we develop GridView, lets work out main functions for database operations. Create a Class File naming "ManageUsers" and add following functions one by one

Fetch Data from Database.
public DataTable Fetch()
    {
        string sql = "Select * From UserTable";
        SqlDataAdapter da = new SqlDataAdapter(sql, cnstr);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
        // Write your own Logic for fetching data, this method should return a DataTable
    }


Update Data into Database
public void Update(int id, string FirstName, string LastName, string EmailAddress, string LoginId, string Password, string StartDate, string EndDate)
    {
        string sql = "UPDATE UserTable SET [First Name] = '"+ FirstName + "',[Last Name] = '" + LastName + "',[Login Id] = '" + LoginId +"' ,[Password] = '" + Password 

+ "'";
             sql += ",[Start Date] = '" + StartDate +"',[End Date] = '" + EndDate +"',[Email Address] = '" + EmailAddress + "' WHERE Id=" + id;

        SqlConnection conn = new SqlConnection(cnstr);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();

    }


Insert new records into Database
public void Insert(string FirstName, string LastName, string EmailAddress, string LoginId, string Password, string StartDate, string EndDate)
    {
       string sql = "INSERT INTO UserTable ([First Name],[Last Name],[Login Id],[Password],[Start Date],[End Date],[Email Address]) ";
       sql +=" VALUES ('"+ FirstName +"','" + LastName + "','" + LoginId +"','" + Password + "','" + StartDate + "','" + EndDate + "','" + EmailAddress + "')";
           
        SqlConnection conn = new SqlConnection(cnstr);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
    }

Delete records from Database

public void Delete(int id)
    {
        string sql = "DELETE FROM UserTable WHERE Id=" + id;
        SqlConnection conn = new SqlConnection(cnstr);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
        // Write your own Delete statement blocks.
    }

In above code cnstr is the connection string for our

database.

Now we shall make changes in GridView (Note: Make sure GridView is added on page and under updatepanel) (Download Demo)

Once we add gridview inside updatepanel, do following things
  1. set AutoGenerateColumns as False.
  2. Change the ShowFooter Flag to True
  3. set the DataKeyNames your column name for Id. (This field can have multiple values depending on requirement, we are going to use Id, as it is primary key of our datatable. These values are available in GridView events. We can access them using. GridView.DataKeys[e.RowIndex].Values[0]
  4. Smart Navigation Tag of the GridView control, choose Add New Column
    Now add 8 BoundField columns with DataField values as "Id","First Name","Last Name","Email Address", "Login Id", "Password", "Start Date", "End Date"; also add 2 CommandField columns with one for Edit/Update and another for Delete functions. Now we can see our Grid View control is ready. Above data fields are column names of the DataTable we are using. (To bind correct columns, our datatable column names and gridview bound column's "DataField" should match.
  5. We shall also give facility to add new records, for that we will put controls in Footer row. To do this we need to convert all above BoundField columns to template field columns. Click on the Smart Navigation Tag on the GridView choose Edit Columns, the Field’s property window will open.  Select column by column from Id, include also Edit column, and select ‘Convert this field into a TemplateField’
    Except "delete" column all the BoundField columns are converted in to Template Field Column.
  6. Now one by one we will controls to Footer of the GridView. Right click on the GridView control, select Edit Template.
    Column[0] – Id: select Edit Template, choose column[0] – Id, you can view a label placed in the ItemTemplate section and a TextBox placed in the EditItemTemplate section (Id is our Primary key and it should not be editable). In edit Item Section template, put Label. Do not add anything in Footer Template.

    Column[1] - First Name
    Now again select Edit Template, choose column[1] - First Name, Add another TextBox in the FooterTemplate section and name it as NewFirstName. 

    Column[2] - Last Name
    Choose column[2] - Last Name, Add another TextBox in the FooterTemplate section and name it as NewLastName. 

    Column[3] - Email Address
    Choose column[3] - Email Address, Add another TextBox in the FooterTemplate section and name it as NewEmailAddress. 

    Column[4] - Login Id
    Choose column[4] - Login Id, Add another TextBox in the FooterTemplate section and name it as NewLoginId. 

    Column[5] - Password
    Choose column[5] - Password, Add another TextBox in the FooterTemplate section and name it as NewPassword. 

    Column[6] - Start Date
    Choose column[6] - Start Date, Add another TextBox in the FooterTemplate section and name it as NewStartDate. (Check following source view, we have added, Calender Extender of Ajax Toolkit)

    Column[7] - End Date
    Choose column[7] - End Date, Add another TextBox in the FooterTemplate section and name it as NewEndDate.  (Check following source view, we have added, Calender Extender of Ajax Toolkit)

    Column[8] - Edit
    Just add a link button into the FooterTemplate section, specify its CommandName property as ‘AddNew’.

  7. Source of the Gridview control changes to following, check we have added Calender Extender for date selection. (Download Demo)

    
            
                
                    
                        
                    
                    
                        
                    
                
                
                    
                        
                    
                    
                        
                    
                    
                        
                    
                
                
                    
                        
                    
                    
                        
                    
                    
                        
                    
                
                
                    
                        
                    
                    
                        
                    
                    
                        
                    
                
                
                    
                        
                    
                    
                        
                    
                    
                        
                    
                
                
                    
                        
                    
                    
                        
                    
                    
                        
                    
                
                
                    
                        
                        
                    
                    
                        
                        
                    
                    
                        
                    
                
                
                    
                        
                        
                    
                    
                        
                        
                    
                    
                        
                    
                
                
                    
                        
                         
                    
                    
                        Add New
                    
                    
                        
                    
                
                
            
            
    
  8. Now we shall develop code in code behind of web page i.e. in C#. We have already developed ManageUsers Class in start. We will develop code for handing Edit,Update and Insert operations of GridView. Add events as shown in following image.


    Now check out following code for each event we have added for GridView.

    Create object of the Class "ManageUsers"; and write function to Bind Customer details to the GridView.
    private void BindCustomers()
        {
            DataTable CustomerTable = customer.Fetch();
    
            if (CustomerTable.Rows.Count > 0)
            {
                gridUserManagement.DataSource = CustomerTable;
                gridUserManagement.DataBind();
            }
            else
            {
                CustomerTable.Rows.Add(CustomerTable.NewRow());
                gridUserManagement.DataSource = CustomerTable;
                gridUserManagement.DataBind();
    
                int TotalColumns = gridUserManagement.Rows[0].Cells.Count;
                gridUserManagement.Rows[0].Cells.Clear();
                gridUserManagement.Rows[0].Cells.Add(new TableCell());
                gridUserManagement.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                gridUserManagement.Rows[0].Cells[0].Text = "No Record Found";
            }
        }
    

    Initializing the GridView control on Page load:
    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindCustomers();
            }
        }
    

    GridView RowEditing Event
    protected void gridUserManagement_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gridUserManagement.EditIndex = e.NewEditIndex;
            BindCustomers(); 
        }
    

    GridView RowCancelingEdit Event
    protected void gridUserManagement_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gridUserManagement.EditIndex = -1;
            BindCustomers(); 
        }
    

    Updating Records (GridView RowUpdating Event): Update the data to the UserTable, by adding the following lines of code in the GridView’s RowUpdating event
    protected void gridUserManagement_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            TextBox txtNewFirstName = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox2");
            TextBox txtNewLastName = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox3");
            TextBox txtNewEmailAddress = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox4");
            TextBox txtNewLoginId = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox5");
            TextBox txtNewPassword = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox6");
            TextBox txtNewStartDate = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox8");
            TextBox txtNewEndDate = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox9");
    
            customer.Update(Convert.ToInt32(gridUserManagement.DataKeys[e.RowIndex].Values[0].ToString()), txtNewFirstName.Text, txtNewLastName.Text, txtNewEmailAddress.Text, txtNewLoginId.Text, txtNewPassword.Text, txtNewStartDate.Text, txtNewEndDate.Text);
            gridUserManagement.EditIndex = -1;
            BindCustomers(); 
        }
    
    The above block of codes in RowUpdating event, finds the control in the GridView, takes those values in pass it to the ManageUsers class Update method. The first parameter GridView1.DataKeys[e.RowIndex].Values[0].ToString() will return the Id of the Customer. That is the unique id for each customer to perform update function.

    Delete In GridView:
    protected void gridUserManagement_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            customer.Delete(Convert.ToInt32(gridUserManagement.DataKeys[e.RowIndex].Values[0].ToString()));
            BindCustomers(); 
        }
    

    Add New Records from GridView control

    protected void gridUserManagement_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("AddNew"))
            {
                TextBox txtNewFirstName = (TextBox)gridUserManagement.FooterRow.FindControl("NewFirstName");
                TextBox txtNewLastName = (TextBox)gridUserManagement.FooterRow.FindControl("NewLastName");
                TextBox txtNewEmailAddress = (TextBox)gridUserManagement.FooterRow.FindControl("NewEmailAddress");
                TextBox txtNewLoginId = (TextBox)gridUserManagement.FooterRow.FindControl("NewLoginId");
                TextBox txtNewPassword = (TextBox)gridUserManagement.FooterRow.FindControl("NewPassword");
                TextBox txtNewStartDate = (TextBox)gridUserManagement.FooterRow.FindControl("NewStartDate");
                TextBox txtNewEndDate = (TextBox)gridUserManagement.FooterRow.FindControl("NewEndDate");
    
                customer.Insert(txtNewFirstName.Text, txtNewLastName.Text, txtNewEmailAddress.Text, txtNewLoginId.Text, txtNewPassword.Text, txtNewStartDate.Text, txtNewEndDate.Text);
                BindCustomers();
            } 
        }
    


This is how we can develop a simple GridView control in Asp.Net with Add Update Delete functionality.

Download Demo Code here --> Add Update Delete in Gridview Asp.net
Submit this story to DotNetKicks

Read more...

Friday, February 11, 2011

Stock Market Ticker For Website - Getting Historical Data

To get Historical Data from Yahoo Finance, we can use certain parameters in Query String. Check out following query string for NASDAQ (i.e. Symbol "^IXIC");
http://ichart.finance.yahoo.com/table.csv?s=^IXIC&a=01&b=5&c=1971&d=01&e=8&f=2011&g=m&ignore=.csv
 If we analyze above link we can see some parameters varying from a to g. We can use these parameters to filter HISTORICAL data as per our requirement. Each of above parameter (i.e. from a to g) indicates following things
  • s - Ticker symbol.(This parameter is not optional; other parameters are optional)
  • a - Month number, starting with 0 for January.
  • b - Day number, eg, 1 for the first of the month.
  • c - Year.

    End date for historical prices (default is the most current available closing price):
  • d - Month number, starting with 0 for January.
  • e - Day number, eg, 1 for the first of the month.
  • f - Year.
  • g - Possible values are 'd' for daily (the default), 'w' for weekly, and 'm' for monthly.

We can download csv file and modify its URL run time as per our requirements.
Submit this story to DotNetKicks

Read more...

Tuesday, February 1, 2011

Stock Market Ticker For Website - Yahoo Finance API

In My Previous article Stock Market Ticker For Website; we have seen how to USE YAHOO FINANCE URL, i.e. remote CSV file available for Download to use in Stock Market Ticker.

Suppose we want to download and CSV file with Market Indices
But to display various details related to stock market YAHOO Finance has allowed us to take advantage of live data. Do check out my article about Stock Market Ticker For Website

In previous article we use following link to get market data
http://download.finance.yahoo.com/d/quotes.csv?s=^DJI,^IXIC,^GSPC,^FTSE,^GDAXI,^FCHI,^N225,^HSI,^STI,^BSESN,^NSEI&f=sl1c1&e=.csv
Check out "f=sl1c1" this is where we need to apply following code for getting desired details. e.g. if we want to get "day-low,day-high, 52-week low & 52-week high" along with symbol(s), last trade(price)(l1) and change(c1) from YAHOO FINANCE, our "f=sl1c1" will change to "f=sl1c1ghjk". This is very simple, use following table for getting desired data about Stock exchanges or for equities. Yes we can also get Cross Currency rates from YAHOO FINANCE (e.g. Symbol "USDINR=X,USDEUR=X")

a Ask a2 Average Daily Volume a5 Ask Size
b Bid b2 Ask (Real-time) b3 Bid (Real-time)
b4 Book Value b6 Bid Size c Change & Percent Change
c1 Change c3 Commission c6 Change (Real-time)
c8 After Hours Change (Real-time) d Dividend/Share d1 Last Trade Date
d2 Trade Date e Earnings/Share e1 Error Indication (returned for symbol changed / invalid)
e7 EPS Estimate Current Year e8 EPS Estimate Next Year e9 EPS Estimate Next Quarter
f6 Float Shares g Day’s Low h Day’s High
j 52-week Low k 52-week High g1 Holdings Gain Percent
g3 Annualized Gain g4 Holdings Gain g5 Holdings Gain Percent (Real-time)
g6 Holdings Gain (Real-time) i More Info i5 Order Book (Real-time)
j1 Market Capitalization j3 Market Cap (Real-time) j4 EBITDA
j5 Change From 52-week Low j6 Percent Change From 52-week Low k1 Last Trade (Real-time) With Time
k2 Change Percent (Real-time) k3 Last Trade Size k4 Change From 52-week High
k5 Percebt Change From 52-week High l Last Trade (With Time) l1 Last Trade (Price Only)
l2 High Limit l3 Low Limit m Day’s Range
m2 Day’s Range (Real-time) m3 50-day Moving Average m4 200-day Moving Average
m5 Change From 200-day Moving Average m6 Percent Change From 200-day Moving Average m7 Change From 50-day Moving Average
m8 Percent Change From 50-day Moving Average n Name n4 Notes
o Open p Previous Close p1 Price Paid
p2 Change in Percent p5 Price/Sales p6 Price/Book
q Ex-Dividend Date r P/E Ratio r1 Dividend Pay Date
r2 P/E Ratio (Real-time) r5 PEG Ratio r6 Price/EPS Estimate Current Year
r7 Price/EPS Estimate Next Year s Symbol s1 Shares Owned
s7 Short Ratio t1 Last Trade Time t6 Trade Links
t7 Ticker Trend t8 1 yr Target Price v Volume
v1 Holdings Value v7 Holdings Value (Real-time) w 52-week Range
w1 Day’s Value Change w4 Day’s Value Change (Real-time) x Stock Exchange
y Dividend Yield

Download Demo code here --> Stock Market Ticker for Websites(MarketWatch.zip)
Above  demo code is associated with my previous article.


Submit this story to DotNetKicks

Read more...

Tuesday, January 11, 2011

Asp.Net Reading File From Url

In this article is about Reading file from URL specially Text of CSV files, which we can directly read for the source and convert them into table. By doing this we generally avoid file handling, saving the file and then reading it again. WebRequest class of System.Net library is used to read remotely hosted text file or csv file.

We simply need to use following function which will read remote file and put it in a string format. String is named as output string.

WebRequest req = WebRequest.Create(YOURURL);
        WebResponse result = req.GetResponse();
        Stream ReceiveStream = result.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader sr = new StreamReader(ReceiveStream, encode);
        string output = string.Empty;
        Char[] read = new Char[256];
        int count = sr.Read(read, 0, read.Length);
        while (count > 0)
        {
            String str = new String(read, 0, count);
            output += str;
            count = sr.Read(read, 0, read.Length);
        }

We are following simple steps in Asp.net for Reading file from URL.
  1. Identify the URL and create WebRequest Object
  2. Get the Response Stream 
  3. Encoding it in Appropriate Unicode format
  4. Reading the Data Stream.
  5. Finally getting the whole text string in one string variable i.e. "output" in this case.
It is very easy to in Asp.net to Read file from Url, as we have seen in above code. We can write our logic to manipulate the string. Submit this story to DotNetKicks

Read more...

Wednesday, December 8, 2010

Reading Excel File in Asp.net

One of the very common requirement in asp.net is end user uploaded Excel file and in Code behind, we need to Read the uploaded Excel file and Make sense out of data, i.e. Reading Excel File in Asp.net (Demo Code). 

Reading Excel File in Asp.net is Very simple task, but if there are standard operations need to be done, then we have to specify the Excel format and ask end user to upload file in certain format only.

Below we will discuss how to read and Excel File. (Demo Code)

Before we go ahead check out folder structure of Read Excel File in Asp.net

Also after we upload excel file it gets bind to a grid view, all these operations are done in Default.aspx



Html of the Default.aspx page is as below

Select Date :
Upload Excel File :

On Click of Upload Button we upload excel file and Save it in UploadedFiles folder. We then Read file from UploadedFiles folder.
C# code on Upload Button click is as below, code is very easy to understand, you can also download Demo Code for reference.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        
        if (FileUpload1.FileName.ToString() != "" && FileUpload1.ToString().Contains("."))
        {
            String filepath = Server.MapPath("UploadedFiles");
            FileUpload1.SaveAs(filepath + "\\" + FileUpload1.FileName.Split('\\')[FileUpload1.FileName.Split('\\').Length - 1]);
            string excelPath = (filepath + "\\" + FileUpload1.FileName.Split('\\')[FileUpload1.FileName.Split('\\').Length - 1]);

            ExcelGridView.DataSource = GetExcelData(excelPath);
            ExcelGridView.DataBind();
        }
    }

In above code we pass Excel Path to "GetExcelData" function which returns DataTable which we in turn bind to GridView
GetExcelData function is as below

public DataTable GetExcelData(string ExcelFilePath)
    {
        string OledbConnectionString = string.Empty;
        OleDbConnection objConn = null;
        OledbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";
        objConn = new OleDbConnection(OledbConnectionString);

        if (objConn.State == ConnectionState.Closed)
        {
            objConn.Open();
        }

        OleDbCommand objCmdSelect = new OleDbCommand("Select * from [Sheet1$]", objConn);
        OleDbDataAdapter objAdapter = new OleDbDataAdapter();
        objAdapter.SelectCommand = objCmdSelect;
        DataSet objDataset = new DataSet();
        objAdapter.Fill(objDataset, "ExcelDataTable");
        objConn.Close();
        return objDataset.Tables[0];

    }

In above Code check out OleDbCommand; we are just writing a select query which fetch data from Sheet1 of uploaded Excel, similarly if we can give Sheet Name instead of Sheet1. If your Excel Data starts from some other cell then change select query like "Select * from [Sheet1$B7:F200]"; first row of this range will come as columns in Data Table
Now we are done with Excel Upload and Reading the file, there are certain things which we needs to be take care before uploading Excel file which are as below
  • It certain column in Excel contains number do format that Column for number and make sure all the entries in that column are number, if some entries are in text format then, in Data Table we get those entries as blank entries (i.e. DataTable has empty cell for that respective excel cell.)
  • Define the Range of Operation if your data does not start from A1 cell.
  • All cells in 1st row (i.e. First row of the range you specify) are considered as column name, and in C# Data Table they appear as exact.
  • To Specify the Range modify select query as Select * from [Sheet2$B7:F200] ; you can use your own sheet name instead of Sheet1 or Sheet2
Download Ready to Use Demo Code -- > ReadExcelFileInAsp.Net.zip
    Submit this story to DotNetKicks

    Read more...

    Sunday, October 10, 2010

    Image Handling in Asp.net

    This article discuss about Image Handling, which in turns become important while handling high resolution images and displaying them in different sizes. Especially in case of E-commerce web applications, where admin can add different images of the same product so that users can get feel of the products. Also for image galleries where we need display same image in different sizes with zoom in and zoom out options.
    For above requirement following points should be considered
    • Image should not distorted when re-sized.
    • Quality of the image should remain same.
    • If image is of High resolution then while displaying image is different sizes; the image which loads in browser should be of relative size. E.g. suppose image resolution is of 2736x3648, and we resize such high resolution image in the size of 200x300, then the new small image should be of relative size, i.e. original image size is 3.34MB then while displaying in small size it should be reduced as per size.
    • All images displayed in browser should be of same time, i.e. user can upload images like JPEG, JPG, BMP, TIFF etc. and while displaying all images should be displayed in PNG format only.
    • End user should be able save image of size which he/she is able to see in browser. i.e. if browser is showing image with 200x300 size; user can save image by right clicking it, then the image which is getting saved should be of the 200x300 size only.
    Download DemoCode for better understanding of this article, you can also get to debug code while reading the article.
    The main file for all above operations is ImageHandler.ashx, its a http handler file, in that file following function takes care of resizing of image, just check it out.
    private Image ResizeImage(Image img, int maxWidth, int maxHeight)
        {
            if (img.Height < maxHeight && img.Width < maxWidth) return img;
            Double xRatio = (double)img.Width / maxWidth;
            Double yRatio = (double)img.Height / maxHeight;
            Double ratio = Math.Max(xRatio, yRatio);
            int NewX = (int)Math.Floor(img.Width / ratio);
            int NewY = (int)Math.Floor(img.Height / ratio);
            Bitmap imgCopy = new Bitmap(NewX, NewY, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            Graphics graphicsImg = Graphics.FromImage(imgCopy);
            graphicsImg.Clear(Color.Transparent);
            graphicsImg.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            //HighQualityBicubic gives best quality when resizing images
            graphicsImg.DrawImage(img,
                new Rectangle(0, 0, NewX, NewY),
                new Rectangle(0, 0, img.Width, img.Height),
                GraphicsUnit.Pixel);
            graphicsImg.Dispose();
            img.Dispose();
            return imgCopy;
        }
    
    Above function takes care of re-sizing of image, this function simply maintains the quality of image, and if image which we are re-sizing is less than in size than that we are asking for, this function simply returns the image. To avoid distortion of image on re-sizing we have maintained aspect ratio too.
    We are using ashx file as query string in Image source, which picks up image and render it in desired size code is as below.
    
    
    So remaining code of our Ashx file is as below
    string sImageFileName = "";
        string imageSize = "";
        int oldHeight, oldWidth, NewHeight, NewWidth;
    
        System.Drawing.Image objImage;
        
        public void ProcessRequest (HttpContext context)
        {
            sImageFileName = context.Request.QueryString["img"];
            imageSize = Convert.ToString(context.Request.QueryString["sz"]);
    
            if (imageSize == "Small") NewHeight = 50;
            else if (imageSize == "Thumb") NewHeight = 160;
            else if (imageSize == "Medium") NewHeight = 320;
            else if (imageSize == "Large") NewHeight = 640;
            
            objImage = System.Drawing.Bitmap.FromFile(System.Web.HttpContext.Current.Server.MapPath("Images//" + sImageFileName));
    
            oldHeight = objImage.Height;
            oldWidth = objImage.Width;
            NewWidth = oldWidth * (NewHeight / oldHeight);
    
            objImage = ResizeImage(objImage, oldHeight, NewHeight);
    
            MemoryStream objMemoryStream = new MemoryStream();
            objImage.Save(objMemoryStream, System.Drawing.Imaging.ImageFormat.Png);
            byte[] imageContent = new byte[objMemoryStream.Length];
            objMemoryStream.Position = 0;
            objMemoryStream.Read(imageContent, 0, (int)objMemoryStream.Length);
    
            context.Response.BinaryWrite(imageContent);
        }
     
        public bool IsReusable
        {
            get 
            {
                return false;
            }
        }
    
     
        private bool callback()
        {
            return true;
        }
    
    
    We have developed logic for image handling in mainly two files one is web user control i.e. webImageGallery.ascx and another is ImageHandler.ashx.
    Check out folder structure of the democode.
    Following Html code of imgGallery.ascx is, do refer democode.
    We have one function in imgGallery.ascx.cs file, which builds gallery kind of logic is named CreateImages(), and its code is as below, you can put your own logic for creating image gallery the way you want, I tired to keep logic simple. Once you build do solution check out source code of the gallery. Its simple JavaScript which changes image source on click on thumb image.
    protected void CreateImages()
        {
            int Count = 0;
            HtmlTableRow _htmlTableRow = new HtmlTableRow();
            _ProductTable.Rows.Add(_htmlTableRow);
    
            Directory.SetCurrentDirectory(imagePath);
    
            for (Count = 1; Count <= imageCount; Count++)
            {
                HtmlTableCell _htmlTableTd = new HtmlTableCell();
                _htmlTableRow.Cells.Add(_htmlTableTd);
                _htmlTableTd.Align = Convert.ToString(setImageAlign);
                Image _ThumbImage = new Image();
                _htmlTableTd.Controls.Add(_ThumbImage);
                if (Convert.ToString(setBorder) == "True")
                {
                    _ThumbImage.BorderStyle = BorderStyle.Solid;
                    _ThumbImage.BorderWidth = 1;
                }
                _ThumbImage.ID = ThumbImageName + Count;
                _ThumbImage.ImageUrl = "ImageHandler.ashx?img=" + imageNames[Count - 1] + "&sz=" + Convert.ToString(setThumbImageSize);
                _ThumbImage.Attributes.Add("onclick", "javascript:ImageButton_OnClientClick('" + _mainImage.ClientID + "','" + imageNames[Count - 1] + "','" + setMainImageSize + "');");
            }
    
            _mainImage.ImageUrl = "ImageHandler.ashx?img=" + imageNames[imageCount - (Count-1)] + "&sz=" + Convert.ToString(setMainImageSize);
        }
    
    Please check out variables in DemoCode, they are simply used as properties.
    Once websuercontrol is ready, we simply drag and drop it in Default.aspx page and set following properties of the imageGallery web user control.
    protected void Page_Load(object sender, EventArgs e)
        {
            ImageGallary.ImagePath = Server.MapPath("Images");
            ImageGallary.ImageNames = new string[] { "1_1.JPG", "1_2.JPG", "1_3.JPG", "1_4.JPG", "1_5.JPG" };
            ImageGallary.ImageCount = ImageGallary.ImageNames.Length;
            ImageGallary.SetImageAlign = _ImageAlign.Left;
            ImageGallary.SetMainImageSize = _ImageSize.Medium;
            ImageGallary.SetThumbImageSize = _ImageSize.Small;
            ImageGallary.SetBorder = _Border.True;
        } 
    Download Democode here---> ImageUserControl.zip Submit this story to DotNetKicks

    Read more...

    Thursday, August 5, 2010

    Cross Page PostBack In Asp.Net

    In web development, many times we come across following situation

    We need to redirect to new page, but we also need some data which belongs to previous page, we might need to display the data on new page. So what things we normally do are,
    eighter keep the data in session, or in hidden variable, or put data in application variable, or again run the code to get same data and bind it to similar kind of control.

    I think this is something which we can avoid by simply applying logic of Cross Page Postback, where we can directly identify the controls whose value we need to display on new page.
    E.g.
    step1--> We have Grid View on say PAGE1.aspx and we redirect to PAGE2.aspx.
    step2--> On PAGE2.aspx we need same Grid View to Display. For this we will probably use traditional ways to maintain the grid.

    Now what if I say we can directly access grid which is already filled with data, and simply put the same grid on PAGE2.aspx. This sounds very simple. And it is very simple. For better understanding just check out following code which I have written on PAGE2.aspx



    It looks very easy to use the code. You can DOWNLOAD the demo code, explained below
    In above code check out the If condition where we have check whether it is a CrossPagePostBack or not.
    We have following things in our web application.
    • Page1.aspx (with cs code)
    • Page2.aspx (with cs code)


    Lets build Page1.aspx first, we have following HTML in Page1.aspx file. 



    check out the PostBackUrl of button. which is set to Page2.aspx, we just need to do this in our code so that Page1 will be accessible in Page2.aspx
    which looks like following page

    Now we will write code in Page1.aspx.cs file which is as below, you can generally copy paste the code in your files.



    This is what we have to do for Page1.aspx, we are done with our code. In Page1.aspx we simple have two textboxes and one Grid View control which we bind to some sample table. In Page2.aspx we Just make Grid View Object and set the reference of Page1's Grid View to new gird view thats it. If you observe the code written for Page2.aspx, we don't retrieve the data from any where and bind it to Grid View, we simple set the reference. This makes code execution also easy, and in similar way we can always pick some random controls which we need to display on some other page. We can also have many links referring to different pages depending on the requirement.

    Download Demo Code here --> CrossPagePostback.zip

    Submit this story to DotNetKicks

    Read more...

    Saturday, July 10, 2010

    Ajax-Handle complex data type (e.g. Class)

    Use of complex data types in Ajax programming is a tricky part. In normal scenario we need to communicate between client and server via string manipulation only. (Demo Code)
    In this article we will discuss about, Microsoft Ajax and the way we can handle complex data types. We shall use web service for Ajax communication; web service will be exposed to client using Script Manager. Complex data types can be handled using JSON objects, in this article we will discuss only about how to handle complex data types. Script Manager internally uses JSON serialization class for handling complex data types; so will not care about the JSON about in this article.
    Let’s assume we have a Public class Employee as below.




    In above class the elements which we need to be accessed in JavaScript are public; here we are not considering any function in a class.

    Again we are going to expose a web service to Script Manager for this article. So we also have a web service in demo code it is “WebService.asmx”.
    Following two namespaces are required to make a web service Ajax Enabled. We will not go into any details of these namespaces.
    using System.Web.Script.Services;
    using System.Web.Script.Serialization;
    Our web service class is as below





    Following are the two extra things we have added above the WebService class, this is to indicate that the web service will be called from JavaScript, and is enabled of Creating corrosponding script object of class Employee.





    In the Demo, Employee and WebService both classes are added under namespace Demo, and are in the same file “webservice.asmx”.
    Our server side code ends here. Now we shall develop only client side code.
    Our form tag is as follow




    In above code, we have used script manganer and registred our web service and JavaScript file.
    Here onwards we are going to deveolp JavaScript
    Calling of WebService methods using JavaScript and script manager is very simple, we just need to use the simple namaspace sequence.
    e.g. If we want to call getDefaultData function of a webservice we simply needs
    Demo.WebService.getDefaultData().
    If we want to add a response handler we just need to specify the function name in bracess like Demo.WebService.getDefaultData(OnSucceeded)
    For the demo purpose our JavaScript contains mainly three functions

    _getDefaultData() – This JavaScript function is used to call a webmethod getDefaultData. This Web Method returns default data Set for the Employee class.
    The JS function is as below





    _sendDataToServer() – This JavaScript function is used to pass client side input to the server, or to the web method.
    The JS function is as below





    IN ABOVE FUNCTION CHECK THE WAY WE HAVE CREATED OBJECT OF AN EMPLOYEE CLASS. THIS EMPLOYEE CLASS EXISTS IN C# CODE, BUT USING AJAX.NET WE ARE ABLE TO CREATE INSTANCE ON CLIENT SIDE AS WELL.

    OnSucceeded(result,userContext, methodName) – This JavaScript function is used to Handle response from the server. The function is as below




    Download Demo Code here ---> DealingWith_ComplexTypes.zip
    Submit this story to DotNetKicks

    Read more...