johnllao

June 30, 2009

Manipulating Local User Accounts

Filed under: Uncategorized — johnllao @ 11:17 pm

In this blog I wil show some easy codes to Create, and manipulate a local user account. In my code I will be utilising the WinNT provider.

Creating a local user account

string username = UserNameTextBox.Text;
string password = PasswordTextBox.Text;

try
{
    DirectoryEntry localAd = new DirectoryEntry("WinNT://" + Environment.MachineName);
    DirectoryEntry user = localAd.Children.Add(username, "user");
    user.Invoke("SetPassword", new object[] { password });
    user.Invoke("Put", new object[] { "Description", password });
    user.Invoke("Put", new object[] { "FullName", "You are " + username });
    user.CommitChanges();

}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

On this code I have shown a simple way to create a local user account. Here we user the Invoke to call a method thru reflection from the underlying WinNT provider.

Changing password

string username = UserNameTextBox.Text;
string password = PasswordTextBox.Text;

try
{
    DirectoryEntry user = new DirectoryEntry("WinNT://" + Environment.MachineName + "/" + username);
    if (user != null)
    {
        user.Invoke("SetPassword", new object[] { password });
        user.Invoke("Put", new object[] { "Description", password });
        user.Invoke("Put", new object[] { "FullName", "You are " + username });
        user.CommitChanges();
    }
}
catch (Exception ex)
{
     MessageBox.Show(ex.Message);
}

This code is similar to the creation of user excep that the expression user from the provider is slightly different. Here we used the syntax WinNT://<server name>/<user name> to further filter our query toget the user name information. Alternatively, you can also implement the first code however you neede to use the Find function to get the user information.

Disabling an account

string username = UserNameTextBox.Text;
string password = PasswordTextBox.Text;

try
{
    DirectoryEntry user = new DirectoryEntry("WinNT://" + Environment.MachineName + "/" + username);
    if (user != null)
    {
        user.Properties["UserFlags"].Value = Convert.ToInt32(user.Properties["UserFlags"].Value) | 2;
        user.CommitChanges();
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

To disable a user account just user the “| 2″ expression against the existing value of the UserFlags. To enable it back just use the “& ~2″ expression against the existing value of the UserFlags (e.g. user.Properties["UserFlags"].Value = Convert.ToInt32(user.Properties["UserFlags"].Value) & ~2).

That’s it. Happy coding…

June 21, 2009

Using WcfPortal

Filed under: Uncategorized — johnllao @ 10:25 am

As we are all aware DataPortal in CSLA serves as the backbone in implemeting SOA in CSLA. This allows our application business objects to be hosted in other server. The beauty of implementing this in CSLA is that no code change needed to be done in our business object.  In this blog I will show how this can be achieved using a WCF hosted in IIS.

First this to do is to create a .svc file in your web project. In our case we will name our .svc file as WcfPortal.svc.

<%@ ServiceHost Language="C#" Debug="false" Service="Csla.Server.Hosts.WcfPortal" %>

As you can see, the value of service attribute is set to Csla.Server.Hosts.WcfPortal.

Next step is to set the following configuration in the web.config of your web project.

  <system.serviceModel>
    <bindings>
      <wsHttpBinding>

        <binding name="wsHttpBindingSettings"
                 closeTimeout="00:10:00"
                 openTimeout="00:10:00"
                 sendTimeout="00:10:00"
                 maxReceivedMessageSize="2147483647"
                 maxBufferPoolSize="2147483647"
                 messageEncoding="Text" >

          <readerQuotas maxDepth="2147483647"
                        maxStringContentLength="2147483647"
                        maxArrayLength="2147483647"
                        maxBytesPerRead="2147483647"
                        maxNameTableCharCount="2147483647" />

        </binding>

      </wsHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfPortalBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="Csla.Server.Hosts.WcfPortal" behaviorConfiguration="WcfPortalBehavior" >
        <endpoint address="" binding="wsHttpBinding" contract="Csla.Server.Hosts.IWcfPortal" bindingConfiguration="wsHttpBindingSettings" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
  </system.serviceModel>

One of the most important stuff to check is the bindingConfiguration settings, in our example we set the value of the maxReceivedMessageSize to a very big value. this is to avoid exceptions regarding the limit of the size of the message sent across the channel. Due to the size of your business object some scenarios may exceed the default size set by Wcf.

On the client machine se the following configurations

  <system.serviceModel>
    <bindings>
      <wsHttpBinding>

        <binding name="wsHttpBindingSettings"
                 closeTimeout="00:10:00"
                 openTimeout="00:10:00"
                 sendTimeout="00:10:00"
                 maxReceivedMessageSize="2147483647"
                 maxBufferPoolSize="2147483647"
                 messageEncoding="Text" >

          <readerQuotas maxDepth="2147483647"
                        maxStringContentLength="2147483647"
                        maxArrayLength="2147483647"
                        maxBytesPerRead="2147483647"
                        maxNameTableCharCount="2147483647" />

        </binding>

      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint name="WcfDataPortal"
                address="http://localhost:52423/WcfPortal.svc"
                binding="wsHttpBinding"
                contract="Csla.Server.Hosts.IWcfPortal"
                bindingConfiguration="wsHttpBindingSettings"/>
    </client>
  </system.serviceModel>

That’s it! Happy coding

June 5, 2009

Session_Start and Session_End event from custom HttpApplication

Filed under: Uncategorized — johnllao @ 7:23 pm

Example that shows how to assign Session_Start and Session_End events from a custom HttpApplication object.

By default HttpApplication only contains events related to a particular request such as BeginRequest, so in order to initiate the Session_Start and Session_End event one has to get reference to the SessionStateModule. SessionStateModule is one of the HttpModule that was attached to a web application, this module handles the session management. SessionHttpModule is also a sealed class so we cannot inherit from it, so the only way to intercept the Session_Start and Session_End events is to get reference of this module.

Please see the code below.

    public class KyuApplication : System.Web.HttpApplication
    {
        public override void Init()
        {
            SessionStateModule session = Modules["Session"] as SessionStateModule;
            if (session != null)
            {
                session.Start += new EventHandler(Session_Start);
                session.End += new EventHandler(Session_End);
            }
        }

        private void Session_Start(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Session_Start");
        }

        private void Session_End(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Session_End");
        }
    }

June 2, 2009

Object Builder Sample

Filed under: Uncategorized — johnllao @ 2:07 pm

ObjectBuilder Sample

The following code shows a simple example to use the ObjectBuilder as an IOC / DI container. ObjectBuilder is a component of the Microsoft Enterprise Application Block it is also the backbone of the Unity DI.

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Practices.ObjectBuilder;

namespace StudyObjectBuilder.ConsoleApplication
{
    /// <summary>
    /// 
    /// </summary>
    public class Program
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            Locator l = new Locator();
            l.Add(typeof(ILifetimeContainer), new LifetimeContainer());

            Builder b = new Builder();
            b.Strategies.Clear();
            b.Strategies.AddNew<CreationStrategy>(BuilderStage.Creation);
            b.Strategies.AddNew<TypeMappingStrategy>(BuilderStage.PreCreation);
            b.Strategies.AddNew<SingletonStrategy>(BuilderStage.PreCreation);
            b.Strategies.AddNew<PropertyReflectionStrategy>(BuilderStage.PreCreation);
            b.Strategies.AddNew<PropertySetterStrategy>(BuilderStage.Initialization);
            b.Strategies.AddNew<ConstructorReflectionStrategy>(BuilderStage.PreCreation);
            //b.Strategies.AddNew<MethodReflectionStrategy>(BuilderStage.PreCreation);
            //b.Strategies.AddNew<MethodExecutionStrategy>(BuilderStage.Initialization);
            //b.Strategies.AddNew<BuilderAwareStrategy>(BuilderStage.PostInitialization);

            b.Policies.SetDefault<ICreationPolicy>(new DefaultCreationPolicy());
            b.Policies.Set<ISingletonPolicy>(new SingletonPolicy(true), typeof(ConsoleLogger), null);
            b.Policies.Set<ITypeMappingPolicy>(new TypeMappingPolicy(typeof(TraceLogger), null), typeof(ILogger), null);

            ConsoleLogger logger = b.BuildUp<ConsoleLogger>(l, null, null);

            Person p = b.BuildUp<Person>(l, null, null);
            p.Id = 1;
            p.Name = "John";
            p.Greet();

            Person p2 = b.BuildUp<Person>(l, null, null);
            p2.Id = 2;
            p2.Name = "Bob";
            p2.Greet();

            Console.ReadLine();
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class Person
    {
        private ILogger _logger;
        //[Microsoft.Practices.ObjectBuilder.Dependency(CreateType = typeof(ConsoleLogger))]
        //public ILogger Logger
        //{
        //    get { return _logger; }
        //    set { _logger = value; }
        //}

        private int _id;

        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        public Person([Microsoft.Practices.ObjectBuilder.Dependency(CreateType = typeof(ConsoleLogger))]ILogger logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 
        /// </summary>
        public void Greet()
        {
            _logger.Write("Hello " + _name);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public interface ILogger
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        void Write(string message);
    }

    /// <summary>
    /// 
    /// </summary>
    public class TraceLogger : ILogger
    {

        public TraceLogger()
        {

        }

        #region ILogger Members
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        public void Write(string message)
        {
            System.Diagnostics.Trace.WriteLine(message);
        }

        #endregion
    }

    /// <summary>
    /// 
    /// </summary>
    public class ConsoleLogger : ILogger
    {

        public ConsoleLogger()
        {

        }

        #region ILogger Members
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        public void Write(string message)
        {
            Console.WriteLine(message);
        }

        #endregion
    }
}

Blog at WordPress.com.