ASP.NET

Also checkout my blogs on: PMP | C# | SQL | Personal

 
  Friday, January 27, 2006

Remoting

System.Runtime.Remoting.ObjectHandle objRemote;

objRemote = System.Activator.CreateInstance(assemblyName, className);

object objCurr = objRemote.Unwrap();

int test = objCurr.Sum(1,2)                    


http request to another webpage

System.Net.HttpWebResponse Rs;

System.Net.HttpWebRequest Rq;

Rq = (HttpWebRequest)WebRequest.Create(url);

Rq.Method = "GET";

Rq.ContentType = "text/html";

Rq.Proxy.Credentials = CredentialCache.DefaultCredentials;

Rq.Credentials = CredentialCache.DefaultCredentials;

Rq.ServicePoint.ConnectionLimit = 25;

Rs = (HttpWebResponse)Rq.GetResponse();

StreamReader sr= new StreamReader(Rs.GetResponseStream());

String html = sr.ReadToEnd();


Wednesday, January 11, 2006

SQL Connection

///////////

using System.Data;

using System.Data.SqlClient;

///////////

SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);

SqlCommand myCommand = new SqlCommand("sp_UpdateUser", myConnection);

myCommand.CommandType = CommandType.StoredProcedure;

SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);

parameterItemID.Value = itemId;

myCommand.Parameters.Add(parameterItemID);

// out parameters to Sproc

SqlParameter paramRoles = new SqlParameter("@AccessRoles", SqlDbType.NVarChar, 256);

paramRoles.Direction = ParameterDirection.Output;

myCommand.Parameters.Add(paramRoles);

myConnection.Open();

try

{

   myCommand.ExecuteNonQuery();

//or

// SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

// return result

}

catch{}

finally

{

  if (myConnection.State == ConnectionState.Open)

   {

        myConnection.Close();

   }

}



Tuesday, January 10, 2006

Error Handling

  • By default, the information shown for a run-time error is the call stack.
  • If debug mode is enabled, ASP.NET displays the line number in source code where the run-time error originated.

<%@ Page Debug="true" % >

<configuration> <system.web> <compilation debug="true"/> </system.web> </configuration>

  • errors are shown to local clients, to remote clients, or to both. By default, errors are only shown to local clients (clients on the same computer as the server). You can also specify a custom error page to redirect clients to if an error occurs.
  • errors can be handling at the page page level, also at application level in Application_Error event in Global.asax. This event will occur for any unhandled exception thrown within the application.











Redirect to a different page

Response.Redirect(url,bln)

  • The browser receives request from the webserver and browser does this. The user will not be able to find out the difference, except that it takes long to see something in the browser window. Basically the sends a http status code of 302 (object moved), which direct browser to look into the header for the new url.
  • Since the browser is directed to send another request to the new url, unnessary load on the server
  • Can be used to transfer to external pages that are not running on the same server.

Server.Transfer(url,bln)

  • If bln == true, all the form variables will also be transferred to the new url.
  • Transfer to the new page happens on the server side completely and browser is not involved and will not be aware.
  • For the above reason, the address in the browser doesn’t change
  • Can not be used to transfer to aspx pages running on the same server. Can not transfer to external websites.
  • Known issue: when bln is set to true.. click to open. The problem is, the _VIEWSTATE is also transferred to the new aspx page. This causes the ASP.NET machine authentication check (MAC) to assume that the ViewState of the new page has been tampered with. Solution is to set EnableViewStateMac to false in the new page.

Server.Execute(url,bln)

  • Works similar to Server.Transfer, only difference is, in Server.Transfer the current execution is terminated and the control is transferred to new page. In Server.Execute, it is like a function call. The control moves to the new page, and returns back to the called page.
  • If bln == true, all the form variables are transferred, so EnableViewStateMac to false in the new page
  • Once the call is returned back, the response stream of the new page is added to the response stream of the called page. To have more control, the response of the new page can be fetched into a TextWriter and can be placed where ever required. Sample code given below:
    System.Text.StringWriter sw = new System.Text.StringWriter();
    Server.Execute(“newPage.aspx”,sw);
    lbl.Text = sw.ToString();

Debuggers

1.   CorDBG – command-line debugger.  To use CorDbg, you must compile the original C# file using the /debug switch.

2.   DbgCLR – graphic debugger.  Visual Studio .NET uses the DbgCLR.


Monday, January 09, 2006

How to control access to specific pages based on authorization

At any point in the applicaiton, one can do the following...

IPrincipal usr = HttpContext.Current.User
If (usr.IsInRole("Admin") == false)
Response.Redirect("AccessDenied.aspx");
//usr.Identity.Name gives the logged in user id. If wanted
The above can be put in "Page_Load" event (or, OnLoad event) of the aspxs page to restrict control.

Configure Forms authentication

  • Set IIS security to 'Anonymous', which means all the requests come to the webserver with user id "IUSR_MachineName'.
  • Configure ASP.NET for Forms authentication in Web.Config
  • Set Authorization to deny="?" and allow users="*"
  • Create a FormsAuthetication Ticket in login page or control (Code Snippet 1 below)
  • Redirect the user to the requested page. If the user directly reached the login page, redirect the user to home page. Code in Snippet 1
  • Create Generic Principal object in global.asax file and put it in current context user. (Snippet 2)

SNIPPET: 1

using System.Web.Security;

private void Logon_Click(object sender, System.EventArgs e)
{

bool isAuthenticated = IsAuthenticated (txtUserName.Text, txtPassword.Text );
if (isAuthenticated == true )
{
// roles format "ManagerEmployeeSales"
// This makes it easy to store them in the authentication ticket

string roles = RetrieveRoles( txtUserName.Text, txtPassword.Text);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( intVersion,txtUserName.Text, DateTime.Now,DateTime.Now.AddMinutes(20),boolPersistent,roles) // Version is 1, persistent= fasle

string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);

Response.Cookies.Add(authCookie);
Response.Redirect( FormsAuthentication.GetRedirectUrl(
txtUserName.Text, false ));
}

}

SNIPPET 2:

using System.Web.Security;

using System.Security.Principal;

protected void Application_AuthenticateRequest(Object sender,
EventArgs e)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if(null == authCookie)
{
// There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch(Exception ex)
{
// Log exception details (omitted for simplicity)
return;
}
if (null == authTicket)
{
// Cookie failed to decrypt.
return;
}
string[] roles = authTicket.UserData.Split(new char[]{''});
// Create an Identity object
FormsIdentity id = new FormsIdentity( authTicket );
// This principal will flow throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, roles);
// Attach the new principal object to the current HttpContext
object
Context.User = principal;
}


Thursday, January 05, 2006

Overload Main function in C#

The following are the possible overloading of main function....
 
static void Main() {...}

static void Main(string[] args) {...}

static int Main() {...}

static int Main(string[] args) {...}