Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Friday, January 14, 2011

Display Loading Image in Asp.net

To display loading image we shall use following JavaScript. There are many ways to display loading, but I feel this is the simple to use and implement. We just need one div tag with position set to absolute, and put loading image inside the div tag. Check out following code.

Loading...

(Make sure you set z-index if required.)
In above I have just used text "Loading...", instead of this you can put loading images.Put this div tag as first element of FORM tag. And after above div tag immediately put following JavaScript 



And call function "init()", on "onload" event of body tag.

Done, now as your page loads you can see "Loading..."... Submit this story to DotNetKicks

Read more...

Monday, November 22, 2010

Google Charts API for ASP.NET

Google Visualization has provided a powerful set of JavaScripts which allows us to develop various graphs and charts. I think if we are developing something like dashboard or something like Google Analytic dashboard, then using Google Visualizations is amazing idea. In case of Asp.net we can simply develop a logic to use DataTables as input and Graph will be generated automatically. Again we can capture the click events for the graph and display alerts or run some JavaScript as per our logic (DemoCode).

In this article we will simply check out different graphs and its integration with asp.net. Check out following Screen shots.





Google Charts API can be implemented effectively in Asp.net, this is just a small part of actual assignment I did for the development of a dashboard.
Step 1: Understanding Table structure of Google API.Google Charts API accepts table as input and generate graphs accordingly. It takes Table in Following format. (for more information check out  Google References )


We should be careful while generating Table in HTML, i.e. while adding Rows and Columns in Google DataTable. Google Data Table creation looks as follows

var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('number', 'Salary');
        data.addRows(4);
There are many things we can do with Google Table which I am not including in this article.

Check out following JavaScript code for creating Google Table and Adding data in it
var data = new google.visualization.DataTable();
   function setDataforGraph()
        {
         // Create and populate the data table.
       var raw_data =  [['INFOSYS', 3077.15, 3081.65, 3015.9, 3059.80, 3082.65, 3054.65, 2997.85, 3030.05, 2970.95, 3003.95]];
            var xAxis = ['05-Nov-10', '08-Nov-10', '09-Nov-10', '10-Nov-10', '11-Nov-10', '12-Nov-10', '15-Nov-10', '16-Nov-10', '18-Nov-10','19-Nov-10'];

            data.addColumn('string', 'Date');
            for (var i = 0; i < raw_data.length; ++i) {
                data.addColumn('number', raw_data[i][0]);
            }
            
            data.addRows(xAxis.length);
            for (var j = 0; j < xAxis.length; ++j) {
                data.setValue(j, 0, xAxis[j].toString());
            }
            for (var i = 0; i < raw_data.length; ++i) {
                for (var j = 1; j < raw_data[i].length; ++j) {
                    data.setValue(j - 1, i + 1, raw_data[i][j]);
                }
            }
          
        }

We also need to include JavaScript sources, there are some packages Google Provides, as we are going to use this for Charts we include coreCharts
Add script file "http://www.google.com/jsapi"


Once we done with DataTable creation we go for the logic to display Charts. We need to call Google Function

function drawVisualization(Type) {

            // Create and draw the visualization.
            var targetDiv = document.getElementById('visualization');
            var chart;
            if(Type == "ColumnChart") chart = new google.visualization.ColumnChart(targetDiv);
            else if(Type == "PieChart") chart = new google.visualization.PieChart(targetDiv);
            else if (Type == "AreaChart") chart = new google.visualization.AreaChart(targetDiv);
            else if (Type == "BarChart") chart = new google.visualization.BarChart(targetDiv);
            else if(Type == "LineChart") chart = new google.visualization.LineChart(targetDiv);
            chart.draw(data);
            new google.visualization.events.addListener(chart, 'select', selectionHandler);

            function selectionHandler(e) {
                selection = chart.getSelection();
                for (var i = 0; i < selection.length; i++) {
                    var item = selection[i]; 
                    alert(data.getValue(item.row, 1));
                }
            }
        }

Above function can be called on any event. Which will generate Chart of Particular Type. Refer Demo Code. We can add selectionHandler to capture events on click of chart. Above function will give us value of the Item i.e. Data. Check out following image.


HTML Structure of form is something like below, where we have Div tag for Google Visualization.

