Showing posts with label Web User Control. Show all posts
Showing posts with label Web User Control. Show all posts

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...

Wednesday, March 16, 2011

Active Directory Authentication Asp.net

Very offen in web development, we come across a requirement where we need to use Active Directory Authentication in Asp.net; i .e. we need to use Active Directory to Authenticate user. The flow for the same can be assumed as following point. In this case we shall not have User table in Database unless required, we can verify the Authenticity of user with Active Directory.
  1. User logs in with Active Directoyl Login and Password.
  2. System verifies Login and Password with Active Directory
  3. If we get Success we will proceed the login else will display error.

We shall use following C# class naming AuthenticateUser to implement ActiveDirectory Authentication in Asp.net

public class AuthenticateUser
{
    public AuthenticateUser()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    private string _path;
    private string _filterAttribute;

    public AuthenticateUser(string path)
    {
        _path = path;
    }

    public bool IsAuthenticated(string domain, string username, string pwd)
    {
        string domainAndUsername = domain + @"\" + username;
        DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

        try
        {
            //Bind to the native AdsObject to force authentication.
            object obj = entry.NativeObject;

            DirectorySearcher search = new DirectorySearcher(entry);

            search.Filter = "(SAMAccountName=" + username + ")";
            search.PropertiesToLoad.Add("cn");
            SearchResult result = search.FindOne();

            if (null == result)
            {
                return false;
            }

            //Update the new path to the user in the directory.
            _path = result.Path;
            _filterAttribute = (string)result.Properties["cn"][0];
        }
        catch (Exception ex)
        {
            throw new Exception("Error authenticating user. " + ex.Message);
        }

        return true;
    }


}

Remeber we have added "System.DirectoryServices" name space.

We can simply use following code to Authenticate user using ActiveDirectory in asp.net

Note: In following code we use Authentication on Page Load event, you can implement this on Login Page.

protected void Page_Load(object sender, EventArgs e)
    {
        AuthenticateUser cls = new AuthenticateUser("LDAP://YourActiveDirectoryPath"); //Set Active Directory Path
        bool flag = cls.IsAuthenticated("ZESTORMTPL", "UserLoginID", "Password");
        //Put your UserLoginID and Password
    }
Active Directory Authentication Asp.net is as simple as copy pasting above code and use it as it is.
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...

Wednesday, January 19, 2011

Stock Market Ticker For Website

In this article we shall work out on Live stock market ticker for website. To develop live stock market ticker for website the basic requirement is to have live data. Free live data is available at some cost, but to display tickers on website we can always go for two to three minutes delayed data, which we can download from Yahoo Finance. Yahoo Finance is giving enable use to download CSV file in the manner we want. Once we get the CSV file logic which remains is to display data and Polling of data at certain interval

Check out folder structure of our Demo Code

(Note: Demo contains Cross Currency Data as well; which will be same as Stock market data.)

In this article we shall be considering major stock exchanges, and in demo code we shall see updates related to stock exchanges.
  • DOW (Symbol: ^DJI)
  • Nasdaq (Symbol: ^IXIC)
  • S&P 500 (Symbol: ^GSPC)
  • FTSE 100 (Symbol: ^FTSE)
  • DAX (Symbol: ^GDAXI)
  • CAC 40 (Symbol: ^FCHI)
  • Hang Seng (Symbol: ^HSI)
  • NIKKEI 225 (Symbol: ^N225)
  • Straits Times (Symbol: ^STI)
  • BSE India (Symbol: ^BSESN)
  • NSE India (Symbol: ^NSEI)

If you go to Yahoo Finance and put any of the Symbol you can check all related data. Also that data is allowed to download, we are going to use this downloaded data to display live (little delayed) data to develop Stock Market Ticker for Website. (Note: If you are not aware about ICALLBack Event handler, please refer this article ---> ICallback Event Handler Article
We are going to get data from Yahoo Finance in CSV format. So we shall write logic accordingly. Following is the function to convert CSV in to Data Table.

public static DataTable csvToDataTable(string strData, bool isRowOneHeader)
    {
        DataTable csvDataTable = new DataTable();
        //no try/catch - add these in yourselfs or let exception happen
        String[] csvData = strData.Replace("\r", "").Replace("=X", "").Split('\n');
        //if no data in file ‘manually’ throw an exception
        if (csvData.Length == 0)
        {
            throw new Exception("CSV File Appears to be Empty");
        }

        String[] headings = csvData[0].Split(',');
        int index = 0; //will be zero or one depending on isRowOneHeader
        if (isRowOneHeader) //if first record lists headers
        {
            index = 1; //so we won’t take headings as data
            //for each heading
            for (int i = 0; i < headings.Length; i++)
            {
                //replace spaces with underscores for column names
                headings[i] = headings[i].Replace("", "_");
                //add a column for each heading
                csvDataTable.Columns.Add(headings[i], typeof(string));
            }
        }
        else //if no headers just go for col1, col2 etc.
        {
            for (int i = 0; i < headings.Length; i++)
            {
                //create arbitary column names
                csvDataTable.Columns.Add("col" + (i + 1).ToString(), typeof(string));
            }
        }
        //populate the DataTable
        for (int i = index; i < csvData.Length - 1; i++)
        {
            //create new rows
            DataRow row = csvDataTable.NewRow();
            for (int j = 0; j < headings.Length; j++)
            {
                //fill them
                row[j] = csvData[i].Split(',')[j];
            }
            //add rows to over DataTable
            csvDataTable.Rows.Add(row);
        }

        //return the CSV DataTable
        return csvDataTable;
    }

Another Important Function for our development of Stock Market Ticker for website is, the function which will call Yahoo Finance to fetch desired data.

We shall user WebRequest Class to call remove CSV file i.e. Read a downloadable CSV file from remote server. Check out following function.

 public DataTable CallYahooFinance()
    {
        WebRequest req = WebRequest.Create(StaticVariables.Markets);
        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);
        }
        output = output.Replace("^DJI", "DOW").Replace("^IXIC", "NASDAQ").Replace("^GSPC", "S&P500");
        output = output.Replace("^FTSE", "FTSE 100").Replace("^GDAXI", "DAX").Replace("^FCHI", "CAC 40");
        output = output.Replace("^HSI", "HANG SENG").Replace("^N225", "NIKKEI 225").Replace("^STI", "STRAITS TIMES");
        output = output.Replace("^BSESN", "SENSEX").Replace("^NSEI", "NIFTY");
        DataTable DT = csvToDataTable(output, false);
        DT.Columns[0].ColumnName = "Market";
        DT.Columns[1].ColumnName = "Last Trade";
        DT.Columns[2].ColumnName = "Change (in %)";
        return DT;
    } 

