Thursday, 30 May 2013

Storing Class Object in Session in Asp.net

Create a new Project in Asp.net 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.


Thanks
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.

Example:

If you want to add one variable in View State,
ViewState["Var"]=Count;

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
User_S1.jpg
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
[Serializable]
public class student
{
    public int Roll;
    public string Name;
    public void AddStudent(int intRoll,int strName)
      {
        this.Roll=intRoll;
        this.Name=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.

User_S4.gif













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)
{
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
}


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 asp.net .


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);
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                dr.Read();
                Session["uid"] = TextBox1.Text;
                Session["upass"] = TextBox2.Text;
                Response.Redirect("Admin.aspx");
            }
            else
            {
                Response.Redirect("Error.aspx");
            }
        } 
    }


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


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)
    Console.WriteLine(i);

Output:
0
1
2

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
Aggregation
  • Aggregate
  • Average
  • Count
  • LongCount,
  • Max,
  • Min,
  • Sum
Conversion
  • Cast,
  • OfType,
  • ToArray,
  • ToDictionary,
  • ToList,
  • ToLookup,
  • ToSequence
Element
  • DefaultIfEmpty,
  • ElementAt,
  • ElementAtOrDefault,
  • First,
  • FirstOrDefault,
  • Last,
  • LastOrDefault,
  • Single,
  • SingleOrDefault
Equality
  • EqualAll
Generation
  • Empty,
  • Range,
  • Repeat
Grouping
  • GroupBy
Joining
  • GroupJoin,
  • Join
Ordering
  • OrderBy,
  • ThenBy,
  • OrderByDescending,
  • ThenByDescending,
  • Reverse
Partitioning
  • Skip,
  • SkipWhile,
  •  Take,
  •  TakeWhile
Quantifiers
  • All,
  • Any,
  • Contains
Restriction
  • Where
Selection
  • Select,
  • SelectMany
Set
  • 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";         
        patients.Add(p);


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;
   gdView.DataBind();
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)
     {
       Debug.WriteLine("\t"+l.PatientName);
     }
 }
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 →

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)