Wednesday, December 31, 2008

Link for AJAX learning videos from asp forum.

Here is the link http://www.asp.net/learn/ajax-videos/

Sunday, October 26, 2008

Creating a Windows Registry entry in InstallShield script

Hi,

Now we will try to create a Registry entry from Installshield script. Here I am giving a function which I have used in my projects and its worked fine.

function CreateRegistry(sKey, sKeyName, sKeyValue)

int iResult;

STRING sClass;

begin

Disable(LOGGING);

WriteLog("Trying to create registry. Reg Key: "+sKey+ " ,KeyName: "+sKeyName+" ,KeyValue: "+sKeyValue);

try

sKey="SOFTWARE\\"+sKey;

RegDBSetDefaultRoot( HKEY_LOCAL_MACHINE );

sClass = "FPClass";

if( RegDBCreateKeyEx(sKey,sClass)< 0 ) then

WriteLog("Failed to create registry key.");

MessageBox("Fail to create key for application",INFORMATION);

else

WriteLog("Registry Key successfully created. Trying to create Registry Value.");

iResult = RegDBSetKeyValueEx(sKey,sKeyName,REGDB_STRING_EXPAND,sKeyValue,-1);

if(iResult > 0) then

WriteLog("Failed to creat Registry value");

MessageBox("Unable to create Registry",INFORMATION);

else

WriteLog("Registry value successfully created.");

endif ;

endif;

catch

WriteErrorLog("Unable to create registry key. The key is "+sKey+" and name is "+sKeyName);

MessageBox("Unable to create Registry", INFORMATION);

endcatch;

Enable(LOGGING);

end;


Hope this will help someone somewhereJ.

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();
}
}

Tuesday, February 19, 2008

Real life example of Factory Method Design Pattern

Hi,

When i read any design pattern i would like to have some real life example to get that easily. Today i was going throug Factory Method design pattern from
http://www.dofactory.com/Patterns/PatternFactory.aspx and looking for one good example. Finally i found a good one and now i am sharing that with you.

A non-software example that demonstrates this pattern would be a restaurant. Restaurants serve a variety of items which they list in the menu. The restaurant's waiter provides a menu to the customer and, based on the items available in the Menu, the customer selects the items and orders them. These selected items are prepared and served to the customer by the waiter.
If you map this non-software example against the factory design pattern, we can say:
Items, as the subclasses, are served to the customer by a waiter and its preparation is hidden from the customer.
The waiter, as the Factory class, takes the customer's order based on the items available in the menu and serves them.
The customer, as the Client code, orders the items and does not see how the items are prepared.

Hope this will help you to understand the implementation of this pattern.

/Zaq

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

Tuesday, January 15, 2008

Finding gaps in an identity column (or any integer based column for that matter) using MS SQL

Few days ago one of my friend ask me to do a query to find gaps in an identity column in MS SQL. This is not that tough i thought and started to work on it. But i was given a boundary, no Stored Procedure can be introduced. Need to write it in query and if possible then in a single query! I found some solution but those were for MS SQL 2005 and got a comment "With Sql Server 2000, it would be extremely difficult and would require some iterative techniques."

But now i have a solution for that and want to share with you. Here it is with complete query for Table Creation, Data insertion and Selecting query.

Table query :

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[StudentInfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[StudentInfo]GOCREATE TABLE [dbo].[StudentInfo] ( [SlNo] [int] NULL , [Name] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [Roll] [int] NULL ) ON [PRIMARY]
GO

Inserting Data:

Insert Into StudentInfo Values(1,'Zakirul', 1)
Insert Into StudentInfo Values(2,'Mamun', 2)
Insert Into StudentInfo Values(3,'Robin', 3)
Insert Into StudentInfo Values(5,'Fakhrul', 4)
Insert Into StudentInfo Values(7,'Shamol', 5)

Selection Query:

SELECT DISTINCT (a.SlNo + 1) gapId Into #tmp FROM StudentInfo a
WHERE NOT EXISTS
(SELECT * FROM StudentInfo b WHERE b.SlNo = a.SlNo + 1)
AND a.SlNo < (SELECT MAX(SlNo) FROM StudentInfo)

UNION ALL

SELECT a.SlNo + 1 FROM StudentInfo a
WHERE NOT EXISTS
(SELECT * FROM StudentInfo b WHERE b.SlNo = a.SlNo + 1)
AND a.SlNo > (SELECT MAX(SlNo) FROM StudentInfo)



SELECT gapId AS BitPosition FROM #tmp ORDER BY gapId

It is working nicely for my domain, hope work with yours. Feel free to ask me any question regarding this.

Thanks,
-Zaq

Wednesday, January 9, 2008

An introduction about Lambda Expressions

Ok start with a short introduction. With lambda expressions, we can define function objects for use at any time. C# has always supported this capability via delegates, whereby you create a function object and wire it up to the backing code at the time of creation. Lambda expressions join these two actions—creation and connection—into one expressive statement in the code. A functional is a function that takes functions in its parameter list and operates on those functions, possibly even returning another function as the result. For example, a functional could accept two functions, where one performs one mathematical operation and the other performs a different mathematical operation, and return a third function that is a composite function built from the two. Lambda expressions provide a more natural way to create and invoke functionals. In simple syntactic terms, lambda expressions are a syntax whereby you can declare anonymous functions (delegates) in a more fluid and expressive way. Lambda expressions really take two forms. The form that most directly replaces anonymous methods in syntax includes a statement block within braces. I like to refer to these as lambda statements. These lambda statements are a direct replacement for anonymous methods. Lambda expressions, on the other hand, provide an even more abbreviated way to declare an anonymous method and do not require code within braces nor a return statement. Both types of lambda expressions can be converted to delegates.

Zaq

Monday, January 7, 2008

How to run a script file from MS SQL Query Analyzer

No direct command can be use to read a script file and execute it. But the isql.exe and osql.exe come in handy when you have to execute a script file from within T-SQL. Just call any of these exes using xp_cmdshell and pass the script file name as parameter to it. See SQL Server Books Online for more information about the input parameters of these exes. Here are some quick examples:

EXEC master..xp_cmdshell 'osql /d DatabaseName /U UserName /P Password /i C:\YourFileNameWithExt -n'

See xp_cmdshell in SQL Server Books Online if you are having permissions problems in getting this technique to work

Hope this will work.


Zaq