Showing posts with label Windows Applications. Show all posts

XMLWriter

XMLWriter class is used to create and xml file.
Below example is used create xml file in the bin location
using System.Xml;

class Program
{
    class Employee
    {
        int _id;
        string _firstName;
        string _lastName;
        int _salary;

        public Employee(int id, string firstName, string lastName, int salary)
        {
            this._id = id;
            this._firstName = firstName;
            this._lastName = lastName;
            this._salary = salary;
        }

        public int Id { get { return _id; } }
        public string FirstName { get { return _firstName; } }
        public string LastName { get { return _lastName; } }
        public int Salary { get { return _salary; } }
    }

    static void Main()
    {
        Employee[] employees = new Employee[4];
        employees[0] = new Employee(1, "David", "Smith", 10000);
        employees[1] = new Employee(3, "Mark", "Drinkwater", 30000);
        employees[2] = new Employee(4, "Norah", "Miller", 20000);
        employees[3] = new Employee(12, "Cecil", "Walker", 120000);

        using (XmlWriter writer = XmlWriter.Create("employees.xml"))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("Employees");

            foreach (Employee employee in employees)
            {
                writer.WriteStartElement("Employee");

                writer.WriteElementString("ID", employee.Id.ToString());
                writer.WriteElementString("FirstName", employee.FirstName);
                writer.WriteElementString("LastName", employee.LastName);
                writer.WriteElementString("Salary", employee.Salary.ToString());

                writer.WriteEndElement();
            }

            writer.WriteEndElement();
            writer.WriteEndDocument();
           
        }
    }
}
XML data
<Employees>
    <Employee>
      <ID>1</ID>
      <FirstName>David</FirstName>
      <LastName>Smith</LastName>
      <Salary>10000</Salary>
    </Employee>
    <Employee>
      <ID>3</ID>
      <FirstName>Mark</FirstName>
      <LastName>Drinkwater</LastName>
      <Salary>30000</Salary>
    </Employee>
    <Employee>
      <ID>4</ID>
      <FirstName>Norah</FirstName>
      <LastName>Miller</LastName>
      <Salary>20000</Salary>
    </Employee>
    <Employee>
      <ID>12</ID>
      <FirstName>Cecil</FirstName>
      <LastName>Walker</LastName>
      <Salary>120000</Salary>
    </Employee>

</Employees>

Thursday, 10 March 2016
Posted by Sudhir Chekuri

XMLReader

XMLReader class is used to read the xml data
Below example is used to read data from xml file
ReadText.xml
<?xml version="1.0" encoding="utf-8" ?>
<Header>
    <article name="backgroundworker">
     Example text.
    </article>
    <article name="threadpool">
     More text.
    </article>
    <article></article>
    <article>Final text.</article>
</Header>
Output
Start <Header> element.
Start <article> element.
  Has attribute name: backgroundworker
  Text node: Example text.
Start <article> element.
  Has attribute name: threadpool
  Text node: More text.
Start <article> element.
  Text node:
Start <article> element.
  Text node: Final text.
Code
using System;
using System.Xml;

class Program
{
    static void Main()
    {
        // Create an XML reader for this file.
        using (XmlReader reader = XmlReader.Create("ReadText.xml"))
        {
            while (reader.Read())
            {
                // Only detect start elements.
                if (reader.IsStartElement())
                {
                    // Get element name and switch on it.
                    switch (reader.Name)
                    {
                        case "Header":
                            // Detect this element.
                            Console.WriteLine("Start <Header> element.");
                            break;
                        case "article":
                            // Detect this article element.
                            Console.WriteLine("Start <article> element.");
                            // Search for the attribute name on this current node.
                            string attribute = reader["name"];
                            if (attribute != null)
                            {
                                Console.WriteLine("  Has attribute name: " + attribute);
                            }
                            // Next read will contain text.
                            if (reader.Read())
                            {
                                Console.WriteLine("  Text node: " + reader.Value.Trim());
                            }
                            break;
                    }
                }
            }
        }
        Console.ReadKey();
    }

}

Posted by Sudhir Chekuri

XML Basics

XML stands for EXtensible Markup Language.
XML was designed to store and transport data.
XML was designed to be both human- and machine-readable.
.xml is the extension for xml documents.

Creating XML document

The following data can be written in xml format as shown below.
Data:
Note
To: Tove
From: Jani
Happy weekend
XML Format:
<?xml version="1.0" encoding="UTF-8"?>
<note>
  
<to>Tove</to>
  
<from>Jani</from>
  
<heading>Reminder</heading>
  
<body>Happy weekendbody>
</note>
XML Example to store books information

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>

  <book category=
"cooking">
    <title lang=
"en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>
2005</year>
    <price>
30.00</price>
  </book>

  <book category=
"children">
    <title lang=
"en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>
2005</year>
    <price>
29.99</price>
  </book>

  <book category=
"web">
    <title lang=
"en">XQuery Kick Start</title>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
    <year>
2003</year>
    <price>
49.99</price>
  </book>

  <book category=
"web" cover="paperback">
    <title lang=
"en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>
2003</year>
    <price>
39.95</price>
  </book>

</bookstore>


Posted by Sudhir Chekuri

Install windows services

Go to "Start" - "All Programs" -"Microsoft Visual Studio 2012" - "Visual Studio Tools" then click "Developer Command Prompt for VS2012".

Go to folder location in which exe is present in command prompt and use the below command to install the windows service application (SampleWindowsService).

InstallUtil.exe “SampleWindowsService.exe”

Successful message will be displayed in command prompt after successful installation.

Go to services and see your windows services which will be names as Service1.

Now this service will be running continuously and will write text in LogFile.txt file which is created in the same folder from where your exe is executed. For every 30 seconds task will be executed and will write new text in that LogFile.

Start and stop your service from services. It will log the start and stop enteries in LogFile as shown below.

3/10/2016 1:21:25 PM: Test window service started

3/10/2016 1:21:55 PM: Job is running

3/10/2016 1:22:25 PM: Job is running

3/10/2016 1:22:55 PM: Job is running

3/10/2016 1:23:25 PM: Job is running

3/10/2016 1:23:55 PM: Job is running

3/10/2016 1:24:25 PM: Job is running

3/10/2016 1:24:41 PM: Test window service stopped


Posted by Sudhir Chekuri

Creating Windows Services

File – New Project – Select language as C# and windows service as application type.
Enter name for the project. Example: SampleWindowsService
Click on ok.
Right-click the "Service1.cs" file in Solution Explorer and rename it "to" Scheduler or any other name that you want to give it. Then click “click here to switch to code view”.
In the code view, you can see two methods called OnStart() and OnStop(). The OnStart() triggers when the Windows Service starts and the OnStop() triggers when the service stops.
Create a new class file(Library.cs) in the project with a method to log messages using below code.
Code in Library.cs file

using System;
using System.IO;

namespace SampleWindowsService
{
    public static class Library
    {
        public static void WriteErrorLog(string Message)
        {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory+"LogFile.txt",true);
                sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
                sw.Flush();
                sw.Close();
            }
            catch { }
        }
    }
}

Scheduler.cs
using System;
using System.ServiceProcess;
using System.Text;
using System.Timers;

namespace SampleWindowsService
{
    public partial class Scheduler : ServiceBase
    {
        private Timer timer1 = null;
        public Scheduler()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer1 = new Timer();
            this.timer1.Interval = 30000;//every 30 secs
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled = true;
            Library.WriteErrorLog("Test window service started");
       
        }

        private void timer1_Tick(object sender, ElapsedEventArgs e)
        {
//Write code her to do some scheduled task
            Library.WriteErrorLog("Job is running");

        }


        protected override void OnStop()
        {
            timer1.Enabled = false;
            Library.WriteErrorLog("Test window service stopped");
        }
    }
}

Go to design view of Scheduler.cs – right click on the design window and select Add Installer.
Now ProjectInstaller.cs file will be added to your project in solution explorer.
Open ProjectInstaller design window – Right click on serviceInstaller1 – Select properties
Change StartType property to automatic so that service will be automatically started.
Open ProjectInstaller design window – Right click on serviceProcessInstaller1 – Select properties
Change Account property to LocalSystem.
Build the project and see the exe file created in project location.

Posted by Sudhir Chekuri

Followers

Total Pageviews

Powered by Blogger.

- Copyright © 2013 DevStudent - Metrominimalist - Powered by Blogger - Designed by Johanes Djogan -