Tuesday 21 February 2012

Creating csv file and editable dropdown with xml saving





 <?xml version="1.0" encoding="us-ascii" standalone="yes"?>
<Masters>

 <DESIGNATION>
    <DISG>Additional Inspector General  A/C</DISG>  
  </DESIGNATION>
</Masters>



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Net.NetworkInformation;
using System.Management;
  public partial class A: Form
  {
        string sourcefile = Application.StartupPath + "\\Master.xml";
         int cmbDDODesignationflag = 0;

           private void A_Load(object sender, EventArgs e)
        {

                   loadmasters();

        }

         public void loadmasters()
        {
            #region : XML Parsing to load all ComboBox fields :
            try
            {

               // address();
                XmlDocument doc = new XmlDocument();
                doc.Load(sourcefile);
                         
                XmlNodeList DDODISGNode = doc.GetElementsByTagName("DISG");
                foreach (XmlNode Node3Node in DDODISGNode)
                {
                    //These nodes contain the data we want so lets add it to our List.
                    cmbDDODesignation.Items.Add(Node3Node.InnerText.ToString().Trim());
                }             

            }
            catch (Exception ex)
            {
                Logging.Logflatfile_Ex(ex);
            }

            #endregion
        }

    public void updatemasters()
        {
            try
            {
                //FileStream fxml = new FileStream(sourcefile, FileMode.OpenOrCreate);
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(sourcefile);

                if (cmbDDODesignationflag == 1)
                {

                    // find channel element to append to
                    var channels = xDoc.GetElementsByTagName("DESIGNATION", string.Empty);

                    // if no channel tags then exit
                    if (channels.Count == 0)
                        return;
                    // create new item
                    var newItem = xDoc.CreateElement("DISG");
                    // add attributes (with value)
                    // Note: You do not have any attributes in your xml.
                    // This is added to show you how to do it and what the effect is.

                    newItem.InnerText = cmbDDODesignation.Text.ToString().Trim();

                    channels[0].AppendChild(newItem);
                    // add new item to first channel         
                    xDoc.Save(sourcefile);
                    cmbDDODesignation.Items.Add(cmbDDODesignation.Text.ToString().Trim());
                }
               
                          }
            catch (Exception ex)
            {
                MessageBox.Show("Exception Occurred.", "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Logging.Logflatfile_Ex(ex);
            }

        }

     private void cmbDDODesignation_Leave(object sender, EventArgs e)
        {
            string cmbDDODesignationNewItem = string.Empty;
            cmbDDODesignationNewItem = this.cmbDDODesignation.Text.ToString().Trim();

            // If there is no flavor to add, do nothing
            if (cmbDDODesignationNewItem == string.Empty)
            {
                cmbDDODesignationflag = 0;
                return;
            }
            else
            {
                if (this.cmbDDODesignation.FindStringExact(cmbDDODesignationNewItem) != -1)
                {
                   
                //if (cmbDDODesignation.Items.Contains(cmbDDODesignationNewItem.ToUpper()) || cmbDDODesignation.Items.Contains(cmbDDODesignationNewItem.ToLower()))
                // {
                    //MessageBox.Show(NewItem + " exists already in the list and will not be added.");
                    cmbDDODesignationflag = 0;
                    return;
                }
                else
                {
                    //this.cmbDDODesignation.Items.Add(cmbDDODesignationNewItem);
                    cmbDDODesignationflag = 1;

                }

            }

          
        }

public void createCSVFromDatable()
        {
            try
            {
                DataTable dt = new DataTable();
                #region : Assigning Fields data to DataTable :

             
                                                   
                dt.Columns.Add("DDODisgnation");
                 dt.Columns.Add("DateTime");            



                                DataRow dr = dt.NewRow();

              
                             
                dr["DDODisgnation"] = cmbDDODesignation.Text.Trim();
                   dr["DateTime"] = DateTime.Now.ToString();
             




                          

              
                dt.Rows.Add(dr);
                #endregion
                destcsvfile = Application.StartupPath + "\\A.csv";
                string newFileName = destcsvfile;


                string clientDetails =     dr["DDODisgnation"].ToString().Trim() + ","             
                                     
                                      + dr["DateTime"].ToString().Trim() + Environment.NewLine;


                if (!File.Exists(newFileName))
                {
                    string clientHeader =  "DDODisgnation".Trim() + ","                                                       
                                        + "DateTime".Trim() + Environment.NewLine;

                    File.WriteAllText(newFileName, clientHeader);
                    File.AppendAllText(newFileName, clientDetails);

                }
                else
                {
                    File.AppendAllText(newFileName, clientDetails);
                }

                if (File.Exists(destcsvfile))
                {
                    MessageBox.Show("Record Created Sucessfully for " + txtFirstName.Text + "\n with Unique ID: " + dr["UniqueID"], "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        updatemasters();

                }
                else
                {
                    MessageBox.Show("Unable to create csv file", "Fail", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception Occurred.", "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Logging.Logflatfile_Ex(ex);
            }

        }


    

Creating zip files with password using 7zip sharp library

 steps:
=====
 1)download SevenZipSharp from http://sevenzipsharp.codeplex.com/ 
 and 7z.dll from http://www.dll-files.com/dllindex/dll-files.shtml?7z

2) 7z.dll and SevenZipSharp.dll to bin folder
3)refer "SevenZipSharp.dll" to u r project by add reference window



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Diagnostics;

using SevenZip;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Globalization;

Compress and create password:
======================
                    string sourcefile = Path.GetTempPath() + txtName.Text + "_" + txtGenreralNo.Text + ".xml";
 if (File.Exists(sourcefile))
                    {

                        SaveFileDialog sd = new SaveFileDialog();
                        sd.Filter = "ZIP Files(*.7z)|*.7z";
                        sd.FileName = txtName.Text + "_" + txtGenreralNo.Text;
                        //  sd.ShowDialog();

                        if (sd.ShowDialog() == DialogResult.OK)
                        {
                            string destfile = sd.FileName;


                            CompressFileLZMA(sourcefile, destfile, "mohan");

                            MessageBox.Show(destfile + " is created sucessfully");

                            File.Delete(sourcefile);

                            Reset();
                        }
                        else
                        {

                        }
                    }
                    else
                    {                       
                        MessageBox.Show("Error while saving details");
                    }


private static void CompressFileLZMA(string inFile, string outFile, string password)
        {
            SevenZipCompressor.SetLibraryPath(Application.StartupPath + "\\7z.dll");
            //----------------------------------------
            SevenZip.SevenZipCompressor szc = new SevenZip.SevenZipCompressor();
            //if (File.Exists(outFile))
            //    szc.CompressionMode = SevenZip.CompressionMode.Append;
            //else
            //szc.CompressionMode = SevenZip.CompressionMode.Create;

            FileStream archive1 = new FileStream(inFile, FileMode.Open);
            string file = archive1.Name.Remove(0, archive1.Name.LastIndexOf('\\') + 1);
            FileStream archive2 = new FileStream(outFile, FileMode.Create);
            try
            {
                szc.DirectoryStructure = true;
                szc.EncryptHeaders = true;
                szc.DefaultItemName = file; //if the full path given the folders are also created
                szc.CompressStream(archive1, archive2, password);
            }
            catch (Exception e)
            {
                Logging.Logflatfile_Ex(e);
            }
            archive1.Close();
            archive2.Close();
            //---------------------------------

            //SevenZipCompressor mSevenZipCompressor = new SevenZipCompressor
            //{
            //    ArchiveFormat = OutArchiveFormat.SevenZip,
            //    CompressionMethod = CompressionMethod.Lzma2,
            //    CompressionMode = CompressionMode.Create,
            //    DirectoryStructure = false,

            //    CompressionLevel = CompressionLevel.Normal

            //};


            //SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();
            //FileStream input = new FileStream(inFile, FileMode.Open);
            //FileStream output = new FileStream(outFile, FileMode.Create);
            //// Write the encoder properties
            //coder.WriteCoderProperties(output);

            //// Write the decompressed file size.
            //output.Write(BitConverter.GetBytes(input.Length), 0, 8);

            //// Encode the file.
            //coder.Code(input, output, input.Length, -1, null);


            //output.Flush();
            //output.Close();
        }
decompress and remove  the password
===========================
private void btnDecompress_Click(object sender, EventArgs e)
        {



            SevenZipExtractor.SetLibraryPath(Application.StartupPath + "\\7z.dll");
            //"D:\Documents and Settings\Administrator\My Documents\Downloads\SevenZipSharp\SevenZip\7z.dll");

            ofd = new OpenFileDialog();
            ofd.Filter = "7z FILES(*.7z)|*.7z";
            ofd.ShowDialog();
            txtDecompress.Text = ofd.FileName;

            if (txtDecompress.Text != string.Empty)
            {
                DecompressFileLZMA(txtDecompress.Text, "mohan");



                //string destfile = Path.GetTempPath() + ofd.SafeFileName;
                //destfile = Path.ChangeExtension(destfile, ".xml");
                //DecompressFileLZMA(txtDecompress.Text, destfile);
                //string name = destfile;
                //name = Path.ChangeExtension(name, ".xml");
                ////DecryptFile(destfile, name);
                //MessageBox.Show(name + " is created sucessfully");
            }


        }

private static void DecompressFileLZMA(string inFile, string password)
        {


            try
            {
                FileStream archive1 = new FileStream(inFile, FileMode.Open);

                string destfile = archive1.Name.Substring(0, archive1.Name.LastIndexOf('\\'));

                SevenZip.SevenZipExtractor sz = new SevenZip.SevenZipExtractor(archive1, password);

                sz.ExtractArchive(destfile);
                archive1.Close();
                MessageBox.Show(inFile + " is extracted sucessfully to \n " + destfile);
            }
            catch (Exception ex)
            {
                Logging.Logflatfile_Ex(ex);
            }