Ex2.

Windows Application

Form1.cs, Form1.Designer.cs, Program.cs

Form1.Designer.cs

namespace ex2
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name=”disposing”>true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code

/// <summary>
/// Required method for Designer support – do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.loadButton = new System.Windows.Forms.Button();
searchWord = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.filePath = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.searchButton = new System.Windows.Forms.Button();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
statusBox = new System.Windows.Forms.ListBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
//
// loadButton
//
this.loadButton.Location = new System.Drawing.Point(12, 56);
this.loadButton.Name = “loadButton”;
this.loadButton.Size = new System.Drawing.Size(75, 23);
this.loadButton.TabIndex = 1;
this.loadButton.Text = “Load”;
this.loadButton.UseVisualStyleBackColor = true;
this.loadButton.Click += new System.EventHandler(this.loadButton_Click);
//
// searchWord
//
searchWord.Location = new System.Drawing.Point(10, 26);
searchWord.Name = “searchWord”;
searchWord.Size = new System.Drawing.Size(130, 20);
searchWord.TabIndex = 2;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.filePath);
this.groupBox1.Controls.Add(this.loadButton);
this.groupBox1.Location = new System.Drawing.Point(15, 16);
this.groupBox1.Name = “groupBox1″;
this.groupBox1.Size = new System.Drawing.Size(261, 90);
this.groupBox1.TabIndex = 4;
this.groupBox1.TabStop = false;
this.groupBox1.Text = “File”;
//
// filePath
//
this.filePath.Location = new System.Drawing.Point(15, 25);
this.filePath.Name = “filePath”;
this.filePath.Size = new System.Drawing.Size(226, 20);
this.filePath.TabIndex = 2;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.searchButton);
this.groupBox2.Controls.Add(searchWord);
this.groupBox2.Location = new System.Drawing.Point(17, 124);
this.groupBox2.Name = “groupBox2″;
this.groupBox2.Size = new System.Drawing.Size(258, 61);
this.groupBox2.TabIndex = 5;
this.groupBox2.TabStop = false;
this.groupBox2.Text = “Word”;
//
// searchButton
//
this.searchButton.Location = new System.Drawing.Point(164, 25);
this.searchButton.Name = “searchButton”;
this.searchButton.Size = new System.Drawing.Size(75, 23);
this.searchButton.TabIndex = 3;
this.searchButton.Text = “Search”;
this.searchButton.UseVisualStyleBackColor = true;
this.searchButton.Click += new System.EventHandler(this.searchButton_Click);
//
// groupBox3
//
this.groupBox3.Controls.Add(statusBox);
this.groupBox3.Location = new System.Drawing.Point(18, 205);
this.groupBox3.Name = “groupBox3″;
this.groupBox3.Size = new System.Drawing.Size(256, 164);
this.groupBox3.TabIndex = 6;
this.groupBox3.TabStop = false;
this.groupBox3.Text = “Status”;
//
// openFileDialog1
//
this.openFileDialog1.FileName = “openFileDialog1″;
//
// statusBox
//
statusBox.FormattingEnabled = true;
statusBox.Location = new System.Drawing.Point(12, 24);
statusBox.Name = “statusBox”;
statusBox.Size = new System.Drawing.Size(226, 121);
statusBox.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 381);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Name = “Form1″;
this.Text = “Form1″;
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.ResumeLayout(false);

}

#endregion

private System.Windows.Forms.Button loadButton;
static System.Windows.Forms.TextBox searchWord;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox filePath;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Button searchButton;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
static System.Windows.Forms.ListBox statusBox;
}
}

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace ex2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

static List<String> searchResults = new List<String>();
public class SearchTask
{
public Thread s_thread;
public string f_name;
public SearchTask(string file)
{
f_name   = file;
s_thread = new Thread(new ThreadStart(SearchWord));
}

private void SearchWord()
{
FileStream fs = new FileStream(f_name,FileMode.Open,FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string s  = sr.ReadToEnd();
string[] fileWords = s.Split(‘ ‘);
searchResults.Add(” ” + fileWords);
foreach(string word in fileWords)
{

if (word == searchWord.Text)
{
//searchResults.Add(“”);
searchResults.Add(“Cuvant gasit”);
}
else
searchResults.Add(“Cuvant nu gasit”);

}
}
}

private void loadButton_Click(object sender, EventArgs e)
{
System.Windows.Forms.DialogResult OPEN = openFileDialog1.ShowDialog();
if (OPEN == DialogResult.OK)
{
String path = openFileDialog1.FileName; //The Path to the file//
filePath.Text = path;
}
}

private void searchButton_Click(object sender, EventArgs e)
{

string word = searchWord.Text;
string path = filePath.Text;
//MessageBox.Show(path);
//string dest = path.Split(“.”, 1);
string dest = @”C:\Documents and Settings\admin\Desktop\SD\”;

int index = 0;
byte[] segment = new byte[30];

using (Stream source = File.OpenRead(path))
{
while (source.Position < source.Length)
{
index++;
// Create a new sub File, and read into it
string newFileName = Path.Combine(dest, Path.GetFileNameWithoutExtension(path));
newFileName += index.ToString() + Path.GetExtension(path);
using (Stream destination = File.OpenWrite(newFileName))
{
while (destination.Position < segment.Length)
{
int bytes = source.Read(segment, 0, segment.Length);
destination.Write(segment, 0, bytes);

// Are we at the end of the file?
if (bytes < segment.Length)
{
break;
}
}
}
}
}
//MessageBox.Show(index.ToString());
List<SearchTask> tasks = new List<SearchTask>();
for (int i = 1; i <= index; i++)
{
string pathToFile = Path.GetFileNameWithoutExtension(filePath.Text) + i + Path.GetExtension(filePath.Text);
SearchTask task = new SearchTask(pathToFile);
tasks.Add(task);
}
foreach(SearchTask t in tasks)
{
t.s_thread.Start();
for (int i = 0; i < searchResults.Count(); i++)
statusBox.Items.Add(searchResults[i]);
}
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace ex2
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

Description

Sa se creeze o applicatie desktop care sa permite incarcarea unui fisier text , specificarea unui cuvant , si care sa caute acel cuvant in fisierul text, prin segmentarea fisierului in mai multe bucati si cautand in paralel (cu thrad-uri pt fiecare segment) acel cuvant. De asemenea sa se afiseze info de debug in form de genul : de cate ori s-a gasit cuvantul , la ce pozitii, timp de inceput cautare, timp de sfarsit cautare pt fiecare thread in parte.

Clasa Socket

Clasa Socket din namespace-ul System.Net.Sockets reprezinta o implementare a interfetei soclurilor Berkeley si ofera metode sincrone si asincrone de transfer a datelor.

Operatiile pe un socket pot fi asemanate cu operatiile de IO pe un fisier, socket-ul fiind asociat handle-ului pe fisier.

Socket-urile pot fi folosite pentru a face două aplicaţii să comunice între ele. Aplicaţiile sunt, de obicei, pe calculatoare diferite, însă pot fi şi pe acelaşi calculator.

Pentru ca două aplicaţii să comunice între ele cu ajutorul socket-urilor, indiferent dacă sunt pe acelaşi calculator sau pe calculatoare diferite, de obicei, o aplicaţie este un server care ascultă continuu cererile care sosesc şi cealaltă aplicaţie acţionează ca un client si face conexiuni către aplicaţia server. Aceasta din urmă poate să accepte sau să respingă conexiunea. Dacă aplicaţia server acceptă conexiunea un dialog se poate stabili între client şi server. După ce clientul termina ceea ce avea de comunicat el poate să închidă conexiunea cu serverul. Serverele au un număr finit de conexiuni care pot fi deschise.

Atât timp cât un client are o conexiune activă acesta poate trimite date serverului sau poate primi date de la acesta. De fiecare dată când partener de comunicatie (client sau server) trimite date celuilalt partener se presupune că aceasta din urmă recepţionează datele respective.

Dar cum realizează cealaltă parte că datele au sosit? Există două soluţii la această problemă:

- fie aplicaţia verifică dacă nu au sosit date la intervale regulate

- fie are nevoie de un mecanism prin care aplicaţia să fie informată că au sosit date, putând astfel să le proceseze.

Din moment ce Windows-ul este un sistem de operare care se bazează pe evenimente cea mai bună opţiune este cea care se bazează pe notificare.
Aşa cum am spus anterior, pentru ca cele două aplicaţii să comunice între ele este necesară realizarea, mai întâi, a unei conexiuni. Pentru ca două aplicaţii să realizeze o conexiune în primă fază
este necesar ca să se realizeze identificarea acestora (sau a calculatoarelor pe care rulează). Aşa cum se ştie, calculatoarele sunt identificate în reţea printr-un IP.

Exemple:

Simple Threaded TCP Server

Network Information

Console Application


using System;
using System.Collections.Generic;
using System.Text;
using System;
using System.Net.NetworkInformation;
namespace pr16
{
class Program
{
static void Main(string[] args)
{
IPGlobalProperties props = IPGlobalProperties.GetIPGlobalProperties();
NetworkInterface[] interfete = NetworkInterface.GetAllNetworkInterfaces();
Console.WriteLine("Interfete retea pentru {0}", props.HostName);
foreach (NetworkInterface interfata in interfete)
{
IPInterfaceProperties ipprop = interfata.GetIPProperties();
Console.WriteLine("{0}:",interfata.Name);
Console.WriteLine(" Descriere: {0}", interfata.Description);
Console.WriteLine(" Interfata: {0}", interfata.NetworkInterfaceType);
if (interfata.NetworkInterfaceType == NetworkInterfaceType.Loopback)
continue;
Console.WriteLine("Viteza: {0} bps", interfata.Speed);
Console.WriteLine("Stare: {0}", interfata.OperationalStatus);
Console.WriteLine("Adresa fizica (MAC):{0}", interfata.GetPhysicalAddress().ToString());
Console.WriteLine("Sufix DNS: {0}", ipprop.DnsSuffix);
Console.WriteLine("DNS activat : {0}", ipprop.IsDnsEnabled);
UnicastIPAddressInformationCollection adreseIP = ipprop.UnicastAddresses;
if (adreseIP.Count > 0)
{
foreach (UnicastIPAddressInformation uni in adreseIP)
{
DateTime when;
Console.WriteLine(" Adresa IP unicast: {0}", uni.Address);
Console.WriteLine(" Mask: {0}", uni.IPv4Mask);
Console.WriteLine(" Timp ramas 'DHCP lease time': {0}",(DateTime.UtcNow + TimeSpan.FromSeconds(uni.DhcpLeaseLifetime)).ToString() );
}
}
}
Console.Read();
}
}
}

2.3

Windows Application

Masina.cs; CalculTaxaImpl.cs; Form1.cs;

Form1


private System.Windows.Forms.Button buttonExit;
private System.Windows.Forms.Button buttonAdd;
private System.Windows.Forms.Button buttonPrint;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textBoxNume;
private System.Windows.Forms.TextBox textBoxCapacitate;
private System.Windows.Forms.ComboBox comboBoxTipEuro;
private System.Windows.Forms.ListBox listBoxPrint;

*code*

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace TaxaInmatriculare
{
public partial class Form1 : Form
{
// lista generica in care se pastreaza obiectele introduse de utilizator
List listaMasini = new List();
Masina tmp = null;
public Form1()
{
InitializeComponent();
buttonAdd.Click += buttonAdd_Confirmation;
}
private void buttonExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void buttonAdd_Click(object sender, EventArgs e)
{
string nume = textBoxNume.Text;
int capacitate = 0;
try
{
capacitate = int.Parse(textBoxCapacitate.Text);
Masina m = new Masina(nume, capacitate);
string opt = comboBoxTipEuro.SelectedItem.ToString().ToLower();
switch (opt) {
case "euro1":
m.Ct = CalculTaxaImpl.Euro1;
break;
case "euro2":
m.Ct = CalculTaxaImpl.Euro2;
break;
case "euro3":
m.Ct = CalculTaxaImpl.Euro3;
break;
case "euro4":
m.Ct = CalculTaxaImpl.Euro4;
break;
case "euro5":
m.Ct = CalculTaxaImpl.Euro5;
break;
}
m.Taxa = m.Ct(m.Capacitate);
listaMasini.Add(m);
tmp = m;
}
catch {
MessageBox.Show("Invalid Data!");
}
}
private void buttonAdd_Confirmation(object sender, EventArgs e)
{
if (tmp != null)
{
MessageBox.Show(tmp.ToString() + " was added.");
}
}
private void buttonPrint_Click(object sender, EventArgs e)
{
foreach (Masina m in listaMasini)
{
listBoxPrint.Items.Add(m.ToString());
}
}
private void Form1_Load(object sender, EventArgs e)
{

}
}
}

Masina.cs


using System;
using System.Collections.Generic;
using System.Text;
namespace TaxaInmatriculare
{
public delegate float CalculTaxa(int arg);
class Masina
{
string nume;
int capacitate;
public int Capacitate
{
get { return capacitate; }
set { capacitate = value; }
}
public CalculTaxa Ct;
float taxa;
public float Taxa
{
get { return taxa; }
set { taxa = value; }
}
public Masina(string nume, int capacitate) {
this.nume = nume;
this.capacitate = capacitate;
}
public override string ToString()
{
return nume + ": " + taxa;
}
}
}

CalculTaxaImpl.cs

using System;
using System.Collections.Generic;
using System.Text;
namespace TaxaInmatriculare
{
class CalculTaxaImpl
{
public static float Euro1(int capacitate) {
return 0.6f * capacitate;
}
public static float Euro2(int capacitate)
{
return 0.4f * capacitate;
}
public static float Euro3(int capacitate)
{
return 0.3f * capacitate;
}
public static float Euro4(int capacitate)
{
return 0.2f * capacitate;
}
public static float Euro5(int capacitate)
{
return 0.1f * capacitate;
}
}
}

2.2

Windows Application

Agent.cs; CalculBonusImpl.cs; Form1.cs;

Form1:

private System.Windows.Forms.Button buttonExit;
private System.Windows.Forms.Button buttonPrint;
private System.Windows.Forms.Button buttonAdd;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textBoxNume;
private System.Windows.Forms.TextBox textBoxSal;
private System.Windows.Forms.TextBox textBoxIncasari;
private System.Windows.Forms.ListBox listBoxPrint;

*code*

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace AgentImobiliar
{
public partial class Form1 : Form
{
private List<Agent> agentList = new List<Agent>();
private Agent tmpAgent;
public Form1()
{
InitializeComponent();
buttonAdd.Click += buttonAdd_MyClick;
}
private void buttonExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void buttonPrint_Click(object sender, EventArgs e)
{
foreach (Agent a in agentList)
{
listBoxPrint.Items.Add(a.ToString());
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
string nume = textBoxNume.Text;
int inc = 0, sal = 0;
try {
inc = int.Parse(textBoxIncasari.Text);
sal = int.Parse(textBoxSal.Text);
Agent a = new Agent(nume, sal, inc);
if (inc <= 20000) {
a.Cb = CalculBonusImpl.Bonus1;
}
else if (inc <= 50000)
{
a.Cb = CalculBonusImpl.Bonus2;
}
else {
a.Cb = CalculBonusImpl.Bonus1;
}
a.Sal += a.Cb(a.Incasari);
agentList.Add(a);
tmpAgent = a;
} catch {
MessageBox.Show("Invalid data!");
}
}
private void buttonAdd_MyClick(object sender, EventArgs e)
{
MessageBox.Show("Inserted data: " + tmpAgent.ToString());
}
}
}

Agent.cs

using System;
using System.Collections.Generic;
using System.Text;
namespace AgentImobiliar
{
public delegate float CalculBonusDelegate(int incasari);
class Agent
{
int incasari;
public int Incasari
{
get { return incasari; }
set { incasari = value; }
}
string nume;
public string Nume
{
get { return nume; }
set { nume = value; }
}
float sal;
public float Sal
{
get { return sal; }
set { sal = value; }
}
public CalculBonusDelegate Cb;
public Agent(String nume, float sal, int incasari) {
this.nume = nume;
this.sal = sal;
this.incasari = incasari;
}
public override string ToString()
{
return nume + ": " + sal;
}
}
}

CalculBonusImpl.cs


using System;
using System.Collections.Generic;
using System.Text;
namespace AgentImobiliar
{
public class CalculBonusImpl
{
public static float Bonus1(int incasari) {
return 0.1f * incasari;
}
public static float Bonus2(int incasari)
{
return 0.15f * incasari;
}
public static float Bonus3(int incasari)
{
return 0.2f * incasari;
}
}
}

Description

Să se dezvolte o aplicaţie desktop prin care să se calculeze bonusul salarial corespunzător câtorva agenţi imobiliari a căror date sunt introduse de către utilizator prin intermediul unei aplicaţii desktop. Se va crea clasa Agent, iar datele introduse se vor stoca întro listă generică.
De asemenea, după modelul din sursele de pe site, adăugaţi un delegat de tip EventHandler care la apăsarea butonului de introducere să afişeze obiectul introdus. Consideram că pentru încasări de până în 20,000Ron bonusul este de 10%, pentru încasări între 20,001 şi 50,000Ron bonusul este de 15%, iar pentru încasări de peste 50,001Ron, bonusul este de 20%.

Lista generica:
private List<Agent> agentList = new List<Agent>();
-adaugare:
agentList.Add(a);
-afisare:
foreach (Agent a in agentList)
{
listBoxPrint.Items.Add(a.ToString());
}

Words about delegates & events

Uneori în dezvoltarea unei aplicaţii este nevoie să specificăm la îndeplinirea unei condiţii o acţiune ce trebuie sa aibă loc, chiar dacă nu sa decis care va fi exact această acţiune. Mai mult putem avea mai multe cazuri şi mai multe acţiuni.

In C/C++ soluţia o constituiau pointerii la funcţii. In C# echivalentul lor sunt elementele numite delegate.

Un event (eveniment) defineşte o modificare de stare in cadrul aplicaţiei, modificare ce va determina un răspuns corespunzător. Eventurie şi elementele delegate, se utilizează frecvent împreună, un delegat reprezentând răspunsul corespunzător evenimentului.

Din punct de vedere tehnic, un delegat este o referinţă la o metodă cu o anumită semnătură şi un anumit tip de valoare returnată. Scopul elementelor delegate este de a oferi flexibilitate maximă, acţiunea ce se va executa fiind selectată exact în momentul execuţiei.
Exemplu de declaraţie a unui delegat : public delegate int compute(Object obj);

Delegatul fiind practic un tip referinţă poate apare declarat şi în afara unei clase. Adevăratul scop al delegaţilor iese în evidenţa doar când sunt folosiţi împreună cu evenimentele.

Pe scurt, o clasă declară un eveniment. Orice clasă, inclusiv clasa în care a fost declarat evenimentul poate să conţină o metodă “înregistrată” să trateze acel eveniment. Această înregistrare se face prin intermediul unei componente delegat care specifică semnătura metodei respective. Delegatul respectiv poate fi unul definit în librăriile .Net sau poate fi definit de programator.

2.1 Asynchronous File Operations

Console Application


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
namespace AsyncFileOps
{
public delegate void CountBytesDelegate(int count);
class Program
{
static event CountBytesDelegate CountBytesEvent;
static byte[] data = new byte[9];
static FileStream fs = new FileStream(@"C:\Documents and Settings\admin\Desktop\SD\test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
static MemoryStream ms = new MemoryStream();
static void Main(string[] args)
{
// initializare fisier, scriem 10 linii de text - decomentati inainte de prima rulare
/*for (int i = 0; i < 10; ++i)
{
byte[] b = Encoding.UTF8.GetBytes("linia " + i + Environment.NewLine);
fs.Write(b, 0, b.Length);
}*/
fs.Flush();
CountBytesEvent += OnBytesRead;
fs.Seek(0, SeekOrigin.Begin);
fs.BeginRead(data, 0, data.Length, ReadCallback, null);
Console.WriteLine(">>> Press any key to exit ....");
Console.ReadKey();
}
static void OnBytesRead(int count) {
Console.WriteLine(System.DateTime.Now + ": " + count + " bytes were read.");
}
static void ReadCallback(IAsyncResult ias) {
int noBytes = fs.EndRead(ias);
if (noBytes == 0)
{
Console.WriteLine("READING IS DONE");
fs.Close();
ms.Close();
return;
}
Console.WriteLine("DEBUG(readData): " + Encoding.UTF8.GetString(data, 0, noBytes));
Thread.Sleep(500);
OnBytesRead(noBytes);
ms.BeginWrite(data, 0, noBytes, WriteCallBack, null);
}
static void WriteCallBack(IAsyncResult ias)
{
ms.EndWrite(ias);
ms.Flush();
fs.BeginRead(data, 0, data.Length, ReadCallback, null);
}
}
}

Description
- Functie care citeste continut unui fisier si depune datele citite intr-un MemoryStream. Citirea trebuie sa se faca in mod asincron prin utilizarea unui delegate asincron.
- Clasa care publica un eveniment ce notifica obiectele ce subscriu atunci cand s-au citit un numar de octeti.

Working with XML Files [1]

Windows Application

Form1.cs


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace pr13
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Windows.Forms.DialogResult OPEN = openFileDialog1.ShowDialog();
if (OPEN == DialogResult.OK)
{
string path = openFileDialog1.FileName; // The Path to the .Xml file //
FileStream READER = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Set up the filestream (READER) //
System.Xml.XmlDocument CompSpecs = new System.Xml.XmlDocument();// Set up the XmlDocument (CompSpecs) //
CompSpecs.Load(READER); //Load the data from the file into the XmlDocument (CompSpecs) //
System.Xml.XmlNodeList NodeList = CompSpecs.GetElementsByTagName("CompSpecs"); // Create a list of the nodes in the xml file //
textBox1.Text = NodeList[0].FirstChild.ChildNodes[0].InnerText; // Load Type //
textBox2.Text = NodeList[0].FirstChild.ChildNodes[1].InnerText; // Load RAM //
textBox3.Text = NodeList[0].FirstChild.ChildNodes[2].InnerText; // Load CPU Speed //
}
}
private void button2_Click(object sender, EventArgs e)
{
if (openFileDialog1.FileName.Length > 0) //If a file is open
{
string path = openFileDialog1.FileName; // The Path to the .Xml file //
FileStream READER = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Set up the filestream (READER) //
System.Xml.XmlDocument CompSpecs = new System.Xml.XmlDocument();// Set up the XmlDocument (CompSpecs) //
CompSpecs.Load(READER); //Load the data from the file into the XmlDocument (CompSpecs) //
System.Xml.XmlNodeList NodeList = CompSpecs.GetElementsByTagName("CompSpecs"); // Create a list of the nodes in the xml file //
NodeList[0].FirstChild.ChildNodes[0].InnerText = textBox1.Text; // Save the type
NodeList[0].FirstChild.ChildNodes[1].InnerText = textBox2.Text; // Save the RAM
NodeList[0].FirstChild.ChildNodes[2].InnerText = textBox3.Text; // Save the CPU Speed
//Save the xml file
//Create a FileStream for writing
FileStream WRITER = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); //Set up the filestream (READER) //
//Write the data to the filestream
CompSpecs.Save(WRITER);
}
}
private void button3_Click(object sender, EventArgs e)
{
Close();
}
}
}

StreamWriter, StreamReader

Console Application


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace pr11
{
class Program
{
static void Main(string[] args)
{
FileInfo f = new FileInfo(@"C:\Documents and Settings\admin\Desktop\SD\file2.txt");
StreamWriter w = f.CreateText();
w.WriteLine("This is from");
w.WriteLine("Chapter 6");
w.WriteLine("Of C# Module");
w.Write(w.NewLine);
w.WriteLine("Thanks for your time");
w.Close();
//
Console.WriteLine("Reading the contents from the file");
StreamReader s = File.OpenText(@"C:\Documents and Settings\admin\Desktop\SD\file2.txt");
string read = null;
while ((read = s.ReadLine()) != null)
{
Console.WriteLine(read);
}
s.Close();
Console.Read();
}
}
}

Monitors

A monitor is the most basic synchronization construct.

Any object can have a monitor associated with it, and no monitor can be associated with more than one object.

Monitors have a “lock,” which may be acquired by only one thread at a time. It must be released by that thread before another thread can acquire it.

You can guard a section of code by declaring an object that is visible to all threads, such as a class field, and having a section of code acquire the lock from that monitor before performing some operation and then release the lock when it completes.

Console Application

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace pr10
{
class Program
{
static object myLockObject = new Object();
static void SayHello()
{
Console.WriteLine("Hello, ");
Thread.Sleep(1000);
Monitor.Enter(myLockObject); // Acquire the lock.
Console.WriteLine("Wonderful "); // This section of code
Thread.Sleep(1000); // is run by only one
Console.WriteLine("World"); // thread at a time.
Monitor.Exit(myLockObject); // Release the lock.
}
static void Main(string[] args)
{
Thread thread1 = new Thread(new ThreadStart(SayHello));
Thread thread2 = new Thread(new ThreadStart(SayHello));
thread1.Start();
thread2.Start();
Console.ReadLine();
}
}
}

MSDN Info