Posts Tagged ‘C#.Net’

Linq to NHibernate, Version 1.0

Thursday, September 10th, 2009

A few weeks ago, Oren Eini (Ayende Raihan or, as is often referred to) communicated the release of version 1.0 of the Linq provider for NHibernate, a feature highly demanded by users since the advent of integrated query language. NET.

Although it will be included as part of NHibernate product in future versions, have decided to release the current release of the supplier as separate package so you can start to be used from now. It is being tested in many applications in production for several years, and apparently the performance is just right.

And how can help the supplier, if you’re user of NHibernate? The following example from Caffeinated Coder demonstrates how to query database can be simplified and made more readable using Linq and also benefit from strong typing, intellisense and compile-time checks:

Using NHibernate API:

public IList<Call> GetCallsByDate(DateTime beginDate, int interpreterId)
{
    ICriteria criteria = Session.CreateCriteria(typeof(Call))
        .CreateAlias("Customer", "Customer")
        .Add(Restrictions.Gt("StartTime", beginDate))
        .Add(
            Restrictions.Or(
                Restrictions.Lt("EndTime", DateTime.Now), Restrictions.IsNull("EndTime"))
            )
        .Add(Restrictions.Eq("Interpreter.Id", interpreterId))
        .AddOrder(Order.Desc("StartTime"))
        .AddOrder(Order.Desc("Customer.Name"));
        return criteria.List<Call>() as List<Call>;
}

Using Linq:

public IList<Call> GetCallsByDateWithLinq(DateTime beginDate, int interpreterId)
{
    var query = from call in Session.Linq<Call>()
        where call.StartTime > beginDate
            && (call.EndTime == null || call.EndTime < DateTime.Now )
            && call.Interpreter.Id == interpreterId
        orderby call.StartTime descending, call.Customer.Name
        select call;

    return query.ToList();
}

You can download both binaries and source code from the SourceForge project page.

Code in C# to create a backup of a database in SQL server and restore it

Wednesday, August 19th, 2009

Here they left a code in C # very useful when making your applications with databases in SQL server can support the database and restore it.

Support code for a button:

private void btnBackUp_Click(object sender, EventArgs e)
{
    bool bBackUpStatus = true;

    Cursor.Current = Cursors.WaitCursor; 

     if (Directory.Exists(@"c:\SQLBackup"))
        {
            if (File.Exists(@"c:\SQLBackup\wcBackUp1.bak"))
            {
                if (MessageBox.Show(@"Do you want to replace it?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    File.Delete(@"c:\SQLBackup\wcBackUp1.bak");
                }
                else
                    bBackUpStatus = false;
            }
        }
        else
            Directory.CreateDirectory(@"c:\SQLBackup");

        if (bFileStatus)
        {
            //Connect to DB
            SqlConnection connect;
            string con = "Data Source = localhost; Initial Catalog=dbWiseCodes ;Integrated Security = True;";
            connect = new SqlConnection(con);
            connect.Open();
            //----------------------------------------------------------------------------------------------------

            //Execute SQL---------------
            SqlCommand command;
            command = new SqlCommand(@"backup database dbWiseCodes to disk ='c:\SQLBackup\wcBackUp1.bak' with init,stats=10", connect);
            command.ExecuteNonQuery();
            //-------------------------------------------------------------------------------------------------------------------------------

            connect.Close();

            MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
}

Code for a button to restore:


private void btnRestore_Click(object sender, EventArgs e)
{

    Cursor.Current = Cursors.WaitCursor;

    try
    {
        if (File.Exists(@"c:\SQLBackup\wcBackUp1.bak"))
        {
            if (MessageBox.Show("Are you sure you restore?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //Connect SQL-----------
                SqlConnection connect;
                string con = "Data Source = localhost; Initial Catalog=master ;Integrated Security = True;";
                connect = new SqlConnection(con);
                connect.Open();
                //-----------------------------------------------------------------------------------------

                //Excute SQL----------------
                SqlCommand command;
          command = new SqlCommand("use master", connect);
            command.ExecuteNonQuery();
                command = new SqlCommand(@"restore database dbWiseCodes01 from disk = 'c:\SQLBackup\wcBackUp1.bak'", connect);
                command.ExecuteNonQuery();
                //--------------------------------------------------------------------------------------------------------
                connect.Close();

                MessageBox.Show("Has been restored database", "Restoration", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        else
            MessageBox.Show(@"Do not make any endorsement above (or is not in the correct path)", "Restoration", MessageBoxButtons.OK, MessageBoxIcon.Information);

    }
    catch (Exception exp)
    {
        MessageBox.Show(exp.Message);
    }

}

.NET: Checking whether an Internet connection is available

Wednesday, May 20th, 2009

The method using ping checks whether there is an internet connection or not?

In C#.NET

The following namespace is required:

using System.Net.NetworkInformation;
/// <Summary>
/// Checks whether an Internet connection is available.
/// </Summary>
/// <Returns>
/// True / false
/// </Returns>
/// Site: WiseCodes.Com

public static bool wcCheckInternetConnectionStatus()
{
 Ping pingSender = new Ping();

 try
 {
PingReply pReply = pingSender.Send("www.microsoft.com", 100);

 return pReply.Status == IPStatus.Success;
 }
 catch
 {
 return false;
 }
}

Link: System.Net.NetworkInformation Namespace (Via MSDN)

Happy Programming!! ;-)

.NET: Check links (http, https, ftp, news etc …)

Thursday, May 14th, 2009

In this article we show how we can know what kind of address is an address. We will use the URI class, which does not allow URLs to work. The class belongs to the URI name space System.

The URI class has property “Scheme” that indicates the type of URI scheme today. The schemes that detects the URI class are:

* UriSchemeFile: tells us that points the direction in which our class is a file URI.
* UriSchemeFtp: the scheme is FTP (File Transfer Protocol)
* UriSchemeGopher: specifies that we can access through URI using the Gopher protocol.
* UriSchemeHttp: access is a URI using the HTTP protocol.
* UriSchemeHttps: the address is https, http secure.
* UriSchemeMailto: tells us that the address is an e-mail, which can be accessed via SMTP.
* UriSchemeNetPipe: tells us that the identifier URI is NetPipe.
* UriSchemeNetTcp: can access through URI using the protocol NetTCP.
* UriSchemeNews: URI is the address of a newsgroup or News.
* UriSchemeNntp: a newsgroup is accessed via NNTP.

The fields above are just reading.

In the following example, create a constant that contains the address from which we obtain information and identify which type of management is our constant.

In Visual Basic:

Const strURL As String = “http://www.wisecodes.com”
Dim strDir As New Uri(strURL)
Select Case strDir.Scheme
Case Uri.UriSchemeFile
'Code for when the address is a file
Case Uri.UriSchemeFtp
'Code for when the address is ftp
Case Uri.UriSchemeGopher
'Code for when the address is a file Gopher
Case Uri.UriSchemeHttp
'Code for when the address is http
Case Uri.UriSchemeHttps
'Code for when the address is https
Case Uri.UriSchemeMailto
'Code for when the address is an e-mail
Case Uri.UriSchemeNetPipe
'Code for when the address is NetPipe
Case Uri.UriSchemeNetTcp
'Code for when the address is NetTcp
Case Uri.UriSchemeNews
'Code for when the address is a newsgroup
Case Uri.UriSchemeNntp
'Code for when the address is a newsgroup
'accessible via NNTP.
End Select

In C Sharp

const string strURL = “http://www.wisecodes.com”
Uri strDir = new Uri (strURL);
switch (strDir.Scheme)
{
case Uri.SchemeFile:
//Code for when the address is a file
case Uri.UriSchemeFtp:
//Code for when the address is ftp
case Uri.UriSchemeGopher:
//Code for when the address is a file Gopher
case Uri.UriSchemeHttp:
//Code for when the address is http
case Uri.UriSchemeHttps:
//Code for when the address is https
case Uri.UriSchemeMailto:
//Code for when the address is an e-mail
case Uri.UriSchemeNetPipe:
//Code for when the address is NetPipe
case Uri.UriSchemeNetTcp:
//Code for when the address is NetTcp
case Uri.UriSchemeNews:
//Code for when the address is a newsgroup
caseUri.UriSchemeNntp:
//Code for when the address is a newsgroup
//accessible via NNTP.
}

Link: Via Microsoft
Happy Programming!! ;-)

Desktop Refreshing in .NET

Wednesday, April 29th, 2009

With this method, you can rebuild the desktop (for example, if the icon has re-positioned via code)

public static void wc_RefreshDesktop()
{
 SHChangeNotify(0x8000000, 0, IntPtr.Zero, IntPtr.Zero);
}

Happy Programming!!

Reading source code of a WebPage

Saturday, April 25th, 2009

This method, get the HTML source code of any WebPage

C#.NET

using System.Net;

WebClient webClient = new WebClient();
string strHTMLSourceCode = webClient.DownloadString("http://www.microsoft.com");

VB.NET

Imports System.Net

Dim webClient As WebClient = New WebClient()
Dim strHTMLSourceCode As String = webClient.DownloadString("http://www.microsoft.com")

Read More about webClient.DownloadString(string)…

Happy Programming!!

ASP.Net Gridview to CSV, Excel

Saturday, April 25th, 2009

This method, export to Excel file from Gridview

VB.NET


Sub wc_gvGridviewToExcel(ByVal gvGridview As Gridview, ByVal strExcelFilePath As String)

'Columns

Dim intColumnsCount As Integer = gvGridview.Columns.Count - 1

'Header

Dim strHeaderNames As String = Nothing

For i = 0 To intColumnsCount

strHeaderNames += gvGridview.Columns(i).HeaderText & ";"

Next

WriteToExcel(strHeaderNames, strExcelFilePath)

'Each Row

Dim strRowText As String = Nothing

For Each grdRow As gvGridviewRow In gvGridview.Rows

For i = 0 To intColumnsCount

strRowText += grdRow.Cells(i).Text & ";"

Next

WriteToExcel(strRowText, strExcelFilePath)

strRowText = Nothing

Next

End Sub

Sub WriteToExcel(ByVal strText As String, ByVal strExcelFileName As String)

Dim myFileWriter As New System.IO.StreamWriter(strExcelFileName, True)

myFileWriter.WriteLine(strText)

myFileWriter.Close()

End Sub

C#.NET

public void wc_gvGridviewToExcel(Gridview gvGridview, string strExcelFilePath)
{

 //Columns

 int intColumnsCount = gvGridview.Columns.Count - 1;

 //Header

 string strHeaderNames = null;

 for (i = 0; i <= intColumnsCount; i++) {

 strHeaderNames += gvGridview.Columns(i).HeaderText + ";";
 }

 WriteToExcel(strHeaderNames, strExcelFilePath);

 //Each Row

 string strRowText = null;

 foreach (gvGridviewRow grdRow in gvGridview.Rows) {

 for (i = 0; i <= intColumnsCount; i++) {

 strRowText += grdRow.Cells(i).Text + ";";
 }

 WriteToExcel(strRowText, strExcelFilePath);

 strRowText = null;

 }
}

public void WriteToExcel(string strText, string strExcelFileName)
{

 System.IO.StreamWriter myFileWriter = new System.IO.StreamWriter(strExcelFileName, true);

 myFileWriter.WriteLine(strText);

 myFileWriter.Close();
}

Happy Programming!!

Compare Files

Friday, April 24th, 2009

This method Compares 2 files and returns true or false.

C#.NET

private bool wc_CompareFiles(string FilePath1, string FilePath2)
{
FileInfo FI1 = new FileInfo(FilePath1);
FileInfo FI2 = new FileInfo(FilePath2);

if (FI1.Length != FI2.Length)
return false;

byte[] Filebytes1 = File.ReadAllBytes(FilePath1);
byte[] Filebytes2 = File.ReadAllBytes(FilePath2);

if (Filebytes1.Length != Filebytes2.Length)
return false;

for (int i = 0; i &lt;= Filebytes2.Length - 1; i++)
{
if (Filebytes1[i] != Filebytes2[i])
return false;
}
return true;
}

VB.NET


Private Function wc_CompareFiles(ByVal FilePath1 As String, ByVal FilePath2 As String) As Boolean
 Dim FI1 As New FileInfo(FilePath1)
 Dim FI2 As New FileInfo(FilePath2)

 If FI1.Length <> FI2.Length Then
 Return False
 End If

 Dim Filebytes1 As Byte() = File.ReadAllBytes(FilePath1)
 Dim Filebytes2 As Byte() = File.ReadAllBytes(FilePath2)

 If Filebytes1.Length <> Filebytes2.Length Then
 Return False
 End If

 For i As Integer = 0 To Filebytes2.Length - 1
 If Filebytes1(i) <> Filebytes2(i) Then
 Return False
 End If
 Next
 Return True
End Function

Happy Programming!!

LinqPad

Thursday, April 23rd, 2009

I just learned of the existence of a very interesting tool called LinqPad, which allows query data using LINQ with. Net Framework 3.5.

Click on the image to view large.

Allows queries like:

a) LINQ to SQL
b) LINQ to Objects
c) LINQ to XML

After doing some tests I can say that is an excellent tool, very comprehensive and allows flexibility to experience the power of LINQ and more of this interesting framework, which aims to be the big bet. NET for data access.

Read More about LinqPad

FTP file upload in .NET 2.0

Friday, April 17th, 2009

It is clear that the FileUpload components, which can be found on the Standard toolbar of Visual Studio 2005 allows uploading files to the remote site, but does not cover all the expectations desired or at least not mine.
So it is interesting to know how we can attack a specific server and an FTP to copy the desired file to the remote location to stay.

To do this:

Step 1: In general declarations establish that the class will use.

C#

using System.Net;

VB.NET

Imports System.Net

Step 2: Create a button in the Click event and write the following code in C# or VB.NET:

C#

private static void wc_UploadFTP(string ftpServerPath, string filename, string username, string password)
 {
WebClient ClientFtp = new WebClient() ;
ClientFtp.Credentials = new NetworkCredential(username, password);
ClientFtp.UploadFile(ftpServerPath + "/" + new FileInfo(filename).Name, "STOR", filename);
}

VB.NET


Private Shared Sub wc_UploadFTP(ByVal ftpServerPath As String, ByVal filename As String, ByVal username As String, ByVal password As String)
 Dim ClientFtp As New WebClient()
 ClientFtp.Credentials = New NetworkCredential(username, password)
 ClientFtp.UploadFile((ftpServerPath & "/") + New FileInfo(filename).Name, "STOR", filename)
End Sub

Happy Programming!!