Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

hjnntaao

« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS 

WFC Service Library Code

Code generated when creating a project of type "WCF Service Library" using Microsoft .NET Framework 3.0 RC and Orcas CTP

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;

/*

    HOW TO HOST THE WCF SERVICE IN THIS LIBRARY IN ANOTHER PROJECT
    You will need to do the following things: 
    1)    Add a Host project to your solution
        a.    Right click on your solution
        b.    Select Add
        c.    Select New Project
        d.    Choose an appropriate Host project type (e.g. Console Application)
    2)    Add a new source file to your Host project
        a.    Right click on your Host project
        b.    Select Add
        c.    Select New Item
        d.    Select "Code File"
    3)    Paste the contents of the "MyServiceHost" class below into the new Code File
    4)    Add an "Application Configuration File" to your Host project
        a.    Right click on your Host project
        b.    Select Add
        c.    Select New Item
        d.    Select "Application Configuration File"
    5)    Paste the contents of the App.Config below that defines your service endoints into the new Config File
    6)    Add the code that will host, start and stop the service
        a.    Call MyServiceHost.StartService() to start the service and MyServiceHost.EndService() to end the service
    7)    Add a Reference to System.ServiceModel.dll
        a.    Right click on your Host Project
        b.    Select "Add Reference"
        c.    Select "System.ServiceModel.dll"
    8)    Add a Reference from your Host project to your Service Library project
        a.    Right click on your Host Project
        b.    Select "Add Reference"
        c.    Select the "Projects" tab
    9)    Set the Host project as the "StartUp" project for the solution
        a.    Right click on your Host Project
        b.    Select "Set as StartUp Project"

    ################# START MyServiceHost.cs #################

    using System;
    using System.ServiceModel;

    // A WCF service consists of a contract (defined below), 
    // a class which implements that interface, and configuration 
    // entries that specify behaviors and endpoints associated with 
    // that implementation (see <system.serviceModel> in your application
    // configuration file).

    internal class MyServiceHost
    {
        internal static ServiceHost myServiceHost = null;

        internal static void StartService()
        {
            //Consider putting the baseAddress in the configuration system
            //and getting it here with AppSettings
            Uri baseAddress = new Uri("http://localhost:8080/service1");

            //Instantiate new ServiceHost 
            myServiceHost = new ServiceHost(typeof(HelloWorldWCFService.service1), baseAddress);

            //Open myServiceHost
            myServiceHost.Open();
        }

        internal static void StopService()
        {
            //Call StopService from your shutdown logic (i.e. dispose method)
            if (myServiceHost.State != CommunicationState.Closed)
                myServiceHost.Close();
        }
    }

    ################# END MyServiceHost.cs #################
    ################# START App.config or Web.config #################

    <system.serviceModel>
    <services>
         <service name="HelloWorldWCFService.service1">
           <endpoint contract="HelloWorldWCFService.IService1" binding="wsHttpBinding"/>
         </service>
       </services>
    </system.serviceModel>

    ################# END App.config or Web.config #################

*/
namespace WCFService
{
    // You have created a class library to define and implement your WCF service.
    // You will need to add a reference to this library from another project and add 
    // the code to that project to host the service as described below.  Another way
    // to create and host a WCF service is by using the Add New Item, WCF Service 
    // template within an existing project such as a Console Application or a Windows 
    // Application.

    [ServiceContract()]
    public interface IService1
    {
        [OperationContract]
        string MyOperation1(string myValue);
        [OperationContract]
        string MyOperation2(DataContract1 dataContractValue);
    }

    public class service1 : IService1
    {
        public string MyOperation1(string myValue)
        {
            return "Hello: " + myValue;
        }
        public string MyOperation2(DataContract1 dataContractValue)
        {
            return "Hello: " + dataContractValue.FirstName;
        }
    }

    [DataContract]
    public class DataContract1
    {
        string firstName;
        string lastName;

        [DataMember]
        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }
        [DataMember]
        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }
    }

}

Windows Powershell Cmdlet - Creation and Registration

Adapted from "Windows PowerShell Programmer's Guide", at http://windowssdk.msdn.microsoft.com/en-us/library/ms714674.aspx

// Reference added to "System.Management.Automation.dll" in "C:\Program Files\Windows PowerShell\v1.0":
using System.Management.Automation;

namespace CmdletTest
{
    [Cmdlet(VerbsCommon.Get, "Hjnntaao")]
    public class GetHjnntaaoCommand : Cmdlet
    {
        // BeginProcessing - pre-processing/set-up

        // If accepts pipeline input, must override ProcessRecord and, optionally, EndProcessing

        // If does not take pipline input, should override EndProcessing

        // Cmdlets should never call WriteLine, or equivalent.
        protected override void ProcessRecord()
        {
            Process[] processes = Process.GetProcesses();

            
            WriteObject(processes);
        }
    }

    /* 
       This method of registering the Cmdlet with PowerShell extends the shell using snap-ins. This should
       be the default way of registering Cmdlets. The other way, registering with a custom shell,
       should only be used to create executable files.
     
       To install:
       1) installutil CmdletTest.dll
       2) Verify the snap in is in the list of registered snap-ins awaiting to be loaded by
          running "get-pssnapin -registered"
       3) Add the snap in to the shell by using "add-pssnapin "GetHjnntaaoPSSSnapIn01"
     */
    [RunInstaller(true)]
    public class GetHjnntaaoPSSnapIn01 : PSSnapIn
    {
        public override string Name
        {
            get { return "GetHjnntaaoPSSnapIn01"; }
        }

        public override string Vendor
        {
            get { return "HjnntaaoCorp"; }
        }

        public override string Description
        {
            get { return "Hjnntaao's Cmdlet"; }
        }

    }
}

C# - XML serialization from string

From http://weblogs.asp.net/whaggard/archive/2006/09/04/String-Streams-in-.Net.aspx

xmlSerializer.Deserialize(new StringReader(xmlString));

c# IsNumeric method

From Subtext source code - http://subtextproject.com/

public static bool IsNumeric(string text)
{
    return Regex.IsMatch(text,"^\\d+$");
}

MVP - Composition overview

Adapted from code supporting article at http://msdn.microsoft.com/msdnmag/issues/06/08/DesignPatterns/default.aspx

public partial class ViewCustomers : System.Web.UI.Page, IViewCustomerView
{
	private ViewCustomerPresenter presenter;

	protected override void OnInit(EventArgs e)
    	{
        	base.OnInit(e);
        	presenter = new ViewCustomerPresenter(this);
        	this.customerDropDownList.SelectedIndexChanged += delegate
                                                                  {
                                                                  	presenter.DisplayCustomerDetails();
                                                              	  };
    	}

	// ...
}

public class ViewCustomerPresenter
{
	private readonly IViewCustomerView view;
	private readonly ICustomerTask task;

	public ViewCustomerPresenter(IViewCustomerView view) : this(view, new CustomerTask()) {}

        public ViewCustomerPresenter(IViewCustomerView view, ICustomerTask task)
        {
            this.view = view;
            this.task = task;
        }

        public void DisplayCustomerDetails()
        {
            int? customerId = SelectedCustomerId;

            if (customerId.HasValue)
            {
                CustomerDTO customer = task.GetDetailsForCustomer(customerId.Value);
                UpdateViewFrom(customer);
            }
        }

        private void UpdateViewFrom(CustomerDTO customer)
        {
            view.CompanyName = customer.CompanyName;
            view.ContactName = customer.ContactName;
            view.ContactTitle = customer.ContactTitle;
            view.Address = customer.Address;
            view.City = customer.City;
            view.Region = customer.Region;
            view.Country = customer.CountryOfResidence.Name;
            view.Phone = customer.Phone;
            view.Fax = customer.Fax;
            view.PostalCode = customer.PostalCode;
        }



	// ...
}

public class CustomerTask : ICustomerTask
{
	...
}

ADO.NET - Succinctly populating a DataTable

From code supporting article at http://msdn.microsoft.com/msdnmag/issues/06/08/DesignPatterns/default.aspx

    public class DatabaseGateway
    {
        public DataTable QueryForDataTable(string expression)
        {
            using (IDatabaseConnection connection = new DatabaseConnection())
            {
                DataTable table = new DataTable();

                using (IDataReader reader = connection.CreateCommandFor(expression).ExecuteReader())
                {
                    table.Load(reader);
                }

                return table;
            }
        }
    }

    public class DatabaseConnection : IDatabaseConnection
    {
        public IDbCommand CreateCommandFor(string dynamicSqlExpression)
        {
            IDbCommand command = underlyingConnection.CreateCommand();
            command.CommandType = CommandType.Text;
            command.CommandText = dynamicSqlExpression;
            return command;
        }

        public void Dispose()
        {
            underlyingConnection.Close();
            underlyingConnection.Dispose();
            underlyingConnection = null;
        }


        // ...
    }

Domain object interface

public interface IDomainObject
{             
    int Id{get;}
}
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS