Monday, June 25, 2012

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>
 

Sunday, May 2, 2010

The Object base class

In the .NET Framework, all types are derived from System.Object. That relationship helps establish the common type system used throughout the .NET Framework

Using Value Types

The simplest types in the .NET Framework, primarily numeric and boolean types, are
value types. Value types are variables that contain their data directly instead of containing
a reference to the data stored elsewhere in memory. Instances of value types are
stored in an area of memory called the stack, where the runtime can create, read,
update, and remove them quickly with minimal overhead.

There are three general value types:
  • Built-in types
  • User-defined types
  • Enumerations
Each of these types is derived from the System.ValueType base type.