In above code "output" is the string i.e. CSV string and we have replaced Yahoo Finance Symbols with the Name of the Stock Index.

If you check above function Webrequest.Create Method contains URL. To get CSV File we are using following URL, if you simple copy paste the URL you can download CSV file. URL for Stock Market Ticker is set into Static variable.

public static class StaticVariables
{
public static string Markets = "http://download.finance.yahoo.com/d/quotes.csv?s=%5EDJI,%5EIXIC,%5EGSPC,%5EFTSE,%5EGDAXI,%5EFCHI,%5EN225,%5EHSI,%5ESTI,%5EBSESN,%5ENSEI&f=sl1c1&e=.csv";
}

Thats it now we got the relevant data from yahoo finance which we can display the way we want. We are using ICallback Event handler to poll data from Yahoo Server. Now if you are aware about ICallback Simply check out following functions. Where we are not doing anything special.


protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            String cbReference =
                Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
            String callbackScript;
            callbackScript = "function CallServer(arg, context)" +
                "{ " + cbReference + ";}";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
        }
    }

Also check Region for ICallback Implementation
public void RaiseCallbackEvent(String eventArgument)
    {
    
    }
    public String GetCallbackResult()
    {
        GridView GridView1 = new GridView();
        GridView1.DataSource = CallYahooFinance();
        GridView1.DataBind();

        return getHTML(GridView1);
    }


public string getHTML(GridView _grid)
    {
        string result = string.Empty;
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            _grid.RenderControl(htw);
            htw.Flush();
             result = sw.ToString();
        }
        return result;
    }
//getHTML returns HTMLString for GRIDView

Now in the HTML of our page we have only following tags.

We use following JavaScript to Fetch live data from server side at the interval of 1000mili second.

function call()
    {
    window.document.getElementById('_polling').style.display="";
    CallServer("", "");
    }
    
     function ReceiveServerData(retValue)
    {   
        document.getElementById("result").innerHTML = retValue;
        window.document.getElementById('_polling').style.display="none";
        setTimeout("call()",1000); //Set polling to 1000mili second
    }

Implementation of above code is very simple check out Demo code for the same.
Download Demo Code here --> Stock Market Ticker For Website.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...

Monday, June 21, 2010

News Feed - Web User Control

This is very simple code to create web user control to display News Feeds. Using this user can change properties of News Feeds and set his/her own url, number of news to display.

This code is developed in ASP.NET using C#, JavaScript and Simple HTML.

Lets step by step develop web user control for feeds

--------------------- Step 1 --------------------------------
Create one Web User control Named NewsFeed. Copy Past following code in C# file i.e. in ascx file. Just check out Properties in the code.



--------------------- Step 2 --------------------------------
Here we will use google code to read feeds and retrieve data. For more information you can check Google Code.

Put following Code in HTML view of same Web User Control. Following code will include google JSAPI file in your code, and it will load Google Ajax Feed API.



--------------------- Step 3 --------------------------------

We will use following code to set properties of Web User control in javaScript. Check out variables "feedUrl" , "feedNumber"; these variables are set in ASCX file. "feeddiv" is a div tag set in above code. We will display our feed in this div tag.



--------------------- Step 4 --------------------------------

Following code takes care of Feeds retrieval, and manipulate HTML which we are suppose to display in Div tag discussed above.

"display" feed function automatically get called once we retrieve feeds using googleFeed.

"errMessage" is set in ASCX page. Which can be set as property of Web User Control.


 

This is very simple code to develop. Any one with basic understanding of HTML, JavaScript and ASPX can develop web user control to display Feeds.

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

Read more...