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.