Passing Parameters to Crystal Reports

20. October 2009 16:26

C# 

I found many tutorials on the internet that shows how to pass the parameters (Discreet Parameters) to crystal reports, I tried all of them, but unfortunately I didn't get anyone of it to work. Therefore I though to give a trial on my code and eventually I got it running. I assume that you have a report ready with a parameter.

Firstly to get it running we have to use the below namespaces:

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

After you added a namespace now we have to pass a value to the report parameter, Here is the code to do this: Step 1: Create a ReportDocument object and initialize it

ReportDocument crReportDocument = new ReportDocument();

Step 2: Use the Load method of the ReportDocument object to load the report in the memory and use it.

crReportDocument.Load("C:\\report.rpt");

Step 3: After loading the report in the ReportDocument object, we can now set the value to the report parameter using SetParameterValue method. This is an overloaded method which we can use according to the requirement. I have used the parameter name and parmeter value which are of string and object type respectively.

crReportDocument.SetParameterValue("id", 115);

Step 4: As the data in the report is being populated from the database according to the parameter provided in the previous step. So to populate the data from the database we also have to set the database credentials to log in to the database and populate the report data.

crReportDocument.SetDatabaseLogon("sa", "pass#word1", "MX", "AdventureWorks");

Step 5: After the credentials have been set up for he database, the last step is to set the ReportSource property of the Crystal Report Viewer.

crystalReportViewer1.ReportSource = crReportDocument;

Here is the complete code:

ReportDocument crReportDocument = new ReportDocument();
crReportDocument.Load("C:\\report.rpt");
crReportDocument.SetParameterValue("id", 115);
crReportDocument.SetDatabaseLogon("sa", "pass#word1", "MX", "AdventureWorks"); crystalReportViewer1.ReportSource = crReportDocument;
Currently rated 3.0 by 1 person

Requesting delivery/read receipt from C# using MailMessage class

16. October 2009 15:38

.NET Framework C# 

Sending e-mail through code is easy, but how do we get to know that an e-mail that we send is delivered and read by the intended recipient. When we send e-mail through code we can request a delivery notification and read receipt from the receiver, similar to the way we do in outlook. But the problem is not every mail server supports this kind of request from the code. We set a mail header while sending mail from code which is then processed by the mail server and the sender of the mail gets the intended response. I have test the below code with Microsoft Exchange Server and it works perfectly fine. So let’s see what the code has:

First we need the namespace to use MailMessage class.

using System.Net;
using System.Net.Mail;

Initialize MailMessage class and set To, From, Subject and Body parameters

//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("prashantmx@xyz.com"); mail.To.Add("ankur@abc.com"); //set the content mail.Subject = "This is an email"; mail.Body = "this is the body content of the email.";

Now we have to set the Header property of the mail message class to request read/delivery recipt. As usual I first want to get notified for the e-mail I have sent has been delivered or not and then I want to get notified when my e-mail has been read by the recipient. Here I have also commented the deprecated method which is used in the previous version of .NET framework.

//This method has been deprecated.
//mail.Headers.Add("Return-Receipt-To", "prashantmx@xyz.com");
//Use this if you need a delivery notification of an email. DeliveryNotificationOption is an //umeration and can be used to set the delivery notification on the following options:
//1. Delay
//2. Never
//3. None
//4. OnFailure
//5. OnSuccess
/You can use also use OnFailure enum with OnSuccess enum. If in case the e-mail fails to 
//delivered you'll get notification for both the cases
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
//Add "Disposition-Notification-To" for Read receipt
mail.Headers.Add("Disposition-Notification-To", "");

When you set the headers for requesting delivery and read receipt, set the mail server and login credentials for the domain or for the e-mail service you use and then in the end call the Send method to send the e-mail.

//Set the SMTP server. You can also set the hostname instead of IP Address
SmtpClient smtp = new SmtpClient("192.168.1.5"); 
//Set the user network/domain credentials
NetworkCredential netCredit = new NetworkCredential("prashant@xyz.com", "pass#word1", "DOMAIN_NAME");
//Get SMTP to authenticate the credentials
smtp.Credentials = netCredit;
//Send the e-mail
smtp.Send(mail);

As I mentioned earlier also I have tested the above code with Exchange server only and it works perfectly. Here is the complete listing of the code :

static void ReadReceipts()
{
 //create the mail message
 MailMessage mail = new MailMessage();
 //set the addresses
 mail.From = new MailAddress("prashantmx@xyz.com");
 mail.To.Add("ankur@abc.com");
 //set the content
 mail.Subject = "This is an email";
 mail.Body = "this is the body content of the email.";
 //This method has been deprecated.
 //mail.Headers.Add("Return-Receipt-To", "prashantmx@xyz.com"); 
 //Use this if you need an delivery notification of an email.             //DeliveryNotificationOption is an enumeration
 //and can be used to set the delivery notification on the following options:
 //1. Delay
 //2. Never
 //3. None
 //4. OnFailure
 //5. OnSuccess
 //You can use also use OnFailure enum with OnSuccess enum. If in case the e-mail
 //fails to delivered you'll get notification for both the cases
 mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
 //Add "Disposition-Notification-To" for Read receipt
 mail.Headers.Add("Disposition-Notification-To", "");
 
 //Set the SMTP server. You can also set the hostname instead of IP Address
 SmtpClient smtp = new SmtpClient("192.168.1.5"); 
 //Set the user network/domain credentials
 NetworkCredential netCredit =             new NetworkCredential("prashant@xyz.com", "pass#word1", "DOMAIN_NAME");
         //Get SMTP to authenticate the credentials
 smtp.Credentials = netCredit;
 //Send the e-mail
 smtp.Send(mail);
}
Currently rated 4.2 by 11 people

Using Hashtables

20. September 2009 21:40

C# 

Here I illustrate how to create and use hash table. Each element of hash table is a combination of Key/Value pair stored in a DictionaryEntry object. A value in a hash table can be null or contains no value but a key cannot be of null reference. Key in hash table work as an identifier for the value where you can search a hash table for a value with a specified key.

First you will need to import the namespace System.Collection. We use System.Collection namespace because it contains various interface and classes the defines various collection of objects like list, dictionary, queues, hash tables and bit arrays.

1. Adding Key/Values to Hash Table

using System;
using System.Collections;
class HashtableClass
{
 public static void Main()
 {
   Hashtable htbl = new Hashtable();
   htbl.Add("AL", "Alabama");
   htbl.Add("CA", "California");
   htbl.Add("FL", "Florida");
   htbl.Add("NY", "New York");
   htbl.Add("WY", "Wyoming");
   // Get a collection of the keys.
   ICollection coll = htbl.Keys;
   foreach (string str in coll)
   {
     Console.WriteLine(str + ": " + htbl[str]);
   }
 }
}

2. Clear all Key/Value pairs in a hash table

To clear all the key/value pairs in a hash table use Clear() method of a hash table class:

htbl.Clear();

3. Remove Key/Value pairs from hash table

Just if you want to remove a particular value from a hash table use the Remove() method of hash table class and specify the Key to remove the key/value:

htbl.Remove("NY");

4. Adding Key/value pair to hash table by using indexer

We can use Add() method of the hash table class to add key/value pair to the hash table, but instead we can use indexer to add key/pair:

htbl["NY"] = "New York";

5. Use the ContainsKey() method to check if hash table contains a key

Just a simple method to use with an IF condition:

if(htbl.ContainsKey("NY"))
{
       Console.WriteLine("Hashtable contains key NY");
}

6. Use the ContainsValue() method to check if hash table contains a key

Just a simple method to use with an IF condition:

if(htbl.ContainsValue("New York"))
{
Console.WriteLine("Hashtable contains value New York");
}

7. Copy the keys from hash table into an array using the CopyTo() method

string[] keys=new string[5];
htbl.Keys.CopyTo(keys,0);
 No Rating

C# Method: Encrypting a string using MD5 algorithm

20. July 2009 00:40

C# Code Snippets 

Encrypting a string using the MD5 algorithm

This C# method will encrypt any string using MD5 algorithm. It generates the same hash as the PHP MD5() function

using System;using System.Collections.Generic;
using System.Linq;using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
namespace EncryptString
{
    class Program
    {
        public static string EncodePassword(string originalPassword)
        {
            Byte[] originalBytes;
            Byte[] encodedBytes;
            MD5 md5;
            md5 = new MD5CryptoServiceProvider();
            originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
            encodedBytes = md5.ComputeHash(originalBytes);
            return Regex.Replace(BitConverter.ToString(encodedBytes), "-", "").ToLower();
         }
         static void Main(string[] args)
         {
            Console.WriteLine("Enter a string to Encrypt");
            string strEnc = Console.ReadLine();
            Console.WriteLine(EncodePassword(strEnc));
            Console.ReadLine();
         }
    }
}
Currently rated 3.0 by 2 people

GUIDs in C# / SQL

26. June 2009 15:37

C# SQL Server Code Snippets 

GUID pronounced as goo'id - Globally unique identifier is a 128-bit integer that can be used to uniquely identify something. If you want to identify the large collection of data GUID is the best approach in my view. Also you can use the autoincremental integer to identify records, this is the basic approach programmer's use.

GUID method can be found under the System namespace and it also provides some overloads. Here is how we can use the GUID overloads:

System.Guid.NewGuid().ToString();    //c93ded50-7cce-4f3a-b8aa-5a1a34d80b14
System.Guid.NewGuid().ToString("N"); //636bdfd2bbc541229fbc6b869995ce6f
System.Guid.NewGuid().ToString("D"); //45e602b6-0904-47ac-a764-a5522f56f40f
System.Guid.NewGuid().ToString("B"); //{68f55508-f72c-4a38-b96b-f493c3c5adb9}
System.Guid.NewGuid().ToString("P"); //(1c2e52a7-e384-445e-b80a-e8704c6ecbd6)

To create GUID in SQL Server use the simple select statement:

SELECT NEWID()

 No Rating