Tuesday, December 21, 2010

Creating Custom Sections in App.Config File

/////Config File////
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

    <section name ="Application" type="CustomSectionsExample.MyHandler, CustomSectionsExample"/>
  </configSections>
  <Application>
    <Name>POWERPNT</Name>
    <Runtime>1</Runtime>
    <Message>Say Hey to Word application</Message>
    <MessageTime>1</MessageTime>
  </Application >
 
</configuration>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Create Custom Handler
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration.Install;
using System.Configuration;

namespace CustomSectionsExample
{
    public class MySettings
    {
        public string Name;
        public MySettings()
        {
        }
    }
   public  class MyHandler: IConfigurationSectionHandler
    {
        public MyHandler()
        {
          
           
        }
       
      
       

        #region IConfigurationSectionHandler Members

        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            MySettings Settings = new MySettings();
            Settings.Name = section.SelectSingleNode("Name").InnerText;
            return Settings;
        }

        #endregion
    }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Finally Read from App.Config
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace CustomSectionsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            MySettings settings = (MySettings)ConfigurationManager.GetSection("Application");
            Console.WriteLine(settings.Name);
            Console.ReadKey();
        }
    }
}

Run Open Office Applications

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TTA.Util;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.beans;

namespace TTA.Util
{
  public class OpenOffice
  {
    XComponent xComponent;
    XComponentLoader componentLoader;
    unoidl.com.sun.star.lang.XMultiServiceFactory multiServiceFactory;
    unoidl.com.sun.star.uno.XComponentContext localContext;

    public OpenOffice(string FileName, string fileType)
    {
      localContext = uno.util.Bootstrap.bootstrap();
      multiServiceFactory = (unoidl.com.sun.star.lang.XMultiServiceFactory)localContext.getServiceManager();
      componentLoader = (XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop");
      PropertyValue[] loadDesc = new PropertyValue[1];
      loadDesc[0] = new PropertyValue();

      loadDesc[0].Name = "Hidden";
      loadDesc[0].Value = new uno.Any(true);
      xComponent = componentLoader.loadComponentFromURL(fileType, "_blank", 0, loadDesc);
      ((XStorable)xComponent).storeToURL(General.PathConverter(FileName), new unoidl.com.sun.star.beans.PropertyValue[0]);
      xComponent.dispose();
      xComponent = componentLoader.loadComponentFromURL(General.PathConverter(FileName), "_blank", 0, new unoidl.com.sun.star.beans.PropertyValue[0]);
    }

    public bool Close()
    {
      try
      {
        ((XStorable)xComponent).store();
        xComponent.dispose();
        return true;
      }
      catch
      {
        return false;
      }
    }
  }
}



///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Now to open the application
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void Impress_Load(object sender, EventArgs e)
    {
      string FileName = General.GetAppString("UserDocuments") + GlobalData.GetStudentInfo()[0].ToString().Trim() + "_" + GlobalData.GetUserName() + General.GetFileExtension(General.GetAppString("OpenOfficeApp1"));
      GlobalData.SetFileName(FileName);
      op = new OpenOffice(FileName, "private:factory/" + General.GetAppName(General.GetAppString("OpenOfficeApp1")));
      CountDownTimer ct = new CountDownTimer();
      ct.Show();
      timer1.Interval = 1000;
      timer1.Enabled = true;
      Process[] procs = System.Diagnostics.Process.GetProcessesByName("SOFFICE", ".");
      IntPtr hWnd = procs[0].MainWindowHandle;
      SwitchToThisWindow(hWnd, false);
    }

Open and run Word, Excel, PowerPoint Applications

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.Reflection;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using TTA.Util;
using System.Diagnostics;
using System.Runtime.InteropServices;



namespace TTA
{
    public partial class MicrosoftOffice : Form
    {
        public static PowerPoint.Application objApp;
        public static PowerPoint.Presentations objPresSet;
        public static PowerPoint._Presentation objPres;
        public static PowerPoint.Slides objSlides;
        public static PowerPoint._Slide objSlide;
        public static string ProcessName = null;

        public MicrosoftOffice()
        {
            InitializeComponent();
        }

        [DllImport("user32.dll", SetLastError = true)]
        static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);


        static void PowerpointWindow()
        {
           
          
            //Create a new presentation based on a template.
            objApp = new PowerPoint.Application();
            objApp.Visible = MsoTriState.msoTrue;
            objPresSet = objApp.Presentations;
            objPres = objPresSet.Open("D:\\Temp\\GDR.ppt", MsoTriState.msoCTrue, MsoTriState.msoTrue, MsoTriState.msoTrue);
            objSlides = objPres.Slides;

            //Build Slide 1:
            objSlide = objSlides.Add(1, PowerPoint.PpSlideLayout.ppLayoutTitleOnly);
            objPres.SaveAs("D:\\Temp\\GDR.ppt", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoTrue);
            ProcessName = "POWERPNT";
         
        }
        public bool CloseWindow(PowerPoint.Application App)
        {
            return true;
           
           
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (GlobalData.GetMicrosoftOfficeWindowState())
            {
                timer1.Enabled = false;
                timer1.Enabled = false;

                //if (objApp.Windows.Count == 0)
                //{
                   
                   
                //    MessageBox.Show("Powerpoint closed from outside.");
                //    System.Windows.Forms.Application.Exit();
                //}
                Process[] processes = System.Diagnostics.Process.GetProcessesByName(ProcessName, ".");
                foreach (Process p1 in processes)
                {
                    p1.Kill();
                }
               
               
               
                ImpressResult result = new ImpressResult();
                result.MdiParent = this.MdiParent;
                result.Show();
                this.Close();

            }
        }

        private void MicrosoftOffice_Load(object sender, EventArgs e)
        {
            //PowerpointWindow();
            //OpenExcel();
            word();
            CountDownTimer ct = new CountDownTimer();
            ct.Show();
            timer1.Interval = 1000;
            timer1.Enabled = true;

         
          
           
           
        }

        static void OpenExcel()
        {
            object missing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            excelApp.Visible = true;
            Microsoft.Office.Interop.Excel.Workbook newWorkbook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            string workbookPath = "D:\\Temp\\SomeWorkBook2.xlsx";
            newWorkbook.SaveAs(workbookPath, missing, missing, missing, true, missing, XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
            excelApp.Quit();
           
            excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            excelApp.Visible = true;
            Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
                0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            ProcessName = "EXCEL";
        }

        static void word()
        {
            Microsoft.Office.Interop.Word.ApplicationClass WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            object fileName = @"D:\Temp\sam.doc";
            object readOnly = false;
            object isVisible = true;
            // Here is the way to handle parameters you don't care about in .NET
            object missing = System.Reflection.Missing.Value;
            // Make word visible, so you can see what's happening
            WordApp.Visible = true;
            // Open the document that was chosen by the dialog
            Microsoft.Office.Interop.Word.Document aDoc = WordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
            // Activate the document so it shows up in front
            aDoc.Activate();
            ProcessName = "WINWORD";
           
           
        }



    }
}

Tuesday, December 7, 2010

Escape characters like "\" in a string in a sql query

strLocation = strLocation + @"%";

