Friday, 2 March 2012

Displaying Madular content using WPF





 * code for design file

<Window x:Class="LayoutPanels.ModularContent"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ModularContent" Height="362" Width="516"   
    >
  <ScrollViewer>
  <StackPanel>
  <WrapPanel Background="LightSteelBlue" Name="pnlList">
    <CheckBox Margin="5" IsChecked="True">Panel1</CheckBox>
    <CheckBox Margin="5" IsChecked="True">Panel2</CheckBox>
    <CheckBox Margin="5" IsChecked="True">Panel3</CheckBox>
    <CheckBox Margin="5" IsChecked="True">Panel4</CheckBox>
  </WrapPanel>
   
  <WrapPanel>
    <StackPanel Name="Panel1" >
    <Border Padding="5" BorderBrush="Yellow" BorderThickness="2">
      <UniformGrid Rows="2" Columns="2">
        <Button Margin="10" Padding="10">1</Button>
        <Button Margin="10" Padding="10">2</Button>
        <Button Margin="10" Padding="10">3</Button>
        <Button Margin="10" Padding="10">4</Button>
      </UniformGrid>
    </Border>
    </StackPanel>
   
    <StackPanel Name="Panel2">
      <Border Padding="15" BorderBrush="Yellow" BorderThickness="2">
      <TabControl>
        <TabItem Header="Page1">
          <Button Padding="100,50,100,50">Tabs</Button>
        </TabItem>
        <TabItem Header="Page2">         
        </TabItem>       
      </TabControl>
      </Border>
    </StackPanel>

    <StackPanel Name="Panel3">
      <Border Padding="15" BorderBrush="Yellow" BorderThickness="2">
        <StackPanel>
          <TextBox MinLines="5" MaxWidth="150" TextWrapping="Wrap">This is a test of a text box that contains wrapped text.</TextBox>
          <StackPanel Orientation="Horizontal">
            <Button>OK</Button>
            <Button>Cancel</Button>
          </StackPanel>
        </StackPanel>
      </Border>
    </StackPanel>

    <StackPanel Name="Panel4">
      <Border Padding="15" BorderBrush="Yellow" BorderThickness="2">
        <UniformGrid Rows="2" Columns="2">
          <Button Margin="10" Padding="10">1</Button>
          <Button Margin="10" Padding="10">2</Button>
          <Button Margin="10" Padding="10">3</Button>
          <Button Margin="10" Padding="10">4</Button>
        </UniformGrid>
      </Border>
    </StackPanel>
  </WrapPanel>
   
  </StackPanel>
  </ScrollViewer>
</Window>

* code file
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Xps.Packaging;
using System.IO;

namespace LayoutPanels
{
    /// <summary>
    /// Interaction logic for ModularContent.xaml
    /// </summary>

    public partial class ModularContent : System.Windows.Window
    {

        public ModularContent()
        {
            InitializeComponent();

            AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(chk_Checked));
            AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(chk_Unchecked));           
        }

        private void chk_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox chk = (CheckBox)e.OriginalSource;
            DependencyObject obj = LogicalTreeHelper.FindLogicalNode(this, chk.Content.ToString());
            ((FrameworkElement)obj).Visibility = Visibility.Visible;
        }

        private void chk_Unchecked(object sender, RoutedEventArgs e)
        {
            CheckBox chk = (CheckBox)e.OriginalSource;
            DependencyObject obj = LogicalTreeHelper.FindLogicalNode(this, chk.Content.ToString());
            ((FrameworkElement)obj).Visibility = Visibility.Collapsed;
        }
    }
}

showing multiple forms using one button click in WPF

 Displaying different forms using one button click in WPF
* Code For Design file

<Window x:Class="LayoutPanels.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Menu" Height="400" Width="252"
    >
    <Grid>
      <StackPanel Margin="5" Button.Click="ButtonClick">
        <Button>SimpleStack</Button>
        <Button>SimpleWrap</Button>
        <Button>SimpleDock</Button>
        <Button>BasicDialogBox</Button>
        <Button>SimpleGrid</Button>
        <Button>LayoutRoundingTest</Button>
        <Button>SplitWindow</Button>
        <Button>DoubleSplitWindow</Button>
        <Button>SharedSizeGroup</Button>
        <Button>SimpleCanvas</Button>
        <Button>SimpleInkCanvas</Button>
        <Button>TheUniformGrid</Button>
        <Button>TextBoxColumn</Button>
        <Button>LocalizableText</Button>
        <Button>ModularContent</Button>
      </StackPanel>
       
    </Grid>
</Window>

* Code for .cs file

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Reflection;


namespace LayoutPanels
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>

    public partial class Window1 : Window
    {

        public Window1()
        {
            InitializeComponent();           
        }

        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            // Get the current button.
            Button cmd = (Button)e.OriginalSource;
               
            // Create an instance of the window named
            // by the current button.
            Type type = this.GetType();
            Assembly assembly = type.Assembly;                      
            Window win = (Window)assembly.CreateInstance(
                type.Namespace + "." + cmd.Content);

            // Show the window.
            win.ShowDialog();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}





Creating summary report using c#code

* Create this class
* calling report method at on buton click
* function to generate report


* Create this class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;

namespace BPSM_Server
{
    public static class Report
    {
        #region: Write Message to Reportfile :

        public static void Write(string FileName, string message)
        {
            try
            {
                string filePath = FileName;
                string logLine = System.String.Format("{0}", message);
                if (!File.Exists(filePath))
                {
                    StreamWriter sw;
                    //sw = File.AppendText(filePath);
                    sw = File.CreateText(filePath);
                    sw.WriteLine(logLine);
                    sw.Close();
                }
                else
                {

                    ArrayList lines = new ArrayList();
                    StreamReader rdr = new StreamReader(filePath);
                    string line;
                    while ((line = rdr.ReadLine()) != null)
                        lines.Add(line);
                    rdr.Close();
                    lines.Add(logLine);
                    StreamWriter wrtr = new StreamWriter(filePath);
                    foreach (string strNewLine in lines)
                        wrtr.WriteLine(strNewLine);
                    wrtr.Close();
                }
            }
            catch (Exception ex)
            {
                Logging.Logflatfile_Ex(ex);
            }

        }

        #endregion


    }
}
* calling report method at on buton click

 private void btnReport_Click(object sender, EventArgs e)
        {
            GeneratePacketsReport(txtPDFPath.Text);
        }

* function to generate report
  public void GeneratePacketsReport(string pdfspath)
        {
            try
            {
               

                    //SetControlPropertyValue(lblCopyfolder, "Text", "Writing SummaryReport..");
                    string ReportPath = pdfspath + "\\" + "ReportSummary" + System.DateTime.Now.ToString("ddMMyyyyhhmmss") + ".txt";
                    //Report.Write(ReportPath, "Operation Summary for 'DIsc'  " + XMLPath.Substring(0, 3));
                    //Report.Write(ReportPath, "========================================================================================================================");
                    //Report.Write(ReportPath, "Application : " + System.Reflection.Assembly.GetExecutingAssembly().GetName().FullName.Split(',')[0] + " " + System.Reflection.Assembly.GetExecutingAssembly().GetName().FullName.Split(',')[1]);

                    //Report.Write(ReportPath, "Data As Per 'Disc' ");
                    //Report.Write(ReportPath, "************************");
                    //Report.Write(ReportPath, "CIDR :" + TotalCIDR.Count);
                    //Report.Write(ReportPath, "Registrar :" + TotalRegistrar.Count);
                    //Report.Write(ReportPath, "Docs :" + TotalDocs.Count);
                    //Report.Write(ReportPath, "");
                    //Report.Write(ReportPath, "");

                    //Report.Write(ReportPath, "Summary of Current Operation");
                    //Report.Write(ReportPath, "**********************************");

                    //Report.Write(ReportPath, "Records Inserted");
                    //Report.Write(ReportPath, "*****************");
                    //Report.Write(ReportPath, "TotalInsertedPackets: " + InsertedRecords.Count);
                    //Report.Write(ReportPath, "Records Updated");
                    //Report.Write(ReportPath, "*****************");
                    //Report.Write(ReportPath, "CIDR: " + CIDRDeletedCount.Count);
                    //Report.Write(ReportPath, "Registrar: " + RegistrarDeletedCount.Count);
                    //Report.Write(ReportPath, "Docs: " + DocsDeletedCount.Count);
                    //Report.Write(ReportPath, "Manifest File Updated Count :" + ManifetCopYied.Count);

                   
                    if (pdfcount!=null && pdfcount.Count > 0)
                    {
                        Report.Write(ReportPath, "Total PDF FILES:" + pdfcount.Count);
                        Report.Write(ReportPath, "*****************");
                        foreach (FileInfo name in pdfcount)
                        {
                            Report.Write(ReportPath, "File Name: " + name.ToString());
                        }
                        pdfcount.Clear();
                    }
                    Report.Write(ReportPath, "");
                    Report.Write(ReportPath, "");

                    if (SkippedPDFFiles!=null&&SkippedPDFFiles.Count > 0)
                    {
                        Report.Write(ReportPath, "Skipped PDF Files:" + SkippedPDFFiles.Count);
                        Report.Write(ReportPath, "*****************");
                        foreach (string name in SkippedPDFFiles)
                        {
                            Report.Write(ReportPath, "File Name " + name.ToString());
                        }
                        SkippedPDFFiles.Clear();
                    }
                    Report.Write(ReportPath, "");
                    Report.Write(ReportPath, "");
                    if (UIDGeneratedPDFFILES!=null&& UIDGeneratedPDFFILES.Count > 0)
                    {
                        Report.Write(ReportPath, "Unique Id generated pdf files:" + UIDGeneratedPDFFILES.Count);
                        Report.Write(ReportPath, "*****************");
                        foreach (string name in UIDGeneratedPDFFILES)
                        {
                            Report.Write(ReportPath, "File Name: " + name.ToString());
                        }
                        UIDGeneratedPDFFILES.Clear();

                    }
                    Report.Write(ReportPath, "");
                    Report.Write(ReportPath, "");
                    if (UIDUpdatedFlagsCount!=null&& UIDUpdatedFlagsCount.Count > 0)
                    {
                        Report.Write(ReportPath, "Unique Id Updated flags :" + UIDUpdatedFlagsCount.Count);
                        Report.Write(ReportPath, "*****************");
                        foreach (string name in UIDUpdatedFlagsCount)
                        {
                            Report.Write(ReportPath, "File Name: " + name.ToString());
                        }
                        UIDUpdatedFlagsCount.Clear();
                    }
                    Report.Write(ReportPath, "");
                    Report.Write(ReportPath, "");
                                       
                    MessageBox.Show(ReportPath + "Generated Successfully");
               
                //TotalCIDR.Clear();
                //InsertedRecords.Clear();
                //TotalRegistrar.Clear();
                //TotalDocs.Clear();
                //CIDRDeletedCount.Clear();
                //RegistrarDeletedCount.Clear();
                //filesnotprocessed.Clear();
                //ManifetCopYied.Clear();
                //CIDRCopiedCount.Clear();
                //Invoke(new MethodInvoker(GetWoleText));
                //DocsDeletedCount.Clear();
                //SetControlPropertyValue(lblStatusd1, "Text", "Completed.");
                //SetControlPropertyValue(button3, "Enabled", true);
                //SetControlPropertyValue(lblCopyfolder, "Text", ReportPath + " Generated Successfully.");
                //SetControlPropertyValue(button1, "Enabled", true);
                //SetControlPropertyValue(button2, "Enabled", true);
              
            }
            catch (Exception ee)
            {
                Logging.Logflatfile_Ex(ee);
            }

        }

DatagridView editable checkbox creation at runtime

* Creating chekboxs at runtime to a datagridView in windows application
* Get the value of checked column (using cellclick event)
*  Check whether the check box is checked or not on button click
* make checkbox column readonly =true and remaining or Readonly false(using cellbeginedit event)



 Creating chekboxs at runtime to a datagridView in windows application
if (empdata.Tables[0].Rows.Count != 0)
                    {
                        dataGrid1.DataSource = empdata.Tables[0];
                        foreach (DataGridViewRow row in dataGrid1.Rows)
                        {

                            //Get the appropriate cell using index, name or whatever and cast to DataGridViewCheckBoxCell
                            DataGridViewCheckBoxCell cell = row.Cells[0] as DataGridViewCheckBoxCell;

                            //Compare to the true value because Value isn't boolean
                            if (cell == null)
                            {
                                column = new DataGridViewCheckBoxColumn();
                                {
                                    column.HeaderText = "select";
                                    column.AutoSizeMode =
                                        DataGridViewAutoSizeColumnMode.DisplayedCells;
                                    //column.FlatStyle = FlatStyle.Standard;
                                    //column.ThreeState = true;
                                    column.CellTemplate = new DataGridViewCheckBoxCell();
                                    column.ReadOnly = false;
                                    //column.CellTemplate.Style.BackColor = Color.Beige;
                                }
                                dataGrid1.Columns.Insert(0, column);
                                //dataGrid1.Columns["select"].ReadOnly = false;
                                //dataGrid1.Columns[0].ReadOnly = false;


                            }
                            else
                            {
                                // dataGrid1.Columns.Clear();
                            }

                        }

Get the value of checked column (using cellclick event)

  private void dataGrid1_CellClick_1(object sender, DataGridViewCellEventArgs e)
        {

            for (int i = 0; i < this.dataGrid1.RowCount; i++)
            {
                string re_value = dataGrid1.Rows[i].Cells[0].Selected.ToString();
                this.dataGrid1.Rows[i].Cells[0].Value = re_value; //"true";           

            }



        }

*  Check whether the check box is checked or not
 foreach (DataGridViewRow dr in dataGrid1.Rows)
                        {
                           
                            if (Convert.ToBoolean(dr.Cells[0].Value) == true)
                            {
                                //rows_with_checked_column.Add(row);
                                uniqueid = dr.Cells[1].Value.ToString();
                            }


                        }
 make checkbox column readonly =true and remaining or Readonly false(using cellbeginedit event)
 private void dataGrid1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.ColumnIndex != 0)
            {
                e.Cancel = true;
            }

        }


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);
            }




Thursday, 26 January 2012

Reading .doc or word file using c#.net

1 First ,u need to add Microsoft Office Object Library throgh Add reference/com tab
2 second add  this namespace Microsoft.Office.Interop.Word;
note :install msoffice 2003 or 2007  (then only u will get Microsoft Office Object Library dlls)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Word;
using System.Drawing;

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

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Word Documents(*.doc)|*.doc";
            ofd.ShowDialog();
            txtCurrentFile.Text = ofd.FileName;         
         
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            if (txtCurrentFile.Text.Length > 0)
            {
                readFileContent(txtCurrentFile.Text);
            }
            else
            {
                MessageBox.Show("Enter a valid file path");
            }
        }

        private void readFileContent(string path)
        {
            Microsoft.Office.Interop.Word.ApplicationClass wordApp = new ApplicationClass();
            object file = path;
            object nullobj = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(
                ref file, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj);
            doc.ActiveWindow.Selection.WholeStory();
            doc.ActiveWindow.Selection.Copy();
            IDataObject data = Clipboard.GetDataObject();           
            txtWordData.Text = data.GetData(DataFormats.Text).ToString();           
                    doc.Close(ref nullobj, ref nullobj, ref nullobj);
            wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);

        }
    }
}