Sunday, October 20, 2013

Selecting data from two Different SQL Servers

For selecting the data from two databases of two different servers, first we have to link the two servers.

sp_addlinkedserver('servername')

Then you can run the query like,

select * from Table1
unionall
select * from [server2].[database].[dbo].[Table1]

Read Text File using C#

Article about reading the Text file line by line using the StreamReader in C#


Namespace :

 using System.IO;

Code:

string line;

// Read the file and display it line by line.
StreamReader file = new StreamReader(@"c:\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}

file.Close();

Friday, June 21, 2013

Get Serial Number of Hard Drive using C#

To get the Serial # of HDD using C#

Namespace :

Imports System.Management


Code:

Dim devid As String = ""
Dim driveser As String = ""

Try
      Dim searcher As New ManagementObjectSearcher( _
      "root\CIMV2", "SELECT * FROM Win32_DiskDrive")
     
       For Each queryObj As ManagementObject In searcher.Get()
       If queryObj("SerialNumber") <> "" Then driveser = queryObj("SerialNumber")
                Debug.Print(queryObj("Model") + ":" + driveser)
       Next

Catch err As ManagementException
       Debug.Print("An error occurred while querying for WMI data: " & err.Message)
End Try

Saturday, April 13, 2013

Accept Only Numeric Textbox

Simple code to accept only numeric in Textbox. You have to handle the key press event of textbox and have to check the key character is numeric or not.

Code:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
    {
        e.Handled = true;
    }  
}

Friday, March 29, 2013

Replace/Mask Images of PDF file using Itextsharp

Article is about masking or replacing the images from PDF documents using iTextSharp. 

iTextSharp  is a free .NET component, you can download the DLL from http://sourceforge.net/projects/itextsharp/

After downloading the DLL, add reference of DLL in project by clicking on Add Reference from solution explorer.


Namespace :

using iTextSharp.text;
using iTextSharp.text.pdf;



Code:

   PdfReader pdf = new PdfReader("Test.pdf");
            PdfStamper stp = new PdfStamper(pdf, new FileStream("output.pdf",
FileMode.Create));
            


PdfWriter writer = stp.Writer;
             for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
            {
               
                Image img = Image.GetInstance("Img.jpg");
            PdfDictionary pg = pdf.GetPageN(pageNumber);
            PdfDictionary res =
              (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
            PdfDictionary xobj =
              (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
            if (xobj != null)
            {
                foreach (PdfName name in xobj.Keys)
                {
                    PdfObject obj = xobj.Get(name);
                    if (obj.IsIndirect())
                    {
                        PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
                        PdfName type =
                          (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
                        if (PdfName.IMAGE.Equals(type))
                        {
                            PdfReader.KillIndirect(obj);
                            Image maskImage = img.ImageMask;
                            if (maskImage != null)
                                writer.AddDirectImageSimple(maskImage);
                            writer.AddDirectImageSimple(img, (PRIndirectReference)obj);
                            break;
                        }
                    }
                }
            }
        }
            stp.Close();

Saturday, March 23, 2013

Reading WebResponse in C#

Namespace:
 
using System.Net;

Code:

         try
        {
            String Result, URL;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            ICredentials credentials = new NetworkCredential("username", "Password", "Domain");
            IWebProxy webProxy = new WebProxy("proxy URL", 8080);
            webProxy.Credentials = credentials;
            request.Proxy = webProxy;

            WebResponse myResponse = request.GetResponse();
            StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
            Result = sr.ReadToEnd();
            sr.Close();
            myResponse.Close();
        }
        catch {    }

Thursday, March 21, 2013

Use Crystal Report in C#

Code to view the Crystal Report using C#.

Namespace:

using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;


Code:


            CrystalDecisions.CrystalReports.Engine.ReportDocument oRpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
             CrystalDecisions.Shared.IConnectionInfo conn;


             ConnectionInfo CInfo = new ConnectionInfo();
             CInfo.ServerName = "server";
             CInfo.UserID = "ID";
             CInfo.Password = "Password";

             TableLogOnInfo tableInfo = new TableLogOnInfo();
             tableInfo.ConnectionInfo = CInfo;

             TableLogOnInfos tablelog = new TableLogOnInfos();
             tablelog.Add(tableInfo);

             crystalReportViewer1.ReportSource = Application.StartupPath + "\\Report.rpt";
             crystalReportViewer1.LogOnInfo = tablelog;

             ReportDocument obj = new ReportDocument();
             obj.Load(Application.StartupPath + "\\Report.rpt");

              obj.SetParameterValue("Para1","Value");
             obj.SetParameterValue("Para2", "Value");
           
             crystalReportViewer1.ReportSource = obj;

Wednesday, March 20, 2013

Start or Stop Services on Remote Machine

Sample code to control the remote machine/system services. Below code shows how to Start or Stop the remote computer service.

Note : To run this code user must have the rights to Start/Stop the service of the remote computer.

Namespace: 
       using System.Management;


Code:

Start service of the Remote Machine:

              try
                {

                    #region Code to start the service
              
                    string serviceName = "Service1";
                    string IP="Remote machine IP";
                    string username ="UserID";
                    string password ="Pass";

                    ConnectionOptions connectoptions = new ConnectionOptions();
                    //connectoptions.Impersonation = ImpersonationLevel.Impersonate;
                    connectoptions.Username = username;
                    connectoptions.Password = pass;

                    //IP Address of the remote machine
                 
                    ManagementScope scope = new ManagementScope(@"\\" + IP + @"\root\cimv2");
                    scope.Options = connectoptions;

                    //WMI query to be executed on the remote machine
                    SelectQuery query = new SelectQuery("select * from Win32_Service where name = '" + serviceName + "'");

                    using (ManagementObjectSearcher searcher = new
                                ManagementObjectSearcher(scope, query))
                    {
                        ManagementObjectCollection collection = searcher.Get();
                        foreach (ManagementObject service in collection)
                        {
                            if (service["Started"].Equals(false))
                            {
                                //Start the service
                                service.InvokeMethod("StartService", null);                             
                            }

                        }
                    }
                  
           #endregion

                }
                catch ()
                {
                 
                }


Similar way you can stop the service of Remote Machine:

                       if (service["Started"].Equals(true))
                        {
                            //Stop the service
                            service.InvokeMethod("StopService", null);                           
                        }

Tuesday, March 19, 2013

Generate PDF From images using itextsharp

Article is about creating PDF documents using iTextSharp. 

iTextSharp  is a free .NET component, you can download the DLL from http://sourceforge.net/projects/itextsharp/

After downloading the DLL, add reference of DLL in project by clicking on Add Reference from solution explorer.


Namespace :

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;


Code:

            DirectoryInfo dir = new System.IO.DirectoryInfo("Image Path");
            FileInfo[] file;
            file = dir.GetFiles("*.jpg");
            String[] Fname;
            String Path;

 using (FileStream fs = new FileStream(Path+ "Test.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
            {
              
                using (Document doc = new Document())
                {
                    using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
                    {
                        doc.Open();
                        doc.SetMargins(0, 0, 0, 0);
                       
                        iTextSharp.text.Image importImage;
                       
                        for (int j = 0; j <= file.Length - 1; j++)
                        {
                          
                                Chapter chapter1 = new Chapter("", j);
                                chapter1.NumberDepth = 0;
                                chapter1.TriggerNewPage = true;
                                importImage = iTextSharp.text.Image.GetInstance(file[j].FullName);
                                doc.SetPageSize(new iTextSharp.text.Rectangle(0, 0, importImage.Width, importImage.Height));
                                doc.SetPageSize(new iTextSharp.text.Rectangle(importImage.Width, importImage.Height));
                                chapter1.Add(importImage);
                                doc.Add(chapter1);                          
                           
                        }
                                             
                        doc.Close();
                    }
                }
            }

Sunday, March 17, 2013

Fill SQL data in Dataset

Add Namespace :

using System.Data.SqlClient;

Code:

  SqlConnection con;
  SqlCommand cmd ;
  SqlDataAdapter adp = new SqlDataAdapter();
  DataSet ds = new DataSet();

  con = new SqlConnection( "Data Source=ServerName;Initial Catalog=DatabaseName;UserID=UserName;Password=Password" );

try
{
    con .Open();
    cmd = new SqlCommand("Select * from Tablename", con);
    adp.SelectCommand = cmd;
    adp.Fill(ds, "Tablename");
    adp.Dispose();
    cmd.Dispose();
    con.Close();
}
catch (Exception ex)
{

}

Saturday, March 16, 2013

Send email using C#

Simple code to send the email gmail SMTP.


Add Namespaces :
using System.Net.Mail;
 
Code :
 
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); //Enter your SMTP address

mail.From = new MailAddress("your_emailID@gmail.com");
mail.To.Add("to_address");
mail.Subject = "Test EMail";
mail.Body = "Test SMTP mail from GMAIL";

SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);