Wednesday, November 10, 2010

How to export DataTable to CSV file


In this short post I will show you how to expert DataTable to CSV file. I have created C# function ExportTableToCsv with one parameted of DataTable data type.

private static string ExportTableToCsv(DataTable sourceTable)
{
    StringBuilder sb = new StringBuilder();

    for (int rowCount = 0; rowCount < sourceTable.Rows.Count; rowCount++)
    {
        for (int colCount = 0; colCount < sourceTable.Columns.Count; colCount++)
        {
            sb.Append(sourceTable.Rows[rowCount][colCount]);
            if (colCount != sourceTable.Columns.Count - 1)
            {
                sb.Append(",");
            }
        }
        if (rowCount != sourceTable.Rows.Count - 1)
        {
            sb.AppendLine();
        }
    }
    return sb.ToString();
}

SQL Server - How to create login using SMO



This is not a problem, when you have SQL Server Management studio installed. But what if you don’t have Management Studio is not installed? In this case you can use sqlcmd utility. In some cases, you need to backup databases programmatically and this could be done via Server Management objects. In this short example I will show you how to create SQL Server login and assign it to sysadmin server role.

ServerConnection conn = new ServerConnection("SQLSERVERINSTANCE", "USERNAME", "PASSWORD");
try
{
    Server srv = new Server(conn);
    Login newLogin = new Login(srv, "TestLogin");
    newLogin.LoginType = Microsoft.SqlServer.Management.Smo.LoginType.SqlLogin;
    newLogin.Create("TestPassword");
    newLogin.AddToRole("sysadmin");   
}
catch (Exception err)
{
    Console.WriteLine(err.Message);
}
This short example connects to SQL Server instance and creates new login called TestLogin with sysadmin server role.

Sunday, November 7, 2010

Single layer perceptron as linear classifier

Perceptron is the simplest type of feed forward neural network. It was designed by Frank Rosenblatt as dichotomic classifier of two classes which are linearly separable. This means that the type of problems the network can solve must be linearly separable. Basic perceptron consists of 3 layers:
  • sensor layer
  • associative layer
  • output neuron
There are a number of inputs (xn) in sensor layer, weights (wn) and an output. Sometimes w0 is called bias and x0 = +1/-1 (In this case is x0=-1).


For every input on the perceptron (including bias), there is a corresponding weight. To calculate the output of the perceptron, every input is multiplied by its corresponding weight. Then weighted sum is computed of all inputs and fed it through a limiter function that evaluates the final output of the perceptron.
The output of neuron is formed by activation of the output neuron, which is function of input:
(1)

The activation function F can be linear so that we have a linear network, or nonlinear. In this example I decided to use threshold (signum) function:

(2)

Output of network in this case is either +1 or -1 depending on the input. If the total input (weighted sum of all inputs) is positive, then the pattern belongs to class +1, otherwise to class -1. Because of this behavior, we can use perceptron for classification tasks.

Lets consider we have a perceptron with 2 inputs and we want to separate input patterns into 2 classes. In this case the separation between the classes is straight line, given by equation:

(3)

When we set x0=-1 and mark w0=θ then we can rewrite equation (3) into form:

(4)

Here I will describe learning method for perceptron. Learning method of perceptron is iterative procedure that adjust the weights. A learning sample is presented to the network. For each weight the new value is computed by adding a correction to the old value. The threshold is updated in the same way:

(5)


where y is output of perceptron, d is desired output and γ is the learning parameter.



More about program and source code, you can find on www.CodeProject.com

Wednesday, November 3, 2010

How to replace Machine Name with Domain name in WCF Service wsdl link


Today I was developing the application for streaming files on server using WCF. Everything was fine until I deployed application on production server. I found out that WCF was taking machine name instead of IP address or domain name. This accurs when WCF service is hosted on IIS. The links to wsdl use local machine name. The autogenerated page I received when I was navigating to the .svc page said:

svcutil.exe http://[machinename]/FileTransferService.svc

I discovered that it could be done by folloving steps:
  • Produce the wsdl in the browser and save to file (by hitting .svc?wsdl from browser)
  • Produce the xsd files by hitting url from wsdl (xsd=xsd0, etc), and save to file from browser
  • replace all machine name references from wsdl with domain name (or ip address) and change xsd references and save
  • replace all machine name references from xsd files with domain name (or ip address)
  • make sure to name xsd file with .xsd extension (ie, name0.xsd, name1.xsd, name2.xsd)
  • copy wsdl and xsd file(s) to virtual directory
  • add to your web.config following lines

<behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceBehavior">
          <serviceMetadata httpGetEnabled="true" externalMetadataLocation="http://IPorDomainName/MyServices/FileTransferService.wsdl"  />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

Tuesday, November 2, 2010

New Article on CodeProject.com

Before couple of days I have posted a new article on CodeProject.com. In this article I will show you, how to backup and restore databases using SMO. More about that you can find here: http://www.codeproject.com/KB/database/SQLServer_Backup_SMO.aspx

Monday, November 1, 2010

SQL Server - How to create LinkedServer using SMO

LinkedServer allows you to access resources in the other resources. Consider, you have a server named "ServerA" and you would like to grab some data from the remote server named "ServerB". In that case, you need to create a linked server. In our scenario, the linked server is "ServerB".

The linked servers communicate using an OLE DB connection. These connections handle the commands between the linked servers, so coders and administrators can query data and tables without knowing the intricacies of database communication.

Here is the code example that shows how to create LinkedServer using SMO:


Server srv = new Server(@"INSTANCEA");
LinkedServer lsrv = new LinkedServer(srv, "INSTANCEB"); 
LinkedServerLogin login = new LinkedServerLogin();
login.Parent = lsrv;
login.Name = "LOGIN_ON_INSTANCEA";
login.RemoteUser = "LOGIN_ON_INSTANCEB";
login.SetRemotePassword("PASSWORD");
login.Impersonate = false;
lsrv.ProductName = "SQL Server";
lsrv.Create();
login.Create();

By specifying SQL Server as the product name, data is accessed on the linked server by using the SQL Server Client OLE DB Provider, which is the official OLE DB provider for SQL Server.