Friday, July 31, 2009

Enable session state on a Web Methods, Web service

By default each web method session state is disabled.
Example:

Declare and assign a session variable in Global.asax Session_Start.

void
Session_Start(objectsender, EventArgs e)
{
Session["Overhead"] = 3;
}

Access this session variable (Session["Overhead"] ) in Add Web Method.

[WebMethod(Description = "adds x , y and Overhead session")]
public int Add(int x, int y)
{
return (x + y) + (int)Session["Overhead"] ;
}

This will not work and throws an error. To avoid this needs to enable session state in each web metods.

Example:

[WebMethod(EnableSession = true, Description = "adds x , y and Overhead session")]
public int Add(int x, int y)
{
return(x + y) + (int)Session["Overhead"] ;
}

In this above example in the [WebMethod] attribute EnableSession property has explicitily set to true. Now the Add web method is retrieving Session["Overhead"] variable’s value. All you have to do is just enable the session in [WebMethod] attribute.


Thursday, July 30, 2009

WebService Method Overloading

Thursday, July 30, 2009

WebService Method Overloading

First of all what is method overloading ?
Method means having more than one method with the same name but different signature is the simple definition.
Example:

private int Add(int x, int y)
{
return x + y;
}

private int Add(int x)
{
return x + 3;
}

private float Add(float x, float y)
{
return x + y;
}

Above three methods have the same name but different signature.
The following table shows the signature difference among Add methods.

Though method overloading allowed in .Net, it's not allowed in web services as to comply with a rule (WSI BP 1.1 is that each method within a WSDL document must be unique), This clearly emphasis on method overloading. But by using [WebMethod] attribute we can use method overloading. With [WebMethod] pass the MessageName then web service uniquely identifies the overloaded methods.

Example:

[WebMethod(Description = "Adds two integers.",MessageName = "AddInts")]
private int Add(int x, int y)
{
return x + y;
}

[WebMethod(Description = "Adds 3 on an int value.",MessageName "AddThree")]
private int Add(int x)
{
return x + 3;
}

[WebMethod(Description = "Adds two floats.", MessageName = "AddFloats")]
private float Add(float x, float y)
{
return x + y;
}

Here on above three Add methods have unique MessageName as to allow method overloading in web services
Tuesday, July 28, 2009

VS2010 Beta C# 4.0 Optional parameters, named arguments A feature I was waiting for..

I was a VB 6.0 developer and I still doing some vb6.0 coding. I often use optional arguments(parameters) with vb6.0, which makes my life easy most of the times.

What is an optional argument?
Arguments must be provided when calling a method if it is not an optional parameter, but can omit arguments for optional parameters.


Example:
VB6.0

Public Function PurchaseOrder(ByVal vPurOrdNo As String, Optional vNotes As Variant)
''Coding....
End Function

on the above example PurchaseOrder function can be called in both ways as follows,

call PurchaseOrder("2010", "passing value to optional argument")
or
call PurchaseOrder("2010")

I was wondering why Microsoft dosn't introduce this feture in visual c# as it's provide such a richness for the language. I heard a good news, .Net 4.0 framework has this feture with named arguments.

* Each optional parameter has a default value as part of its definition
* If argument not passed for optional parameter then the default value will be used.
* Optional parameters must be declared after all the normal parameters (most right side)

Here is the above example PurchaseOrder method is C#

public class OptionalArgumentExample
{
static void Main(string[] args)
{
// Instance anExample does not send an argument for the constructor's
// optional parameter.

PurchaseOrder("2010", "passing value to optional argument");
PurchaseOrder(("2010");
}



// optional parameters needs to be defined with default values. in this
// example "notes" paramete has a default value, so the here the "notes"
//parametes is optional.
public void PurchaseOrder(string purordno, string notes= "default string")
{
//coding here..
}
}


What is a named argument?
Named arguments allows you to pass an argument for a parameter with the parameter's name rather than with the parameter's position in the parameter list.
Example:
C# .Net4.0
public class NameArgumentExample
{

static void Main(string[] args)
{
// Calling normal way
Console.WriteLine(CalculateInterest(5000, 10));

// passing with named arguments any order
Console.WriteLine(CalculateInterest(capitol: 5000, interestRate: 10));
Console.WriteLine(CalculateInterest(interestRate: 10, capitol: 5000));

}

static int CalculateInterest(int capitol, int interestRate)
{
return (( capitol / 100) * interestRate );
}
}
Monday, July 20, 2009

Rare validation

It's very rare get a chance to validate a check box, I got it today. VS doesn't have a
validation control to achieve this but www.asp.net has recommended a validation
control i.e CheckValidator which is a .dll (AT.Web.UI.Validators.dll
) and can be added to the tool panel. I added this to my validation controls section .
Can be used as normal validation control to validate checkboxes and radio boxes.


<"asp:checkbox ID="chkAgreement" runat="server" Text="I have read the agreement" /">
<"asp:Button ID="btnSubmit" runat="server" Style="z-index: 100; left: 129px; position: absolute; top: 77px" Text="Submit" /">

<"at:CheckValidator ID="_checkValidator" runat="server" ControlToValidate="chkAgreement" Text="Please accept the agreement" style="z-index: 102; left: 15px; position: absolute; top: 47px"">
<"/at:CheckValidator">

A personal belief

I personally believe as a Sri Lankan, Mr Bandaranayake is the bad ever governor
in Sri Lanka. I personally believe we are not yet independent though Mr. Bandaranayake
spelled it several times. As declaring Sinhalese as the official language he created a gap between poor and rich, conflict between Tamils and Sinhalese and a opportunity to learn English which could have bring most success to our country,

Watch this video and feel free to comment my personal vision.

http://www.youtube.com/watch?v=rbL5E5naR6s
Thursday, July 16, 2009

Session variable lifetime

 

Before I talk about session variable's life time, Ill just brief why a session variable comes in to play with a web application.

A session is a mechanism to maintain state on a web application, as HTTP protocol is a stateless protocol. What does it means by stateless? this protocol (HTTP) serves as the request comes and destroys all the data (information) on a request. Pages are destroyed and recreated with each round trip to server. Session variables comes in to play when there is a requirement to maintain the state of a web application. Do not misunderstand that session is not the only mechanism to available to maintain state of a web application. Ok, will get back to the topic.

On an ASP.Net application session variable's expiry time decides the life time of a Session
set in the web.config configuration section under
Example:

< sessionState mode="InProc"  timeout="20" >

In the above example the timeout = "20" sets the
expiry time of session variables to 20 minutes.
Tuesday, July 14, 2009

A tip to avoid SQL injection

System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(
"select * from Orders where OrderID= '" + passOrderID + "'";

An user can pass anything to passOrderID , this leads a hacker to easily replace
string with something malicious. As shown in the above bad example do not build
dynamic strings, instead use parameters. Anything passed to a parameter considered
as field data and not as part of SQL statement, This avoids above malicious scenario.

Following code snippet demos a parametrized querying steps,



//define SQLCommand object
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(
"select * from Orders where OrderID= @OrderID", conn);

//define parameters used in SQLCommand object
SqlParameter para = new SqlParameter();
para.ParameterName = "@OrderID";
para.Value = passOrderID;

// add parameter to SQLCommand object
cmd.Parameters.Add(para);

or in one line

cmd.Parameters.Add(new SqlParameter("@OrderID",passOrderID));

This makes the application more secure.

Monday, July 13, 2009

Early and Late Binding

Declaring an variable with specific object type called Early Binding.
Example:

'  Create a variable to hold a new object of type File Stream.
Dim fs As System.IO.FileStream

Declaring an variable with type object called Late Binding,
later this variable can hold any object type.

' Create a variable to hold a new object
Dim
anyObject As Object
or
Dim fs

' Later you can assign any object type to this variable
anyObject = CreateObject("Excel.Application")
or you can use the anyObject to hold any other your object type
anyObject = CreateObject("Define.Start")




Friday, July 10, 2009

maintain scrollposition after post back?

By default a web page will be returned to the top of the page, after a postback. What if you want to take back to the position where user was before the postback , it's simple. You can do one of the followings.

1.For the whole website
In the web.config add the attribute to the pages node.
<"pages maintainScrollPositionOnPostBack="true">

2. Particular page,
In the HTML (.ASPX)

< %@ Page Language="C#" MaintainScrollPositionOnPostback = "true"


and you can set this in

3.CODE (ASPX.SC)
Page.MaintainScrollPositionOnPostBack = true;

That's all you have to do. You will be back to where you were.

My Achievements

Member of

Blog Archive

Followers

free counters