Thursday, 30 May 2013

Storing Class Object in Session in

Create a new Project in named "storeObjInSession"

in Default.aspx.cs file within class put below code snippet..

// properties that you want to store in session
        public int EmpId {get; set;}
        public string EmpName {get; set;}

//constructor to assign value in Properties
        // you can also get value in Properties from UI
        public _Default() {
            EmpId = 1;
            EmpName = "Suraj K.";

        protected void Page_Load(object sender, EventArgs e)
            _Default emp1 = new _Default();
            Session["EmployeeObj"] = emp1;

when we run our project Default.aspx page on the page load event  _Default class object is stored in Session variable Session["EmployeeObj"]  .

Accessing Session data  in other page

now we can get this object in other web page by Session. 
in about.aspx page create two aspx label named lbl1 and lbl2 like this...

    <asp:Label ID="lbl1" runat="server"></asp:Label><br />
    <asp:Label ID="lbl2" runat="server"></asp:Label>

in about.aspx.cs page  within Class we put the following Code..

        protected void Page_Load(object sender, EventArgs e)
            _Default obj;
            obj = (_Default)(Session["EmployeeObj"]);
            lbl1.Text = obj.EmpId.ToString();
            lbl2.Text = obj.EmpName;

now run your Application . run default.aspx page and after that click on about link(about.aspx) .here we get EmpId and EmpName data through Session.

Suraj K. Mad.

Continue Reading →

Wednesday, 29 May 2013

View State in Asp.Net

What is view state?
View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page.


If you want to add one variable in View State,

For Retrieving information from View State
string Test=ViewState["TestVal"];

When we should use view state?

  • Size of data should be small , because data are bind with page controls , so for larger amount of data it can be cause of performance overhead.
  • Try to avoid storing secure data in view state

View State use Hidden field to store its information in a encoding format.

Suppose you have written a simple code , to store a value of control:

ViewState["Value"] = MyControl.Text;

Now, Run you application, In Browser, RighClick > View Source , You will get the following section of code
How to store object in view state?

We can store an object easily as we can store string or integer type variable. But what we need ? we need to convert it into stream of byte. because as I already said , view state store information in hidden filed in the page. So we need to use Serialization. If object which we are trying to store in view state ,are not serializable , then we will get a error message .

Just take as example,

//Create a simple class and make it as Serializable
public class student
    public int Roll;
    public string Name;
    public void AddStudent(int intRoll,int strName)

Now we will try to store object of "Student" Class in a view state.

//Store Student Class in View State
student _objStudent = new student();
_objStudent.AddStudent(2, "Abhijit");
ViewState["StudentObject"] = _objStudent;

//Retrieve Student information view state
 student _objStudent;
_objStudent = (student)ViewState["StudentObject"]; 

Enabling and Disabling View State
You can enable and disable View state for a single control as well as at page level also. To turnoff view state for a single control , set EnableViewState Property of that control to false. e.g.:
TextBox1.EnableViewState =false;

To turnoff the view state of entire page, we need to set EnableViewState to false of Page Directive as shown bellow.


Continue Reading →

Monday, 27 May 2013

Prevent User To Go Back Page After Logout

simply put this function in your Webpage . this will prevent user to go to back page after logout ..

protected void Page_Init(object sender, EventArgs e)

Continue Reading →

Thursday, 23 May 2013

SQL Injection

SQL injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution. Any procedure that constructs SQL statements should be reviewed for injection vulnerabilities because SQL Server will execute all syntactically valid queries that it receives. Even parameterized data can be manipulated by a skilled and determined attacker.

The primary form of SQL injection consists of direct insertion of code into user-input variables that are concatenated with SQL commands and executed. A less direct attack injects malicious code into strings that are destined for storage in a table or as metadata. When the stored strings are subsequently concatenated into a dynamic SQL command, the malicious code is executed.

The injection process works by prematurely terminating a text string and appending a new command. Because the inserted command may have additional strings appended to it before it is executed, the malefactor terminates the injected string with a comment mark "--". Subsequent text is ignored at execution time.

The following example shows a simple SQL injection.
SQL Server Table 'login' -

I have Created a Login page in .

the Code for Login Button is below Described..

protected void Button1_Click(object sender, EventArgs e)
        if (TextBox1.Text != "" && TextBox2.Text != "")
            id = TextBox1.Text;
            pass = TextBox2.Text;
            string query= "select * from login where loginid='" + TextBox1.Text + "' and password= '" + TextBox2.Text + "'";
            SqlCommand cmd = new SqlCommand(query, con);
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
                Session["uid"] = TextBox1.Text;
                Session["upass"] = TextBox2.Text;

now enter the LoginId and Password in textboxes of Login Page (suppose userid is 'admin' and password is 'admin' ) the query Variable contains "select * from login where loginid='admin' and password= 'admin' ";
the Page login Successfull.

Now the Question is How to inject this or Login if we don't  know UserID and Password..

this is very Simple . You just need to pass the Sql Query snippet in Login Textbox and you can Login Successfully.

now enter the  ' or 1=1;--  in UserID text box and enter some characters in Password textbox(if you set Required field for Password) and Click Login Button. now the query variable Contains  "select * from login where loginid='' or 1=1;--' and password= 'pass' ";
the Page logins Successfull. this Query comment the Password condition and 1 = 1 becomes true and fetch the all login table information. and you can access the admin.aspx page .

this is the Way You can Access Authorised Data if you are Unauthorised.
please feel free to comment or ask anything.

Thanks and Regards:
Suraj K. Mad.

Continue Reading →


LINQ is a technique for querying data from any Datasource. data source could be the collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.

Advantages:  as Linq Queries is integrated with .net c# language , it enables you to write code much faster then than if you were writing oldstyle queries. In some cases I have seen, by using LINQ development time cut in half.
Microsoft basically divides LINQ into three areas and that are give below.
1- LINQ to Object {Queries performed against the in-memory data}
2- LINQ to ADO.Net

  • LINQ to SQL (formerly DLinq) {Queries performed against the relation database only Microsoft SQL Server Supported}
  • LINQ to DataSet {Supports queries by using ADO.NET data sets and data tables}
  • LINQ to Entities {Microsoft ORM solution}
3- LINQ to XML (formerly XLinq) { Queries performed against the XML source}

now we write some code snippet of LINQ.

1. Code Snippet

int[] nums = new int[] {0,1,2};
var res = from a in nums
             where a < 3
             orderby a
             select a;
foreach(int i in res)


One thing that I want to share with you guys is LINQ to Object support querying against any object that inherits from IEnumerable (all .Net collection inherits from IEnumerable interface). LINQ to Object provided main types of Operator Type that are give below.

Operator Types
Operator Name
  • Aggregate
  • Average
  • Count
  • LongCount,
  • Max,
  • Min,
  • Sum
  • Cast,
  • OfType,
  • ToArray,
  • ToDictionary,
  • ToList,
  • ToLookup,
  • ToSequence
  • DefaultIfEmpty,
  • ElementAt,
  • ElementAtOrDefault,
  • First,
  • FirstOrDefault,
  • Last,
  • LastOrDefault,
  • Single,
  • SingleOrDefault
  • EqualAll
  • Empty,
  • Range,
  • Repeat
  • GroupBy
  • GroupJoin,
  • Join
  • OrderBy,
  • ThenBy,
  • OrderByDescending,
  • ThenByDescending,
  • Reverse
  • Skip,
  • SkipWhile,
  •  Take,
  •  TakeWhile
  • All,
  • Any,
  • Contains
  • Where
  • Select,
  • SelectMany
  • Concat,
  • Distinct,
  • Except,
  • Intersect,
  • Union

To the good use of above operator types I need samle patient class so here it

using System;

public class Patient
    // Fields
    private string _name;
    private int _age;
    private string _gender;
    private string _area;
    // Properties
    public string PatientName
        get { return _name; }
        set { _name = value; }

    public string Area
        get { return _area; }
        set { _area = value; }
    public String Gender
        get { return _gender; }
        set { _gender = value; }
    public int Age
        get { return _age; }
        set { _age = value; }

Here is my code that intiliaze patients object with following data.

List<Patient> patients = new List<Patient> {
           new Patient { PatientName="Ali Khan", Age=20, Gender="Male" , Area = "Gulshan"},
           new Patient { PatientName="Ahmed Siddiqui", Age=25 ,Gender="Male", Area = "NorthKarachi" },
           new Patient { PatientName="Nida Ali", Age=20, Gender="Female", Area = "NorthNazimabad"},
           new Patient { PatientName="Sana Khan", Age=18, Gender="Female", Area = "NorthNazimabad"},
           new Patient { PatientName="Shahbaz Khan", Age=19, Gender="Male", Area = "Gulshan"},
           new Patient { PatientName="Noman Altaf", Age=19, Gender="Male", Area = "Gulshan"},
           new Patient { PatientName="Uzma Shah", Age=23, Gender="Female", Area = "NorthKarachi"}};
Patient p = new Patient();
        p.Age =33; p.Gender = "male";
        p.PatientName = "Hammad Ali"
        p.Area = "Defence";         

I have been written a blog on the new way of initilaztion.

This code snippet fetch those records whose gender is equal to “Male”. 
   gdView.DataSource = from pa in patients
                        where pa.Gender == "Male"
                        orderby pa.PatientName, pa.Gender, pa.Age
                        select pa;
The following code snippet uses the selection operator type, which brings all those records whose age is more than 20 years.
 var mypatient = from pa in patients
                  where pa.Age > 20
                  orderby pa.PatientName, pa.Gender, pa.Age
                  select pa;
        foreach(var pp in mypatient)
        Debug.WriteLine(pp.PatientName + " "+ pp.Age + " " +          pp.Gender);
 The following code snippet uses the grouping operator type that group patient data on the bases area. 
var op = from pa in patients
group pa by pa.Area into g
select new {area = g.Key, count = g.Count(), allpatient = g};
 foreach(var g in op)
    Debug.WriteLine(g.count+ "," + g.area);
    foreach(var l in g.allpatient)
This code snippet determine the count of those records, which lay in above 20 years. 
int patientCount = (from pa in patients
                    where pa.Age > 20
                    orderby pa.PatientName, pa.Gender, pa.Age
                    select pa).Count();

All the above codes are few example of LINQ to Object technique of LINQ. In my up coming post you will see both LINQ to SQL and LINQ to XML code snippets.

Happy Coding...
Thanks and Regards:
Suraj K. Mad.

Continue Reading →


ADFS (1) ADO .Net (2) Ajax (1) Angular (1) Angular Js (17) Angular2 (28) ASP .Net (14) Authentication (1) Azure (1) Breeze.js (1) C# (50) CD (1) CI (2) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DevOps (4) DI (4) Dotnet (22) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (8) Lamda (3) Linq (11) Mongodb (1) MVC (50) NodeJS (7) RDLC (1) Report (1) SDLC (1) Sql Server (30) SSIS (3) SSO (1) SSRS (2) UI (1) WCF (13) Web Api (11) Web Service (1) XMl (1)