Monday, June 24, 2013

Adding attributes to an XML node in c#

XmlDocument doc = new XmlDocument();
//Create Root Element
XmlElement root = doc.CreateElement("Datasource");
//Create Var Tag Node
XmlElement var = doc.CreateElement("var");
//Apply Host Name Attribute to the var element
var.SetAttribute("name", "Host");
// create innertext element for var
XmlElement str = doc.CreateElement("string");
str.InnerText = "127.0.0.1";
//add inntertext element to the var node
var.AppendChild(str);
//add var node in root node
root.AppendChild(var);

var = doc.CreateElement("var");
var.SetAttribute("name", "Database");
str = doc.CreateElement("string");
str.InnerText = "TestDB";
var.AppendChild(str);
root.AppendChild(var);

var = doc.CreateElement("var");
var.SetAttribute("name", "Username");
str = doc.CreateElement("string");
str.InnerText = "Root";
var.AppendChild(str);
root.AppendChild(var);

var = doc.CreateElement("var");
var.SetAttribute("name", "Password");
str = doc.CreateElement("string");
str.InnerText = "Root123";
var.AppendChild(str);
root.AppendChild(var);
doc.AppendChild(root);
//Create Xml File To Application Start up Path Folder
doc.Save(Application.StartupPath + "_datasource.xml");

how to get files and folder name in zip file c# ICSharpCode.SharpZipLib.Zip

ZipInputStream zip = new ZipInputStream( File.OpenRead(path));
            ZipEntry item;
            while ((item = zip.GetNextEntry()) != null )
            {
                Console.WriteLine(item.Name);
            }

Saturday, June 22, 2013

What is MySQLDUMP And How To Use In C#

What is MySQLDUMP?

The mysqldump is console based executable utility and it allows us to assign a host of options to get the backup of a database to a file, a different MySQL server running anywhere in the world .
In fact MySQL does not backup our data instead of that it executes a set of basic sql syntaxes like "create table" and "insert into" in the MySQL server to re-create the database/s. 
The mysqldump utility is present in the root directory of mysql, let us assume it is c:\mysql and you could find a folder bin in that directory. Using the mysqldump utility we can provide several commands so that we can change the way of taking backups.


1.Using This Command First You Will Download XAMPP

2.And Install It

3.After Installing Open Command Prompt

4.Go to [C:\xampp\mysql\bin] Folder Using cd Command

Like CD C:\xampp\mysql\bin

5.Now Type Command

mysqldump -hHostname -uUsername DatabaseName > FileName


Example

mysqldump -h127.0.0.1 -uroot TestDB > TestDB.sql

With Password

mysqldump -h127.0.0.1 -uroot -p123 TestDB > TestDB.sql

Now In C#

if (File.Exists(Application.StartupPath + "\\mysqldump.exe"))

{
   try
   {
       using (StreamWriter sw = new StreamWriter (Application.StartupPath + "\\dump.bat"))
       {
sw.Write("mysqldump -h127.0.0.1 -uroot -p123 TestDB > TestDB.sql");
sw.Close();
       }
       Shell(Application.StartupPath + "\\dump.bat", AppWinStyle.Hide , false);
   File.Delete(Application.StartupPath + "\\dump.bat");
   }
   catch (Exception ex)
   {}
}
else
{
      MessageBox.Show("MySqlDump.Exe Not Found.");
}

Tuesday, June 18, 2013

download HTML Source in C#

using System.Net;

private string DownloadPagesource(string Url)

        WebClient wc = new WebClient();
        return wc.DownloadString(Url); 
}


//This Method Return You To Website Page Source Code

Thursday, June 13, 2013

C# Code to count kbps and download files from url

