The Darkside

Shedding light on things and stuff

 
  Home :: Contact :: Syndication  :: Login
  87 Posts :: 0 Stories :: 56 Comments :: 2 Trackbacks

Ads

 

Donate via PayPal...

...if you feel the site helped.

Archives

Post Categories

Open Source Projects

Other Blogs

Sunday, November 18, 2012 #

I’m playing around with the new Service Bus for Windows Server 1.0 (running locally on my dev machine) and have managed to get a few basic examples doing what they need to do: Connect, send a message and receive a message. My starting point for these examples was on MSDN, and you’ll see the similarity in the sample I provide later.

What absolutely stumped me was that when I configured a VM and deployed the service bus software to it, my examples all failed – mostly with the same themes: Authorization failure or invalid token provider.

Clearly, the inner workings of the Microsoft.ServiceBus namespace had been doing authentication all along on my dev machine, but was now failing as the VM I had set up was only on a workgroup. To solve this, I first created a local user on the VM (called SBUser), and then used the Service Bus PowerShell to create a new namespace, and set the ManageUsers parameter to my newly created user.

New-SBNamespace -Name DarksideNamespace -ManageUsers SBUser

which should return something like this to you:

Name : DarksideNamespace
AddressingScheme : Path
CreatedTime : 11/18/2012 9:56:13 AM
IssuerName : DarksideNamespace
IssuerUri : DarksideNamespace
ManageUsers : {SBUser}
DnsEntry :
PrimarySymmetricKey : ==removed==
SecondarySymmetricKey :

In the code below, I set up a token provider that has the details of the local user on the VM, and I use that token provider when creating the namespace manager and messaging factory.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.Threading.Tasks;
  7. using Microsoft.ServiceBus;
  8. using Microsoft.ServiceBus.Messaging;
  9.  
  10. namespace Darkside
  11. {
  12.     class Program
  13.     {
  14.         static string ServerFQDN = "SBWS-VM";
  15.         static int HttpPort = 9355;
  16.         static int TcpPort = 9354;
  17.         static string ServiceNamespace = "DarksideNamespace";
  18.  
  19.  
  20.         static void Main(string[] args)
  21.         {
  22.             //Build up the connection string
  23.             ServiceBusConnectionStringBuilder connBuilder = new ServiceBusConnectionStringBuilder();
  24.             connBuilder.ManagementPort = HttpPort;
  25.             connBuilder.RuntimePort = TcpPort;
  26.             connBuilder.Endpoints.Add(new UriBuilder() { Scheme = "sb", Host = ServerFQDN, Path = ServiceNamespace }.Uri);
  27.             connBuilder.StsEndpoints.Add(new UriBuilder() { Scheme = "https", Host = ServerFQDN, Port = HttpPort, Path = ServiceNamespace }.Uri);
  28.  
  29.             //Create the token provider
  30.             var tokenProvider = TokenProvider.CreateOAuthTokenProvider(connBuilder.StsEndpoints, new NetworkCredential("SBUser", "P@ssword1", ServerFQDN));
  31.  
  32.             //Create the Namespace manager
  33.             NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connBuilder.ToString());
  34.             namespaceManager.Settings.TokenProvider = tokenProvider;
  35.  
  36.             //Create the Messaging factory
  37.             MessagingFactory messagingFactory = MessagingFactory.Create(connBuilder.Endpoints, tokenProvider);
  38.  
  39.             //Set up the queue
  40.             var queueName = "TestQueue";
  41.             QueueDescription queue;
  42.             if (namespaceManager.QueueExists(queueName))
  43.             {
  44.                 Console.WriteLine("Queue found - retrieving...");
  45.                 queue = namespaceManager.GetQueue(queueName);
  46.             }
  47.             else
  48.             {
  49.                 Console.WriteLine("Queue not found - creating...");
  50.                 queue = namespaceManager.CreateQueue(queueName);
  51.             }
  52.             Console.WriteLine("Message count: " + queue.MessageCount);
  53.  
  54.             //Set up the message sender and send a test message
  55.             MessageSender myMessageSender = messagingFactory.CreateMessageSender(queueName);
  56.             var sendMessage = new BrokeredMessage("This is my message for the time " + DateTime.Now.ToShortTimeString());
  57.  
  58.             Console.WriteLine("Sending message...");
  59.             myMessageSender.Send(sendMessage);
  60.  
  61.             //Set up the message receiver and receive a message
  62.             MessageReceiver myMessageReceiver = messagingFactory.CreateMessageReceiver(queueName);
  63.             Console.WriteLine("Receiving message...");
  64.             var receiveMessage = myMessageReceiver.Receive();
  65.  
  66.             Console.WriteLine("Received Message contents: " + receiveMessage.GetBody<string>());
  67.  
  68.             //Remove the message from the queue and dispose of the object
  69.             receiveMessage.Complete();
  70.             receiveMessage.Dispose();
  71.  
  72.             //Wait.
  73.             Console.ReadLine();
  74.         }
  75.     }
  76. }

Just a side note: This is demonstration code – please don’t hardcode everything the way I have done in the example :)


Tuesday, October 30, 2012 #

If you encounter a Null Reference Exception when debugging your Windows Phone project shortly after either renaming the solution, project or assembly, on the line

  1. PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;

It may be as a result of the project not rebuilding correctly, and more specifically, it seems to be related to the App.xaml file. I’ve found that either doing a Clean Solution and then a rebuild, or adding white space to the app.xaml file resolves the problem.


Tuesday, June 05, 2012 #

If you’d like VS2012 RC to have normal, non-screaming all-caps menus, there is a registry key you can set to remedy this!

Browse to HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\General\ and add a new DWORD – call it SuppressUppercaseConversion and set the value to 1.

If you’d prefer to do this using PowerShell, use the following line:

Set-ItemProperty -Path HKCU:\Software\Microsoft\VisualStudio\11.0\General -Name SuppressUppercaseConversion -Type DWord -Value 1

Now your menus will be ‘normal’ again :)


Wednesday, May 30, 2012 #

This question popped up on StackOverflow yesterday, so I put together a very simple example application to demonstrate how to make use of Castle Windsor for a self-hosted WCF service.

For my example, there is a service contract WindsorWCF.IMyService and a service called WindsorWCF.MyService. I've chosen to configure the service with a TCP endpoint in the app config as follows:

Code Snippet
  1. <system.serviceModel>
  2.   <services>
  3.     <service name="WindsorWCF.MyService">
  4.       <endpoint name ="IMyService_Endpoint" address="net.tcp://localhost:9872/MyService" binding="netTcpBinding" contract="WindsorWCF.IMyService" />
  5.     </service>
  6.   </services>
  7. </system.serviceModel>

Next, add an windsor xml config file (call it windsor.config) to your service project, and add a component to it:

Code Snippet
  1. <configuration>
  2.   <components>
  3.     <component id="MyService" service="WindsorWCF.IMyService, WindsorWCF" type="WindsorWCF.MyService, WindsorWCF" />
  4.   </components>
  5. </configuration>

In the service host application itself, I've added the following code (I used a console application when I wrote the code, but the idea is the same):

Code Snippet
  1. static void Main(string[] args)
  2. {
  3.     InitWindsor();
  4.     var host = new DefaultServiceHostFactory().CreateServiceHost("MyService", new Uri[0]);
  5.     host.Open();
  6.     Console.ReadLine();
  7. }
  8.  
  9. static IWindsorContainer Container { get; set; }
  10. private static void InitWindsor ()
  11. {
  12.     Container = new WindsorContainer().AddFacility<WcfFacility>().Install(Configuration.FromXmlFile("windsor.config"));
  13. }

That's it for the example - I trust it makes sense.


Friday, January 20, 2012 #

Wow – it seems like last year just flew by. I opened LiveWriter this morning and realised that I last posted an article in June 2011, and that I have 14 incomplete articles that I’ve never got round to completing.

To kick off the year, I’m going to start off with (what I think) is an underused class in Castle ActiveRecord (actually, it resides from NHibernate) – Disjunction.

The Disjunction type can be used to construct large 'OR' statements for use in ActiveRecord data retrievals. If you have used this class before, you may have noticed that any ‘OR’ operations that have more than two boolean operation that you’ve wanted to perform end up looking like this:

    var criteria = Restrictions.Or
        (
        Restrictions.Or(Restrictions.Like("Firstname", "Foo"), Restrictions.Like("Lastname", "Foo")),
        Restrictions.Or(Restrictions.Like("Firstname", "Bar"), Restrictions.Like("Lastname", "Bar"))
        );
 
    var person = Person.FindAll(criteria);

The example above ends up producing some unnecessary code clutter to essentially come up with the SQL statement:

WHERE 
   Firstname LIKE '%Foo%' OR
   Firstname LIKE '%Bar%' OR
   Lastname  LIKE '%Foo%' OR
   Lastname  LIKE '%Bar%'

Using the Disjunction class, you can modify the original example to look like this:

            var criteria = new Disjunction();
            criteria.Add(Restrictions.Like("Firstname", "Foo"));
            criteria.Add(Restrictions.Like("Firstname", "Bar"));
            criteria.Add(Restrictions.Like("Lastname", "Foo"));
            criteria.Add(Restrictions.Like("Lastname", "Bar"));
 
            var person = Person.FindAll(criteria);

In my opinion: better looking code and, although it’s not quite made evident in the examples above, it makes for much easier programming. Image that you were searching 5 fields for three keywords – the “tree” that you’ve effectively built in the first example would start looking horrendous and would be a nightmare to maintain.


Tuesday, June 07, 2011 #

A while ago I blogged about a template project that I often use as my starting point for Windows services. I’ve recently been introduced to a component called TopShelf that makes writing a service even simpler as well as taking just about all the plumbing code needed for installing/uninstalling and running in debug mode.

Here’s an example of the code that goes into the Main method. It sets up the service, name, description, and you tell it what to call on the Start and Stop service control events.

 Expand Code
        static void Main(string[] args)
        {
            const string name = "My Service Host";
            const string description = "My Service Host Description";
            var host = HostFactory.New(configuration =>
            {
                configuration.Service<ServiceHostControl>(
                    callback =>
                    {
                        callback.SetServiceName(name);
                        callback.ConstructUsing(s => new ServiceHostControl());
                        callback.WhenStarted(service => service.Start());
                        callback.WhenStopped(service => service.Stop());
                    });
                configuration.SetDisplayName(name);
                configuration.SetServiceName(name);
                configuration.SetDescription(description);
                configuration.DependsOnMsSql(); //Just here as an example of some of the features
                configuration.RunAsLocalService();
            });
            host.Run();
        }

I make reference in the code above to a class called ServiceHostControl. This class is the only other code I have in my template project as of now – it provides the stub methods for starting and stopping the service.

 Expand Code
    internal class ServiceHostControl
    {
        public void Start()
        {
            Console.WriteLine("starting...");
            //Do everything here to start up the service...
            Console.WriteLine("started.");
        }
 
        public void Stop()
        {
            Console.WriteLine("stopping...");
            //Do everything here to shut the service down...
            Console.WriteLine("stopped.");
        }
    }

There is no longer a need to have a service installer class anymore either in the project – all this functionality is brought to the party by the Topshelf component. To install your service, you simply drop to a command prompt and type in:

{serviceassembly.exe} install

and (as you can most likely guess) to uninstall, you type in:

{serviceassembly.exe} uninstall

It’s as simple as that.


Thursday, May 12, 2011 #

This is just a quick tip that you can use to restart ReSharper in Visual Studio (without restarting the IDE) if it becomes unresponsive. In my case, it just disappears from view and the majority of my shortcuts stop working.

Open the immediate window, either through the menu “Debug->Windows->Immediate” or using the keyboard shortcut “Ctl-Alt-I”.

Type in:

>ReSharper_Suspend press enter, and then

>ReSharper_Resume

You must type the “>” first to be able to enter commands in the immediate window.

 

