* Download SolutionSchoolTest.zip - 89.16 KB
Introduction
First of all, please accept my appologizes for my poor english :)
This article speak about creating entities proxy classes for your own need.
Problem
The proxy class generated from a ADO.Net Data Service is simple and only helps for standard CRUD scenarii. But as soon as you want to make something complex or special you will find some restrictions. If you need some features that do not exist inside this proxy you can write them by adding a new partial class to your project or use reflexion. You can make this easily to add some features such as a static method or a simple utility method. But if you have to make a feature shared between all your entities or something that depends on your entities semantics you won't be able to use this way.
You need to use an automatic generation of a proxy class that contains the features you need. That's the thing we will make here : create new set of partial classes to complete existing partial class of the proxy with our needs or create the whole set of proxy classes.
Our answer
In order to generate our own class we will have to read metadatas from the web data service.
The generation will use the msxsl.Exe tool from microsoft : it build a result from an xml and a xslt file. The "result" will be our proxy classes, the "xml" will be the $metadata result of the web data service and the "xslt" the job we have to make here.
Create the Data base
Very simple step. Microsoft offer some T-Sql scripts to generate a sample database. Go here to find it. Install the script to create to own base.
The Solution
We are not here to learn how to create those projects. So just download the zip gived with this article to get the entire solution. You will find in it :
* A web project with an ADO.net data service
* An entities project with an edmx.
* A client project.
gd01.png
In the solution directory i added a Tools directory where you can find the msxsl.exe tools.
gd02.png
Before launching the service we have to make a link between the edmx and the data base.
Inside the web.config file change the end of the connexion string to make a connection to the school database :
Collapse
provider=System.Data.SqlClient;provider connection string="Data Source=localhost\sqlexpress;
Initial Catalog=School;Integrated Security=True;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />
Start the web data service by right click on the WebDataService.svc file on the solution explorer and selecting "Open in Browser". You will see something like this :
gd03.png
Our service is ready.
Generation needs metadatas (xml part)
We need a Xml file that contains all informations about the entities of the school model and their relation. Just add the keyword $metadata to the end of the web data service url like this :
gd04.png
You see now a complete description of the school model :
Collapse
The proxy class will be generated from this xml.
The xslt file
The xslt file will generate the entities classes proxy. Here is the content of the xslt file :
Collapse
{
{
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string property)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(property));
}
}
#endregion
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
public
Even if you know absolutly nothing about xslt language you can read this file.You can find here all templates that match the nodes of the $metadata result of the web data service. You can change it very easlily.
Inside the properties of the client project select the generation event. Inside the pre build event you can see the following command :
$(SolutionDir)Tools\msxsl.exe http://localhost:3932/BackOfficeServices/WebDataService.svc/$metadata $(ProjectDir)EntitiesGeneratorXSLTFile.xslt -o $(ProjectDir)EntitiesCustom.cs
it call the msxsl.exe tool in order to generate a file named entitiescustom.cs from the transformation of our service with a specified xslt file. Each time you build the solution, the EntitiesCustom.cs file will be generated bu the msxsl.exe tool with the xml extracted from the $metadata response of the web data service and with the xslt seen before. You can begin this command with the "REM" keyword in order to comment the line.
The result (proxy classes)
The result if similar to the proxy class generated by Microsoft. I added some debugger attributes to clean the class aspect and some #region. Here is one of the entity class generated :
Collapse
#region class Course
[global::System.Serializable()]
[global::System.Data.Services.Common.DataServiceKeyAttribute("CourseID")]
public partial class Course : global::System.ComponentModel.INotifyPropertyChanged
{
#region Fields
[global::System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
private global::System.Int32 _CourseID;
[global::System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
private global::System.Int32 _Credits;
[global::System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
private global::System.String _Title;
[global::System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
private global::System.Collections.ObjectModel.Collection
new global::System.Collections.ObjectModel.Collection
[global::System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
private Department _Department;
[global::System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
private OnlineCourse _OnlineCourse;
[global::System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
private OnsiteCourse _OnsiteCourse;
[global::System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
private global::System.Collections.ObjectModel.Collection
new global::System.Collections.ObjectModel.Collection
#endregion //Fields
#region Properties
public global::System.Int32 CourseID
{
get
{
return this._CourseID;
}
set
{
if (this._CourseID != value)
{
this._CourseID = value;
this.OnPropertyChanged("CourseID");
}
}
}
public global::System.Int32 Credits
{
get
{
return this._Credits;
}
set
{
if (this._Credits != value)
{
this._Credits = value;
this.OnPropertyChanged("Credits");
}
}
}
public global::System.String Title
{
get
{
return this._Title;
}
set
{
if (this._Title != value)
{
this._Title = value;
this.OnPropertyChanged("Title");
}
}
}
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
public global::System.Collections.ObjectModel.Collection
{
get
{
return this._CourseGrade;
}
set
{
if (this._CourseGrade != value)
{
this._CourseGrade = value;
this.OnPropertyChanged("CourseGrade");
}
}
}
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
public Department Department
{
get
{
return this._Department;
}
set
{
if (this._Department != value)
{
this._Department = value;
this.OnPropertyChanged("Department");
}
}
}
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
public OnlineCourse OnlineCourse
{
get
{
return this._OnlineCourse;
}
set
{
if (this._OnlineCourse != value)
{
this._OnlineCourse = value;
this.OnPropertyChanged("OnlineCourse");
}
}
}
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
public OnsiteCourse OnsiteCourse
{
get
{
return this._OnsiteCourse;
}
set
{
if (this._OnsiteCourse != value)
{
this._OnsiteCourse = value;
this.OnPropertyChanged("OnsiteCourse");
}
}
}
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
public global::System.Collections.ObjectModel.Collection
{
get
{
return this._Person;
}
set
{
if (this._Person != value)
{
this._Person = value;
this.OnPropertyChanged("Person");
}
}
}
#endregion //Property
#region INotifyPropertyChanged Membres
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string property)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(property));
}
}
#endregion
}
#endregion //class
now we can test our proxy.
The test
We will try to retrieve a Person and change its name.
Here is the code added to the Program.cs file of the client side project.
Collapse
var query = from u in entities.Person
where u.LastName == "Abercrombie"
select u;
foreach (Person person in query)
{
Console.Out.WriteLine("A Person finded :");
Console.Out.WriteLine(string.Format("{0} {1}", person.FirstName, person.LastName));
Console.Out.WriteLine("Why not changing its name ?");
Console.Out.WriteLine("Please specifies a new first name :");
string firstName = Console.In.ReadLine();
person.FirstName = firstName;
entities.UpdateObject(person);
entities.SaveChanges();
Console.Out.WriteLine("New name saved");
}
gd06.png
Our proxy class works well !
Conclusion
With this way of doing you can easily add features to your entities classes and enjoy the ADO.Net data services. Just change the xslt and add your own features.
I did not test the xslt in a lot of scenarii. If there are some problem just ask me.->Read More...
Generate your own proxy for ADO.Net Data Services on client side
Người đăng: Orchid vào lúc 14:01 0 nhận xét
Nhãn: Web Services
Create A Web Service Method to Get NT Service Information
* Download source files - 2.5 KB
Introduction
Recently, I created a mobile application-Siccolo that allows me to manage SQL Servers by using Web services hosted on public domain (see more information here about how to develop a mobile management tool).
As part of a management tool, I needed to show some information about the selected NT Service, such as path to a service executable. For example, services.msc shows it like this:
In my mobile management tool, I needed to display in a similar manner:
The code presented retrieves information about Path to Executable for a selected NT Service.
Background
My "managing" Web service is hosted under SSL with "Integrated Windows" authentication being set. Therefore, a mobile application is required to pass network credentials. And this is needed to be able to remotely access to get information from the registry on the remote machine.
Using the Code
Components used:
* serviceprocessor.asmx.cs - Web service interface
* NTServiceInfo.cs - a small "wrapper" to retrieve NT Service information
.NET provides just the tool for this task - System.ServiceProcess.ServiceController class. To create an instance of System.ServiceProcess.ServiceController:
Collapse
// C# //
...
System.ServiceProcess.ServiceController Service;
if (this.m_MachineName!="")
{Service = new ServiceController(this.m_ServiceName, this.m_MachineName ) ;}
else
{Service = new ServiceController(this.m_ServiceName ) ;}
...
The fact that authentication (Integrated Windows authentication or Basic) is in place on IIS, actually helps here. In order to be able to access service(s) on a different machine than Web service host, Web service needs to "assume" an identity of authenticated user. Normally, Web service is running under ASP.NET user with minimum privileges and I needed to impersonate authenticated user with the Web service.
On the server side, to retrieve an authenticated user, we need to use System.Web.Services.WebService.User and then impersonate: and code does just that - "Impersonates the user represented by the WindowsIdentity object."
Collapse
// C# //
...
System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext =
((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
...
To retrieve the path to the executable, we can look under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services, find the selected service, and get ImagePath:
To read the value of a registry key (on the remote machine, or on the local machine):
Collapse
private string ReadRegestryKey(string RegistryKey, out string ErrorInfo)
{
try
{
string Value="";
ErrorInfo ="";
RegistryKey Key;
RegistryKey KeyHKLM = Registry.LocalMachine;
try
{
if (this.m_MachineName !="" ) //open on remote machine
Key = Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(
RegistryHive.LocalMachine, this.m_MachineName
).OpenSubKey(RegistryKey);
else
Key = KeyHKLM.OpenSubKey(RegistryKey);
Value = Key.GetValue("ImagePath").ToString();
Key.Close();
}
catch (Exception ex_open_key)
{
ErrorInfo = "Error Accessing Registry [" + ex_open_key.ToString() + "]";
return "";
}
return Value;
}
catch (Exception ex_read_registry)
{
ErrorInfo = ex_read_registry.Message;
return "";
}
}
Once the path to the executable is extracted, we need to check if the path needs to be "extracted" from something like %SystemRoot%\system32\... to the actual path.
Value of %SystemRoot% can be found in the registry:
Collapse
private string ExpandEnvironmentString(string Path)
{
string SystemRootKey = "Software\\Microsoft\\Windows NT\\CurrentVersion\\";
RegistryKey Key;
if (this.m_MachineName !="" )
Key = Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(
RegistryHive.LocalMachine, this.m_MachineName
).OpenSubKey(SystemRootKey);
else
Key = Registry.LocalMachine.OpenSubKey(SystemRootKey);
string ExpandedSystemRoot ="";
ExpandedSystemRoot = Key.GetValue("SystemRoot").ToString();
Key.Close();
Path = Path.Replace ("%SystemRoot%", ExpandedSystemRoot);
return Path;
}
Finally:
Collapse
public string PathToExecutable(WindowsPrincipal User)
{
//HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services.
string RegistryKey = "SYSTEM\\CurrentControlSet\\Services\\" +
this.m_ServiceName;
string ErrorInfo="";
System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext =
((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
string Path= this.ReadRegestryKey(RegistryKey, out ErrorInfo);
if ( Path.IndexOf("%")>0)
{
Path = ExpandEnvironmentString(Path);
}
impersonationContext.Undo();
return Path;
}
Notice, how the calls to ReadRegestryKey() and ExpandEnvironmentString() are "wrapped in" :
Collapse
impersonationContext =
((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
...
...
impersonationContext.Undo();
Then, the actual Web method:
Collapse
[WebMethod]
public bool GetNTServiceInfo(string RemoteServerAddress ,
string NTServiceName,
out string ServiceInfo_XML ,
out string ErrorInfo )
{
try
{
string ToDebugSetting
= System.Configuration.ConfigurationSettings.AppSettings.Get("DebugMode");
bool ToDebug = (ToDebugSetting!="");
ErrorInfo="";
ServiceInfo_XML ="";
System.ServiceProcess.ServiceController Service;
if (RemoteServerAddress!="")
{Service = new ServiceController(NTServiceName, RemoteServerAddress ) ;}
else
{Service = new ServiceController(NTServiceName ) ;}
DataSet objDataSet = new DataSet("QueryResults");
objDataSet.Tables.Add("ServiceInfo");
objDataSet.Tables[0].Columns.Add("service_display_name",
System.Type.GetType("System.String"));
objDataSet.Tables[0].Columns.Add("status",
System.Type.GetType("System.String"));
objDataSet.Tables[0].Columns.Add("service_name",
System.Type.GetType("System.String"));
objDataSet.Tables[0].Columns.Add("path_to_executable",
System.Type.GetType("System.String"));
objDataSet.Tables[0].Columns.Add("can_stop",
System.Type.GetType("System.Boolean"));
objDataSet.Tables[0].Columns.Add("can_pause_and_continue",
System.Type.GetType("System.Boolean"));
objDataSet.Tables[0].Columns.Add("services_depend_on",
System.Type.GetType("System.String"));
objDataSet.Tables[0].Columns.Add("dependent_services",
System.Type.GetType("System.String"));
NTServiceInfo si = new NTServiceInfo(NTServiceName,
RemoteServerAddress);
Object[] r = new Object[8] {Service.DisplayName,
Service.Status.ToString(),
Service.ServiceName,
si.PathToExecutable((WindowsPrincipal) this.User),
Service.CanStop.ToString(),
Service.CanPauseAndContinue.ToString(),
si.ServiceDependOnStringList(Service.ServicesDependedOn),
si.DependentServicesStringList(Service.DependentServices)
};
objDataSet.Tables[0].Rows.Add(r);
Service.Close();
System.IO.StringWriter objStringWriter =new System.IO.StringWriter();
objDataSet.WriteXml(objStringWriter, XmlWriteMode.WriteSchema);
ServiceInfo_XML = "" + objStringWriter.ToString();
ErrorInfo = "";
return true;
}
catch (Exception ex_get_service_info)
{
ServiceInfo_XML ="";
ErrorInfo = ex_get_service_info.Message;
return false;
}
}
Points of Interest
If you would like to read more on this story, please take a look at Siccolo - Free Mobile Management Tool For SQL Server and full article at How to Develop Mobile Management Tool.->Read More...
Người đăng: Orchid vào lúc 13:57 0 nhận xét
Nhãn: Web Services
Calling web service using ASP.NET
Introduction
Web Services signal a new age of trivial distributed application development. While Web Services are not intended nor do they have the power to solve every distributed application problem, they are an easy way to create and consume services over the Internet. One of the design goals for Web Services is to allow companies and developers to share services with other companies in a simple way over the Internet.
Web services take Web applications to the next level.
Using Web services your application can publish its function or message to the rest of the world.
Web services use XML to code and decode your data and SOAP to transport it using open protocols.
With Web services your accounting departments Win 2k servers billing system can connect with your IT suppliers UNIX server.
Using Web services you can exchange data between different applications and different platforms.
With Microsoft .Net platform it is a simple task to create and consume Web Services. In this article am going to show how to call a published web services inside a web project.
I use a test published web services; Extentrix Web Services 2.0 Application Edition (http://www.extentrix.com/webservices/2.0.0/ExtentrixWebServicesForCPS.asmx) that Extentrix published for the developer community to help them in testing and developing.
So I’ll explain simply the functions of this web services APIs. In general Extentrix Web Services for Citrix Presentation Server helps you get information about a published application for a specific client with the specified details, server types, and client types. It also returns the
For more information, visit http://www.extentrix.com/Web%20Services/Index.htm
You can find more samples, use this web services, and test it on http://www.extentrix.com/Web%20Services/Test%20Drive.htm?id=6
Background
Knowledge in ASP.NET is preferred
Using the code
Simple Steps to consume web service:
- Create Web Site project
- Add web Reference
- Call the web services APIs inside the code
First Step: Create Web Site project
1. To create new Web Site project, choose New from File menu, then choose Web Site as shown below.
2. Choose ASP.NET Web Site. Name the project and click OK
Second Step: Add web Reference
After creating the Web Site project, it’s time to add a web reference for our web service.
1. In the solution explorer, right click the project node, choose Add Web Reference
2. A new window with Add Web Reference title will be opened.
In the URL field, insert the URL for the web service. In this tutorial as I mentioned before I’ll use the test published web services form Extentrix. “Extentrix Web Services 2.0 – Application Edition”
http://www.extentrix.com/webservices/2.0.0/ExtentrixWebServicesForCPS.asmx
After clicking the Go button you will see the web services APIs.
3. Set a name for your web service reference in the web reference name field and click Add Reference
Third Step: Call the web services APIs inside the code
After a successful adding to the web service, now we are ready to call the web services APIs inside our project.
1. First we need to add the added web reference to our class.
“ExtentrixWS” is the name of the added web service from the previous step.
using ExtentrixWS; 2. Create a proxy object for our added web service reference, where the ExtentrixWebServicesForCPS is the name of the Web Services
//define a web service proxy object.
private ExtentrixWS.ExtentrixWebServicesForCPS proxy;
3. As I explained before we need credentials to pass to Citrix Presentation Server, we will pass these credentials through the web services APIs
//define a Citrix Presentation Server Credentials object
private Credentials credentials;
Initialize the proxy and the credentials objects
//intialaize objects
proxy = new ExtentrixWebServicesForCPS();
credentials = new Credentials();
4. Set the values for Citrix credentials. I set the credentials values for the test of Extentrix Web Service.
//set credentials
//these values are according to Citrix testdrive presentation server
//for which Extentrix published a web service for delovepers to use it
//as a test web service.
credentials.Password = "demo";
credentials.UserName = "citrixdesktop";
credentials.Domain = "testdrive";
//because it is a sample,we will use no encryption method.
//so the password will be sent as a clear text.
credentials.PasswordEncryptionMethod = 0;
//set the domain type to windows domain
credentials.DomainType = 0;
Now we can call any web services available as simple as calling any ordinary function.
5. Call the GetApplicationsByCredentialsEx web service. This web service takes the following parameters:
- Credentials: Citrix Credential to access Citrix Presentation Server Farm.
- Client Name: pass your machine name
- Client IP: pass your machine IP
- Desired Details : what the details you asked for
- Server Types: pass “all”
- Client Types: pass “all”
Am not going to explain Extentrix web services APIs, if you are interested you can go to http://www.extentrix.com/Web%20Services/Index.htm and look for it.
This API returns an array of ApplicationItemEx, this class will be built for you once you add the web reference.
This class contains the published application properties. I used this web service to get all the published applications, and then I created an ImageButton for each application.
// 1) Get all the published applications list by calling GetApplicationsByCredentialsEx web service.
// 2) create an ImageButton for each application
// 3) Create Image for the application
// 4) Add it to the AppList panel.
// 5) Set the event handler for each ImageButton, so when clicking it the associated application will run
//calling the web service
ApplicationItemEx[] items = proxy.GetApplicationsByCredentialsEx(credentials, Request.UserHostName,
Request.UserHostAddress, new string[] { "icon","icon-info"}, new string[]{ "all" },
new string[] { "all"});
//loop for each published application
for (int i = 0; i < items.Length; i++) {
//create the ImageButton
System.Web.UI.WebControls.ImageButton app = new System.Web.UI.WebControls.ImageButton();
//set the Image URL to the created image
app.ImageUrl = createIcon(items[i].InternalName,items[i].Icon);
//set the ToolTip to the name of the published application
app.ToolTip = items[i].InternalName;
//add the ImageButton to the AppList panel
AppList.Controls.Add(app);
//set the event handler for the ImageButton.
app.Click += new
System.Web.UI.ImageClickEventHandler(this.OnApplicationClicked);
}
Finally another example in calling web service is to launch the published application.
In this example, in the event handler of the applications ImageButtons I launch the clicked application.
I get the
Then I write the
private
void OnApplicationClicked (object
sender, System.EventArgs e)
{
ServicePointManager.Expect100Continue = false;
// Get the event source object.
System.Web.UI.WebControls.ImageButton app = (System.Web.UI.WebControls.ImageButton)sender;
//Get the file ICAfile content by calling LaunchApplication web service.
string ica = proxy.LaunchApplication(app.ToolTip, credentials, Request.UserHostName, Request.UserHostAddress);
//Set the response content type to "application/x-ica" to run the file.
Response.ContentType = "application/x-ica";
//Run the application by writing the file content to the response.
Response.BinaryWrite(Response.ContentEncoding.GetBytes(ica) );
Response.End();
}
References:
->Read More...Người đăng: Orchid vào lúc 13:49 0 nhận xét
Nhãn: Web Services
Email Sending Web Service
Introduction
This article will show you how simple to create a Email Notification Web Service. But unfortunately i am still not able to include the attachement inside the email. It is quite easy to add and attachement if you are using point to point connection on your service client and service consumer. But if you have to include the Service Registry in between then it will be not easy to archieve.
Background
I have started my web service development and WCF development recently. I found that the email notification service can be one of the function or module that can be resue on other application. After failing to get some good example, i decide to do it on my owned. By the way the detail function and module of email sending in this article is also from Code Project. What i have done is just expose this email sending module from component layer to service layer. For those reader who known about SOA (Service Oriented Architecture) will understand more about what i am saying.
Create A new web service
With VS2008 you can easily create and Web Service via the templete inside the VS2008. In default you shoud get an "ASMX" file and the C# file which is the background code for the "ASMX" file.
Expose your component as Service
If you already have the email notification module on your owned, just copy and paste into your web service project. If not you can just get from the zip file that i have uploaded together with this article.
This kind of service development enable you to reduce your effort to change your existing component to become a web services where later it can be reuse in other applicaition or system. Even though it is not a good example of SOA but it can be also consider as SOA landscape in the IT landscape.
After copy the module you can start to create an interface to link your service parameter with the module parameter.Notification Service Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace EmailNotification
{
///
/// Summary description for EmailNotification
///
[WebService(Namespace = "http://MailServiceSample/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class SentEmail : System.Web.Services.WebService
{
[WebMethod]
public string Sending_Email(string strEmailAddrFrom, string[] strEmailAddrTo, int intTotalEmailTo, string strAttachement)
{
EmailAlert NewMail = new EmailAlert();
return NewMail.EmailSent(strEmailAddrFrom, strEmailAddrTo, intTotalEmailTo, strAttachement);
}
}
}
Example Notification Module Code public string EmailSent(string strEmailAddrFrom, string [] strEmailAddrTo, int intTotalEmailTo, string strAttachement)
{
string strSent= " ";
try
{
// Initializes a new instance of the System.Net.Mail.MailMessage class.
myMailMessage = new MailMessage();
// Obtains the e-mail address of the person the e-mail is being sent to.
for (int NumberOfEmails = 0; NumberOfEmails < intTotalEmailTo; NumberOfEmails++)
{
myMailMessage.To.Add(new MailAddress(strEmailAddrTo[NumberOfEmails]));
}
// Obtains the e-mail address of the person sending the message.
myMailMessage.From = new MailAddress(strEmailAddrFrom, "Admin");
// You can add additional addresses by simply calling .Add again.
// Support not added in the current example UI.
//
// myMailMessage.To.Add( new System.Net.Mail.MailAddress( "addressOne@example.com" ));
// myMailMessage.To.Add( new System.Net.Mail.MailAddress( "addressTwo@example.com" ));
// myMailMessage.To.Add( new System.Net.Mail.MailAddress( "addressThree@example.com" ));
// You can also specify a friendly name to be displayed within the e-mail
// application on the client-side for the To Address.
// Support not added in the current example UI.
// See the example below:
//
// myMailMessage.To.Add(new System.Net.Mail.MailAddress( this.txtToAddress.Text, "My Name Here" ));
// myMailMessage.From(new System.Net.Mail.MailAddress( this.txtToAddress.Text, "Another Name Here" ));
// System.Net.Mail also supports Carbon Copy(CC) and Blind Carbon Copy (BCC)
// Support not added in the current example UI.
// See the example below:
//
// myMailMessage.CC.Add ( new System.Net.Mail.MailAddress( "carbonCopy@example.com" ));
// myMailMessage.Bcc.Add( new System.Net.Mail.MailAddress( "blindCarbonCopy@example.com" ));
// Obtains the subject of the e-mail message
myMailMessage.Subject = "Error On Optimizer Program";
// Obtains the body of the e-mail message.
myMailMessage.Body = "Error On Optimizer Program. Please check the detail from the attachment";
// Listed below are the two message formats that can be used:
// 1. Text
// 2. HTML
//
// The default format is Text.
myMailMessage.IsBodyHtml = true;
// Listed below are the three priority levels that can be used:
// 1. High
// 2. Normal
// 3. Low
//
// The default priority level is Normal.
//
// This section of code determines which priority level
// was checked by the user.
myMailMessage.Priority = MailPriority.High;
//myMailMessage.Priority = MailPriority.Normal;
//myMailMessage.Priority = MailPriority.Low;
// Not Yet Implement
// This section of code determines if the e-mail message is going to
// have an attachment.
if (strAttachement != "" || strAttachement != null)
{
Attachment att = new Attachment(strAttachement);
myMailMessage.Attachments.Add(att);
}
// Custom headers can also be added to the MailMessage.
// These custom headers can be used to tag an e-mail message
// with information that can be useful in tracking an e-mail
// message.
//
// Support not added in the current example UI.
// See the example below:
// myMailMessage.Headers.Add( "Titan-Company", "Titan Company Name" );
// Initializes a new instance of the System.Net.Mail.SmtpClient class.
SmtpClient myMailClient = new SmtpClient();
// Obtains the email server name or IP address to use when sending the e-mail.
myMailClient.Host = "Your Mail Host";
// Defines the port number to use when connecting to the mail server.
// The default port number for SMTP is 25/TCP.
myMailClient.Port = 25;
// Specifies the delivery method to use when sending the e-mail
// message. Listed below are the three delivery methods
// that can be used by namespace System.Net.Mail
//
// 1. Network = sent through the network to an SMTP server.
// 2. PickupDirectoryFromIis = copied to the pickup directory used by a local IIS server.
// 3. SpecifiedPickupDirectory = is copied to the directory specified by the
// SmtpClient.PickupDirectoryLocation property.
myMailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
// Initializes a new instance of the System.Net.NetworkCredential class.
//NetworkCredential myMailCredential = new NetworkCredential();
// Obtains the user account needed to authenticate to the mail server.
//myMailCredential.UserName = this.txtUserAccount.Text;
// Obtains the user password needed to authenticate to the mail server.
//myMailCredential.Password = this.txtUserPassword.Text;
// In this example we are providing credentials to use to authenticate to
// the e-mail server. Your can also use the default credentials of the
// currently logged on user. For client applications, this is the desired
// behavior in most scenarios. In those cases the bool value would be set to true.
//myMailClient.UseDefaultCredentials = true;
// Obtains the credentials needed to authenticate the sender.
//myMailClient.Credentials = myMailCredential;
// Set the method that is called back when the send operation ends.
myMailClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
// Sends the message to the defined e-mail for processing
// and delivery with feedback.
//
// In the current example randomToken generation was not added.
//
//string randomToken = "randonTokenTestValue";
//myMailClient.SendAsync( myMailMessage, randomToken );
object userState = myMailMessage;
try
{
//you can also call myMailClient.SendAsync(myMailMessage, userState);
Console.WriteLine("Mail Sending In progress");
myMailClient.Send(myMailMessage);
}
catch (System.Net.Mail.SmtpException ex)
{
Console.WriteLine(ex.Message, "Send Mail Error");
strSent = strSent + ex.Message;
}
myMailMessage.Dispose();
strSent = "Mail Sent !!";
}
// Catches an exception that is thrown when the SmtpClient is not able to complete a
// Send or SendAsync operation to a particular recipient.
catch (System.Net.Mail.SmtpException exSmtp)
{
Console.WriteLine("Exception occurred:" + exSmtp.Message, "SMTP Exception Error");
strSent = strSent + "Exception occurred:" + exSmtp.Message;
}
// Catches general exception not thrown using the System.Net.Mail.SmtpException above.
// This general exception also will catch invalid formatted e-mail addresses, because
// a regular expression has not been added to this example to catch this problem.
catch (System.Exception exGen)
{
Console.WriteLine("Exception occurred:" + exGen.Message, "General Exception Error");
strSent = strSent + "Exception occurred:" + exGen.Message;
}
return strSent;
}
->Read More...
Người đăng: Orchid vào lúc 13:48 0 nhận xét
Nhãn: Web Services
Your first C# Web Service
Introduction
Creating your first web service is incredibly easy. In fact, by using the wizards in Visual Studio. NET you can have your first service up and running in minutes with no coding.
For this example I have created a service called MyService in the /WebServices directory on my local machine. The files will be created in the /WebServices/MyService directory.
A new namespace will be defined called MyService, and within this namespace will be a set of classes that define your Web Service. By default the following classes will be created:
| Global (in global.asax) | Derived from HttpApplication. This file is the ASP.NET equivalent of a standard ASP global.asa file. |
| WebService1 (in WebService1.cs) | Derived from System.Web.Services.WebService. This is your WebService class that allows you to expose methods that can be called as WebServices. |
There are also a number of files created:
| AssemblyInfo.cs | Contains version and configuration information for your assembly. |
| web.config | Defines how your application will run (debug options, the use of cookies etc). |
| MyService.disco | Discovery information for your service. |
| WebService1.asmx | Your WebService URL. Navigate to this file in a browser and you will get back a user-friendly page showing the methods available, the parameters required and the return values. Forms are even provided allowing you to test the services through the web page. |
| bin\MyService.dll | The actual WebService component. This is created when you build the service. |
The class for your service that is created by default is called (in this case) WebService1, and is within the MyService namespace. The code is partially shown below.
namespace MyService
{
...
/// <summary>
/// Summary description for WebService1.
/// </summary>
[WebService(Namespace="http://codeproject.com/webservices/",
Description="This is a demonstration WebService.")]
public class WebService1 : System.Web.Services.WebService
{
public WebService1()
{
//CODEGEN: This call is required by the ASP+ Web Services Designer
InitializeComponent();
}
...
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
A default method HelloWorld is generated and commented out. Simply uncomment and build the project. Hey Presto, you have a walking talking WebService.
A WebService should be associated with a namespace. Your Wizard-generated service will have the name space http://tempuri.org. If you compile and run the service as-is you'll get a long involved message indicating you should choose a new namespace, so we add the namespace, and the WebService description as follows:
[WebService(Namespace="http://codeproject.com/webservices/",
Description="This is a demonstration WebService.")]
public class WebService1 : System.Web.Services.WebService
{
... To test the service you can right click on WebService1.asmx in the Solution Explorer in Visual Studio and choose "View in Browser". The test page is shown below,
When invoked this returns the following:
Getting the demo application to run
If you downloaded the source code with this article then you will need to create a directory 'WebServices' in your web site's root directory and extract the downloaded zip into there. You should then have:
\WebServices
\WebServices\bin
\WebServices\WebService1.asmx
... Navigating to http://localhost/WebServices/WebService1.asmx won't show you the WebService because you need to ensure that the webservice's assembly is in the application's /bin directory. You will also find that you can't load up the solution file MyService.sln. To kill two birds with one stone you will need to fire up the IIS management console, open your website's entry, right click on the WebServices folder and click Properties. Click the 'Create' button to create a new application the press OK. The /WebServices directory is now an application and so the .NET framework will load the WebService assembly from the /WebServices/bin directory, and you will be able to load and build the MyService.sln solution.
Extending the example
So we have a WebService. Not particularly exciting, but then again we haven't exactly taxed ourselves getting here. To make things slightly more interesting we'll define a method that returns an array of custom structures.
Within the MyService namespace we'll define a structure called ClientData:
public struct ClientData
{
public String Name;
public int ID;
}
and then define a new method GetClientData. Note the use of the WebMethod attribute in front of the method. This specifies that the method is accessible as a WebService method.
[WebMethod]
public ClientData[] GetClientData(int Number)
{
ClientData [] Clients = null;
if (Number > 0 && Number <= 10)
{
Clients = new ClientData[Number];
for (int i = 0; i < Number; i++)
{
Clients[i].Name = "Client " + i.ToString();
Clients[i].ID = i;
}
}
return Clients;
}
If we compile, then navigate to the the .asmx page then we are presented with a form that allows us to enter a value for the parameter. Entering a non-integer value will cause a type-error, and entering a value not in the range 1-10 will return a null array. If, however, we manage to get the input parameter correct, we'll be presented with the following XML file:
It's that easy.
Caching WebServices
Often a WebService will return the same results over multiple calls, so it makes sense to cache the information to speed things up a little. Doing so in ASP.NET is as simple as adding a CacheDuration attribute to your WebMethod:
[WebMethod(CacheDuration = 30)]
public ClientData[] GetClientData(int Number)
{ The CacheDuration attribute specifies the length of time in seconds that the method should cache the results. Within that time all responses from the WebMethod will be the same.
You can also specify the CacheDuration using a constant member variable in your class:
private const int CacheTime = 30; // seconds
[WebMethod(CacheDuration = CacheTime)]
public ClientData[] GetClientData(int Number)
{ Adding Descriptions to your WebMethods
In the default list of WebMethods created when you browse to the .asmx file it's nice to have a description of each method posted. The Description attribute accomplishes this.
[WebMethod(CacheDuration = 30,
Description="Returns an array of Clients.")]
public ClientData[] GetClientData(int Number)
{ Your default .asmx page will then look like the following:
There are other WebMethod attributes to control buffering, session state and transaction support.
Deploying the WebService
Now that we have a WebService it would be kind of nice to allow others to use it (call me crazy, but...). Publishing your WebService on your server requires that your solution be deployed correctly. On the Build menu of Visual Studio is a "Deploy" option that, when first selected, starts a Wizard that allows you to add a Deployment project to your solution. This creates an installation package that you can run on your server which will create the necessary directories, set the correct parameters and copy over the necessary files.
This doesn't really give you an idea of what, exactly, is happening, so we'll deploy our MyService manually.
Deploying the application is done using the steps in Getting the demo application to run. We need to create a directory for our service (or use an existing directory) for our .asmx file, and we need to have the service's assembly in the application's bin/ directory. Either place the .asmx file in a subdirectory on your website and place the assembly in the /bin folder in your website's root, or place the /bin in the subdirectory containing the .asmx file and mark that directory as an application (see above).
If you choose to create a separate directory and mark it as an application then Within this directory you need to add the following files and directories:
| MyService.asmx | This file acts as the URL for your service |
| MyService.disco | The discovery document for your service |
| web.config | Configuration file for your service that overrides default web settings (optional). |
| /bin | This directory holds the assembly for your service |
| /bin/MyService.dll | The actual service asembly. |
Người đăng: Orchid vào lúc 12:57 0 nhận xét
Nhãn: Web Services
How to make a webservices
The term Web services describes a standardized way of integrating Web-based applications using the XML, SOAP, WSDL and UDDI open standards over an Internet protocol backbone. XML is used to tag the data, SOAP is used to transfer the data, WSDL is used for describing the services available and UDDI is used for listing what services are available. Used primarily as a means for businesses to communicate with each other and with clients, Web services allow organizations to communicate data without intimate knowledge of each other's IT systems behind the firewall.
Unlike traditional client/server models, such as a Web server/Web page system, Web services do not provide the user with a GUI. Web services instead share business logic, data and processes through a programmatic interface across a network. The applications interface, not the users. Developers can then add the Web service to a GUI (such as a Web page or an executable program) to offer specific functionality to users.
Web services allow different applications from different sources to communicate with each other without time-consuming custom coding, and because all communication is in XML, Web services are not tied to any one operating system or programming language. For example, Java can talk with Perl, Windows applications can talk with UNIX applications.
Web services do not require the use of browsers or HTML.
Web services are sometimes called application services.
->Read More...Người đăng: Orchid vào lúc 05:16 0 nhận xét
Nhãn: Web Services
