Chart Control in Console Application Saving it as an image and sending it to Mail as a Html Format.


Today i want to discuss how to work with Chart Control in Console Application using Asp.net.I will illustrate two things one is Saving it as Physical File(.Jpeg Format/png Format) and sending the chart it through Mail as a body content (only works in some Mail servers) with snippet of code lines and Images.

Chart Controls works well in Asp.net web Application.But to Use it in Console Application.We need to do the following things.

Especially If you are working with .Net Framework 3.5 then you need to do the following steps.

If the dll is not found in your computer. Please find the setup in the following url.

http://www.microsoft.com/en-us/download/details.aspx?id=14422.You will download from here.And after installing the ChartControl exe the dll will be placed in this following path.

After running the setup file.The dll will be found in this Below path.
C:\Windows\assembly

After getting the System.Web.DataVisualization.dll the dll will not get added or refered in your Console Application.Because its a web Control.You need to act as little bit smart to add a reference to your console apllication


Chart dlls found

1)Open a dummy website and add this dll reference to your Application.Now close the dummy webapplication or dummy website

2)Now open your Original Console Application right click and add reference.Now go to recent tab and add the dll to your console Application.

The Below image illustrate how to work with that.

recent tabs

if it is .Net Framework4.0 than you have to browse the below file path
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0

if not found browse the below url http://contacinfo.com/15710/web and directly download the dll in your computer

After adding the dll in to your console Application.Now our task is to create the Physical image file of the chart and to send the chart send to Email(Not as an attachment) in the Email Body.The below code will illustrate that.

The First and foremost step is to import the namespace in your code

using System.Web.UI.DataVisualization

import namespace

After importing the namespace you will find the Chart Class in your Console Application.Now below Code illustrates How to save the physical image of the chart and Send the Chart control in Email Body.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Web.UI.WebControls;
using System.Web.UI.DataVisualization;
using System.Net.Mail;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

System.Web.UI.DataVisualization.Charting.Chart Chart1 = new System.Web.UI.DataVisualization.Charting.Chart();
//System.Web.UI.DataVisualization.Charting.Series sitem =new System.Web.UI.DataVisualization.Charting.Series();
// sitem.ChartType= System.Web.UI.DataVisualization.Charting.SeriesChartType.Line;
// Chart1.Series.Add(sitem);
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htmlwrter = new HtmlTextWriter(sw);

SqlConnection consql = null;
string strMailBody = "";
string strConString = System.Web.Configuration.WebConfigurationManager.AppSettings["AdminDBConnString"].ToString();
DataSet dsSMSCCount = new DataSet();
string strconsql = strConString;
consql = new SqlConnection(strconsql);
consql.Open();

string strQuery = "SELECT CMP_VAR_NAME, CMP_INT_CHARCOUNT, CMP_INT_ID FROM dbo.MDU_MST_CAMPAIGNS";

//string strQuery = "select sid_var_code senderid,CONVERT(VARCHAR,(SMSH_DTM_SENTDATE),101) sentdate, ";
//strQuery = strQuery + "count(1) as SmsCount from SynapseEngine.dbo.MBX_MST_SENDSMSHISTORY0 , HostingAdmin.dbo.MBX_MST_SENDERID ";
//strQuery = strQuery + " where smsh_int_moduleid in (0,1,2) and SMSh_INT_SENTSTATUS in (0,1) ";
//strQuery = strQuery + "and CONVERT(VARCHAR,(SMSH_DTM_SENTDATE),101) >= CONVERT(VARCHAR,(GETDATE()-4) ,101) and SID_Int_ID = smsh_int_senderid ";
//strQuery = strQuery + "group by sid_var_code,CONVERT(VARCHAR,(SMSH_DTM_SENTDATE),101) order by SmsCount desc";
SqlCommand cmdsql = new SqlCommand(strQuery, consql);
SqlDataAdapter adaptsql = new SqlDataAdapter(cmdsql);
adaptsql.Fill(dsSMSCCount);

Chart1.Series.Add(new System.Web.UI.DataVisualization.Charting.Series("Default"));
Chart1.Width = 300;
Chart1.Height = 300;
Chart1.Titles.Add("SMSCampaign Count");
Chart1.BackColor = System.Drawing.Color.FromArgb(211, 223, 240);
// Chart1.BorderlineDashStyle = System.Web.UI.DataVisualization.Charting.ChartDashStyle.Dot;
Chart1.BackGradientStyle = System.Web.UI.DataVisualization.Charting.GradientStyle.TopBottom;
Chart1.BorderlineWidth = 1;
Chart1.Palette = System.Web.UI.DataVisualization.Charting.ChartColorPalette.BrightPastel;
Chart1.BorderlineColor = System.Drawing.Color.FromArgb(26, 59, 105);
Chart1.RenderType = System.Web.UI.DataVisualization.Charting.RenderType.BinaryStreaming;
Chart1.BorderSkin.SkinStyle = System.Web.UI.DataVisualization.Charting.BorderSkinStyle.Emboss;
Chart1.AntiAliasing = System.Web.UI.DataVisualization.Charting.AntiAliasingStyles.All;
Chart1.TextAntiAliasingQuality = System.Web.UI.DataVisualization.Charting.TextAntiAliasingQuality.Normal;
Chart1.Series.Clear();

Chart1.Series.Add(new System.Web.UI.DataVisualization.Charting.Series("testing"));

// Chart1.Series["Default"].Points.DataBind(testdata, "CMP_VAR_NAME", "CMP_INT_CHARCOUNT", string.Empty);

Chart1.DataSource = dsSMSCCount.Tables[0];

Chart1.Series[0].XValueMember = "CMP_VAR_NAME";
Chart1.Series[0].YValueMembers = "CMP_INT_CHARCOUNT";
//Chart1.Series["Default"].Points[1].Color = System.Drawing.Color.PaleGreen;
//Chart1.Series["Default"].Points[2].Color = System.Drawing.Color.LawnGreen;
Chart1.Series[0].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Column;
//Chart1.ChartAreas.Add(new System.Web.UI.DataVisualization.Charting.ChartArea("ChartArea1"));
System.Web.UI.DataVisualization.Charting.ChartArea chartarea = new System.Web.UI.DataVisualization.Charting.ChartArea("Chartarea");
chartarea.AxisX.MajorGrid.Enabled = false;
chartarea.AxisY.MajorGrid.Enabled = false;
Chart1.ChartAreas.Add(chartarea);
Chart1.ChartAreas["Chartarea"].Area3DStyle.Enable3D = true;
Chart1.ChartAreas[0].Area3DStyle.Inclination = -20;
Chart1.DataBind();
Chart1.ChartAreas[0].AxisX.Interval = 1;
Chart1.Series[0].IsValueShownAsLabel = true;
Random random = new Random();
foreach (var item in Chart1.Series[0].Points)
{
System.Drawing.Color c = System.Drawing.Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
item.Color = c;
item.IsVisibleInLegend = true;
}


Chart1.SaveImage("D:\\users\\save.png");
string name = Chart1.GetHtmlImageMap("D:\\users\\save.png");



System.IO.MemoryStream imageStream = new System.IO.MemoryStream();
Chart1.SaveImage(imageStream, System.Web.UI.DataVisualization.Charting.ChartImageFormat.Jpeg);




String table = String.Format("", Convert.ToBase64String(imageStream.ToArray()));

DataGrid dgrd = new DataGrid();
dgrd.DataSource = dsSMSCCount;
dgrd.DataBind();
dgrd.RenderControl(htmlwrter);

string maintable = table + htmlwrter.InnerWriter;

// mailFrom mailTo mailCC mailSubject mailSignature

SmtpClient client = new SmtpClient();
MailMessage msg = new MailMessage();
try
{
MailAddress Fromaddress = new MailAddress("phani.bhushan@vectramind.in");
client.Host = "";// ;
client.Port = 25;
msg.From = Fromaddress;
msg.To.Add();
msg.CC.Add();
msg.Subject = "Test Chart from Mail";
msg.IsBodyHtml = true;
msg.Body = maintable;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential();


client.Send(msg);

}
catch (Exception exp)
{

}
finally
{
client = null;
msg = null;
}



}
[\CODE]

Now with run time C# Code in Microsoft Visual Studio

Chart Image and Memory stream

After Converting the image in to bytes assign to Image Control.The below figure will show that...

store bytes in  image  Control

Please Verify Your Email in Outlook.......

Outlookimage

Is it Nice.........

Important Points to Remember :



Please set the Axis Intervals for the chart.

Please set the Axis Labels to the Chart it will easily Understandable for the End User.

if you want to set dynamical colors for your Points in the chart choose Random Colors class by iterating Chart Points.

Choose Chart Type(i.e 3D or Plain) by setting true or False.

Chart Saved as Image in Physical Location



Chart Physical Images


Attachments

Article by srirama
A Good advice from parent to a Child , Master to a Student , Scholar to an Ignorant is like a doctor prescribed pill it is bitter to take but when they take it will do all good for them --- Bhushan

Follow srirama or read 73 articles authored by srirama

Comments

Guest Author: Sello08 Jan 2014

Hi, this was the exact thing, I was trying to do. thanks for such an elaboration material. but what is that in double quotes in string.format
String table = String.Format("", Convert.ToBase64String(imageStream.ToArray())); It doesn't show anything here.

Author: srirama08 Jan 2014 Member Level: Gold   Points : 2


The Code which was missing in the above article is given below.


String table = String.Format("lessthansymbol(<)img src="data:imageBmp;base64,{0}\"greaterthansymbol(>)", Convert.ToBase64String(imageStream.ToArray()));
remove less than symbol and greater than symbol and brackets keep simply < >



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: