A recursive method for copying files and folders

by Emanuele 9/24/2008 10:53:00 AM

How to copy files and folders recursively in C#.

 

        private static void CopyRecursiveFiles(DirectoryInfo d,
            string DestinationDirectory, bool DeleteSource, bool CreateEmptyDir,string Extension)
        {
            // Get files.

            FileInfo[] fis = d.GetFiles("*." + Extension);
            // Create the destination directory, if CreateEmptyDir or contains files

            if ((fis.Length > 0) || (CreateEmptyDir))
                Directory.CreateDirectory(DestinationDirectory);
            foreach (FileInfo fi in fis)
            {
                fi.CopyTo(DestinationDirectory + "\\" + fi.Name);
                ScriviLog("File " + fi.Name + " copiato.");
                // Delete the origin file if DeleteSource
                if (DeleteSource)
                    fi.Delete();
            }
            // Recursive copy children dirs
            DirectoryInfo[] dis = d.GetDirectories();
            foreach (DirectoryInfo di in dis)
            {
                CopyRecursiveFiles(di, DestinationDirectory + "\\" + di.Name,
                                      DeleteSource, CreateEmptyDir,Extension);
            }
            // Delete the origin dir if DeleteSource
            if (DeleteSource)
                d.Delete();
        }

How to fill a string with a repeated character in C#

by Emanuele 6/24/2008 11:36:00 AM

How to format the string "abc" with "000000000abc" in c#?

It's very simple.
You can use the method PadLeft of the string object.
This method has two parameters.
The first is the number of times that the character will repeat.
The second is the Char value to repeat.

            string str;
            char charzero;
            str = "abc";
            charzero = '0';
            string Result = str.PadLeft(9, charzero);

 

 

Tags:

Asp.Net

Insert a Virtual Earth Map in your asp.net page - Part 3

by Emanuele 6/20/2008 3:30:00 PM

Another interesting thing in Microsoft Virtual Earth is calculate the route between two points.
The method for do this is GetDirections.
This method has two parameters.
The first is an array with the list of the points.
The second is a VERouteOptions object that specified some options.
The options is:

DistanceUnit: enum (Kilometer, Miles)
DrawRoute: if true, the function draws the road on the map
RouteColor: the color of the route
RouteMode: enum VERouteMode (Walking, Driving)
RouteOptimize: enum (MinimizeTime, MinimizeDistance)
SetBestMapView: if true, the map moves on your route
RouteCallback: the function invoked when the search is finished

Add this html code under the map (see the first or second article)

<input id="txtStart" type="text" name="txtStart" value="Piana del Sole, Roma, Lazio, Italy"/>
<input id="txtEnd" type="text" name="txtEnd" value="Piazza del Popolo (historical site), Rome, Lazio, Italy"/>
<input id="find" type="button" value="Find" name="GetRoute"
       onclick="GetRoute();"/>

Add this javascript function:

function GetRoute(){
  try{
    var options = new VERouteOptions();
    options.DrawRoute = true;
    options.SetBestMapView = true;
    options.DistanceUnit = VERouteDistanceUnit.Kilometer;
    map.GetDirections([document.getElementById('txtStart').value,
      document.getElementById('txtEnd').value], options);
  }
  catch(e)
  {
    alert(e.message);
  }
}

In the attachment you find the example page that I created.

VirtualEarth3.zip (1.13 kb)

Enjoy!

Insert a Virtual Earth Map in your asp.net page - Part 2

by Emanuele 6/20/2008 10:34:00 AM
In the first article, I describe how to insert and navigate a Virtual Earth Map in your asp.net page.
Here, I describe how to search a Point of Interest (POI) in your map.
The Map control includes a function called Find.
This function accepts ten parameters:

What: a string you want to search
Where: a string where you want to search
FindType: enum VEFindType (Now there is only value: Business)
ShapeLayer: a VEShapeLayer object where the pushpin are placed
StartIndex and NumberOfResults: parameters to manage the search results
ShowResults: if true, the pushpin are placed on the POI
CreateResults: if true, the pushpin are created
UseDefaultDisambiguation: if true, the default form is shown with much disambiguation in the first and second parameters
SetBestMapView: if true, the map moves automaticaly on the result
Callback: function called when the search are finished

