Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, 14 March 2013

Convert image files to Tiff file format

http://www.kerrywong.com/tiff-merge-and-split-utility/

http://www.bobpowell.net/generating_multipage_tiffs.htm

Sunday, 25 November 2012

Runtime add item to PropertyGrid Drop-down List

This sample demonstrates the technique for setting two items of a property grid from the drop-down list. These items have the type of string, but it must be simple to remake them for any other type.
Firstly, inherit the class from UITypeEditor:

public class SelEditor : System.Drawing.Design.UITypeEditor
 {       
//this is a container for strings, which can be picked-out
  ListBox Box1 = new ListBox();
  IWindowsFormsEditorService edSvc;
//this is a string array for drop-down list
  public static string[] strList;

  public SelEditor()
  {
   Box1.BorderStyle=BorderStyle.None;
//add event handler for drop-down box when item will be selected
   Box1.Click+=new EventHandler(Box1_Click);
  }

  public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle
(System.ComponentModel.ITypeDescriptorContext context)
  {
   return UITypeEditorEditStyle.DropDown;
  }

  // Displays the UI for value selection.
  public override object EditValue
(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object
value)
  {
   Box1.Items.Clear();
   Box1.Items.AddRange(strList);
   Box1.Height=Box1.PreferredHeight;
   // Uses the IWindowsFormsEditorService to display a
   // drop-down UI in the Properties window.
   edSvc = (IWindowsFormsEditorService)provider.GetService(typeof
(IWindowsFormsEditorService));
   if( edSvc != null )
   {
    edSvc.DropDownControl( Box1 );
    return Box1.SelectedItem;

   }
   return value;
  }

  private void Box1_Click(object sender, EventArgs e)
  {
   edSvc.CloseDropDown();
  }
 }


Secondly, describe a property in the class, displayed in the property grid:

 public class Class1
 {
//These are string arrays for different drop-down list.
  string[] Str1= {"AAA","BBB","CCC","DDDD"};
  string[] Str2= {"WW","EEE"};

  string s1,s2;
  public Class1()
  {
   //
   // TODO: Add constructor logic here
   //
  }


  [EditorAttribute(typeof(SelEditor), typeof(System.Drawing.Design.UITypeEditor))]
  public string STR_1
  {
   get{SelEditor.strList=Str1; return s1;}
   set{s1=value;}
  }
 
  [EditorAttribute(typeof(SelEditor), typeof(System.Drawing.Design.UITypeEditor))]
  public string STR_2
  {
   get{SelEditor.strList=Str2; return s2;}
   set{s2=value;}
  }

 }

Tuesday, 14 August 2012

c# Send email using Gmail smtp



using System;
using System.Windows.Forms;
using System.Net.Mail;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress("
your_email_address@gmail.com");
                mail.To.Add("to_address");
                mail.Subject = "Test Mail - 1";
                mail.Body = "mail with attachment";

                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment("your attachment file");
                mail.Attachments.Add(attachment);

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

                SmtpServer.Send(mail);
                MessageBox.Show("mail Send");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

Monday, 13 August 2012

MailSystem.NET Component

MailSystem is a suite of .NET components that provide users with an extensive set of email tools. MailSystem provides full support for SMTP, POP3, IMAP4, NNTP, MIME, S/MIME, OpenPGP, DNS, vCard, vCalendar, Anti-Spam (Bayesian , RBL, DomainKeys), Queueing, Mail Merge and WhoIs

http://mailsystem.codeplex.com/

Wednesday, 25 July 2012

C# Process.Start

Starts a process resource and associates it with a Process component.
Example: call external application to view documents and web pages. It also executes EXE programs and external command line utilities.

Program that opens directory [C#]
using System.Diagnostics;
class Program
{
    static void Main()
    {
     //
     // Use Process.Start here.
     //
      Process.Start("C:\\");
    }
}

Program that opens text file [C#]
using System.Diagnostics;
class Program
{
    static void Main()
    {
     //
     // Open the file "example.txt" that is in the same directory as
     // your .exe file you are running.
     //
      Process.Start("example.txt");
    }
}

Program that searches Google [C#]
using System.Diagnostics;
class Program
{
    static void Main()
    {
      // Search Google.
       Process.Start("http://google.com/");
    }
}

Program that starts WINWORD.EXE [C#]
using System.Diagnostics;
class Program
{
    static void Main()
    {
     // A.
     // Open specified Word file.
     OpenMicrosoftWord(@"C:\Users\Sam\Documents\Gears.docx");
    }
    /// <summary>
    /// Open specified word document.
    /// </summary>
    static void OpenMicrosoftWord(string f)
    {
      ProcessStartInfo startInfo = new ProcessStartInfo();
      startInfo.FileName = "WINWORD.EXE";
      startInfo.Arguments = f;
      Process.Start(startInfo);
    }
}

Program that runs EXE [C#]
using System.Diagnostics;
class Program
{
    static void Main()
    {
      LaunchCommandLineApp();
    }
    /// <summary>
    /// Launch the  application with some options set.
    /// </summary>
    static void LaunchCommandLineApp()
    {
      // For the example
      const string ex1 = "C:\\";
      const string ex2 = "C:\\Dir";

      // Use ProcessStartInfo class
      ProcessStartInfo startInfo = new ProcessStartInfo();
      startInfo.CreateNoWindow = false;
      startInfo.UseShellExecute = false;
      startInfo.FileName = "myprog.exe";
      startInfo.WindowStyle = ProcessWindowStyle.Hidden;
      startInfo.Arguments = "-f d " + ex2;

 try
 {
     // Start the process with the info we specified.
     // Call WaitForExit and then the using statement will close.
     using (Process exeProcess = Process.Start(startInfo))
     {
       exeProcess.WaitForExit();
     }
 }
 catch
 {
     // Log error.
 }
    }
}

Saturday, 5 May 2012

.Net File.Exists, Directory.Exists

// C# Example code for File.Exists, Directory.Exists
using System;
using System.IO;
using System.Collections;

public class RecursiveFileProcessor 
{
    public static void Main(string[] args) 
    {
        foreach(string path in args) 
        {
            if(File.Exists(path)) 
            {
                // This path is a file
                ProcessFile(path); 
            }               
            else if(Directory.Exists(path)) 
            {
                // This path is a directory
                ProcessDirectory(path);
            }
            else 
            {
                Console.WriteLine("{0} is not a valid file or directory.", path);
            }        
        }        
    }


    // Process all files in the directory passed in, recurse on any directories 
    // that are found, and process the files they contain.
    public static void ProcessDirectory(string targetDirectory) 
    {
        // Process the list of files found in the directory.
        string [] fileEntries = Directory.GetFiles(targetDirectory);
        foreach(string fileName in fileEntries)
            ProcessFile(fileName);

        // Recurse into subdirectories of this directory.
        string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach(string subdirectory in subdirectoryEntries)
            ProcessDirectory(subdirectory);
    }

    // Insert logic for processing found files here.
    public static void ProcessFile(string path) 
    {
        Console.WriteLine("Processed file '{0}'.", path);     
    }
}

Friday, 4 May 2012

Windows System Folders

// Sample for the Environment.GetFolderPath method
using System;

class Sample
{
    public static void Main()
    {
    Console.WriteLine();
    Console.WriteLine("GetFolderPath: {0}",
                 Environment.GetFolderPath(Environment.SpecialFolder.System));
    }
}
/*
This example produces the following results:

GetFolderPath: C:\WINNT\System32
*/


Environment.SpecialFolder Enumeration
http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx

Friday, 27 April 2012

Reading and Writing XML Files

To create or manipulate XML files, you must use the classes and methods inside the System.XML namespace of the .NET Framework.

Writing XML FilesWe can use the XmlWriter class to write XML files. It allows you to write XML text into a stream and then save it into an xml file.

using System.Xml;

public class Program
{
    public static void Main()
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;

        XmlWriter writer = XmlWriter.Create("Products.xml", settings);
        writer.WriteStartDocument();
        writer.WriteComment("This file is generated by the program.");
        writer.WriteStartElement("Product");
        writer.WriteAttributeString("ID", "001");
        writer.WriteAttributeString("Name", "Soap");
        writer.WriteElementString("Price", "10.00");
        writer.WriteStartElement("OtherDetails");
        writer.WriteElementString("BrandName", "X Soap");
        writer.WriteElementString("Manufacturer", "X Company");
        writer.WriteEndElement();
        writer.WriteEndDocument();

        writer.Flush();
        writer.Close();
    }
}


We first import the System.Xml namespace. We use the XmlWriterSettings class to create a setting for the XmlWriter that we will use. We dictated the program to use proper indention when writing the xml by using this settings. We then create an XmlWriter object by calling the XmlWriter.Create method and supplying the filename and the XmlWriterSettings object.

Using the XmlWriter class, we can write our xml. We first use the XmlWriter.WriteStartDocument() method which writes the xml declaration you find on the top of most xml files. Next we create a sample comment using teh XmlWriter.WriteComment() method. To write an Xml Element, we use the XmlWriter.WriteStartElement() and supply the name of the element as the argument. The XmlWriter.WriteStartElement() must be paired with XmlWriter.WriteEndElement which writes the closing tag of that element. We now create some attributes for the element using the XmlWriter.WriteAttributeString() method and supply the name and the value for that attribute.

We used the XmlWriter.WriteElementString() method with a name and a value as the arguments to write an element that is wrapping a value. We then nested another element inside the Products element by writing one more set of XmlWriter.WriteStartElement() and XmlWriter.WriteEndElement() . Inside it, we add two more elements that contain values. To mark the end of the document, we simly call the XmlWriter.WriteEndDocument() method.
Finally, we used the XmlWriter.Flush() method to clean the contents of the stream and the XmlWriter.Close() method to save the file and stop the program from using it.
The above code will produce the following XML file contents:

<?xml version="1.0" encoding="utf-8"?>
<!--This file is generated by the program.-->
<Product ID="001" Name="Soap">
  <Price>10.00</Price>
  <OtherDetails>
    <BrandName>X Soap</BrandName>
    <Manufacturer>X Company</Manufacturer>
  </OtherDetails>
</Product>


Reading XML Files
To read xml files, we can use the XmlReader class. We will use the XML file we created earlier to assign the values into variables. Note that we will simply use variables for storing the values from the XML. A better approach is by creating a Products class the follows the heirarchy of the XML file. The following program demonstrates the use of XmlReader class.

using System;
using System.Xml;

public class Program
{
    public static void Main()
    {
        XmlReader reader = XmlReader.Create("Products.xml");

        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element
                && reader.Name == "Product")
            {
                Console.WriteLine("ID = " + reader.GetAttribute(0));
                Console.WriteLine("Name = " + reader.GetAttribute(1));

                while (reader.NodeType != XmlNodeType.EndElement)
                {
                    reader.Read();
                    if (reader.Name == "Price")
                    {
                        while (reader.NodeType != XmlNodeType.EndElement)
                        {
                            reader.Read();
                            if (reader.NodeType == XmlNodeType.Text)
                            {
                                Console.WriteLine("Price = {0:C}", Double.Parse(reader.Value));
                            }
                        }

                        reader.Read();
                    } //end if
                    if (reader.Name == "OtherDetails")
                    {
                        while (reader.NodeType != XmlNodeType.EndElement)
                        {
                            reader.Read();
                            if (reader.Name == "BrandName")
                            {
                                while (reader.NodeType != XmlNodeType.EndElement)
                                {
                                    reader.Read();
                                    if (reader.NodeType == XmlNodeType.Text)
                                    {
                                        Console.WriteLine("Brand Name = " + reader.Value);
                                    }
                                }
                                reader.Read();
                            } //end if

                            if (reader.Name == "Manufacturer")
                            {
                                while (reader.NodeType != XmlNodeType.EndElement)
                                {
                                    reader.Read();
                                    if (reader.NodeType == XmlNodeType.Text)
                                    {
                                        Console.WriteLine("Manufacturer = " + reader.Value);
                                    }
                                }

                            } //end if
                        }
                    } //end if
                } //end while
            } //end if

        } //end while
    }
}


Output:
ID = 001
Name = Soap
Price = $10.00
Brand Name = X Soap
Manufacturer = X Company


There are other ways to read Xml files but this tutorial will focus on using the XmlReader class. First, we create an XmlReader object using the static method Create and passing the filename of the XML file that will be read.

XmlReader reader = XmlReader.Create("Products.xml");

We now enter a loop that will read each node in the xml file including the whitespaces. We use the XmlReader.Read() that returns true if there are more nodes to read or false if there is no more or if it reaches the end of the file.
We first look at the Product element. The first condition checks if the current node read by the reader is an element and has a name of "Product". The XmlNodeTpe enumeration list all the possible node types including whitespaces, text and comments. We then show the values of the attributes of the product element:

Console.WriteLine("ID = " + reader.GetAttribute(0));
Console.WriteLine("Name = " + reader.GetAttribute(1));

The GetAttribute() method gets the values of the attribute of an element. The number indicates what attribute you are getting. 0 indicates the first attribute and 1 indicates the second attribute.
You will now encounter a series of nested while and if statements. The first while loop will search for the Price element. The Read() method will go to the next node while it is not an end element. If the type of the node is a text, we display it on the screen.
Basically, reading xml files using XmlReader requires you to look carefully at the structure of your XML.

Thursday, 26 April 2012

Select XML Nodes by Attribute Value

Select XML Nodes by Attribute Value [C#]


This example shows how to select nodes from XML document by attribute value. Use method XmlNode.Selec­tNodes to get list of nodes selected by the XPath expression. Suppose we have this XML file.
[XML]
<Names>
    <Name type="M">John</Name>
    <Name type="F">Susan</Name>
    <Name type="M">David</Name>
</Names>

To get all name nodes use XPath expression /Names/Name. To get only male names (to select all nodes with specific XML attribute) use XPath expression /Names/Name[@type='M'].

[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(str);  // suppose that str string contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/Names/Name[@type='M']");
foreach (XmlNode xn in xnList)
{
  Console.WriteLine(xn.InnerText);
}

The output is:
John
David