At this point we are done with the Google Charts API usage in HTML. Now to make Google Charts work in asp.net we simply need to develop a logic in code behind which will enable us to Create GoogleDataTable.

To generate data in code behind we use string elements which we can simple get in JavaScript on page render.

public string x_Axis = string.Empty;
    public string graphTable = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            graphTable = getGoogleVisualizationStr(DemoDataTable);
            x_Axis = "'05-Nov-10', '08-Nov-10', '09-Nov-10', '10-Nov-10', '11-Nov-10', '12-Nov-10', '15-Nov-10', '16-Nov-10', '18-Nov-10','19-Nov-10'";
        }
    }

We keep Demo Table in c# code, with same data values used in above table.
private DataTable DemoDataTable
    {
        get
        {
            DataTable DT = new DataTable();
            DT.TableName = "GENERAL";
            DT.Columns.Add(new DataColumn("Name", typeof(string)));
            DT.Columns.Add(new DataColumn("Data1", typeof(long)));
            DT.Columns.Add(new DataColumn("Data2", typeof(long)));
            DT.Columns.Add(new DataColumn("Data3", typeof(long)));
            DT.Columns.Add(new DataColumn("Data4", typeof(long)));
            DT.Columns.Add(new DataColumn("Data5", typeof(long)));
            DT.Columns.Add(new DataColumn("Data6", typeof(long)));
            DT.Columns.Add(new DataColumn("Data7", typeof(long)));
            DT.Columns.Add(new DataColumn("Data8", typeof(long)));
            DT.Columns.Add(new DataColumn("Data9", typeof(long)));
            DT.Columns.Add(new DataColumn("Data10", typeof(long)));
            DT.Rows.Add(new object[] { "INFOSYS", 3077.15, 3081.65, 3015.9, 3059.80, 3082.65, 3054.65, 2997.85, 3030.05, 2970.95, 3003.95 });
            return DT;
        }
    }

We write a simple code to generate rowData used in above lines of code.

private string getGoogleVisualizationStr(DataTable DT)
    {
        string googleVisualTable = string.Empty;
        googleVisualTable = "[";
        for (int i = 0; i < DT.Rows.Count; i++)
        {
            for (int j = 0; j < DT.Columns.Count; j++)
            {
                if (j == 0)
                {
                    googleVisualTable += "[ '" + DT.Rows[i][j] + "'";
                }
                else if (j == DT.Columns.Count - 1) googleVisualTable += "," + DT.Rows[i][j] + "]";
                else googleVisualTable += "," + DT.Rows[i][j];

            }
            if (i != DT.Rows.Count - 1) googleVisualTable += ",";
        }
        googleVisualTable += "]";
        return googleVisualTable;
    }
We replace our JavaScript code with
var raw_data = <%= graphTable %>
var xAxis = [<%=x_Axis %>];

Thats it we are done with development of Google Charts API for ASP.NET. Above code used data of only one company to keep things simple. To add more companies simply add it in data table. So that our graphs will look like




Download Democode for reference --> GoogleVisualizationDemo.zip Submit this story to DotNetKicks

Read more...

Thursday, October 28, 2010

Display your logo on address bar

Many times to make our site standout, we need to display our logo near address bar. There is very simple JavaScript which takes care of this. We need to put following code in tag HEAD tag.






For each page of the website we need to add above code.
demoico.ico is an icon file which we can use to display near address bar.
We can also manipulate Header Section Dynamically, and change the icon for different pages. 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...

Tuesday, August 10, 2010

Different ways of web page Redirect in Asp.Net

