Friday, June 22, 2012

Upload and Download files in C#.NET


<%@ Page Language="C#"  AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
html xmlns="http://www.w3.org/1999/xhtml">
head runat="server">
title>title>
head>
body>
form id="form1" runat="server">
div>
   table border="1" cellspacing="0" cellpadding="0" id="tbl">
   tbody>
   tr>
    td>
    
    td>
   tr>
   tbody>
 table>
 table border="1" cellspacing="0" cellpadding="0" id="tblButton">
 tbody>
 tr>
  td>
   
  td>
  td>
  asp:Button ID="btnDownload" Text="Download" runat="server" OnClick="btnDownload_Click" />
  td>
  tr>
tbody>
table>
div>
form>
body>
html>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
  }
  protected void btnUpload_Click(object sender, EventArgs e)
  {
    String filePath = FileUpload1.FileName;
    String strFileName = "";
    if (FileUpload1.PostedFile != null)
    {
       HttpPostedFile file = FileUpload1.PostedFile;
      //Get the size of the file so you can read the file
      int contentLen = file.ContentLength;
      if (contentLen > 0)
      {
          strFileName = Path.GetFileName(filePath);
          file.SaveAs(Server.MapPath(strFileName));
      }
  }
}
 protected void btnDownload_Click(object sender, EventArgs e)
 {
  string fileName = "Amazon.txt";
  string filePath = Server.MapPath(fileName);
  Response.Clear();
  Response.AppendHeader("content-disposition", "attachment; filename=" + filePath);
  Response.ContentType = "application/octet-stream";
  Response.WriteFile(filePath);
  Response.Flush();
  Response.End();
}
}

Wednesday, June 20, 2012

Google Maps Control for ASP.Net

Hide the console window in "C# Console Application"

To hide the console window right click the project -> Properties -> Application in Visual Studio , under Output type select "Windows Application"



Article : Label vs Literal in ASP.NET


Unlike the Label control, the Literal control does not render any additional html tags thats why the best practice says: never use the ASP.NET Label control when a Literal can do the job. In different cases we use the Literal/Label controls to label input controls without knowing the difference between them. The below should help you to decide which control you should use when building asp.net web application.
Label vs Literal:

Label:
The Label web server control is used to label other controls on an aspx web page/UserControl. It is used to display text with the ability to change the style (appearing) of the displayed text.
Inheritance Hierarchy:System.Object
System.Web.UI.Control
System.Web.UI.WebControls.WebControl
System.Web.UI.WebControls.Label
<asp:Label ID="lblFirstName" runat="server" CssClass="myCssClass" Text="First Name" />
It will be rendered as:
<span id="ctl00_ContentPlaceHolder1_lblFirstName" class="myCssClass">First Name</span>
(NB: the id of the Label is related to the structure of your asp page and if you are using MasterPage or not)

Literal:
Use the System.Web.UI.WebControls.Literal control to reserve a location on the Web page to display text. The Literal control is similar to the Label control, except the Literal control does not allow you to apply a style to the displayed text. You can programmatically control the text displayed in the control by setting the Text property.
Inheritance Hierarchy:
System.Object
System.Web.UI.Control
System.Web.UI.WebControls.Literal
<asp:Literal id="litFirstName" runat="server" Text="First Name" />It will be rendered as:

First Name

Tips to improve asp.net application performance


To increase the performance of an asp.net web application, in this post I offered some tips that I've found useful for writing high-performance ASP.NET applications:
  • Deploy with ‘Release' build and ensure ‘Debug' is set to false in the web.config
Make sure you use Release Build mode and not Debug Build when you deploy your site to production. When you create the application, by default the attribute ‘Debug' is set to "true" in the web.config which is very useful while developing. However, when you are deploying your application, always set it to "false". <compilation debug="false" ... />
  • Disable ViewState if you don’t need it
The ViewState is not needed when the following conditions are true:
a)The page does not post back (if it is used only to display data, only output page)
b)The events of the server controls are not handled
c)The controls are repopulated on each page refresh
  • Consider using caching
Caching avoids redundant work. If you use caching properly, you can avoid unnecessary database lookups and other expensive operations.ASP.NET allows you to cache entire pages, fragment of pages or controls. You can cache also variable data by specifying the parameters that the data depends. By using caching you help ASP.NET engine to return data for repeated request for the same page much faster.
  • Consider using HTTP compression
HTTP compression is supported by most modern browsers and by IIS. HTTP Compression is a define a way to compress content transferred from Web servers across the World Wide Web to browsers. The impact of compression is that the number of transmitted bytes is reduced and thus a higher performance is gained.
  • Consider disabling tracing
Before you deploy your application, disable tracing because it is not recommended to turn it on while the application is running in production. Tracing may cause performance issues.
<configuration>
<system.web>
<trace enabled="false" pageOutput="false" />
</system.web>
</configuration>
  • Consider using paging for large result sets
Paging large query result sets can significantly improve the performance of an application. The paging can be done at the SQL procedure level this will reduces the back-end work on the database, it be done at the server level to reduce the size of data that is sent to the client and that will be rendered as Html content.
  • Use 'using' statment to dispose resources
The using statement defines a scope at the end of which an object will be disposed even if an exception is thrown, please note that the object that you are trying to dispose should implement 'System.IDisposable'.The following code fragment demonstrates this. using (SqlConnection cn = new SqlConnection(connectionString))
{
using (SqlCommand cm = new SqlCommand(commandString, cn))
{
cn.Open();
cm.ExecuteNonQuery();
}
}
  • Stored Procedures
Stored procedures provide improved performance to your asp.net application. When you develop stored procedures, keep the following recommendations in mind:
·
Use Set NOCOUNT ON in stored procedures, if you turn on the NOCOUNT option, stored procedures will not return the row-count information to the client, and this will prevent SQL Server from sending the DONE_IN_PROC message for each statement in the stored procedure.
· Do not use the sp_ prefix for custom stored procedures, Microsoft does not recommend to use the prefix "sp_" in the user-created stored procedure name, because SQL Server always looks for a stored procedure beginning with "sp_" in the master database.
  • String Management
Use the += operator when the number of appends is known.
Use the StringBuilder object when the number of appends is unknown.

  • Consider using DTO pattern
In some cases to satisfy a single client request it require making multiple calls to the remote interface, so instead of doing multiple calls consider using Data Transfer Object (DTO) that holds all the data required by the remote call in one single object.
  • Consider using Server.Transfer instead of Response.Redirect
Both cause a new page to be processed, but the interaction between the client and server is different in each situation. Server.Transfer acts as an efficient replacement for the Response.Redirect method. Response.Redirect specifies to the browser to request a different page. Because a redirect forces a new page request, the browser makes two requests to the Web server, so the Web server handles an extra request. IIS 5.0 introduced a new function, Server.Transfer, which transfers execution to a different ASP page on the server. This avoids the extra request, resulting in better overall system performance

 Reference : Checklist for Performance Improvement http://msdn.microsoft.com/en-us/library/ff647706.aspx

Tuesday, June 19, 2012

ASP.Net Page-Life-Cycle

ASP.NET Page-Life-Cycle :



Page Life Cycle


ASP.NET Engine


FRAMEWORK_ARCHITECTURE

The .NET Framework provides support to developers to create new application. It consists of all the necessary components to develop and run programs on our computers. some of the components are as follows:
  • Common Language Runtime (CLR)
  • Common Type System (CTS)
  • Assemblies
  • Base Class Library
  • ASP .NET and ASP.NET AJAX
  • ADO.NET
  • Windows Forms
  • Windows Presentation Foundation (WPF)
  • Windows Communication Foundation (WCF)
  • LINQ
CLR (Common Languate Runtime) :
CLR is the most prominent component of .NET framework. As the name itself indicates that it is Runtime for the applications that are developed in .NET. It provides a runtime environment to the code and serves several services to the application like memory management, exception handling, security, threading, verification and compilation etc,. We can say in one sentence that “CLR manages code execution at runtime by managing every resource that possibly involved or necessary to complete the task”.
Managed code and Unmanaged code:
Managed Code:
Managed code is the code that is executed directly by the CLR. The applications that are created using managed code will have CLR components like automatic garbage collection type checking. These components will provide platform and language independence to managed code applications. The CLR compiles the applications to Intermediate Language (IL) not to machine language. This intermediate language describes the attribute, classes and methods the code in the assembly.  Intermediate Language is CPU independent, which must be converted to CPU understandable code which will be done by JIT Compiler (Just In Time Compiler) just before execution. Native code is a CPU specific code which is the output of the JIT Compiler that can actually runs in the runtime.
Unmanaged Code :
Unmanaged code can be directly compiled to machine code and  can run on the machine where it has been compiled. since it has no components like memory management and other prominent servies it might get manipulated and may cause harmful issues.

Common Type System ( CTS ) :
The CTS specifies guidelines for using, creating and managing data types at runtime. It is a included module in the runtime environment for supporting multilingual system. Main functions of CTS are as follows
  1. Helps in Cross language communication, type safety, and performance efficiency of code providing a framework.
  2.  Supports Object-Oriented model for implementation of different programming languages.
  3. Provides guidelines for different languages to follow, ensuring proper interaction between objects of different languages.
  4. Suooirts primitive data types, such as Byte, Char, Int Boolean that are used in the process of developoment of an application.
Assemblies and Metadata:
Generally an assembly is a unit that consists of four elements manifest, type metadata, IL Code and resources. A metadata is binary info that describes a program, stored in a CLR or in the memory. When compilation is going on a PE File(Portable Executable) the meta data is inserted into a part of file while code converted into IL which will be inserted into other part of file. Metadata describes every attribute we have. While executing the program CLR loads this meta data into memory and find information about all classes and methods needed to execute the application. The description of attributes in the metadata are language neutral, which includes identities like name, version, culture, public key, type of assembly, reference assemblies, permissions, Information about names, visibility, base class, interfaces used, and members.


 Thanks,
Reference MSN,Dotnet4u

Friday, June 15, 2012

Number To Word JavaScript


    <script>
        function Convert(rupeeval) {

            var rVal = rupeeval;
            rVal = Math.floor(rVal);
            var rup = new String(rVal);
            rupRev = rup.split("");
            actualNumber = rupRev.reverse();

            if (Number(rVal) >= 0) {

            }
            else {
                alert('Number cannot be converted');
                return false;
            }
            if (Number(rVal) == 0) {
                document.getElementById('wordValue').innerHTML = rup + '' + 'Rupees Zero Only';
                return false;
            }
            if (actualNumber.length > 9) {
                alert('the Number is too big to covertes');
                return false;
            }

            var numWords = ["Zero", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine"];
            var numPlace = ['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'];
            var tPlace = ['dummy', ' Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'];

            var numWordsLength = rupRev.length;
            var totalWords = "";
            var numtoWords = new Array();
            var finalWord = "";
            j = 0;
            for (i = 0; i < numWordsLength; i++) {
                switch (i) {
                    case 0:
                        if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                            numtoWords[j] = '';
                        }
                        else {
                            numtoWords[j] = numWords[actualNumber[i]];
                        }
                        numtoWords[j] = numtoWords[j] + ' Only';
                        break;
                    case 1:
                        CTen();
                        break;
                    case 2:
                        if (actualNumber[i] == 0) {
                            numtoWords[j] = '';
                        }
                        else if (actualNumber[i - 1] != 0 && actualNumber[i - 2] != 0) {
                            numtoWords[j] = numWords[actualNumber[i]] + ' Hundred and';
                        }
                        else {
                            numtoWords[j] = numWords[actualNumber[i]] + ' Hundred';
                        }
                        break;
                    case 3:
                        if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                            numtoWords[j] = '';
                        }
                        else {
                            numtoWords[j] = numWords[actualNumber[i]];
                        }
                        if (actualNumber[i + 1] != 0 || actualNumber[i] > 0) {
                            numtoWords[j] = numtoWords[j] + " Thousand";
                        }
                        break;
                    case 4:
                        CTen();
                        break;
                    case 5:
                        if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                            numtoWords[j] = '';
                        }
                        else {
                            numtoWords[j] = numWords[actualNumber[i]];
                        }
                        if (actualNumber[i + 1] != 0 || actualNumber[i] > 0) {
                            numtoWords[j] = numtoWords[j] + " Lakh";
                        }
                        break;
                    case 6:
                        CTen();
                        break;
                    case 7:
                        if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                            numtoWords[j] = '';
                        }
                        else {
                            numtoWords[j] = numWords[actualNumber[i]];
                        }
                        numtoWords[j] = numtoWords[j] + " Crore";
                        break;
                    case 8:
                        CTen();
                        break;
                    default:
                        break;
                }
                j++;
            }

            function CTen() {
                if (actualNumber[i] == 0) {
                    numtoWords[j] = '';
                }
                else if (actualNumber[i] == 1) {
                    numtoWords[j] = numPlace[actualNumber[i - 1]];
                }
                else {
                    numtoWords[j] = tPlace[actualNumber[i]];
                }
            }
            numtoWords.reverse();
            for (i = 0; i < numtoWords.length; i++) {
                finalWord += numtoWords[i];
            }

        }

</script>