Saturday, April 11, 2009

Smart Clients : Click once Features of VS.NET 2005

What is a Smart Client Application?


Smart client applications can be designed to combine the benefits of a rich client
Application with the deployment and manageability strengths of a thin client
Application, although the precise nature of the balance between the two approaches
Depends on the exact scenario.

Smart client applications often have very diverse requirements, and so vary greatly
In design and implementation. However, all smart clients share some or all of the
Following characteristics:

• Make Use of Local Resources
• Make Use of network Resources
• Support occasionally connected users
• Make use of network resources
• Support, Provide intelligent installation and update
• Provide client device flexibility




What is ClickOnce Feature of .NET 2005?


ClickOnce is a deployment technology that enables self-updating Windows-based applications that can be installed and run with minimal user interaction. Applications are published to a file share, Web Site, or media such as a CD.
Once published, ClickOnce apps can be automatically updated with minimal user input.
ClickOnce deployment overcomes three major issues inherent in deployment:
• Difficulties in updating applications. With Microsoft Windows Installer deployment, whenever an application is updated, the user must reinstall the entire application; with ClickOnce deployment, you can provide updates automatically. Only those portions of the application that have changed are downloaded, then the full, updated application is reinstalled from a new side-by-side folder.
• Impact to the user's computer. With Windows Installer deployment, applications often rely on shared components, with the potential for versioning conflicts; with ClickOnce deployment, each application is self-contained and cannot interfere with other applications.
• Security permissions. Windows Installer deployment requires administrative permissions and allows only limited user installation; ClickOnce deployment allows non-administrative users to install and grants only those Code Access Security permissions necessary for the application.




The core ClickOnce deployment architecture is based on two XML manifest files: an Application manifest file and a Deployment manifest file.

The application manifest describes the application itself, including the assemblies, the dependencies and files that make up the application, the required permissions, and the location where updates will be available. The application developer authors the application manifest by using the Publish Wizard in Visual Studio 2005 or the manifest generation tool (Mage.exe) in the .NET Framework SDK.

The deployment manifest describes how the application is deployed, including the location of the application manifest, and the version of the application that clients should run. An administrator authors the deployment manifest using the manifest generation tool (Mage.exe) in the .NET Framework SDK.
To make a ClickOnce application available to users, you must publish it to a Web server; file share, or removable media. You can publish the application using the Publish Wizard; additional properties related to publishing are available on the Publish page of the Project Designer or you can publish the application on the server manually.


To Publish to Web Using Publish Wizard


1. In Solution Explorer, select the application project.
2. Right-click the project node and choose Publish. The Publish Wizard appears.
3. On the Where do you want to publish the application? Page; enter a valid URL using the format http://localhost/foldername, then clicks Next.
4. In the “Will the application be available offline?” page, click the appropriate option:
o If you want to enable the application to be run when the user is disconnected from the network, click Yes, this application will be available online or offline. A shortcut on the Start menu will be created for the application.
o If you want to run the application directly from the publish location, click No, this application is only available online. A shortcut on the Start menu will not be created.
Click Finish to publish the application. Publishing status is displayed in the status notification area of the taskbar.

The above solution to deploy the ClickOnce applications is suitable for the Projects Where all the projects are under the same Project/Solution. It is not suitable for the projects in which all projects are separately built. Like in Our project there is a main logon application through which an user is login & then he/she will click on the applications available to that user and that application is executed. In this case we have to mention the start up exe file and dependent files in manifest files used for ClickOnce.The other way to publish your application on the Web Server is to manually create your application & deployment manifest file using a command line toll mage.exe provided by the .NET SDK.






To Publish the application manually on Web Server


To publish your application on the Web Server without using the publish wizard is little bit tricky. For this you have to follow the steps given below:

STEPS:
1. Please create one folder under wwwroot folder for example YourClickOnceApplication.
2. Create one subfolder under YourClickOnceApplication for example YourClickOnceApplication _1_0_0_0 since first time you are publishing application.
3. Copy your .exe, .dlls, resource files\folders & config files from bin\Release folder into YourClickOnceApplication _1_0_0_0.
4.Go to Start-->Program-->Microsoft .Net Framework SDK v2.0-->SDK Command Prompt & type MageUi.exe one window will open,

Mageui Screen.


5. Create a new application manifest by selecting File, New, Application Manifest from the menu.
6. On the default Name tab, enter the name and version number of this deployment.
7. Select the Files tab and click the Browse... button next to the Application Directory text box.
8. Select the directory containing your application files that you created in step 2, and click OK on the folder selection dialog box.
9. Click the Populate button to add all your application files to the file list. If your application contains more than one executable file, mark the main executable file for this deployment as the startup application by selecting Entry Point from the File Type drop-down list. (If your application only contains one executable file, MageUI.exe will mark it automatically for you.). To have a custom icon displayed in your ClickOnce application the icon must be deployed with the application and the file must be specified as the value for the iconFile attribute in the .exe.manifest file.
10. Select the Permissions Required tab and select the level of trust you need your application to assert. The default is Full Trust, which will be suitable for most applications.
11. Select File, Save from the menu, and save the application manifest. You will be prompted to sign the application manifest when you save it. Save it in folder created in step 2 (i.e. under YourClickOnceApplication _1_0_0_0 folder).
12. Select File, New, Deployment Manifest from the menu to create your deployment manifest, and then on the Name tab, supply a name and version number (1.0.0.0 in this example).
13. Select the Publisher tab, and supply values for Publisher and Product. (Product is the name given your application on the Windows Start menu when you install your application locally.)
14. Switch to the Deployment tab, Select the Application type as Install locally & give the URL of the virtual directory which u have created in step1 named YourClickOnceApplication like here you can give like http://localhost/ YourClickOnceApplication/YourAppName.application.
15. Switch to the Update tab, and specify how often you would like this application to update. If your application uses the ClickOnce Deployment API to check for updates itself, clear the check box labeled this application should check for updates if not check the checkbox Also you can define the way your application will self update.
16. Switch to the Application Reference tab. You can pre-populate all of the values on this tab by clicking the Select Manifest button and selecting the application manifest you created in 9th step.
17. Choose Save and save the deployment manifest to disk. You will be prompted to sign the application manifest when you save it. Save deployment manifest in folder created in step 1 (i.e. under YourClickOnceApplication folder).
That’s it now browse .application file from location given in step 12 for example
http://localhost/ YourClickOnceApplication/YourAppName.application
Note: ClickOnce doesn’t support Fire Fox browser. To Support fire fox you have to install a plug-in provide on URL.


Applications distributed with ClickOnce do not get installed in the program Files folder. Instead they are placed in an Application cache that resides in the Local Settings folder under the current user’s Document’s & Settings Folder. By controlling this aspect of the deployment, multiple versions of an application can reside on the client pc at the same time.
All ClickOnce applications, whether they are installed locally or hosted online, are stored on the client computer in a ClickOnce application cache. A ClickOnce cache is a family of hidden directories under the Local Settings directory of the current user's Documents and Settings folder. This cache holds all the application's files, including the assemblies, configuration files, application and user settings, and data directory. The cache is also responsible for migrating the application's data directory to the latest version. Because of this it is very simple process to rollback a ClickOnce application to its previous version. If the user goes to the Add/Remove programs control applet, the dialog presented will have the choice of removing the ClickOnce application or the rolling back to the previous version. An administrator can change the manifest file to point to the previous version.
By default, client computers have 250 MB of storage for online ClickOnce applications. Data files do not count toward this limit. A system administrator can enlarge or reduce this quota on a particular client computer by changing the registry key, HKEY_CURRENT_USER\Software\Classes\Software\Microsoft\Windows\CurrentVersion\Deployment\OnlineAppQuotaInKB, which is a DWORD value that expresses the cache size in kilobytes. For example, in order to reduce the cache size to 50 MB, you would change this value to 51200.
When you need to deploy a new version of the application, you will need to create a new directory named after the new version—for example, YourClickOnceApplication _1_1_0_0 and move the new application files into that new directory. You should generate a new application manifest and store it in the new directory, and have the publisher sign the new manifest. Once you get the signed manifest back, you can use Mage.exe to update the deployment manifest and point it at the new application manifest:
mage -Update YourAppName.application -Version 1.1.0.0 -AppManifest YourClickOnceApplication _1_1_0_0\ YourAppName.exe.manifest
Now when you will run your application it will ask that a new version is updated on server whether you want to install or not. If you say yes then it will download the entire latest file from the server and reinstall the application on your system.

Now there are some issues with this manual deployment of ClickOnce application in comparison to deployment through wizard. Like
• When you deploy through wizard it creates an html page by itself to show the application manifest URL and user can easily navigate through this URL to install the ClickOnce application.
• Other thing is if you want to add some prerequisites with your ClickOnce application through wizard it is very easy task you have to just Click On prerequisites button and it will provide you to add the prerequisites list. Wizard automatically creates a ‘SetUp.exe’ which contain that prerequisite installation URL and settings related to those prerequisites.
• Next thing is wizard automatically create a certificate (myapplication.pfx) to sign your application & deployment manifest files.
• If you want to change anything in application or deployment manifest files then you have to again sign it with the certificate (licence) provided by the issuer.



We can do the above task manually in following ways when we are deploying the ClickOnce application manually as:

We can use windows built in facility to create the certificate files. Using makecert command we can create a certificate (.pfx) and after creating this file we can add this certificate in Clients certificates. The level of trust that is being requested is part of trust license configuration. A public key is used to sign the application must also be supplied to the license issuer. The trust licence is then embedded in the deployment manifest. The last step is to sign the deployment manifest with your own key pair. To Sign the application and deployment manifest we can use following commands as:

mage -s app manifest -cf cert_file -pwd password
mage -u deployment manifest -appm app manifest
mage -s deployment manifest -cf certfile -pwd password

To add the prerequisite for ClickOnce Deployment This should be added in application.exe.manifest file (Application Manifest file) for .NET 2.0 framework







After adding above you have to again sign the application manifest using proper certificate and also update the deployment manifest reference for the application manifest file using mage –update command.

Labels:

Migration of desktop applications to the web using Visual WebGui

The following is the first part of a 3 parts series of articles ppublished on VisualWebGui website describing the various available migration options of desktop/smart client applications to the web using Visual WebGui.

In order to discuss the migration process of legacy desktop applications to the web, we should first agree on 3 different types of desktop applications:


1. WinForms based desktop application (C#/VB.NET). The UI layer is coded using .NET languages – the business can be .NET, COM+ or any other interop.

2. VB 6.0 based applications. The UI layer is coded with VB 6.0.

3. Other desktop or smart client technologies (C++ MFC/ATL, Delphi, Java etc). Any other smart client technology based applications.



WinForms based desktop applications to Web

Background
Normally, without Visual WebGui the migration process of a WinForms desktop application to the web will require a full re-engineering of the UI layer to fit the web architecture and capabilities.

If we take WinForms migration to ASP.NET for example using any AJAX 3rd party controls in order to provide a rich UI experience, we will have to consider:


* Entirely new API.

* Entirely new update approach.

* Entirely new look & feel – or work hard to customize the UI to look the same.

* Lighten the amount of data transferred to the client and presented at any given time to avoid severe latency.

* Compromise on features list due to the web limitations.

* Handling security holes created as a result of opening services consumed by client side AJAX and transferring business logics to the client.



Visual WebGui SDK is fully integrated with Visual Studio and provides the exact same API and set of tools/capabilities which are provided out-of-the-box with WinForms 1.0 and 2.0. This fact enables the native capability of simply copying any existing WinForms source code to a VWG project and providing a fully functional equivalent web application.

The Process
The basic 3 steps of migration:


1. Open a new Visual WebGui application.

2. Copy the code from your WinForms project into this new web application.

3. Replace any reference to WinForms API namespace (“System.Windows.Forms”) within the code to Visual WebGui API reference (“Gizmox.WebGUI.Forms”).


Any standard WinForms application which is using the will then compile and execute as a plain web application.

The outcome of this short process is an ASP.NET based solution in terms of deployment and runtime and has the following properties:


* Deployment is copy & paste equivalent to an ASP.NET web site.

* Server infrastructure requires an IIS and .NET CLR only.

* The application can be consumed from any plain browser - no installation is made on the client.

* Minor static and cached footprint on the client ~200kb of plain JS and HTML code due to the Empty Client concept.

* Support for multiple presentation layers with the same code base (DHTML/Silverlight or Smart Client).

* Maintain a single layer of code – no need to write or maintain JavaScript, HTML and services.

* Highly secured due to the Empty Client concept.


Considerations & Exceptions
There are 3 major setbacks you might have on the process which you can quantify in advance and estimate the amount of work that has to be done in order to migrate your application:


1. Minor differences between the VWG API and WinForms which are mainly caused by architecture differences.

2. The amount of 3rd party controls that are used in your application. This section describes a situation of using some non-WinForms out-of-the-box controls (for example Infragistics or DevExpress controls etc). In those cases you can select the most suitable solution from the following 3 options:


* Choose a similar control from the WinForms out-of-the-box, adjust your code to use it and then perform the migration process.

* Select an equivalent 3rd party ASP.NET control (Infragistics, Telerik, DevExpress etc.) which provides the same functionality, wrap it by a click of a button in VWG and adjust your code to use it.

* Write your own VWG custom control which will perfectly suit your needs and then adjust your code after the migration process to use this control.

3. Adjustments of a single user desktop application to a multiuser web environment. This section summarizes some of the major issues of transforming a single user application to a multiuser application sharing the same CPU, Memory space and other resources.


* Thread safety – since a WinForms application can contain static members which are accessible to a single user, you should now consider one of the following:


o Replacing those static members to a synchronized multi-thread safe data structures.

o Lock critical read/write sections to protect concurrent multi user access.

o Remove the statics and find instance or DB based solutions.

* Memory load – in a desktop application, there might be places when the original consideration of the amount of memory in use was based on the assumption that the executing machine is local. therefore, many items are loaded to memory simultaneously without limitation.



Now, on a shared memory environment, when the server does the heavy lifting, the amount of memory consumed by each user will set the number of concurrent users that can be served by each server.


The following steps are recommended:


* Consider loading items to memory on demand (keep only the headers and the identifiers in memory).

* Remove any large objects read to memory – for example, don’t save binary objects to memory, instead write the binary to the response stream directly to the client.

* Prefer DB based paging on entire prefaces and memory based paging. Visual WebGui provides mechanisms to enable it easily.



Summery
Migration of any WinForms application to the web using Visual WebGui has the following advantages:


1. In 3 simple steps you will be able to get very close to a working web application.

2. The effort you have to make in order to accomplish a fully functional web application is measurable.

3. The application can keep using the existing BL and DL layers, and only the UI is either migrated automatically or adjusted.

Labels:

To Publish to Web Using Publish Wizard

1. In Solution Explorer, select the application project.
2. Right-click the project node and choose Publish. The Publish Wizard appears.
3. On the Where do you want to publish the application? Page; enter a valid URL using the format http://localhost/foldername, then clicks Next.
4. In the “Will the application be available offline?” page, click the appropriate option:
o If you want to enable the application to be run when the user is disconnected from the network, click Yes, this application will be available online or offline. A shortcut on the Start menu will be created for the application.
o If you want to run the application directly from the publish location, click No, this application is only available online. A shortcut on the Start menu will not be created.
Click Finish to publish the application. Publishing status is displayed in the status notification area of the taskbar.

The above solution to deploy the ClickOnce applications is suitable for the Projects Where all the projects are under the same Project/Solution. It is not suitable for the projects in which all projects are separately built. Like in Our project there is a main logon application through which an user is login & then he/she will click on the applications available to that user and that application is executed. In this case we have to mention the start up exe file and dependent files in manifest files used for ClickOnce.The other way to publish your application on the Web Server is to manually create your application & deployment manifest file using a command line toll mage.exe provided by the .NET SDK.

To Publish the application manually on Web Server


To publish your application on the Web Server without using the publish wizard is little bit tricky. For this you have to follow the steps given below:

STEPS:
1. Please create one folder under wwwroot folder for example YourClickOnceApplication.
2. Create one subfolder under YourClickOnceApplication for example YourClickOnceApplication _1_0_0_0 since first time you are publishing application.
3. Copy your .exe, .dlls, resource files\folders & config files from bin\Release folder into YourClickOnceApplication _1_0_0_0.
4.Go to Start-->Program-->Microsoft .Net Framework SDK v2.0-->SDK Command Prompt & type MageUi.exe one window will open,

Mageui Screen.


5. Create a new application manifest by selecting File, New, Application Manifest from the menu.
6. On the default Name tab, enter the name and version number of this deployment.
7. Select the Files tab and click the Browse... button next to the Application Directory text box.
8. Select the directory containing your application files that you created in step 2, and click OK on the folder selection dialog box.
9. Click the Populate button to add all your application files to the file list. If your application contains more than one executable file, mark the main executable file for this deployment as the startup application by selecting Entry Point from the File Type drop-down list. (If your application only contains one executable file, MageUI.exe will mark it automatically for you.). To have a custom icon displayed in your ClickOnce application the icon must be deployed with the application and the file must be specified as the value for the iconFile attribute in the .exe.manifest file.
10. Select the Permissions Required tab and select the level of trust you need your application to assert. The default is Full Trust, which will be suitable for most applications.
11. Select File, Save from the menu, and save the application manifest. You will be prompted to sign the application manifest when you save it. Save it in folder created in step 2 (i.e. under YourClickOnceApplication _1_0_0_0 folder).
12. Select File, New, Deployment Manifest from the menu to create your deployment manifest, and then on the Name tab, supply a name and version number (1.0.0.0 in this example).
13. Select the Publisher tab, and supply values for Publisher and Product. (Product is the name given your application on the Windows Start menu when you install your application locally.)
14. Switch to the Deployment tab, Select the Application type as Install locally & give the URL of the virtual directory which u have created in step1 named YourClickOnceApplication like here you can give like http://localhost/ YourClickOnceApplication/YourAppName.application.
15. Switch to the Update tab, and specify how often you would like this application to update. If your application uses the ClickOnce Deployment API to check for updates itself, clear the check box labeled this application should check for updates if not check the checkbox Also you can define the way your application will self update.
16. Switch to the Application Reference tab. You can pre-populate all of the values on this tab by clicking the Select Manifest button and selecting the application manifest you created in 9th step.
17. Choose Save and save the deployment manifest to disk. You will be prompted to sign the application manifest when you save it. Save deployment manifest in folder created in step 1 (i.e. under YourClickOnceApplication folder).
That’s it now browse .application file from location given in step 12 for example
http://localhost/ YourClickOnceApplication/YourAppName.application
Note: ClickOnce doesn’t support Fire Fox browser. To Support fire fox you have to install a plug-in provide on URL.


Applications distributed with ClickOnce do not get installed in the program Files folder. Instead they are placed in an Application cache that resides in the Local Settings folder under the current user’s Document’s & Settings Folder. By controlling this aspect of the deployment, multiple versions of an application can reside on the client pc at the same time.
All ClickOnce applications, whether they are installed locally or hosted online, are stored on the client computer in a ClickOnce application cache. A ClickOnce cache is a family of hidden directories under the Local Settings directory of the current user's Documents and Settings folder. This cache holds all the application's files, including the assemblies, configuration files, application and user settings, and data directory. The cache is also responsible for migrating the application's data directory to the latest version. Because of this it is very simple process to rollback a ClickOnce application to its previous version. If the user goes to the Add/Remove programs control applet, the dialog presented will have the choice of removing the ClickOnce application or the rolling back to the previous version. An administrator can change the manifest file to point to the previous version.
By default, client computers have 250 MB of storage for online ClickOnce applications. Data files do not count toward this limit. A system administrator can enlarge or reduce this quota on a particular client computer by changing the registry key, HKEY_CURRENT_USER\Software\Classes\Software\Microsoft\Windows\CurrentVersion\Deployment\OnlineAppQuotaInKB, which is a DWORD value that expresses the cache size in kilobytes. For example, in order to reduce the cache size to 50 MB, you would change this value to 51200.
When you need to deploy a new version of the application, you will need to create a new directory named after the new version—for example, YourClickOnceApplication _1_1_0_0 and move the new application files into that new directory. You should generate a new application manifest and store it in the new directory, and have the publisher sign the new manifest. Once you get the signed manifest back, you can use Mage.exe to update the deployment manifest and point it at the new application manifest:
mage -Update YourAppName.application -Version 1.1.0.0 -AppManifest YourClickOnceApplication _1_1_0_0\ YourAppName.exe.manifest
Now when you will run your application it will ask that a new version is updated on server whether you want to install or not. If you say yes then it will download the entire latest file from the server and reinstall the application on your system.

Now there are some issues with this manual deployment of ClickOnce application in comparison to deployment through wizard. Like
• When you deploy through wizard it creates an html page by itself to show the application manifest URL and user can easily navigate through this URL to install the ClickOnce application.
• Other thing is if you want to add some prerequisites with your ClickOnce application through wizard it is very easy task you have to just Click On prerequisites button and it will provide you to add the prerequisites list. Wizard automatically creates a ‘SetUp.exe’ which contain that prerequisite installation URL and settings related to those prerequisites.
• Next thing is wizard automatically create a certificate (myapplication.pfx) to sign your application & deployment manifest files.
• If you want to change anything in application or deployment manifest files then you have to again sign it with the certificate (licence) provided by the issuer.

We can do the above task manually in following ways when we are deploying the ClickOnce application manually as:

We can use windows built in facility to create the certificate files. Using makecert command we can create a certificate (.pfx) and after creating this file we can add this certificate in Clients certificates. The level of trust that is being requested is part of trust license configuration. A public key is used to sign the application must also be supplied to the license issuer. The trust licence is then embedded in the deployment manifest. The last step is to sign the deployment manifest with your own key pair. To Sign the application and deployment manifest we can use following commands as:

mage -s app manifest -cf cert_file -pwd password
mage -u deployment manifest -appm app manifest
mage -s deployment manifest -cf certfile -pwd password

To add the prerequisite for ClickOnce Deployment This should be added in application.exe.manifest file (Application Manifest file) for .NET 2.0 framework


After adding above you have to again sign the application manifest using proper certificate and also update the deployment manifest reference for the application manifest file using mage –update command.

Labels:

What is ClickOnce Feature of .NET 2005?

ClickOnce is a deployment technology that enables self-updating Windows-based applications that can be installed and run with minimal user interaction. Applications are published to a file share, Web Site, or media such as a CD.
Once published, ClickOnce apps can be automatically updated with minimal user input.
ClickOnce deployment overcomes three major issues inherent in deployment:
• Difficulties in updating applications. With Microsoft Windows Installer deployment, whenever an application is updated, the user must reinstall the entire application; with ClickOnce deployment, you can provide updates automatically. Only those portions of the application that have changed are downloaded, then the full, updated application is reinstalled from a new side-by-side folder.
• Impact to the user's computer. With Windows Installer deployment, applications often rely on shared components, with the potential for versioning conflicts; with ClickOnce deployment, each application is self-contained and cannot interfere with other applications.
• Security permissions. Windows Installer deployment requires administrative permissions and allows only limited user installation; ClickOnce deployment allows non-administrative users to install and grants only those Code Access Security permissions necessary for the application.


The core ClickOnce deployment architecture is based on two XML manifest files: an Application manifest file and a Deployment manifest file.

The application manifest describes the application itself, including the assemblies, the dependencies and files that make up the application, the required permissions, and the location where updates will be available. The application developer authors the application manifest by using the Publish Wizard in Visual Studio 2005 or the manifest generation tool (Mage.exe) in the .NET Framework SDK.

The deployment manifest describes how the application is deployed, including the location of the application manifest, and the version of the application that clients should run. An administrator authors the deployment manifest using the manifest generation tool (Mage.exe) in the .NET Framework SDK.
To make a ClickOnce application available to users, you must publish it to a Web server; file share, or removable media. You can publish the application using the Publish Wizard; additional properties related to publishing are available on the Publish page of the Project Designer or you can publish the application on the server manually

Labels:

What is a Smart Client Application?

What is a Smart Client Application?

Smart client applications can be designed to combine the benefits of a rich client
Application with the deployment and manageability strengths of a thin client
Application, although the precise nature of the balance between the two approaches
Depends on the exact scenario.

Smart client applications often have very diverse requirements, and so vary greatly
In design and implementation. However, all smart clients share some or all of the
Following characteristics:

• Make Use of Local Resources
• Make Use of network Resources
• Support occasionally connected users
• Make use of network resources
• Support, Provide intelligent installation and update
• Provide client device flexibility

Labels:

Smart Client Advantages

Any updates to the application, a single change and the changes will be reflected to all the clients when they are launched the next time. This is called a smart client.
Lets see the Client Application Code
Collapse

using System;
using System.Reflection;
using System.Windows.Forms;
namespace MySmartClient
{
class SmartClient
{
[STAThread]
static void Main(string[] args)
{
SmartClient objSmartClient = new SmartClient();

//display splash screen

Splash splash = new Splash();
splash.Show();
Application.DoEvents();

// Set the URL to load the Assembly from

string strURL = "http://Server/Smart/Bin/Release/Smart.exe";

// Set the class to call

string sClassName = "MySmartClient.SmartForm";

Assembly assemblyContent = null;

try
{
// Load the assembly

assemblyContent = Assembly.LoadFrom(strURL);
}
catch(Exception e)
{
}
splash.Close();
// Create a object for the Class

Type typeContent = assemblyContent.GetType(sClassName);
// Invoke the method. Here we are invoking the Main method.

try
{
typeContent.InvokeMember ("Main", BindingFlags.Public |
BindingFlags.InvokeMethod | BindingFlags.Static, null, null, null);
}
catch(Exception e)
{
}
}
}
}

This is all that would be installed on the client. The actual application will be available on the Server. First time the client application is launched, the .NET Framework will download the required assemblies locally. Henceforth every time the application is launched, the .NET Framework will check for the version of the assemblies, if the server has a latest version, it will downloaded or else the locally available assemblies will used to launch the application. This way, any updates to the application can be handled easily at one location, thereby making the deployment of application easy

Labels:

Smart Client Features

A smart client would have the following characteristics:

* Local Resource Utilization - A smart client application always has code artifacts on the client that enable local resources to be utilized. What do we mean by local resources? We mean everything from hardware to software resources. A smart client may take advantage of the local CPU, local memory or disk, or any local devices connected to the client, such as a telephone, bar-code/RFID reader, and so on. But it may also take advantage of local software, such as Microsoft Office applications, or any installed line-of-business (LOB) applications that interact with it.
* Connected - Smart client applications are never standalone and always form part of a larger distributed solution. This could mean that the application interacts with a number of Web services that provide access to data or an LOB application. Very often, the application has access to specific services that help maintain the application and provide deployment and update services.
* Offline Capable - Because they are running on the local machine, one of the key benefits that smart client applications offer is that they can be made to work even when the user is not connected. For applications running in occasional or intermittent connectivity situations, such as those used by traveling workers or even those running on laptops, tablets, PDA's, and so on, where connectivity cannot be guaranteed at all times, being able to work while disconnected is essential. Even when the client is connected, the smart client application can improve performance and usability by caching data and managing the connection in an intelligent way.
* Intelligent Install and Update - Smart client applications manage their deployment and update in a much more intelligent way than traditional rich client applications. The .NET framework enables application artifacts to be deployed using a variety of techniques, including simple file copy or download over HTTP. Applications can be updated while running and can be deployed on demand by clicking on a URL. The Microsoft(r) .NET Framework provides a powerful security mechanism that guarantees the integrity of the application and its related assemblies. Assemblies can be given limited permissions in order to restrict their functionality in semi-trusted scenarios.
* Client Device Flexibility - The .NET Framework together with the .NET Compact Framework provides a common platform upon which smart client applications can be built. Often, there will be multiple versions of the smart client application, each targeting a specific device type and taking advantage of the devices unique features and providing functionality appropriate to its usage.

Let us look at one of the very important features of Smart clients Intelligent Install and Update.
Intelligent Install and Update (Easy Deployment)

Smart client applications manage their deployment and update in a much more intelligent way than traditional rich client applications.
Components

A Smart client application will have two components

1. A very thin client application to be installed locally
2. The actual application hosted on a Web Server build using Strong named assemblies

Process involved

When the user opens a Smart client Application

1. The User opens the Application.
2. The application references a assembly hosted on a Web Server
3. The .NET Framework checks if the previously downloaded assembly is the latest one.
4. If not downloads the latest version from the server, loads the assembly locally and launches the application.

Labels:

What is a Smart Client?

A Smart Client is an application that uses local processing, consumes XML Web Services and can be deployed and updated from a centralized server. While the .NET Framework (Windows Forms) and the .NET Compact Framework provide the ability to develop Smart Clients with ease, other technologies can provide smart client applications by utilizing the same architecture. Smart Client is the concept of architecting your application solution into a smart, flexible and convenient platform that utilizes web services for communication.
Why do we need a Smart Client?

To understand the need lets see the pros and cons of both the existing architectures the Thin Client (Web) and the Thick Client (Desktop)
The Thin Client

The Thin clients or the Web application provided features like

1. Easy to Update Single location update
2. Easy to deploy Single location Update
3. Easy to manage.

If it had the above features then it also had the following issues

1. Network dependency are usually Network based
2. Poor user experience mainly emit HTML
3. Complex to develop.

The Thick Client

The Thick clients or the Rich client or Desktop Applications or Client/Server application provided features like

1. Rich User experience by means of better user interface
2. Offline capabilities Need not be connected on a Network
3. High Developer Productivity
4. Responsive & Flexible

The Thick did provide the above feature but on the other hand they also had the following issues

1. Tough to Update Each location needs modifications
2. Tough to Deploy Deployment had to be done at multiple location
3. DLL Hell

Labels:

C# Regular Expressions Cheat Sheet

Cheat sheet for C# regular expressions metacharacters, operators, quantifiers etc
Character
Description
\

Marks the next character as either a special character or escapes a literal. For example, "n" matches the character "n". "\n" matches a newline character. The sequence "\\" matches "\" and "\(" matches "(".

Note: double quotes may be escaped by doubling them: ""
^ Depending on whether the MultiLine option is set, matches the position before the first character in a line, or the first character in the string.
$ Depending on whether the MultiLine option is set, matches the position after the last character in a line, or the last character in the string.
* Matches the preceding character zero or more times. For example, "zo*" matches either "z" or "zoo".
+ Matches the preceding character one or more times. For example, "zo+" matches "zoo" but not "z".
? Matches the preceding character zero or one time. For example, "a?ve?" matches the "ve" in "never".
. Matches any single character except a newline character.
(pattern) Matches pattern and remembers the match. The matched substring can be retrieved from the resulting Matches collection, using Item [0]...[n]. To match parentheses characters ( ), use "\(" or "\)".
(?pattern) Matches pattern and gives the match a name.
(?:pattern) A non-capturing group
(?=...) A positive lookahead
(?!...) A negative lookahead
(?<=...) A positive lookbehind .
(?x|y Matches either x or y. For example, "z|wood" matches "z" or "wood". "(z|w)oo" matches "zoo" or "wood".
{n} n is a non-negative integer. Matches exactly n times. For example, "o{2}" does not match the "o" in "Bob," but matches the first two o's in "foooood".
{n,} n is a non-negative integer. Matches at least n times. For example, "o{2,}" does not match the "o" in "Bob" and matches all the o's in "foooood." "o{1,}" is equivalent to "o+". "o{0,}" is equivalent to "o*".
{n,m} m and n are non-negative integers. Matches at least n and at most m times. For example, "o{1,3}" matches the first three o's in "fooooood." "o{0,1}" is equivalent to "o?".
[xyz] A character set. Matches any one of the enclosed characters. For example, "[abc]" matches the "a" in "plain".
[^xyz] A negative character set. Matches any character not enclosed. For example, "[^abc]" matches the "p" in "plain".
[a-z] A range of characters. Matches any character in the specified range. For example, "[a-z]" matches any lowercase alphabetic character in the range "a" through "z".
[^m-z] A negative range characters. Matches any character not in the specified range. For example, "[m-z]" matches any character not in the range "m" through "z".
\b Matches a word boundary, that is, the position between a word and a space. For example, "er\b" matches the "er" in "never" but not the "er" in "verb".
\B Matches a non-word boundary. "ea*r\B" matches the "ear" in "never early".
\d Matches a digit character. Equivalent to [0-9].
\D Matches a non-digit character. Equivalent to [^0-9].
\f Matches a form-feed character.
\n Matches a newline character.
\r Matches a carriage return character.
\s Matches any white space including space, tab, form-feed, etc. Equivalent to "[ \f\n\r\t\v]".
\S Matches any nonwhite space character. Equivalent to "[^ \f\n\r\t\v]".
\t Matches a tab character.
\v Matches a vertical tab character.
\w Matches any word character including underscore. Equivalent to "[A-Za-z0-9_]".
\W Matches any non-word character. Equivalent to "[^A-Za-z0-9_]".
\num Matches num, where num is a positive integer. A reference back to remembered matches. For example, "(.)\1" matches two consecutive identical characters.
\n Matches n, where n is an octal escape value. Octal escape values must be 1, 2, or 3 digits long. For example, "\11" and "\011" both match a tab character. "\0011" is the equivalent of "\001" & "1". Octal escape values must not exceed 256. If they do, only the first two digits comprise the expression. Allows ASCII codes to be used in regular expressions.
\xn Matches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, "\x41" matches "A". "\x041" is equivalent to "\x04" & "1". Allows ASCII codes to be used in regular expressions.
\un Matches a Unicode character expressed in hexadecimal notation with exactly four numeric digits. "\u0200" matches a space character.
\A Matches the position before the first character in a string. Not affected by the MultiLine setting
\Z Matches the position after the last character of a string. Not affected by the MultiLine setting.
\G Specifies that the matches must be consecutive, without any intervening non-matching characters.

Labels:

Check if the given string is AlphaNumeric

This code sample returns true if the passed stirng contains only alpha numeric characters.


Public Shared Function IsAlphaNumeric(ByVal strToCheck As String) As Boolean
Dim pattern As Regex = New Regex("[^a-zA-Z0-9]")

Return Not pattern.IsMatch(strToCheck)
End Function

Labels:

Validating Postal Codes using Javascript

he below javascript function uses regular expression to validate a 6 digit postal code.


function checkpostal( var str )
{
var regdigit= /^(\d{1,6})(\.?)(\d{1,3})$/ ;
var m = regdigit.test( str );
if (m==true)
return true;
else
return false;
}

Labels:

Strip HTML tags from string

This code sample removes all the HTML tags (any text between < >) within the given text. YOu can use thsi function to stripp off all HTML tags from a web page and display as plain text. This sample code will replace only words enclosed within < >. If there is < or > with no text in between, they will not be removed.


Dim objRegExp as New RegEx("<(.|\n)+?>")
string plainText = objRegExp.Replace(htmlText, "")

Labels:

How to use the Regex.Split() to split strings in C# ?

As you might know the string Split method allows you to split a string only be a specified character. If you wish to split a string using the power of the regular expressions to specify the delimiter a good solution is to use the Regex.Split() method


using System.Text;
using System.Text.RegularExpressions;

...

string strText=" DotnetSpider@@ Spider@@ Is @@ Good @@ for @@ Learner ";

foreach(string strItem in Regex.Split(strText,"@@")){
Console.WriteLine(strItem);
}




will print:

Dotnet
Spider
Good
for
Learner

Labels:

Check if String is Integer Using Regular Expression

In .NET 2.0 there is a TryParse method for Int32. However TryParse is not compatible with .NET 1.1. The solution below is compatible with .NET 1.1 and demonstrates how to check if string is integer, using one simple regular expression.


public bool IsNumeric(string inputData)
{
Regex isNumber = new Regex(@"^\d+$");
Match m = isNumber.Match(inputData);

return m.Success;
}

Labels:

Text validation for TextInput in Flex

In flex, a text input is a textbox. In forms, we always have a requirement to validate user input before accepting the form completely.

In flex, we can restrict input with the following code.






The example code above restricts the input text to only alphanumeric characters. The restrict attribute of a TextInput facilitates such a restriction.

Labels:

Remove Trailing Zeroes From a String in C# using Regular Expressions

The code sample is that of a function RemoveTrailingZeros in C#, that takes a string input and removes all trailing zeros in it.

The code uses the Regex object provided by the .Net class library. Regular Expressions optimize the operation of "searching patterns" in a string. The following code can also be taken as an example to remove any character (trailing) from a string. The only change require will be that we need to change the Regular Expression.


//Regex is in System.Text.RegularExpressions namespace
public string RemoveTrailingZeroes(string input)
{
Regex reg1 = new Regex("\\.\\d*(?<1>0+)[^\\d]*$", RegexOptions.IgnoreCase);

Match m = reg1.Match(input);
if( m.Success )
{
input = input.Replace(m.Groups["1"].Value, "");
Regex reg2 = new Regex("(?<1>\\.)[^\\d]*$", RegexOptions.IgnoreCase);
m = reg2.Match(input);

if( m.Success )
{
input = input.Replace(".", "" );
}
Regex reg3 = new Regex("\\d", RegexOptions.IgnoreCase );
m = reg3.Match(input);
if( !m.Success )
{
input = "0" + input;

}

}
if(input.StartsWith("."))
input = "0" + input;

return input;
}

Labels:

ValidateExpression for Day,Month and Year

The code sample contains basic validation expressions generally needed in every application. Users should be allowed to enter only valid day,month and year values for a particular date.

In this code snippet uses regular expression validator and sets it's validation expression property. This example is very useful when clients don't need calender control.

ValidationExpression for Day


Day: ValidationExpression="^((([1-9]?)|([1-2][0-9])?)|([3][0-1]?))$"



ValidationExpression for Month


ValidationExpression="^((([1-9]?)|([0][1-9])?)|([1][0-2]?))$"



ValidationExpression for Year


ValidationExpression="[0-9]{4}"

Labels:

To restrict date to mm/dd/yyyy format

The following code sample is a regular expression that can be used approriately to control date inputs to a particular format. In thise example, we restrict the user to enter date values in month/date/year format.

Take a regular expression validator Control and in validation expression write the following code


([1-9]|1[012])[- /.]([1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d

Labels:

Restricting Date Values with Regular Expression validator

The code sample contains examples on how to restrict the user to enter a data value in a particular format. These formatting rules can be enforced by using Regular Expression validator.


date Format (for MM/DD/YYYY format)


([1-9]|1[012])[- /.]([1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d


date Format (for DD/MM/YYYY format)


(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d

Labels:

Regular Expression Samples

This code shows how to use regular expression in c#


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

namespace RegularExpression
{
class Program
{
static void Main(string[] args)
{
Validation valid = new Validation();
bool flag = valid.IsAlphaNumeric("10A");
Console.WriteLine(flag);
}
}
//Class for the Validation
class Validation
{
//Function to test for the positive integer
public bool IsNaturalNumber(string strNumber)
{
Regex NotNatural = new Regex("[^0-9]");
Regex Natural = new Regex("0*[1-9][0-9]*");
return !NotNatural.IsMatch(strNumber) && Natural.IsMatch(strNumber);
}
//Function for test the natural numbes with zero
public bool IsWholeNumber(string strNumber)
{
Regex whole = new Regex("[^0-9]");
return !whole.IsMatch(strNumber);
}
//Function to check for a given string is a number or not
public bool IsNumber(string strNumber)
{
Regex NotNumberPattern = new Regex("[^0-9]");
Regex TwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
Regex TwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
string strValidRealPattern = "^([-][.][-.]|[0-9])[0-9]*[.]*[0-9]+$";
string validIntegerPattern = "^([-][0-9])[0-9]*$";
Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + validIntegerPattern + ")");
return !objNumberPattern.IsMatch(strNumber) &&
!TwoDotPattern.IsMatch(strNumber) &&
!TwoMinusPattern.IsMatch(strNumber) &&
objNumberPattern.IsMatch(strNumber);

}
//Function to check for the alphabets
public bool IsAlpha(string strCheck)
{
Regex objAlphaPattern = new Regex("[^a-zA-Z]");
return !objAlphaPattern.IsMatch(strCheck);
}
//Function to check for the alphanumeric
public bool IsAlphaNumeric(string strCheck)
{
Regex objAlphaNumeric = new Regex("[^a-zA-Z0-9]");
return !objAlphaNumeric.IsMatch(strCheck);
}
}
}

Labels:

Regular Expression for DD/MM/YYYY Format

(0[1-9]|[12][0-9]|3[01])[//.](0[1-9]|1[012])[//.](19|20)\d\d

Labels:

Regular Expression Validation using Exec() in Javascript

Exec() method of the Javascript is the Regular Expression object (RegExp::exec()). exec() method allows to use the regular expression object and finds the pattern defined. RegExp.$1,$2 .. $9 are the first through ninth parenthesized expressions matched.

The following code snippet shows how exex() method works.


//Paste the code into script tag
function getInfo()
{
reg = /(\w+)\s(\d+)/;
var str="Shanthi 22";
reg.exec(str);
document.write("Name: " +RegExp.$1+"
Age :"+RegExp.$2);
}
//Paste the code into body tag
onload()="getInfo()"

Labels:

Validate Zip Code

The following pattern checks whether the input string is a valid zipcode in the format ddddd or ddddd-dddd, where d is any digit 0-9.


private void btnValidate_Click(object sender, System.EventArgs e)
{
bool IsValid = true;
if (!Regex.IsMatch(txtZip.Text, @"^\s*(\d{5}|(\d{5}-\d{4}))\s*$"))
{
txtZip.ForeColor = Color.Red;
IsValid = false;
}
else
{
txtZip.ForeColor = Color.Black;
}
}

Labels:

Using regular expression to search for string,substring among array of strings

//Below is an function which searches for a existence of a string,substring among array of strings.

//Declare the string to search and the content string


string[] words ={"This","is an attempt","to search","string contents","using","regular expressions." };
string strToSearch = "regular";

//call the function SearchAndDisplay which will search and display the result.


if (!SearchAndDisplay(strToSearch,words))
{
Response.Write("No matches found.");
}

/*
This function iterates through a given array and finds existence of a string among it.if found returns true and prints the string else returns false.
*/
private bool SearchAndDisplay(string strToSearch,string[]arrContentString)
{
bool isMatchFound = false;
foreach (string tempString in arrContentString)
{
if (System.Text.RegularExpressions.Regex.IsMatch(tempString, strToSearch, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
isMatchFound = true;
Response.Write("Match found in :" + tempString.Trim() + "
");
}

}
return isMatchFound;

}

Labels:

Find number from a string

This regular expression will display if a string entered contains a number.


private void btnFindNumber_Click(object sender, System.EventArgs e)
{

Regex re = new Regex(@"\d+");
Match m = re.Match(txtFindNumber.Text);
if (m.Success)
{
lblResults.Text = string.Format("RegEx found " + m.Value + " at position " + m.Index.ToString());
}
else
{
lblResults.Text = "You didn't enter a string containing a number!";
}
}

Labels:

TextBox should start with a character and should only contain alphanumeric

Below script helps to bind the user to enter the value in the textbox which starts only with a character and then it may be followed by any alpanumeric characters
To achive this simply follow the following Steps

Write the below javascript function in the aspx page under head section :






In the Body Section of the .aspx page just bind the onClientclick event of the button to the function above in the javascript to check the value of TextBox1

Take one texbox and button control on the page as shown below




Labels:

TextBox should only contain the following format 12345-67890

Below script helps to bind the user to enter the value in the textbox which
contain first five numbers followed by one hypen and followed by five numbers
for example 12345-67890
To achive this simply follow the following Steps

Write the below javascript function in the aspx page under head section :





In the Body Section of the .aspx page just bind the onClientclick event of the button to the function above in the javascript to check the value of TextBox1

Take one texbox and button control on the page as shown below




Labels:

TextBox for mobile number validation ie it start with 9 and followed by 9 digits

Below script helps to bind the user to enter the value in the textbox which
which starts with digit 9 and followed by nine digits
for example 9001234567
To achieve this simply follow the following Steps

Write the below javascript function in the aspx page under head section :



In the Body Section of the .aspx page just bind the onClientclick event of the button to the function above in the javascript to check the value of TextBox1

Take one texbox and button control on the page as shown below


Labels:

How to remove trailing & leading spaces with regular expression in c#

The following code sample helps to remove trailing & leading spaces with regular expression in c#
This Needs a reference to System.Text.RegularExpressions. Pass the method, your string and it will trim the string

//Namespace Reference
using System.Text.RegularExpressions;

public string TrimString(string str) //pass the str which has to be trimmed
{
try
{
string pattern = @"^[ \t]+|[ \t]+$";
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
str = reg.Replace(str, "");
return str;
}
catch (Exception ex)
{
throw ex;
}
}

Labels:

Common Regular Expressions

1.NameValidationRegularExpression = "^[a-zA-Z]+(([\'\\,\\.\\-][a-zA-Z])?[a-zA-Z]*)*$"; ^[a-zA-Z0-9]+(([\'\\,\\.\\-][a-zA-Z0-9])?[a-zA-Z0-9]*)*$ ;
2. NumberValidationRegularExpression = "^([1-9]([0-9])+)$";
3. AlphaNumericValidationRegularExpression = "^([a-zA-Z0-9]+)$"; , ^[a-zA-Z0-9]+(\s*)
4. DateValidationRegularExpression = "^(01|1|02|2|3|03|5|05|4|04|06|6|7|07|8|08|10|9|09|11|12)[/-]((31(?! (02|04|06|09|11|2|4|6|9)))|((30|29)(?! 02))|(29(?= 02 (((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\\d|2[0-8])[/-]((1[6-9]|[2-9]\\d)\\d{2})$";
5. EmailIdValidationRegularExpression = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$";
6. ZipCodeValidationRegularExpression = "^\\d{5}((-|\\s)?\\d{4})?$";
7. PhoneValidationRegularExpression = "((\\(\\d{3}\\) ?)|(\\d{3}-))?\\d{3}-\\d{4}";
8. CurrencyValidationRegularExpression = "^\\$?\\-?([1-9]{1}[0-9]{0,2}(\\,\\d{3})*(\\.\\d{0,2})?|[1-9]{1}\\d{0,}(\\.\\d{0,2})?|0(\\.\\d{0,2})?|(\\.\\d{1,2}))$|^\\-?\\$?([1-9]{1}\\d{0,2}(\\,\\d{3})*(\\.\\d{0,2})?|[1-9]{1}\\d{0,}(\\.\\d{0,2})?|0(\\.\\d{0,2})?|(\\.\\d{1,2}))$|^\\(\\$?([1-9]{1}\\d{0,2}(\\,\\d{3})*(\\.\\d{0,2})?|[1-9]{1}\\d{0,}(\\.\\d{0,2})?|0(\\.\\d{0,2})?|(\\.\\d{1,2}))\\)$";
9. ClassValidationRegularExpression = "^([-]|[_]|[a-zA-Z0-9-:_+,<>./| #'`]+)$";
10. NameValidationRegularExpression = "^([a-zA-Z0-9-]{1,25})$";
11. GuidValidationRegularExpression ="^\\{?[a-zA-Z\\d]{8}-([a-zA-Z\\d]{4}-){3}[a-zA-Z\\d]{12}\\}?$";
12. URLValidationExpression = "^(http|https|ftp)\\://((([a-z_0-9\\-]+)+(([\\:]?)+([a-z_0-9\\-]+))?)(\\@+)?)?(((((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5]))))|((([a-z0-9\\-])+\\.)+([a-z]{2}\\.[a-z]{2}|[a-z]{2,4})))(([\\:])(([1-9]{1}[0-9]{1,3})|([1-5]{1}[0-9]{2,4})|(6[0-5]{2}[0-3][0-6])))?$";
13. FederalIDValidationExpression = "^([a-zA-Z 0-9\\-]+)$";
14. Name = ^[a-zA-Z0-9'@#_\-\*\./\\:`~\s\^]+(\s*)
15. Decimal(11,3)--- ^[1-9]\d{0,10}(\.\d{0,3})?$

Labels:

TextBox should only contain small case alphabets

Javascript code:



Take the button and the textbox control in the page as follows


Labels:

Validation for creditcard no

here i have post he regex for credit card number which has totally 16 digit

after every 4 digit it has "-" or not contain.


^(\d{4}-){3}\d{4}$|^(\d{4} ){3}\d{4}$|^\d{16}$

ex"

< %@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" % >
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

< html xmlns="http://www.w3.org/1999/xhtml" >

< head runat="server" >
< title> < /title >

< /head >

< body >

< form id="form1" runat="server" >

< div >

< asp:TextBox ID="TextBox1" runat="server" CausesValidation="True" > < /asp:TextBox >

< /div >
< asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"

ControlToValidate="TextBox1" ErrorMessage="your error message"

ValidationExpression="^(\d{4}-){3}\d{4}$|^(\d{4} ){3}\d{4}$|^\d{16}$" >< /asp:RegularExpressionValidator >
< /form >

< /body >

< /html >

Labels:

Accept a text of 1000 characters only

Here we have to discuss about , suppose in a message board related to same point of

view , we place the text with multiline = True.. so user can enter a number of

paragraphs, so the user has to avoid more lines ( paragraph ) to allow only the

specific Character here the Regular expression to allow only 1000 Characters


REGEX - Validataion Expression - [\\s\\S]{0,1000}$

Labels:

Regular Expression

Regular Expression:

are specially formatted strings used to find patterns in text.

Like what you do when you search for something like files in windows by providing search pattern like *.exe or ms*.exe.

what is the meaning of specially formatted?

This mean that it is not as any string it has specific format to match the string you want. for example:

Zip code must be constructed with 5 digits no spaces or (-)or(_) or(.) etc....

also not less than 5 or more than 5

like: 12365 accepted

but: 123 or 444444 not accepted.

So the Regular expression to match what we want may be like that:

"^\d{5}$"


don't you see that it is special formated ?!

this means to find any digit "\d" five times {5} in the whole string "^....$"

if it is like this "\d{5}"

then this number will be accepted: 123456 which consiste of 6 digit & we want only 5.

We will describe some of Regular Expression symbols on our Tutorial.

When you are trying to provide form validation, it is usefull to use Regular Expressions to your work.

Here we will test Class Regex in namespace System.Text.RegularExpressions,

you have to reference at the begining that you want to use this namespace:

// To enable you to use RegularExpressions
// namespace's Classes like Regex & Match.
using System.Text.RegularExpressions;


Regex class contains several static methods that allow you to use a regular expression without explicitly creating a Regex object. Using a static method is equivalent to constructing a Regex object, using it once and then destroying it.

Regex has the static method Match, it searches an input string for an occurrence of a regular expression & returns the precise result as a single Match object -object of class Match-.

Example:

suppose we want to validate a name which must start with Letter in Uppercase and has any number of characters but not numbers.

Ex:

Mohammed: accepted

john: not accepted because it is starting with small letter [j].

Step 1:

what is the suitable Regular Expression for this work?

it is "^[A-Z]+[a-zA-Z]*$"

what is this expression mean?

^ and $ match the positions at the beginning and end of the string, which mean search the entire string for the specific patter.

[A-Z] Means a range of characters between A to Z in Uppercase; means the 1st Character of the string must be in Capital letter.

+ mean Matches one or more occurrences of the patter [A-Z].

[a-zA-Z] range of characters in upper or lower case.

* mean Matches zero or more occurrences of the patter [a-zA-Z]. (+ or * comes after the patter you are looking).

now we can read that expression as follow:

A name that starts with a Capital letter(A-Z) followed by any number of Letters in upper or lower case.

Step 2: How can we code this in C# using Regex Class?

suppose we have a textBox called txtName.

Code:

// public static Match Match(string input,string pattern);
// this is the parameter of the Match method in Regex Class,
// this method returns a referenc to Match Class
// so that we can access its properties and methods
// through this reference.
Match MyRegMatch = Regex.Match(txtName.Text,"^[A-Z]+[a-zA-Z]*$")
// using Success property in Our Match object to
// check if the match occure or not.
if(!MyRegMatch.Success)
{
//Name was incorrect Cause no Match occur
MessageBox.Show("Invalid First Name",
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
txtName.Focus();
return;
}


also we can Regex.Match(txtName.Text,"^[A-Z]+[a-zA-Z]*$").Success directly in if condition

This is very simple example of what is Regular expression and how it can be used. Later we will introduce more about Regular expression and its use in other tutorials.

Notes: Usefull resources:

Regular Expressions Symbols in details in VS.Net Documentation:

Link #1

More about Regex Class:

Link #2

---------------------------------------------------------------------------- example of Regular Expression Patter with its description:

"^[0-9]+\s+([a-zA-z]+|[a-zA-z]+\s+[a-zA-z]+)$"


[0-9]+ means Start with one or more Numbers like 1234

\s+ followed by one or more white spaces Like

([a-zA-z]+|[a-zA-z]+\s+[a-zA-z]+) this is complex one which means:

even if the next word start with one or more characters

in any lettercase that is not a number, | means OR

or it can be start with one or more characters followed

by white one or more white spaces followed by one or more characters.

example that is accepted:

123 NasrCity Cairo

1234 Giza

examples that is not accepted

123

Labels: ,

Learn how to write a Regular Expression:

What Regular Expression?
A regular expression is a pattern that can match various text strings, used for validations.

Where and when to use Regular Expression?
It can be used in the programming languages which supports or has regular expression class as in built or it supports third party regular expression libraries.

Regular expressions can be used to valid different type of data without increase the code with if and case conditions. A number of if conditions can be omitted with single line of regular expression checking.

Benefits of Regular Expression:
The following are benefits (not all included) of use of Regular Expression.
a) # line of code can be reduced.
b) Speed Coding.
c) Easy maintenance (you don’t need to change if validation criteria changes, just check the regular expression string).
d) Easy to understand (you don’t need to understand the programmer logic on large if statements and case statements).

Elements of Regular Expression:
Here are the basic elements of regular expression characters/literals, which can be used to build big regular expressions:

^ ---->Start of a string.
$ ---->End of a string.
. ----> Any character (except \n newline)
{...}----> Explicit quantifier notation.
[...] ---->Explicit set of characters to match.
(...) ---->Logical grouping of part of an expression.
* ---->0 or more of previous expression.
+ ---->1 or more of previous expression.
? ---->0 or 1 of previous expression; also forces minimal matching when an expression might match several strings within a search string.
\ ---->Preceding one of the above, it makes it a literal instead of a special character. Preceding a special matching character, see below.
\w ----> matches any word character, equivalent to [a-zA-Z0-9]
\W ----> matches any non word character, equivalent to [^a-zA-Z0-9].
\s ----> matches any white space character, equivalent to [\f\n\r\v]
\S----> matches any non-white space characters, equivalent to [^\f\n\r\v]
\d ----> matches any decimal digits, equivalent to [0-9]
\D----> matches any non-digit characters, equivalent to [^0-9]

\a ----> Matches a bell (alarm) \u0007.
\b ----> Matches a backspace \u0008 if in a [] character class; otherwise, see the note following this table.
\t ---->Matches a tab \u0009.
\r ---->Matches a carriage return \u000D.
\v ---->Matches a vertical tab \u000B.
\f ---->Matches a form feed \u000C.
\n ---->Matches a new line \u000A.
\e ---->Matches an escape \u001B

$number ----> Substitutes the last substring matched by group number number (decimal).
${name} ----> Substitutes the last substring matched by a (? ) group.
$$ ----> Substitutes a single "$" literal.
$& ----> Substitutes a copy of the entire match itself.
$` ----> Substitutes all the text of the input string before the match.
$' ----> Substitutes all the text of the input string after the match.
$+ ----> Substitutes the last group captured.
$_ ----> Substitutes the entire input string.

(?(expression)yes|no) ----> Matches yes part if expression matches and no part will be ommited.


Simple Example:
Let us start with small example, taking integer values:
When we are talking about integer, it always has fixed series, i.e. 0 to 9 and we will use the same to write this regular expression in steps.

a) Regular expression starts with “^”
b) As we are using set of characters to be validated, we can use [].
c) So the expression will become “^[1234567890]”
d) As the series is continues we can go for “-“ which gives us to reduce the length of the expression. It becomes “^[0-9]”
e) This will work only for one digit and to make it to work for n number of digits, we can use “*”, now expression becomes “^[0-9]*”
f) As with the starting ending of the expression should be done with “$”, so the final expression becomes “^[0-9]*$”

Note: Double quotes are not part of expression; I used it just to differentiate between the sentences.

Is this the way you need to write:
This is one of the way you can write regular expression and depending on the requirements and personal expertise, regular expression could be compressed much shorter, for example above regular expression could be reduced as.

a) Regular expression starts with “^”
b) As we are checking for the digits, there is a special character to check for digits “\d”
c) And digits can follow digits , we use “*”
d) As expression ends with “$”, the final regular expression will become
"^\d*$”

Digits can be validated with different ways of regular expressions:

1) ^[1234567890]*$
2) ^[0-9]*$
3) ^\d*$

Which one to choose?
Every one of above expressions will work in the same way, choose the way you are comfort, it is always recommended to have a smaller and self expressive and understandable, as these will effect when you write big regular expression.

Example on exclude options:
There are many situation which demands us to exclude only certain portion or certain characters,
Eg: a) Take all alpha numeric and special symbols except “&”
b) Take all digits except “7”
then we cannot prepare a big list which includes all instead we use the symbol of all and exclude the characters / symbols which need to be validated.
Eg: “^\w[^&]*$” is the solution to take all alpha numeric and special symbols except “&”.

Other Examples:
a) There should not be “1” as first digit,?
^[^1]\d*$ ? this will exclude 1 as first digit.

b) There should not be “1” at any place?
^\d[^1]*$ ? this will exclude the 1 at any place in the sequence.

Note: Here ^ operator is used not only to start the string but also used to negate the values.

Testing of Regular expression:
There are several ways of testing this
a) You can write a windows based program.
b) You can write a web based application.
c) You can even write a service based application.


Windows base sample code:
Here are steps which will be used for regular expression checking in dotNet:

a) Use System.Text.RegularExpression.Regex to include the Regex class.
b) Create an Regex object as follows:
Regex regDollar= new System.Text.RegularExpressions.Regex("^[0-9]*$ ");
c) Call the IsMatch(string object) of the Regex call, which will return true or flase.
d) Depending on the return state you can decide whether passed string is valid for regular expression or not.]

Here is the snap shot code as function:

Public boolean IsValid(string regexpObj, string passedString)
{
//This method is direct method without any exceptional throwing..
Regex regDollar= new System.Text.RegularExpressions.Regex(regexpObj);
return regDollar.IsMatch(passedString);
}
With minor changes to the above function it can be used in windows or webbased or even as a service.

Another way -- Online checking:
At last if you are fed up with above and you have internet connection and you don’t have time to write sample, use the following link to test online

http://www.regexplib.com/RETester.aspx

Labels: ,

How to match a pattern by using regular expressions and Visual C#

Using regular expressions to match a pattern

1. Start Visual C#.
2. Create a new Visual C# Console Application.
3. Specify the using keyword on the Text.RegularExpressions namespace so that you will not be required to qualify declarations in those namespaces later in your code. The using statement must be used prior to any other declarations:

using System.Text.RegularExpressions;


4. Define a new regular expression that will use a pattern match to validate an e-mail address. The following regular expression is structured to accomplish three things:
1. Capture the substring before the @ symbol and put that into the "user" group.
2. Capture the substring after the @ symbol and put that into the "host" group.
3. Make sure that the first half of the string does not have an @ symbol.

Regex emailregex = new Regex("(?[^@]+)@(?.+)");


5. Define a new string containing a valid e-mail address. This provides a default value if the method's command-line argument is empty:

String s = "johndoe@tempuri.org";


6. Check to see if there are any command-line parameters; if there are, retrieve the first parameter and assign it to the variable "s".

if ( args.Length > 0 ) {
s = args[0];
}


7. Use the Match method to pass in the e-mail address variable and return a new Match object. The Match object will return regardless of whether any matches were found in the source string.

Match m = emailregex.Match(s);


8. By examining the Success property, we can decide whether to continue processing the Match object or to print an error message. If successful, display the "user" and "host" named groups within the Groups collection of the Match object.

if ( m.Success ) {
Console.WriteLine("User: " + m.Groups["user"].Value);
Console.WriteLine("Host: " + m.Groups["host"].Value);
} else {
Console.WriteLine(s + " is not a valid email address");
}
Console.WriteLine();


9. To keep the console window open after running the application, add the following lines of code:

System.Console.WriteLine("Press Enter to Continue...");
System.Console.ReadLine();


10. Build your project.
11. To run the application in the development environment using the default e-mail address specified in the code, press F5 or select Start from the Debug menu. To start the application with a command-line argument, there are three options:
* On the Project menu, click Properties, and then click Debug. In the Start Options section in the right pane, specify the e-mail address that you want to test. Press F5, or click Start on the Debug menu to run the application.

In Visual C# .NET 2003: On the Project menu, click Properties. In the left pane, click the Configuration Properties folder, and then click Debugging. Under Start Options, click Command Line Arguments and specify the e-mail adress that you want to test. Press F5 or select Start from the Debug menu to run the application.
* Start a command window and navigate to the "bin\debug" folder under the folder in which your project resides. Then type in the name of the executable followed by the e-mail address you wish to test.
* Locate the executable file for this project, and drag it to the Start...Run window on the taskbar. Add the e-mail address to verify, and click or press OK.

Labels: ,

How to dynamically load images in Crystal Reports using Visual Studio 2005

We must have a field (image path) in our database. We need to create a new DataSet/XML schema (XSD) (TypedDataSet) to use as resource data in creating a report, and add an additional field that is not in the table and which is of type base64Binary:
Or add it in XML:
< name="”image_stream”" type="”xs:base64Binary”" minoccurs="”0″">
When designing a report, drag and drop the “image_stream” field in the region where you want it to appear. Add CrystalReportViewer to your ASPX page. In the code-behind of your page, add the following method to load the image:
private void LoadImage(DataRow objDataRow, string strImageField, string FilePath)
{
try
{
FileStream fs = new FileStream(FilePath,
System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] Image = new byte[fs.Length];
fs.Read(Image, 0, Convert.ToInt32(fs.Length));
fs.Close();
objDataRow[strImageField] = Image;
}
catch (Exception ex)
{
Response.Write("" + ex.Message + "");
}
}
We need to fill the TypedDataSet, and before assigning this DataSet to the “SetDataSource” of our report, we need to add a few lines of code:
TypedDataSet ds = new TypedDataSet();

SqlConnection cn = new SqlConnection("Data Source=ServerName;" +
"Initial Catalog=DataBaseName;User ID=UserName;" +
"Password=UserPassWord");
SqlCommand Cmd = new SqlCommand();
SqlDataAdapter myAdapter = new SqlDataAdapter();

Cmd.CommandText = " Select * From TableName";
Cmd.Connection = cn;

myAdapter.SelectCommand = Cmd;

try
{
cn.Open();
myAdapter.Fill(ds.Tables[0]);
cn.Close();
}
catch (Exception ex)
{
throw;
}


for (int index = 0; index < ds.Tables[0].Rows.Count; index++)
{
if (ds.Tables[0].Rows[index]["image_path"].ToString() != "")
{
string s = this.Server.MapPath(
ds.Tables[0].Rows[index]["image_path"].ToString());

if (File.Exists(s))
{
LoadImage(ds.Tables[0].Rows[index], "image_stream", s);
}
else
{
LoadImage(ds.Tables[0].Rows[index], "image_stream",
"DefaultPicturePath");
}
}
else
{
LoadImage(ds.Tables[0].Rows[index], "image_stream",
"DefaultPicturePath");
}
}

try
{
// Finally display report in crystal report viewer
ReportDocument crDoc = new ReportDocument();
crDoc.Load(Server.MapPath("CrystalReport.rpt"));
crDoc.SetDataSource(ds.Tables[0]);
CrystalReportViewer1.ReportSource = crDoc;
}
catch (Exception ex)
{
throw;
}

Labels:

Passing Value into Parameter Field of Crystal Report During Run time

This code sample shows how to pass a parameter to Crystal Reports using C# syntax.


CrystalDecisions.Shared.ParameterFields pfields = new CrystalDecisions.Shared.ParameterFields();
CrystalDecisions.Shared.ParameterField pfield = new CrystalDecisions.Shared.ParameterField();
CrystalDecisions.Shared.ParameterDiscreteValue disvalue = new CrystalDecisions.Shared.ParameterDiscreteValue();


disvalue.Value = "This Is a Parameter Value"; // Parameter Value
pfield.Name = "c1"; // Parameter Name

pfield.CurrentValues.Add(disvalue);
pfields.Add(pfield);

crystalReportViewer1.ParameterFieldInfo = pfields; //U must use crystalReportViewer

crystalReportViewer1.ReportSource = @"G:\WindowsApplication1\WindowsApplication1\crpt.rpt";

Labels:

Convert a Crystal Report to PDF

This Code shows how to convert a Crystal Report to PDF Document.




'First Create a crystal Report.
' Drag and drop the Crystal Report Viewer in the form
' copy this code on top of the code
Imports System.Data
Imports System.Data.SqlClient
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared

Private myDS As New Dataset1() ' Dataset you created.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim rpt As New CrystalReport1() 'The report you created.
Dim myConnection As SqlConnection
Dim MyCommand As New SqlCommand()
Dim myDA As New SqlDataAdapter()

Try

myConnection = New SqlConnection("Data Source=localhost;Integrated Security=SSPI;" & _
"Initial Catalog=pubs;")
MyCommand.Connection = myConnection
MyCommand.CommandText = "SELECT * FROM authors"
MyCommand.CommandType = CommandType.Text
myDA.SelectCommand = MyCommand

myDA.Fill(myDS, "authors")
rpt.SetDataSource(myDS)
CrystalReportViewer1.ReportSource = rpt

Catch Excep As Exception
MessageBox.Show(Excep.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

End Sub

' This code is used to convert crystal report to pdf
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

' Variable Declaration

Dim CrReport As New CrystalReport1() ' Report Name

Dim CrExportOptions As ExportOptions

Dim CrDiskFileDestinationOptions As New DiskFileDestinationOptions()

Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions()

' Set the destination path and file name
CrDiskFileDestinationOptions.DiskFileName = "d\RichText.pdf"

' Set the crystal report datasource to fill the dataset
CrReport.SetDataSource(myDS)


' Set export options

CrExportOptions = CrReport.ExportOptions



With CrExportOptions

' Set the destination to a disk file

.ExportDestinationType = ExportDestinationType.DiskFile

' Set the format to PDF

.ExportFormatType = ExportFormatType.PortableDocFormat

' Set the destination options to DiskFileDestinationOptions object

.DestinationOptions = CrDiskFileDestinationOptions

.FormatOptions = CrFormatTypeOptions



End With



' Trap any errors that occur on export

Try

' Export the report

CrReport.Export()

Catch err As Exception

MessageBox.Show(err.ToString())

End Try


End Sub

Labels:

Load Crystal Report from File

This code will show how to load a crystal report .rpt file that is saved on a local drive instead of embedded. The advantage to this is the program does not need to be re-compiled each time a report is modifed. Also, the .rpt can be upload from the application and stored in a database and then written to file. Do not embed the .rpt file when using this method.


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

namespace Report
{
public partial class Report : Document
{
public void ReportLoad()
{
ReportDocument reportDocument = new ReportDocument();
string filePath = "C:\Projects\Application\Report\CrystalReport.rpt";
reportDocument.Load(filePath);
crystalReportViewer.ReportSource = reportDocument;
}
}

}

Labels:

Exports generated crystal report into Excel Format & download.

1.First Create crystal report.
2.Create Interface to display report (i.e aspx Form) in that add Crystal Viewer (CrystalReportViewer1) & Command Button (btnExToExcel).
3.Change report name into CallReport().
4.CrystalReportViewer1 is an ID of Crystal Report Viewer. AND btnExToExcel is an ID of command button.



Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Web
Imports CrystalDecisions.Shared
Imports CrystalDecisions.ReportSource

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
CallReport()
End If
End Sub

Private Sub CallReport()
Dim objDS As New DataSet

Dim EmpReportDoc As New CrystalDecisions.CrystalReports.Engine.ReportDocument()
Dim rptFile As String = Server.MapPath("rptEmployee.rpt")

EmpReportDoc.Load(rptFile)
Session("Emprpt") = EmpReportDoc

''Create Dataset as per requirement

EmpReportDoc.SetDataSource(objDS.Tables(0))

Me.CrystalReportViewer1.ReportSource = EmpReportDoc
CrystalReportViewer1.RefreshReport()
End Sub

#Region " Export To Excel "

Protected Sub btnExToExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExToExcel.Click

Dim objEmpDoc As New ReportDocument
objEmpDoc = Session("Emprpt")

Dim oStream As MemoryStream = objEmpDoc.ExportToStream(ExportFormatType.Excel)

With HttpContext.Current.Response

.ClearContent()

.ClearHeaders()

.ContentType = "application/xls"

.AddHeader("Content-Disposition", "attachment; filename=Employee Details.xls")

.Clear()

.BinaryWrite(oStream.ToArray)

.End()

End With

End Sub

#End Region

Labels:

How to pass parameters to crystal report at runtime.

This example shows how to pass parameters to Crystal reports at runtime.

First create crystal report. In the interface of report (.aspx form) to display report, add report document through Toolbox-->Components-->ReportDocument.

Call the sub routine CreatePDF to display report.

rptProduct is the name of crystal report and docProd is the name of report document.

Add a blank formula in the cyrstal report.This formula should not be running formula.


Imports System.Data
Imports System.Data.SqlClient
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System.IO

'This call is required by the Web Form Designer.
Private Sub InitializeComponent()
'start - This code should be pasted under #Region Private Sub itializeComponent()
'rptProduct is the name of crystal report.
Me.docProd = New rptProduct
'
'docProd
'
Me.docProd.PrintOptions.PaperOrientation = CrystalDecisions.Shared.PaperOrientation.DefaultPaperOrientation
Me.docProd.PrintOptions.PaperSize = CrystalDecisions.Shared.PaperSize.DefaultPaperSize
Me.docProd.PrintOptions.PaperSource = CrystalDecisions.Shared.PaperSource.Upper
Me.docProd.PrintOptions.PrinterDuplex = CrystalDecisions.Shared.PrinterDuplex.Default
'Ends here

'Declaration of report document
Protected WithEvents docProd As rptProduct

Private Sub CreatePDF()
Dim objDS As New DataSet
Dim dfdoFile As New CrystalDecisions.Shared.DiskFileDestinationOptions
Dim strServerPath As String
Dim szFileName As String


'Create dataset as per requirement

docProd.SetDataSource(objDS.Tables(0))

szFileName = Session.SessionID & ".pdf" ' rptDailyCalls.pdf
strServerPath = MapPath("~") & "\Report\" ' Here the pdf file will be saved.
File.Delete(strServerPath & "\" & szFileName) ' Delete file first
dfdoFile.DiskFileName = strServerPath & "\" & szFileName
docProd.DataDefinition.FormulaFields("DispFromDate").Text = "Date(" & Format(Date.Now,"dd/MM/yyyy") & ")"
'Here DispFromDate is the name of blank formula
With docProd
.ExportOptions.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile
.ExportOptions.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat
.ExportOptions.DestinationOptions = dfdoFile
.Export()
End With
'URL of the pdf file
Response.Redirect("http://localhost/WebApplication1/" & szFileName ,Flase)
End Sub

Labels:

Pass Values to Crystal Report Formula Field

Pass values dynamically to crystal report formula field


rpt.DataDefinition.FormulaFields["Head1"].Text = "'" + Session["BRANCH_NAME"].ToString() + "'";
rpt.DataDefinition.FormulaFields["Head2"].Text = "'" + Session["ADDRESS1"].ToString() + "'";
rpt.DataDefinition.FormulaFields["Head3"].Text = "'" + head3 + "'";
rpt.DataDefinition.FormulaFields["Head4"].Text = "'" + head4 + "'";

Labels:

Export crystal report to pdf directly

the given code directly export to pdf format.

store your query result in dataset 'ds'


//Declare Reportdocument Object
ReportDocument rpt=new ReportDocument();

//set a ReportPath and assign the dataset to reportdocument object
rpt.Load(Server.MapPath("Report1.rpt"));
rpt.SetDataSource(ds);


//assign the values to crystal report viewer
CrystalReportViewer1.ReportSource = rpt;
CrystalReportViewer1.DataBind();

//Exporting PDF
MemoryStream oStream; // using System.IO
oStream = (MemoryStream)
rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(oStream.ToArray());
Response.End();

Labels:

Export Crystal Report to Excel Sheet

The Given Coding is directly export the crystal report without showing crystalreportviewer

MemoryStream oStream; // using System.IO
oStream = (MemoryStream)
rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.Excel);
Response.Clear();
Response.Buffer = true;
Response.ContentType = "appliaction/ms-excel";

Response.BinaryWrite(oStream.ToArray());
Response.End()

Labels:

Way to convert Crystal Report to Word without crystalreportviewer

The Given Coding is directly used to export the crystal report without showing crystalreportviewer


MemoryStream oStream; // using System.IO
oStream = (MemoryStream)
rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocument);
Response.Clear();
Response.Buffer = true;
Response.ContentType = "appliaction/ms-word";

Response.BinaryWrite(oStream.ToArray());
Response.End()

Labels:

Bind Crystal Report in ASP.Net

This code sample shows how to bind a crystal report in asp.net


Dim myConnection As New SqlClient.SqlConnection()
myConnection.ConnectionString = "server= (local)\NetSDK;database=pubs;Trusted_Connection=yes"
Dim MyCommand As New SqlClient.SqlCommand()
MyCommand.Connection = myConnection
MyCommand.CommandText = "Select * from Stores"
MyCommand.CommandType = CommandType.Text
Dim MyDA As New SqlClient.SqlDataAdapter()
MyDA.SelectCommand = MyCommand
Dim myDS As New Dataset1()
'This is our DataSet created at Design Time
MyDA.Fill(myDS, "Stores")
'You have to use the same name as that of your Dataset that you created during design time
Dim oRpt As New CrystalReport1()
' This is the Crystal Report file created at Design Time
oRpt.SetDataSource(myDS)
' Set the SetDataSource property of the Report to the Dataset
CrystalReportViewer1.ReportSource = oRpt

Labels: