Illustrated C# 2008 - free ebook
Thursday, April 16th, 2009If you want to learn C#, here is a great free pdf book for you. This is very good book for programmers beginners. Enjoy!
More about book…
If you want to learn C#, here is a great free pdf book for you. This is very good book for programmers beginners. Enjoy!
More about book…
I will create an example and we go through it. Suppose we have a task to display on some web page data from table customers.
at the moment I will not take care about database. let’s say that database already exists, tables and data are there. We can do this task very quickly. It is not some big deal. We will open connection to database, read data from table, display data and close connection.
all of that can be put in one class. Bu the question is: “Is that really good practice?” in my favorite C# I will write down some code. To follow me, create an empty ASP.NET project in your Visual Studio ( I use VS2005)and choose C# for language.
There is Default.aspx page in your solution. Add GridView control (drag and drop from Toolbox). Call your grid view as: “grdCustomers“.
Edit Default.aspx.cs file:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace Customers
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strConnection = null;
string strSQL = "select customerID, customerName, customerContact from Customers ";
strConnection = "server=DB_SERVER_NAME; initial catalog=TestDB; user=usernameValue; password=passwordValue";
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(strConnection);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(strSQL, conn);
da.Fill(ds);
grdCustomers.DataSource = ds;
grdCustomers.DataBind();
conn.Close();
}
}
}
and when we start web app with “F5″ button, we get this on the screen:

What is wrong with this? This is working, right. What if we need an other web page to display Employees. The most of the previous code will be the same except the sql query; and we will have the copy paste in our application which is bad. The other problem is sql server connection string which is hardcoded. First we will put sql connection string into configuration: Web.Config.
Edit web config to looks like this:
< ?xml version="1.0"?>
and after that, change your Default.aspx.cs code. This line:
strConnection = "server=DB_SERVER_NAME; initial catalog=TestDB; user=usernameValue; password=passwordValue";
Chamge with this one:
strConnection = ConfigurationManager.ConnectionStrings["SQLServerConnStr"].ConnectionString;
That is better. Now we do not need to think about sql server, its location or username/password. When we move our application to some other server, we only need to edit web.config file. No “building” necessary at all. But this can make some problem letter. If in the future Microsoft publish some better way for reading from web config we will need to change our code and recompile it again. To avoid this I will create one new project which will be used in entire solution for reading from web.config.
Create new project, type of Class library, language C#. Call it: “WebCommon“. Renamce Class1.cs to Configuration.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace WebCommon
{
public static class Configuration
{
public static string ReadSqlConfiguration
{
get
{
return ConfigurationManager.ConnectionStrings["SQLServerConnStr"].ConnectionString;
}
}
}
}
You need to add System.Configuration reference to this WebCommon project.
When this is done, now get back to our web project and add reference to WebCommon project.
this is how Default.aspx.cs looks after modification:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using WebCommon;
namespace Customers
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strConnection = null;
string strSQL = "select customerID, customerName, customerContact from Customers ";
strConnection = WebCommon.Configuration.ReadSqlConfiguration();
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(strConnection);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(strSQL, conn);
da.Fill(ds);
grdCustomers.DataSource = ds;
grdCustomers.DataBind();
conn.Close();
}
}
}
This is how we read from web.config now:
strConnection = WebCommon.Configuration.ReadSqlConfiguration();
we need this using directive:
using WebCommon;
Now we will separate our presentation layer and data access layer. Data access layer will deal with database. Create new Project, type of class Library, language C#. Call it: “DAL” Data Access Layer. Rename Class1.cs to Helper.cs
Enter this code to Helper.cs
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace DAL
{
public class Helper
{
public DataSet GetDataSet(string strSql, string strSqlServerConnection)
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(strSqlServerConnection);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
da.Fill(ds);
conn.Close();
return ds;
}
}
}
There is a public method GetDataSet(string strSql, string strSqlServerConnection) which executes sql query and return populated data set.
Now add reference to this project to our web project and modify Default.aspx.cs:
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using WebCommon;
using DAL;
namespace Customers
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds;
string strSQL = "select customerID, customerName, customerContact from Customers ";
DAL.Helper objHelper = new DAL.Helper();
ds = objHelper.GetDataSet(strSQL, WebCommon.Configuration.ReadSqlConfiguration);
grdCustomers.DataSource = ds;
grdCustomers.DataBind();
}
}
}
This is code in code behind of Default.aspx page. As you can see there is a less code than in the begining. If we need some other page to display similiar info like employees, we will create new page and put some code like this:
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using WebCommon;
using DAL;
namespace Customers
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds;
string strSQL = "select employeID, employeeName, employeeAddress, zipCode, COuntry from Employees";
DAL.Helper objHelper = new DAL.Helper();
ds = objHelper.GetDataSet(strSQL, WebCommon.Configuration.ReadSqlConfiguration);
grdCustomers.DataSource = ds;
grdCustomers.DataBind();
}
}
}
If I think a litle bit more I will decide to remove this sql queries from my web project. web project should be presentation layer and there we only use information for publishing or perform some actions. I will create one more Layer for some business logic and derision making. It will be BL(Business Layer)
Create new Project, type of class Library, call it BL and renamce Class1.cs to Customers.cs and put this code there.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using WebCommon;
using DAL;
namespace BL
{
public class Customers
{
public DataSet GetCustomers()
{
DataSet ds;
string strSQL = "select customerID, customerName, customerContact from Customers ";
DAL.Helper objHelper = new DAL.Helper();
ds = objHelper.GetDataSet(strSQL, WebCommon.Configuration.ReadSqlConfiguration);
return ds;
}
public int UpdateCustomer()
{
// to do
return 0;
}
public int DeleteCustomer(int customerID)
{
// to do
return 0;
}
}
}
You need to add references to “WebCommon” and to “DAL” in “BL” project. And now modify Web project. Remove reference to DAL and WebCommon and add reference to BL.
edit Default.aspx.cs:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using BL;
namespace Customers
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds;
BL.Customers objCustomers = new BL.Customers();
ds = objCustomers.GetCustomers();
grdCustomers.DataSource = ds;
grdCustomers.DataBind();
}
}
}
Now our presentation layer, GUI or web form doesn’t know about data sources. All data it will get from BL. Just call proper method of BL. In BL project we can add more classes for Employees, Customers, Orders, …
DAL (Data Access Layer) is used to provide information.
that is all for now. Have a good day.
Model–View–Controller (MVC) is an architectural pattern used in software engineering. It allows software developers to build a Web application as a composition of three roles: Model, View and Controller. A Model represents the state of a particular aspect of the application. Frequently, a model maps to a database table with the entries in the table representing the state of the table. A Controller handles interactions and updates the model to reflect a change in state of the application. A View extracts necessary information from a model and renders a user interface to display that”.<br/>
Here is the code for simple Calculator application written in Java which is organized according the the Model-View-Controller (MVC) pattern.<br/>
The main program initializes everything and ties everything together.
Main.java:
import javax.swing.*;
public class Main{
public static void main(String[] args) {
CalcModel model = new CalcModel();
CalcView view = new CalcView(model);
CalcController controller = new CalcController(model, view);
view.setVisible(true);
}
}
here is the View class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class CalcView extends JFrame {
private static final String INITIAL_VALUE = "1";
private JTextField m_userInputTf = new JTextField(5);
private JTextField m_totalTf = new JTextField(20);
private JButton m_multiplyBtn = new JButton("Multiply");
private JButton m_clearBtn = new JButton("Clear");
private CalcModel m_model;
CalcView(CalcModel model) {
m_model = model;
m_model.setValue(INITIAL_VALUE);
m_totalTf.setText(m_model.getValue());
m_totalTf.setEditable(false);
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(new JLabel("Input"));
content.add(m_userInputTf);
content.add(m_multiplyBtn);
content.add(new JLabel("Total"));
content.add(m_totalTf);
content.add(m_clearBtn);
//... finalize layout
this.setContentPane(content);
this.pack();
this.setTitle("Simple Calc - MVC");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void reset() {
m_totalTf.setText(INITIAL_VALUE);
}
String getUserInput() {
return m_userInputTf.getText();
}
void setTotal(String newTotal) {
m_totalTf.setText(newTotal);
}
void showError(String errMessage) {
JOptionPane.showMessageDialog(this, errMessage);
}
void addMultiplyListener(ActionListener mal) {
m_multiplyBtn.addActionListener(mal);
}
void addClearListener(ActionListener cal) {
m_clearBtn.addActionListener(cal);
}
}
Here is the Controller class:
import java.awt.event.*;
public class CalcController {
private CalcModel m_model;
private CalcView m_view;
CalcController(CalcModel model, CalcView view) {
m_model = model;
m_view = view;
view.addMultiplyListener(new MultiplyListener());
view.addClearListener(new ClearListener());
}
/*
* 1. Get the user input number from the View.
* 2. Call the model to mulitply by this number.
* 3. Get the result from the Model.
* 4. Tell the View to display the result.
* If there was an error, tell the View to display it.
*/
class MultiplyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String userInput = "";
try {
userInput = m_view.getUserInput();
m_model.multiplyBy(userInput);
m_view.setTotal(m_model.getValue());
} catch (NumberFormatException nfex) {
m_view.showError("Bad input: '" + userInput + "'");
}
}
}
class ClearListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
m_model.reset();
m_view.reset();
}
}
}
and here is the Model class:
import java.math.BigInteger;
public class CalcModel {
private static final String INITIAL_VALUE = "0";
private BigInteger m_total; // The total current value state.
CalcModel() {
reset();
}
public void reset() {
m_total = new BigInteger(INITIAL_VALUE);
}
public void multiplyBy(String operand) {
m_total = m_total.multiply(new BigInteger(operand));
}
public void setValue(String value) {
m_total = new BigInteger(value);
}
public String getValue() {
return m_total.toString();
}
}
have a nice day ![]()
In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A developer creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.
We use Mock object for NUnit testing if we have 2, 3 or more layer architecture.
In programming terms mock objects are objects that “imitate” some other objects, claiming to have the same attributes, methods etc. like the original.

Rhino Mocks allows you to easily create mock objects and setup a wide range of expectations on them using strongly typed notation instead of compiler-opaque strings.
To mock an object, its class MUST implement an interface.
Public class Car : ICar
{
public int StartEngine();
…
// More methods to be implemented
}
MockRepository mockRepository = new MockRepository();
MyCar = mockRepository.CreateMock<ICar>();
Here is the scenario and source code in C# for demonstration.
We have one solution and 2 projects, representing 2 layers.
Project: DataLayer which gets some information from xml file, database or some other web service, …
DataLayer project has one class: PersonDAL.
using System;
using System.Collections.Generic;
using System.Text;
namespace DataLayer
{
public class PersonDAL
{
private string _name;
private string _id;
private List
lista = new List
();
public PersonDAL(string name, string id)
{
_name = name;
_id = id;
}
public List
CreateList()
{
lista.Add(new PersonDAL("Peter", "1"));
lista.Add(new PersonDAL("George", "2"));
lista.Add(new PersonDAL("Michael", "3"));
return lista;
}
public PersonDAL GetPersonByID(string id)
{
PersonDAL result = new PersonDAL("", "");
result = null;
foreach (PersonDAL person in lista)
{
if (person.ID == id)
{
result = person;
break;
}
}
return result;
}
public string ID
{
get { return _id; }
}
public string Name
{
get { return _name; }
}
}
}
it is a simple class which gets data from some resource. In this case, data are hardcoded but never mind.
The other project is BusinessLayer, it represents some business logic. It is Layer 2.
Person class:
using System;
using System.Collections.Generic;
using System.Text;
using DataLayer;
namespace BusinessLayer
{
public class Person
{
public string _id;
public string _name;
public Person(string id, string name)
{
_id = id;
_name = name;
}
}
}
interface IPersonService:
using System;
using System.Collections.Generic;
using System.Text;
namespace BusinessLayer
{
public interface IPersonService
{
List
GetPersons();
Person GetPersonByID(string id);
}
}
and PersonService class:
using System;
using System.Collections.Generic;
using System.Text;
namespace BusinessLayer
{
public class PersonService : IPersonService
{
DataLayer.PersonDAL person = new DataLayer.PersonDAL("", "");
public List
GetPersons()
{
List
list = new List
();
foreach (DataLayer.PersonDAL objPerson in person.CreateList())
{
list.Add(new Person(objPerson.ID, objPerson.Name));
}
return list;
}
public Person GetPersonByID(string id)
{
return new Person(person.GetPersonByID(id).ID,person.GetPersonByID(id).Name);
}
}
}
Ok, that is part of some huge application. Let’s code some Unit test here. Supose we do not have data resource at this moment and we can not test this with real data. We must fake it.
So, create new project, type of Class Library into this solution and call it: Test
Add references for both projects and references for NUnit.Framework and
Rhino.Mocks. This project for now has only one class. We use it for testing.
PersonServiceTest class:
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Rhino.Mocks;
using BusinessLayer;
using DataLayer;
[TestFixture]
public class PersonServiceTest
{
[SetUp]
public void TestInit()
{
}
[Test]
public void Test()
{
MockRepository mockRepository = new MockRepository();
IPersonService personRepository = mockRepository.CreateMock();
Person mockPerson = new Person("1", "Milan");
Person objPerson;
Expect.Call(personRepository.GetPersonByID("1")).Return(mockPerson);
mockRepository.ReplayAll();
objPerson = personRepository.GetPersonByID("1");
Assert.AreEqual(objPerson._id, mockPerson._id);
}
}
In this tutorial our focus is on creating dynamic thumbnails with the help of .NET framework. Here is the scenario: We have simple aspx page with FileUpload and Button control. We will use FMPEG library, so you can have it installed before you start this example.
Here is the code of aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
and code for web.config file:
as you can see, we save location of fmpeg and thumb path in web.config.
and here is the code which will uplaod video and save it’s thumb:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string thumbpath, thumbname, inputfile;
string thumbargs;
thumbpath = ConfigurationManager.AppSettings.GetValues("thumbpath")[0];
inputfile = thumbpath + fileUpload.FileName;
fileUpload.PostedFile.SaveAs( inputfile);
thumbname = thumbpath + fileUpload.PostedFile.FileName.Substring(0, fileUpload.PostedFile.FileName.LastIndexOf(".")) + ".jpg";
thumbargs = "-i " + inputfile + " -f image2 -ss 1 -vframes 1 -s 150x150 " + thumbname;
Process thumbproc = new Process();
thumbproc = new Process();
thumbproc.StartInfo.FileName = thumbpath = ConfigurationManager.AppSettings.GetValues("ffmpegPath")[0];
thumbproc.StartInfo.Arguments = thumbargs;
thumbproc.StartInfo.UseShellExecute = false;
thumbproc.StartInfo.CreateNoWindow = false;
thumbproc.StartInfo.RedirectStandardOutput = false;
try
{
thumbproc.Start();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
thumbproc.WaitForExit();
thumbproc.Close();
}
}
One of the first things I’ve learned as .NET developer was using of App.config or Web.config files. Almost every application in which development I took a part had some database. Here is the brief sample how to connect to SQL Server from C#:
string connString = @"Server=(LOCAL);Database=Northwind;User ID=sa;Password=;"; string sqlString = "SELECT * FROM PRODUCTS"; DataSet ds = new DataSet(); SqlConnection conn = new SqlConnection(connString); conn.Open(); SqlDataAdapter da = new SqlDataAdapter(sqlString, conn); da.Fill(ds); dgrProducts.DataSource = ds; dgrProducts.DataBind(); conn.Close();
This code will open connection to database, read table and fill data set. Then we bind data from data set to dataGrid or GridView (control named dgrProducts).
But it is not a good practice to keep connection string hard coded. Place it into configuration file.
< ?xml version="1.0" encoding="utf-8" ?>
and here is how you can read value from configuration file. It is a good practice to create new project, type of Class Library for that.
using System;
using System.Configuration;
namespace ConnectionString
{
public class Configuration
{
public static string ReadConnectionString
{
get
{
return ConfigurationSettings.AppSettings.Get("ConnectionString");
}
}
}
}
this sample runs on .NET 1.1 framework
For 3.0 .NET we use:
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace ConnectionString
{
public class Configuration
{
protected static string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["ConnectionString"].
ToString();
}
}
}
}
As you can see we use System.Configuration reference.
Here is how Microsoft describes it: “The Policy Injection Application Block provides a mechanism for automatically applying policies to object instances; this helps developers to better manage crosscutting concerns and maximize separation of concerns and encapsulation of behavior. Developers define the set of policies for the target classes and their members through configuration of the Policy Injection Application Block or by applying attributes to individual members of the target class.
The matching rules for each policy encompass a range of capabilities for selecting classes and members, including the name of the assembly, the namespace, the type, the member name, the member signature, attributes that are applied to the member, and more.“
I’ll show you one small demo apllication which demonstrates how it works:
Create empty solution and add Class Library project called: BusinessObject. put those 2 files there: CellPhone.cs and ICellPhone.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace BusinessObject
{
public interface ICellPhone
{
void SendSMS(String toPhoneMumber, String mesgSubject, String text);
void Ring();
void Dial(String toPhoneNumber);
void Answer();
void HangUp();
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace BusinessObject
{
public class CellPhone : ICellPhone
{
private String phoneNumber;
public CellPhone(String number)
{
phoneNumber = number;
}
public void SendSMS(String toPhoneMumber, String mesgSubject, String text)
{
Console.WriteLine("I am sending SMS to "
+ toPhoneMumber
+ ", with subject "
+ mesgSubject
+ " and text "
+ text
);
}
public void Ring()
{
Console.WriteLine("Ringing ...");
}
public void Dial(String toPhoneNumber)
{
Console.WriteLine("I am dialing " + toPhoneNumber);
}
public void Answer()
{
Console.WriteLine("Yes plese!");
}
public void HangUp()
{
Console.WriteLine("Have a nice day.");
}
}
}
As you can see we have very simple class CellPhone which implements ICellPhone interface. Then, create and new project to your solution. It can be Console Application. I’ll call it client.
Add BusinessObject reference to your client project. Also you have to add some .NET references in order to use Policy Injection.
Microsoft.Practices.EnterpriseLibrary.Common
Microsoft.Practices.EnterpriseLibrary.PolicyInjection
Microsoft.Practices.EnterpriseLibrary.PolicyInjection
Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers

Now take a look of code for Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.Logging;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration;
namespace Client
{
class Program
{
static void Main(string[] args)
{
BusinessObject.CellPhone cellPhone = PolicyInjection.Create("222333");
cellPhone.Dial("123123");
cellPhone.Ring();
cellPhone.Answer();
}
}
}
This line is interesting:
BusinessObject.CellPhone cellPhone = PolicyInjection.Create
I don’t use BusinessObject.CellPhone cellPhone = new BusinessObject.CellPhone(”222333″); as you can see. If you want to use Policy Injection, this is how you create your objects. And very important rule: your object must implement some interface or must inherits class: “MarshalByRefObject“. Now you can try to “Build” and start (F5) your application, but for now there is no some differences. It works as it should be.
We have to do 2 more things. Add new project type of class library and to add App.config file to our client application.
First, add new project, type of class library, called: “CustomPIABHandler”.
Rename Class1.cs to LogCallHandler.cs and add some references to project as it is shown on the pictire below:

Now select custom handler. Click on property for Custom Handler and click type. From new PopUp window click on button “Load Assembly” and select LogCallHandler. You should navigate to your bin folder of your CustomPiabHanlder project and select CustomPIABHandler.dll.
And at last, add value for namespace matching rule. Click on Namespace Matching Rule and select it’s Property. Click on collection and add value: BusinessObject. And for the end add Reference of CustomPIABHandler to Client project.to be continued
Our today discussion is about logging in .NET apps. In this demonstration I will use Visual Studio 2005 and Enterprise Library 3.1 - May 2007.
The Microsoft Enterprise Library is a set of tools and programming libraries for the Microsoft .NET Framework. Enterprise Library Logging Application Block provides you tool for perform logging into your application easily.
All you need is this using directive:
using Microsoft.Practices.EnterpriseLibrary.Logging;
and reference to: “Microsoft.Practices.EnterpriseLibrary.Logging“.
And when you want to log some method, you do it like this:
LogEntry log = new LogEntry();
log.Priority = 1;
log.Message = "Executing";
log.Categories.Add("General");
log.Title = "Executing method name";
Logger.Write(log);
that is all you need to put into your code. Take a look this line: “log.Categories.Add(”General”);”.
At this moment developer doesn’t know how application perform the logging. Does it use some txt file, database or something else. That is why we use App.config file to specify things like that. For editing App.config I suggest to do this edit tool: right click on App.config and select “Edit Enterpise Library Confoguration” .

When we want to use logging, 1-st we have to add “Category”. Take a look at picture!

I will call my Category “General”. Category gets name by Default, so you use “Property” window to change it’s name. After that add trace reference to your category.

For trace reference we need trace listener! So let’s add some trace listener, like this:

I selected “Flat File Trace Listener“. Choose Property for your trace listener. I select Filename to be: C:\trace.log.

After that select “Trace Reference Listener” and in it’s property window connect it to FlatFileTraceListener. Like this:

And that would be all. Now start your application and take a look at file: C:\trace.log.
We can go one step further and create our Logging class. Here is how can we do that.
Create new project in your solution, and call it Logger, type of project: Class Library, language C#. You have to add reference to you project for: “Microsoft.Practices.EnterpriseLibrary.Logging“.
and here is your class:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Logging;
namespace Logger
{
public static class MyLogger
{
public static void Logg(String message, String category, Int32 priority, String title)
{
LogEntry log = new LogEntry();
log.Priority = priority;
log.Message = message;
log.Categories.Add(category);
log.Title = title;
Logger.Write(log);
}
}
}
and here is how you call it from some of your method. First add reference to Logger project.
Logger.MyLogger.Logg("Exucuting method name", "General", 1, "before method start");
Let’s go further with WCF. In this post I will discuss about using business objects and WCF. For the beginning create blank solution named “SampleWCFWithBusinessObjetcs”, and put 4 projects there:
1. project type Class Library, language C#: “BusinessObjetcs”
2. project type Windows Application, language C#: “Client”
3. project type Console Application, language C#: “Host” and
4. project type Class Library, language C#: “Service”
Project named “BusinessObjetcs” we will use to create business entites, project “Host” will host our WCF,
project “Service” will be wcf and project “Client” will be windows application for testing - our client.
Let’s start with “BusinessObjects”, create new class there called Person. Here is the code:
using System;
using System.Collections.Generic;
using System.Text;
namespace BusinessObjetcs
{
public class Person
{
private Int32 m_Id;
private String m_Name;
private DateTime m_BirthDate;
public Person(Int32 id, String name, DateTime birthDate)
{
m_Id = id;
m_Name = name;
m_BirthDate = birthDate;
}
public Int32 Id
{
get { return m_Id; }
set { m_Id = value; }
}
public String Name
{
get { return m_Name; }
set { m_Name = value; }
}
public DateTime BirthDate
{
get { return m_BirthDate; }
set { m_BirthDate = value; }
}
}
}
Then let’s focus to our “Service” project. I will create an interface and one class which implements that interface: IPerson and Person. As you can imagine IPerson is an itnerface and Person is a class. Before you start, add 2 references to “Service” project. The first one is System.ServiceModel and the other is reference to project “BusinessObjects“. After that create class and interface. Here is the code:
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using BusinessObjetcs;
namespace Service
{
[ServiceContract]
public interface IPersonService
{
[OperationContract]
Person GetPersonByID(Int32 id);
[OperationContract]
void UpdatePerson(Person person);
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using BusinessObjetcs;
using System.Collections;
namespace Service
{
public class PersonService : IPersonService
{
private Dictionary m_People = new Dictionary();
public PersonService()
{
m_People.Add(1, new Person(1, "Peter Petrovic", new DateTime(1977, 04, 5)));
m_People.Add(2, new Person(2, "John Johnson", new DateTime(1987, 14, 6)));
m_People.Add(3, new Person(3, "Mihajlo Lalic", new DateTime(1967, 24, 7)));
}
public Person GetPersonByID(Int32 id)
{
Person result = null;
if(m_People.ContainsKey(id))
{
result = (Person)m_People[id];
}
return result;
}
public void UpdatePerson(Person person)
{
if(m_People.ContainsKey(person.Id) )
{
m_People[person.Id] = person;
}
}
}
}
At this time you should try to build solution and if everything is OK, let’s go to create host for our wcf service.
In host project add reference to “System.ServiceModel” and to “Service” project. In “Host” project you’l find Program.cs
update this file to:
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using Service;
namespace Host
{
class Program
{
static void Main(string[] args)
{
Type t;
t = typeof(Service.PersonService);
using (ServiceHost host = new ServiceHost(t))
{
host.Open();
Console.WriteLine("Service started...");
Console.ReadLine();
host.Close();
}
}
}
}
So if you run Host application our service will be started, but not so fast. We are missing one thing. end points!
Create App.config file for “Host” project and copy paste this.
Ok, I hope that is all for now, and I hope it’s works. Set your “Host” project to be startup project and press “F5″.
If you have some problems it is OK. You probably get message about: “Type ‘BusinessObjetcs.Person’ cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.”

Add an Using statement for System.Runtime.Serialization to the top of the source code file for the Person class and add Reference to System.Runtime.Serialization. Then add the DataContract attribute to the Person class declaration and the DataMember attribute to each of the properties. After that your “Person”class looks like this one:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
namespace BusinessObjetcs
{
[DataContract]
public class Person
{
private Int32 m_Id;
private String m_Name;
private DateTime m_BirthDate;
public Person(Int32 id, String name, DateTime birthDate)
{
m_Id = id;
m_Name = name;
m_BirthDate = birthDate;
}
[DataMember]
public Int32 Id
{
get { return m_Id; }
set { m_Id = value; }
}
[DataMember]
public String Name
{
get { return m_Name; }
set { m_Name = value; }
}
[DataMember]
public DateTime BirthDate
{
get { return m_BirthDate; }
set { m_BirthDate = value; }
}
}
}
Ok, now rebuild all and press “F5″. Wait for a while and then try to get “http://localhost:8081/PersonService”. Here is preview:
So, if everything works for now, let’s add Service Reference to “Client” project. I called it “PersonServiceProxy”. After adding service reference, Visual Studio created new file for you: “PersonServiceProxy.cs“. It is useful to take a look. There you can find some classes and interfaces:
Ok, now let’s finish our demo. Put some controls to your form. 
and add some lines of code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
LoadListBox();
}
private void LoadListBox()
{
using (PersonServiceProxy.PersonServiceClient ws = new PersonServiceProxy.PersonServiceClient())
{
lstPeople.DisplayMember = "Name";
lstPeople.ValueMember = "Id";
lstPeople.DataSource = ws.GetPeople();
}
}
private void lstPeople_SelectedIndexChanged(object sender, EventArgs e)
{
using (PersonServiceProxy.PersonServiceClient ws = new PersonServiceProxy.PersonServiceClient())
{
PersonServiceProxy.Person _person = ws.GetPersonByID(Convert.ToInt32(lstPeople.SelectedValue));
txtBirthDate.Text = _person.BirthDate.ToString();
txtName.Text = _person.Name;
txtID.Text = _person.Id.ToString();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
PersonServiceProxy.Person _person = new Client.PersonServiceProxy.Person();
_person.BirthDate = Convert.ToDateTime(txtBirthDate.Text);
_person.Name = txtName.Text;
_person.Id = Convert.ToInt32(txtID.Text);
using (PersonServiceProxy.PersonServiceClient ws = new PersonServiceProxy.PersonServiceClient())
{
ws.UpdatePerson(_person);
LoadListBox();
}
}
}
}
Now you have to set your solution to have multiple startup projects:
“Host” and “Client”.
When you hit “F5″ here is what you got.

try to play a litle bit with this!
It is really fun! I hope you’ll find this interesting. The subject of this post is how to test your web service or some wcf service. You only need WSDL and SoapUI. Foe this demonstration we’ll use this service created in Windows Communication Foundation (WCF). If you start your Service you, you will see something like this in your web browser. In my case URL address is: http://localhost:3363/WebServiceHost/Service.svc
“You have created a service.
To test this service, you will need to create a client and use it to call the service. You can do this using the svcutil.exe tool from the command line with the following syntax:
svcutil.exe http://localhost:3363/WebServiceHost/Service.svc?wsdl”
I need only this wsdl so I’ll click on this link: “http://localhost:3363/WebServiceHost/Service.svc?wsdl”.
That is the first step, remember location of your wsdl. Then start SoaupUI applcation, and under projects click “New WSDL project”.

Enter your project name, and enter URL of your WSDL and press OK.
Here is preview:
Now we will test method “FunctionAdd”. Click on Request 1 under the FunctionAdd and populate xml request.
Here is XML request:
And here is response

That is all. I find this tool “SoapUI” very interesting at all.
Recent Comments