Saturday, 7 November 2015

Delegate In C# With Example

0

Delegate is a type which  encapsulate a reference to a method inside a delegate object. Delegate are object-oriented, type-safe, and secure.

If this is our method :

public int add(int a, int b)
{
return a + b;
}




 To make reference to the method (add). 

 First we need to define the delegate to make its object (obvious).


Declaration :


Syntax

public delegate type_of_delegate delegate_name(  );

 It is declared globally i.e outside all functions.


public partial class Delegate : System.Web.UI.Page
{
public delegate int delegate_add(int a, int b);

protected void Page_Load(object sender, EventArgs e)
{
}



Using the delegate at a particular function, as said by passing the reference of the function(add) to the object of the delegate (AddUsingDelegate).


 protected void btnAdd_Click(object sender, EventArgs e)
{
delegate_add AddUsingDelegate = new delegate_add(add);
int result = AddUsingDelegate(int.Parse(txtNo1.Text), int.Parse(txtNo2.Text));

}


Putting Altogether 

public partial class Delegate : System.Web.UI.Page
{
public delegate int delegate_add(int a, int b);

protected void Page_Load(object sender, EventArgs e)
{
}

protected void btnAdd_Click(object sender, EventArgs e)
{
delegate_add AddUsingDelegate = new delegate_add(add);
int result = AddUsingDelegate(int.Parse(txtNo1.Text), int.Parse(txtNo2.Text));

}
public int add(int a, int b)
{
return a + b;
}
}


Advantages :


Encapsulating the method's call from caller
When we are using delegate it provide exact encapsulation as we are using a separate class. Here our method call is completely encapsulated


Effective use of delegate improves the performance of application
The performance is improved due to encapsulation and due to the fact that it is decided at run-time which method is called.

Anonymous" invocation
Property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.








Read More »

Thursday, 5 November 2015

Validating Currency and Number upto 4 decimals

0


Question :

I would like to validate whether a string satisfy the following currency format with maximum 4 decimal places and could allow ',' regardless of culture.
Eg:
2,000,000(valid)
200000.0000(valid)
200 (valid)
200.00000(invalid)
How could it be done?


Solution :

I have tried this on a web application :

design page :

<asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
    <asp:Button ID="btnCheck" runat="server" Text="check" onclick="btnCheck_Click" />
    <asp:Label ID="lblResult" runat="server"></asp:Label>


code page :




protected void btnCheck_Click(object sender, EventArgs e)
{
string NumberEntered = txtNumber.Text;


if (NumberEntered.Contains('.'))
{
string[] newNumber = NumberEntered.Split('.');


if (newNumber.Length == 2)
{
string noOfZeros = newNumber[1];

if (noOfZeros.Length <= 4)
{
lblResult.Text = "Number is accepted";
}
else
{
lblResult.Text = "Number is not accepted";
}
}
}
else
{
lblResult.Text = "Number is accepted";
}

}


Read More »

How to bind dropdownlist at page load in asp.net ?

0


Design Code :


<asp:DropDownList ID="ddlName" runat="server"
          AutoPostBack="true">

    </asp:DropDownList>

Note : AutoPostback is marked true.




At .cs 

  protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlBind( );
            }
       }
 public void ddlBind( )
        {
            string[ ] UserName = new string[ ] { "Kumar", "Rohit", "Shivam" };
            ddlName.DataSource = UserName;
            ddlName.DataBind( );
        }



Note :    

We have first checked that the page is a postback or not.
 If you will not use IsPostBack then you will always get "Kumar" our first listitem at the time of selectedIndexChange

Because the dropdown is re-binded.


Related Articles :


Read More »

Wednesday, 4 November 2015

File validation on size and extension

0


When you provide fileUpload button to let user upload some file, you surely require to validate the file extension and size of file.

Getting File Extension :

string fileExt = Path.GetExtension(fileUpload1.FileName);
//Here fileUpload1 is the fileUpload button id.

Now you can check this extension with the required extension.


Getting File Size :

  double fileSize = fileUpload1.FileBytes.Length;
// The fileSize will be in bytes.

Now just compare this value with the maximum file size allowed.



You can do the same in web.config File :


We use web.config to make settings global and more secure.


Web.config

 <appSettings>
    <add key="fileExtension" value=".txt"/>
    <add key="fileSize" value="1024"/>
 
  </appSettings>

// Means we are storing .txt at key fileExtension.
We could have saved more then one value by separating them by comma (,).


.cs file

string FileExtensionlist = ConfigurationManager.AppSettings["fileExtension"].ToString();
int FileSizeLimit = int.Parse(ConfigurationManager.AppSettings["fileSize"]);

Note:

 By default 4MB of file is allowed to be uploaded in asp.net.


If you want to increase the filesize validation then wrote following code in web.config:


maxRequestLength:

 Specifies the limit for the input stream buffering threshold in KB and allows you to control the allowed total size of the upload. Anything bigger than that will result in the default for the framework "Page not found" error.

ExecutionTimeout:

Specifies the maximum number of seconds for which a request is allowed to be executed before being automatically shut down by ASP.NET – the default time is 110 seconds. If the request takes longer to be executed, an exception will be thrown.


Code :

<system. web>

<httpRuntime maxRequestLength="102400" executionTimeout="3600" />

...

</system .web>

// /this will make the limit to 100MB. and execution time is 3600 sec.



Read More »

Tuesday, 3 November 2015

Session State in Asp.net

0


Web-based programming distinguishes itself as a programming idiom in which you try to manage an application serving multiple users distributed over a wide area. So, we need to have particular sort of data such as username for all different active users to provide the file and services for that are meant for them. To do this we require, data-holding area that persists for the lifetime of a single user’s session. This type of data is known as session state.



The Session object is a dictionary of name/value pairs. You can associate any Common Language Runtime (CLR)-based object with a key of your choosing and place it in the Session object so that it will be there when the next request belonging to that session comes through. Then, you can access that piece of data using the key under which it was stored.

For Example:


If you want to store some information provided by the user in the Session object, you can write code like this:

void StoreInfoInSession()
{
String strFromUser = TextBox1.Text;
Session["strFromUser"] = strFromUser;
}  
// To retrieve the string during the next request, use code like this: 
void GetInfoFromSession()
{
String strFromUser = Session["strFromUser"] ; // NOTE: may be null
TextBox1.Text = strFromUser;
}


The brackets on the Session object indicate an indexer. The indexer is a convenient syntax for expressing keys—both when inserting data into and retrieving data from the Session object.


 In ASP.NET, session state can live in a number of places, including
(1) “in proc”—in the ASP.NET worker process,
(2) on a separate state server running a Windows Service process, and
(3) in a Microsoft SQL Server database.


Configuring Session State


Don’t use it at all.        By disabling session state, your application performance will increase because the page doesn’t need to load the session when starting, and neither does it need to store session state when it’s going away. On the other hand, you won’t be able to associate any data with a particular user between page invocations.


 Store session state “in proc.”   This is how session state is handled by default. In this case, the session dictionaries (the Session objects) are managed in the same process as the page and handler code. The advantage of using session state in process is that it’s very fast and convenient. However, it’s not durable. For example, if you restart Internet Information Services (IIS) or somehow knock the server down, all session state is lost. In some cases, this might not be a big deal. However, if the shopping cart contains sizable orders, losing that might be a big deal. In addition, the in-process session manager is confined to a single computer, meaning you can’t use it in a Web farm. (A Web farm is a group of servers tied together to serve Web pages as a single application.)


Store session state in a state server.      This option tells the ASP.NET runtime to direct all session management activities to a separate Windows Service process running on a particular computer. With this option, you have the advantage of running your server in a Web farm. The ASP.NET session state facilities support Web farms explicitly. To run in a Web farm, you direct all your applications to go to the same place to retrieve session information. The downside of this approach is that it does impede performance somewhat—applications need to make a network round-trip to the state server when loading or saving session information. To reduce the overall size of the stored information, when storing session data in the state server, with ASP.NET 4 you now have the option of using compression to reduce the amount of data being transferred. Just include the compressionEnabled=true setting in the sessionState section of web.config.


 Store session state in a database.  Configuring your application to use a SQL Server database for state management causes ASP.NET to store session information in a SQL Server database somewhere on your network. Use this option when you want to run your server from in a Web farm when you want session state to be durable and safe. As with the state server approach, when storing session data in the SQL Server database, you have the option of using compression to reduce the amount of data being transferred. Again just include the compressionEnabled=true setting in the sessionState section of web.config.


you might prefer to configure session state through the session state configuration page in IIS:



Session State Timeouts


The timeout configuration setting manages the lifetime of the session. The lifetime of the session is the length of time in minutes a session can remain idle before ASP.NET abandons it and renders the session ID invalid. The maximum value is 525,601 minutes (one year), and the default is 20.



Read More »