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
    A- LINQ to SQL (formerly DLinq) {Queries performed against the relation database only Microsoft SQL Server Supported}
    B- LINQ to DataSet {Supports queries by using ADO.NET data sets and data tables}
    C- 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.

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

Return type of Linq
its depends on the select operation.
If you are querying a database(Linq to SQL) then the return type is IQueryable<T> where T is Product in below
var product = from p in dbContext.Products
             
select p;
If you are using Linq againist a datasource which is an Enumerable collection(List) then the return type will be IEnumerable<t>

Continue Reading →

Wednesday 22 May 2013

ADO.NET Entity Framework:: Insert Update and Delete


Every .NET developer sometime will start using ADO.NET Entity Framework.
And first question will be such as how to insert, update and delete records.
Performing basic Inser, Update and Delete operations via the Entity Framework is very straight forward.

first you need to create a Database Table -
Script-
Create Database StudentDetail

USE [StudentDetail]
GO

CREATE TABLE [dbo].[login](
 [loginid] [varchar](20NOT NULL,
 [password] [varchar](20NOT NULL,
  [rights] [varchar](20Null
)

after that you need to create a new Project windows or Web as per your Knowledge and Need..

Right Click on Project in SolutionExplorer Add -> Add New Item .opens a Pop Window , Add new edmx File like this.



Rename the file Name Click Add. it opens a new Popup Window Data Model Wizard. select Generate From Database click on Next Button . Click on New Connection Button , Connection Properties Popup Opens. Change Datasource as Microsoft SQL Server. Provide Server Name, Database name and Click OK button.
Entity Class name is byDefault Entered in TextBox like Below , Click on Next.


in the Next Popup Select Table from Database Click on Finish Button. Your edmx file Looks like This


Now you have to Write the Code for CRUD operation...

for insert Operation use the below Code  in Your Function 
     using (StudentDetailEntities std = new StudentDetailEntities())
            {
           #region  Code for insert row in Table using EF
           login log = new login() { loginid = "S009", password = "pass", rights = "user" };
                //Add to memory
                std.AddTologins(log);
                //Save to database
                std.SaveChanges();
      #endregion
          }


for Update Operation use the below Code  in Your Function 


          using (StudentDetailEntities std = new StudentDetailEntities())
            {
       #region  Code for Update row in Table using EF
                //Get the specific LoginID from Database
            login _log = (from log in std.logins where log.loginid == "S009" select              log).First();
                //Change the LoginID in memory
                _log.password = "s009";
                //Save to database
                std.SaveChanges();
         #endregion

             }

for Delete Operation use the below Code  in Your Function 

           using (StudentDetailEntities std = new StudentDetailEntities())
            {
              #region  Code for Delete row in Table using EF
              login _login= (from log in std.logins where log.loginid== "s009" select log).First();
                std.DeleteObject(_login);
                std.SaveChanges();
                #endregion
           
          }

Happy coding!

Thanks and Regards
SUraj K Mad.




Continue Reading →

Tuesday 21 May 2013

API and Web Service

Difference Between API and Web Service

An API is an Application Programming Interface. An example of an API would be ADO.NET or Google APIs . An API encapsulates functionality into a library for you to access. It contains the operations, properties, etc. necessary to perform your actions.

A web service is a middle tier operation that you write on your own or consume someone Else's. A web service contains functionality that does some sort of operation. Example: A user inputs a value into a text box and clicks a submit button. The submit button calls the web service and passes the value in the text box to it. The web service accepts this value and makes a call to a database to query information. The database returns the information to the web service. The web service can then perform an operation on that set of information or simply send it back to your presentation layer for the user to see.
Continue Reading →

Thursday 16 May 2013

Maintaining Session in MVC


Sessions can be maintained in MVC by 3 ways tempdata ,viewdata and viewbag.

What is the difference between tempdata ,viewdata and viewbag?

Temp data: -Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect,“tempdata” helps to maintain data between those redirects. It internally uses session variables.

View data: - Helps to maintain data when you move from controller to view.

View Bag: - It’s a dynamic wrapper around view data. When you use “Viewbag” type casting is not required. It uses the dynamic keyword internally.

Session variables: - By using session variables we can maintain data from any entity to any entity.

Hidden fields and HTML controls: - Helps to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Below is a summary table which shows different mechanism of persistence.

Maintains data betweenViewData/ViewBagTempDataHidden fieldsSession
Controller to ControllerNoYesNoYes
Controller to ViewYesNoNoYes
View to ControllerNoNoYesYes

Continue Reading →

Tuesday 14 May 2013

How to find page load time: ASP.NET

One of the important factors that measures a website's performance is the page loading time. Therefore, it is very essential to keep an eye on how long it takes for web pages to load on the client browser. In ASP.NET, this can be achieved using the application class, that acts as an entry point for all incoming requests. I am considering a situation where you just need the page load time. If you want to know more detailed diagnostic information about web pages, I recommend you to take a look at the Tracing Option ASP.NET provides, that would help you to know more than just the loading time of the page. Using Application class's begin_request and end_request handlers you can log the time taken for each web page in your web application to load.

To make use of the Application Class, add a new Global.asax page to your ASP.NET web application and add the below code to it. 

public void Application_BeginRequest(object srcEventArgs e)
{
    Context.Items["loadstarttime"] = DateTime.Now;
}

public void Application_EndRequest(object srcEventArgs e)
{
    DateTime end = (DateTime)Context.Items["loadstarttime"];
    TimeSpan loadtime = DateTime.Now - end;
    Response.Write("<h3>This page took " + loadtime + "ms to load</h3>");
}

The above code will execute whenever a page in your web application is requested. BeginRequest event will fire whenever a new request is received and EndRequest will fire when the request is processed. We make use of the Items collection of the Context class to store and retrieve the initial time when the request is received. Now the time taken for the page to load will be displayed in each page of your web application whenever each of it is requested just like the one shown below.

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives