This is code when i create my sample web application i want to create html ui in back end code so i created using string builder.
if (dt.Rows.Count > 0)
            {
                StringBuilder strb = new StringBuilder();
                strb.Append("<br/><br/>");
                strb.Append("<table border='1' cellpadding='3'>");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strb.Append("<tr><td>");
                    strb.Append(dt.Rows[i]["Subject"].ToString());
                    strb.Append("</td>");
                    strb.Append("<td>");
                    strb.Append("<input type=\"text\" name=\"subject\" id=\"txtSubject" + i.ToString() + "\" runat=\"server\" />");
                    strb.Append("<input type=\"hidden\" name=\"hidsubject\" id=\"hidSubject" + i.ToString() + "\" runat=\"server+\" value=" + dt.Rows[i]["Subject_ID"].ToString() + "/>");
                    strb.Append("</td></tr>");
                }
                //subject = subject + "," + dt.Rows[i]["Subject_ID"].ToString();
                //hidSubject.Value = subject;
                strb.Append("</table>");
                divMark.InnerHtml = strb.ToString();
            }
Read more ...

This solution i experienced. when i develop wpf application there i used combobox. when i try to add new student that time combobox items not reloaded. because of application loading time i loaded dynamically. so i don't no how to refresh the combobox list. After that i got this solution. when u add new item while after "objwindow.ShowDialog()" refresh the combobox.
 <ComboBox Name="Student" ItemsSource="{Binding Source={StaticResource Students}, XPath=Student/@StudentName}"
SelectionChanged="{pti:DelegateCreator student_Changed}" MinWidth="150"
Style="{StaticResource RequiredComboBox}" />
if you want to refresh from the controller your combobox name declare commonly like
ComboBox _studentList = FindLogicalNode(window, STUDENT_LIST) as ComboBox;
other wise your refresh from the xaml.cs file there your can declare like "this.FindResource"
private static void studentConfig_Click(object source, RoutedEventArgs args)
        {
            StudentConfiguration objwindow = new StudentConfiguration();
            objwindow.ShowDialog();
            (_studentList.FindResource("Students") as XmlDataProvider).Refresh();            
        }
Read more ...

This code when i want to get all my system printer list and set the default printer in my application while i used this code its working good. because of i want to do bar code printer so i have used more then one printer. Its very easy to get the system printer name using this method.
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Drawing.Printing;

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

    private void Form1_Load(object sender, EventArgs e)
    {
        printer();
    }

    public static void printer() 
    {
        foreach (string printer in PrinterSettings.InstalledPrinters)
                 Console.WriteLine(printer);
 
            var printerSettings = new PrinterSettings();
            Console.WriteLine(string.Format("The default printer is: {0}",                         printerSettings.PrinterName));                 
     }
}
Read more ...

This is code Add xml node in configuration file using C# method. Step:1 this is sample.config file
<TABLE>
<ROW>
    <COLUMN SOURCE="1" NAME="age" />
    <COLUMN SOURCE="3" NAME="firstname" />
    <COLUMN SOURCE="4" NAME="lastname" />
  </ROW>
</TABLE>
Step:2 I want to add xml node for my application configuration settings. so i want to add configuration setting using user interface Step:3 I created user interface one add page for add xml node. Step:4 I used this method and pass the xml value add the node.
public bool AddconfigFileXmlNode()
        {
            try
            {
                var doc = new XmlDocument();
                doc.Load("D:\\sample.config");
                 
                XmlNode profile;                
                profile = doc.SelectSingleNode("TABLE/ROW");

                XmlElement newChild = doc.CreateElement("COLUMN");

                newChild.SetAttribute("SOURCE", "4");
                newChild.SetAttribute("NAME", "lastname");  
            

                profile.AppendChild(newChild);
                doc.Save("D:\\sample.config");
            }
            catch { }
            return true;
        }
Read more ...

This is split the your string value using the special character
 private void SplitString()
        {
     string _BaseString="RIVE-SENT-KUMA-XXX"
            string[] seperate_filelds = _BaseString.Split('-');
            int counter = 0;
           // bool is_legit = false;

            foreach (string each_field in seperate_filelds)
            {
                counter++;
                // reading the first field which is prefix field
                if (counter == 1)
                {
     //fristValue = "RIVE";
                   string fristValue = each_field  ;

                }
                else if (counter == 2)
                {
                    //secondValue = "SENT";
                   string secondValue = each_field  ;
                }
  else if (counter == 3)
                {
                    //thirdValue = "SENT";
                   string secondValue = each_field  ;
                }
  else if (counter == 4)
                {
                    //furthValue = "XXXX";
                   string furthValue = each_field  ;
                }
               else
                { break; }
            }
                     
        }
Read more ...

This is one way of Encryption and Decryption algorithm. Its working good.
  private const string initVector = "tu89geji340t89u2";

        private const int keysize = 256;

        public static string Encrypt(string Text, string Key)
        {
            byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(Text);
            PasswordDeriveBytes password = new PasswordDeriveBytes(Key, null);
            byte[] keyBytes = password.GetBytes(keysize / 8);
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();
            byte[] Encrypted = memoryStream.ToArray();
            memoryStream.Close();
            cryptoStream.Close();
            return Convert.ToBase64String(Encrypted);
        }

        public static string Decrypt(string EncryptedText, string Key)
        {
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            byte[] DeEncryptedText = Convert.FromBase64String(EncryptedText);
            PasswordDeriveBytes password = new PasswordDeriveBytes(Key, null);
            byte[] keyBytes = password.GetBytes(keysize / 8);
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
            MemoryStream memoryStream = new MemoryStream(DeEncryptedText);
            CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
            byte[] plainTextBytes = new byte[DeEncryptedText.Length];
            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            memoryStream.Close();
            cryptoStream.Close();
            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
        }
Read more ...

I want to know my system information using C# 1. ProcessorId 2. Product 3. Manufacturer 4. Signature 5. Caption 6. PhysicalMedia(SerialNumber) 7. Version 8. OperatingSystem(SerialNumber) just call the method like this:
RunQuery("Processor", "ProcessorId");
RunQuery("BaseBoard", "Product");
RunQuery("BaseBoard", "Manufacturer");
RunQuery("DiskDrive", "Signature");
RunQuery("VideoController", "Caption");
RunQuery("PhysicalMedia", "SerialNumber");
RunQuery("BIOS", "Version");
RunQuery("OperatingSystem", "SerialNumber");
 private static string RunQuery(string TableName, string MethodName)
        {
            ManagementObjectSearcher MOS = new ManagementObjectSearcher("Select * from Win32_" + TableName);
            foreach (ManagementObject MO in MOS.Get())
            {
                try
                {
                    return MO[MethodName].ToString();
                }
                catch (Exception e)
                {
                    System.Windows.Forms.MessageBox.Show(e.Message);
                }
            }
            return "";
        }
Read more ...

This code remove the special character from string value using c sharp. when i want to string value only the aliphatic and number. I trim the special character using the method.
private static string RemoveUseLess(string st)
        {
            char ch;
            for (int i = st.Length - 1; i >= 0; i--)
            {
                ch = char.ToUpper(st[i]);

                if ((ch < 'A' || ch > 'Z') &&
                    (ch < '0' || ch > '9'))
                {
                    st = st.Remove(i, 1);
                }
            }
            return st;
        }
Read more ...

Cryptography Alogrithm using C#

Posted by senthil | 10:13:00 PM | | 0 comments »

This is Encryption and Decryption algorithm. Its work good I used on this code working perfectly.
public static string Encrypt(string toEncrypt, bool useHashing)
{
    byte[] keyArray;
    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

    System.Configuration.AppSettingsReader settingsReader = 
                                        new AppSettingsReader();
    // Get the key from config file

    string key = (string)settingsReader.GetValue("SecurityKey", 
                                                     typeof(String));
    //System.Windows.Forms.MessageBox.Show(key);
    //If hashing use get hashcode regards to your key
    if (useHashing)
    {
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        //Always release the resources and flush data
        // of the Cryptographic service provide. Best Practice

        hashmd5.Clear();
    }
    else
        keyArray = UTF8Encoding.UTF8.GetBytes(key);

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    //set the secret key for the tripleDES algorithm
    tdes.Key = keyArray;
    //mode of operation. there are other 4 modes.
    //We choose ECB(Electronic code Book)
    tdes.Mode = CipherMode.ECB;
    //padding mode(if any extra byte added)

    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateEncryptor();
    //transform the specified region of bytes array to resultArray
    byte[] resultArray = 
      cTransform.TransformFinalBlock(toEncryptArray, 0, 
      toEncryptArray.Length);
    //Release resources held by TripleDes Encryptor
    tdes.Clear();
    //Return the encrypted data into unreadable string format
    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}





public static string Decrypt(string cipherString, bool useHashing)
{
    byte[] keyArray;
    //get the byte code of the string

    byte[] toEncryptArray = Convert.FromBase64String(cipherString);

    System.Configuration.AppSettingsReader settingsReader = 
                                        new AppSettingsReader();
    //Get your key from config file to open the lock!
    string key = (string)settingsReader.GetValue("SecurityKey", 
                                                 typeof(String));
            
    if (useHashing)
    {
        //if hashing was used get the hash code with regards to your key
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        //release any resource held by the MD5CryptoServiceProvider

        hashmd5.Clear();
    }
    else
    {
        //if hashing was not implemented get the byte code of the key
        keyArray = UTF8Encoding.UTF8.GetBytes(key);
    }

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    //set the secret key for the tripleDES algorithm
    tdes.Key = keyArray;
    //mode of operation. there are other 4 modes. 
    //We choose ECB(Electronic code Book)

    tdes.Mode = CipherMode.ECB;
    //padding mode(if any extra byte added)
    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateDecryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(
                         toEncryptArray, 0, toEncryptArray.Length);
    //Release resources held by TripleDes Encryptor                
    tdes.Clear();
    //return the Clear decrypted TEXT
    return UTF8Encoding.UTF8.GetString(resultArray);
}



<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
Read more ...

Related Posts Plugin for WordPress, Blogger...