Monday, April 12, 2010

Delete Registry key using Install Script

Delete Registry key using Install Script.

Here is the function you can use to delete a registry key in InstallShield project.


function DeleteRegisrtyKey(szKey)

STRING szClass;

begin

try

RegDBSetDefaultRoot( HKEY_LOCAL_MACHINE );

szKey="SOFTWARE\\"+szKey;

WriteLog("Trying to delete registry value for "+szKey);

szClass = "FPClass";

if (RegDBKeyExist(szKey) < 0) then

WriteLog(szKey +" can not be located in the registry. Deletion failed.");

MessageBox("Unable to delete the registry "+szKey,INFORMATION);

else

if (RegDBDeleteKey (szKey) < 0) then

WriteLog("Failed to delete the Registry.");

else

WriteLog("Registry successfully deleted.");

endif;

endif;

catch

WriteErrorLog("Exception during deleting the registry key. The key is: "+szKey);

endcatch;

end;

Monday, April 5, 2010

SQL Server 2005 VS SQL Server 2008

New Features in SQL Server 2005:
1. It included native support for managing XML data, in addition to relational data.For this purpose, it defined an xml data type that could be used either as a data type in database columns or as literals in queries.
2. XML columns can be associated with XSD schemas; XML data being stored is verified against the schema. XML is converted to an internal binary data type before being stored in the database. Specialized indexing methods were made available for XML data. XML data is queried using XQuery; SQL Server 2005 added some extensions to the T-SQL language to allow embedding XQuery queries in T-SQL. In addition, it also defines a new extension to XQuery, called XML DML, that allows query-based modifications to XML data.
3. SQL Server 2005 also allows a database server to be exposed over web services using TDS packets encapsulated within SOAP (protocol) requests. When the data is accessed over web services, results are returned as XML.
4. For relational data, T-SQL has been augmented with error handling features (try/catch) and support for recursive queries (Common Table Expressions).
5. SQL Server 2005 has also been enhanced with new indexing algorithms and better error recovery systems. Data pages are checksummed for better error resiliency, and optimistic concurrency support has been added for better performance.
6. Permissions and access control have been made more granular and the query processor handles concurrent execution of queries in a more efficient way.
7. Partitions on tables and indexes are supported natively, so scaling out a database onto a cluster is easier.
8. SQL CLR was introduced with SQL Server 2005 to let it integrate with the .NET Framework.
9. SQL Server 2005 introduced "MARS" (Multiple Active Results Sets), a method of allowing usage of database connections for multiple purposes.


New Features in SQL Server 2008:
1. The current version of SQL Server, SQL Server 2008,[4] (code-named "Katmai",[5]) was released (RTM) on August 6, 2008[6] and aims to make data management self-tuning, self organizing, and self maintaining with the development of SQL Server Always On technologies, to provide near-zero downtime.
2. SQL Server 2008 also includes support for structured and semi-structured data, including digital media formats for pictures, audio, video and other multimedia data. In current versions, such multimedia data can be stored as BLOBs (binary large objects), but they are generic bitstreams.
3. Other new data types include specialized date and time types and a Spatial data type for location-dependent data.
4. Better support for unstructured and semi-structured data is provided using the new FILESTREAM[8] data type, which can be used to reference any file stored on the file system.
5. Structured data and metadata about the file is stored in SQL Server database, whereas the unstructured component is stored in the file system. Such files can be accessed both via Win32 file handling APIs as well as via SQL Server using T-SQL; doing the latter accesses the file data as a BLOB.
6. Backing up and restoring the database backs up or restores the referenced files as well.
7. SQL Server 2008 also natively supports hierarchical data, and includes T-SQL constructs to directly deal with them, without using recursive queries.
8. The Full-Text Search functionality has been integrated with the database engine, which simplifies management and improves performance.
9. Spatial data will be stored in two types. A "Flat Earth" (GEOMETRY or planar) data type represents geospatial data which has been projected from its native, spherical, coordinate system into a plane. A "Round Earth" data type (GEOGRAPHY) uses an ellipsoidal model in which the Earth is defined as a single continuous entity which does not suffer from the singularities such as the international dateline, poles, or map projection zone "edges". Approximately 70 methods are available to represent spatial operations for the Open Geospatial Consortium Simple Features for SQL, Version 1.1
10. SQL Server includes better compression features, which also helps in improving scalability.
11. It also includes Resource Governor that allows reserving resources for certain users or workflows.
12. It also includes capabilities for transparent encryption of data as well as compression of backups.
13. SQL Server 2008 supports the ADO.NET Entity Framework and the reporting tools, replication, and data definition will be built around the Entity Data Model.
14. On the management side, SQL Server 2008 includes the Declarative Management Framework which allows configuring policies and constraints, on the entire database or certain tables, declaratively.
15. The version of SQL Server Management Studio included with SQL Server 2008 supports IntelliSense for SQL queries against a SQL Server 2008 Database Engine
16. SQL Server 2008 also makes the databases available via Windows PowerShell providers and management functionality available as Cmdlets, so that the server and all the running instances can be managed from Windows PowerShell.

Monday, March 22, 2010

Registry key contain last few “Run” command

Today I came across a very interesting registry key which I wanna share. If you go to your "Start" menu and open the "Run" dialog from there, you will see a dropdown list labeled as "Open". This list contains the last few entries you wrote there [probably last 26 entry is its limit]. This list populated from the following registry key


"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU"


Lets try yourself, and you know you can make some funny staff from there.

Have fun coding, take care.

/Zaq

Sunday, March 7, 2010

Compatibility issue on IE7 and IE8

If you want to make your site compatible with both IE7 and IE8 together, then just add this meta tag in your site. It will solve your problem.

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>

Monday, February 15, 2010

Check if a String contains a substring using InstallScript

Check if a String contains a substring.

If you want to check whether a string contains a specific substring or not, it's quite easy in .net or Java or any other OO language. But when it comes to InstallScript it's not that straight forward. In spent little time on InstallShield help but could not manage anything usual. And then finally google help me to reach some example on that. Here is a function I wrote to use in my project:


prototype BOOL IsStringContains(STRING,STRING);

function BOOL IsStringContains(szSource, szArgs)

BOOL bIsContains;

begin

if(szSource % szArgs) then

bIsContains = TRUE;

else

bIsContains = FALSE;

endif;

return bIsContains;

end;


And then I use this call this function like this:


if(IsStringContains("This is Zakirul","Zakirul")) then

MessageBox("String match found.", INFORMATION);

else

MessageBox("String doesn't found",INFORMATION);

endif;


Hope this will help you.

Thanks,

Zakirul

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.

How to merge multiple .NET assemblies into a single .NET assembly?

Answer is ILMerge, LMerge is a utility for merging multiple .NET assemblies into a single .NET assembly. It works on executables and DLLs alike and comes with several options for controlling the processing and format of the output. See the accompanying documentation for details.

Monday, January 26, 2009

RegExp for Telephone Number

^[+]?[\d]{1,3}[\-]?(([\d]{8,18})|([(]{1}[\d]{8,18}[)]{1}))

Lets explain this RegExp part by part.

"^[+]?" this part ensures that there will be an optional first character which will be a "+". And if you will start with a digit then it will be fine due to the next part of Expression.

"[\d]{1,3}" this part will ensure that you must enter a number not more than 3 digit and not less than 1 digit.

"[\-]?" this part will ensure that you may enter a "-"after satisfying first two part.

"[\d]{8,18}" this part ensure that you need to enter a number from 8-18 digit.

"[(]{1}[\d]{8,18}[)]{1}" this part will ensure that you will start with a "(" and enter a number between 8 to 18 digits and at the end you will enter a ")".

Now "(([\d]{8,18})|([(]{1}[\d]{8,18}[)]{1}))" this part will ensure to have any one part of these two to be satisfied.

Monday, January 5, 2009

Free eBooks download

http://www.ebooksboard.com/

Event list on XHTML

Event list on XHTML

http://www.w3schools.com/tags/ref_eventattributes.asp

Thursday, January 1, 2009

Link for HTML color code in hex with sample

Link for HTML color code in hex with sample.

http://www.colourlovers.com/blog/2007/06/30/ultimate-html-color-hex-code-list/

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