Bitmap Default resolution

Recently I encountered a problem regarding default resolution for Images. An image that had been stored in a database as a multi-page tiff needed to be split into individual bitmaps for display and print on a winform using standard GDI+. While spliting the tiffs and creating the new bitmaps, the resolution was lost and was set to the default value of Bitmaps. While the display on the winform was not a problem as the viewer handled the image sizing, the printing of the image resulted in a very distorted printed image.

Upon examination of the image, the resolution was 300 x 300. Upon creation of the bitmap it defaulted to 72 x 72.

This problem was quickly resolved by setting the resolution of all of the new  bitmaps  to the original resolution contained in the image object.

Seems like a simple fix, but it created a huge problem on the project.

-Craig

General

Comments (0)

Permalink

Creating a Project Installer for a Windows Service

I recently had to create a Windows Service for a project I’m currently working on.  Rather than installing/uninstalling using InstallUtil, I decided to create a project installer to do the work for me.  It took a little bit of digging to gather all of the necessary steps, so here is what I did to get up and running.

  1. Create your Windows Service project and Windows Service.
  2. Navigate to the designer for your Windows Service. Under the properties for your service you should see (Name) and ServiceName. Fill in both of these properties with your desired names. You will need to reference these later.
  3. In the designer for your Windows Service, right-click and click Add Installer. You should now have a ProjectInstaller.cs file, along with a designer file for the installer.
  4. Navigate to the designer for your new project installer. You should see two components, a Service Process Installer and a Service Installer. Under the Service Installer properties, you will need to add a DisplayName, and provide the ServiceName of the service you will be installing. The ServiceName must match the (Name) property of the service.
  5. Build your Windows Service project. Now in the same solution, add a new Setup Project. This will provide the Wizard interface for the installation process.
  6. After adding the project, you need to add the primary output of your Windows Service to the Setup Project. Do this by right-clicking on the Setup Project -> Add -> Project Output. Select your Windows Service project from the drop down, highlight Primary Output and click OK.
  7. Up to this point the installer will install the correct files, but it doesn’t know what to do with the files. We can add custom actions to do the service installation work. Right-click on the Setup Project -> View -> Custom Actions. For a Windows Service we need to add actions for Install, Rollback, and Uninstall. Right-click each of these and click Add Action. Double click Application Folder and select the Primary Output from your Windows Service project.
  8. You can now build your Setup Project. The output of this build will be two setup files which are used to install your new Windows Service.

-Jon

.NET Framework
General

Comments (0)

Permalink

.NetTiers Component Business Layer Architecture

I posted a blog on my blog site that takes a look at the Patterns used in the .NetTier Service Layer Architecture.  Check it out at …

http://www.stanfordkennedy.com/2009/05/nettiers-architecture-design-patterns.html

~Stan Kennedy

General

Comments (0)

Permalink

Writing ASP.NET MVC Applications on MacOS X?

Interesting news today, there’s a new build of MonoDevelop that works with MacOS X.  MonoDevelop is a fully functional IDE for writing apps in Mono, a cross platform .NET library.

 

image

 

Follow the link for more info: http://tirania.org/blog/archive/2009/May-05-1.html

.NET Framework
Mono

Comments (0)

Permalink

Recover from a WCF Service Fault, Part 2 (Generic ServiceClientFactory Class)

After finding the simple solution for handling WCF Service Faults in the original post, I figured it should be relatively trivial to find a generic solution to this problem if you’re using similar WCF clients in a project and want to reset ALL of them on a channel fault.  I developed a generic ServiceClientFactory class that will generate a WCF Service Client instance from a generic “GetClient” function and will automatically handle resetting of faulted channels.

Class Implementation Source Code:

/* Service Client Factory
 * Author: Michael Gerety, Senior Consultant, Tallan, Inc.
 * Description: A generic service client factory that automatically
 *              resets faulted channels for WCF services that have
 *              endpoints and behaviors defined in web/app.config files.
 */             

using System;
using System.Collections.Generic;
using System.ServiceModel;
namespace Tallan
{
    /// <summary>
    /// Singleton factory class for WCF Services.
    /// Creates service clients based on interface type and automatically
    /// resets faulted channels.
    /// </summary>
    public class ServiceClientFactory
    {
        private readonly Dictionary<Type, object> factories;
        private static ServiceClientFactory instance;

        private ServiceClientFactory()
        {
            factories = new Dictionary<Type, object>();
        }

        /// <summary>
        /// Retrieves a service client for the interface specified in generic parameter.
        /// </summary>
        /// <typeparam name="T">Interface type to use for Service Client creation.</typeparam>
        /// <returns>Service client instance for specified interface.</returns>
        public T GetClient<T>()
        {
            var genericType = typeof(T);
            Type serviceClientType;
            if (genericType.IsInterface)
            {
                serviceClientType = GetClientType(genericType);

                if (serviceClientType == null)
                    return default(T);

                var client = Activator.CreateInstance(serviceClientType);
                if (!(client is ICommunicationObject))
                {
                    client = null;
                    return (T)client;

                }
                (client as ICommunicationObject).Faulted += Channel_Faulted<T>;

                if (!factories.ContainsKey(typeof(T)))
                {
                    var prop = serviceClientType.GetProperty("ChannelFactory");
                    var factory = prop.GetValue(client, null);
                    factories.Add(typeof(T), factory);
                }
                return (T)client;
            }
            return default(T);
        }

        #region Reflection Utilities
        private static Type GetClientType(Type type)
        {
            var assy = type.Assembly;
            var serviceModelAssy = typeof(ChannelFactory).Assembly;
            var clientBaseType = serviceModelAssy.GetType("System.ServiceModel.ClientBase`1").MakeGenericType(type);

            foreach (var classType in assy.GetTypes())
            {
                if (classType.IsClass && type.IsAssignableFrom(classType))
                {
                    if (classType.IsSubclassOf(clientBaseType))
                        return classType;
                }
            }

            return null;
        }

        #endregion

        /// <summary>
        /// Event handler for ClientBase.Faulted event.
        /// </summary>
        /// <typeparam name="T">Interface type of service</typeparam>
        /// <param name="sender">ClientBase instance</param>
        /// <param name="e">Event Args</param>
        private void Channel_Faulted<T>(object sender, EventArgs e)
        {
            ((ICommunicationObject)sender).Abort();
            var factory = (ChannelFactory<T>)factories[typeof(T)];
            factory.CreateChannel();
        }

        /// <summary>
        /// Returns the singleton instance of ServiceClientFactory.
        /// </summary>
        /// <returns>Singleton instance of ServiceClientFactory</returns>
        public static ServiceClientFactory GetFactory()
        {
            if (instance == null)
            {
                instance = new ServiceClientFactory();
            }
            return instance;
        }
    }
}

Sample Usage:

//Get instance of ServiceClientFactory
            var factory = ServiceClientFactory.GetFactory();
            var client = factory.GetClient<IAuthenticateService>();
            try
            {
                client.AuthenticateUser("joe", "bob");
            }
            catch (Exception)
            {
                //Handle Exception
            }

            //channel isn't in faulted state, you can re-execute.
            client.AuthenticateUser("joe", "bob1");

This was thrown together and proven to work for my purposes.  If anyone has any suggestions about how to improve this utility class, please feel free to comment or contact me with suggestions.

.NET Framework
WCF

Comments (2)

Permalink

Recover from a WCF Service Fault

I’ve been looking for an elegant way to recover from a WCF Service Client’s channel going into a Faulted state, and after searching for some time came across a great simple quick and dirty example:

When creating your WCF Service Client, add an event handler to the ICommunicationObject.Faulted event on your service client:

   1: private static ChannelFactory<IAuthenticateService> AuthChannelFactory = null;

   2:  

   3: public static IAuthenticateService GetClient()

   4: {

   5:     if (AuthChannelFactory == null)

   6:         AuthChannelFactory = new ChannelFactory<IAuthenticateService>();

   7:     var client = AuthChannelFactory.CreateChannel();

   8:     

   9:     (client as ICommunicationObject).Faulted += new EventHandler(AuthChannel_Faulted);

  10:     return client;

  11: }

In the event handler, re-create the channel using the channel factory:

   1: static void AuthChannel_Faulted(object sender, EventArgs e)

   2:        {

   3:            (sender as ICommunicationObject).Abort();

   4:            sender = AuthChannelFactory.CreateChannel();

   5:        }

You can re-use the AuthChannel_Faulted event by checking the object type and using the correct ChannelFactory based on type. 

Method obtained from : Nahid’s Blog

General

Comments (1)

Permalink

Unable to launch the ASP.NET Development Server because port ‘n’ is in use.

This error displays itself when trying to debug a Web Application or Web Service project from within Visual Studio 2005 and/or Visual Studio 2008 on machines running ESET NOD32 Antivirus.  This problem seems to occur every couple of months on our team, and for some reason we always go round and round trying to troubleshoot it, even though we’ve seen the fix numerous times, so I’m documenting it here again.

Step 1:

image

Double-click the NOD32 Antivirus link in your system tray.  Highlight “Setup” in the left pane and click “Antivirus and antispyware”

 

Step 2:

Click ConfigureU under Web access protection (see image above).

Step 3:

image

Select “Antivirus and antispyware” –gt; “Web access protection” –gt; “HTTP” –gt; “Web Browsers”  Find all of your devenv.exe instances in the list and click the check box next to them until a red x appears (image ).  Note: DO NOT make the box checked (image ) or the issue will continue!

Step 4:

Click “OK” and close NOD32.  You should now be able to launch the ASP.NET Development web server again without issue.

.NET Framework
General

Comments (0)

Permalink

Debugging Windows Services in the Visual Studio IDE

In one of our current projects we made  the decision to move our WCF services from an IIS hosted environment into a Window Service hosted environment.  This move gave us greater flexibility in mangement and distribution of our WCF services, and allowed us to use multiple endpoints (http, net.tcp, pipes) without the need for Windows Activation Services (WAS) which would have required that our clients be running Vista and/or Server 2008.

One of the major pains about working with developing Windows Services, however, is that you can’t start a windows service project from within the debugger.  You have to instead install and start the service to execute it.

I have a workaround for this that allows us to test our WCF services from within the IDE without installing the service.

Steps:

1. In the Windows Service, put any code you’d normally put in the OnStart and OnStop events into their own functions:

private void OpenWCFServices()
{
    householdHost.Open();
}

private void CloseWCFServices()
{
    householdHost.Close();

}
protected override void OnStart(string[] args)
{
    OpenWCFServices();
}

protected override void OnStop()
{
    CloseWCFServices();
}

2. Using precompiler directives, specify 2 public functions that also call your start and stop methods.  This allows these methods to be publicly available at debug time only (you’ll see why in Step 3).

#if DEBUG
        public void DebugStart()
        {
            OpenWCFServices();
        }

        public void DebugStop()
        {
            CloseWCFServices();
        }
#endif

3. Create a new Windows Form in your service project.  Alter the constructor so that it requires an instance of your service to be created.  Add a Button to stop your WCF services to the form.

    public partial class DebugForm : Form
    {
        private FEEAApplicationServiceHost service;
        public DebugForm(FEEAApplicationServiceHost service)
        {
            InitializeComponent();
            this.service = service;
            this.service.DebugStart();
        }

        private void ExitButton_Click(object sender, EventArgs e)
        {
#if DEBUG
            service.DebugStop();
#endif
        }
    }

 

4. Alter your Program.cs to use this form as your running application instead of the Service using the same #if DEBUG directives.

       /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {

#if DEBUG
            Application.EnableVisualStyles();
            Application.Run(new DebugForm(new FEEAApplicationServiceHost()));
#else
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new FEEAApplicationServiceHost()
            };
            ServiceBase.Run(ServicesToRun);
#endif

        }
    }

This allows you to launch your service from the IDE and debug during development, while still having the ability to compile and distribute your service without changing a line of code.  (Although I’d probably recommend removing this code from anything that is truly production-level.

So now, when you right click your service project and select Debug –gt; Start new instance, you see the following form:

 

image

Once this is up, you can start an instance of your code that accesses the service, and you’re all set.

.NET Framework
WCF

Comments (0)

Permalink

Interesting Links - RoR and MVC.NET

A couple topics I have been looking into lately are Ruby on Rails and ASP.NET MVC.

Here are some helfpul links I found along the way.

Visual Studio Add-ins - I have heard of quite a few of these. The link is kind of old but some of the tools are still relevant.

http://msdn.microsoft.com/en-us/magazine/cc300778.aspx

Free Chapter on MVC in Action - This book comes out in August but some of the content is available now.

http://www.manning.com/palermo/

MVC.NET - Interesting article. I like the last section where they talk about MVC vs. Web Forms.

http://msdn.microsoft.com/en-us/magazine/cc337884.aspx

ASP.NET vs. Ruby - Decent comparison between the two technologies.

http://dotnetaddict.dotnetdevelopersjournal.com/ruby_vs_aspnet_1.htm

http://dotnetaddict.dotnetdevelopersjournal.com/aspnet_ruby_agility.htm

http://dotnetaddict.dotnetdevelopersjournal.com/aspnet_ruby_datadriven.htm

General

Comments (0)

Permalink

WCF Security Part 1

A few months ago I was given the task of setting up security for some WCF services we had created. After a couple days of scouring the internet for ideas and solutions, I ended up purchasing a book on WCF. Although there is a lot of information on the web about WCF and what security methods are available to us as developers, the information was always incomplete, and connecting the dots wasn’t the easiest. The example below shows how we can setup message based WCF security for a service which will be accessed over the internet, although the same code could be used for an intranet application as well. The example will require both user authentication and an x509 certificate.

For our WCF service, we’re using the wsHttpBinding. This binding provides much of the same functionality as a basic web service, with added service features such as reliable messaging, WS-Addressing, and WS-Security. Since this post is mainly on setting up security for a WCF service, I won’t go into too many details of the other features of wsHttpBinding.

After creating the WCF service, open up the web.config file for the WCF Service Application project. After scrolling down for a long time, you should come across a System.serviceModel tag. This tag contains all of the configuration settings for the WCF services contained in this project. Here’s what you should be looking at now:

<system.serviceModel>

<services>

<service name=WcfService1.Service1 behaviorConfiguration=WcfService1.Service1Behavior>

<!– Service Endpoints –>

<endpoint address=“” binding=wsHttpBinding contract=WcfService1.IService1>

<!–

Upon deployment, the following identity element should be removed or replaced to reflect the

identity under which the deployed service runs. If removed, WCF will infer an appropriate identity

automatically.

–>

<identity>

<dns value=localhost/>

</identity>

</endpoint>

<endpoint address=mex binding=mexHttpBinding contract=IMetadataExchange/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name=WcfService1.Service1Behavior>

<!– To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment –>

<serviceMetadata httpGetEnabled=true/>

<!– To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information –>

<serviceDebug includeExceptionDetailInFaults=false/>

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

By default, a WCF service will use the wsHttpBinding, this is what we want to continue using. We need to make a few modifications to this web.config in order to provide the additional functionality we want. First take a look at the serviceBehaviors section. By default we already have a behavior for our Service1. Here is an example of a modified behavior:

<behavior name=WcfService1.Service1Behavior>

<serviceCredentials>

<serviceCertificate findValue=CN=ServiceCertificate storeLocation=LocalMachine

storeName=My x509FindType=FindBySubjectDistinguishedName />

<userNameAuthentication userNamePasswordValidationMode=Windows/>

</serviceCredentials>

</behavior>

There is a lot of info in this behavior pertaining to security. The first bit describes the x509 certificate we would like to use that is already installed on our machine. We can create our own test x509 certificate for development purposes if need be. We can also describe the user authentication mode, in this case we are just using Windows authentication.

The next section extends the wsHttpBinding to provide some additional features not turned on be default:

<bindings>

<wsHttpBinding>

<binding name=wsHttpBindingSettings messageEncoding=Text>

<security mode=Message>

<message clientCredentialType=UserName />

</security>

</binding>

</wsHttpBinding>

</bindings>

Here we can describe the transport type, as well as the client credential type. This is fairly simple, we are using Message based transport with UserName security.

Finally we need to tie these sections together with Service1:

<service behaviorConfiguration=WcfService1.Service1Behavior name=WcfService1.Service1Behavior>

<endpoint address=“” binding=wsHttpBinding bindingConfiguration=wsHttpBindingSettings

contract=WcfService1.IService1 listenUriMode=Explicit>

<identity>

<dns value=ServiceCertficate />

</identity>

</endpoint>

<endpoint address=mex binding=mexHttpBinding contract=IMetadataExchange />

</service>

The only changes we made here are in the bindingConfiguration property and the dns value. The bindingConfiguration allows you to bind our binding configuration to this service, and the dns value should match the x509 certificate name.

I’ll be posting some more on this topic, including writing your own custom username validation code for WCF, and creating your own test x509 certificate. Hope this helps!

-Jon

.NET Framework

Comments (0)

Permalink