Friday, 17 June 2011

Work Musings - Open File Dialog

The other day while working on the open file dialog control in c#, it dawned to us that the openfiledilalog remembers the path of the previous file. This can introduce subtle errors. As an example let us assume that we have an app that writes a line of text to a file such as say a disclaimer.



private void button1_Click(object sender, EventArgs e)
{
String fileName = String.Empty;
DialogResult dlg = openFileDialog1.ShowDialog();
fileName = openFileDialog1.FileName;
if (String.IsNullOrEmpty(fileName) == false)
{
StreamWriter wrt = new StreamWriter(fileName, true);
wrt.WriteLine("So lets see this is my impact ");
wrt.Close();

}

}

IF the user were to open a file for the first time and write the disclaimer to it and
then decides to open a second file in the open file dialog and presses cancel , the
openfile dialog will still remember the previous file name and cause the text to be written again.


To over come this , this piece of code will be apt :
private void button1_Click(object sender, EventArgs e)
{
String fileName = String.Empty;
//Note how the file Name is initialized
`````````` DialogResult dlg = openFileDialog1.ShowDialog();
switch (dlg)
{
case DialogResult.OK:
fileName = openFileDialog1.FileName;
break;
default:
fileName = String.Empty;
break;

}

if (String.IsNullOrEmpty(fileName) == false)
{
StreamWriter wrt = new StreamWriter(fileName, true);
wrt.WriteLine("So lets see this is my impact ");
wrt.Close();

}

}

Sunday, 22 November 2009

Play Fair Cipher

Hey Folks,
The other day I coded Play Fair cipher using C#. and Here is the code for it.
If you have any doubts, you can ask me. I have made the code as close to C as possible.

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

namespace PlayFairCipher
{

class Cipher
{
char[] alphaMap; //alphaMap will hold all alphabets from a to z.
//In the play fair cipher we dont make a distinction
//between captial and small letters
//Instead of making alphamap manually hold all the characters
// like alphaMap[0] = 'a', I have filled it using a simple
//constructor method
string keyword; //The Key that is given by the user.
char[,] LookupTable;
string encryptedText;
string decryptedText;
string Text;
public Cipher() {

alphaMap = new char[26]; //fill alphaMap using a simple loop
for (int i = 0; i < 26; i++){
int t = (int)'a';
alphaMap[i] = (char)(t + i);
}
LookupTable = new char[5, 5];
}
//This module takes the keyword and based on that generates the lookup
//Table.
//In the lookup Table, I have fused y and Z, in general J and I are fused
//However there is no hard and fast rule that only J and I must be fused
public void generateTable()
{
int k = 0;
int i = 0;
int j = 0;
int[] flagarray; //flag array is used to tell if the alphabet is already
flagarray = new int[25];// covered in the array or not
Console.WriteLine("Enter your Key word");
string inputText= Console.ReadLine();
for (i = 0; i < inputText.Length; i++)
if (Char.IsLetter(inputText[i]))
{
if (inputText[i] != 'z')
keyword += inputText[i];
else
keyword += 'y';
}


keyword = keyword.ToLower();
char[] table;
table = new char[26]; // instead of a 2D, we shall use a single Dimensonal array
//that will be used to populate the lookup table
for (k = 0, i = 0; i < keyword.Length; i++)
{
int p = (int)keyword[i] - (int)('a'); //97 is the ascii code for a
if (flagarray[p] != 1)
{

table[k] = keyword[i];
flagarray[p] = 1;
k++;
}


}
for ( j = 0; j < 25; j++)
{
if (flagarray[j] == 0)
{
table[k] = alphaMap[j];
k++;
}

}

for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
LookupTable[i, j] = table[i * 5 + j];

}

}


}
public void Decrypt()
{
int startindex = 0;
int endindex = 2; //startindex+2 as we will take 2 chars at a time
int increment = 2;//as we are taking 2 characters at a time
while (endindex <= Text.Length)
{
decryptedText += getDecode(startindex, increment);
startindex = endindex;
endindex += 2;


}

Console.WriteLine("\n*********************************************");
Console.WriteLine("Decrypted String with X not Stripped");
Console.WriteLine(decryptedText);
Console.WriteLine("\n*********************************************");
Console.WriteLine("\n*********************************************");
Console.WriteLine("Decrypted String with X removed ");
string StrippedString="";
for (int i = 0; i < decryptedText.Length; i++)
if (decryptedText[i] != 'x')
StrippedString += decryptedText[i];
Console.WriteLine(StrippedString);
Console.WriteLine("\n*********************************************");
Console.WriteLine("\n*********************************************");
Console.WriteLine("Encoding had fused Y and Z together");
Console.WriteLine("Replace all Y by Z Another String is ");
string yReplacedByZString="";
for (int i = 0; i < StrippedString.Length; i++)
if (StrippedString[i] == 'y')
yReplacedByZString += 'z';
else
yReplacedByZString += StrippedString[i];
Console.WriteLine(yReplacedByZString);
Console.WriteLine("\n*********************************************");

}

public void Encrypt()
{

string inputText;
Console.WriteLine("Enter your String \n"); //Can be made to read from a file also
inputText = Console.ReadLine();
for(int i =0;i if (Char.IsLetter(inputText[i]))
{
if (inputText[i] != 'z')
Text += inputText[i];
else
Text += 'y'; //Replace all z by y;
}
Text = diagraph(Text); //the text sans repeating and odd length

Console.WriteLine("\n*************************************");
Console.WriteLine("Text sans Repeating characters and stuffed with X and z replaced by Y :");
Console.WriteLine(Text);
Console.WriteLine("\n*********************************************");
encryptedText = getTextFromLookUpTable();
Console.WriteLine("\n*********************************************");
Console.WriteLine("Encrypted Sting :");
Console.WriteLine(encryptedText);
Console.WriteLine("\n*********************************************");
//Console.ReadLine();

}

private string getTextFromLookUpTable()
{
string Lookuptext="";
//Read Two characters at time and then Encrypt it
int startindex = 0;
int endindex = 2; //startindex+2 as we will take 2 chars at a time
int increment = 2;//as we are taking 2 characters at a time
while (endindex <=Text.Length)
{
Lookuptext += getEncode(startindex,increment);
startindex = endindex;
endindex += 2;


}
return Lookuptext;
}

//The Encoding module
public string getEncode(int startindex,int increment)
{
String temp = Text.Substring(startindex, increment);
String encodedText="";
char firstChar = temp[0];
char secondChar = temp[1];
int firstcharRow = 0;
int secondcharRow = 0;
int firstcharColumn = 0;
int secondcharColumn = 0;
string encodedFirstChar = "";
string encodedSecondChar = "";
int i = 0;
int j = 0;
//we have fused Y and Z together as Y , so when Z comes we use an
//automatic implication
if(firstChar == 'z' || secondChar == 'z'){
if(firstChar=='z'){

firstcharRow = 5;
firstcharColumn = 5;
}
else {
secondcharRow = 5;
secondcharColumn = 5;

}


}

if (firstcharColumn != 5)//firstchar is not a z so we try to determine
{
for(i=0;i<5;i++)
for(j=0;j<5;j++)
if (LookupTable[i, j] == firstChar)
{
firstcharRow = i;
firstcharColumn = j;
break;

}


}

if (secondcharColumn != 5)//secondchar is not a z so we try to determine
{
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
if (LookupTable[i, j] == secondChar)
{
secondcharRow = i;
secondcharColumn = j;
break;

}


}
//Now that we have obtained the first and the second character positions
//in the look up table , we can now look at three cases
//case1 : Row and columns of both the induvidual characters are different
if ((firstcharColumn != secondcharColumn) && (secondcharRow != firstcharRow))
{
encodedFirstChar+= LookupTable[firstcharRow, secondcharColumn];
encodedSecondChar+= LookupTable[secondcharRow, firstcharColumn];
encodedText = encodedFirstChar + encodedSecondChar;


}
//case 2 : First and second Characters are in the same Row
//replace first character character on its immediate right
//similiarly second character by character on its immediate right
else if (firstcharRow == secondcharRow)
{
firstcharColumn = (firstcharColumn + 1) % 5; //to wrap around
secondcharColumn = (secondcharColumn + 1) % 5;

encodedFirstChar += LookupTable[firstcharRow, firstcharColumn];
encodedSecondChar += LookupTable[secondcharRow, secondcharColumn];
encodedText = encodedFirstChar + encodedSecondChar;




}

//case 3: Characters are in the same column
//Keeping the column number constant increment the
//rownumber by 1
else if (secondcharColumn == firstcharColumn)
{

firstcharRow = (firstcharRow + 1) % 5; //to wrap around
secondcharRow = (secondcharRow + 1) % 5;

encodedFirstChar += LookupTable[firstcharRow, firstcharColumn];
encodedSecondChar += LookupTable[secondcharRow, secondcharColumn];
encodedText = encodedFirstChar + encodedSecondChar;



}
return encodedText;
}

//The Decoding module
public string getDecode(int startindex, int increment)
{
String temp = encryptedText.Substring(startindex, increment);
String decodedText = "";
char firstChar = temp[0];
char secondChar = temp[1];
int firstcharRow = 0;
int secondcharRow = 0;
int firstcharColumn = 0;
int secondcharColumn = 0;
string decodedFirstChar = "";
string decodedSecondChar = "";
int i = 0;
int j = 0;



for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
if (LookupTable[i, j] == firstChar)
{
firstcharRow = i;
firstcharColumn = j;
break;

}

for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
if (LookupTable[i, j] == secondChar)
{
secondcharRow = i;
secondcharColumn = j;
break;

}



//Now that we have obtained the first and the second character positions
//in the look up table , we can now look at three cases
//case1 : Row and columns of both the induvidual characters are different
if ((firstcharColumn != secondcharColumn) && (secondcharRow != firstcharRow))
{
decodedFirstChar += LookupTable[firstcharRow, secondcharColumn];
decodedSecondChar += LookupTable[secondcharRow, firstcharColumn];
decodedText = decodedFirstChar + decodedSecondChar;


}
//case 2 : First and second Characters are in the same Row
//replace first character character on its immediate left
//similiarly second character by character on its immediate left
else if (firstcharRow == secondcharRow)
{
firstcharColumn = (firstcharColumn -1) ; //to wrap around
secondcharColumn = (secondcharColumn -1) ;
if (firstcharColumn < 0)
firstcharColumn = 4;
if (secondcharColumn < 0)
secondcharColumn = 4;
decodedFirstChar += LookupTable[firstcharRow, firstcharColumn];
decodedSecondChar += LookupTable[secondcharRow, secondcharColumn];
decodedText = decodedFirstChar + decodedSecondChar;




}

//case 3: Characters are in the same column
//Keeping the column number constant decrement the
//rownumber by 1
else if (secondcharColumn == firstcharColumn)
{

firstcharRow = (firstcharRow -1) ; //to wrap around
secondcharRow = (secondcharRow -1);
if (firstcharRow < 0)
firstcharRow = 4;
if (secondcharRow < 0)
secondcharRow = 4;
decodedFirstChar += LookupTable[firstcharRow, firstcharColumn];
decodedSecondChar += LookupTable[secondcharRow, secondcharColumn];
decodedText = decodedFirstChar + decodedSecondChar;



}
return decodedText;
}






//This module does two things, in case of repeating letters like
//aa, replaces by axa
//Also sees that the lenght of the string is even,
//if not the string is padded with an x
private string diagraph(string sample)
{
string temp = sample;
int i = 0;
string placeHolder = "";
for (i = 0; i < (temp.Length-1); i++)
if (temp[i] == temp[i + 1] )
{
placeHolder += temp[i];
placeHolder += "x";


}
else placeHolder += temp[i];
placeHolder += temp[i];
if ((placeHolder.Length % 2) != 0)
placeHolder += 'x';

return placeHolder;
}


public void Display()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
Console.Write(LookupTable[i, j] + " ");

}
Console.WriteLine();
}

}
}



class Program
{
static void Main(string[] args)
{


Cipher c1 = new Cipher();
c1.generateTable();// Generate a Look Up Table
c1.Display();//Display the Look Up Table
c1.Encrypt(); //Encrypt the String
c1.Decrypt();//Decrypt the String
Console.WriteLine("\n*********************************************");
Console.WriteLine("Have a Nice Day ");
Console.ReadLine();


}
}
}