As a website developer many times we come across situation where we need to redirect pages, as there are many ways to redirect pages in asp.net and in HTML as well; one should know the difference between various web page redirect methods.
In this article we will discuss various web page redirecting methods we can use in asp.net

  1. Hyperlink: This is a traditional way of web page redirect which can use with HTML TAG i.e "A" tag. This is a static link on a page, which can be used as a tag with various style attributes. Also we can put data in opening and closing tag of "A". Asp.Net provides Hyper Link control, which is a class inherited from Webcontrol class. This control needs user to click explicitly on link for web page redirect.
    
     

    There are many attributes and events which are associated with hyperlink control, which can be used for many purposes.

    Hyperlink has following characteristics
    • New request is performed on Target Page.
    • Current page information doesn't get passed. Need to use query string to pass parameters
    • User Need to Initiate the web page transfer request.
    • Redirects to any page, not only restricted to current domain.
    When to Use
    • For navigation without any processing, e.g. Menu's list Items
    • When user should control the navigation.
  2. CrossPagePostBacks :By default, buttons in an ASP.NET Web page post the page to itself. i.e. it simply acts as a submit button of HTML. Where as Cross-page posting enables us to change the style of submitting the page, we can configure a button on an ASP.NET Web page to post the current page to a different page. Typically in multi-page forms, we can use such buttons on the page to move to the next and previous pages of the form.

    Though cross page posting is similar to hyperlinks, in cross page posting, the target page is invoked using an HTTP post command, which sends the values of controls on the source page to the target page. In addition if source and target page are in the same web application then the target page can access public properties of the source page. You can check out the article on cross page post by, click on CROSS PAGE POSTBACK
    Hyperlink has following characteristics
    • Post current Page Information into Target Page.
    • Makes Post information available into target page.
    • User Need to Initiate the cross page postback request.
    • Redirects to any page, not only restricted to current domain.
    • Enables the target page to read public properties of the source page if the pages are in the same Web application.
    When to Use
    • To pass current page information to the target page (as in multi-page forms).
    • When user should control the navigation.
  3. Response.Redirect: This is simple HTTP redirection we can directly use in code behind. very simple to use  When we use Response.Redirect the browser issues a new request to the target server in the form of an HTTP GET request. Response.Redirect is same as form submit in HTML, it does exactly same, actually in HTML response.redirect come as submit only. This method passes the server elements using query string. We can always use this method in code behind with our logic to redirect to other page(s).
    Hyperlink has following characteristics



    • Performs a new HTTP GET request on the target page.
    • Passes the query string (if any) to the target page. In Internet Explorer, the size of the query string is limited to 2,048 characters.
    • Provides programmatic and dynamic control over the target URL and query string.
    • Enables you to redirect to any page, not just pages in the same Web application.
    • Enables you to share information between source and target pages using session state.

    When to Use
    • For conditional navigation, when you want to control the target URL and control when navigation takes place. For example, use this option if the application must determine which page to navigate to based on data provided by the user.
  4. Server.Transfer: In case of Server.Transfer, server simple transfers the current source page context to the target page. The target page then renders in place of the source page. To use Server.Transfer, source page and target page should be in the same web application. When we use transfer method target page can read control values and public property values from the source page. Transfer between source and target pages happens on the server, because of this the browser has no information about the changes page, and it retains all information about the original i.e. source URL. Browser history doesn't get update to reflect the transfer. This is the best strategy to keep URL hidden, if user refresh the page he/she will be redirected to source page rather than new transferred page.
    Server.Transfer has following characteristics
    • Instead of source page control is transfered to new page which get renders in place of source
    • Redirects only to target pages that are in the same Web application as the source page.
    • Enables us to read values and public properties from source page.
    • Browser information Does not update with information about the target page. Pressing the refresh or back buttons in the browser can result in unexpected behavior.
    When to Use
    • For conditional navigation, when you want to control when navigation takes place and you want access to the context of the source page.
    • Best used in situations where the URL is hidden from the user.
Submit this story to DotNetKicks

Read more...

Sunday, July 25, 2010

XMLHTTPJSClass - JSON Class for Ajax Operations

In the development of Ajax application many times we may come across following issues.
  • Need to update multiple text boxes simultaneously.
  • Fill more that one dropdown lists.
  • Combination of text boxes, dropdown lists and div tags.
  • Calling different web pages and different webservices

Means one event may lead to updating of many html elements. In such cases we will have to send Ajax request in a loop. Again for each request we will have to take care of timeouts and request failures. Here if data is static we can keep it on HTML page and using JavaScript can directly hide and show the contents. But if we have to use real time data and also choices of display vary according to choices of the user, in such case looping of Ajax request may not be a good idea.

In this article we will discuss about XMLHTTPRequest object and JavaScript. We will develop a JavaScript class in which we can vary our choices and also be able to update multiple HTML contents. Also this class can be extended as per the requirements.