In our example we use only the first and the second parameters.

Add the follow html code to the first example:

Search:
<input id="txtPOI" type="text" name="txtPOI"/>
<input id="txtAddress" type="text" name="txtAddress"/>
<input id="find" type="button" value="Find" name="find"
    onclick="Find();"/>

Add the follow javascript to the first example:

function Find()
{
    try
    {
        map.Find(
          document.getElementById('txtPOI').value,
          document.getElementById('txtAddress').value
        );
    }
    catch(e)
    {
        alert(e.message);
    }
}


Now, launch the page and try to search something.

In the attachment you find the example page that I created.

VirtualEarth2.zip (1.02 kb)

Insert a Virtual Earth Map in your asp.net page - Part 1

by Emanuele 6/19/2008 5:59:00 PM

To interface with Microsoft Virtual Earth we must use javascript, because the code and the controls to get the maps is client side.
With Microsoft Virtual Earth, we can see the map in much formats, but the thing that the others envy is the Bird View.
With Bird View we can see the road or the palace like a "bird" see it.

Insert the map

To see the map on own page, we create a div in html format:

<div id="VirtualMap" style="position:relative; width:600px; height:600px;"></div>

If we miss the position attribute the map is not viewed correctly.

After this, we put in the tag <head> the follow javascript script:

<script type="text/javascript" src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1"></script>

The parameter "v" is required and it is the version of the Virtual Earth Map Control.

Under the previous script we must put other script, that create the map control in the map container.

      <script type="text/javascript">
         var map = null;

         var StartPoint = new VELatLong(45.39844997630408, 10.546875000000014);

         var pinPoint = null;
         var pinPixel = null;
                  
         function GetMap()
         {
            map = new VEMap('VirtualMap');
            map.LoadMap(StartPoint, 4, VEMapStyle.Road, false, VEMapMode.Mode2D, true, 4);
         }

         function getInfo()
         {
            var center = map.GetCenter();

            info  = "Zoom level:\t" + map.GetZoomLevel() + "\n";
            info += "Latitude:\t"   + center.Latitude    + "\n";
            info += "Longitude:\t"  + center.Longitude;

            alert(info);
         }
      </script>


Replace the tag body with this tag: <body onload="GetMap();">

We can change all parameters in the function LoadMap.
The StartPoint class is the coordinates where the map starts when is loaded.
The second parameter is the zoom level: 1 to 19.
The third parameter is the style of the map. (Road,Aerial,Hybrid,Oblique,Birdseye,BirdseyeHybrid)
The fourth parameter indicates if the user can navigate in the map or not.
The fifth parameter is the visualization mode of the map. (2D,3D).
The sixth parameter is the boolen that indicates if the navigation control are visible or not.
The seventh parameter is the number of "square" that the control map load until you navigate on the map.

Follow this instructions and view the page on your browser.

 

In the attachment you find the example page.

VirtualEarth1.zip (879.00 bytes)

Shortcut to Start and Stop MsSqlServer Service

by Emanuele 6/18/2008 12:13:00 PM
Very frequently I start and stop default istance of Sql Server, to deploy new stuff on the server or on my local machine.
I created two batch files on my desktop to speed up this operation.

First of all we test if the command line script run correctly or not.

Click Start -> Run -> type "cmd" to start command prompt.


Start SqlServer Default Istance

Type "net start mssqlserver" and press Enter.



Stop SqlServer Default Istance

Type "net stop mssqlserver" and press Enter.




If two commands run correctly, we can go on to create the batch files.

p.s. If you use Windows Vista, you must launch the commands with administrator privileges.


Create the shortcuts

Right click on desktop and select New -> Text Document.
Rename the file with "start sqlserver.bat"
Put the command "net start mssqlserver" in the file and save.

Right click on desktop and select New -> Text Document.
Rename the file with "stop sqlserver.bat"
Put the command "net stop mssqlserver" in the file and save.

If you use Windows Vista, right click and select "Run as administrator".

