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)

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

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;
        }

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

Convert Int value to Hex value and vice versa in C#

by Emanuele 12/9/2007 5:00:00 PM

This morning I created another function to convert something in other something.
This time this function convert Int Value to Hex Value and Hex Value to Int Value.
You find a demo at this link.

    protected void CmdConvert1(object sender, EventArgs e)
    {
        //set the default value
        uint uiDecimal = 0;

        try
        {
            // Convert text string to integer
            uiDecimal = Convert.ToUInt32(TxtText1.Text);
        }

        catch (OverflowException exception)
        {
            // Show overflow message and return
            TxtHex1.Text = "Overflow";
            return;
        }

        // Format hex value and show in another textbox
        TxtHex1.Text = String.Format("{0:x2}", uiDecimal);
    }
   
    protected void CmdConvert2(object sender, EventArgs e)
    {
        uint uiHex = 0;

        try
        {
            // Convert hex value to int
            uiHex = Convert.ToUInt32(TxtHex2.Text, 16);
        }

        catch (OverflowException exception)
        {
            // Show overflow message and return
            TxtText2.Text = "Overflow";
            return;
        }

        // Format it and show as a string
        TxtText2.Text = uiHex.ToString();
    }

Convert Arabic numeral to Roman numerals in C#

by Emanuele 12/8/2007 4:33:00 PM

In these days I created a function that converts an arabic numeral to roman numerals.
The code is simple.
You can find the demo at this link.

     public String ArabicToRoman(int nr)
    {
        String sArabicToRoman = "";
        try
        {
            if (nr >= 889)
            {
                sArabicToRoman = "M" + ArabicToRoman(nr - 1000);
            }
            else if (nr >= 389)
            {
                sArabicToRoman = "D" + ArabicToRoman((nr - 500));
            }
            else if (nr >= 89)
            {
                sArabicToRoman = "C" + ArabicToRoman((nr - 100));
            }
            else if (nr >= 39)
            {
                sArabicToRoman = "L" + ArabicToRoman((nr - 50));
            }
            else if (nr >= 9)
            {
                sArabicToRoman = "X" + ArabicToRoman((nr - 10));
            }
            else if (nr >= 4)
            {
                sArabicToRoman = "V" + ArabicToRoman((nr - 5));
            }
            else if (nr >= 1)
            {
                sArabicToRoman = "I" + ArabicToRoman((nr - 1));
            }
            else if (nr <= -889)
            {
                sArabicToRoman = "M" + ArabicToRoman(nr + 1000);
            }
            else if (nr <= -389)
            {
                sArabicToRoman = "D" + ArabicToRoman(nr + 500);
            }
            else if (nr <= -89)
            {
                sArabicToRoman = "C" + ArabicToRoman(nr + 100);
            }
            else if (nr <= -39)
            {
                sArabicToRoman = "L" + ArabicToRoman(nr + 50);
            }
            else if (nr <= -9)
            {
                sArabicToRoman = "X" + ArabicToRoman(nr + 10);
            }
            else if (nr <= -4)
            {
                sArabicToRoman = "V" + ArabicToRoman(nr + 5);
            }
            else if (nr <= -1)
            {
                sArabicToRoman = "I" + ArabicToRoman(nr + 1);
            }
        }
        catch (Exception _e_)
        {
            TxtRoman.Text = "Error.";
        }
        return sArabicToRoman;
    }

 

Button with confirm message

by Emanuele 11/9/2007 1:39:00 AM

It's simple, but it's much important when you want make a site with much user experience.
If you have a button that makes an important and critical job, you need a confirm button to add much security for users.
Well, with this simple line of code, you can do that.
When you click "OK" on the message, the application fire the "OnClick" event that you specifid.
Otherwise, the page does nothing.
Simple but useful.

<asp:Button ID="ButtonDelete" runat="server" OnClick="ButtonDelete_Click1" OnClientClick="return confirm('Confermi la cancellazione ?');" />

 

Launch a DTS from Asp.net page

by Emanuele 11/7/2007 2:52:00 PM

Introduction

Data Trasformation Services (DTS) is a tool and set of programmable objects that lets you extract, trasform and consolidate data from various source into various destinations.

How to

Launch a DTS from Asp.net page is much useful, when you must import some data from disparate sources.
First, add reference Microsoft.SqlServer.ManagedDTS to project.
Place into the class the follow using:

using Microsoft.SqlServer.Dts.Runtime;

Now, into the page load event place this code:

string
pkgLocation;
Package pkgImport;
Application appImport;
DTSExecResult pkgResults;

pkgLocation = @"c:\temp\DtsTest.dtsx";
appImport = new Application();
pkgImport = appImport.LoadPackage(pkgLocation, null);
pkgResults = pkgImport.Execute();

if (pkgResults == DTSExecResult.Success)
{
    TxtEsito.text = "DTS Eseguito con successo.";
}

Also we can

Also, we can see the state of job using the follow state enumeration http://msdn2.microsoft.com/en-us/library/microsoft.sqlserver.dts.runtime.dtsexecresult.aspx



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