Some other notes:

  • You can use the command window as well (just leave out the angle bracket), however, I find that the shortcut “Ctl-Alt-A” often breaks when ReSharper is broken. Moving my hand to my mouse is an effort :)
  • You could also use the command “ReSharper_ToggleSuspended” twice in a row; You just have to keep swapping to a code window to test it out.

Monday, April 04, 2011 #

I’ve been contemplating the fact that Reflector is no longer a free tool, and paying the $35 (USD) for the tool. I’ll be honest: paying for software has never been an issue for me. I even use SQL Prompt from RedGate. I write software, and need to get paid for it, for a living.

But…

The fact that RedGate said that they would continue offering Reflector for free and did an about turn on it has riled me a tad. They haven’t even offered existing users a “this-is-the-final-free-version-and-will-never-get-updated” option. Sad.

I went through the suggestions from this Stack Overflow article, and personally feel that ILSpy is the best alternative.

Here’s the list (copied from the summary from the article above):

  1. Common Compiler Infrastructure (CCI)
  2. Mono Cecil
  3. ILSpy
  4. Kaliro
  5. Dotnet IL Editor (DILE)
  6. Monoflector (no longer active as of April 2011)

Try them out – see what you think…


Wednesday, March 30, 2011 #

Configuration

Version 3 now supports the short-hand configuration options supplied by NHibernate. You choose the DB type, supply a connection string name, and the rest of the defaults are chosen for you.

  <configSections>

    <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"/>

  </configSections>

  <connectionStrings>

    <add name="ARTest" connectionString="Server=(local); Database=ComplexDBTest; Integrated Security=SSPI"/>

  </connectionStrings>

  <activerecord>

    <config db="MsSqlServer2005" csn="ARTest"/>

  </activerecord>

SessionScope-less Lazy Loading

This is a great change that’s been implemented. The code example below (very contrived, I know, but demonstrates the point) used to throw an exception, but doesn’t anymore.

    [ActiveRecord("Person", Lazy = true)]

    public partial class Person : ActiveRecordBase<Person>

    {

        [PrimaryKey(Generator = PrimaryKeyType.GuidComb, Column = "PersonId")]

        public virtual Guid Id { get; set; }

 

        [HasMany(typeof(ContactNumber), Table = "ContactNumbers", ColumnKey = "PersonId", Lazy = true)]

        public virtual IList<ContactNumber> PersonIdContactNumbersList { get; set; }

    }

 

    [ActiveRecord("ContactNumber")]

    public partial class ContactNumber : ActiveRecordBase<ContactNumber>

    {

        [PrimaryKey(Generator = PrimaryKeyType.GuidComb, Column = "ContactNumberId")]

        public virtual Guid Id { get; set; }

 

        [BelongsTo(Type = typeof(Person), Column = "PersonId")]

        public virtual Person Person { get; set; }

    }

 

    public class Program

    {

        static void Main(string[] args)

        {

            ActiveRecordStarter.Initialize(Assembly.GetExecutingAssembly(), ActiveRecordSectionHandler.Instance);

 

 

            ContactNumber contactNumber;

            using (new SessionScope())

            {

                contactNumber = ContactNumber.FindFirst(Order.Asc("Id"));

            }

            Debug.WriteLine(contactNumber.Person.Id); //Used to throw an exception

        }

    }

Make sure that in your configuration, (if you’re still specifying the entire config) you’re using the Castle.ActiveRecord.ByteCode.ProxyFactoryFactory proxy factory.

 

Lazy Loading of Blob Properties

You can now use the “Lazy” keyword on blob properties which tells NHibernate not to include this column in the select statement, but only call it when it’s explicitly used. Some notes on this, though:

  • If you have more than one column marked as lazy, they are ALL fetched when you access the first one.
  • The property should be an auto-prop
  • This results in and extra select being fired off when you used this column – it may end up being a problem in large sets of data.

The syntax is straight forward:

        [Property (Column ="Data", ColumnType = "BinaryBlob" , Lazy = true)]

        public virtual byte[] Data { get; set; }

 

LINQ

LINQ support is now rolled into the Castle ActiveRecord assembly, and doesn’t require a reference to another file.

 

SessionScopeWebModule (Breaking Change)

This has been removed from the main Castle ActiveRecord assembly and is now in the assembly Castle.ActiveRecord.Web.dll. You’ll need to update your configuration for the HttpModule as follows:

    <httpModules>

      <add name="ARScope" type="Castle.ActiveRecord.Framework.SessionScopeWebModule, Castle.ActiveRecord.Web"/>

    </httpModules>


Friday, February 11, 2011 #

It’s been a while since I used the SqlDependency class and the features it provides, and was then quite disappointed that I hadn’t a copy of the plumbing code anywhere on my web clipboard (a.k.a darkside.co.za). I’ve put together a static helper class that you can attach an event to, and then call the Start(…) method.

Here is the code for the class (UPDATE: or you can download it here):

 Expand Code
    1 using System.Data;
    2 using System.Data.SqlClient;
    3 
    4 namespace Darkside
    5 {
    6     public class SqlNotificationHelper
    7     {
    8         private static SqlConnection m_SqlConnection;
    9         private static SqlCommand m_SqlCommand;
   10         private static DataSet m_DataSet;
   11         private static string m_ConnectionString;
   12 
   13         public delegate void DataChanged(DataSet dataSet);
   14         public static event DataChanged DataChangedEvent;
   15 
   16         public static void Start(string connectionString, string sql, CommandType commandType)
   17         {
   18             m_ConnectionString = connectionString;
   19             SqlDependency.Stop(m_ConnectionString);
   20             SqlDependency.Start(m_ConnectionString);
   21             if (m_SqlConnection == null)
   22                 m_SqlConnection = new SqlConnection(m_ConnectionString);
   23             if (m_SqlCommand == null)
   24                 m_SqlCommand = new SqlCommand(sql, m_SqlConnection) { CommandType = commandType };
   25             if (m_DataSet == null)
   26                 m_DataSet = new DataSet();
   27 
   28             SetupNotification();
   29         }
   30 
   31         public static void Stop()
   32         {
   33             SqlDependency.Stop(m_ConnectionString);
   34             if (m_SqlConnection != null)
   35                 m_SqlConnection.Close();
   36         }
   37 
   38         private static void SqlDependencyOnChange(object sender, SqlNotificationEventArgs e)
   39         {
   40             var sqlDependency = sender as SqlDependency;
   41             if (sqlDependency != null)
   42                 sqlDependency.OnChange -= SqlDependencyOnChange;
   43             SetupNotification();
   44             if (DataChangedEvent != null)
   45                 DataChangedEvent(m_DataSet);
   46         }
   47 
   48         private static void SetupNotification()
   49         {
   50             m_DataSet.Clear();
   51 
   52             m_SqlCommand.Notification = null;
   53             var sqlDependency = new SqlDependency(m_SqlCommand);
   54             sqlDependency.OnChange += SqlDependencyOnChange;
   55             using (var adapter = new SqlDataAdapter(m_SqlCommand))
   56             {
   57                 adapter.Fill(m_DataSet, "DataSet");
   58             }
   59         }
   60     }
   61 }
   62 

And you can use it as follows:

protected static void Main()
{
    SqlNotificationHelper.DataChangedEvent += new SqlNotificationHelper.DataChanged(SqlNotificationHelper_DataChangedEvent);
    SqlNotificationHelper.Start("Server=(local); Database=Test; Integrated Security=SSPI", "SELECT Id, FirstName, Surname FROM dbo.People", CommandType.Text);
    Console.ReadLine();
}
 
private static void SqlNotificationHelper_DataChangedEvent(System.Data.DataSet dataSet)
{
    Console.WriteLine("Event – Data Updated." + dataSet.Tables[0].Rows.Count);
}

I should point out that you need to be quite specific in the type of query that you use. The list contained here on MSDN is quite comprehensive. The most common pitfalls I can imagine will befall people is using a * in the SELECT statement, and not specifying the table name in two-part format. The change event still fires even if the query isn’t correct, however, it fires repeatedly and can be quite a pain to debug.