<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Code Reference &#187; c#</title>
	<atom:link href="http://sullivan.net/blog/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://sullivan.net/blog</link>
	<description>A collection of code for my reference (and perhaps other people too)</description>
	<lastBuildDate>Wed, 25 Jan 2012 17:53:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Add a POST method to the WCF service</title>
		<link>http://sullivan.net/blog/2010/06/add-post-method-to-service/</link>
		<comments>http://sullivan.net/blog/2010/06/add-post-method-to-service/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 10:54:40 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=376</guid>
		<description><![CDATA[NOTE: This continues the series from the post Read the GET request parameters in the AfterReceiveRequest() method I changed the name of the SchemeTest() method to SimpleTest() because the scheme test will be done on the POST request sending XML, not on a GET request. Here is the new interface: namespace WCFServiceWithScheme { [ServiceContract] public [...]]]></description>
			<content:encoded><![CDATA[<p>NOTE: This continues the series from the post <a href="http://sullivan.net/blog/2010/06/read-get-request-parameters-in-the-afterreceiverequest-method/">Read the GET request parameters in the AfterReceiveRequest() method</a></p>
<p>I changed the name of the SchemeTest() method to SimpleTest() because the scheme test will be done on the POST request sending XML, not on a GET request.</p>
<p>Here is the new interface:</p>
<pre class="brush: c#">
namespace WCFServiceWithScheme
{
    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        [WebGet(UriTemplate = &quot;SimpleTest?name={name}&quot;)]
        string SimpleTest(string name);

        [OperationContract]
        [WebInvoke(Method = &quot;POST&quot;, UriTemplate = &quot;SchemeTest&quot;,
           BodyStyle = WebMessageBodyStyle.Bare,
           RequestFormat = WebMessageFormat.Xml)]
        string SchemeTest(RequestObject theRequest);
    }
}
</pre>
<p>Here are the new public methods:</p>
<pre class="brush: c#">
namespace WCFServiceWithScheme
{
    public class TestService : ITestService
    {
        public string SimpleTest(string name)
        {
            return &quot;The name is &quot; + name;
        }

        public string SchemeTest(RequestObject theRequest)
        {
            return &quot;nothing interesting&quot;;
        }
    }
}
</pre>
<p>We have to create the simple object that will be POSTed in the request. I called it 'RequestObject'.<br />
Notice we have included a namespace in the DataContract. This will also have to be sent in the request to the service.</p>
<pre class="brush: c#">
namespace WCFServiceWithScheme
{
    [DataContract(Namespace = &quot;http://WCFServiceWithScheme&quot;)]
    public class RequestObject
    {
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string LastName { get; set; }
        [DataMember]
        public short Age
        {
            get { return age; }
            set { age = value; }
        }

        private short age = 0;
    }
}
</pre>
<p>The XML submitted for this object is here. Notice the namespace is included.</p>
<pre class="brush: c#">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;RequestObject xmlns=&quot;http://WCFServiceWithScheme&quot;&gt;
     &lt;Age&gt;21&lt;/Age&gt;
     &lt;FirstName&gt;Howard&lt;/FirstName&gt;
     &lt;LastName&gt;Lumpy&lt;/LastName&gt;
&lt;/RequestObject&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/06/add-post-method-to-service/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Read GET request parameters in the AfterReceiveRequest() method</title>
		<link>http://sullivan.net/blog/2010/06/read-get-request-parameters-in-the-afterreceiverequest-method/</link>
		<comments>http://sullivan.net/blog/2010/06/read-get-request-parameters-in-the-afterreceiverequest-method/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 10:11:04 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=367</guid>
		<description><![CDATA[NOTE: This continues the series from the post Expand the simple service with IDispatchMessageInspector On a GET request, the relevant data is in the parameters. Here is how to read this data: Determine the request's mothod (GET or POST) You don't know what method is called or how it was called. Get the URITemplateMatchResults Get [...]]]></description>
			<content:encoded><![CDATA[<p>NOTE: This continues the series from the post <a href="http://sullivan.net/blog/2010/06/wcf-service-with-idispatchmessageinspector/">Expand the simple service with IDispatchMessageInspector</a></p>
<p>On a GET request, the relevant data is in the parameters. Here is how to read this data:</p>
<ul>
<li>Determine the request's mothod (GET or POST)<br />
             You don't know what method is called or how it was called.</li>
<li>Get the URITemplateMatchResults</li>
<li>Get the operation name (method) that was called.</li>
<li>Get the RequestUri</li>
<li>Loop thru the Querry Parameters</li>
<li>Loop thru the Bound Variables</li>
</ul>
<p>NOTE: Any request to the service will run thru there. If you have 10 different GET and POST methods in your service, a request to any of them will go thru here before it goes to the called method.</p>
<pre class="brush: c#">
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
    // Get the request message from the request
    HttpRequestMessageProperty requestMessage = request.Properties[&quot;httpRequest&quot;] as HttpRequestMessageProperty;
    string method = string.Empty;
    if (requestMessage != null)
    {
        // The method will be GET or POST.
        method = requestMessage.Method;
    }

    // Get the UriTemplateMatchResults from the request.
    // Here you can see some of the fun things that are revealed.
    UriTemplateMatch results = internalCopy.Properties[&quot;UriTemplateMatchResults&quot;] as UriTemplateMatch;
    if (results != null)
    {
        // Get the operation name from the request.
        // Here you can see what method was called in the Service.
        // Since we have only one method (SchemeTest), it should be this.
        // We can add a simple &#039;HelloWorld&#039; method to see this value change.
        string operationName = string.Empty;
        if (results.RelativePathSegments.Count &gt; 0)
            operationName = results.RelativePathSegments[results.RelativePathSegments.Count - 1];

        //
        string requestUri = results.RequestUri.ToString();

        // If the request method is GET, then you can play with the query parameters, uri template, and bound variables
        if (method == &quot;GET&quot;)
        {

            // Loop thru the querry parameters
            NameValueCollection queryParameters = results.QueryParameters;
            foreach (var p in queryParameters)
            {
                Console.WriteLine(p);
            }

            // The Uri template is the same as in the Attribute of the interface: [WebGet(UriTemplate = &quot;SchemeTest?name={name}&quot;)]
            string template = results.Template.ToString();

            // You can loop thru the key in the variables passed in.
            NameValueCollection boundVariables = results.BoundVariables;
            foreach (string key in boundVariables.AllKeys)
            {
                // Variable names are always in UPPER case. Don&#039;t know why.
                if (key == &quot;NAME&quot;)
                    Console.WriteLine(&quot;This is the &#039;name&#039; key&quot;);
            }
        }

       Object correlationState = new object();
       return correlationState;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/06/read-get-request-parameters-in-the-afterreceiverequest-method/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>CreateBufferedCopy of request in MessageInspector of WCF Service</title>
		<link>http://sullivan.net/blog/2010/06/createbufferedcopy-of-request/</link>
		<comments>http://sullivan.net/blog/2010/06/createbufferedcopy-of-request/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 09:55:28 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=364</guid>
		<description><![CDATA[NOTE: This continues the series from Expand the simple service with IDispatchMessageInspector When your web service is called, before the request reaches the main service method, the 'AfterReceiveRequest()' method is fired. Here is where you can inspect the request. Very important to know, you must make a copy of the message because reading the original [...]]]></description>
			<content:encoded><![CDATA[<p>NOTE: This continues the series from <a href="http://sullivan.net/blog/2010/06/wcf-service-with-idispatchmessageinspector/">Expand the simple service with IDispatchMessageInspector</a></p>
<p>When your web service is called, before the request reaches the main service method, the 'AfterReceiveRequest()' method is fired.<br />
Here is where you can inspect the request.</p>
<p>Very important to know, you must make a copy of the message because reading the original message changes its State from 'created' to 'copied' and downstream processing won't work. Do this by creating a buffered copy.<br />
NOTE: This applies mostly to getting the message body from a POST request.</p>
<pre class="brush: c#">
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
    Console.WriteLine(&quot;Inside the ApplyClientBehavior&quot;);

    // Create a buffered copy of the request.
    // You can then use the internal copy to work with.
    MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
    request = buffer.CreateMessage();
    Message internalCopy = buffer.CreateMessage();
    buffer.Close();

    // Check the message state easily
    Console.WriteLine(&quot;State of message: &quot; + internalCopy.State);

    Object correlationState = new object();
    return correlationState;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/06/createbufferedcopy-of-request/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WCF Service with IDispatchMessageInspector</title>
		<link>http://sullivan.net/blog/2010/06/wcf-service-with-idispatchmessageinspector/</link>
		<comments>http://sullivan.net/blog/2010/06/wcf-service-with-idispatchmessageinspector/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 08:13:34 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=350</guid>
		<description><![CDATA[If you want to do any pre or post inspection of a web service such as scheme validation, you can use the IDispatchMessageInspector. This example is based on the Simple Service example. I modified the Simple Service example and added the IDispatchMessageInspector. The IDispatchMessageInspector gives you access to 2 events. - AfterReceiveRequest() fires before you [...]]]></description>
			<content:encoded><![CDATA[<p>If you want to do any pre or post inspection of a web service such as scheme validation, you can use the IDispatchMessageInspector.</p>
<p>This example is based on the <a href="http://sullivan.net/blog/2009/08/wcf-simple-servcie/">Simple Service</a> example. I modified the Simple Service example and added the IDispatchMessageInspector.</p>
<p>The IDispatchMessageInspector gives you access to 2 events.<br />
 - AfterReceiveRequest() fires before you enter the web service method:<br />
   object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { return new Object; }<br />
 - BeforeSendReply() fires after you leave the web service method:<br />
   void BeforeSendReply(ref Message reply, object correlationState) { }</p>
<p>The object returned from the first method is the 'correlationSate' object of the 2nd method. If your custom validation fails in the first, you can return a 'correlationState' object that the 2nd method will receive automatically. This allows you to return 'Bad Request' or something like that.</p>
<p>There is nothing unusual about the Interface for the service as you can see in ITestService.cs:</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

using System.ServiceModel.Web;

namespace WCFServiceWithScheme
{
    // NOTE: If you change the interface name &quot;ITestService&quot; here, you must also update the reference to &quot;ITestService&quot; in Web.config.

    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        [WebGet(UriTemplate = &quot;SchemeTest?name={name}&quot;)]
        string SchemeTest(string name);
    }
}
</pre>
<p>There is also nothing unusual about the class that inherits from the interface. TestService.svc.cs:</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFServiceWithScheme
{
    public class TestService : ITestService
    {
        public string SchemeTest(string name)
        {
            return &quot;The name is &quot; + name;
        }
    }
}
</pre>
<p>The differences begin to show in the Web.config.<br />
You will see the 'behaviorExtensions' tag and the additional addition to the 'endpointBehaviors'.<br />
The name for the 'behaviorExtensions' is the new behavior in the 'endpointBehavior'.<br />
The behaviorExtensions' TYPE is the name of the BehaviorExtensionElement class followed by the namespace. </p>
<p>The system.serviceModel in the Web.confi:</p>
<pre class="brush: c#">
  &lt;system.serviceModel&gt;

    &lt;!-- Required for IDispatchMessageInspector --&gt;
    &lt;extensions&gt;
      &lt;behaviorExtensions&gt;
        &lt;add name=&quot;restHttpBehavior&quot; type=&quot;WCFServiceWithScheme.MyBehaviorExtensionElement, WCFServiceWithScheme, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&quot;/&gt;
      &lt;/behaviorExtensions&gt;
    &lt;/extensions&gt;

    &lt;bindings&gt;
      &lt;!-- Minimum for WebHttp --&gt;
      &lt;webHttpBinding&gt;
        &lt;binding name=&quot;WCFServiceWithScheme.MyDefaultBinding&quot;/&gt;
      &lt;/webHttpBinding&gt;
    &lt;/bindings&gt;

    &lt;behaviors&gt;

      &lt;!-- serviceBehaviors --&gt;
      &lt;serviceBehaviors&gt;
        &lt;behavior name=&quot;WCFServiceWithScheme.MyServiceBehavior&quot;&gt;
          &lt;serviceMetadata httpGetEnabled=&quot;true&quot; /&gt;
          &lt;serviceDebug includeExceptionDetailInFaults=&quot;false&quot; /&gt;
        &lt;/behavior&gt;
      &lt;/serviceBehaviors&gt;

      &lt;!-- endpointBehaviors --&gt;
      &lt;endpointBehaviors&gt;
        &lt;behavior name=&quot;WCFServiceWithScheme.MyWebBehavior&quot;&gt;
          &lt;webHttp/&gt;
          &lt;restHttpBehavior/&gt;
        &lt;/behavior&gt;
      &lt;/endpointBehaviors&gt;

    &lt;/behaviors&gt;

    &lt;services&gt;

      &lt;!-- Minimum for WebHttp --&gt;
      &lt;service behaviorConfiguration=&quot;WCFServiceWithScheme.MyServiceBehavior&quot; name=&quot;WCFServiceWithScheme.TestService&quot;&gt;

        &lt;!-- Minimum for WebHttp --&gt;
        &lt;endpoint address=&quot;web&quot; behaviorConfiguration=&quot;WCFServiceWithScheme.MyWebBehavior&quot; binding=&quot;webHttpBinding&quot; contract=&quot;WCFServiceWithScheme.ITestService&quot; bindingConfiguration=&quot;WCFServiceWithScheme.MyDefaultBinding&quot;&gt;
          &lt;identity&gt;
            &lt;dns value=&quot;localhost&quot;/&gt;
          &lt;/identity&gt;
        &lt;/endpoint&gt;

      &lt;/service&gt;

    &lt;/services&gt;
  &lt;/system.serviceModel&gt;
</pre>
<p>There are 2 new classes that you must create:<br />
* A MessageInspector class that inherits from IDispatchMessageInspector<br />
* A BehaviorExtensionElement class that inherits from BehaviorExtensionElement and IEndpointBehavior.</p>
<p>The MessageInspector class contains the AfterReceiveRequest and BeforeSendReply methods.<br />
Place break points in these methods and you can see the order in which they are fired.</p>
<p>The MyMessageInspector.cs class:</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Dispatcher;

namespace WCFServiceWithScheme
{
    public class MyMessageInspector : IDispatchMessageInspector
    {

        #region IDispatchMessageInspector Members

        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            Console.WriteLine(&quot;Inside the ApplyClientBehavior&quot;);
            // Good idea to return error class stuff to let you know if anything happened in here
            Object correlationState = new object();
            return correlationState;
        }

        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            // !!!!!!!!! correlationState comes from the AfterReceiveRequest method !!!!!!!!!!!!!
            // If the AfterReceiveRequest method determines it is a bad request, this is where you return, &#039;Bad Request&#039;
            Console.WriteLine(&quot;Inside the ApplyClientBehavior&quot;);
        }

        #endregion
    }
}
</pre>
<p>The BehaviorExtensionElement class contains several methods. The most important one is 'ApplyDispatchBehavior(). This is where you add your message inspector.</p>
<p>The Validate() is fired only during initialization of the service and before ApplyDispatchBehavior().<br />
To test this when running locally, do an IISreset, place a break point in the Validate() method and the other methods, and hit F5 to start debugging. </p>
<p>MyBehaviorExtensionElement.cs</p>
<pre class="brush: c#">
using System;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;

namespace WCFServiceWithScheme
{
    public class MyBehaviorExtensionElement : BehaviorExtensionElement, IEndpointBehavior
    {
        #region BehaviorExtensionElement
        public override Type BehaviorType
        {
            get { return typeof(MyBehaviorExtensionElement); }
        }

        protected override object CreateBehavior()
        {
            return new MyBehaviorExtensionElement();
        }
        #endregion

        #region IEndpointBehavior Members

        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            Console.WriteLine(&quot;Inside the AddBindingParameters&quot;);
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            Console.WriteLine(&quot;Inside the ApplyClientBehavior&quot;);
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {
            Console.WriteLine(&quot;Adding custom message inspector...&quot;);
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MyMessageInspector());
        }

        public void Validate(ServiceEndpoint endpoint)
        {
            Console.WriteLine(&quot;Inside the Validate&quot;);
        }

        #endregion
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/06/wcf-service-with-idispatchmessageinspector/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>WCF Web Service with Scheme Validation and other tricks</title>
		<link>http://sullivan.net/blog/2010/06/wcf-web-service-with-scheme-validation-and-other-tricks/</link>
		<comments>http://sullivan.net/blog/2010/06/wcf-web-service-with-scheme-validation-and-other-tricks/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 08:12:56 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=357</guid>
		<description><![CDATA[This series of posts will cover the various aspects of creating a WCF web service that will use a scheme to validate. NOTE: This is different than the Secure WCF REST webservice I posted earlier. The previous one uses the WCF REST Starter Kit and has a very simple Web.config. This series covers: Creating a [...]]]></description>
			<content:encoded><![CDATA[<p>This series of posts will cover the various aspects of creating a WCF web service that will use a scheme to validate.</p>
<p>NOTE: This is different than the <a href="http://sullivan.net/blog/2009/12/secure-wcf-rest-part1-xml-schema-validation/">Secure WCF REST webservice</a> I posted earlier. The previous one uses the WCF REST Starter Kit and has a very simple Web.config.</p>
<p>This series covers:</p>
<ul>
<li>Creating a <a href="http://sullivan.net/blog/2009/08/wcf-simple-servcie/">Simple Service</a> based on REST</li>
<li><a href="http://sullivan.net/blog/2010/06/wcf-service-with-idispatchmessageinspector/">Expand the simple service with IDispatchMessageInspector</a></li>
<li><a href="http://sullivan.net/blog/2010/06/read-get-request-parameters-in-the-afterreceiverequest-method/">Read the GET request parameters in the AfterReceiveRequest() method</a></li>
<li><a href="http://sullivan.net/blog/2010/06/add-post-method-to-service/">Add a POST method to the service</a></li>
<li>How and why you should <a href="http://sullivan.net/blog/2010/06/createbufferedcopy-of-request/">use 'CreateBufferedCopy' to clone the request</a></li>
<li><a href="http://">Read the message body in a POST request</a></li>
<li>Loading and using the scheme</li>
<li>Dynamically expanding the UriTemplate on a Get request</li>
<li>How to optionally embed the XSD file in the assembly</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/06/wcf-web-service-with-scheme-validation-and-other-tricks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simpel context menues in WPF</title>
		<link>http://sullivan.net/blog/2010/05/simpel-context-menues-in-wpf/</link>
		<comments>http://sullivan.net/blog/2010/05/simpel-context-menues-in-wpf/#comments</comments>
		<pubDate>Fri, 28 May 2010 09:44:50 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=332</guid>
		<description><![CDATA[The first thin you must do is to create the context menu in the xaml page. This is done as follows: &#60;UserControl.ContextMenu&#62; &#60;ContextMenu Name=&#34;rightClickContextMenu&#34; Visibility=&#34;Collapsed&#34;&#62; &#60;MenuItem Header=&#34;Delete&#34; Name=&#34;btnDelete&#34; Click=&#34;btnDelete_Click&#34;/&#62; &#60;MenuItem Header=&#34;Open&#34; Name=&#34;btnOpen&#34; Click=&#34;btnOpen_Click&#34;/&#62; &#60;MenuItem Header=&#34;Copy&#34; Name=&#34;btnCopy&#34; Click=&#34;btnCopy_Click&#34;/&#62; &#60;/ContextMenu&#62; &#60;/UserControl.ContextMenu&#62; Listen for the right click event and display the menu private void m(object sender, MouseEventArgs e) [...]]]></description>
			<content:encoded><![CDATA[<p>The first thin you must do is to create the context menu in the xaml page.<br />
This is done as follows:</p>
<pre class="brush: c#">
&lt;UserControl.ContextMenu&gt;
    &lt;ContextMenu Name=&quot;rightClickContextMenu&quot; Visibility=&quot;Collapsed&quot;&gt;
        &lt;MenuItem Header=&quot;Delete&quot; Name=&quot;btnDelete&quot; Click=&quot;btnDelete_Click&quot;/&gt;
        &lt;MenuItem Header=&quot;Open&quot; Name=&quot;btnOpen&quot; Click=&quot;btnOpen_Click&quot;/&gt;
        &lt;MenuItem Header=&quot;Copy&quot; Name=&quot;btnCopy&quot; Click=&quot;btnCopy_Click&quot;/&gt;
    &lt;/ContextMenu&gt;
&lt;/UserControl.ContextMenu&gt;
</pre>
<p>Listen for the right click event and display the menu</p>
<pre class="brush: c#">
private void m(object sender, MouseEventArgs e)
{
    if (e.RightButton == MouseButtonState.Pressed)
    {

        rightClickContextMenu.PlacementRectangle = new Rect(e.GetPosition(diagram), new Size());
        rightClickContextMenu.Visibility = Visibility.Visible;
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/05/simpel-context-menues-in-wpf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Facebook: The very basics required for your first application</title>
		<link>http://sullivan.net/blog/2010/05/facebook-the-very-basics-required-for-your-first-application/</link>
		<comments>http://sullivan.net/blog/2010/05/facebook-the-very-basics-required-for-your-first-application/#comments</comments>
		<pubDate>Fri, 21 May 2010 10:04:05 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Facebook]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=329</guid>
		<description><![CDATA[I was required to create a Facebook (Viesbook in Dutch) application for my work. I discovered how much I hate Facebook, it view of privacy, and especially, their API documentation. Their documentation is the worse I have ever seen. If you want to work in C#, don't go to Facebook. I found a great set [...]]]></description>
			<content:encoded><![CDATA[<p>I was required to create a Facebook (Viesbook in Dutch) application for my work. I discovered how much I hate Facebook, it view of privacy, and especially, their API documentation. Their documentation is the worse I have ever seen.</p>
<p>If you want to work in C#, don't go to Facebook. I found a great set of Libraries from Vatlab (<a href="http://vatlab.com/">Vatlab - Facebook .NET Applications</a>). The support for their libraries is excellent! I got replied back immediately.</p>
<p>I will now give a very basic framework (based on the Vatlap Starter Kit) that will give you an Application page and a Profile Wall-Tab widget. </p>
<p>Based on the Starter Kit from the VatLap package, you will have:</p>
<ul>
<li>Master.Master</li>
<li>Default.aspx</li>
<li>SecondPage.aspx</li>
<li>GlobalData.cs</li>
<li>Web.config - after creating your </li>
<li>Images directory</li>
<li>FVK directory - can be used to customize the existing functinality used in the starter kit. Not necessary to change anything to get the basic structure working.</li>
</ul>
<p><strong>First step: </strong></p>
<ul>
<li>Sign in to your Facebook account</li>
<li>Open a new tab and go to <a href="http://www.facebook.com/developer">http://www.facebook.com/developer</a>. </li>
<li>Click the allow</li>
<li>One the developer page, click the 'Set Up New Application' button. This process is explained in the VatLab documentation. When you are finished, you will have an API Key, Application Secret code, and an Applicatin ID. These must be copied to to your Web.config file.</li>
</ul>
<p>Now you are ready to modify the Start Kit pages</p>
<p><strong>Update Master.Master</strong><br />
I disabled the bookmark stuff. I am trying to keep it as simple as possible.<br />
I also disabled the 'SecondPage.aspx'. I don't need it for this.<br />
The Invite Friends tab I left because it works and you can ignore it. It does work well.</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyNamespace
{
    public partial class Master : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //AppUser loggedUser = SessionData.LoggedUser;
            //if (loggedUser.bookmark.HasValue &amp;&amp; loggedUser.bookmark == true)
            //{
            //    bookmark1.Visible = false;
            //}

            if (!Page.IsPostBack)
            {
                tab1.AddTab(&quot;Home Page&quot;, &quot;Default.aspx&quot;, 100);
                //tab1.AddTab(&quot;Second Page&quot;, &quot;SecondPage.aspx&quot;, 100);
                tab1.AddTab(&quot;Invite Friends&quot;, &quot;Invite.aspx&quot;, 100);

                tab1.NumOfRightTabs = 1;
                tab1.Distance = 5;
            }
        }

        //protected void BookmarkCalled(object sender, EventArgs e)
        //{
        //    //DAL.AppUserDAL.SetBookmark(SessionData.LoggedUser.id);
        //    bookmark1.Visible = false;
        //}
    }
}
</pre>
<p>On the Source page, I commented out the bookmark reference and the banner:</p>
<pre class="brush: c#">
&lt;%--&lt;img src=&quot;Images/banner.png&quot; alt=&quot;&quot; /&gt;--%&gt;
&lt;%--&lt;fb:bookmark ID=&quot;bookmark1&quot; runat=&quot;server&quot; AppName=&quot;Facebook Start&quot; ImageUrl=&quot;~/Images/bookmark.png&quot; OnBookmarkCalled=&quot;BookmarkCalled&quot; /&gt;--%&gt;
</pre>
<p><strong>Default page</strong><br />
The 'Add to profile' button is very important. This is how users can add your application to their Profile Wall-Tab without having to go to 'Account|Applications'.<br />
You must register the user control and then add it to the page.</p>
<p>On the same page, you should add whatever content you want on your Applicaiton's default page.</p>
<pre class="brush: c#">
&lt;%@ Page Title=&quot;&quot; Language=&quot;C#&quot; MasterPageFile=&quot;~/Master.Master&quot; AutoEventWireup=&quot;true&quot; CodeBehind=&quot;Default.aspx.cs&quot; Inherits=&quot;MyNamespace.Default&quot; %&gt;
&lt;%@ Register TagPrefix=&quot;fvk&quot; TagName=&quot;addtoprofile&quot; Src=&quot;~/FVK/AddtoProfileButton.ascx&quot; %&gt;
&lt;asp:Content ID=&quot;Content1&quot; ContentPlaceHolderID=&quot;head&quot; runat=&quot;server&quot;&gt;
&lt;/asp:Content&gt;
&lt;asp:Content ID=&quot;Content2&quot; ContentPlaceHolderID=&quot;ContentPlaceHolder1&quot; runat=&quot;server&quot;&gt;
    &lt;fvk:addtoprofile ID=&quot;addtoprofile1&quot; runat=&quot;server&quot; /&gt;

    Hello world!

&lt;/asp:Content&gt;
</pre>
<p>The code behind page contains the magic.<br />
To add the Profile page Wall-Tab widget, you have to make a call to SetFBML and pass in the User ID and the HTML code you want to display in the column. </p>
<p>To pass in the User ID, the user must be logged in. </p>
<ul>
<li>RequireLogin = true;' - must be in the constructor.</li>
<li> 'Facebook.Schema.user user = Api.Users.GetInfo();' - this gets the user info which includes ID, Name and all that stuff.</li>
<li>'Api.Profile.SetFBML((long)user.uid, fmbl, fmbl, null);' - The call that will build the Wall-Tab widget.<BR><br />
             NOTE: Once built, the wall tab will not change. Another call to SetFBML must be made to change the content.<BR></li>
</ul>
<p>As an example, I added a very simple form. This is an AJAX type FaceBook form that will call another page and update itself. More on this below.</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
using Facebook.Web;
using FVK;

namespace MyNamespace
{
    public partial class Default : CanvasIFrameBasePage
    {
        public Default()
        {
            // User must be logged in
            RequireLogin = true;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GlobalData.Init();
            }

            // Get the user info
            Facebook.Schema.user user = Api.Users.GetInfo();
            if (user != null &amp;&amp; user.uid != null)
            {
                // Create the HTML code to show in the Wall-Tab widget
                string fmbl = &quot;&lt;form style=\&quot;margin: 0px; padding: 0px;\&quot;&gt;&quot;;
                fmbl += &quot;&lt;div id=\&quot;responseDiv\&quot;&gt;&lt;/div&gt;&quot;;
                fmbl += &quot;&lt;input type=\&quot;text\&quot; name=\&quot;requestField\&quot; id=\&quot;requestField\&quot;/&gt;&quot;;
                fmbl += &quot;&lt;input type=\&quot;submit\&quot; clickrewriteurl=\&quot;http://mydomain.com/mydir/doSomething.aspx\&quot; clickrewriteid=\&quot;responseDiv\&quot; clicktoshow=\&quot;responseDiv\&quot; value=\&quot;Do something\&quot; /&gt;&quot;;
                Api.Profile.SetFBML((long)user.uid, fmbl, fmbl, null);
            }
            else
            {
                // cannot get user info. Do something.
            }
        }
    }
}
</pre>
<p><strong>That is it!</strong><br />
It is really that simple. If you try to find this on your own, you will most likely run across libraries that don't work well or are not documented well. Between libraries, things work differently. So the documentation you read in one post may not apply to your work.</p>
<p>If the content in the Wall-Tab widget is static, how can it be updated?<br />
Facebook created Mock-AJAX. Here is how it works:</p>
<pre class="brush: c#">
// This DIV will be updated dynamically with the content returned.
fmbl += &quot;&lt;div id=\&quot;responseDiv\&quot;&gt;&lt;/div&gt;&quot;;
// This is a simple form tag that send content to the page behind.
fmbl += &quot;&lt;input type=\&quot;text\&quot; name=\&quot;requestField\&quot; id=\&quot;requestField\&quot;/&gt;&quot;;
// This submit tag, when clicked, will call the page &#039;doSomething.aspx&#039;. The response will be placed in &#039;responseDiv&#039;.
fmbl += &quot;&lt;input type=\&quot;submit\&quot; clickrewriteurl=\&quot;http://mydomain.com/mydir/doSomething.aspx\&quot; clickrewriteid=\&quot;responseDiv\&quot; clicktoshow=\&quot;responseDiv\&quot; value=\&quot;Do something\&quot; /&gt;&quot;;
</pre>
<p>It works well and it is simple.</p>
<p>doSomething.aspx can return anything from text to HTML code.</p>
<p>I hope this helps someone.</p>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/05/facebook-the-very-basics-required-for-your-first-application/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Trouble with VS 2008?</title>
		<link>http://sullivan.net/blog/2010/04/trouble-with-vs-2008/</link>
		<comments>http://sullivan.net/blog/2010/04/trouble-with-vs-2008/#comments</comments>
		<pubDate>Fri, 23 Apr 2010 09:50:42 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=327</guid>
		<description><![CDATA[If you are having trouble opening a project in VS? It says the file have been download from the Team Foundation server, yet they are not. You may want to re-initialize Visual Studio. Close VS. Open the VS Command Prompt. Enter the command: devenv /setup With luck this will solve some of your problem. What [...]]]></description>
			<content:encoded><![CDATA[<p><strong>If you are having trouble opening a project in VS? </strong><br />
It says the file have been download from the Team Foundation server, yet they are not. You may want to re-initialize Visual Studio.</p>
<p>Close VS.<br />
Open the VS Command Prompt.<br />
Enter the command: devenv /setup<br />
With luck this will solve some of your problem. What exactly does it do? Oh the mysteries of Microsoft.</p>
<p><strong>Visual Studio is not closing?</strong><br />
If VS refuses to close, then open the Task Manager.<br />
In the Processes tab, kill all instinces of devenv.exe</p>
<p><strong>Workspace cleaning can help speed things up.. if you are lucky.</strong><br />
Open the Pending Changes window (View | Other Windows | Pending Changes).<br />
In the Workspace select box select 'Workspaces...<br />
If you see more than one workspace you may be want to remove the ones you don't use.<br />
Edit each one to view the Working Folders. It will show the Source Control folder and the Local folder.<br />
If one of your workspaces has old info, remove it.<br />
Cleaning up garbage always helps.</p>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/04/trouble-with-vs-2008/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding comments to cells using Interop.Excel</title>
		<link>http://sullivan.net/blog/2010/04/adding-comments-to-cells-using-interop-excel/</link>
		<comments>http://sullivan.net/blog/2010/04/adding-comments-to-cells-using-interop-excel/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 09:44:03 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Excel]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=322</guid>
		<description><![CDATA[Before I showed how to create an excel document programmatically. It is very easy to add comments to the cells. There is one thing you should know first. Comments are not added to a range of cells. They are only added to the 1 cell in a range. If you have a range extending from [...]]]></description>
			<content:encoded><![CDATA[<p>Before I showed how to <a href="http://sullivan.net/blog/2010/04/export-to-excel-in-c/">create an excel document programmatically</a>. </p>
<p>It is very easy to add comments to the cells. There is one thing you should know first. Comments are not added to a range of cells. They are only added to the 1 cell in a range.</p>
<p>If you have a range extending from B1 to C5, the comment is added to cell B1.</p>
<p>You would think you can simple add a comment to the range you are adding your value with. That is not so and I could find nowhere that this is mentioned (If Microsoft documented their stuff well, we would not need these blogs).</p>
<p>Adding to my previous example, I created 2 new methods to handle comments. This time I excluded the 'end' cell:</p>
<pre class="brush: c#">
public void AddCommentToCell(int x, int y, string comment)
{
    if (x &lt; 1) x = 1;
    if (y &lt; 1) y = 1;

    string start = excelColumnLetter(x - 1) + y.ToString();
    AddCommentToCell(start, comment);
}

public void AddCommentToCell(string start, string comment)
{
    Range range = (Range)sheet.get_Range(start, missing);
    range.ClearComments();
    range.AddComment(comment);
}
</pre>
<p>These methods are used as such</p>
<pre class="brush: c#">
// First create the cell
xl.AddContentToCell(x, y, 1, rowSpan, text);
// Then add the comment
xl.AddCommentToCell(x, y, comment);
</pre>
<p>This examples shows adding the comment. You can see that I must create a new range for the comment. The 'end' must be 'missing':</p>
<pre class="brush: c#">
string start = &quot;A1&quot;;
string end = &quot;C3&quot;;

Range range = (Range)sheet.get_Range(start, end);
range.MergeCells = true;
range.WrapText = true;

range.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignTop;
range.Borders.LineStyle = XlLineStyle.xlDash;
range.Borders.Weight = XlBorderWeight.xlMedium;
range.Borders.Color = 0x060606;
range.Interior.Color = 0xffff8080;
range.Value2 = &quot;Content for the cell&quot;;
range.ColumnWidth = width;
range.RowHeight = height;

Range cRange = (Range)sheet.get_Range(start, System.Reflection.Missing.Value);
cRange.AddComment(&quot;hello there&quot;);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/04/adding-comments-to-cells-using-interop-excel/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using external libraries in a SSIS Script Component</title>
		<link>http://sullivan.net/blog/2010/04/using-external-libraries-in-a-ssis-script-component/</link>
		<comments>http://sullivan.net/blog/2010/04/using-external-libraries-in-a-ssis-script-component/#comments</comments>
		<pubDate>Fri, 02 Apr 2010 11:14:38 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[T-SQL]]></category>
		<category><![CDATA[Console Application]]></category>
		<category><![CDATA[DllImport]]></category>
		<category><![CDATA[SSIS]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=315</guid>
		<description><![CDATA[I found myself needing to encrypt a column of data in a SSIS package. I added a Script Component that would take one field from the database and return the same field encrypted. The library that does the encrypting was not written in Visual Studio. It was created in Power Basic I think. Normally, you [...]]]></description>
			<content:encoded><![CDATA[<p>I found myself needing to encrypt a column of data in a SSIS package.<br />
I added a Script Component that would take one field from the database and return the same field encrypted.<br />
The library that does the encrypting was not written in Visual Studio. It was created in Power Basic I think.</p>
<p>Normally, you would just import the library using DLLImport and run the method you need. Like this:</p>
<pre class="brush: c#">
private const string MYENCRYPTOR = @&quot;C:\Encrypt.dll&quot;;

[DllImport(MYENCRYPTOR, EntryPoint = &quot;ENCRYPTMYID&quot;, SetLastError = true, CharSet = CharSet.Ansi)]
private static extern string EncryptMyId(int myId);
...
...
...
string encryptedId = EncryptMyId(id);
</pre>
<p>This works in a normal project, but for some reason I do not know, it will not work in an SSIS package.<br />
To fix this, I created a Console Application wrapper for the encrypt method.<br />
The console application accepts the ID as an input variable and returns the encrypted ID as a string.</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace ExcryptThis
{
    class Program
    {
        private const string MYENCRYPTOR = @&quot;C:\Encrypt.dll&quot;;

        [DllImport(MYENCRYPTOR, EntryPoint = &quot;ENCRYPTMYID&quot;, SetLastError = true, CharSet = CharSet.Ansi)]
        private static extern string EncryptMyId(int myId);

        static void Main(string[] args)
        {
            string sId;
            if (args.Count&lt;string&gt;() &gt; 0)
            {
                sId = args[0];

                try
                {
                    int id = Convert.ToInt32(sId);
                    string encryptedId = EncryptMyId(id);
                    Console.Write(encryptedId);
                }
                catch (Exception ex) { }
            }
        }
    }
}
</pre>
<p>Note: be sure to use a Console.Write and not a .WriteLine or you will add a "\r\n" at the end of the returned value.</p>
<p>Then, in the SSIC Script Component, I call the console application as I described <a href="http://sullivan.net/blog/2010/04/run-command-line-program-from-c/">in my previous post</a>.</p>
<p>Wrapped in the console application it runs fine.</p>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/04/using-external-libraries-in-a-ssis-script-component/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