We will first talk about class in JavaScript, there is no keyword called class in JavaScript but we can use function as a class.

Checkout following code



In above script if we remove obj.Msg = "HI"; we will get an alert with text Hello.


Now step by step we will start developing our JavaScript class.
1.Include JS file and write following


In this step we have created XMLHTTPRequest object and simply send call to the server. By default method is GET (this.Method = "GET") and calling type is Ascynchronous (this.Async = true)


2.In this step we will develop simple logic which will allow us to dynamically call Ajax function.

For this in our above Ajax function we will add one JSON (www.json.org) object as follows.



In above script we can set the default values for all. Please reffer demo JS file to understand this better. We will use these values to set response from the server to textboxes,drop down lists,Div tags, td tags etc. Using "CallPage" : "CallPage.aspx" we can define default server page and while calling Ajax function we can reset this value to web method or to any other web page.
As we will proceed in this article we will come to know how can we change all above values and how can we use it for multiple updation.Also we will see that how to extend the class for further customization.

3.As we have seen in 1st step;

this.request.onreadystatechange=this.handleResponse;
In this step we will develop this.handleResponse function also in this function we will use JSON object defined in 2nd step.
Whenever this.handleResponse function gets call script looses the focus of this. To keep trac of this object we will assing it to some variable. i.e



In this function we will be able to receive data from server. Once we get the data we can play with it the way we want.
This function will take care of the responses from web services as well as from web pages.
Difference is, web service returns response in the form of XML where are response from the webpage can be defined by web developer.

The function will be as follows



If there is any problem in understanding please go through above code again.

In the the 1st step we have



While developing Ajax application take care of following point.
  • URL for XMLHTTPRequest object should belong to same domain.
  • Firefox and other browser doesn’t allow cross domain communication.
  • IE will show warning

Thus our


e.g. "http://localhost/Demo/CallPage.aspx?"+this.JSONArray.Querystring;

Also when ever we want to call web methods like above example, we need to set following protocols under in web.config file.



4.Up to this point we have finished with development of Ajax logic which will return us response. And in this point we will develop logic for population HTML controls

In this.handleResponse (step 3) we have seen that we get response in
“data” variable in JavaScript.

So once we got response from the server we will write following logic



self.JSONArray.isEdit[0].textBoxId will contain id of the text box in which we have to fill the response. And data is the response from the server.
In 2nd step we have defined JSON object as follows



And in our above switch we have simply used the elements of JSON object

At this point we will see how to call our Ajax Class, how to initiate the request and how to set Elements of our JSON object.
Simply create object of our AjaxClass().



if obj.JSONArray.dependentType=1 then our switch case will not work for text box, but it will work for dropdown list (check above switch case). Means we will have to set dropdown list of JSON object.



and so on, we can define our own set of HTML controls to be filled.

In the same way we can change all default settings in JSON object of that class.
e.g. obj.JSONArray.Method = "GET";
obj.JSONArray.CallPage = "Mywebservice/webMethod";
obj.JSONArray.Querystring= "My querystring";

For this URL will be



In case of web service we will have to set CallPage element in the same way we did in above example.

Now for multiple textboxes simple trick,
obj.JSONArray.isEdit[0].textBoxId="txt1$txt2$txtn";//$ is a delimiter
While sending data from server send it with the same delimiter,in such a way when we split obj.JSONArray.isEdit[0].textBoxId and response data on $; we will get one to one data and textBoxId.

Now we can have different types like “txtbox(es) + drop down list(s) + div” in such case we can use "misc" option of isEdit element of JSON object.
And we can define our PopulateControls function the way we want.

Just think of the choices for getting Response from AjaxCall; we can develop very critical systems using this logic and keeping code as simple as possible. Also we can integrate our ICallback logic for large data transfer.



Demo JavaScript file is as below ( DOWNLOAD)



Download Demo Code here --> XMLHTTPJSClass.zip

Submit this story to DotNetKicks

Read more...

Tuesday, July 13, 2010

CSS- Bubble Tool Tip

Very simple to use bubble tool tip, easy to implement.
I got this code some time back, during my initial phase of web development.



In the body tag put following code




This code is very easy to understand, check style tag and download following images and change the paths accordingly in style tag.



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

Read more...