Monday, June 25, 2012

How to Declare a Value Type Variable

To use a type, you must first declare a symbol as an instance of that type. Value types
have an implicit constructor, so declaring them instantiates the type automatically; you
don’t have to include the New keyword as you do with classes. The constructor assigns
a default value (usually null or 0) to the new instance, but you should always explicitly
initialize the variable within the declaration, as shown in the following code block:


' VB
Dim b As Boolean = False

// C#
bool b = false;

Declare a variable as nullable if you want to be able to determine whether a value has
been assigned. For example, if you are storing data from a yes/no question on a form
and the user did not answer the question, you should store a null value. The following
code declares a boolean variable that can be true, false, or null:

' VB
Dim b As Nullable(Of Boolean) = Nothing

// C#
Nullable// b = null;

// Shorthand notation, only for C#
bool? b = null;

Declaring a variable as nullable enables the HasValue and Value members. Use HasValue
to detect whether a value has been set as follows:

' VB
If b.HasValue Then Console.WriteLine("b is {0}.", b.Value) _
Else Console.WriteLine("b is not set.")

// C#
if (b.HasValue) Console.WriteLine("b is {0}.", b.Value);
else Console.WriteLine("b is not set.");

Encrypting QueryStrings with .NET

Encrypting QueryStrings with .NET

Once upon a time in the tech world, obscurity was security - this being most true in the early years of the industry, when there were gaping holes in privacy policies and confidential client information was bandied about from site to site without a care as to who actually could read the information.
With the new Cryptography classes in .NET, there's absolutely no excuse for not hiding even the most innocuous user data. If you ever need to 'piggy-back' information from one web page to another, whether it is within a POST or a GET parameter, you're passing clear information that anyone can sniff - and that's a bad thing.
If you're not going to use a session variable for storing end user information, you're most likely going to keep some sort of State by passing the information to a cookie or push it around with GET/POST parameters. If you're passing around any sort of ID or user information like their name, it's better to err on the side of caution and encrypt the information.
GET Vs. POST
A POST parameter keeps the information out of the URL, but it can still be sniffed quite easily as it passes in clear text across your network or the Internet. Using POST will keep the mere curious at bay, as the information is not contained in the URL - but this will not stop someone determined to snag out your data.
A QueryString parameter passes information within the site's URL. Why would you even use a QueryString? Well, maybe you need to let your user bookmark a particular page, or maybe you have to refer directly to a page in a URL via a link - you can't do either if you're using POST. A QueryString puts data in the URL for the entire world to see, so if you don't know if the end user is malicious, I'd think hard about using a QueryString for anything but site-related information.

Be smart and encrypt any and all data you're moving around from page to page, especially if that information could be used maliciously. You may trust your users, but you still need that extra level of security that clear text GET/POST data doesn't provide.Imagine this scenario - you've been passing the customer's ID in the database around in a QueryString, in a URL that looks like this:

http://yoursite.com?cust_id=29

You know what a user is going to do? Switch that 29 to a 30 or 12 or some other number, and if you're not checking for invalid requests, you'll be dishing up some other customer's data.

Enter Encryption
What I was looking for was a quick way to encrypt and decrypt parts of a QueryString - it had to be on the fly, quick and dirty.
I chose Base64 because it wouldn't throw bizarre characters in my QueryString that I couldn't pass around… Little did I know that I'd hit a snag while passing around my encrypted QueryString - Apparently, the Request.QueryString object interprets the '+' sign as a space! So, with a quick Replace function slapped on my decrypt string, no harm, no foul.
Symmetric Key
The whole trick to this working is that the QueryString is encrypted and decrypted with the same private key. This is the secret key - if anyone gets a hold of your key, they can decrypt the data themselves, so keep it a secret!
We're going to use a hard-to-crack 8 byte key, !#$a54?3, to keep parts of our QueryString secret.
Let's Walk through the C# portion of the code:
Notice our two functions that abstract the dirty work that our Encryption64 class. The first, encryptQueryString, is used to encrypt the value of a QueryString. The second, decryptQueryString, is used to decrypt the value of an encrypted QueryString.
public string encryptQueryString(string strQueryString) {
    ExtractAndSerialize.Encryption64 oES =

        new ExtractAndSerialize.Encryption64();
    return oES.Encrypt(strQueryString,"!#$a54?3");

}

public string decryptQueryString(string strQueryString) {
    ExtractAndSerialize.Encryption64 oES =

        new ExtractAndSerialize.Encryption64();
    return oES.Decrypt(strQueryString,"!#$a54?3");

}
If we wanted to encrypt our QueryString on our first page, we could do something like this:
string strValues = "search term";
string strURL = "http://yoursite.com?search="
    + encryptQueryString(strValues);Response.Redirect(strURL);
Inside our code-behind in our second page, we pass the contents our QueryString to a variable named strScramble. After that, we replace the '+' signs that our wonderful Request.QueryString has replaced with a space. We pass that string into our function, decryptQueryString, and retrieve the decrypted string.
string strScramble =  Request.QueryString["search"];
string strdeCrypt = decryptQueryString(
    strScramble.Replace(" ", "+"));
Now we've decrypted the value of the QueryString, 'search', and we can do whatever we want with it. The end user is going to see a URL that looks like:



http://yoursite.com?search=da00992Lo39+343dw



They'll never be able guess what's going on in your QueryString, and if they try to fool around with it, there's no way to crack the code without knowing the Symmetric key.



VB.NET
Imports System
Imports System.IO
Imports System.Xml

Imports System.Text
Imports System.Security.Cryptography

Public Class Encryption64

Private key() As Byte = {}
Private IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}

Public Function Decrypt(ByVal stringToDecrypt As String, _
ByVal sEncryptionKey As String) As String

Dim inputByteArray(stringToDecrypt.Length) As Byte
Try
key = System.Text.Encoding.UTF8.GetBytes(Left(sEncryptionKey, 8))

Dim des As New DESCryptoServiceProvider()
inputByteArray = Convert.FromBase64String(stringToDecrypt)
Dim ms As New MemoryStream()

Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), _

CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)

cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8

Return encoding.GetString(ms.ToArray())
Catch e As Exception
Return e.Message

End Try
End Function

Public Function Encrypt(ByVal stringToEncrypt As String, _

ByVal SEncryptionKey As String) As String
Try
key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8))

Dim des As New DESCryptoServiceProvider()
Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes( _

stringToEncrypt)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), _

CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)

cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
Catch e As Exception

Return e.Message
End Try
End Function

End Class

Crystal Reports In ASP.NET

This example shows how to Create Crystal Reports In ASP.NET 2.0,3.5,4.0 Using C# And VB.NET. I am generating Crystal report by fetching data from two tables and grouping them based on Project Name. Database tables are just for demo purpose you can create your own tables with whatever schema you want

Two tables are as shown below.


Create a new website and right click on solution explorer > add new Item > Select Crystal Report
In the dialog box choose blank report.


Now click on CrystalReports Menu in VS and select DataBase Expert 


In database expert dialog box expend create new connection > OLEDB(ADO) section


Now select SQL Native client and enter you SQL server address , username , password and pick database name from the dropdown. 



In next screen Expend your database objects in left pane and add the tables you want to use in right pane 

Link your tables based on Primary keys (If any)



Click ok to finish the wizard.
Right click on Field Explorer and select Group Name Fields  > Insert Group

In next box select the field you to report to be grouped (in my case it's ProjectsName)


Click on OK to finish
Now design the report , drag and fields from Database fields in field explorer and which you want to show in report and drop them in Section3(Details), and preview the report, it should look like show below.

Go to default.aspx page and drag and drop CrystalReportViewer from the toolbox, click on smart tag and choose new report source.





Choose you report from the dropdown menu and click ok to finish.
Now when you build and run the sample , it asks for the database password everytime


To fix this we need to load the report programmatically and provide username and password from code behind .
Now run the report , it should look like this 


Html markup of default.aspx look like
<form id="form1" runat="server">
<div>
  <CR:CrystalReportViewer ID="CrystalReportViewer1" 
                          runat="server" AutoDataBind="True"
                          Height="1039px" 
                          ReportSourceID="CrystalReportSource1" 
                          Width="901px" />
  <CR:CrystalReportSource ID="CrystalReportSource1" 
                          runat="server">
            <Report FileName="CrystalReport.rpt">
            </Report>
   </CR:CrystalReportSource>
    
    </div>
    </form>


using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;


C# code behind

Write this code in the event you find appropriate , i m writing it in Page_Load , you can write this code in click event of button or in pagePreRender event
The code to provide password programmatically.
protected void Page_Load(object sender, EventArgs e)
    {
        ReportDocument crystalReport = new ReportDocument();
        crystalReport.Load(Server.MapPath("CrystalReport.rpt"));
        crystalReport.SetDatabaseLogon
            ("amit", "password", @"AMIT\SQLEXPRESS", "TestDB");
        CrystalReportViewer1.ReportSource = crystalReport;
    }

VB.NET code behind
Protected Sub Page_Load
(ByVal sender As Object, ByVal e As EventArgs)

Dim crystalReport As New ReportDocument()

crystalReport.Load(Server.MapPath("CrystalReport.rpt"))

crystalReport.SetDatabaseLogon
("amit", "password", "AMIT\SQLEXPRESS", "TestDB")

CrystalReportViewer1.ReportSource = crystalReport

End Sub

Friday, June 22, 2012

Windows Forms Tip: Ensure only one instance of your application is running at a time

In some scenarios, you may wish to ensure that a user can run only one instance of your application at a time. Besides ensuring that only a single instance of your application is running, you may also want to bring the instance already running to the front and restore it, if it is minimized.

First, to ensure that only one instance of your application is running at a time, the best method I've found is to create a mutex that is held by the operating system. This will put a request to the operating system that a mutex be created if one does not already exist. Only one mutex can ever be created at a time, so if you request a new one and it cannot be created, you can safely assume that your application is already running.



using System.Threading
using System.Runtime.InteropServices;


public class Form1 : Form
{
     [STAThread]
     static void Main()
     {
          bool createdNew;


          Mutex m = new Mutex(true, "YourAppName", out createdNew);

          if (! createdNew)
          {
               // app is already running…
              
MessageBox.Show("Only one instance of this application is allowed at a time.");
              
return;
         
}




          Application.Run(new Form1());



          // keep the mutex reference alive until the normal termination of the program
          GC.KeepAlive(m);
     }
}


The above code will work for the vast majority of your needs. It will also run under scenarios where your code is executing with less than FullTrust permissions (see Code Access Security in MSDN for further information).

If your application can run with Full Trust permissions, we can take this a step further and find the window of the application instnace already running and bring it to the front for the user:

public class Form1 : Form
{
     [STAThread]
     static void Main()
     {
          bool createdNew;


          System.Threading.Mutex m = new System.Threading.Mutex(true, "YourAppName", out createdNew);

          if (! createdNew)
          {
               // see if we can find the other app and Bring it to front
              
IntPtr hWnd = FindWindow("WindowsForms10.Window.8.app3", "YourAppName");


               if(hWnd != IntPtr.Zero)
              
{
                   
Form1.WINDOWPLACEMENT placement = new Form1.WINDOWPLACEMENT();
                    placement.length = Marshal.SizeOf(placement);


                    GetWindowPlacement(hWnd, ref placement);

                    if(placement.showCmd != SW_NORMAL)
                    {
                         placement.showCmd = SW_RESTORE;


                         SetWindowPlacement(hWnd, ref placement);
                         SetForegroundWindow(hWnd); 

                 
   }
               }


               return;
         
}



          Application.Run(new Form1());



          // keep the mutex reference alive until the normal termination of the program
          GC.KeepAlive(m);
     }


     private const int SW_NORMAL = 1; // see WinUser.h for definitions
    
private const int SW_RESTORE = 9;

     [DllImport("User32",EntryPoint="FindWindow")]
    
static extern IntPtr FindWindow(string className, string windowName);

     [DllImport("User32",EntryPoint="SendMessage")]
    
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

     [DllImport("User32",EntryPoint="SetForegroundWindow")]
    
private static extern bool SetForegroundWindow(IntPtr hWnd);

     [DllImport("User32",EntryPoint="SetWindowPlacement")]
    
private static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);

     [DllImport("User32",EntryPoint="GetWindowPlacement")]
    
private static extern bool GetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);

     private struct POINTAPI
     {
         
public int x;
         
public int y;
     }


     private struct RECT
     {
         
public int left;
         
public int top;
         
public int right;
         
public int bottom;
     }


     private struct WINDOWPLACEMENT
     {
         
public int length;
         
public int flags;
         
public int showCmd;
         
public POINTAPI ptMinPosition;
         
public POINTAPI ptMaxPosition;
         
public RECT rcNormalPosition;
     }
}


As you can see, with minimal effort, you can easily add a polished touch to your application. This might even help you avoid some extra legwork in ensuring that there are no issues with running multiple instances of your app at the same time that you might have to address.

For more information about the Platform Invoke mechanisms to call Win32 API functions, I recommend that you check out .NET Framework Solutions: In Search of the Lost Win32 API by John Mueller and Charles Petzold's seminal classic Programming Windows.

Until Longhorn comes out and more of the Windows platform becomes managed, platform invokes and interop will remain a key technology to understand and use to your advantage to fill the gaps left by the Windows Forms framework.




For C# in VS2008  It’s still pretty short:


static void Main()
{
bool createdNew;
System.Threading.Mutex m = new System.Threading.Mutex(true, “Your App here”, out createdNew);

if (!createdNew)
{
MessageBox.Show(“Another instance is already running.”);
return;
}

{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
} GC.KeepAlive(m); // important!
}

Wednesday, June 20, 2012

MAC Address Using WMI on Internet Explorer

In this little article, i will help you in finding the MAC address from javascript with the help of WMI Library. The script runs only on IE with the following limitations
  • Works on Internet Explorer only
  • Internet Explorer security settings should allow creating ActiveX Objects
  • WMI scripting library is installed on the client machine
Setting IE Security Level
First of all you will need to change the security settings of IE, allowing the following two options
  • Initialize and script ActiveX controls not marked as safe for script -> Set it to enable or prompt
  • Run ActiveX controls and plugins -> Set it to enable or prompt
To change these two options, go to Tools -> Internet Options -> Security -> Custom Level 
 






Installing WMI scripting library
The next step is to install WMI Library, you can download it for free from the Microsoft website. WMI Library can be downloaded from
http://www.microsoft.com/downloads/details.aspx?FamilyID=6430f853-1120-48db-8cc5-f2abdc3ed314&displaylang=en

What is WMI scripting library?
The WMI scripting library provides the set of automation objects through which scripting languages, such as VBScript, JScript, and ActiveState ActivePerl access the WMI infrastructure. The WMI scripting library is implemented in a single automation component named wbemdisp.dll that physically resides in the systemroot\System32\Wbem directory. (description from microsoft.com)

SWbemLocator
At the top of the WMI scripting library object model is the SWbemLocator object. SWbemLocator is used to establish an authenticated connection to a WMI namespace, much as the VBScript GetObject function and the WMI moniker "winmgmts:" are used to establish an authenticated connection to WMI. However, SWbemLocator is designed to address two specific scripting scenarios that cannot be performed using GetObject and the WMI moniker.(description from microsoft.com)

The whole script is given below, just copy this script and execute in IE only.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Getting MAC Address From Javascript(IE Only)</title>
 
<script language="javascript">
function showMacAddress(){
 
	var obj = new ActiveXObject("WbemScripting.SWbemLocator");
	var s = obj.ConnectServer(".");
	var properties = s.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");
	var e = new Enumerator (properties);

 
	var output;
	output='<table border="0" cellPadding="5px" cellSpacing="1px" bgColor="#CCCCCC">';
	output=output + '<tr bgColor="#EAEAEA"><td>Caption</td><td>MACAddress</td></tr>';
	while(!e.atEnd())

	{
		e.moveNext();
		var p = e.item ();
		if(!p) continue;
		output=output + '<tr bgColor="#FFFFFF">';
		output=output + '<td>' + p.Caption; + '</td>';
		output=output + '<td>' + p.MACAddress + '</td>';
		output=output + '</tr>';
	}

	output=output + '</table>';
	document.getElementById("box").innerHTML=output;
}
</script>
 
</head>
<body>
	<input type="button" value="Show MAC Address" onclick="showMacAddress()" />

	<div id="box">
	</div>
</body>
</html>