Encrypting data.

image_pdfimage_print

using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;

public class StoreCryptoStream : ICryptoStream {
static byte[] tag1 = {(byte)'[',(byte)'S',(byte)'a',(byte)'u' ,
(byte)'d' ,(byte)'e',(byte)'s' ,(byte)']'};
static byte[] tag2 = {(byte)'[',(byte)'S',(byte)'a',(byte)'u' ,
(byte)'r' ,(byte)'c',(byte)'2' ,(byte)']'};

FileStream fs;

public StoreCryptoStream(FileStream fout) {
fs = fout;
}
public virtual void CloseStream() { fs.Close(); }
public virtual void CloseStream(Object obj) { fs.Close(); }
public virtual void SetSink(ICryptoStream pstm) { }
public virtual void SetSource(CryptographicObject co) { }
public virtual ICryptoStream GetSink() { return null; }

public virtual void Write(byte[] bin) {
int len = bin.GetLength(0);
Write(bin, 0, len);
}

public virtual void Write(byte[] bin, int start, int len) {
fs.Write(bin, start, len);
}
}
public class MainClass {
static byte[] symKey;
static byte[] symIV;

private static bool GenerateKey(string password) {
try {

int len;
char[] cp = password.ToCharArray();
len = cp.GetLength(0);
byte[] bt = new byte[len];

for (int i = 0; i < len; i++) { bt[i] = (byte)cp[i]; } symKey = new byte[8]; symIV = new byte[8]; SHA1_CSP sha = new SHA1_CSP(); sha.Write(bt); sha.CloseStream(); for (int i = 0; i < 8; i++) { symKey[i] = sha.Hash[i]; } for (int i = 8; i < 16; i++) { symIV[i - 8] = sha.Hash[i]; } return true; } catch (Exception e) { Console.WriteLine("An Exception Occurred in Generating eys:" + e.ToString()); return false; } } private static void EncryptData(string infile, string outfile) { try { FileStream fin = new FileStream(infile, FileMode.Open, FileAccess.Read); FileStream fout = new FileStream(outfile, FileMode.OpenOrCreate, FileAccess.Write); fout.SetLength(0); byte[] bin = new byte[4096]; long totlen = fin.Length; long rdlen = 0; int len; SymmetricAlgorithm des = new DES_CSP(); StoreCryptoStream scs = new StoreCryptoStream(fout); SymmetricStreamEncryptor sse = des.CreateEncryptor(symKey, symIV); SHA1_CSP sha = new SHA1_CSP(); sse.SetSink(sha); sha.SetSource(sse); sha.SetSink(scs); scs.SetSource(sha); while (rdlen < totlen) { len = fin.Read(bin, 0, 4096); sse.Write(bin, 0, len); rdlen = rdlen + len; } sse.CloseStream(); fin.Close(); fout.Close(); } catch (Exception e) { Console.WriteLine("An exception occurred while encrypting :" + e.ToString()); } } public static void Main(string[] args) { GenerateKey(args[0]); EncryptData(args[1], args[2]); } } [/csharp]

sample code for the EndInvoke method

image_pdfimage_print
   
 

using System;
using System.Threading;

public delegate int DelegateClass(out DateTime start,out DateTime stop);

public class Starter {

    public static void Main() {
        DelegateClass del = MethodA;
        DateTime start;
        DateTime stop;
        IAsyncResult ar = del.BeginInvoke(out start, out stop,null, null);
        ar.AsyncWaitHandle.WaitOne();

        int elapse = del.EndInvoke(out start, out stop, ar);
        Console.WriteLine("Start time: {0}", start.ToLongTimeString());
        Console.WriteLine("Stop time: {0}", stop.ToLongTimeString());
        Console.WriteLine("Elapse time: {0} seconds",elapse);
    }
    public static int MethodA(out DateTime start, out DateTime stop) {
        start = DateTime.Now;
        Thread.Sleep(5000);

        stop = DateTime.Now;
        return (stop - start).Seconds;
    }
}

    


What happens if an unhandled exception is raised in a multicast delegate?

image_pdfimage_print
   
 

using System;
using System.Threading;

public delegate void DelegateClass();

public class Starter {
    public static void Main() {
        Console.WriteLine("Running on primary thread");
        try {
            DelegateClass del = MethodA;
            IAsyncResult ar = del.BeginInvoke(null, null);
            del.EndInvoke(ar);
        } catch (Exception except) {
            Console.WriteLine("Running on primary thread");
            Console.WriteLine("Exception caught: " + except.Message);
        }
    }

    public static void MethodA() {
        if (Thread.CurrentThread.IsThreadPoolThread == true) {
            Console.WriteLine("Running on a thread pool thread");
        } else {
            Console.WriteLine("Running on primary thread");
        }
        throw new Exception("failure");
    }
}

    


Get Top Parent Culture

image_pdfimage_print
   
 
///////////////////////////////////////////////////////////////////////////////////////////////
//
//    This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
//    Copyright (c) 2005-2008, Jim Heising
//    All rights reserved.
//
//    Redistribution and use in source and binary forms, with or without modification,
//    are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright notice,
//      this list of conditions and the following disclaimer in the documentation and/or
//      other materials provided with the distribution.
//
//    * Neither the name of Jim Heising nor the names of its contributors may be
//      used to endorse or promote products derived from this software without specific prior
//      written permission.
//
//    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//    IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//    POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace WOSI.Utilities
{
    public class GlobalizationUtils
    {
        public static CultureInfo GetTopParentCulture(CultureInfo culture)
        {
            CultureInfo currentCulture = culture;

            while (currentCulture.Parent != System.Globalization.CultureInfo.InvariantCulture)
                currentCulture = currentCulture.Parent;

            return currentCulture;
        }
    }
}

   
     


International Text

image_pdfimage_print


   
 
/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury, 
   Zach Greenvoss, Shripad Kulkarni, Neil Whitlow

Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace Wrox.ProgrammingWindowsGUI.Chapter5
{
   /// <summary>
   /// Summary description for Form1.
   /// </summary>
   public class InternationalText : System.Windows.Forms.Form
   {
      internal System.Windows.Forms.Label lblInternationalText;
      internal System.Windows.Forms.Label lblCharCode;
      private System.Windows.Forms.TextBox textBox1;
      /// <summary>
      /// Required designer variable.
      /// </summary>
      private System.ComponentModel.Container components = null;

      public InternationalText()
      {
         //
         // Required for Windows Form Designer support
         //
         InitializeComponent();

         //
         // TODO: Add any constructor code after InitializeComponent call
         //
      }

      /// <summary>
      /// Clean up any resources being used.
      /// </summary>
      protected override void Dispose( bool disposing )
      {
         if( disposing )
         {
            if (components != null) 
            {
               components.Dispose();
            }
         }
         base.Dispose( disposing );
      }

        #region Windows Form Designer generated code
      /// <summary>
      /// Required method for Designer support - do not modify
      /// the contents of this method with the code editor.
      /// </summary>
      private void InitializeComponent()
      {
         this.lblInternationalText = new System.Windows.Forms.Label();
         this.lblCharCode = new System.Windows.Forms.Label();
         this.textBox1 = new System.Windows.Forms.TextBox();
         this.SuspendLayout();
         // 
         // lblInternationalText
         // 
         this.lblInternationalText.Location = new System.Drawing.Point(8, 64);
         this.lblInternationalText.Name = "lblInternationalText";
         this.lblInternationalText.Size = new System.Drawing.Size(288, 23);
         this.lblInternationalText.TabIndex = 0;
         // 
         // lblCharCode
         // 
         this.lblCharCode.Location = new System.Drawing.Point(8, 96);
         this.lblCharCode.Name = "lblCharCode";
         this.lblCharCode.Size = new System.Drawing.Size(88, 23);
         this.lblCharCode.TabIndex = 2;
         // 
         // textBox1
         // 
         this.textBox1.Location = new System.Drawing.Point(8, 24);
         this.textBox1.Name = "textBox1";
         this.textBox1.Size = new System.Drawing.Size(288, 20);
         this.textBox1.TabIndex = 3;
         this.textBox1.Text = "";
         this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);
         // 
         // InternationalText
         // 
         this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
         this.ClientSize = new System.Drawing.Size(304, 134);
         this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                      this.textBox1,
                                                                      this.lblCharCode,
                                                                      this.lblInternationalText});
         this.MaximizeBox = false;
         this.Name = "InternationalText";
         this.Text = "InternationalText";
         this.ResumeLayout(false);

      }
        #endregion

      /// <summary>
      /// The main entry point for the application.
      /// </summary>
      [STAThread]
      static void Main() 
      {
         Application.Run(new InternationalText());
      }

      protected override void OnInputLanguageChanged(InputLanguageChangedEventArgs e)
      {
         MessageBox.Show(e.InputLanguage.Culture.Name); 
      }

      protected override void OnInputLanguageChanging(InputLanguageChangingEventArgs e)
      {
         MessageBox.Show(e.InputLanguage.Culture.Name);
      }

      private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
      {
         lblInternationalText.Text += e.KeyChar.ToString();
         lblCharCode.Text = ((int)e.KeyChar).ToString();
      }
   }
}

           
         
     


Get the Hash code for string value

image_pdfimage_print

using System;
public class HashValues {
public static void Main( ) {
String[] identifiers ={“A”,”B”,”C”,”D”,”E”,”F”,”G”,”H”,”I”,”J”,”K”,”L”};

for(int i = 0; i < identifiers.Length; i++) { String id = identifiers[i]; int hash = id.GetHashCode(); int code = hash % 23; Console.WriteLine("{0,-12}{1,12}{2,12}", id, hash, code); } } } [/csharp]

Class behaves properly using overridden Equals and GetHashCode methods

image_pdfimage_print


   


using System;
using System.Collections;

public class GoodCompare {
  public static void Main() {
    Name president = new Name ("A", "B");
    Name first = new Name ("C", "D");
    Console.WriteLine("The hash codes for first and president are: ");
    
    if (president.GetHashCode() == first.GetHashCode())
       Console.WriteLine("equal");
    else
       Console.WriteLine("not equal");
    
  }
}



public class Name {
  protected String first;
  protected char initial;
  protected String last;
          
  public Name(String f, String l) {
    first = f; 
    last = l; 
  }
  public Name(String f, char i, String l) : this(f,l) {
    initial = i;  
  } 
  public override String ToString() {
    if (initial == &#039;u0000&#039;)
       return first + " " + last;
    else  
       return first + " " + initial + " " + last;
  }
  public override bool Equals(Object o) {
    if (!(o is Name))
       return false;
    Name name = (Name)o;
    return first == name.first &amp;&amp; initial == name.initial
             &amp;&amp; last == name.last;
  }
  public override int GetHashCode() {
    return first.GetHashCode() + (int)initial 
                             + last.GetHashCode();
  }

}