Wednesday, April 24, 2013

REGISTER FOCEFULLY .dll and .ocx files







Run the command prompt .and register forcefully the .dll and .ocx file into Registery.


Sunday, April 7, 2013

Read from File and Insert Data into Database

 Save abc.txt file as :
PORT_OF_DESTINATION|DESCRIPTION_OF_GOODS|CUSTOMS_TARIFF_HEADING|QUANTITY|UNIT_QUANTITY_CODE|VALUE_OF_GOODS_in_rupees
Piraeus|HESSIAN CLOTH (DETL AS PER INV)(C.E.SEALCARGO)(WE SHALL CLAIM THE BENEFITS AS ADMISSIBLE UNDER CHAPTER 3 OF FTP)|53101013|10880|MTR|540320.75
Piraeus|HESSIAN CLOTH (DETL AS PER INV)(C.E.SEALCARGO)(WE SHALL CLAIM THE BENEFITS AS ADMISSIBLE UNDER CHAPTER 3 OF FTP)|53101013|16000|YDS|603674.53
Singapore|GALV.NON ALLOY STEEL WIRE ROPE (WIRESTEEL CORE) C.E. SEAL, WE INTEND TOCLAIM BENEFITF UNDER CHAPTER 3|73121020|4000|MTR|515590.49
Singapore|UNGALV. STEEL WIRE ROPES (WIRE STEELCORE) C.E. SEAL, WE INTEND TO CLAIMBENEFITF UNDER CHAPTER 3|73121010|1500|MTR|684033.55
Jebel Ali|ELECTROLYTIC TIN PLATE AS PER INVOICE  |72101210|11.115|MTS|598274.78
Jebel Ali|ELECTROLYTIC TIN PLATE AS PER INVOICE  |72101210|24.149|MTS|1235039.42

 then

  public partial class Upload : Form
    {
        DBConnection dbObj = new DBConnection();
        public Upload()
        {
            InitializeComponent();
        }
      
        private void btnInsert_Click(object sender, EventArgs e)
        {
             try
            {
                string directoryPath = string.Empty;

                DialogResult result = openFileDialog1.ShowDialog();
                if (result == DialogResult.OK) // Test result.
                {
                    directoryPath = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
                    MessageBox.Show(directoryPath);                  
                }             
                string allReadText = File.ReadAllText(directoryPath);
                string[] listOfValue = allReadText.Replace("'", "\"").Split('|', '\n');
                string[] list = new string[100000];
                for (int i = 6, k = 0; i < listOfValue.Length; )
                {
                    string temp = string.Empty;
                    int j = 1;
                    while (j < 7)
                    {

                        temp = temp + listOfValue[i] + "|";
                        i++;
                        j++;
                    }                 
                    string[] text = temp.Split('|');
                    Records objRecord = new Records();
                    objRecord.FileId = 1;//take value from Database
                    objRecord.PortOfDescription = text[0];
                    objRecord.DescOfGoods = text[1];
                    objRecord.CustomTariff = text[2];
                    objRecord.Quantity = text[3];
                    objRecord.Unit = text[4];
                    objRecord.RateOfGoods = text[5];
                    objRecord.RecordDate = System.DateTime.Now.Date;//Take date from file creation.
                    dbObj.InsertDataIntoDataBase(objRecord);
                  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Table is finished.");
            }
        }
    }

and use dbconnection class:
 public class DBConnection
    {
        private static string connection = System.Configuration.ConfigurationSettings.AppSettings["ConStr"].ToString();
        private int result = 0;

        /// <summary>
        /// Inserts the data into data base.
        /// </summary>
        /// <param name="objRecord">The obj record.</param>
        internal void InsertDataIntoDataBase(Records objRecord)
        {
            SqlConnection con = null;
            try
            {
                using (con = new SqlConnection(connection))
                {
                    con.Open();

                    using (SqlCommand cmd = new SqlCommand("spInsertSiteRecords", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@FileId",objRecord.FileId);
                        cmd.Parameters.AddWithValue("@PortDest",objRecord.PortOfDescription);
                        cmd.Parameters.AddWithValue("@DescOfGoods",objRecord.DescOfGoods);
                        cmd.Parameters.AddWithValue("@CutomTrf",objRecord.CustomTariff);
                        cmd.Parameters.AddWithValue("@Quantity",objRecord.Quantity);
                        cmd.Parameters.AddWithValue("@Unit",objRecord.Unit);
                        cmd.Parameters.AddWithValue("@RateInRupees",objRecord.RateOfGoods);
                        cmd.Parameters.AddWithValue("@RecordDate",objRecord.RecordDate);
                        result = cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                VMSLog(ex.Message);
                VMSLog(ex.StackTrace);

            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }

        /// <summary>
        /// VMSs the log.
        /// </summary>
        /// <param name="Message">The message.</param>
        public void VMSLog(string Message)
        {
            StreamWriter sw = null;
            try
            {
                string sMonth = "";
                string sLogFormat = DateTime.Now.ToShortDateString().ToString() + DateTime.Now.ToLongTimeString().ToString() + " : ";
                string sPathName = ".\\";
                string sYear = DateTime.Now.Year.ToString();
                if (DateTime.Now.Month < 10)
                    sMonth = "0" + DateTime.Now.Month.ToString();
                else
                    sMonth = DateTime.Now.Month.ToString();
                string sDay = DateTime.Now.Day.ToString();
                string sErrorTime = sDay + "-" + sMonth + "-" + sYear;
                sw = new StreamWriter(sPathName + "VMSLog " + sErrorTime + ".txt", true);
                sw.WriteLine(sLogFormat + Message);
                sw.Flush();

            }
            catch (Exception ex)
            {
                VMSLog(ex.Message);

            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                    sw.Close();
                }
            }
        }
    }

and Recordsclass is data object class:
 public class Records
    {
        public int FileId { get; set; }
        public string PortOfDescription { get; set; }
        public string DescOfGoods { get; set; }
        public string CustomTariff { get; set; }
        public string Quantity { get; set; }
        public string Unit { get; set; }
        public string RateOfGoods { get; set; }
        public DateTime RecordDate { get; set; }

    }

and in App.config file :
 <appSettings>
    <add key="ConStr" value="Data Source=BELAKUR-PC;Initial Catalog=IceGateDB;Integrated Security=True"/>
  </appSettings>

Tuesday, March 19, 2013

SEND MAIL using GMAIL

using windows form you can send your email or sms
page:

after click on Send button:

 private void button1_Click(object sender, EventArgs e)
        {
            string mailBody = txtBody.Text;
            //From:abc@gmail.com
            MailMessage message = new MailMessage("abc@gmail.com", txtTo.Text.Trim(), "Test Mail", mailBody);
         
            AlternateView htmlMail = AlternateView.CreateAlternateViewFromString(mailBody, null, "text/html");
            // Set ContentId property. Value of ContentId property must be the same as
            // the src attribute of image tag in email body.
            message.AlternateViews.Add(htmlMail);
            // your remote SMTP server IP.
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.Credentials = new System.Net.NetworkCredential("your GMAIL ID", "Your Gmail Passowrd");
            smtp.EnableSsl = true;
            smtp.Send(message);
            message = null;
        }

Monday, March 4, 2013

Random example on Format



 DayOfWeek today = DayOfWeek.Thursday;
            string[] format = { "g", "f", "D", "x" }; //Format String can be only "G", "g", "X", "x", "F", "f", "D" or "d".
            foreach (string item in format)
            {
                Console.WriteLine(today.ToString(item));
            }
            Console.ReadKey();

From MSDN site ,best example of HashTable


public static void Main()
        {
            // Create a new hash table.
            //
            Hashtable openWith = new Hashtable();

            // Add some elements to the hash table. There are no
            // duplicate keys, but some of the values are duplicates.
            openWith.Add("txt", "notepad.exe");
            openWith.Add("bmp", "paint.exe");
            openWith.Add("dib", "paint.exe");
            openWith.Add("rtf", "wordpad.exe");
            openWith["giri"] = "giriword.exe";

            IDictionaryEnumerator ide = openWith.GetEnumerator();
            while (ide.MoveNext())
                Console.WriteLine(ide.Key + " is related with " + ide.Value);

            ICollection ic = openWith.Keys;
            foreach (string item in ic)
            {
                Console.WriteLine(openWith[item]);
            }

            //// The Add method throws an exception if the new key is
            //// already in the hash table.
            //try
            //{
            //    openWith.Add("txt", "winword.exe");
            //}
            //catch
            //{
            //    Console.WriteLine("An element with Key = \"txt\" already exists.");
            //}

            //// The Item property is the default property, so you
            //// can omit its name when accessing elements.
            //Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

            //// The default Item property can be used to change the value
            //// associated with a key.
            //openWith["rtf"] = "winword.exe";
            //Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

            //// If a key does not exist, setting the default Item property
            //// for that key adds a new key/value pair.
            //openWith["doc"] = "winword.exe";

            //// ContainsKey can be used to test keys before inserting
            //// them.
            //if (!openWith.ContainsKey("ht"))
            //{
            //    openWith.Add("ht", "hypertrm.exe");
            //    Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]);
            //}

            //// When you use foreach to enumerate hash table elements,
            //// the elements are retrieved as KeyValuePair objects.
            //Console.WriteLine();
            //foreach (DictionaryEntry de in openWith)
            //{
            //    Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
            //}

            //// To get the values alone, use the Values property.
            //ICollection valueColl = openWith.Values;

            //// The elements of the ValueCollection are strongly typed
            //// with the type that was specified for hash table values.
            //Console.WriteLine();
            //foreach (string s in valueColl)
            //{
            //    Console.WriteLine("Value = {0}", s);
            //}

            //// To get the keys alone, use the Keys property.
            //ICollection keyColl = openWith.Keys;

            //// The elements of the KeyCollection are strongly typed
            //// with the type that was specified for hash table keys.
            //Console.WriteLine();
            //foreach (string s in keyColl)
            //{
            //    Console.WriteLine("Key = {0}", s);
            //}

            //// Use the Remove method to remove a key/value pair.
            //Console.WriteLine("\nRemove(\"doc\")");
            //openWith.Remove("doc");

            //if (!openWith.ContainsKey("doc"))
            //{
            //    Console.WriteLine("Key \"doc\" is not found.");
            //}
            Console.ReadKey();
        }

Dictionary method with IEqualityComparer method


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

namespace BInnovitec.Abstract
{
    public class Employee
    {
        public string rollNumber { get; set; }
        public string name { get; set; }
        public string branch { get; set; }

        public static ArrayList GetEmployeeArrayList()
        {
            ArrayList alEmployee = new ArrayList();
            alEmployee.Add(new Employee { rollNumber = "1", name = "Girijesh", branch = "CS" });
            alEmployee.Add(new Employee { rollNumber = "2", name = "Srijesh", branch = "ME" });
            return alEmployee;
        }
        public static Employee[] GetEmployeeArray()
        {
            //their are 2methods defined here use anyone.
            return (GetEmployeeArrayList().Cast<Employee>().ToArray());
            //return ((Employee[])GetEmployeeArrayList().ToArray(typeof(Employee)));
        }
    }

    public class MyStringFieldNumberComparer : IEqualityComparer<string>
    {
        public bool Equals(string x, string y)
        {
            return (Int32.Parse(x) == Int32.Parse(y));
        }
        public int GetHashCode(string obj)
        {
            return Int32.Parse(obj).ToString().GetHashCode();
        }
    }
    //refrence from java2s.com
    public class Program
    {
        static void Main(string[] args)
        {
            CompleExampleOfArrayListWithDictionary();
            Console.ReadKey();
        }

        private static void CompleExampleOfArrayListWithDictionary()
        {
            Dictionary<String, Employee> employeeArrayDataRecord = Employee.GetEmployeeArray().ToDictionary(k => k.rollNumber, new MyStringFieldNumberComparer());
            string[] userInput = { "01", "0001", "000001","000000001 " };
            foreach (string input in userInput)
            {
                Employee e = employeeArrayDataRecord[input];
                Console.WriteLine("Employee whose rollnumber is == \"{0}\" : {1} {2}", input, e.name, e.branch);
            }
        }
    }
}

==================================================================

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

namespace BInnovitec.Abstract
{
    public class Employee
    {
        public int rollNumber { get; set; }
        public string name { get; set; }
        public string branch { get; set; }

        public static ArrayList GetEmployeeArrayList()
        {
            ArrayList alEmployee = new ArrayList();
            alEmployee.Add(new Employee { rollNumber = 1, name = "Girijesh", branch = "CS" });
            alEmployee.Add(new Employee { rollNumber = 2, name = "Srijesh", branch = "ME" });
            return alEmployee;
        }
        public static Employee[] GetEmployeeArray()
        {
            //their are 2methods defined here use anyone.
            return (GetEmployeeArrayList().Cast<Employee>().ToArray());
            //return ((Employee[])GetEmployeeArrayList().ToArray(typeof(Employee)));
        }
    }

    public class MyStringFieldNumberComparer : IEqualityComparer<string>
    {
        public bool Equals(string x, string y)
        {
            return (Int32.Parse(x) == Int32.Parse(y));
        }
        public int GetHashCode(string obj)
        {
            return Int32.Parse(obj).ToString().GetHashCode();
        }
    }  
    public class Program
    {
        static void Main(string[] args)
        {
            CompleExampleOfArrayListWithDictionary();
            Console.ReadKey();
        }

        private static void CompleExampleOfArrayListWithDictionary()
        {
            Dictionary<int, string> employeeArrayDataRecord = Employee.GetEmployeeArray().ToDictionary(k => k.rollNumber, i => string.Format("{0}, {1}", i.name, i.branch));
            int[] userInput = { 1,2 };
            foreach (int input in userInput)
            {
                string name = employeeArrayDataRecord[input];
                Console.WriteLine("Employee information in string format is ={0}", name);
            }
        }
    }
}




Factory Design Pattern(reference java2s )


using System;
using System.Collections;

namespace FactoryDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Page p = new CatalogPage();
            p.AddMoudle();
            p.DisplayPage();
            p = new ManualPage();
            p.AddMoudle();
            p.DisplayPage();
            Console.ReadLine();
        }
    }

    public abstract  class Page
    {
        protected ArrayList pageCompositor = new ArrayList();
        public abstract void AddMoudle();
        public abstract void DisplayPage();
             
    }

    public class CatalogPage : Page
    {
        public CatalogPage() { this.AddMoudle(); }
        public override void AddMoudle()
        {
            this.pageCompositor.Clear();
            this.pageCompositor.Add(new FeatureModule());
            this.pageCompositor.Add(new PictureModule());
        }

        public override void DisplayPage()
        {
            foreach (Module item in this.pageCompositor)
                item.SomeModule();
        }
    }

    public class FeatureModule :Module
    {
        public FeatureModule() { }
        public override void SomeModule()
        {
            Console.WriteLine("Feature content.");
        }
    }

    public class PictureModule : Module
    {
        public PictureModule() { }
        public override void SomeModule()
        {
            Console.WriteLine("Picture content.");
        }
    }

    public abstract  class Module
    {
        public abstract void SomeModule();
    }

    public class ManualPage : Page
    {
        public ManualPage() { }
        public override void AddMoudle()
        {
            this.pageCompositor.Clear();
            this.pageCompositor.Add(new TechnicalModule());
            this.pageCompositor.Add(new PictureModule());
            this.pageCompositor.Add(new InstructionModule());
        }

        public override void DisplayPage()
        {
            Console.WriteLine("Manual page contents: ");
            foreach(Module c in this.pageCompositor)
                c.SomeModule();
            Console.WriteLine();
        }
    }

    public class TechnicalModule :Module
    {
        public override void SomeModule()
        {
            Console.WriteLine("Techinical content.");
        }
    }

    public class InstructionModule :Module
    {
        public override void SomeModule()
        {
            Console.WriteLine("Instruction content.");
        }
    }
}

Dictionary Method


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

namespace BInnovitec.Abstract
{
    //refrence from java2s.com
    class Program
    {
        static void Main(string[] args)
        {
            CompleExampleOfArrayListWithDictionary();
            // AbstractFunction();
            // AggregateProgram();
          //  ConvertArrayToDictionary();
            Console.ReadLine();
        }

        private static void ConvertArrayToDictionary()
        {
            var employeeRecord = new[] {
                new {Name="Rajesh",Age=12,Branch="CS"},
                new {Name="Girijesh",Age=23,Branch="ME"},
                new {Name="Mahesh",Age=24,Branch="EC"}};
            var employeeDictionary = employeeRecord.ToDictionary(employeeKey => employeeKey.Name);
            Console.WriteLine("{0} age is :{1} and branch is:{2}", employeeDictionary["Girijesh"].Name, employeeDictionary["Girijesh"].Age, employeeDictionary["Girijesh"].Branch);
        }

  private static void CompleExampleOfArrayListWithDictionary()
        {
            Dictionary<int, Employee> employeeArrayDataRecord = Employee.GetEmployeeArray().ToDictionary(k => k.rollNumber);
            foreach (var emp in employeeArrayDataRecord)
            {
                Console.WriteLine(emp.Value.name+""+emp.Value.branch+""+emp.Value.rollNumber);
            }
        }
 public class Employee
    {
        public int rollNumber { get; set; }
        public string name { get; set; }
        public string branch { get; set; }

        public static ArrayList GetEmployeeArrayList()
        {
            ArrayList alEmployee = new ArrayList();
            alEmployee.Add(new Employee { rollNumber = 1, name = "Girijesh", branch = "CS" });
            alEmployee.Add(new Employee { rollNumber = 2, name = "Srijesh", branch = "ME" });
            return alEmployee;
        }
        public static Employee[] GetEmployeeArray()
        {
            //their are 2methods defined here use anyone.
            return (GetEmployeeArrayList().Cast<Employee>().ToArray());
            //return ((Employee[])GetEmployeeArrayList().ToArray(typeof(Employee)));
        }
    }

        private static void AggregateProgram()
        {
            int number = 4;
            IEnumerable<int> sequenceNumber = Enumerable.Range(1, number);
            foreach (var item in sequenceNumber)
            {
                Console.WriteLine(item);
            }
            // int[] sequenceNumber = {1,2,3,4,5 };
            var result = sequenceNumber.Aggregate((a, b) => a * b);
            Console.WriteLine("1*2*..*number = {0} ", result);
            result = sequenceNumber.Aggregate(0, (p, q) => p + q);
            Console.WriteLine("1+2+..+number = {0} ", result);
            var testResult = from m in typeof(int).GetMethods()
                             group m by m.Name into gBy
                             select gBy;
            Dictionary<string, int> myDictionary = testResult.ToDictionary(k => k.Key, k => k.Count());
            foreach (var item in myDictionary)
            {
                Console.WriteLine("The key is:{0} and value is:{1}", item.Key, item.Value);

            }
        }

        private static void AbstractFunction()
        {
            MotorVehicle mvc = new MotorVehicle("BMW", "$10008");
            mvc.ShowNameAndPrice();
        }
    }

    public class MotorVehicle : Vehicle
    {
        public MotorVehicle(string name, string price)
            : base(name, price)
        {
            //ToDO
        }

        public override void ShowNameAndPrice()
        {
            Console.WriteLine("The name of Car is :{0} and price tag ={1} ");
            Console.WriteLine(nameV + "" + priceV);
        }
    }

    public abstract class Vehicle
    {
        public string nameV;
        public string priceV;
        public Vehicle(string name, string price)
        {
            // TODO: Complete member initialization
            this.nameV = name;
            this.priceV = price;
        }
        public abstract void ShowNameAndPrice();
    }
}
=================================================

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

namespace BInnovitec.Abstract
{
    //refrence from java2s.com
    public class Program
    {
        static void Main(string[] args)
        {
            #region Using constructor
            ArrayList list = new ArrayList();
            list.Add(new Instrument("computer", 12.23, 2));
            list.Add(new Instrument("printer", 2.23, 4));
            foreach (var item in list)
            {
                Console.WriteLine(item);
            }
            #endregion          
                Console.ReadKey();
        }

     
    }

    public class Instrument
    {
        public string name { get; set; }
        public double cost { get; set; }
        public int quantity { get; set; }

        public Instrument(string itemName, double money, int number)
        {
            this.name = itemName;
            this.cost = money;
            this.quantity = number;
        }

        public override string ToString()
        {
            return String.Format("{0,-10}Cost: {1,6:C}  Quantity: {2}", name, cost, quantity);
        }
    }
}

Saturday, March 2, 2013

Chain design patter using school life example


in ChainOfResponsibilityPatternThroughSchool class:-
--------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GuideLines
{
   public class ChainOfResponsibilityPatternThroughSchool
    {
        public abstract class Chain
        {
            protected Chain nextClassInChain;
            public abstract void DealWithRequirement(string requirement);
            public void NextInChain(Chain next)
            {
                this.nextClassInChain = next;
            }
        }

        public class Highschool : Chain
        {

            public override void DealWithRequirement(string requirement)
            {
                switch (requirement)
                {
                    case "10th":
                        Console.WriteLine("{0} staff", this);
                        break;
                    default:
                        if (nextClassInChain != null)
                            nextClassInChain.DealWithRequirement(requirement);
                            break;
                }
            }
        }
        public class Intermediate : Chain
        {

            public override void DealWithRequirement(string requirement)
            {
                switch (requirement)
                {
                    case "12th": Console.WriteLine("{0} requirement.",this);
                        break;
                    default:
                        if (nextClassInChain != null)
                            nextClassInChain.DealWithRequirement(requirement);
                        break;
                }
            }
        }
        public class Btech : Chain
        {

            public override void DealWithRequirement(string requirement)
            {
                switch (requirement)
                {
                    default: Console.WriteLine("{0} has managed the {1} ",requirement ,this);
                        break;
                }
            }
           public Btech() { ;}
        }
    }
}
==============================================
and on Program.cs part
   public class Program : ChainOfResponsibilityPatternThroughSchool
    {
        public static void Main(string[] args)
        {
          
            #region Chain pattern with Hirarchy level

            Chain boy = new Highschool();
            Chain student = new Intermediate();
            Chain engineer = new Btech();

            boy.NextInChain(student);
            student.NextInChain(engineer);

            boy.DealWithRequirement("BTech");
            boy.DealWithRequirement("12th");
            boy.DealWithRequirement("Intermediate");
            boy.DealWithRequirement("10th");
            Console.ReadLine();
            #endregion
       }
}