Simple Async HTTP Request

by Manuel 7/24/2008 8:25:00 AM

Since .NET Framework 2.0 there is a very easy way to perform an asynchronous HTTP request and retrieve the result as a string.
The System.Net.WebClient class provides methods and events to handle this task in a very convenient way:


using System.Net; 

private void Button_Click(object sender, RoutedEventArgs e)
{
   string topic=this.SearchTextBox.Text;
   string url = "http://yourserver.com";
   WebClient client = new WebClient();
   client.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
   client.DownloadStringAsync(
new Uri(url));
}

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
   if (e.Error == null)
   {
      string result = e.Result;
   }
}

Currently rated 3.0 by 2 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C# | ASP.NET

Switching the current asp.net user account programmatically

by Manuel 12/13/2007 9:51:00 AM

Sometimes it is necessary to change the user under whose account asp.net runs to execute a special method. This could be the case e.g. if you want to access an ADS with a local asp.net user and you get an error message "invalid username or password" (there is the possibility to pass a username and passwort, but that didn't work for me).

The usage of the class below is very simple:

...
Impersonation
imp = new Impersonation();
imp.ImpersonateValidUser(
"username", "domain", "password");
//execute your work here
imp.UndoImpersonation();
....




using
System;
using System.Security.Principal;
using System.Runtime.InteropServices;

namespace
Security
{

   public class Impersonation
   
{

      
public const int LOGON32_LOGON_INTERACTIVE = 2;
      
public const int LOGON32_PROVIDER_DEFAULT = 0;
      
WindowsImpersonationContext impersonationContext;

      [DllImport("advapi32.dll")]
      
public static extern int LogonUserA(String lpszUserName, 
         
String lpszDomain,
         
String lpszPassword,
         
int dwLogonType, 
         
int dwLogonProvider,
         
ref IntPtr phToken);
      
      [
DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
      
public static extern int DuplicateToken(IntPtr hToken, 
         
int impersonationLevel, 
         
ref IntPtr hNewToken);

 

      [
DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
      
public static extern bool RevertToSelf();

      [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
      
public static extern bool CloseHandle(IntPtr handle);

      public bool ImpersonateValidUser(String userName, String domain, String password)
      {
         
WindowsIdentity tempWindowsIdentity;
         
IntPtr token = IntPtr.Zero;
         
IntPtr tokenDuplicate = IntPtr.Zero;
         
         
if(RevertToSelf())
         {
            
if(LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, 
               LOGON32_PROVIDER_DEFAULT,
ref token) != 0)
            {
               
if(DuplicateToken(token, 2, ref tokenDuplicate) != 0) 
               {
                  tempWindowsIdentity =
new WindowsIdentity(tokenDuplicate);
                  impersonationContext = tempWindowsIdentity.Impersonate();
                  
if (impersonationContext != null)
                  {
                     CloseHandle(token);
                     CloseHandle(tokenDuplicate);
                     
return true;
                  }
               }
            } 
         }
         if(token!= IntPtr.Zero) CloseHandle(token);
         
if(tokenDuplicate!=IntPtr.Zero) CloseHandle(tokenDuplicate);
         
return false;
      
}

      public void UndoImpersonation()
      {
         impersonationContext.Undo();
      }

   }
}

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

C# | ASP.NET

How to provide data global during a request (or where is the request context?) (ASP.NET)

by Manuel 12/13/2007 9:40:00 AM

You can save your data during a HttpRequest by passing it to System.Web.HttpContext.Current.Items[itemKey].
Objects stored in this Collection will be available during the whole lifecycle of the HttpRequest.

Example of usage:

System.Web.HttpContext.Current.Items["reloadCount"] = 5;

int reloadCount = (int) System.Web.HttpContext.Current.Items["reloadCount"];

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C# | ASP.NET

How to read and write a DataSet from and to XML (C#)

by Manuel 12/13/2007 9:38:00 AM
private DataSet ReadDataSet(string dataPath)
{
   DataSet ds = new DataSet();
   ds.ReadXml(dataPath,
XmlReadMode.ReadSchema);
   return ds;
}

private void WriteDataSet(DataSet ds, string path)
{
   ds.WriteXml(path,
XmlWriteMode.WriteSchema);
}

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C# | ASP.NET

How to convert a comma seperated file (.csv) into a dataset (C#)

by Manuel 12/13/2007 9:35:00 AM
public DataSet GetCSVFile( string fileName)
{
     string pathName = System.IO. Path .GetDirectoryName(fileName);
     string file = System.IO. Path .GetFileName(fileName);
     OleDbConnection excelConnection = new OleDbConnection
     (@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ pathName + ";Extended Properties=Text;");
     OleDbCommandexcelCommand = newOleDbCommand(@"SELECT * FROM "+ file, excelConnection);
     OleDbDataAdapterexcelAdapter = newOleDbDataAdapter(excelCommand);
     excelConnection.Open();
     DataSetds = newDataSet();
     excelAdapter.Fill(ds);
     excelConnection.Close();
     return ds;
}

Currently rated 3.8 by 8 people

  • Currently 3.75/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C# | ASP.NET

global.asax events

by Manuel 12/6/2007 2:32:00 AM


HttpApplication Events:

Application_AcquireRequestState
Occurs when ASP.NET acquires the current state (for example, session state) that is associated with the current request. 

Application_AuthenticateRequest
Occurs when a security module has established the identity of the user. 

Application_AuthorizeRequest
Occurs when a security module has verified user authorization. 

Application_BeginRequest
Occurs as the first event in the HTTP pipeline chain of execution when ASP.NET responds to a request. 

Application_Disposed
Adds an event handler to listen to the Disposed event on the application. 

Application_EndRequest
Occurs as the last event in the HTTP pipeline chain of execution when ASP.NET responds to a request. 

Application_Error
Occurs when an unhandled exception is thrown. 

Application_PostAcquireRequestState
Occurs when the request state (for example, session state) that is associated with the current request has been obtained. 

Application_PostAuthenticateRequest
Occurs when a security module has established the identity of the user. 

Application_PostAuthorizeRequest
Occurs when the user for the current request has been authorized. 

Application_PostMapRequestHandler
Occurs when ASP.NET has mapped the current request to the appropriate event handler. 

Application_PostReleaseRequestState
Occurs when ASP.NET has completed executing all request event handlers and the request state data has been stored. 

Application_PostRequestHandlerExecute
Occurs when the ASP.NET event handler (for example, a page or an XML Web service) finishes execution. 

Application_PostResolveRequestCache
Occurs when ASP.NET bypasses execution of the current event handler and allows a caching module to serve a request from the cache. 

Application_PostUpdateRequestCache
Occurs when ASP.NET completes updating caching modules and storing responses that are used to serve subsequent requests from the cache. 

Application_PreRequestHandlerExecute
Occurs just before ASP.NET begins executing an event handler (for example, a page or an XML Web service). 

Application_PreSendRequestContent
Occurs just before ASP.NET sends content to the client. 

Application_PreSendRequestHeaders
Occurs just before ASP.NET sends HTTP headers to the client. 

Application_ReleaseRequestState
Occurs after ASP.NET finishes executing all request event handlers. This event causes state modules to save the current state data. 

Application_ResolveRequestCache
Occurs when ASP.NET completes an authorization event to let the caching modules serve requests from the cache, bypassing execution of the event handler (for example, a page or an XML Web service). 

Application_UpdateRequestCache
Occurs when ASP.NET finishes executing an event handler in order to let caching modules store responses that will be used to serve subsequent requests from the cache. 

Application_Init
This method occurs after _start and is used for initializing code.

Application_Start
As with traditional ASP, used to set up an application environment and only called when the application first starts.

Application_End
Again, like classic ASP, used to clean up variables and memory when an application ends.

Session Events:

Session_Start
As with classic ASP, this event is triggered when any new user accesses the web site.

Session_End
As with classic ASP, this event is triggered when a user's session times out or ends. Note this can be 20 mins (the default session timeout value) after the user actually leaves the site.

Profile Events:

Profile_MigrateAnonymous
Occurs when the anonymous user for a profile logs in.

Passport Events:

PassportAuthentication_OnAuthenticate
Raised during authentication. This is a Global.asax event that must be named PassportAuthentication_OnAuthenticate.
 

Possibly more events defined in other HttpModules like:

System.Web.Caching.OutputCacheModule
System.Web.SessionState.SessionStateModule
System.Web.Security.WindowsAuthentication
System.Web.Security.FormsAuthenticationModule
System.Web.Security.PassportAuthenticationModule
System.Web.Security.UrlAuthorizationModule
System.Web.Security.FileAuthorizationModule
System.Web.Profile.ProfileModule

Currently rated 4.6 by 14 people

  • Currently 4.642857/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C# | ASP.NET

Powered by BlogEngine.NET 1.2.0.0
Theme by Mads Kristensen

About the author

Name of author Author name
Something about me and what I do.

E-mail me Send mail

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012

Sign in