Monday, May 20, 2019

How to display the Pie Chart using C# Asp.Net

Here Parshotam has explained with an example and attached sample code, how to programmatically populate ASP.Net Pie Chart from SQL Server Database Table.


In this example, the Pie is chart is dynamically populated based on DropDownList selection


You will need to modify the Web.Config file as following shown in YELLOW in order to use the ASP.Net 4.0 Chart control.

<appSettings>
  <add key="ChartImageHandler" value="storage=file;timeout=20;" />
</appSettings>
<system.web>
  <compilation debug="true" targetFramework="4.0">
   <assemblies>
     <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   </assemblies>
  </compilation>
  <httpHandlers>
       <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
  </httpHandlers>
  <pages>
   <controls>
                <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   </controls>
  </pages>
</system.web>
<system.webServer>
 <handlers>
  <remove name="ChartImageHandler"/>
            <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
 </handlers>
</system.webServer>


User Interface Code as below : 


<asp:DropDownList ID="ddlCountries" runat="server" OnSelectedIndexChanged="ddlCountries_SelectedIndexChanged"
    AutoPostBack = "true">
</asp:DropDownList><hr />
<asp:Chart ID="Chart1" runat="server" Height="300px" Width="400px" Visible = "false">
    <Titles>
        <asp:Title ShadowOffset="3" Name="Items" />
    </Titles>
    <Legends>
        <asp:Legend Alignment="Center" Docking="Bottom" IsTextAutoFit="False" Name="Default" LegendStyle="Row" />
    </Legends>
    <Series>
        <asp:Series Name="Default" />
    </Series>
    <ChartAreas>
        <asp:ChartArea Name="ChartArea1" BorderWidth="0" />
    </ChartAreas>
</asp:Chart>

Code Behind :
You will need to import the following Namespaces.

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string query = "select distinct shipcountry from orders";
        DataTable dt = GetData(query);
        ddlCountries.DataSource = dt;
        ddlCountries.DataTextField = "shipcountry";
        ddlCountries.DataValueField = "shipcountry";
        ddlCountries.DataBind();
        ddlCountries.Items.Insert(0, new ListItem("Select"""));
    }
}
   
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
    Chart1.Visible = ddlCountries.SelectedValue != "";
    string query = string.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", ddlCountries.SelectedValue);
    DataTable dt = GetData(query);
    string[] x = new string[dt.Rows.Count];
    int[] y = new int[dt.Rows.Count];
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        x[i] = dt.Rows[i][0].ToString();
        y[i] = Convert.ToInt32(dt.Rows[i][1]);
    }
    Chart1.Series[0].Points.DataBindXY(x, y);
    Chart1.Series[0].ChartType = SeriesChartType.Pie;
    Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
    Chart1.Legends[0].Enabled = true;
}
 
private static DataTable GetData(string query)
{
    DataTable dt = new DataTable();
    SqlCommand cmd = new SqlCommand(query);
    String constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    sda.SelectCommand = cmd;
    sda.Fill(dt);
    return dt;
}

Output as below in Pie Chart


Connect to ERP system with .Net Application

Hi everyone !!!!!

here is the example to connect the SAP ERP syetm to .Net Application.

for connection to SAP ERP to .NET Application through RFC (Remote Function), we need some dll files that can be easily available in internet or microsoft

SAPLogonCtrl.dll
SAPFunctionsOCX.dll

Step 1 : Download these 2 files

Step 2 : Open visual studio --> Start New Project (using C# or VB)

Step 3: In the solution explorer 'Right Click', add reference to these dll into you website

Step 4 : After add reference, need to write the code for connect to ERP SAP

Step 5 : Write below code to connect to ERP using namespace


using SAPLogonCtrl;
using SAPFunctionsOCX;


protected Boolean SAPConnection()
    {  

        SAPLogonCtrl.SAPLogonControlClass Login = new SAPLogonCtrl.SAPLogonControlClass();
        SAPLogonCtrl.Connection SapConn;

        Login.ApplicationServer = "ERP Server Name or IP";
        Login.SystemNumber = SystemNumber;
        Login.Client = "ClientNumber";
        Login.Language = "SAP Language";
        Login.User = "SAP User ID";
        Login.Password = "SAP Password";
        SapConn = (SAPLogonCtrl.Connection)Login.NewConnection();
        if (SapConn.Logon(0, true))
        {
            Response.Write("Connected to SAP");
            return true;
        }
        else
        {
            Response.Write("Not able to connect SAP");
            return false;
        }
    }

Friday, September 8, 2017

Get record from Web Service and Display in XML format

in the previous aticle show how to create Web Service.

Here is how to show the record from web service to client browser in XML with header node and detail node

1. Open Visual Studio
2. Create new empty web site 
3. Add new item , add aspx page into web site 
4. Add service reference (add the above web service url ) and given name to web refrence
5. Drag and Drop a testbox into aspx page
5. Drag and Drop a Button into aspx page

6. in the code behind, need to add function for header node and detail node as below


//-------------Detailed Node -----------------//
private void createDNode(string empid, string name, string deptid, string deptname, string email,
                                                                                                                     XmlTextWriter writer)
    {
        writer.WriteStartElement("Detail");
        writer.WriteStartElement("empid");
        writer.WriteString(empid);
        writer.WriteEndElement();

        writer.WriteStartElement("ename");
        writer.WriteString(name);
        writer.WriteEndElement();

        writer.WriteStartElement("deptid");
        writer.WriteString(deptid);
        writer.WriteEndElement();

        writer.WriteStartElement("deptname");
        writer.WriteString(deptname);
        writer.WriteEndElement();

        writer.WriteStartElement("email");
        writer.WriteString(email);
        writer.WriteEndElement();
    }

//---------------------Header Node ----------------//

 private void createHNode(string pID, string pName, XmlTextWriter writer)
    {
        writer.WriteStartElement("Header");
        writer.WriteStartElement("Name");
        writer.WriteString(pID);
        writer.WriteEndElement();
        writer.WriteStartElement("Dept");
        writer.WriteString(pName);
        writer.WriteEndElement();

    }

6 on button click event, add the below code

       DataSet dsResult = new DataSet();
       XmlElement exelement = webService .GetEmployeesDetails(textbox.Text);
      
       XmlNodeReader nodeReader = new XmlNodeReader(exelement);
       dsResult.ReadXml(nodeReader, XmlReadMode.Auto);

      Xml xml = new Xml();
            XmlTextWriter writer = new XmlTextWriter( textbox.Text + ".xml", System.Text.Encoding.UTF8);
            writer.WriteStartDocument(true);
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 2;
            writer.WriteStartElement("Table");
            createHNode(From, Dest, writer);
            for (int i = 0; i < dsResult.Tables[0].Rows.Count; i++)
            {
                createDNode(dsResult.Tables[0].Rows[i][0].ToString(), dsResult.Tables[0].Rows[i][0].ToString(), dsResult.Tables[0].Rows[i][0].ToString(), dsResult.Tables[0].Rows[i][0].ToString(), dsResult.Tables[0].Rows[i][0].ToString(), writer);

            }
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();


            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/xml";
            Response.WriteFile(Server.MapPath("~/New folder/"+ textbox.Text +".xml"));
            Response.Flush();
            Response.End();









Create Web Service and Consume in Web Site

When web page are re-direct in a browser for the end user, Web Services are invoked by other applications. 
They are pieces of business logic that are hosted somewhere on the internet and can be accessed by other applications.

Web Services are cross-platform, a service written in one language can be invoked by an application in some other language

Here are steps how to create web service for get employee records from data base

1. Open Visual Studio 
2. Select New Project as below
3. Select Web Service using web from installed template
4. Write the below code in .cs page 

// Get record into XML format

    [WebMethod]
    public XmlElement EmployeeDetailXml(string EmployeeID)
    {
        sqlCon = new 
               SqlConnection(ConfigurationManager.ConnectionStrings["login"].ConnectionString.ToString());
        sqlCmd = 
                    new SqlCommand("Select * from EmployeeTable where empid=''+EmployeeID+", sqlCon);
        sqlCon.Open();
        sqlDa = new SqlDataAdapter(sqlCmd);
        Ds = new DataSet();
        sqlDa.Fill(Ds);
        sqlCon.Close();
        XmlDataDocument xmlData = new XmlDataDocument(Ds);
        XmlElement xmlElement = xmlData.DocumentElement;
        return xmlElement;

    }
5. After write code into .cs page, build the project.
6. after Build, invoke it for test
       
      


7. It will show you the record from the employee table for the given employee record.




Consume the above web service into web site

1. Open Visual Studio
2. Create new empty web site 
3. Add new item , add aspx page into web site 
4. Add service reference (add the above web service url ) and given name to web refrence
5. Drag and Drop a testbox into aspx page
5. Drag and Drop a Button into aspx page
6 Drag and drop a gridview into aspx th display the web service result into gridview
7. add name space for web service as added into step 4
8 on button click event, add the below code

       WebServiceProject.WebService1 webService = new WebServiceProject.WebService1();
    
        DataSet dsResult = new DataSet();
        XmlElement exelement = webService .GetEmployeesDetails(textbox.Text);
      
            XmlNodeReader nodeReader = new XmlNodeReader(exelement);
            dsResult.ReadXml(nodeReader, XmlReadMode.Auto);

            GVEmployeeDetails.DataSource = dsResult;

            GVEmployeeDetails.DataBind();

9. run the website, and key in userid in textbox
10. on button click, it will show the employee record into gridview.

i hope it will help you to create simple web service and use this into web site







Thursday, June 22, 2017

how to get outlook attachment in folder with sender name

here is the example to save outlook mail attachment into our system folder or server folder


you can uplaod the file with the below paradigm, the below programme is to upload the jpg file formate.


Step 1 : Open visual studio --> Start New Project (using C# or VB)

Step 2: In the solution explorer 'Right Click', add new item  --> add web page into your website

Step 3: search Microsoft.Exchange.WebServices from Manage NuGate

Step 3 : install Microsoft.Exchange.WebServices library to your project

Step 4 : after install the Microsoft.Exchange.WebServices Library , write your code as below

Step 5 : Need to connect to your exchange server

           Write below method to your website to connect to the exchange server and outlook email
           

           using Microsoft.Exchange.WebServices.Data;
            using System.IO
         
            public void ConnectToExchangeServer()
                {
                  try
                      {
                        exchange = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                        exchange.Credentials = new WebCredentials("Your Account Name on Exchange                                                                                     Server", "Password", "Domain");
                        exchange.AutodiscoverUrl("Outlook Email Address");

         
                       Response.Write( "Connected to Exchange Server : " + exchange.Url.Host );

                      }
                catch (System.Exception ex)
                    {
                      Response.Write( "Error Connecting to Exchange Server!!" + ex.Message);
        }

    }

Step 5 : write the code behind on button click event  or page load as per requirement

            the below event will read your outlook email and get access to every function
            using the namespace 

            using Microsoft.Exchange.WebServices.Data;
            using System.IO

           ConnectToExchangeServer();
          TimeSpan ts = new TimeSpan(0, -1, 0, 0);
          DateTime date = DateTime.Now.Add(ts); // It will read only the current date email 
          SearchFilter.IsGreaterThanOrEqualTo filter = new     
                                     SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);

        if (exchange != null)
        {
            FindItemsResults<Item> findResults = exchange.FindItems(WellKnownFolderName.Inbox,
                                                                                                                     filter, new ItemView(50));

            foreach (Item item in findResults)
            {

                EmailMessage message = EmailMessage.Bind(exchange, item.Id);

                if (message.HasAttachments) 
                {
                    foreach (Microsoft.Exchange.WebServices.Data.Attachment attach in
                                                                                                        message.Attachments)
                    {
                        if (attach is FileAttachment)
                        {
                            string file = message.Sender.Name.ToString();
                            string FileFolder = @"C:\\" + file + "\\"; // save your attachment here
                            if (!System.IO.Directory.Exists(FileFolder)) // it will create sender name directory
                            {
                                System.IO.Directory.CreateDirectory(FileFolder);
                            }

                            FileAttachment fileAttachment = attach as FileAttachment;
                            fileAttachment.Load();

                            FileStream theStream = new FileStream(FileFolder + fileAttachment.Name,
                                                                                   FileMode.OpenOrCreate, FileAccess.ReadWrite);
                            fileAttachment.Load(theStream);
                            theStream.Close();
                            theStream.Dispose();
                        }                            
                            
                    }
                }
            }
            if (findResults.Items.Count <= 0)
            {
                lblMsg.Text = "No Messages found!!";

            }
        } 



thank you for viewing this.

this will allow you to create directory in disk folder and save the sender attachments in to disk folder.