IIF equivalent in C#

by Emanuele 6/17/2008 3:32:00 PM
How many times did you write this code?

if (a == 1)
{
    a = 1;
}
else
{
    a = a - 1;
}

I say too much.
In Vb or in VB.net there is an operator called iif that do this in one row.
Is there IIF equivalent in C#?
Yes!!!

a==1 ? a=1 : a=a - 1;

You can use the operator ?: to obtain this goal.
The syntax is very simple:

<bool condition> ? <true value> : <false value>;


Enjoy!

String Format Online Utility

by Emanuele 6/13/2008 10:16:00 AM

Until I surf over internet, I've found an incredible tool for C# and Vb.Net developer.
If you don't remember (like me) all possible formatting options, you found this utility very usefull.
It's a Silverlight project, indeed you must install the silverlight plugin on your browser (if you haven't).
Follow the instructions on the utility and copy the sample code with your pretty Ctrl + C.
This utility write the code in C#, but you can translate it with this other tool translateyourcode.com



Tags:

Asp.Net

How to change default view source editor in IE

by Emanuele 5/19/2008 9:10:00 PM

The default program that shows the source code of webpage, when you are using Internet Explorer is Notepad.
If you want to change this defautl application, one way is edit the system registry.
I tested this solution with Windows Vista and IE 7, WinXp and IE6 and WinXp and IE7.

 
Run REGEDIT, follow the following directions to the proper key.

HKEY_LOCAL_MACHINE -- > Software --> Microsoft --> Internet Explorer

Create the key "View Source Editor" and then create the key "Editor Name".
Modif Default Value of the key "Editor Name" with the path of your Html editor and click Ok.

Restart Internet Explorer and try to choose View -> Source from menu. 

Tags:

Windows Xp

How to change the pattern layout of Log4net

by Emanuele 5/2/2008 4:15:00 PM

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

 

Tha't all folks!!!

Tags:

How to use Log4net in your Web Services

by Emanuele 4/28/2008 3:29:00 PM

You can use Log4net to log your web services activities.
The implementation is the same of web application.
There are two ways to implement the initialization function in your web services.
The first solution is put your code into the Global.asax.
The second solution is put your code into the code behind file of Global.asax.

First of all add Global.asax file in your solution. Right click on the main project and select "Add New Item". In the new window, select "Global Application Class" and click Ok.

Open the Global.asax and put this code:

<%@ Application Language="C#" %>
<script runat="server">
     private void Application_Start(Object sender, EventArgs e)
     {
          log4net.Config.DOMConfigurator.Configure();
     }
</script>

If you want use the code behind file, open the Global.asax.cs file and put this code:

namespace MyWebServices
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(Object sender, EventArgs e)
        {
            log4net.Config.DOMConfigurator.Configure();
        }
    }
}

The Application_Start method is invoked when the Web Service is run for the first time (or reloaded).

If you want know to configure Log4net, see the relative posts on this site.

 

Tags:

Asp.Net

Convert Vb.Net to C# and C# to Vb.net with www.translateyourcode.com

by Emanuele 4/22/2008 9:17:00 PM

In these last sad days, I developed a tool for developers that work with C# and Vb.net simultaneously.
I used some Sharpdevelop classes, to create a web application that convert Vb.net code to C# code and C# code to Vb.net code.
I haven't spent much time for graphics and user experience, but it's the result that it's important.

It's easy to use.
Just paste your code and press "Translate" in the right bottom.
In the next days, I add some functions to my new tool.
I hope you like it.

It's all.

www.translateyourcode.com 

Fibonacci Sequence

by Emanuele 4/15/2008 1:37:00 PM

For a strange reason that I don't know, someone ask to me to implement in a financial application the Fibonacci Sequence.
First of all, I don't know this mathematical role, because I hate this subject!
I seek some information about Fibonacci and this role over Internet and the best information that I found is on wikipedia.
There is a simple way to find and display the number of Fibonacci sequence in C#.

Here, I write the function in C#:

        class Program
        {
            static double FibonacciSequence(double x)
            {
                if (x <= 1) return 1;
                return FibonacciSequence(x - 1) + FibonacciSequence(x - 2);
        }

        static void Main()
        {
                for (int i = 0; i <= 40; i++)
                {
                    Console.WriteLine("Fibonacci number: {0}", FibonacciSequence(i));
                }
                Console.WriteLine("Finished.");
                Console.ReadKey();
            }
        }

and in Vb.net:

    Class Program
        Private Shared Function FibonacciSequence(ByVal x As Double) As Double
            If x <= 1 Then
                Return 1
            End If
            Return FibonacciSequence(x - 1) + FibonacciSequence(x - 2)
        End Function
    
        Private Shared Sub Main()
            For i As Integer = 0 To 40
                Console.WriteLine("Fibonacci number: {0}", FibonacciSequence(i))
            Next
            Console.WriteLine("Finished.")
            Console.ReadKey()
        End Sub
    End Class

 

Tags:

Open Source

Download xml file from web services

by Emanuele 4/3/2008 11:55:00 AM
Sometimes, some network configurations don't allow to access directly to web services.
One way is download the xml file that xml web services returns and load that in a dataset.
I wrote a small function to download xml file from web services.
It's simple, but it's a good starting point to develop other things.


        public bool DownloadXmlFromService()
        {
            string result = "";
            try
            {
                WebProxy proxy = new WebProxy(" proxy address ", port number );
                proxy.Credentials = new NetworkCredential( user id ,  password, domain );
                WebRequest request = WebRequest.Create("http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry?CountryName=Italy");
                request.Proxy = proxy;
                
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                System.IO.Stream stream = response.GetResponseStream();
                System.Text.Encoding ec = System.Text.Encoding.GetEncoding("utf-8");
                System.IO.StreamReader reader = new System.IO.StreamReader(stream, ec);
                char [] chars = new Char[256];
                int count = reader.Read(chars, 0, 256);
                while(count > 0)
                {
                    string str = new String(chars, 0, 256);
                    result = result + str;
                    count = reader.Read(chars, 0, 256);
                }
                response.Close();
                stream.Close();
                reader.Close();
                
                result = result.Replace("&lt;","<");
                result = result.Replace("&gt;",">");
                
                if (File.Exists("temp.xml"))
                {
                    File.Delete("temp.xml");
                }
                
                System.IO.StreamWriter ToFile = new StreamWriter("temp.xml");
                ToFile.Write(result);
                ToFile.Close();
            }
            catch(Exception exp)
            {
                string str = exp.Message;
                return false;
            }
            
            return true;
        }

How to install Windows Server 2008 on VmWare

by Emanuele 3/17/2008 11:55:00 PM

In these days, I wrote a document to explain how to install Windows Server 2008 on VmWare 6.0.
I don't explain the new features of Windows Server 2008, but I say how to configure VmWare 6.0 to work with Windows Server 2008.
The guide is very simple and it contains some screenshots.
I upload two files: a pdf file and a xps file.
Choose your favourite format.

How to Install Server 2008.pdf (1.72 mb)

How to Install Server 2008.xps (4.54 mb)

Encrypt the ViewState

by Emanuele 3/13/2008 7:21:00 PM

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 2/23/2008 2:26:00 PM

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.

How to measure elapsed time in c# with StopWatch

by Emanuele 2/20/2008 9:54:00 AM

A 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();
        }

 

You can find an example application in the attached file.

Sort items in a combobox or dropdownlist

by Emanuele 1/29/2008 5:03:00 PM

The DropDownList control does not expose a sort method to sort items by either the value or the displayed text.

If you pull the values from database, it's very simple because you just add the ORDER BY clause in the SQL SELECT statement.
But if you can't access on the database to modify the stored procedure or view, the solution is to load your data into an array and associate this to the combobox or dropdownlist.

With these simple lines, you can do it.

        private void btnSort_Click(object sender, EventArgs e)
        {
            ArrayList cboItems = new ArrayList();

            foreach (string item in cboCities.Items)
            {
                cboItems.Add(item);
                cboItems.TrimToSize();
            }

            cboItems.Sort();
            cboCities.Items.Clear();
            string[] Items = new string[cboItems.Count];

            cboItems.CopyTo(Items);
            cboCities.Items.AddRange(Items);
        }

 With some little fix, you can switch from combobox to dropdownlist.
On the link below you can find the source code with an example.

SortedList.zip (32.22 kb)

How to determine which version of .Net Framework are installed

by Emanuele 1/10/2008 8:55:00 PM
The easiest way to determine which versions of the .NET Framework are installed on your Pc or on your Server is to navigate the %systemroot%\Microsoft.NET\Framework folder.
You can paste the listed address for the Framework folder into a Windows Explorer address bar to navigate to the Framework folder. The three released versions of the .NET Framework are contained in the following folders:
v1.0.3705
v1.1.4322
v2.0.50727

To determine which versions of the .NET Framework are installed on a computer, follow these steps:
1. Open any one of the folders in the previous list, and then locate the Mscorlib.dll file.
2. Right-click the file, and then click Properties.
3. Click the Version tab, and then note the file version.
4. Use the previous list to determine which version of the .NET Framework is installed on the computer, and then click OK.


Repeat these steps for each version of the .NET Framework on the computer.


Bookmark your code

by Emanuele 1/9/2008 11:47:00 AM

When your write or read the code, sometimes you need to jump from file to file more times.
Everytime you spent a lot of time to find the line that you leave just a minute ago.
With the Visual Studio bookmark you resolve this problem.
To insert a bookmark, press Ctrl+K, Ctrl+K.
For navigation, press Ctrl+K, Ctrl+N to navigate to the next bookmark,Ctrl+K, CTRL+P for the previous bookmark.
It's easy, but it's useful to save time. Laughing

 


Tags:

Asp.Net

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

by Emanuele 12/21/2007 10:38:00 AM

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

Tags: ,

Asp.Net

A funny flash animation - "Animator vs Animation II"

by Emanuele 12/18/2007 12:30:00 AM

This evening my friend send me this flash animation.
I smile a lot!!! Smile
I hope you like it

Create a shortcut to clear memory

by Emanuele 12/17/2007 5:51:00 PM

Sometimes, when you work all day without restar your pc, it appears much slowly.
The only solution is a reboot of your system, but we have never time for this!!!
To remedy this problem simply create a shortcut on your desktop with this settings.

  1.  Create a new shortcut on your desktop (Righ click -> New -> Shortcut)
  2. Insert this string %windir%\system32\rundll32.exe advapi32.dll,ProcessIdleTasks in the textbox
  3. Insert the name of shortcut, like "Clear memory" and click Ok
  4. Test the shortcut

Simply, fast but usefull.

 

Disable message popup alert after windows update

by Emanuele 12/12/2007 10:53:00 AM

Sometimes, after the Windows Update a annoying message popup appears every a few minutes.

Especially it appears when you do something important, it takes focus and your window goes behind.
If you want to disable this reminder follow the following steps:
  1. Click Start -> Run
  2. Enter “gpedit.msc”
  3. Go to Local Computer Policy -> Computer Configuration -> Administrative Templates -> Windows Components -> Windows Update
  4. Double-click on “No auto-restart for scheduled Automatic Update installation”
  5. Set to “Enabled”
  6. Reboot the computer

 

Disable_restart_with_scheduled_installations.gif (50.28 kb)

This solution doesn't run under Windows Xp Home Edition because in this version of Windows, doesn't exist the Group Policies utility.
There is a regedit hack.

  1. Click Start -> Run
  2. Enter “regedit.exe”
  3. Search HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU
  4. Create a DWORD called NoAutoRebootWithLoggedOnUsers 
  5. Set to 1
  6. Reboot the computer
Otherwise download this and hack the registry.



Powered by BlogEngine.NET 1.3.1.0
Theme by Emanuele Bartolesi

About the author

Name of author Emanuele Bartolesi
I'm a senior developer and project manager.

Contact me Contact me

Calendar

<<  December 2008  >>
MoTuWeThFrSaSu
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Disclaimer

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

© Copyright 2008

Sign in

Download Day 2008