Simple way to implement Url Rewrite Class

By Emanuele Bartolesi at April 05, 2010 17:50
Filed Under: Asp.net, C#

There are many ways to implement an url rewrite system in your web application.
This post shows the easiest way.

First, create a page called "default.aspx" with a Panel called "pnlMain".
In the page load event insert this code:

 

Code Snippet
  1. //Test the different page
  2. if (Request.QueryString["id"] == "1")
  3.     pnlMain.Controls.Add(new LiteralControl("<b>Login</b>"));
  4. else if (Request.QueryString["id"] == "2")
  5.     pnlMain.Controls.Add(new LiteralControl("<b>Content</b>"));
  6. else
  7.     pnlMain.Controls.Add(new LiteralControl("<b>Home Page</b>"));

 

Add a global.asax file, create the Application_BeginRequest event and paste the follow code:

 

Code Snippet
  1. void Application_BeginRequest(object sender, EventArgs e)
  2. {
  3.     string originalUrl = Request.Url.ToString();
  4.  
  5.     if (originalUrl.Contains("Login"))
  6.     {
  7.         Context.RewritePath("default.aspx?id=1");
  8.     }
  9.     else if (originalUrl.Contains("Content"))
  10.     {
  11.         Context.RewritePath("default.aspx?id=2");
  12.     }
  13.     else
  14.     {
  15.         Context.RewritePath("default.aspx?id=3");
  16.     }
  17. }

 

Now you can launch your application in Debug mode. Add in the address bar the string "Login" and press Enter. You can try with another value "Content".

This example is very simple but it is a good way to understand how url rewrite class works.

 

How to get string from Http Request

By Emanuele Bartolesi at February 24, 2010 18:05
Filed Under: Asp.net, C#, WebServices

This HOW TO describes one of the various built-in methods .NET provides to use XML returned by a web service.
The simplest way to view the returned data is to get the response stream and put it into a string. This is especially handy for debugging. The following code gets a web page and put the the contents in a string.

        public static string GetPageAsString(string address)
        {
            string result = string.Empty;

            // Create the web request 
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
           
            // Get the web response 
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            // Get the stream from response
            StreamReader reader = new StreamReader(response.GetResponseStream());

            // Read the whole contents and return as a string 
            result = reader.ReadToEnd();

            reader.Dispose();
            reader = null;

            request = null;

            return result;
        }

To call this method write this code:

 GetPageAsString("http://weather.yahooapis.com/forecastrss?p=ITXX0042&u=f");


Here there is the complete sourcecode.

GetXmlFromWebIntoString.rar (37.00 kb)

Web Garden on IIS 7

By Emanuele Bartolesi at June 13, 2009 16:53
Filed Under: Asp.net, IIS
Each Application Pool runs with a single worker process (w3wp.exe).
From IIS 6, we can assign multiple worker process on a single application pool. This method is called Web Garden.
Many worker process can provide better performance and response time to your application.
There are some restriction to use web garden for your application. You must use "out proc" for Session Mode and "Session State Server" or "Sql-server session state".
If you use "in proc" for Session Mode your application not work correctly.

To create a web garden, right click on the Application Pool -> Advance Setting and set the value of Maximum Worker Process under the Process Model section.

How to enable http compression on IIS 6.0

By Emanuele Bartolesi at March 20, 2009 08:33
Filed Under: Asp.net, IIS

With this simple eight steps, you can enable the http compression on IIS 6.
It is useful if your application has very hard pages, but the compression requires much cpu usage.

1. Open a command prompt, type net stop iisadmin and press ENTER.

2. Type cd c:\inetpub\adminscripts and press ENTER.

3. Type CSCRIPT.EXE ADSUTIL.VBS SET W3Svc/Filters/Compression/GZIP/HcScriptFileExtensions "asp" "dll" "exe" "aspx" "asmx" and press ENTER.

4. Type CSCRIPT.EXE ADSUTIL.VBS SET W3Svc/Filters/Compression/DEFLATE/HcScriptFileExtensions "asp" "dll" "exe" "aspx" "asmx" and press ENTER.

5. Type CSCRIPT.EXE ADSUTIL.VBS SET W3Svc/Filters/Compression/GZIP/HcDynamicCompressionLevel "9" and press ENTER.

6. Type CSCRIPT.EXE ADSUTIL.VBS SET W3Svc/Filters/Compression/DEFLATE/HcDynamicCompressionLevel "9" and press ENTER.

7. Type cscript.exe adsutil.vbs set W3SVC/ID/Root/WebServiceTG/DoDynamicCompression True and press ENTER. (ID is the identifier of the application that you can find on the coloumn Identifier of IIS Manager)

8. Type net start w3svc and press ENTER.

How to measure elapsed time in C# with StopWatch

By Emanuele Bartolesi at March 20, 2009 04:50
Filed Under: Asp.net, C#

StopWatch class can measure elapsed time for one interval.
We can use for measuring performance of the new code blocks or algorithms. Use IsRunning method to determine the state of StopWatch object.
Use Start method to begin measuring elapsed time, and Stop method to stop measuring elapsed time.

{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
textBox1.Text = DateTime.Now.TimeOfDay.ToString();
Application.DoEvents();

// Perform a long process
Thread.Sleep(34564);

stopwatch.Stop();
textBox2.Text = DateTime.Now.TimeOfDay.ToString();
textBox3.Text = stopwatch.Elapsed.Milliseconds.ToString();
Application.DoEvents();
}

How to configure the pattern layout of Log4net

By Emanuele Bartolesi at March 20, 2009 04:48
Filed Under: Asp.net, Log, C#

With Log4net, you can configure the layout of the string that you want to log.
It's very simple, because you can change the pattern layout string in few seconds and without compiling the application.
You don't compile everytime change the pattern layout string, because it is in the application config.
For web application it is in the web.config file and for desktop application it is in the app.config.
Each pattern member starts with % and is followeb by the name of pattern member.
You can change the width, padding, left and right justification for each pattern member.

Sometimes, I use this layout pattern: %type %file %line %method %location %class %C %F %L %l %M %n , but below I explain every single member in order to you can create your pattern layout.

a or appdomain Friendly name of appdomain
c or logger Used to output the logger of the logging event
C or class or type The fully type name of the caller class
d or date The date of logging event in the local time zone
exception The exception
F or file The file name where the logging request was issued
identity or u The active user
l or location Location information of the caller
L or line The line number from where the logging request was issued
level or p The level of the logging event
m or message Application supplied message associated with the logging event
M or method The method name where the logging request was issued
n or newline Line separator
r or timestamp The timestamp when the logging request was issued
t or thread The name of thread that generated the logging event
username or w The Windows Identity for active user

Encrypt the ViewState

By Emanuele Bartolesi at March 20, 2009 04:45
Filed Under: Asp.net, C#

By default, the ViewState encryption is disabled in the web applications.
So it is recommended not send private data through Viewstate at least that you are not using SSL.
There are two ways to encrypt your ViewState:
1. Encrypt ViewState in every Page
2. Encrypt ViewState in web.config for all pages in your applications In the first case, add the attribute in the directive <%@Page ViewStateEncryptionMode="Always" %> in your single page.
In the second case, add the attribute viewSateEncryptionMode="Always" in your web.config.
Then add the algorithm of decryption in your web.config.
There are much key of decryption, but the key AES is the best for performance and for security.

See the example:

<configuration>
<system.web>
<machineKey decryptionKey="AutoGenerate,IsolateApps" decryption="AES" />
</system.web>
</configuration>

For more informations go to http://msdn2.microsoft.com/en-us/library/ms998288.aspx

Log4net: use Sql Server to log your application events

By Emanuele Bartolesi at March 19, 2009 06:42
Filed Under: Asp.net, Log
In the previous article on the Log4net configuration, I explain how to configure Log4net with the file appender.
In this article I explain how to configure Log4net with the Sql Server appender.
It is very similar, but we see in detail the new configuration.

Download

You can download the latest version of Log4net from this location.

Add reference to your solution

In Visual Studio 2005 select Project -> Add Reference.
In the tab Browse, find and select the dll Log4net.dll in your local folder.

Modify web.config

Into web.config file add this code into the section Configuration->Configsections:

<configSections>
    <section name="log4net"
      type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> 
</configSections>
<log4net>
  <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
    <bufferSize value="100" />
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <connectionString value="server=localhost; uid=; pwd=; database=" />
    <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES
       (@log_date, @thread, @log_level, @logger, @message, @exception)" />
    <parameter>
      <parameterName value="@log_date" />
      <dbType value="DateTime" />
      <layout type="log4net.Layout.RawTimeStampLayout" />
    </parameter>
    <parameter>
      <parameterName value="@thread" />
      <dbType value="String" />
      <size value="32" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%t" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@log_level" />
      <dbType value="String" />
      <size value="512" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%p" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@logger" />
      <dbType value="String" />
      <size value="512" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%c" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@message" />
      <dbType value="String" />
      <size value="4000" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%m" />
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@exception" />
      <dbType value="String" />
      <size value="2000" />
      <layout type="log4net.Layout.ExceptionLayout" />
    </parameter>
  </appender>
  <root>
    <level value="DEBUG" />
    <appender-ref ref="ADONetAppender" />
  </root>
</log4net>

Change the connectionstring parameters to connect to your database.

Create the table

In your database, create the table to use Log4net. 

CREATE TABLE [dbo].[Log](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Date] [datetime] NULL,
    [Thread] [varchar](255) NULL,
    [Level] [varchar](50) NULL,
    [Logger] [varchar](255) NULL,
    [Message] [varchar](4000) NULL,
    [Exception] [varchar](2000) NULL
) ON [PRIMARY]

Edit the Global.asax file

In the event "Application_Start" of the file Global.asax add this line:

log4net.Config.XmlConfigurator.Configure();

Begin to log

In every page you want to log something, add the static variable like below:
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

This class has 5 levels of severity to log the operations:

log.Debug("log something at this level")
log.Info("log something at this level")
log.Warn("log something at this level");
log.Error("log something at this level");
log.Fatal("log something at this level");

You find the official documentation at this link.

If you want to log on the file system, read the previous article on Log4net.

Log4net: simple way to use in your Asp.net application

By Emanuele Bartolesi at March 19, 2009 06:22
Filed Under: Asp.net, Log

Introduction

Log the actions of your applications is very important especially when you develop new features or develop very difficult logical business.
But it is also important when users use your applications to understand the critical issues or problems.
To implement quickly the log operations Apache developed an opensource library for .Net developers.

Download

You can download the latest version of Log4net from this location.

Add reference to your solution

In Visual Studio 2005/2008 select Project -> Add Reference.
In the tab Browse, find and select the dll Log4net.dll in your local folder.

Modify web.config

Into web.config file add this code into the section Configuration->Configsections:

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

Yet, add the section:

<log4net>

<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">

<file value="c:\temp\web.log" />

<appendToFile value="true" />

<maximumFileSize value="1024KB" />

<maxSizeRollBackups value="10" />

<layout type="log4net.Layout.PatternLayout">

<conversionPattern value="%date %level %logger - %message%newline" />

</layout>

</appender>

<root>

<level value="DEBUG" />

<appender-ref ref="RollingFile" />

</root>

</log4net>

 In this configuration will create a log file into the folder "c:\temp\" until its size is 1024Kb.
After this size the name of file will be web.log.1 until 10.
At this link you can find another configurations.

Global.asax

In the event "Application_Start" of the file Global.asax add this line:

log4net.Config.XmlConfigurator.Configure();

Begin to log

In every page you want to log something, add the static variable like below:

private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

This class has 5 levels of severity to log the operations:

log.Debug("log something at this level")
log.Info("log something at this level")
log.Warn("log something at this level");
log.Error("log something at this level");
log.Fatal("log something at this level");

Simple and fast to use.

You find the official documentation at this link.

About me

I will also give you some useful tips, based on the modest wisdom gained during the years that I've worked as a developer and project manager.

Widget

Ohloh profile for Emanuele Bartolesi

 

Wakoopa

Software tracking

 

Software tracking

from Amazon



hacker emblem



Scarica il pdf di Game
Rivista Game di videogiochi
Trucchi videogiochi