using System;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace Example
{
    public partial class Form1 : Form
    {

        string FileURL = "www.google.com";//your Url

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DownloadString(FileURL);
        }

        private void DownloadString(string URLStr)
        {
            WebClient WC = new WebClient();
            WC.DownloadProgressChanged += new DownloadProgressChangedEventHandler(WC_DownloadProgressChanged);
            WC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(WC_DownloadStringCompleted);
            WC.DownloadStringAsync(new Uri(URLStr));

        }
        string Result = "";
        void WC_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            Result = e.Result;
        }

        void WC_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            //Progress Bar
            PBarCsv.Value = (int)((e.BytesReceived * 100) / e.TotalBytesToReceive);
            //Label For You File Total Byte
            LblTotByt.Text = "Total Bytes : " + e.TotalBytesToReceive.ToString();
            //Label For Remaining Bytes
            LblRemByt.Text = "Remain Bytes : " + (e.TotalBytesToReceive - e.BytesReceived).ToString();
            //Label For Current KBPS Download Speed
            lblSpeed.Text = "KBPS : " + ConvertBytes(e.BytesReceived).ToString() + " Speed";
        }

        private double ConvertBytes(long bytes)
        {
            return (bytes / 1024);
            //return (bytes / 1024f) / 1024f;
        }        

Wednesday, June 12, 2013

Ready State Property For Gecko.GeckoWebBrowser in c#,Wait Until Gecko.GeckoWebBrowser Is Busy,Workin and Loading

//Replace webbrowser.Readystate To This Method

private void WaitBrowser(Gecko.GeckoWebBrowser wb)
        {
            while (wb.IsBusy)
            {
                Application.DoEvents();
            }
        }


//Webbrowser Control Have Property To Check Browser Control Is 
//Loading Or Not In Same Way In Gecko.GeckoWebBrowser Try This 
//Code I Also Try IT

Alternative of Webbrowser is Webkit.Webbrowser

Tuesday, June 11, 2013

Set Webbrowser Input Box Value In C# application

//wb as webbrowser

//if element have not assign id attribute
foreach (HtmlElement item in wb.Document.GetElementsByTagName("input")) 
             if (item != null && item.Name == "password")
             { 
                         item.SetAttribute("Value", "admin123");                                                             
                         break;
             }
}//if element have assign id attribute

HtmlElement Userid = wb.Document.GetElementById("username");
Userid.SetAttribute("Value", "admin");


Monday, June 10, 2013

Delegate In C#

using System;

namespace ConsoleApplication1
{
    class Program
    {
        public delegate void Del(string message);
        static void Main(string[] args)
        {
            // Instantiate the delegate.
            Del handler = DelegateMethod;

            // Call the delegate.
            for (int i = 0; i < 9; i++)
            {
                handler("Hello World " + i.ToString());
            }

            
            Console.ReadKey();
        }

        // Create a method for a delegate. 
        public static void DelegateMethod(string message)
        {
            System.Console.WriteLine(message);
        }
    }
}

Result
Hello World 0
Hello World 1
Hello World 2
Hello World 3
Hello World 4
Hello World 5
Hello World 6
Hello World 7
Hello World 8

Properties In C#

using System;
class Student
{

   // Declare a Code property of type string
   private string iCode = "Nothing";
   public string Code
   {
      get
      {
         return iCode;
      }
      set
      {
         iCode = value;
      }
   }
   
   // Declare a Name property of type string
   private string iName = "Alfread";
   public string Name
   {
      get
      {
         return iName;
      }
      set
      {
         iName= value;
      }
   }

   // Declare a Age property of type int:
   private int iAge= 15;
   public int Age
   {
      get
      {
         return iAge;
      }
      set
      {
         iAge = value;
      }
   }
   public override string ToString()
   {
      return "Code = " + iCode+", Name = " + iName + ", Age = " + iAge ;
   }

   public static void Main()
   {
      // Create a new Student object:
      Student s = new Student();
            
      // Setting code, name and the age of the student
      s.Code = "001";
      s.Name = "Zara";
      s.Age = 9;
      Console.WriteLine("Student Info: {0}", s);
      //let us increase age
      s.Age += 1;
      Console.WriteLine("Student Info: {0}", s);
      Console.ReadKey();
    }
}

C# Read And Write Byte In File With File Stream

using System;
using System.IO;

namespace FileIOApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream F = new FileStream("test.dat", 
            FileMode.OpenOrCreate, FileAccess.ReadWrite);

            for (int i = 1; i <= 20; i++)
            {
                F.WriteByte((byte)i);
            }

            F.Position = 0;

            for (int i = 0; i <= 20; i++)
            {
                Console.Write(F.ReadByte() + " ");
            }
            F.Close();
            Console.ReadKey();
        }
    }
}

C# Creating User Defined Exceptions

using System;
namespace UserDefinedException
{
   class TestTemperature
   {
      static void Main(string[] args)
      {
         Temperature temp = new Temperature();
         try
         {
            temp.showTemp();
         }
         catch(TempIsZeroException e)
         {
            Console.WriteLine("TempIsZeroException: {0}", e.Message);
         }
         Console.ReadKey();
      }
   }
}
public class TempIsZeroException: ApplicationException
{
   public TempIsZeroException(string message): base(message)
   {
   }
}
public class Temperature
{
   int temperature = 0;
   public void showTemp()
   {
      if(temperature == 0)
      {
         throw (new TempIsZeroException("Zero Temperature found"));
      }
      else
      {
         Console.WriteLine("Temperature: {0}", temperature);
      }
   }
}

C# Exception Handling

try
{
   // statements causing exception
}
catch( ExceptionName e1 )
{
   // error handling code
}
catch( ExceptionName e2 )
{
   // error handling code
}
catch( ExceptionName eN )
{
   // error handling code
}
finally
{
   // statements to be executed
}

try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.

catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

throw: A program throws an exception when a problem shows up. This is done using a throw keyword.

Example

using System;
namespace ErrorHandlingApplication
{
    class DivNumbers
    {
        int result;
        DivNumbers()
        {
            result = 0;
        }
        public void division(int num1, int num2)
        {
            try
            {
                result = num1 / num2;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Exception caught: {0}", e);
            }
            finally
            {
                Console.WriteLine("Result: {0}", result);
            }

        }
        static void Main(string[] args)
        {
            DivNumbers d = new DivNumbers();
            d.division(25, 0);
            Console.ReadKey();
        }
    }

}

C# Namespaces

using System;
namespace first_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside first_space");
      }
   }
}
namespace second_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside second_space");
      }
   }
}  
class TestClass
{
   static void Main(string[] args)
   {
      first_space.namespace_cl fc = new first_space.namespace_cl();
      second_space.namespace_cl sc = new second_space.namespace_cl();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

C# Interfaces

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InterfaceApplication
{

public interface ITransactions
{
    // interface members
    void showTransaction();
    double getAmount();
}

public class Transaction : ITransactions
{
    private string tCode;    private string date;
    private double amount;


    public Transaction()
    {
        tCode = " ";
        date = " ";
        amount = 0.0;
    }
    public Transaction(string c, string d, double a)    {
        tCode = c;
        date = d;
        amount = a;
    }    public double getAmount()    {
        return amount;
    }    public void showTransaction()    {
        Console.WriteLine("Transaction: {0}", tCode);
        Console.WriteLine("Date: {0}", date);        Console.WriteLine("Amount: {0}", getAmount());
    }
}
    class Tester
    {
       static void Main(string[] args)
        {            Transaction t1 = new Transaction("001", "8/10/2012",         78900.00);
            Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);

            t1.showTransaction();
            t2.showTransaction();

            Console.ReadKey();
        }
    }
}

Result:
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

C# Inheritance

Base and Derived Classes

A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base class or interface.


The syntax used in C# for creating derived classes is as follows:


class

{
 ...
}
class :
{
 ...
}

Example


using System;

namespace InheritanceApplication
{
   class Shape 
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // Derived class

   class Rectangle: Shape
   {
      public int getArea()
      { 
         return (width * height); 
      }
   }
   
   class RectangleTester
   {
      static void Main(string[] args)
      {
         Rectangle Rect = new Rectangle();

         Rect.setWidth(5);

         Rect.setHeight(7);

         // Print the area of the object.

         Console.WriteLine("Total area: {0}",  Rect.getArea());
         Console.ReadKey();
      }
   }

}

Result

Total area: 35

C# Declaring enum Variable

Example
using System;
namespace EnumApplication
{
    class EnumProgram
    {
        enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
        static void Main(string[] args)
        {
             int WeekdayStart = (int)Days.Mon;
             int WeekdayEnd = (int)Days.Fri;
             Console.WriteLine("Monday: {0}", WeekdayStart);
             Console.WriteLine("Friday: {0}", WeekdayEnd);
             Console.ReadKey();
        }
    }
}

Result
Monday:1
Friday:5

C# Defining a Structure

struct Books
{
   public string title;
   public string author;
   public string subject;
   public int book_id;
};

The following program shows the use of the structure:

using System;
   
struct Books
{
   public string title;
   public string author;
   public string subject;
   public int book_id;
};

public class testStructure
{
   public static void Main(string[] args)
   {

      Books Book1;        /* Declare Book1 of type Book */
      Books Book2;        /* Declare Book2 of type Book */

      /* book 1 specification */
      Book1.title = "C# Programming";
      Book1.author = "Ali Rabjar";
      Book1.subject = "C# Programming";
      Book1.book_id = 123456;

      /* book 2 specification */
      Book2.title = "Billing";
      Book2.author = "Ali";
      Book2.subject =  "Billing";
      Book2.book_id =56789123;

      /* print Book1 info */
      Console.WriteLine( "Book 1 title : {0}", Book1.title);
      Console.WriteLine("Book 1 author : {0}", Book1.author);
      Console.WriteLine("Book 1 subject : {0}", Book1.subject);
      Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);

      /* print Book2 info */
      Console.WriteLine("Book 2 title : {0}", Book2.title);
      Console.WriteLine("Book 2 author : {0}", Book2.author);
      Console.WriteLine("Book 2 subject : {0}", Book2.subject);
      Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);    

      Console.ReadKey();

   }
}

it produces following result:

Book 1 title : C# Programming
Book 1 author : Ali Rabjar
Book 1 subject : C# Programming
Book 1 book_id : 123456
Book 2 title : Billing
Book 2 author : Ali
Book 2 subject : Billing
Book 2 book_id : 56789123

C# The Null Coalescing Operator (??)

using System;

namespace CalculatorApplication
{
   class NullablesAtShow
   {
         
      static void Main(string[] args)
      {
         
         double? num1 = null;
         double? num2 = 3.14157;
         double num3;
         num3 = num1 ?? 5.34;      
         Console.WriteLine(" Value of num3: {0}", num3);
         num3 = num2 ?? 5.34;
         Console.WriteLine(" Value of num3: {0}", num3);
         Console.ReadLine();

      }
   }
}
When the above code is compiled and executed, it produces following result:
Value of num3: 5.34
Value of num3: 3.14157

Nullable in C#

C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable< Int32 > variable. Similarly, you can assign true, false or null in a Nullable< bool > variable. Syntax for declaring a nullable type is as follows:
< data_type> ?  = null;
The following example demonstrates use of nullable data types:
using System;
namespace CalculatorApplication
{
   class NullablesAtShow
   {
      static void Main(string[] args)
      {
         int? num1 = null;
         int? num2 = 45;
         double? num3 = new double?();
         double? num4 = 3.14157;
         
         bool? boolval = new bool?();

         // display the values
         
         Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}", 
                            num1, num2, num3, num4);
         Console.WriteLine("A Nullable boolean value: {0}", boolval);
         Console.ReadLine();

      }
   }
}
When the above code is compiled and executed, it produces following result:
Nullables at Show: , 45,  , 3.14157
A Nullable boolean value: