Blog Home  Home Feed your aggregator (RSS 2.0)  
Software Code Help - Tuesday, June 23, 2009
Blog
 
# 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#  | 
# Monday, June 22, 2009
      Microsoft .net framework provide a facility for sending mail using System.Web.Mail(SMTP)
      First include this using System.Web.Mail in your code, For sending mail we are creating a function sendMail,
      it is used for sending email. For correctly running
      this code, please find register two dll "cdonts.dll" and "cdosys.dll".
      These two dll is microsoft dll used for sending mail.
 
      public void sendMail()
        { 

            try 

            {  

                //Provides properties and methods for sending messages using the Collaboration Data Objects for 
                  Windows 2000 (CDOSYS) message component.
                SmtpMail.SmtpServer= "SMTP Server IP Address";                 MailMessage msg = new MailMessage();                 // Specify the e-mail sender.                 msg.From = "rajshekhar@mail.com";//Self mail address // Set destinations for the e-mail message.                 msg.To = "Send Email Address";                 // Set destinations of Carbon Copy(CC) for the e-mail message.                 msg.Cc = "CC Email Address;                 // Set destinations of Blind carbon copies(BCC) for the e-mail message.                 msg.Bcc = "BCC Email Address";                 // Specify the message subject.                 msg.Subject = this.txtSubject.Text;                 // Specify the message content.                 msg.Body = "Content of Message Assign Here";                 msg.BodyFormat = MailFormat.Text;                 //The username for authenticating to an SMTP server using basic (clear-text) authentication.                 msg.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendusername",
                                 "itq@vmaildeliver.vsnl.com");
                //The password used to authenticate to an SMTP server using basic (clear-text) authentication.                 msg.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendpassword","itq.1.123");                 /%                         Specifies the authentication mechanism to use when authentication is required to send messages
                to an SMTP service using a TCP/IP network socket.                                                          The Secound parameter in smtpauthenticateis CdoProtocolsAuthentication enumeration, It is
                used to specify the mechanism used when authenticating to a Simple Mail Transfer Protocol(SMTP)
                service over the network.                 It has three different type of value:                 Name            Value                Description                 ====            =====                ============                 cdoAnonymous     0                 Do not authenticate.                                  cdoBasic         1                 Use basic (clear-text) authentication. The configuration
                                                   sendusername/sendpassword or postusername/postpassword fields
                                                  are used to specify credentials.                                  cdoNTLM             2              Use NTLM authentication (Secure Password Authentication in
                                                   Microsoft® Outlook® Express).The current process security
                                                   context is used to authenticate with the service.                                  */                                             msg.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1);                 //Sending Message                             SmtpMail.Send(msg);                              }             catch (Exception ex)             {                 ErrorMessage("Send Mail Process was failed!!!");                              }             finally             {                                  SuccessMessage("Send Mail Process was successfull!!!");             }         }

You can use this above code for sending mail using SMTP in ASP.NET.

Monday, June 22, 2009 11:26:30 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]   .Net | asp.net  | 
# Sunday, June 21, 2009

In SQL Server 2000,


sp_lock is used to find dead lock inside the database.
if any dead lock occur then using "Kill spid" is to remove the dead lock.

Sunday, June 21, 2009 11:39:11 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]   SQL Server  | 
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#  | 

HTTP Channel
The HTTP channel transports messages to and from remote objects using the SOAP protocol. All messages are passed through the SOAP formatter, where the message is changed into XML and serialized, and the required SOAP headers are added to the stream. It is also possible to configure the HTTP Channel to use the binary formatter. The resulting data stream is then transported to the target URI using the HTTP protocol.


TCP Channel
The TCP channel uses a binary formatter to serialize all messages to a binary stream and transport the stream to the target URI using the TCP protocol. It is also possible to configure the TCP channel to the SOAP formatter.

Sunday, June 21, 2009 11:33:06 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]   General  | 

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#  | 

we can attach javascript in code behind using this style

 

private void Page_Load(object sender, System.EventArgs e)

{

System.Text.StringBuilder StrValidation = new System.Text.StringBuilder();

//Appending javascript in this string builder

StrValidation.AppendFormat("{0}",@"<script language='javascript'>

function validateForm()

{

if (isBlank(document.baseForm.txtEmail.value)) {

alert('Email ID can not be blank1 !');

document.baseForm.txtEmail.focus();

return false;

}

if (isBlank(document.baseForm.txtSubject.value)) {

alert('Subject can not be blank !');

document.baseForm.txtSubject.focus();

return false;

}

if (isBlank(document.baseForm.txtMessage.value)) {

alert('Please Enter Message in Message Box !');

document.baseForm.txtMessage.focus();

return false;

}

return true;

} </script>");

Page.RegisterClientScriptBlock("AddValidation",StrValidation.ToString());

this.ibtnSubmit.Attributes.Add("onClick", "return validateForm();");

Sunday, June 21, 2009 11:21:26 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0]   asp.net  | 

private void Page_Load(object sender, System.EventArgs e)

{

      base.OuterTable.HorizontalAlign = HorizontalAlign.Center;

      base.ContentBar.VerticalAlign = VerticalAlign.Top;

}

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