Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, April 7, 2009

Calling Javascript functino from your code behind in ASP.Net

Here is the code by which you can call a javascript function within any where of you C# code.



Page.ClientScript.RegisterStartupScript(Page.GetType(), "YourPrompt",
"<script>alert('Hello');</script>");



Hope it works.

Thanks
/Zaq

Wednesday, March 4, 2009

Zip/Unzip using C#

I have spent few hours over internet to find out a way to create zip file using .net 2.0, C#. My intention was to avoid any third party library or application. I started with System.IO.Compression, but I did not find any resource about creating a zip from a directory with files and subdirectory as well. I got few .net library and I felt few of those are quite familier and using wiedly. But as I have some restriction i can not use those. Finally I got a solutoin to create and extract zip file using Shell32.dll. Here is two functions I wrote.

private static void ZipFile(string sourceFolder, string destinationFile)
{
byte[] emptyzip = new byte[] { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

FileStream fs = File.Create(destinationFile);
fs.Write(emptyzip, 0, emptyzip.Length);
fs.Flush();
fs.Close();
fs = null;

//Copy a folder and its contents into the newly created zip file
Shell32.ShellClass sc = new Shell32.ShellClass();
Shell32.Folder SrcFlder = sc.NameSpace(sourceFolder);
Shell32.Folder DestFlder = sc.NameSpace(destinationFile);
Shell32.FolderItems items = SrcFlder.Items();
DestFlder.CopyHere(items, 20);
}


private static string UnzipFile(string inputFileName, string destinationPath)
{
if (!Directory.Exists(destinationPath))
Directory.CreateDirectory(destinationPath);

Shell shell = new ShellClass();
Folder sourceFolder = shell.NameSpace(inputFileName);
Folder destinationFolder = shell.NameSpace(destinationPath);
string outputFileName = sourceFolder.Items().Item(0).Name;
destinationFolder.CopyHere(sourceFolder.Items(), "");
return outputFileName;
}


Here is the code to call those function.

ZipFile(@"D:\SourceFolder", @"D:\MyZip.zip");

UnzipFile(@"D:\MyZip.zip", @"D:\ExtractFolder");

Hope this may help you. Thanks.

Tuesday, September 16, 2008

Execute Java jar file from .Net

Step1: Creating a Java Class

package ZAQ;

import javax.swing.JOptionPane;
public class Hello {
public static void main (String [] args) {
JOptionPane.showMessageDialog(null, "Hello World!");
}
}

Put this Class Inside ZAQ directory and set the class file name as Hello.java


Step2: Preparing of mainClass.txt file.
Write the following line in the file. Please remember to put a carriage return after the line.
Main-Class: ZAQ.Hello


Step3: Compile the Java Class and Build the jar file
Create class file for Hello.java and then build the jar file. Do the following commands
->Javac ZAQ/Hello.java
->jar cmf mainClass.txt ZAQ.jar ZAQ
->java –jar ZAQ.jar Hello
Now your jar is ready.


Step4: Create a batch file to be execute in .Net
Save a file with the following text:
java -jar D:\ZAQ.jar


Step5: .Net code is here.

int i = 0;
string sOut = ShellExec(@"d:\Comm.bat", "", "", out i);
Console.WriteLine(sOut);

And the function is here:

protected static String ShellExec(String cmd, String path, String parms, out int exit_code)
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(path + cmd, parms);
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;

System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
string tool_output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
exit_code = p.ExitCode;
return tool_output;
}

Sunday, September 14, 2008

Use windows authentication for your own application.

This sample is very short and clear, if you wish to authenticate your application user as a windows or domain user then follow the next few steps.

Step1: declare an external function like this.
[DllImport("advapi32.dll", SetLastError = true)]
protected static extern bool LogonUser(string sUsername, string sDomain, string sPassword,
int iLogonType, int iLogonProvider, ref IntPtr ipToken);


Step2: Call the function.
IntPtr pExistingTokenHandle = new IntPtr(0);
pExistingTokenHandle = IntPtr.Zero;
const int LOGON32_PROVIDER_DEFAULT = 0;
// create token
const int LOGON32_LOGON_INTERACTIVE = 2;
string sUserName = "use1";
string sDomain = "domain1";
string sPassword = "Test123";
bool bImpersonated = LogonUser(sUserName, sDomain, sPassword,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);

This "bImpersonated" return True if user authenticated and false if not. And you can decide actions for your application based on this.

Sunday, September 7, 2008

Playing with Windows Registry, CRUD

In this article I’ll show the sample for each operation of CRUD for Win32 Registry. There is nothing theoretical that you should know before this, just should have idea what is win32 registry and how a developer can use it for a product.
Registry keeps information in a hierarchy format. You can put here data for using globally for a client PC. That means if you set a registry value you may use it for any number of product installed on this PC. But this place is not for storing huge data or operation data for your application, rather this place to keep information like settings information, license information, last instance value of your product, or even you can save URL for use external services. I can show hundreds of examples in where you can use Registry as a repository, but I think it’s up to you that how you would like take the advantage of this. Just leave it here and start play with this.

Create a Registry:
In Registry you will be able to save several data type but all will be under a key. In hierarchy it shows like a directory but registry will count this as a Key. So, you can add a key, string, binary, multi-string value and few more type of data under a Key. Here is the code:

string sPath = "HKEY_LOCAL_MACHINE\\SOFTWARE\\TestingRegistry\\ZAQ\\";
string sKeyName = "Address";

static void CreateSubKey(string sPath, string sKeyName, string sValue)
{
RegistryKey reg = null;
if (sPath.Contains("HKEY_LOCAL_MACHINE"))
{
reg = Registry.LocalMachine.CreateSubKey(sPath.Replace("HKEY_LOCAL_MACHINE\\", ""));
reg.SetValue(sKeyName, sValue);
}
else if (sPath.Contains("HKEY_CURRENT_USER"))
{
reg = Registry.CurrentUser.CreateSubKey(sPath.Replace("HKEY_CURRENT_USER\\", ""));
reg.SetValue(sKeyName, sValue);
}
}


Let’s consider you will call this function with this way.
CreateSubKey(sPath,"Phone","010101");
So, this function will add a string value named “Phone” under the key of “ZAQ”. But if you will look at this hierarchy then you will find it will be more logical if there will be a Key name “Address” and the phone number data will be kept under this. To do this you just need to change the “sPath” and make it more extended.

string sPath = "HKEY_LOCAL_MACHINE\\SOFTWARE\\TestingRegistry\\ZAQ\\Address";

So now this one will create a Key name Address and then the Phone number will be kept.

Tuesday, September 2, 2008

Example for Encryption and Decryption with C#.

This example describes how a simple Encryption and Decryption can be written and how those functions can be used from client application.

First we will create a singleton Utility class which will contain Encryption and Decryption functions. For Cryptography operation two values will be required which are “Key” and “IV”. By default I have set those values and also I expose properties for both, so that you can use these values when you will use this class as per your demand.


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

namespace ZAQ.Util.CCryptography
{
public class CCryptography
{
protected string sKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456";
protected string sIV = "ABCDEFGHIJKL";

protected byte[] bKey;
protected byte[] bIV;

private CCryptography()
{
bKey = Convert.FromBase64String(sKey);
bIV = Convert.FromBase64String(sIV);
}

public static CCryptography Instance
{
get
{
return UIUtilityCreator.CreatorInstance;
}
}

public string EncryptString(string Value)
{
UTF8Encoding utf8encoder = new UTF8Encoding();
byte[] inputBytes = utf8encoder.GetBytes(Value);

TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider();
ICryptoTransform cryptoTransform = tdesProvider.CreateEncryptor(bKey, bIV);

MemoryStream encryptedStream = new MemoryStream();
CryptoStream cryptStream = new CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write);
cryptStream.Write(inputBytes, 0, inputBytes.Length);
cryptStream.FlushFinalBlock();
encryptedStream.Position = 0;

Byte[] bResult = new Byte[encryptedStream.ToArray().Length];
encryptedStream.Read(bResult, 0, encryptedStream.ToArray().Length);
cryptStream.Close();
return Convert.ToBase64String(bResult);
}

public string DecryptString(string Value)
{
byte[] inputBytes = Convert.FromBase64String(Value);
TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider();
ICryptoTransform cryptoTransform = tdesProvider.CreateDecryptor(bKey, bIV);

MemoryStream decryptedStream = new MemoryStream();
CryptoStream cryptStream = new CryptoStream(decryptedStream, cryptoTransform, CryptoStreamMode.Write);

cryptStream.Write(inputBytes, 0, inputBytes.Length);
cryptStream.FlushFinalBlock();
decryptedStream.Position = 0;

byte[] bResult = new byte[decryptedStream.ToArray().Length];
decryptedStream.Read(bResult, 0, decryptedStream.ToArray().Length);
cryptStream.Close();

UTF8Encoding myutf = new UTF8Encoding();
return myutf.GetString(bResult).ToString();
}

public string Key
{
set
{
sKey = value;
}
}

public string IV
{
set
{
sIV = value;
}
}

private sealed class UIUtilityCreator
{
// Retrieve a single instance of a Singleton
private static readonly CCryptography _instance = new CCryptography();

public static CCryptography CreatorInstance
{
get { return _instance; }
}
}
}
}


Now here is the sample code to use this class.

class Program
{
static void Main(string[] args)
{
CCryptography oCryptography = CCryptography.Instance;

string sEncrypt = "Test";
string sEncrypted ="";
string sDecrypted = "";
sEncrypted = oCryptography.EncryptString(sEncrypt);
sDecrypted = oCryptography.DecryptString(sEncrypted);

Console.WriteLine("Text to be Encrypted: " + sEncrypt + "\nEncrypted Text: " + sEncrypted + "\nDecrypted Text: " + sDecrypted);
Console.ReadLine();
}
}

Sunday, February 17, 2008

Get the list of bugs that you have fixed during development. [Part-III]

And finally here is your implementation.

using System;
using System.Collections.Generic;
using System.Text;
using FindBug.Entity;

namespace FindBug
{
public class Program
{
static void Main(string[] args)
{
MyCodeWitBugFixing mm = new MyCodeWitBugFixing();
Console.WriteLine("Calling SumTwoDigit(7, 3). Result: {0}", mm.SumTwoDigit(7, 3));
// get the member information and use it to retrieve the custom attributes
System.Reflection.MemberInfo inf = typeof(MyCodeWitBugFixing);

object[] attributes;
attributes = inf.GetCustomAttributes(typeof(BugInformation), false);

// iterate through the attributes, retrieving the properties
foreach (Object attribute in attributes)
{
BugInformation bfa = (BugInformation)attribute;
Console.WriteLine("\nBugID: {0}", bfa.BugID);
Console.WriteLine("Programmer: {0}", bfa.Programmer);
Console.WriteLine("Date: {0}", bfa.Date);
Console.WriteLine("Comment: {0}", bfa.Comment);
}
}
}
}

Put all code together and test it. Hope you will like it.

Part-I, Part-II

Get the list of bugs that you have fixed during development. [Part-II]

This is your BugInformation attribute class.

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

namespace FindBug.Entity
{
[AttributeUsage(AttributeTargets.Class AttributeTargets.Constructor
AttributeTargets.Field AttributeTargets.Method
AttributeTargets.Property, AllowMultiple = true)]
public class BugInformation : System.Attribute
{
//private member data
private int bugID;
private string comment;
private string date;
private string programmer;

public BugInformation(int bugID, string programmer, string date)
{
this.bugID = bugID;
this.programmer = programmer;
this.date = date;
}

//Named Param
public string Comment
{
get
{
return comment;
}
set
{
comment = value;
}
}

//Positional Param
public int BugID
{
get
{
return bugID;
}
}

public string Programmer
{
get
{
return programmer;
}
}

public string Date
{
get
{
return date;
}
}
}
}


Here is your Class, for which you fix bugs.

using System;
using System.Collections.Generic;
using System.Text;
using FindBug.Entity;

namespace FindBug
{

[BugInformation(121, "Mamun", "01/03/08")]
[BugInformation(107, "Zaq", "01/04/08", Comment = "Fixed one error")]
public class MyCodeWitBugFixing
{
public MyCodeWitBugFixing()
{
}

public int SumTwoDigit(int i, int j)
{
return i + j;
}

public int DeductTwoDigit(int i, int j)
{
return i - j;
}
}
}

Part-I, Part-III

Get the list of bugs that you have fixed during development. [Part-I]

The way I will describe is a use of Custom Attribute. Suppose, your organization wants to keep track of bug fixes and you have your own BugTracking system or a database to keep all of your bugs, but you’d like to attach your comment on specific code that you have been fixed and get them as a list to put in database whenever you like. This example describe how to attach bug information to a class and get them by your code.

Generally when you fixed a bug then add comments to your code like this:
// Bug 323 fixed by Mamun on 17/2/2008.

This would make it easy to see in your source code, but there is no enforced connection to Bug 323 in the database. A custom attribute might be just what you need. You would replace your comment with something like this:
[BugInformation(323,"Mamun","17/2/2008") Comment="Off by one error"]

You could then write a program to read through the metadata to find these bug-fix notations and update the database. The attribute would serve the purposes of a comment, but would also allow you to retrieve the information programmatically through tools you'd create.

Part-II, Part-III