Crystal Report send to email using c#.net

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Web.Mail;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        ReportDocument cryRpt;
        string pdfFile = "c:\\csharp.net-informations.pdf";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            cryRpt = new ReportDocument();
            cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
            crystalReportViewer1.ReportSource = cryRpt;
            crystalReportViewer1.Refresh(); 
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                ExportOptions CrExportOptions ;
                DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
                PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
                CrDiskFileDestinationOptions.DiskFileName = pdfFile;
                CrExportOptions = cryRpt.ExportOptions;
                CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
                CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
                CrExportOptions.FormatOptions = CrFormatTypeOptions;
                cryRpt.Export();

                sendmail();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void sendmail()
        {
            try {
                SmtpMail.SmtpServer.Insert(0, "your hostname");
                MailMessage Msg = new MailMessage();
                Msg.To = "to address here";
                Msg.From = "from address here";
                Msg.Subject = "Crystal Report Attachment ";
                Msg.Body = "Crystal Report Attachment ";
                Msg.Attachments.Add(new MailAttachment(pdfFile));
                System.Web.Mail.SmtpMail.Send(Msg);
            } 
            catch (Exception ex) { 
                MessageBox.Show (ex.ToString()); 
            }         
        }
    }
}

Explanin About Collections in c#.net

At its simplest, an object holds a single value. At its most complex, it holds references to many other objects. The .NET Framework provides collections—these include List and Dictionary. They are often useful.
Data types comprising collections of abstract objects are a central object of study in computer science. Sedgewick, p. 143

List

First, the List type provides an efficient and dynamically-allocated array. It does not provide fast lookup in the general case—the Dictionary is better for this. List is excellent when used in loops.
List
Program that uses List type [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 // Use the List type.
 List<string> list = new List<string>();
 list.Add("cat");
 list.Add("dog");

 foreach (string element in list)
 {
     Console.WriteLine(element);
 }
    }
}

Output

cat
dog

Dictionary

DictionaryThe Dictionary type in the base class library is an important one. It is an implementation of a hashtable, which is an extremely efficient way to store keys for lookup. The Dictionary in .NET is well-designed.
Dictionary
We try to reference items in a table directly by doing arithmetic operations to transform keys into table addresses. Sedgewick, p. 587
Program that uses Dictionary [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 // Use the dictionary.
 Dictionary<string, int> dict = new Dictionary<string, int>();
 dict.Add("cat", 1);
 dict.Add("dog", 4);

 Console.WriteLine(dict["cat"]);
 Console.WriteLine(dict["dog"]);
    }
}

Output

1
4
Note: This program shows how the Dictionary can be used with type parameters to store keys and values of specific types.
Tip: Many of the fastest and most powerful collections are found in System.Collections.Generic. These are generic types.
Generic Class

ArrayList

Framework: NETNext, the ArrayList is a collection found in System.Collections and it can store objects of any derived type. You don't need to worry about the type of the elements, at least until you need to use them.
ArrayList
Program that uses System.Collections [C#]

using System;
using System.Collections;

class Program
{
    static void Main()
    {
 ArrayList list = new ArrayList();
 list.Add("cat");
 list.Add(2);
 list.Add(false);

 foreach (var element in list)
 {
     Console.WriteLine(element);
 }
    }
}

Output

cat
2
False

Hashtable

Squares: different patternsTo continue, the Hashtable is a lookup data structure that uses a hash code to find elements quickly. The newer Dictionary collection is usually more appropriate for programs when available.
Hashtable
Program that uses Hashtable [C#]

using System;
using System.Collections;

class Program
{
    static void Main()
    {
 Hashtable table = new Hashtable();
 table["one"] = 1;
 table["two"] = 2;

 // ... Print value at key.
 Console.WriteLine(table["one"]);
    }
}

Output

1

Lists

StepsLists are linear—one element is stored after the other. The List generic type is often the best implementation available for its purpose on the .NET Framework. There are other versions of lists.
LinkedList SortedList
Also: A linear collection, such as an array or List, can be wrapped and made read-only with ReadOnlyCollection.
ReadOnlyCollection
Performance: Many collections (including List and Dictionary) can be optimized by using a capacity. This allocates extra initial memory.
Capacity

Tables

DataThere are many versions of lookup data structures other than the Hashtable and Dictionary in the .NET Framework. Usually, a Dictionary is the best option—but sometimes custom features are needed.

Explain About Windows Services Breafly

Introduction:

Here I will explain what windows service is, uses of windows service and how to create windows service in c#.

Description:



Today I am writing article to explain about windows services. First we will see what a window service is and uses of windows service and then we will see how to create windows service.

What is Windows Service?

Windows Services are applications that run in the background and perform various tasks. The applications do not have a user interface or produce any visual output. Windows Services are started automatically when computer is booted. They do not require a logged in user in order to execute and can run under the context of any user including the system. Windows Services are controlled through the Service Control Manager where they can be stopped, paused, and started as needed.

Create a Windows Service 

Creating Windows Service is very easy with visual studio just follow the below steps to create windows service
Open visual studio --> Select File --> New -->Project--> select Windows Service
And give name as WinServiceSample



After give WinServiceSample name click ok button after create our project that should like this



In Solution explorer select Service1.cs file and change Service1.cs name to ScheduledService.cs because in this project I am using this name if you want to use another name for your service you should give your required name.

After change name of service open ScheduledService.cs in design view right click and select Properties now one window will open in that change Name value to ScheduledService and change ServiceName to ScheduledService. Check below properties window that should be like this


After change Name and ServiceName properties again open ScheduledService.cs in design view and right click on it to Add Installer files to our application.

The main purpose of using Windows Installer is an installation and configuration service provided with Windows. The installer service enables customers to provide better corporate deployment and provides a standard format for component management.

After click on Add installer a designer screen added to project with 2 controls: serviceProcessInstaller1 and ServiceInstaller1

Now right click on serviceProcessInstaller1 and select properties in that change Account to LocalSystem



After set those properties now right click on ServiceInstaller1 and change following StartType property to Automatic and give proper name for DisplayName property


After completion of setting all the properties now we need to write the code to run the windows services at scheduled intervals.

If you observe our project structure that contains Program.cs file that file contains Main() method otherwise write the Main() method like this in Program.cs file

/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ScheduledService()
};
ServiceBase.Run(ServicesToRun);
}
After completion of adding Main() method open ScheduledService.cs file and add following namespaces in codebehind of ScheduledService.cs file

using System.IO;
using System.Timers;
If you observe code behind file you will find two methods those are

protected override void OnStart(string[] args)
{
}

protected override void OnStop()
{
}
We will write entire code in these two methods to start and stop the windows service. Write the following code in code behind to run service in scheduled intervals
 
//Initialize the timer
Timer timer = new Timer();
public ScheduledService()
{
InitializeComponent();
}
//This method is used to raise event during start of service
protected override void OnStart(string[] args)
{
//add this line to text file during start of service
TraceService("start service");

//handle Elapsed event
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

//This statement is used to set interval to 1 minute (= 60,000 milliseconds)

timer.Interval = 60000;

//enabling the timer
timer.Enabled = true;
}
//This method is used to stop the service
protected override void OnStop()
{
timer.Enabled = false;
TraceService("stopping service");
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
TraceService("Another entry at "+DateTime.Now);
}
private void TraceService(string content)
{

//set up a filestream
FileStream fs = new FileStream(@"d:\ScheduledService.txt",FileMode.OpenOrCreate, FileAccess.Write);

//set up a streamwriter for adding text
StreamWriter sw = new StreamWriter(fs);

//find the end of the underlying filestream
sw.BaseStream.Seek(0, SeekOrigin.End);

//add the text
sw.WriteLine(content);
//add the text to the underlying filestream

sw.Flush();
//close the writer
sw.Close();
}

If you observe above code in OnStart method I written event ElapsedEventHandler this event is used to run the windows service for every one minute

After completion code writing build the application and install windows service. To install windows service check this post here I explained clearly how to install windows service and how to start windows service. 

Now the service is installed. To start and stop the service, go to Control Panel --> Administrative Tools --> Services.  Right click the service and select Start. 

Now the service is started, and you will be able to see entries in the log file we defined in the code.

Now open the log file in your folder that Output of the file like this



Microsoft Visual Studio Command to collapse all sections of code


CTRL + M + O will collapse all.
CTRL + M + L will expand all.
CTRL + M + P will expand all and disable outlining.
CTRL + M + M will collapse/expand the current section.
These options are also in the context menu under Outlining.

Clea all controls at a time in DotNet


 void clear()
    {
        foreach (Control c in form1.Controls)       //This loop takes all controls from the form1
        {
            //Clear all textbox values
            if (c is TextBox)
                ((TextBox)c).Text = "";

            //clear all check boxes
            if (c is CheckBox)
                ((CheckBox)c).Checked = false;

            //Clear all radio buttons
            if (c is RadioButton)
                ((RadioButton)c).Checked = false;
        }
    }