        strLocation =  strLocation.Replace(@"\", @"\\");
       
       
        string query = "SELECT * FROM FileFolder where idUser = "+ UserId + " and Location like '" + strLocation +"' " ;

        query += "ORDER BY IsDirectory DESC, IsDefaultDir DESC, Name ASC";

        try
        {
            Database db = new Database();
            db.Param_CreateCommand(query);
            //db.Param_AddWithValue(@"idUser", UserId);
            //db.Param_AddWithValue(@"Location", strLocation);

            DataSet ds = db.Param_GetDataSet();
            db.Cleanup();
            return ds;
        }
        catch (Exception ex)
        {
            General.ExceptionOccured(ex);
        }

        return null;

Tuesday, November 30, 2010

Renaming the folder using regular expressions

string filePath = General.GetUserDirectory(hidUserID.Value);

      //Create the query to be sent to the database
      string _strWhere = "where iduser = '" + hidUserID.Value + "' and location like '%" + hidFileOrFolderName.Value + "%'";

      DataSet ds = new DataSet();
      //Fill the dataset with the rows to be manipulated
      ds = FileFolderDB.GetMultipleRows(_strWhere);

      //Save the dataset in the session for the rollback operations if the database update fails
      Session["DataTableBackUp"] = ds;

      try
      {
          //Check if dataset 'ds' has any tables in it
          if (ds.Tables.Count > 0)
          {
              #region Loop through the data set and perform database update operations

              //Loop through the first table in dataset 'ds'
              for (int j = 0; ds.Tables[0].Rows.Count > 0 && j < ds.Tables[0].Rows.Count; j++)
              {
                  //Assign values from the Table
                  string FolderLocation = ds.Tables[0].Rows[j]["location"].ToString();
                  string _strFolderID = ds.Tables[0].Rows[j]["idFileFolder"].ToString();
                  string _strUserID = ds.Tables[0].Rows[j]["idUser"].ToString();
                  string  _isFolder = ds.Tables[0].Rows[j]["IsDirectory"].ToString();
                  string _filename = ds.Tables[0].Rows[j]["Name"].ToString();

                  //Check if the folderlocation has any match with the compare string


                  //Build first compare string with complete path of the selected folder location
                  string _strCompareString = hidFolder.Value;

                  //Escape any metacharacters in the string for absolute pattern match
                  _strCompareString = Regex.Escape(_strCompareString);

                  //Finally build our custom compare string to detect a specific pattern
                  _strCompareString = _strCompareString + ".";

                 


                  // Check if the file/folder path matches with our compare string
                  if (Regex.IsMatch(FolderLocation, _strCompareString))
                  {
                     


                      //Create another compare string to detect all the files and folder within the selected folder
                      string _strCompareString2 = hidFolder.Value + hidFileOrFolderName.Value;
                      _strCompareString2 = Regex.Escape(_strCompareString2);
                      _strCompareString2 = _strCompareString2 + ".";


                      //Build the replace string which has the full path of folder renamed
                      string _strReplaceString = hidFolder.Value + txtRenameFolder.Text.Trim();
                     
                      //Split the path after the selected folder name
                      string[] split = Regex.Split(FolderLocation, _strCompareString2);

                      //Attach the full path of new folder along with above retrieved content of string
                      string temp = _strReplaceString + @"\" + split[1].ToString();

                      //Create an object of file folder for database insertion
                      FileFolder ff = new FileFolder();

                      //Set the attributes of filefolder
                      ff.UserID = Convert.ToInt64(_strUserID);
                      ff.ID = Convert.ToInt64(_strFolderID);
                      ff.Location = temp;

                      //Checksum calculation only for description purpose
                      if (_isFolder == "False")
                      {
                          string checksum = General.CalculateFileCheckSum( filePath+ ff.Location + _filename);
                      }


                      Database db = new Database();

                      // Finally update the file/folder details with new attributes
                      FileFolderDB.renameFolder(db, ff);


                  }




              }
              #endregion

             
          }
      }
      catch (Exception ex)
      {
          //When an exception occurs rollback the database to the state it was before

          RollbackRenameUpdate(ds);

          //Finally log the error
          General.ExceptionOccured(ex);

      }

Tuesday, November 23, 2010

How to create a persistent cookie?

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class RememberMe : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["UserName"] != null && Request.Cookies["PassWord"] != null)
        {
            txtUsername.Text = Request.Cookies["UserName"].Value;
            txtPassword.Text = Request.Cookies["PassWord"].Value;
       
       
        }
        else
        {
        HttpBrowserCapabilities objBrowsCap;
      
        objBrowsCap = Request.Browser;
        if (objBrowsCap.Cookies)
        {
            lblMessage.Text = "Cookies Enabled";
        }
        else
        {
            lblMessage.Text = "Cookies Disabled";
        }
        }
    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        HttpCookie UserNameCookie = new HttpCookie("UserName", txtUsername.Text.ToString());
        HttpCookie PasswordCookie = new HttpCookie("PassWord", txtPassword.Text.ToString());
        UserNameCookie.Expires = System.DateTime.Now.AddDays(1);
        PasswordCookie.Expires = System.DateTime.Now.AddDays(1);
        Response.Cookies.Add(UserNameCookie);
        Response.Cookies.Add(PasswordCookie);
        lblMessage.Text = "You have logged in successfully";

    }
}

Monday, November 15, 2010

File system watcher syncs to a private folder

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

namespace FileUploader
{
    class Program
    {
        static void Main(string[] args)
        {
            Run();
           

        }

        public static void Run()
        {

            FileSystemWatcher Watcher = new FileSystemWatcher(Environment.GetEnvironmentVariable("USERPROFILE"));
            Watcher.Path = @"E:\Sameer";
            Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            Watcher.Filter = "*.txt";
            Watcher.Created += new FileSystemEventHandler(Watcher_Created);
            Watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
            Watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
            Watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);

            Watcher.EnableRaisingEvents = true;
            Console.ReadKey();
        }
        static void Watcher_Created(object sender, FileSystemEventArgs e)
        {
            try
            {
                string fileName = System.IO.Path.GetFileName(e.FullPath);

                Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);

                System.IO.File.Copy(e.FullPath, @"C:\Users\sameer\Documents\Visual Studio 2008\Projects\FileUploader\FileUploader\Uploaded Docs\" + fileName , true);
               
            }
            catch(Exception ex)
            {
                Console.WriteLine("Problem occured");
            }
           
        }

        static void Watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
        }

        static void Watcher_Renamed(object sender, RenamedEventArgs e)
        {
            try
            {
                Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
                string fileName = System.IO.Path.GetFileName(e.FullPath);
                System.IO.File.Move(@"C:\Users\sameer\Documents\Visual Studio 2008\Projects\FileUploader\FileUploader\Uploaded Docs\" + e.OldName, @"C:\Users\sameer\Documents\Visual Studio 2008\Projects\FileUploader\FileUploader\Uploaded Docs\" + fileName);
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        static void Watcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);
            try
            {
                string fileName = System.IO.Path.GetFileName(e.FullPath);

                Console.WriteLine("File : " + e.FullPath + " Change Type is : " + e.ChangeType);

                System.IO.File.Copy(e.FullPath, @"C:\Users\sameer\Documents\Visual Studio 2008\Projects\FileUploader\FileUploader\Uploaded Docs\" + fileName ,true );
            }
            catch (Exception ex)
            {
                Console.WriteLine("Problem occured" + ex.ToString());
            }
        }


    }
}

Decrypt a string using a specific given key

public static string Decrypt(string strEncrypted)
    {
      try
      {
        TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();

        byte[] byteHash, byteBuff;
        string strTempKey = _key;

        byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
        objHashMD5 = null;
        objDESCrypto.Key = byteHash;
        objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB

        byteBuff = Convert.FromBase64String(strEncrypted);
        string strDecrypted = ASCIIEncoding.ASCII.GetString(objDESCrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
        objDESCrypto = null;

        return strDecrypted;
      }
      catch (Exception ex)
      {
        General.ExceptionOccured(ex);
        return "";
      }
    }

Encrypt a string using a given key?

 public static string Encrypt(string strToEncrypt)
    {
      try
      {
        TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();

        byte[] byteHash, byteBuff;
        string strTempKey = "Sameer";

        byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
        objHashMD5 = null;
        objDESCrypto.Key = byteHash;
        objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB

        byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
        return Convert.ToBase64String(objDESCrypto.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
      }
      catch (Exception ex)
      {
        General.ExceptionOccured(ex);
        return "";
      }
    }

Sunday, November 14, 2010

How to log errors to a Log file everytime an exceptions occurs?

string folder = AppDomain.CurrentDomain.BaseDirectory + GetAppSetting("LogFileDirectory") + "\\";
      CreateDirectory(folder);
      Exception objErr = ex;
      StringBuilder err = new StringBuilder();
      string eol = Environment.NewLine;
      err.Append("Error Time: ").Append(DateTime.Now.Hour).Append(":").Append(DateTime.Now.Minute).Append(eol);
      err.Append("Error Message: ").Append(objErr.Message).Append("\nStack Trace:\n").Append(objErr.StackTrace);
      err.Append("\n**********************************************************************\n");

      if (Convert.ToBoolean(GetAppSetting("SendErrorMail")))
      {
        //Send mail to support when error occured
        string email = GetAppSetting("SupportEmail");
        Email.SendEmail(err.ToString(), email, "", email, "", "Error Message");
      }
      string sErrorTime = DateTime.Now.ToString("dd-MM-yy");

      StreamWriter sw = new StreamWriter(folder + sErrorTime + ".txt", true);
     
      sw.WriteLine(err);
      sw.Flush();
      sw.Close();