Convert a Color Image to Grayscale

Introduction:

In photography and computing, a grayscale or greyscale digital image is an image in which the value of each pixel is a single sample, that is, it carries only intensity information. Images of this sort, also known as black-and-white, are composed exclusively of shades of gray, varying from black at the weakest intensity to white at the strongest.

Grayscale images are often the result of measuring the intensity of light at each pixel in a single band of the electromagnetic spectrum (e.g. infrared, visible light, ultraviolet, etc.), and in such cases they are monochromatic proper when only a given frequency is captured. But also they can be synthesized from a full color image.

Below is the image I used to test my  algorithm and to benchmark its performance:

xs

 

original

METHOD 1:

The first method I’m going to show you is by far the easiest to understand and implement. Unfortunately, it’s also the slowest.

public static Bitmap MakeGrayscale(Bitmap original)
{
//make an empty bitmap the same size as original
Bitmap newBitmap = new Bitmap(original.Width, original.Height);

for (int i = 0; i < original.Width; i++)
{
for (int j = 0; j < original.Height; j++)
{
//get the pixel from the original image
Color originalColor = original.GetPixel(i, j);

//create the grayscale version of the pixel
int grayScale = (int)((originalColor.R * .3) + (originalColor.G * .59)
+ (originalColor.B * .11));

//create the color object
Color newColor =  Color.FromArgb(grayScale, grayScale, grayScale);

//set the new image’s pixel to the grayscale version
newBitmap.SetPixel(i, j, newColor);
}
}

return newBitmap;
}

EXPLANATION:

This code looks at every pixel in the original image and sets the same pixel in the new bitmap to a grayscale version. You can probably figure out why this is so slow. If the image is 2048×2048, this code will call GetPixel and SetPixel over 4 million times. Those functions aren’t the most efficient way to get pixel data from the image.

You might be wondering where the numbers .3, .59, and .11 came from. In reality, you could just take the average color by adding up R, G, B and dividing by three. In fact, you’ll get a pretty good black and white image by doing that. However, at some point, someone a lot smarter than me figured out that these numbers better approximate the human eye’s sensitivity to each of those colors.

faster and complicated

 

public static Bitmap MakeGrayscale2(Bitmap original)
{
unsafe
{
//create an empty bitmap the same size as original
Bitmap newBitmap = new Bitmap(original.Width, original.Height);

//lock the original bitmap in memory
BitmapData originalData = original.LockBits(
new Rectangle(0, 0, original.Width, original.Height),
ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

//lock the new bitmap in memory
BitmapData newData = newBitmap.LockBits(
new Rectangle(0, 0, original.Width, original.Height),
ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

//set the number of bytes per pixel
int pixelSize = 3;

for (int y = 0; y < original.Height; y++)
{
//get the data from the original image
byte* oRow = (byte*)originalData.Scan0 + (y * originalData.Stride);

//get the data from the new image
byte* nRow = (byte*)newData.Scan0 + (y * newData.Stride);

for (int x = 0; x < original.Width; x++)
{
//create the grayscale version
byte grayScale =
(byte)((oRow[x * pixelSize] * .11) + //B
(oRow[x * pixelSize + 1] * .59) +  //G
(oRow[x * pixelSize + 2] * .3)); //R

//set the new image’s pixel to the grayscale version
nRow[x * pixelSize] = grayScale; //B
nRow[x * pixelSize + 1] = grayScale; //G
nRow[x * pixelSize + 2] = grayScale; //R
}
}

//unlock the bitmaps
newBitmap.UnlockBits(newData);
original.UnlockBits(originalData);

return newBitmap;
}
}

EXPLANATION:

There’s a lot of code here so let’s go through it piece by piece. The first thing we need to do is lock the bits in the Bitmap objects. Locking the bits keeps the .NET runtime from moving them around in memory. This is important because we’re going to use a pointer, and if the data is moving around the pointer won’t point to the correct thing anymore. You’ll need to know the pixel format of the image you’re trying to convert. I’m using jpeg’s, which are 24 bits per pixel. There is a way to get the pixel format from an image, but that’s outside the scope of this tutorial. The integer, pixelSize, is the number of bytes per pixel in your original image. Since my images were 24 bits per pixel, that translates to 3 bytes per pixel.

To get pixel data, I start by getting the address to the first pixel in each row of the image. Scan0 returns the address of the first pixel in the image. So in order to get the address of the first pixel in the row, we have to add the number of bytes in the row, Stride, multiplied by the row number, y.

Below is a diagram that might help you understand this a little better.

1w

Now we can get color data straight from memory by accessing it like an array. The byte at x * pixelSize will be the blue, x * pixelSize + 1 is green, and x * pixelSize + 2 is red. This is why pixelSize is very important. If the image you provided is not 3 bytes per pixel, you’ll be pulling color data from the wrong location in memory.

Next, make the grayscale version using the same process as the previous method and set the exact same pixel in the new image. All that’s left to do is to unlock the bitmaps and return the new image.

That is it..!

 

 

Web Folder and Web Application

Web Folder:

Provides an interface for managing files on a remote Web server. Web folders provide document storage and publishing functionality.

A Web directory /web folder organizes Web sites by subject, and is usually maintained by humans instead of software. The searcher looks at sites organized in a series of categories and menus. These collections of links are usually much smaller than search engines’ databases, since the sites are looked at by human eyes instead of by spiders.

There are two ways for sites to be included in a Web directory’s listings; either the site owner can submit the site by hand, or the directory’s editor(s) will eventually come across that site.

 Web Application:

A web application is any application that uses a web browser as a client.A virtual server that resides on an HTTP server but appears to the user as a separate HTTP server. Several Web applications can reside on one computer, each capable of running its own programs and each having individualized access to input and peripheral devices. Each Web application can have its own domain name and IP address.

Web applications commonly use a combination of server-side script (ASP, PHP, etc) and client-side script (HTML, Javascript, etc.) to develop the application. The client-side script deals with the presentation of the information while the server-side script deals with all the hard stuff like storing and retrieving the information.

Most web applications are based on the client-server architecture where the client enters information while the server stores and retrieves information. Internet mail is an example of this, with companies like Yahoo and MSN offering web-based email clients.

Create a Web Application (IIS):

1-Open IIS Manager. For information about opening IIS Manager from administrative tools.

a-

Untitled

b-

1

2-In the Connections pane, expand the Sites node.

2

3-Right-click the site for which you want to create an application, and click Add Application.

3

This window will appear after click on that :

4

  • In the Alias text box, type a value for the application URL, such as marketing. This value is used to access the application in a URL.
  • Click Select if you want to select a different application pool than the one listed in the Application pool box. In the Select Application Pool dialog box, select an application pool from the Application pool list and then click OK.
  • In the Physical path text box, type the physical path of the application’s folder, or click the browse button () to navigate the file system to find the folder.
  • Click OK.

Connectivity in Timetable for students in c#

Contents:-

1)    Introduction

2)    Background

3)    Select Data query

4)    Update Data query

5)    Insert Data Query

6)    Working

 

Introduction:

Timetable is the basic part of any institution. All the tasks are accomplished according to available timetable. It is very useful thing which prevent the system from clashing .And every member of the system goes through this scenario.

 

Background:

Basically timetable was programmed according to the needs of teacher and students i.e.at what time one is available. Connectivity was basically developed to connect the database of school timetable. In which timetable was made according to the available timings of teachers and updating and removing factor is possible, sql connection is made for further updating.

 

Working:

First of all in form 1 SqlConnection was developed to use the stored data. It is very essential because stored data can be utilized at any time .Big storage can be available at any time.

public partial class Form1 : Form

connection to database:

{

SqlConnection connection = new SqlConnection(@”Data Source=Home-pc\SQLEXPRESS;Initial Catalog=Time Table DB;Integrated Security=True”);

DataSet dataset = new DataSet();

SqlDataAdapter DataAdap = new SqlDataAdapter();

public Form1()

{

InitializeComponent();

}

 

private void Form1_Load(object sender, EventArgs e)

{

 

}

 

 

private void button1_Click(object sender, EventArgs e)

Insert Data into Teacher table:-

try

{

String ID = IDTextBox.Text;

int id = Convert.ToInt16(ID);

DataAdap.InsertCommand = new SqlCommand(“insert into Teacher (Teacher_ID,Teacher_FirstName,Teacher_LastName,Teacher_Phone,Teacher_Email)values(@TeacherID,@TeacherFirstName,@TeacherLastName,@TeacherPhone,@TeacherEmail)”, connection);

DataAdap.InsertCommand.Parameters.Add(“@TeacherID”, SqlDbType.Int).Value = id;

DataAdap.InsertCommand.Parameters.Add(“@TeacherFirstName”, SqlDbType.NVarChar, 50).Value = FirstNametextBox.Text;

DataAdap.InsertCommand.Parameters.Add(“@TeacherLastName”, SqlDbType.NVarChar, 50).Value = LastTextBox.Text;

DataAdap.InsertCommand.Parameters.Add(“@TeacherPhone”, SqlDbType.NVarChar, 50).Value = PhonetextBox.Text;

DataAdap.InsertCommand.Parameters.Add(“@TeacherEmail”, SqlDbType.NVarChar, 50).Value = EmailtextBox.Text;

DataAdap.InsertCommand.Parameters.Add(“@course”, SqlDbType.Int).Value = textBox1.Text;

connection.Open();

DataAdap.InsertCommand.ExecuteNonQuery();

connection.Close();

 

}

 

For Exception Case:-

catch

{

MessageBox.Show(“Error”);

}

Description:-

If there is an exception then data will be inserting through finally code.

finally

{

DataAdap.InsertCommand.Dispose();

}

SqlCommand Command = new SqlCommand(“DisplayTeacherRecord”, connection);

Command.CommandType = CommandType.StoredProcedure;

Command.Parameters.Add(“@TeacherID”, SqlDbType.Int).Value =id;

Command.Parameters.Add(“@TeacherFirstName”, SqlDbType.NVarChar, 50).Value = FirstNametextBox.Text;

Command.Parameters.Add(“@TeacherLastName”, SqlDbType.NVarChar, 50).Value = LastTextBox.Text;

Command.Parameters.Add(“@TeacherPhone”, SqlDbType.NVarChar, 50).Value = PhonetextBox.Text;

Command.Parameters.Add(“@TeacherEmail”, SqlDbType.NVarChar, 50).Value = EmailtextBox.Text;

MessageBox.Show(“Enter Successfully”);

}

 

private void textBox1_TextChanged(object sender, EventArgs e)

{

 

}

 

private void button1_Click_1(object sender, EventArgs e)

{

function();

}

 

 

For updating Data:-

The data which is present after running will show data and it will show updating data after clearing previous data via grid view.

 

private void button2_Click(object sender, EventArgs e)

{

dataGridView1.ClearSelection ();

String ID = IDTextBox.Text;

int id = Convert.ToInt16(ID);

DataAdap.UpdateCommand = new SqlCommand (“Update Teacher SET Teacher_FirstName=@TeacherFirst,Teacher_LastName=@TeacherLast,Teacher_Phone=@TeacherPhone,Teacher_Email=@TeacherEmail,Course_ID=@course where Teacher_ID=@TeacherID”, connection);

DataAdap.UpdateCommand.Parameters.Add(“@TeacherID”, SqlDbType.Int).Value = id;

DataAdap.UpdateCommand.Parameters.Add(“@TeacherFirst”, SqlDbType.NVarChar, 50).Value = FirstNametextBox.Text;

DataAdap.UpdateCommand.Parameters.Add(“@TeacherLast”, SqlDbType.NVarChar, 50).Value = LastTextBox.Text;

DataAdap.UpdateCommand.Parameters.Add(“@TeacherPhone”, SqlDbType.NVarChar, 50).Value = PhonetextBox.Text;

DataAdap.UpdateCommand.Parameters.Add(“@TeacherEmail”, SqlDbType.NVarChar, 50).Value = EmailtextBox.Text;

DataAdap.UpdateCommand.Parameters.Add(“@course”, SqlDbType.Int).Value = textBox1.Text;

connection.Open();

DataAdap.UpdateCommand.ExecuteNonQuery();

connection.Close();

function();

DataAdap.UpdateCommand.Dispose();

 

}

 

Select data query:

 

public void function()

{

DataAdap.SelectCommand = new SqlCommand(“select * from Teacher”, connection);

DataAdap.Fill(dataset);

dataGridView1.DataSource = dataset.Tables[0];

connection.Open();

DataAdap.SelectCommand.ExecuteNonQuery();

connection.Close();

 

DataAdap.SelectCommand.Dispose();

}}

Gmail Auto Login Form

INTRODUCTION

It is easy to use the visual studio tool and the C# language. The C# language is easy and helpful in making the good project. This article is about the how to make Gmail SignUp Form.

Back gourd.

Gmail is used by the people for many years. It help peoples to communicate with eachother and to transfer the data.

The code follows the latest standards of C# language and is very easy to use.

Code:

<Doctype!>

<html>

<body>

<form>

<p> Name:</p>

<input type=”text” name=”firstname”> <input type=”text” name=”lastname”><br>

Create a Password: <br><input type=”password” name=”pwd”><br>

Confirm a Password: <br><input type=”password” name=”pwd”><br>

Your Birthday: <br><input type=”text” birthday=”month/date/year”><br>

<p>Gender: </p>

<input type=”radio” name=”sex” value=”male”>Male<br>

<input type=”radio” name=”sex” value=”female”>Female<br>

<form name=”input” action=”html_form_action.asp” method=”get”>

Your  current email address: <input type=”text” name=”user”><br>

<input type=”submit” value=”Submit”>

</form>

</body>

</html>

Explanation of Code:

The code shows the check boxes and radio buttons used in Gmail login form.

<Doctype!>

<html>

<body>

<form>

<p> Name:</p>

<input type=”text” name=”firstname”> <input type=”text” name=”lastname”><br>

This line of code makes a checbox for full name.

 

Create a Password: <br><input type=”password” name=”pwd”><br>

Confirm a Password: <br><input type=”password” name=”pwd”><br>

This line of code shows the password checkboxes.

 

Your Birthday: <br><input type=”text” birthday=”month/date/year”><br>

This line of code shows the birthday checkboxes .

 

<p>Gender: </p>

<input type=”radio” name=”sex” value=”male”>Male<br>

<input type=”radio” name=”sex” value=”female”>Female<br>

This line of code shows the radio buttons for the Gender.

 

 

<form name=”input” action=”html_form_action.asp” method=”get”>

Your  current email address: <input type=”text” name=”user”><br>

<input type=”submit” value=”Submit”>

</form>

</body>

</html>

This line of code shows the checkbox for your current email address and the submit checkbox which sends the data to the server for data storage.

RDLC Report


: RDLC Report : !
By::Numera Pervaiz

Introduction:This is my first article. In this article, I demonstrate how to create a rdlc report using Visual Studio 2010.  This article is deliberately written with the beginner in mind, hence it is rather lengthy as I try to explain in detail what to do, so I apologize if you find it slow-going.

Requirements:

Rdlc reports had to be able to do the following:

  • Be 100% standalone and capable of being accessed in code only i.e. there should be need to add the .rdlc file to your Visual Studio project.
  • Our current production report run tables that have multiple SELECT statements in them. These return a single dataset containing multiple tables. If ds is our dataset, then we get back ds.Tables[0] ds.Tables[1], ds.Tables[2] etc.

Prerequisites:

To use the following technique that I am about to describe you should make sure you meet the following prerequisites:

  • Visual Studio 2010 on your local pc.
  • SQL 2008R2 Management Studio (database) installed on your local pc.

Add a new rdlc file to your Visual Studio Project:

This can b done dynamically. Now we need to add a rdlc report to the project so we can design our report.In the Solution Explorer window single right-click the project name and select Add /New Item.From the templates displayed select report and change the name at the bottom to Report1 rdlc

Dataset

Right click on Application select Add, and again select New Item.

1

Select dataset and give dataset name (Sales Person) and click Add button.

2

Order dataset is prepared in Solution Explorer. Right click on Dataset and select Open.

3

Dataset Designer window is display. In that window right click select add and select Table Adapter.

4

 

5

Select Report Wizard,Give Report Name(Report1) Click Add.

6

In Solution Explorer Report is generated with the name as Report1 in Reports folder.

Report Wizard window Display.

  • Name: Give Dataset name (DataSet1).
  • Data Source : Select Data Source (SalesPerson)
  • Available Datasets :  select  (SalesPersonTable)

Report:

The basic approach will be to add a rdlc file to our Visual Studio project called Report.rdlc, merely so that we can get access to the designer, but when the report is finished it will be copied from the Visual Studio project location to the C:\Reports folder and then renamed to Report1.rdlc to prove absolutely that we are dealing with a standalone file. The project has no knowledge of a file called Report1.rdlc and this file is accessed in code only.

Code:

Dataset objds = new Dataset(“Dataset1″);

Sqlconnection objsqc = new sqlconnection (@”Data Soure =(Local);

Initial Catalog = AdventureWorks2008R2; Integrated Security = True;”);

Sql Command objsc = (“SalesOrder”, objsqc);

objsc.CommandType = CommandType.StoredProcedure;

SqlDataAdapter objadap = new SqlDataAdapter(objsc);

Objadap.Fill(objds);

Microsoft.Reporting.WinForms.ReportDataSource objrepds = new Microsoft.Reporting.WinForms.ReportDataSource (“DataSet1″ , objds.Tables[0]);

this.reportViewer1.LocalReport.DataSources.Clear();

this.reportViewer1.LocalReport.DataSources.Add(obj repds);

this.reportViewer1.RefreshReport();

this.reportViewer1.LocalReport.ReportPath = @”C:\PERVAIZ\4th Smester\Visual Programming\SqlReport\SqlReport\Report1.rdlc”;

this.reportViewer1.Visible = true;

If you installed SQL Server 2008R2 locally then your own pc is the server. Type in your computer name into the Server name.

Main form:

7

Report Contains Record:

After clicking the report1 button then it shows the complete record.

8

For More Help:

You can Visit this Site

Twitter Auto login

Author: Huma Baig (born July 4, 1992)

.Article:Twitter Auto Login

Web Enggineering

Marach 3, 7:30pm
Introduction

The article is based on how to auto login your account.  A simple program through which you can easily login your account automatically. When you run this program your account will be login. The code is written in C# language and is working properly.

It has your username and password when the program is compiled the username and password will checked if both are correct it will logged you in to your account.

The advantage is that  if both are correct it will logged you in to your account.

The advantage is that you no need to open your browser and also no need to open your account it works automatically.

Background

The twitter and face book now a days used a lot with this program your time will be save a lot. The C# language is used to develop large and useful projects. In this case the C# language is used it is very easy to learn and understand.

Code

class Twitter

{

 

public HtmlDocument ObjHTMLDocument = null;

public string homeURL = “https://www.twitter.com”;

public string currentURL = “”;

 

public Twitter()

{

 

}

 

public bool IsLogin()

{

 

HtmlElementCollection collection = ObjHTMLDocument.GetElementsByTagName(“input”);

 

try

{

foreach (HtmlElement eInput in collection)

{

if (eInput.GetAttribute(“class”).Equals(“js-signout-button”))

{

return true;

 

}

 

}

 

return false;

 

}

catch (Exception eObj)

{

MessageBox.Show(eObj.Message + “in isLogin”);

return false;

}

 

 

}

 

 

 

public int GetCase()

{

 

if (IsLogin() == false)

{

return 1;

}

else if (currentURL.Equals(homeURL))

{

return 2;

}

else

return 3;

}

 

 

 

 

 

 

public void login()

{

 

 

HtmlElementCollection theElementCollection;

 

theElementCollection = ObjHTMLDocument.GetElementsByTagName(“input”);

 

 

foreach (HtmlElement curElement in theElementCollection)

{

 

if ((curElement.GetAttribute(“name”).Equals(“session[username_or_email]”)))

{

 

 

curElement.SetAttribute(“value”, “katrinaa5”);

}

else if ((curElement.GetAttribute(“name”).Equals(“session[password]”)))

{

curElement.SetAttribute(“value”, “project”);

}

 

 

 

if (curElement.GetAttribute(“value”).Equals(“Sign in”))

{

curElement.InvokeMember(“click”);

 

}

}

}

The above shows that first code go to the twitter site and then check the username and password. If the username and password exists then it opens the account if not available then it show an error.

This is the simple program which helps in auto login to the account.

HOSTING A WCF SERVICE

 

HOSTING A WCF SERVICE

Introduction

 

In this article we will see how we can host a WCF service. We will look at various ways a WCF service can be hosted and what are the benefits and drawbacks of each hosting method. We will also create a sample client application that will consume the WCF service hosted in different ways.

 

Background

 

This article assumes that reader has some basic knowledge of WCF services. Please refer to the following article to get a refresher on WCF in case it is needed: A Beginner’s Tutorial for Understanding Windows Communication Foundation (WCF)

 

In a service oriented architecture the standalone service is of no use unless it is exposed to the client. To expose a service to the client it needs to be hosted somewhere. By hosting we not only mean a server for hosting but also the application that will host the service as a part of itself.

 

Traditional web services were hosted on IIS. This approach has a lot of benefits which includes not worrying about the creation and disposal of service, On demand availability of web services etc. But this approach has one major drawback i.e. protocols other than HTTP are not supported.

 

WCF comes with the possibility of being invoked and used by protocols other than HTTP. So along with IIS, WCF can also be hosted in different ways so that its full power can be utilized(if required).

 

A WCF service can be hosted in following ways:

 

  1. Hosting in Internet Information Services(IIS).
  2. Hosting in Windows Activation Services(WAS).
  3. Hosting in a Console or Desktop application(Self hosting).
  4. Hosting in a Windows Service.

 

Every method of hosting comes with its own benefits and drawbacks. Let us see each the theory behind each hosting method one by one.

 

Hosting a WCF service in IIS is perhaps the easiest method. It is straight forward process for the developers who are familiar with ASP.NET websites and ASMX web services because the WCF service is also hosted in IIS in similar manner. Also, IIS takes care of creation of service instances, disposal of service instances, recycling and other activities that it does for ASP.NET website. It treats a WCF service like an ASP.NET website and provides all the features of having multiple request handling and dynamic compilation to a WCF service out of the box.

 

if we are using IIS6 or previous version then the major drawback of IIS6.0 hosting is that only HTTP/HTTPS protocol can be used to communicate with the service. Which actually is sufficient for most of the project but if the project needs to communicate to the service using other protocols then this IIS6.0 hosting will not suffice.

 

Now the point to notice in the above text is that I specifically mentioned IIS 6.0 or previous. The reason for this is that IIS 7.0 comes with a feature/component called Windows Activation Service(WAS). So hosting a WCF service in WAS and IIS 7.0 are actually not exclusive. TO host a WCF service using WAS, we need to still host the service in IIS 7.0 and then enable the support for protocols other than HTTP/HTTPS. Hosting in WAS comes with all the benefits of hosting in IIS and on top of that it supports all the protocols too.

 

Now the next process of hosting i.e. self hosting has the major benefits of providing us full control i.e. All the control of starting the service, stopping the service and error handling/logging can be done in our host application. The amount of code that needs to be written to self host a WCF service is very small and it is very easy too. Now the decision for chooing self hosting is purely on the requirements of whether or not you want so much control on the service.

 

Finally, Hosting the service in a windows service is same as self hosting but the service creation and disposing will be abstracted in form of a Windows service. It provides the same capabilities as a self hosted service provides and the decision of whether to use this method or not will rely on the same factors of whether or not you want so much control on the service.

 

Using the code

 

Now that we know the various methods of hosting a WCF service, we can say that if we know how to host a WCF service in IIS, we can make some changes on top of that and host it in WAS too. Similarly, If we understand how to self host a service, we can create a windows service host with the same process.

 

Now in the rest of the article, our focus will be to create a sample service and see how we can host it in IIS and how we can self host it. Then we will touch upon the steps that are needed to host the service on WAS and inside a windows service.

 

Note: Only IIS hosting and self hosting are discussed in detail in rest of the article because these are the most commonly used methods of hosting and other hosting process will be similar but they have some additional steps.

 

Creating the Service Library

 

We can always keep the service code in the host application (in case of self hosting) or inside an ASP.NET website(IIS hosting) but it is always a good idea to have the WCF service in a class library. That way we decouple the service implementation from its host application. Also, we can have a single WCF service and multiple host applications hosting that service.

 

Let us create a simple WCF service library that will take the users name in form of a DataContract and then return him a greeting message from the service. Let us start by creating a simple WCF Service library.


In this service we create a simple DataContract called Person which will keep the user Name.

 

 Collapse | Copy Code

 

[DataContract]
public class Person
{
    [DataMember]
    public string Name { get; set; }
}

 

Now we will have a very simple single method ServiceContract that will take the Person and return a string with containing the greeting message.

 

 Collapse | Copy Code

 

[ServiceContract]
public interface ISampleService
{
    [OperationContract]
    string GreetMe(Person person);
}

 

Finally, we will create the class that will implement the service contract.

 

 Collapse | Copy Code

 

public class SampleService : ISampleService
{
    public string GreetMe(Person person)
    {
        return string.Format("Greetings from Sample service Mr. {0}", person.Name);
    }
}

 

Now we have a very simple toy service ready to play with. To check the working of the service we can simply run the WCF service library project. By doing this a WCF Test Client will open up using which we can test the working of our service. This tool can be used to test the calls to the service and response from the service.


Now one question we should ask is how this service started running without configuring any endpoints. Actually when we create a WCF service library some default configuration with endpointsaddress and Bindings get created in the library’s App.config file.

 

 Collapse | Copy Code

 

<service name="SampleServiceNamespace.SampleService">
    <endpoint address="" binding="wsHttpBinding" contract="SampleServiceNamespace.ISampleService"> 
</endpoint>

 

Now this configuration will be used when we try to run a service library and Visual studio will take care of hosting this service for us for testing purpose. The important point here is that when we host this service ourselves then thisApp.config configuration will be of no use. The host application will have to define its own endpoints and specify theAddressBinding and Contracts separately.

 

Note: The configuration section shown above is not complete. Please refer to the sample code to see the completeApp.config file.

 

Hosting the Service in IIS

 

Now that we have our service ready with us let us go and see how we can host this service in IIS. For this let us go and create a new website specifically WCF Service website.


Now this website comes with its own predefined service template but we are not going to use them so we will delete all of them and then add a reference to our service library project in this website.

 

Once we have the reference to our service library added, its time to create a service and configure endpoints with required addressbinding and contracts. Since we will host this website in the IIS, the address of the .SVC file will become the address of the Service. Now the binding used by default when we try to host a service in IIS isbasicHttpBinding. And for the contract part, we need to specify the contract that should be used from our service library. This can be done by changing the SVC file and pointing the SVC file to the right service implementation.

 

 Collapse | Copy Code

 

<%@ ServiceHost Language="C#" Debug="true" Service="SampleServiceNamespace.SampleService"%>

 

And this will suffice for the service to run within IIS. If we configure this website in IIS and run the .svc file the service will start running hosted in the IIS.


Now we have a service hosted on IIS and it is running. We will see how we can consume this IIS hosted service later in this article.

 

Self Hosting the Service

 

To self host the service let us create a simple Console application that will host the service, open the service and close the service. Let us start by having a simple console application.

 

Once the console application is created, let us add the reference to the Service library into this application. Along with the reference of service library, we also have to add reference to System.ServiceModal andSystem.Runtime.Serialization in this project to get it to work with WCF hosting process.

 

Now we have the service library added in this project along with all other required references. Now we have to define the endpointsaddressbinding and contracts for this service. This can be done either declarative (via configuration file) or imperatively(via code). Let us do it declarative by having the service configured in theapp.config file.

 

 Collapse | Copy Code

 

<services>
    <service name="SampleServiceNamespace.SampleService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration=""
            contract="SampleServiceNamespace.ISampleService" />       
        <host>
            <baseAddresses>
                <add baseAddress="http://localhost/SelfHostedServiceConsole" />
            </baseAddresses>
        </host>
    </service>
</services>

 

We configured this service to use HTTP protocol with basicHttpBinding. The address of the service ishttp://localhost/SelfHostedServiceConsole and the contract is specified as the service contract from our service library i.e. SampleServiceNamespace.ISampleService

 

Note: I really recommend using the “Edit WCF Configuration Tool” that comes with Visual studio(right click the app.config file). This really makes the declarative configuration of WCF service very easy.

 

Now that we have specified the ABC of this service and exposed an endpoint, its time to see how we can host the service. To host the service and open the service host we need to use the ServiceHost class. below code shows how the service can be hosted using the endpoints defined in the above config file.

 

 Collapse | Copy Code

 

using (ServiceHost host = new ServiceHost(typeof(SampleServiceNamespace.SampleService)))
{
    host.Open();

    Console.WriteLine("Service up and running at:");
    foreach (var ea in host.Description.Endpoints)
    {
        Console.WriteLine(ea.Address);
    }

    Console.ReadLine();
    host.Close();
}

 

And when we run the host:


To check the self hosted service, Let us start the host and then type the address in the browser.


And this confirms that the service has been hosted successfully.

 

Consuming the WCF service

 

Let us now go ahead and create a simple Console application to test these two services. First let us create a simple console application. Once we have the console application created, let us add two service reference to it. One for the IIS hosted service and other for the self hosted service.

 

Note: To add the IIS hosted service reference, use the address of the .svc file and to add the reference of self hosted service, use the address specified in the config file of self hosting console. Also, make sure that the hosting console application is running while adding the service reference.


Once we add the service reference the client side endpoints have already been configured in the app.config file. For now we will use this configurations only. Adding the service reference also created the proxy classes for the service. So let us see how we can use these proxy classes to call our IIS hosted and Self hosted WCF service.

 

 Collapse | Copy Code

 

static void Main(string[] args)
{
    // Using the IIS hosted service
    Console.WriteLine("Using the IIS hosted service");
    using (IISHostedService.SampleServiceClient client = new IISHostedService.SampleServiceClient())
    {
        IISHostedService.Person p = new IISHostedService.Person { Name = "Rahul" };
        Console.WriteLine(client.GreetMe(p));
    }

    Console.WriteLine();

    // Using the Self hosted service
    Console.WriteLine("Using the Self hosted service");
    using (SelfHostedService.SampleServiceClient client = new SelfHostedService.SampleServiceClient())
    {
        SelfHostedService.Person p = new SelfHostedService.Person { Name = "Rahul" };
        Console.WriteLine(client.GreetMe(p));
    }

    Console.ReadLine();
}

 

And when we run the application


And this shows us that both our IIS hosted and self hosted services are running.

 

Point of interest

 

In this article, we started our discussion with the various possible ways of hosting a WCF service. We saw how to host a service in IIS and how to self host a service. We have not touched the WAS hosting and Hosting inside a Windows service but these processes will require something additional to be done on top of IIS hosting and self hosting respectively. Since WAS and Windows service knowledge will automatically let the user know how and what additional needs to be done, I skipped these two methods from this article(otherwise the article would have become digressing).

 

Also, I used basic HTTP binding and default behaviors for all demos because the intention of the article was to talk about hosting the WCF service. But these things can easily be tweaked in the hosts and clients (proved they conform to hosting environments capabilities). This article was written from a perspective of beginner’s in WCF. I hope this has been informative.

BY SHAHZAD (038-BSCS-2010) Section B

online admission system

Online Admission System

Applicant must login into his account in order to view his status regarding admission process.
After successful login he can view the following information:New Picture (1)

 

In this area applicant can see the information about the following:
 Result card submission.
 Verification of the given information.
 Merit calculator.
 Enrolled or not.

Twitter auto update

Author: Hussnain Butt (born June 21, 1991)
.Atricle: Twitter Auto Update Web Enggineering

March,3 9:54pm
INTRODUCTION

It is easy to use the visual studio tool and the C# language. The C# language is easy and helpful in making the good project. This article is about the how to make twitter intelligent for auto status updating with the time.

Like if it is morning time from 8a.m to 10a.m the twitter auto update as “Good Morning”. If the time is after 11p.m to 2p.m it update “Good Afternoon” and if the time is between the 4p.m to 6p.m it will say “Good Evening” and finally from 8p.m to 10p.m it will say “Good Night”.

Back gourd.

Twitter is used by the people for many years. Some people have craze to update their status at every moment. So considering this craze there is a solution for automatic updating the status.

You have to just run this program and no need for writing. The program is written in simple C# language.

The code follows the latest standards of C# language and is very easy to use.

Auto keyword:

This feature is introduced in a effort to make C# a more usable language. The committee have given a new meaning for the ‘auto’ keyword [just to remind the readers that the old auto keyword is used to declare a variable having local scope and all local variables if their storage class is not specified as static, extern or register are implicitly converted to auto storage-class specifier.

Code.

Random r = new Random();

int i = r.Next(0, 7);

DateTime t2 = Convert.ToDateTime((“8:00:00 AM”));

DateTime t3 = Convert.ToDateTime((“10:00:00 AM”));

 

if (t1.TimeOfDay.Ticks >= t2.TimeOfDay.Ticks && t1.TimeOfDay.Ticks <= t3.TimeOfDay.Ticks)

{

curElement.InnerText = “Good Morning :)”;

break;

}

else

{

DateTime t4 = Convert.ToDateTime((“11:00:00 AM”));

DateTime t5 = Convert.ToDateTime((“1:00:00 PM”));

if (t1.TimeOfDay.Ticks >= t4.TimeOfDay.Ticks && t1.TimeOfDay.Ticks <=                    t5.TimeOfDay.Ticks)

{

curElement.InnerText = “Good Afternoon :)”;

break;

}

else

{

DateTime t6 = Convert.ToDateTime((“2:00:00 PM”));

DateTime t7 = Convert.ToDateTime((“4:00:00 PM”));

if (t1.TimeOfDay.Ticks >= t6.TimeOfDay.Ticks && t1.TimeOfDay.Ticks      <= t7.TimeOfDay.Ticks)

{

curElement.InnerText = “Good Evening :)”;

break;

}

else

{

DateTime t8 = Convert.ToDateTime((“5:00:00 PM”));

DateTime t9 = Convert.ToDateTime((“10:00:00 PM”));

if (t1.TimeOfDay.Ticks >= t8.TimeOfDay.Ticks && t1.TimeOfDay.Ticks <= t9.TimeOfDay.Ticks)

{

curElement.InnerText = “Good Night :)”;

break;

}

else

{

curElement.InnerText = str[i];

break;

}

Explanation of Code.

The code shows that the twitter if the time comes between the limits then it will convert the status in string and update as Good Morning if the time is not in the limits then break the condition.

DateTime t2 = Convert.ToDateTime((“8:00:00 AM”));

DateTime t3 = Convert.ToDateTime((“10:00:00 AM”));

if (t1.TimeOfDay.Ticks >= t2.TimeOfDay.Ticks && t1.TimeOfDay.Ticks <= t3.TimeOfDay.Ticks)

{

curElement.InnerText = “Good Morning :)”;

break;

}

The code below convert the time to the message in the string which passes the good after noon when time comes between the limit it will update the msg.

DateTime t4 = Convert.ToDateTime((“11:00:00 AM”));

DateTime t5 = Convert.ToDateTime((“1:00:00 PM”));

if (t1.TimeOfDay.Ticks >= t4.TimeOfDay.Ticks && t1.TimeOfDay.Ticks <= t5.TimeOfDay.Ticks)

{

curElement.InnerText = “Good Afternoon :)”;

break;

}

The following code will update as good evening.

DateTime t6 = Convert.ToDateTime((“2:00:00 PM”));

DateTime t7 = Convert.ToDateTime((“4:00:00 PM”));

if (t1.TimeOfDay.Ticks >= t6.TimeOfDay.Ticks && t1.TimeOfDay.Ticks <= t7.TimeOfDay.Ticks)

{

curElement.InnerText = “Good Evening :)”;

break;

}

When the time comes between the 2p.m to 4p.m then the status will upload otherwise it breaks.

DateTime t8 = Convert.ToDateTime((“5:00:00 PM”));

DateTime t9 = Convert.ToDateTime((“10:00:00 PM”));

 

if (t1.TimeOfDay.Ticks >= t8.TimeOfDay.Ticks && t1.TimeOfDay.Ticks <= t9.TimeOfDay.Ticks)

{

curElement.InnerText = “Good Night :)”;

break;

}

The last message for the good night when the time is between the 5-10 p.m the statys wil be Good Night.

This is the whole work which is done automatically. You just have to run this program once and the updating will be done automatically.

Thank you.