Blog Home  Home Feed your aggregator (RSS 2.0)  
Software Code Help - C
Blog
 
# Thursday, January 14, 2010

I have tested it using window application of C#,  In this we have two Hexadecimal value, And we check that the source value exists in our database or not.

        public Test()
        {
            InitializeComponent();

            //8 Byte Hexadecimal Value of source
            this.txtSource.Text = "0x00004000";

            //8 Byte Hexadecimal Value of DB
            this.txtDB.Text = "0xAF00D0b0";
        }

        private void button1_Click(object sender, EventArgs e)
        
        {
            //Convert the Hexadecimal value inot uint.
            uint i = GetHexValue(txtDB.Text.ToString());
            uint b = GetHexValue(txtSource.Text.ToString());
            
            txtResult.Text = (i & b) > 0 ? "Match" : "UnMatch";
        }

        //This is the function used for returning uint value from hexadecimal value.
        public uint GetHexValue(String text)
        {
            uint result = 0;
            String parseText = text;
            if (parseText.StartsWith("0x", true, CultureInfo.InvariantCulture))
            {
                parseText = text.Substring(2);
            }


            if (UInt32.TryParse(parseText, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out result) == false)
            {
                throw new ArgumentException("Text value must be a valid hexidecimal number" + text);
            }

            return result;
        }

 

Thursday, January 14, 2010 10:27:06 AM (GMT Standard Time, UTC+00:00)  #    Comments [0]   C#  | 
# Wednesday, October 07, 2009

A shallow copy creates a new instance of the same type as the original object, and then copies the non-static fields of the original object. If the field is a value type, a bit-by-bit copy of the field is performed. If the field is a reference type, the reference is copied but the referred object is not; therefore, the reference in the original object and the reference in the clone point to the same object.

A deep copy of an object duplicates everything directly or indirectly referenced by the fields in the object

Wednesday, October 07, 2009 7:19:22 AM (GMT Daylight Time, UTC+01:00)  #    Comments [1]   C# | Interview Question .Net  | 
# Wednesday, July 08, 2009
//Create Two image Server path    
string strImagePath1 = Server.MapPath("Image1.jpg");
string strImagePath2 = Server.MapPath("Image2.jpg");
//Get Image objct
System.Drawing.Image FirstImage = Bitmap.FromFile(strImagePath1);
Graphics objGraphics = Graphics.FromImage(FirstImage);
System.Drawing.Image SecondImage = Bitmap.FromFile(strImagePath2);

int iFirstImageWidth, iFirstImageHeight, iSecondImageWidth, iSecondImageHeight;
int xPos, yPos;
//Retrieve the Height and Width of Images
iFirstImageWidth = FirstImage.Width;
iFirstImageHeight= FirstImage.Height;
iSecondImageWidth = SecondImage.Width;
iSecondImageHeight = SecondImage.Height;
//Retrieving the position where to image merge    
xPos = (iFirstImageWidth - iSecondImageWidth) / 2;
yPos = (iFirstImageHeight - iSecondImageHeight) / 2;
//Draw Second Image into First Image
objGraphics.DrawImage(SecondImage, new Point(xPos, yPos));

Response.ContentType = "image/JPEG";
//Save the Merge Image
FirstImage.Save(Server.MapPath("MergeImage.jpg"), ImageFormat.Jpeg);
Wednesday, July 08, 2009 6:43:01 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]   C#  | 
# Tuesday, June 23, 2009


Java of AES Encryption
=======================
            Cipher encrypt = Cipher.getInstance("AES");
            encrypt.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptedData = encrypt.doFinal(data);

C# code using Rijndael(AES) 128 Bit encryption
==============================================

 

       ICryptoTransform transform = GetCryptoServiceProvider(SecretKey);

       //Set up the stream that will hold the encrypted data.
       MemoryStream memStreamEncryptedData = GetMemoryStream(transform, bytesData);

        /// <summary>
        /// Create ICryptoTransform object from Rijndael(AES) ECB/PKCS7
        /// </summary>
        /// <param name="bytesKey">Byte Array key</param>
        /// <returns>ICryptoTransform Object</returns>
        private ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            Rijndael rijndael = new RijndaelManaged();
            try
            {
                rijndael.KeySize = 128;
                rijndael.BlockSize = 128;
                rijndael.Mode = CipherMode.ECB;
                rijndael.Padding = PaddingMode.PKCS7;
                // Test to see if a key was provided
                rijndael.GenerateIV();

                if (null != bytesKey)
                {
                    rijndael.Key = bytesKey;
                }
                else
                {
                    rijndael.GenerateKey();
                    SecretKey = rijndael.Key;
                }
            }
            catch (Exception Ex)
            {
                throw new Exception("Error while creating Rijndael(AEs) Object: \n" + Ex.Message);
            }

            return rijndael.CreateEncryptor();

        }

Tuesday, June 23, 2009 12:18:19 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0]   C#  | 

Java code for retrieve Public key from Certificate
==================================================
 
     KeyStore inputKeyStore = KeyStore.getInstance(Constents.PFX_TYPE);
            FileInputStream fis = new FileInputStream(keyStoreFile);
            char[] nPassword = password.toCharArray();
            inputKeyStore.load(fis, nPassword);
            Enumeration enumeration = inputKeyStore.aliases();
            String keyAlias = null;
            while (enumeration.hasMoreElements()) {
                keyAlias = (String) enumeration.nextElement();
            }
            X509Certificate certificate = (X509Certificate) inputKeyStore
                    .getCertificate(keyAlias);           
            publicKey = certificate.getPublicKey(); 

And Encrypt Code using Public Key of certificate.
=================================================

            Cipher cipher = Cipher.getInstance(xform); //xform:RSA/ECB/PKCS1Padding
            cipher.init(Cipher.ENCRYPT_MODE, publicKey );         
            return cipher.doFinal(Data.getEncoded());


C# compatible Code
===================

Include Namespace of Bouncy Castle Dll.

This DLL is freely available from this link http://www.bouncycastle.org/csharp/

using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;

 

               //Create file stream object to read certificate
                FileStream keyStream = new FileStream(strCertificatePath, FileMode.Open, FileAccess.Read);

                //Read certificate using BouncyCastle component
                Pkcs12Store inputKeyStore = new Pkcs12Store(keyStream, strCertificatePassword.ToCharArray());
                
                //Close File stream
                keyStream.Close();

                string keyAlias = null;

                //Read Key from Alieases  
                foreach (string n in inputKeyStore.Aliases)
                {
                    if (inputKeyStore.IsKeyEntry(n))
                    {
                        keyAlias = n;
                        break;
                    }
                }

                if (keyAlias == null)
                    throw new NotImplementedException("Alias");

                //Read certificate into 509 format
                X509Certificate certificate = (X509Certificate)inputKeyStore.GetCertificate(keyAlias).Certificate;

                //Retrieve public key of certificate
                AsymmetricKeyParameter publicKey = certificate.GetPublicKey();
                #endregion

                 //Encrypting (aesKey is a byte array containing an AES key): RSA/ECB/PKCS1Padding
                IAsymmetricBlockCipher cipher = new Pkcs1Encoding(new RsaEngine());
                cipher.Init(true, publicKey);
                byte[] encodedKey = cipher.ProcessBlock(SecretKey, 0, SecretKey.Length);
Tuesday, June 23, 2009 12:10:47 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0]   C#  | 

First add vjslib.dll from add reference link. Through this dll, we can compress data compatible with Java Compression.

Add Namespace into your class

using java.util.zip;
using java.util;
using java.io;

 

        /// <summary>
        /// This function is used to compress byte array data using java util.
        /// </summary>
        /// <param name="data">Byte Array Data</param>
        /// <param name="path">Path to Store compress File</param>
        /// <param name="fileName">File Name</param>
        public static void compressFileWrite(byte[] data, String path, String fileName)
        {

            try
            {
                java.io.File folder = new java.io.File(path + FORWARD_SLASH + ENCRYPT_OUTPUT_PATH);
                if (!folder.isDirectory())
                {
                    folder.mkdir();
                }
                java.io.File file = new java.io.File(folder.getPath() + FORWARD_SLASH + fileName);
                FileOutputStream fos = new FileOutputStream(file);
                DeflaterOutputStream dos = new DeflaterOutputStream(fos);
                dos.write((sbyte[])(Array)data);
                dos.close();
            }
            catch (java.io.FileNotFoundException Ex)
            {
                throw new Exception("Error while reading file \n" + Ex.Message);
            }
            catch (java.io.IOException Ex)
            {
                throw new Exception("Error in Compress File \n" + Ex.Message);
            }

        }

 This above code is compatible with java compression

Tuesday, June 23, 2009 11:49:36 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]   C#  | 
# Sunday, June 21, 2009
private void Page_Load(object sender, System.EventArgs e)
        {
            DataSet objds        = null;
            OleDbConnection conn = null;
            try
            {            
                if (File.Exists(Server.MapPath("UploadedFare/UploadedFare.xls").Trim()))
                {
                    gblConnSting = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath
                     ("UploadedFare/UploadedFare.xls").Trim() + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";                     conn    = new OleDbConnection(gblConnSting);;                                                          conn.Open();                     objds = new DataSet();                     OleDbDataAdapter objAdp    = new OleDbDataAdapter("select * from [Sheet1$] where
                                                                     [Airline] <> '' OR [Airline] <> null"
,conn);                     objAdp.AcceptChangesDuringFill = false;                     objAdp.Fill(objds);                             dgExcelData.DataSource    = objds.Tables[0].DefaultView;                     dgExcelData.DataBind();                 }                 else                     Response.Write("<B>No Fare Is Uploaded !</B>");             }             catch(Exception ex)             {                 new clsErrorLogging(ex);             }                     finally             {                 dgExcelData.Dispose();                 objds.Dispose();                 conn.Dispose();             }         }
 
Datagrid

       <asp:datagrid id="dgExcelData" runat="server" HeaderStyle-Wrap="False" BorderColor="LightGray"
        BorderWidth="1px">
        <ItemStyle Font-Size="X-Small" Wrap="False"></ItemStyle>
        <HeaderStyle Font-Size="Smaller" Font-Names="Verdana" Font-Bold="True" Wrap="False" HorizontalAlign="Center"
         ForeColor="Black" VerticalAlign="Middle" CssClass="tableheadergrey2" BackColor="Gainsboro" ></HeaderStyle>
       </asp:datagrid>
Sunday, June 21, 2009 11:37:58 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]   asp.net | C#  | 

Threading enables your C# program to perform concurrent processing so you can do more than one operation at a time.
C# supports parallel execution of code through multithreading.Threads are relatively
lightweight processes responsible for multitasking within a single
application.Thread is an independent execution path, able to run simultaneously
with other threads.
For implementing Threading, you first include System.Threading namespace in your project.

class ThreadClass
{
    static void Main() {
    Thread thread1 = new Thread (Display("1");
    Thread thread2 = new Thread (Display("2"));
    thread1.Start();
    thread2.Start();      // Run on the new thread
   
  }

    static void Diaplay(string strparameter)
    {
        while (true) Console.Write(strparameter);   // Write forever
    }
}

In the above program, two thread simultaneously running.
We can share a data between multiple thread through static variable.

class ThreadClass {
  static void Main() {
 static int num;
    Thread thread1 = new Thread (Display("Thread 1");
    Thread thread2 = new Thread (Display("Thread 2"));
    thread1.Start(); 
    thread2.Start();      // Run on the new thread
    
  }
 
  static void Diaplay(string strparameter) {
    while (true) 
    {
  num ++;
  Console.Write (num.ToString() + " " + strparameter);   // Write forever
 }
  }
}

In the above program, we are declaring a num static variable and this number is incrementing
by both thread.

Joining Threads:-Joining is used for blocks the calling thread until a thread terminates. Means
thread to stop processing and wait until a second thread completes its work,
----------
Once a thread starts running and in some situation if we need to tell the thread to stop processing and wait until a second thread completes processing, we need to join the first thread to the second thread. Use the following for the same. This will join the second thread to the first one.
---------

Sleep Threads:- you want to suspend your thread for a short time. For this  Thread
class provide a public static method "Sleep". Sleep is an overloaded function.

Thread.Sleep (Int32):  Suspends the current thread for a specified time.
e.g. thread1.Sleep(1000) //Sleep for 1000 millisecond
 Thread.Sleep (0); // give up CPU time-slice
Thread.Sleep (TimeSpan):  Blocks the current thread for a specified time. 
e.g. Thread.Sleep (TimeSpan.FromSeconds (5));
Thread.Sleep (TimeSpan.FromHours (1)); // sleep for 1 hour
Thread.Sleep (Timeout.Infinite); // sleep until interrupted

Killing Threads: Thread kill itself after completing its task, but you want to kill thread
before completing its task. For this you can use Abort() function.
e.g. thread1.Abort();
-----------
Threads has to die after the execution of the process in normal situations, occasionally it is required for the programmer to kill a thread. Threads can be killed using the following:
-----------
Suspend Thread: You want to stop executing your thread then you use Suspend() method and for running the suspending thread
You use Resume() method.

Thread Priority: Thread priority is basically used for giving which thread is high priority or
low priority. There are five level of priority
*Highest
*AboveNormal
*Normal
*BelowNormal
*Lowest

e.g.
 thread1.Priority = ThreadPriority.BelowNormal;
 thread2.Priority = ThreadPriority.Highest;
 
 Thread.ThreadState Property: ThreadState property gives the current state of thread status.
The initial value is Unstarted.
 ThreadState.Aborted
 ThreadState.AbortRequested
 ThreadState.Stopped
 ThreadState.Unstarted
 ThreadState.WaitSleepJoin;
 ThreadState.Background;
 ThreadState.SuspendRequested;
 ThreadState.Suspended
All of the above property return true or false on the basis of its status.
if you want to check abort status of thread1 then
  if ( thread1.ThreadState == ThreadState.Suspended}
 {
  thread1.Resume();//to again start the thread
 }
Rsume method is used for running the suspended thread. if the thread is not suspended then there will be no effect on thread status.

LOCK
====
"Change Style(Copied)
 lock marks a critical section of the code, and provides synchronization to an object.

Example:

public void Incrementer( )
{
  try
  {
    while (counter < 1000)
    {
      lock (this)
      {
        int temp = counter;
        temp ++;
        Thread.Sleep(1);
        counter = temp;
      }
      // assign the decremented value
      // and display the results
      Console.WriteLine("Thread {0}. Incrementer: {1}", 
         Thread.CurrentThread.Name, counter);
    }
  }

Sunday, June 21, 2009 11:30:18 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]   C#  | 
Copyright © 2010 SoftwareCodeHelp. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: