<?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>Some thoughts about .Net programming </title>
	<atom:link href="http://softblog.violet-tape.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://softblog.violet-tape.net</link>
	<description>Violet Tape</description>
	<lastBuildDate>Mon, 31 Oct 2011 10:19:26 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1.22</generator>
	<item>
		<title>MEF</title>
		<link>http://softblog.violet-tape.net/2011/05/05/mef/</link>
		<comments>http://softblog.violet-tape.net/2011/05/05/mef/#comments</comments>
		<pubDate>Thu, 05 May 2011 08:51:16 +0000</pubDate>
		<dc:creator><![CDATA[Koissakh Kadderah]]></dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Extensions]]></category>
		<category><![CDATA[MEF]]></category>
		<category><![CDATA[plugins]]></category>

		<guid isPermaLink="false">http://softblog.violet-tape.net/?p=169</guid>
		<description><![CDATA[Today I wish to tell about the build system a dynamic, modular application using Managed Extensibility Framework (MEF). Generally this is quite an old technology, which resulted from the system Add-On from the company Microsoft. MEF was a friendly shell over the monstrous system previously proposed. The result was so … <a href="http://softblog.violet-tape.net/2011/05/05/mef/"> Continue reading <span class="meta-nav">&#8594; </span></a>]]></description>
				<content:encoded><![CDATA[<p>Today I wish to tell about the build system a dynamic, modular application using Managed Extensibility Framework (MEF). Generally this is quite an old technology, which resulted from the system Add-On from the company Microsoft. MEF was a friendly shell over the monstrous system previously proposed. The result was so good that the MEF included in delivery .Net Framework 4 by default, so no need to search and download the library separately, and worry whether the library has a person.</p>
<p>It is also now clear that this technology can be used in the development of Enterprise, as it is in the main supply of the framework, but it&#8217;s such an argument against which project managers do not trample. Typically, project managers are very reluctant to use technologies and products which are not mentioned in press releases MS, even if the technology is widely and successfully used by the community. Although they can understand, this is the first point on which they will be kicking in the event of any overlap.</p>
<p>So, MEF easy to make the application modular, and adding new libraries can be carried out on the fly, without the use of sophisticated techniques. All the code is transparent and easy to understand.</p>
<p>MEF can be used starting with version. Net 3.5, taking the necessary libraries from CodePlex. As you may have guessed, from there you can take the source code and see how it all works.</p>
<h1>Main features of MEF:</h1>
<ul>
<li>Provides a standardized way to organize workshops for the application and its appendices. In general, supplements are not tied to a specific application and implement a common interface can be used by different programs, which generally does not cancel and tight binding to the master application. Supplements may be dependent on one another and MEF alone connect them in the correct order.</li>
<li>Provides search and download of the add-ons by MEF</li>
<li>Allows you to tag metadata additions for additional opportunities to connect and filter adds.</li>
</ul>
<p><span id="more-169"></span></p>
<h1>Creating a simple application</h1>
<p>For the beginning do something in the spirit of the HelloWorld application, and then do something more useful, because I would curse myself if focused on HelloWorld example that usually does not demonstrate anything))</p>
<p>So, the application will be very simple that can be. Let it be a console and will display the phrase in various languages, depending on what type of library we will choose as the application. For the beginning ,that&#8217;s it! You will be able to focus only on the MEF code.</p>
<p>Create a console application. It will be the master application. In order to connect and find other libraries allocate additional communication interface in the assembly. So, at this stage we will have a console project <strong>HelloConsole</strong> and the assembly <strong>LangDefiniton</strong>.</p>
<p>To a project HelloConsole add reference to the assembly <strong>System.</strong><strong>ComponentModel.</strong><strong>Composition</strong> System.ComponentModel.Composition and to our library LangDefinition. At this point the solution should look like this:</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/05/mef-01.png"><img class="alignnone size-full wp-image-595" title="mef-01" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/05/mef-01.png" alt="" width="333" height="368" /></a></p>
<p>In the project LangDefinition create a new interface, where we define the method SayHello, which will return the needed text.</p>
<pre class="brush: csharp">namespace LangDefinition {
    public interface ILanguage {
        string SayHello();
    }
}</pre>
<p>&nbsp;</p>
<p>After the defined the interface, you can write code that will load use a supplement to our application. To do this, go to the project HelloConsole and there create a class AddingComposer.</p>
<p>The method, which is responsible for finding and downloading additions will LoadAddings. It shall indicate in which directory to look for additions and load them.</p>
<pre class="brush: csharp">public void LoadAddings() {
    var catalog = new AggregateCatalog();
    catalog.Catalogs.Add(new DirectoryCatalog("Adding"));

    var container = new CompositionContainer(catalog);
    container.ComposeParts(this);
}</pre>
<p>&nbsp;</p>
<p>On the third line indicates exactly where to look for additions. In this case, the specified provider DirectoryCatalog, which allows you to specify the path to the directory with additions (absolute or relative path of the executable library, in this case, the executable file), including filters to specify the library search.</p>
<p>You can also specify an assembly where to look for additions. For this we need to create <strong>AssemblyCatalog</strong>. In addition, you can specify the types that need to be imported. Use the TypeCatalog.</p>
<p>On the fifth line specifies what and how to gather in the main application. You can mark additions as thread-safe .</p>
<p>To gain access to that found by complement, one has to interface with our field and mark it with a special attribute Import, which tells the system that is imported from the supplement type. Total class would look like this:</p>
<pre class="brush: csharp">public class AddingComposer {
    [Import]
    public ILanguage Language { get; set; }

    public void LoadAddings() {
        var catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new DirectoryCatalog("Adding"));

        var container = new CompositionContainer(catalog);
        container.ComposeParts(this);
    }
}</pre>
<p>&nbsp;</p>
<p>At the moment everything is ready to ensure that write the actual code additions.</p>
<p>Add a new class library project. We call it RussianHello. Refer it to the project with an interface to System.ComponentModel.Composition and implement the interface ILanguage.</p>
<pre class="brush: csharp">namespace RussianHello {
     [Export(typeof (ILanguage))]
     public class RuHello : ILanguage {
          public string SayHello() {
              return "Привет";
          }
     }
}</pre>
<p>&nbsp;</p>
<p>To see MEF class, you have to mark the attribute Export.V this case could not specify the interface exports.</p>
<p>Another point to test the application. It will be useful to specify a folder directly on the formation of libraries Addings in the directory where the executable will lie.</p>
<p>The final step is to call the class AddingComposer in the body of Main.</p>
<pre class="brush: csharp">private static void Main(string[] args) {
    var addingComposer = new AddingComposer();

    addingComposer.LoadAddings();
    var hello = addingComposer.Language.SayHello();
    Console.WriteLine(hello);

    Console.ReadLine();
}</pre>
<p>&nbsp;</p>
<p>After this, run the application and see:</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/05/mef-02.png"><img class="alignnone size-full wp-image-596" title="mef-02" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/05/mef-02.png" alt="" width="509" height="239" /></a></p>
<p>This is the basic functionality of MEF, on which many of the articles and come to an end, but of course we go any further, consistently developing the application.</p>
<h1>Adding another language</h1>
<p>Create another assembly, where realise the interface ILanguage for English.</p>
<pre class="brush: csharp">namespace EnglishHello {
     [Export(typeof (ILanguage))]
     public class EnHello : ILanguage {
         public string SayHello() {
             return "Hello";
         }
     }
}</pre>
<p>After that we can cast the appropriate libraries in the folder Adding and watch the result that the message is changing.</p>
<p>But this will happen only if the folder only additions one more addition. If you cast the two additions, the runtime will throw an error on an application that can not be resolved as a complement to download and use.</p>
<p>To resolve this situation, we use metadata for export applications.</p>
<h1>Metadata for export</h1>
<p>Metadata for exports may be untyped and typed. Let&#8217;s start with untyped, as it&#8217;s more simple to use.</p>
<h2>weak typing</h2>
<p>Metadata is added using a special attribute ExportMetadata. We need the constructor, where you can specify a variable name and its value will be used to uniquely identify the add-on.</p>
<p>For a class RuHello add:</p>
<pre class="brush: csharp">[ExportMetadata("Lang","Ru")]</pre>
<p>Then we obtain</p>
<pre class="brush: csharp">[Export(typeof (ILanguage))]
[ExportMetadata("Lang","Ru")]
public class RuHello : ILanguage { ... }</pre>
<p>&nbsp;</p>
<p>Similarly add class EnHello, to see</p>
<pre class="brush: csharp">[Export(typeof (ILanguage))]
[ExportMetadata("Lang","En")]
public class EnHello : ILanguage { ...  }</pre>
<p>&nbsp;</p>
<p>After that we can choose the Build-to-field Lang. Sample itself will be carried out in the master application.</p>
<p>For import multiple we use attribute ImportMany which is used in type to import. This attribute is better to hang on a lazy collection of MEF namespace for posted initialization of components.</p>
<pre class="brush: csharp">[ImportMany(typeof (ILanguage))]
private Lazy&lt;ILanguage, IDictionary&lt;string, object&gt;&gt;[] langVaults { get; set; }</pre>
<p>&nbsp;</p>
<p>Choosing the right additions can be carried out following sample:</p>
<pre class="brush: csharp">public ILanguage GetHello(string type) {
    LoadAddings();

    return (from codeVault in langVaults
              where (string) codeVault.Metadata["Lang"] == type
              select codeVault).Single().Value;
}</pre>
<p>&nbsp;</p>
<p>After this, the main application code looks like this:</p>
<pre class="brush: csharp">public class AddingComposer {
    [ImportMany(typeof (ILanguage))]
    private Lazy&lt;ILanguage, IDictionary&lt;string, object&gt;&gt;[] langVaults { get; set; }

    private void LoadAddings() {
        var catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new DirectoryCatalog("Adding"));

        var container = new CompositionContainer(catalog);
        container.ComposeParts(this);
    }

    public ILanguage GetHello(string type) {
        LoadAddings();

        return (from codeVault in langVaults
                  where (string) codeVault.Metadata["Lang"] == type
                  select codeVault).Single().Value;
    }
}

private static void Main(string[] args) {
    var lang = Console.ReadLine();

    var addingComposer = new AddingComposer();
    var hello = addingComposer
               .GetHello(lang)
               .SayHello();

    Console.WriteLine(hello);

    Console.ReadLine();
}</pre>
<p>&nbsp;</p>
<p>You can mark try to enter values Ru and En and see how the application displays the data to us from the right supplements.</p>
<p>Best of all, before the application starts you can do to clean the folder Adding, copyingand there additions as you work. They will be picked up without restarting the application.</p>
<h2>Strong Typing</h2>
<p>Now try the same things with typed metadata.</p>
<p>In general, the algorithm is as follows: declare a class that will be typed attribute, inherited from his ExportAttribute. Create an interface that will follow a set of properties, but only for reading. Use the newly created attribute on the desired class.</p>
<p>Assume that we have changed the metadata to the point:</p>
<pre class="brush: csharp">namespace EnglishHello {
     [Export(typeof (ILanguage)),
      ExportMetadata("Lang","En"),
      ExportMetadata("Version","2"),
      ExportMetadata("Comment","English language"),
     ]
      public class EnHello : ILanguage {
          public string SayHello() {
             return "Hello";
          }
      }
}</pre>
<p>&nbsp;</p>
<p>Logically languages are fairly limited and may be given enumerated type, version can only be an integer value, this comment line. To get all the advantages of typing, you need to create a necessary attribute types. Since then begin.</p>
<pre class="brush: csharp">[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class LangMetaData : ExportAttribute {
    public Lang Language { get; set; }
    public int Version { get; set; }
    public string Comment { get; set; }
}</pre>
<p>&nbsp;</p>
<p>The class inherits from ExportAttribute, while attributes are applied to it MetadataAttribute and indicates the types it will be used and how. In this case, the attribute should apply only to classes with multiple inheritance through the use is prohibited.</p>
<p>Now we need to create an interface that will follow a set of properties, and they must be declared read-only.</p>
<pre class="brush: csharp">public interface ILangMetaData {
    Lang Language { get;  }
    int Version { get;  }
    string Comment { get; }
}</pre>
<p>&nbsp;</p>
<p>The interface can be declared next to the attribute.</p>
<p>Then you can use attribute. It looks prettier than untyped metadata.</p>
<pre class="brush: csharp">namespace EnglishHello {
     [Export(typeof(ILanguage)),
     LangMetaData(
         Language = Lang.En,
         Version = 2,
         Comment = "English Language"
     )]
     public class EnHello : ILanguage {
         public string SayHello() {
             return "Hello";
         }
     }
}</pre>
<p>&nbsp;</p>
<p>There is no way to make a mistake, the compiler will notice;</p>
<ul>
<li>Know precisely what options might be, intelliSense tell;</li>
<li>It is easy to change and seek to use the project properties;</li>
<li>Sane filter when searching for additions to the application.</li>
</ul>
<p>It remains only to modify the master application to strongly typed metadata understood. The list will announce as we desired dictionary from the interface and the interface metadata.</p>
<pre class="brush: csharp">[ImportMany]
private Lazy&lt;ILanguage, ILangMetaData&gt;[] langVaults { get; set; }</pre>
<p>&nbsp;</p>
<p>I draw your attention that the attribute is not specified ImportMany type that can be booted. If you leave the type, then load the add-on twice and MEF can not correctly resolve the dependency. It is necessary to specify the type or in ImportMany, or in Export, but not in two places at once.</p>
<p>Method GetHello now changed, and in my opinion would be more informative and accurate<br />
Метод GetHello теперь изменится, и на мой взгляд станет более информативным и аккуратным</p>
<pre class="brush: csharp">public ILanguage GetHello(Lang lang) {
    LoadAddings();

    return (from codeVault in langVaults
              where codeVault.Metadata.Language == lang
              select codeVault).Single().Value;
}</pre>
<p>&nbsp;</p>
<p>Hmm &#8230; I haven&#8217;t guessed any difficult examples yet, right? Well, it&#8217;s probably because I do not particularly complicated things and treated. Rest in the next section, and even so there are too many letters. Wait, it is almost ready;)</p>
<p>Hard&#8217;n&#8217;heavy</p>
]]></content:encoded>
			<wfw:commentRss>http://softblog.violet-tape.net/2011/05/05/mef/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Launch of .bat files out of Visual Studio 2010</title>
		<link>http://softblog.violet-tape.net/2011/05/01/launch-of-bat-files-out-of-visual-studio-2010/</link>
		<comments>http://softblog.violet-tape.net/2011/05/01/launch-of-bat-files-out-of-visual-studio-2010/#comments</comments>
		<pubDate>Sun, 01 May 2011 08:33:52 +0000</pubDate>
		<dc:creator><![CDATA[Koissakh Kadderah]]></dc:creator>
				<category><![CDATA[Newbie]]></category>
		<category><![CDATA[Utils]]></category>
		<category><![CDATA[VS improvement]]></category>
		<category><![CDATA[bat]]></category>
		<category><![CDATA[custom]]></category>
		<category><![CDATA[VisualStudio]]></category>

		<guid isPermaLink="false">http://softblog.violet-tape.net/?p=167</guid>
		<description><![CDATA[Or how to hang a voluntary action to the context to any item in the Project Explorer. As already mentioned in the title, this step will be to rotate. Bat files since they are widely used in our daily activities, and constantly open Explorer or FAR is not very convenient. … <a href="http://softblog.violet-tape.net/2011/05/01/launch-of-bat-files-out-of-visual-studio-2010/"> Continue reading <span class="meta-nav">&#8594; </span></a>]]></description>
				<content:encoded><![CDATA[<p>Or how to hang a voluntary action to the context to any item in the Project Explorer.</p>
<p>As already mentioned in the title, this step will be to rotate. Bat files since they are widely used in our daily activities, and constantly open Explorer or FAR is not very convenient. Much better to have effect until the pile and hang it on the key combination to achieve complete nirvana</p>
<p>So, given: a project that uses a batch file</p>
<p>Required: run a batch file from the context menu in the Project Explorer.</p>
<p><span id="more-167"></span></p>
<h2>Create a link to an external application</h2>
<p>In the main menu, select studio Tools -&gt; External Tools &#8230;</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_01.png"><img class="alignnone size-full wp-image-581" title="bat_01" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_01.png" alt="" width="344" height="163" /></a></p>
<p>After that, a window appears where you can specify which application and what parameters to run. In this environment variables are available, such as the path to the file to the project, the file name, the root of the decision, and others.</p>
<p>In the resulting window click on the Add button and fill in the fields according to the screenshot.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_11.png"><img class="alignnone size-full wp-image-588" title="bat_11" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_11.png" alt="" width="471" height="460" /></a></p>
<p>Give the name to the action, so that we ourselves can determine what will happen in the end. Prescribes the name of the application to run. In this case the command line C: \ Windows \ System32 \ cmd.exe</p>
<p>The command line arguments. For us, it will be the path to the file. In the variables it is listed as <strong>$(ItemPath)</strong>. I think you have noticed that before this variable is still &#8220;/ C&#8221;, it says the command line, that is to close immediately after the operation.</p>
<p>Another important thing is to point the working directory for the command line. In my case this is solution folder.</p>
<p>Note in daw Use Output window , to see everything at once in the studio and on stage this customization tool is completed. Click OK and proceed to the next stage of setup.</p>
<h1>Adding context menu</h1>
<p>Before you add a context menu, you need to do a very important step, without which, success is not guaranteed.</p>
<p>So, you need to open the main menu in the studio Tools, and calculate how the order is necessary to you external tool.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_02.png"><img class="alignnone size-full wp-image-582" title="bat_02" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_02.png" alt="" width="345" height="257" /></a></p>
<p>Required item is the sixth. Remember this and move on to the setting in the context menu for files in the Project Explorer.</p>
<p>Open the <strong>Tools &gt; </strong><strong>Customize…</strong>, go to the tab Commands, select the item Context menu and in the dropdown list search for the line <strong>Project </strong><strong>and </strong><strong>Solution </strong><strong>Context </strong><strong>Menus | </strong><strong>Item</strong></p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_03.png"><img class="alignnone size-full wp-image-583" title="bat_03" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_03.png" alt="" width="468" height="487" /></a></p>
<p>After you have selected a row in the drop-down list, you will be all the possible commands that can be displayed for the item.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_04.png"><img class="alignnone size-full wp-image-584" title="bat_04" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_04.png" alt="" width="469" height="490" /></a></p>
<p>We need to add a new team that we are doing. Click on the appropriate menu item and look for the category Tools and you want us to command. Team we are looking at its sequence number in the list, which was in the beginning of this section. Now do you understand why it was necessary to find the serial number of the menu item?</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_05.png"><img class="alignnone size-full wp-image-585" title="bat_05" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_05.png" alt="" width="500" height="370" /></a></p>
<p>After pressing OK, to be like the following on the previous dialog box.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_06.png"><img class="alignnone size-full wp-image-586" title="bat_06" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_06.png" alt="" width="469" height="490" /></a></p>
<p>Close this window and you can try to start .bat in the Project Explorer.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_07.png"><img class="alignnone size-full wp-image-587" title="bat_07" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/bat_07.png" alt="" width="265" height="188" /></a></p>
<p>That&#8217;s all, hope this helps you in your work and allow more productive use of your time.</p>
<p>Hard&#8217;h&#8217;heavy!</p>
]]></content:encoded>
			<wfw:commentRss>http://softblog.violet-tape.net/2011/05/01/launch-of-bat-files-out-of-visual-studio-2010/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NuGet creation</title>
		<link>http://softblog.violet-tape.net/2011/04/28/nuget-creation/</link>
		<comments>http://softblog.violet-tape.net/2011/04/28/nuget-creation/#comments</comments>
		<pubDate>Thu, 28 Apr 2011 08:14:00 +0000</pubDate>
		<dc:creator><![CDATA[Koissakh Kadderah]]></dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Utils]]></category>
		<category><![CDATA[components]]></category>
		<category><![CDATA[composit]]></category>
		<category><![CDATA[nuget]]></category>

		<guid isPermaLink="false">http://softblog.violet-tape.net/?p=165</guid>
		<description><![CDATA[NuGet creation The last time I spoke as NuGet is used, this time it is logical to tell you how to create your NuGet package and place it on a shared hosting or on your own in a local directory, or else in the gallery. Creating your own package NuGet … <a href="http://softblog.violet-tape.net/2011/04/28/nuget-creation/"> Continue reading <span class="meta-nav">&#8594; </span></a>]]></description>
				<content:encoded><![CDATA[<p>NuGet creation<br />
The last time I spoke as NuGet is used, this time it is logical to tell you how to create your NuGet package and place it on a shared hosting or on your own in a local directory, or else in the gallery.</p>
<h1>Creating your own package NuGet</h1>
<p>For example, and I think in most cases, you&#8217;ll create a package NuGet without dependencies on other packages. So we need any project, for simplicity let it be a simple library with the N- of methods.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_01.png"><img class="alignnone size-full wp-image-555" title="nuGet_create_01" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_01.png" alt="" width="287" height="250" /></a></p>
<p>In order to be able to set library or libraries to include in the final NuGet package, you must add the project file with the extension &#8220;<strong>.Nuspec</strong>&#8220;, where there will be described all the properties and the internal function of our package. So far, in the studio there is no setting to create the files required extensions, so that you can create any text file, and change it&#8217;s dwells.</p>
<p>In general, the nuspec file looks as follows:</p>
<pre class="brush: xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;package&gt;
  &lt;metadata&gt;
    &lt;id&gt;WBR.ArgParser&lt;/id&gt;
    &lt;version&gt;1.0.0&lt;/version&gt;
    &lt;title&gt;Argument Parser library&lt;/title&gt;
    &lt;authors&gt;Violet Tape&lt;/authors&gt;
    &lt;description&gt;Easy to use library for parsing app arguments.&lt;/description&gt;
    &lt;language&gt;en-US&lt;/language&gt;
    &lt;projectUrl&gt;http://violet-tape.net&lt;/projectUrl&gt;
    &lt;iconUrl&gt;http://violet-tape.net/images/commandprompt.png&lt;/iconUrl&gt;
    &lt;requireLicenseAcceptance&gt;false&lt;/requireLicenseAcceptance&gt;
  &lt;/metadata&gt;
  &lt;files&gt;
    &lt;file src="bin\Release\WBR.ArgParser.dll" target="lib" /&gt;
  &lt;/files&gt;
&lt;/package&gt;</pre>
<p>&nbsp;</p>
<p>We can say that the comments here are irrelevant. The only thing that is necessary to specify is which tags are mandatory and which are optional.</p>
<p><span id="more-165"></span></p>
<p>Mandatory tags:</p>
<ul>
<li>id &#8211; can not specify a name with spaces or special characters. In general, here are the same rules that apply to URL</li>
<li>version &#8211; package version in the format 1.2.3.</li>
<li>authors &#8211; list of the authors of code separated by commas</li>
<li>description &#8211; the description of what makes the package</li>
</ul>
<p>Everything else is optional and is filled on their own. There is no particular limitation, but iconUrl &#8211; recommend 100&#215;100 image in png format with transparent background. Such are the demands.</p>
<p>If you want to invest in the package a lot of files and to prescribe them by hand , as any normal programmer is too lazy, you can use a batch addition of the mask. Examples of adding and using below.</p>
<pre class="brush: csharp">&lt;files&gt;
  &lt;file src="c:\docs\bin\*.xml" target="lib" /&gt;
  &lt;file src="bin\Debug\*.dll" target="lib" /&gt;
  &lt;file src="bin\Debug\*.pdb" target="lib" /&gt;
  &lt;file src="tools\**\*.*" /&gt;
&lt;/files&gt;</pre>
<p>&nbsp;</p>
<p>After nuspec file will be created, we need NuGet.exe to pack everything into the final file nupkg. This operation is doing with the help of the command</p>
<p>Pack “Path.To.Nuspec.File”</p>
<p>It is best to put the command into PostBuild action in successful assembly and from there to pick up ready-made package</p>
<p>&#8220;$(SolutionDir)Tools\NuGet.exe&#8221; pack &#8220;$(SolutionDir)ArgParser\ArgParser.nuspec&#8221;</p>
<p>After performing such uncomplicated actions you will completely ready and the work package, which may be placed on the official hosting or on your own.</p>
<p>The easiest way to start posting packages from local or network folders. This is the simplest and easiest way, which does not require any significant effort on your part.</p>
<h1>Packages in the local directory</h1>
<p>Let&#8217;s say you have chosen as a repository package local directory C: \ NuGet. Want to copy back all the packages you want, and then configure the package manager NuGet in this directory. This is done as follows:</p>
<p>Call <em>Manager Package Tools &gt; Library Package Manager &gt; Package Manager Settings</em></p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_02.png"><img class="alignnone size-full wp-image-556" title="nuGet_create_02" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_02.png" alt="" width="611" height="284" /></a></p>
<p>After that the window will appear with the settings, where you can specify the package repository.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_021.png"><img class="alignnone size-full wp-image-566" title="nuGet_create_021" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_021.png" alt="" width="757" height="440" /></a></p>
<p>Enter the name of the repository and the path to the folder with the packages, then click Add and you can try to add packages NuGet from a new repository.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_03.png"><img class="alignnone size-full wp-image-557" title="nuGet_create_03" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_03.png" alt="" width="800" height="450" /></a><br />
As you can see in the picture, there&#8217;s a new resource LocalRepository when allocation of it it, downloads the NuGet , which were placed in the appropriate folder. Similarly, all will work with network folder.</p>
<p>As you can see, everything is more than easy!</p>
<h1>Placing in the gallery</h1>
<p>Place in the general gallery of packages NuGet possible after registering on the site <a href="http://nuget.org/">http://nuget.org/</a>. Registration process is very simple, and here consider it does not make sense. After the registeration, you can add your package.</p>
<p>Adding is possible in two ways: through a Web interface and command-line using NuGet.exe.</p>
<h2>Adding through the web interface</h2>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_04.png"><img class="alignnone size-full wp-image-558" title="nuGet_create_04" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_04.png" alt="" width="700" height="437" /></a></p>
<p>Click on the GetStarted and follow the instructions.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_041.png"><img class="alignnone size-full wp-image-568" title="nuGet_create_041" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_041.png" alt="" width="673" height="290" /></a></p>
<p>After the package is loaded, you will be redirected to a page where you can edit the data that was listed in nuspec file.</p>
<p><img class="alignnone size-full wp-image-559" title="nuGet_create_05" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_05.png" alt="" width="672" height="831" /></p>
<p>After you are satisfied that everything is filled properly, you can press on Next at the bottom of the page and you&#8217;ll be taken to setup a logo or a screenshot of the package. This will be the final step in the publication.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_06.png"><img class="alignnone size-full wp-image-560" title="nuGet_create_06" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_06.png" alt="" width="667" height="500" /></a></p>
<p>After clicking Finish, about a minute you can go to the tab My Contributions and see your packadge.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_061.png"><img class="alignnone size-full wp-image-569" title="nuGet_create_061" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_061.png" alt="" width="638" height="217" /></a></p>
<p>In passing to the page you can edit the package some of its properties, delete it. Learn how many people have downloaded the package, find out what other people think about your product.</p>
<h2>Adding through the command line</h2>
<p>After registering, you can find your GUID to update and add packages using the command line utility nuget.exe. Know your GUID may be in the tab MY ACCOUNT, in the upper right corner. After clicking on the specified menu item, you will see the following picture</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_062.png"><img class="alignnone size-full wp-image-570" title="nuGet_create_062" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_062.png" alt="" width="909" height="485" /></a></p>
<p><strong>nuget push -source http://packages.nuget.org/v1/ MyPackage.1.0.nupkg 64f10e0c-207a-4728-95bb-1b0e0f469511</strong></p>
<p>GUID is fake, so that everything is O.K)) But you shouldn&#8217;t tell anybody your own. On this page as you can see an example , as deploit your packages from the command line</p>
<p>Push is the first parameter which says that we download the package, followed by the parameter source, who says, where we load the package. Next comes the name of the package to download, and most recently held a secret option GUID.</p>
<p>In generalthere is nothing particularly complicated.</p>
<h1>Placement on personal hosting</h1>
<p>This method is ideal accommodation if you have a proprietary libraries or commercial software , and a project is big and the work is done by several teams. In the future community plans to make such a placement package easier and more functional.</p>
<p>At the moment the private gallery package only supports return packages, download them we will do by hands.</p>
<p>To create a distribution package of the site will need to first create a blank project Web site.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_07.png"><img class="alignnone size-full wp-image-561" title="nuGet_create_07" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_07.png" alt="" width="800" height="569" /></a></p>
<p>After creating the project type the command in Package Manager: install-package nuget.Server</p>
<p>After that, downloading and instalingl all the packages dependencies. Blank project ready to become a server for the packets. There will be new directory. The most important for us, this folder Packages, in which actually will be adding ready packages NuGet.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_08.png"><img class="alignnone size-full wp-image-562" title="nuGet_create_08" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_08.png" alt="" width="289" height="265" /></a></p>
<p>Add the existing packages in a folder and you can run the site. After starting ,see the following:</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_09.png"><img class="alignnone size-full wp-image-563" title="nuGet_create_09" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_09.png" alt="" width="562" height="441" /></a></p>
<p>Comments on the site speak for themselves. Now you can add the site to available resources and see how it all works.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_10.png"><img class="alignnone size-full wp-image-564" title="nuGet_create_10" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_10.png" alt="" width="757" height="441" /></a></p>
<p>After this, open the package manager, select the resource and watch as shown our packages</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_11.png"><img class="alignnone size-full wp-image-565" title="nuGet_create_11" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuGet_create_11.png" alt="" width="871" height="473" /></a></p>
<p>Voila!</p>
<p>I hope this knowledge will help you in the future and come across to any new uses NuGet, the possibility of decomposition of your projects and upload dependent parts through NuGet.</p>
<p>For myself, I had already decided that, regardless, I will try to connect through NuGet. In this case the libraries loaded locally and do not need to keep track of the correct paths to link to the library. And even the newcomers will not make mistakes, if connect the link on nunit through NuGet, because all team members will receive the correct path to the library and will not be screaming on &#8220;The Right to the relative path of the project!&#8221;;)</p>
]]></content:encoded>
			<wfw:commentRss>http://softblog.violet-tape.net/2011/04/28/nuget-creation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NuGet using</title>
		<link>http://softblog.violet-tape.net/2011/04/25/nuget-using/</link>
		<comments>http://softblog.violet-tape.net/2011/04/25/nuget-using/#comments</comments>
		<pubDate>Mon, 25 Apr 2011 07:38:21 +0000</pubDate>
		<dc:creator><![CDATA[Koissakh Kadderah]]></dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[components]]></category>
		<category><![CDATA[composition]]></category>
		<category><![CDATA[nuget]]></category>

		<guid isPermaLink="false">http://softblog.violet-tape.net/?p=162</guid>
		<description><![CDATA[Today I would like to talk about the use of NuGet. Surely you&#8217;ve heard something about this system of management of external dependencies. Recently, the system grows and more and more developers are putting their systems in the wrapper for distribution with the help of NuGet. NuGet &#8211; a manager … <a href="http://softblog.violet-tape.net/2011/04/25/nuget-using/"> Continue reading <span class="meta-nav">&#8594; </span></a>]]></description>
				<content:encoded><![CDATA[<p>Today I would like to talk about the use of NuGet. Surely you&#8217;ve heard something about this system of management of external dependencies. Recently, the system grows and more and more developers are putting their systems in the wrapper for distribution with the help of NuGet.</p>
<p>NuGet &#8211; a manager to control the dependencies on external libraries. With this tool you can install, update and remove according to your project with great ease. This applies both for the desktop software and the web. In particular, when expanding the CMS Orchard, she drags the half assembly during installation of the library on their own packages. There are examples of NuGet for Silverlight.</p>
<h1>Notes from the back seats</h1>
<p>When studying materials NuGet, a plus appears availability of shared libraries to your projects. Conditional opponents NuGet, or principled opposition asks why you need NuGet for their shared libraries, if there can be external to SVN, and other such things for VCS? So you can refer to the stable branch sources.</p>
<p>Developers NuGet answer that</p>
<ul>
<li>do not control whether access to the version control system,</li>
<li>source code is not displayed to other groups</li>
<li>no need to monitor and switch to other audits by hand (maybe you want to jump from branch Release, to an earlier, or you are referring to an audit in trunk)</li>
</ul>
<p>Quite good advantages. Especially now that your favorite library does not get lost among repositories and projects.</p>
<p><span id="more-162"></span></p>
<h1>Installation</h1>
<p>Get package manager NuGet You can either set yourself ASP.NET MVC 3.0, or download it from the site nuget.codeplex.com. Then in Visual Studio will have a new menu item for viewing and downloading packages NuGet.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_01.png"><img class="alignnone size-full wp-image-537" title="nuget_01" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_01.png" alt="" width="624" height="224" /></a></p>
<p>Tools &gt; Library Package Manager &gt; Add Library Package Reference…</p>
<h1>Usage</h1>
<p>The package manager is out of NuGet looks if you used the add-ons manager for the studio.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_02.png"><img class="alignnone size-full wp-image-538" title="nuget_02" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_02.png" alt="" width="800" height="547" /></a></p>
<p>All the same. A list of available packages, brief description of the allocation package. On accordion tab Online list of available places where packages are NuGet. Now there is only one official resource, but you can easily add a local directory, online directory, your own online store packages NuGet.</p>
<p>Installing and updating packages, up to a disgrace simple &#8211; you simply click on the Install \ Update when you select a package from the list.</p>
<p>Little is need to be said about the search package. I&#8217;m in the studio search periodically disappears and I use the search at the official site nuget.org. At the moment it contains 958 packages. About finding and installing with the help of the console will talk about below.</p>
<p>All actions can be performed from the console package manager, which appears when you install NuGet</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_03.png"><img class="alignnone size-full wp-image-539" title="nuget_03" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_03.png" alt="" width="737" height="498" /></a></p>
<p>Actions carried out in the console for a specific project that is selected as DefaultProject. The screenshot is selected WindowsFormsApplication1, and all the packages that I will show in the console will be installed for this project if the project is not specifically listed.</p>
<h1>Searching</h1>
<p>Displays a list of available pacts in the console is not very convenient, so you better to find him before on the site. For example add to the project StructureMap. Go to the official website and look for the name. As a result of searching you are likely to bring up a page of the form:</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_04.png"><img class="alignnone size-full wp-image-540" title="nuget_04" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_04.png" alt="" width="848" height="606" /></a></p>
<h2>Installing packages</h2>
<p>Here it is specified by a command to execute to install. Copy and paste the text into the console.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_05.png"><img class="alignnone size-full wp-image-541" title="nuget_05" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_05.png" alt="" width="737" height="498" /></a></p>
<p>Execute the command and get all the necessary libraries added to the project. This will download and install all the dependencies needed to run the component. So most likely you will not be in a frenzy of hand-parse all dependencies. Unless of course the author of the package have all true))</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_06.png"><img class="alignnone size-full wp-image-542" title="nuget_06" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_06.png" alt="" width="737" height="498" /></a></p>
<p>In the console we can see what packages have been established and how successfully. Once it is installed, you will see that among the files of the project, a new element packages.config. This file specifies which packages are installed and which version. General view of the file is as follows:</p>
<pre class="brush: xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;packages&gt;
   &lt;package id="structuremap" version="2.6.2" /&gt;
&lt;/packages&gt;</pre>
<p>The newly installed package appears only in that project, which exposed &#8220;by default&#8221;. If you want to add the same package in other projects that will have to choose projects from the drop-down list and then install it.</p>
<p>In this package will not be re-downloaded from a remote resource, NuGet smart enough to know what has already been downloaded in the current software solution, so it just adds a link to the library. In the console you will see the following:</p>
<pre class="brush: xml">PM&gt; Install-Package structuremap
'structuremap 2.6.2' already installed.
Successfully added 'structuremap 2.6.2' to TestProject1.</pre>
<p>&nbsp;</p>
<p>Unfortunately, that can not be specified when adding the package several projects for the integration. The general syntax of the installation is as follows:</p>
<p>Install-Package [-Id] &lt;string&gt; [-IgnoreDependencies] [-ProjectName &lt;string&gt;] [-Version &lt;string&gt;] [-Source &lt;string&gt;] [&lt;CommonParameters&gt;]</p>
<p>Packages are downloaded to the root directory of software solutions to the folder packages, so be sure to add it to your version of control system.</p>
<p>Installed packages can be viewed as out of the package manager</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_08.png"><img class="alignnone size-full wp-image-544" title="nuget_08" src="http://softblog.violet-tape.ru/wp-content/uploads/2011/04/nuget_08.png" alt="" width="800" height="450" /></a></p>
<p>As well as from the console. Operations on the update, and delete as you can make in two ways. For all the package manager is crystal clear with all the console a bit more complicated but more flexible.</p>
<h1>Console</h1>
<p>The basic commands for working with the console:</p>
<p><strong>Package</strong> &#8211; This command lists all packages installed for the selected &#8220;default&#8221; project.</p>
<p>PM&gt; package</p>
<p>Id                             Version              Description<br />
&#8212;                             &#8212;&#8212;-              &#8212;&#8212;&#8212;&#8211;<br />
structuremap                   2.6.2                StructureMap is a Dependency Injection / Inversion of Control tool for .Net that can be used to improve the architectural qualities of an object ori&#8230;<br />
<strong>UpdatePackage</strong> – с помощью этой команды осуществляется обновление установленых пакетов. Для обновления зависимостей в проекте «по умолчанию» необходимо написать<br />
UpdatePackage &#8211; with this command by updating the installed packages. To update the dependencies in the project &#8220;default&#8221; to write</p>
<pre class="brush: xml">PM&gt; Update-Package -Id structuremap</pre>
<p>&nbsp;</p>
<p>If you have the latest version, then NuGet will say:</p>
<pre class="brush: xml">PM&gt; Update-Package -Id structuremap
No updates available for 'structuremap'.</pre>
<p>The full syntax looks like this:<br />
Update-Package [-Id] &lt;string&gt; [-IgnoreDependencies] [-ProjectName &lt;string&gt;] [-Version &lt;string&gt;] [-Source &lt;string&gt;] [&lt;CommonParameters&gt;]</p>
<p>&nbsp;</p>
<p>Unfortunately you can not check for updates all the packages at once and update them. It is necessary to carry out a refresh operation for each packet NuGet. The international community and backstage hope that this opportunity will appear in an upcoming release. In the meantime, knowledgeable people have written here is a script for PowerShell</p>
<pre class="brush: xml">ForEach ($project in get-project -all)
{
get-package | update-package -Project $project.Name
}</pre>
<p>&nbsp;</p>
<p>The result of running:</p>
<pre class="brush: xml">PM&gt; ForEach ($project in get-project -all)
&gt;&gt;  {
&gt;&gt;  get-package | update-package -Project $project.Name
&gt;&gt;  }
No updates available for 'structuremap'.

No updates available for 'structuremap'.

PM&gt;</pre>
<p>The feedback to the script, people write that the confusion about &#8220;too many requests to the resource&#8221;, so I have warned you.</p>
<p>Uninstall-package &#8211; remove a package ,it is not difficult to guess =)</p>
<p>The result:</p>
<pre class="brush: xml">PM&gt; Uninstall-Package -Id structuremap
Successfully removed 'structuremap 2.6.2' from TestProject1.</pre>
<p>General syntax:<br />
Uninstall-Package [-Id] &lt;string&gt; [-RemoveDependencies] [-Force] [-Version &lt;string&gt;] [&lt;CommonParameters&gt;]</p>
<p>&nbsp;</p>
<p>Get-help &#8211; the most important team at work!</p>
<p>Example</p>
<pre class="brush: xml">PM&gt; Package get-help
PM&gt; Package -?</pre>
<h1>Interesting packets</h1>
<p>Scratch in the Internet and looking at examples, we can say that there are the following interesting packages:</p>
<p>nUnit – framework for testing<br />
log4net &#8211; a rich library for logging<br />
structureMap &#8211; IoC container<br />
SqlServerCompact &#8211; 4th version of SQL CE<br />
mvcMailer &#8211; a handy library for mail<br />
jQuery &#8211; just all the family in mind when working in VS2010<br />
moq &#8211; a lightweight library for object mocking</p>
<p>Most likely your favorite library from the world of OpenSource is also in the library NuGet!</p>
<p>The next time I&#8217;ll tell you how you can create NuGet bags and place them in libraries.</p>
]]></content:encoded>
			<wfw:commentRss>http://softblog.violet-tape.net/2011/04/25/nuget-using/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Enum with a human face</title>
		<link>http://softblog.violet-tape.net/2010/12/24/enum-with-a-human-face/</link>
		<comments>http://softblog.violet-tape.net/2010/12/24/enum-with-a-human-face/#comments</comments>
		<pubDate>Fri, 24 Dec 2010 08:17:03 +0000</pubDate>
		<dc:creator><![CDATA[Koissakh Kadderah]]></dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Utils]]></category>
		<category><![CDATA[Attributes]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://softblog.violet-tape.net/?p=159</guid>
		<description><![CDATA[A problem Quite often we have to use enums for a limited set of values. They are very easy to use in your code, but there are problems for bringing them to the interface of the application. Not only in Russian but in English. The values ​​in enum may consist … <a href="http://softblog.violet-tape.net/2010/12/24/enum-with-a-human-face/"> Continue reading <span class="meta-nav">&#8594; </span></a>]]></description>
				<content:encoded><![CDATA[<h1>A problem</h1>
<p>Quite often we have to use enums for a limited set of values. They are very easy to use in your code, but there are problems for bringing them to the interface of the application. Not only in Russian but in English. The values ​​in enum may consist of several words logically and embarrassing them to show in the user interface. For example:</p>
<pre class="brush: csharp">public enum MyEnum {
    None,
    CompositeValue,
    Single
}</pre>
<p>Naturally, it is show to the customer CompositeValue is not good. Much better to show &#8220;Composite Value&#8221;. Or, to translate it into Russian.</p>
<p><span id="more-159"></span></p>
<h1>How it was</h1>
<p>Now in the code you can find the following monstrous construction:</p>
<pre class="brush: csharp">private const string LogSeverity_All = "Все";
private const string LogSeverity_Off = "Никакие";
private const string LogSeverity_Critical= "Критические";
private const string LogSeverity_Error = "Ошибки";
private const string LogSeverity_Warning = "Предупреждения";
private const string LogSeverity_Information = "Информационные";
private const string LogSeverity_Verbose = "Расширенные";
private const string LogSeverity_ActivityTracing = "Трассировочные";</pre>
<p>To translate the text into an enumerated type using a separate code, where each potential case may be a mistake and should be tested.</p>
<pre class="brush: csharp">private static FileSeverityFilter StringToFileSeverityFilter(string value)  {
    switch (value) {
       case LogSeverity_All:
          return FileSeverityFilter.All;
       case LogSeverity_Critical:
          return FileSeverityFilter.Critical;
       case LogSeverity_Error:
          return FileSeverityFilter.Error;
       case LogSeverity_Warning:
          return FileSeverityFilter.Warning;
       case LogSeverity_Information:
          return FileSeverityFilter.Information;
       case LogSeverity_Verbose:
          return FileSeverityFilter.Verbose;
       case LogSeverity_ActivityTracing:
          return FileSeverityFilter.ActivityTracing;
       default:
          return FileSeverityFilter.Off;
     }
}</pre>
<p>And there is an enumerated type</p>
<pre class="brush: csharp">enum FileSeverityFilter  {
    All = 0,
    Off,
    Critical,
    Error,
    Warning,
    Information,
    Verbose,
    ActivityTracing
}</pre>
<p>And to generate values ​​for display property is used</p>
<pre class="brush: csharp">public List&lt;string&gt; LogSeverities {
    get {
        return new List&lt;string&gt; {
                LogSeverity_All,
                LogSeverity_Off,
                LogSeverity_Critical,
                LogSeverity_Error,
                LogSeverity_Warning,
                LogSeverity_Information,
                LogSeverity_Verbose,
                LogSeverity_ActivityTracing
               };

     }
}</pre>
<p>Where again it is easy to forget to specify the new type.<br />
Total:</p>
<ul>
<li>A lot of code where it&#8217;s easy to make mistakes, and make out all of this will be hard enough.</li>
<li>No obvious connection type values ​​and the signatures of men.</li>
<li>Conversion should be done for each enumeration type.</li>
</ul>
<h1>Became</h1>
<p>You can go the other way, getting rid of all the shortcomings, leaving only one where the error occurred, for all possible enumerations. FOr it we will deploy the attribute is Description.</p>
<pre class="brush: csharp">public enum MyEnum {
    [Description("Не выбрано")]
    None,

    [Description("Составное значение")]
    CompositeValue,

    [Description("Значение")]
    Single
}</pre>
<p>Immediately we see a description of what type of matches.</p>
<p>To get the value from the description, you should use the following code:</p>
<pre class="brush: csharp">var type = typeof (MyEnum);
var fieldInfo = type.GetField(enumerate.ToString());
var attributes = (DescriptionAttribute[]) fieldInfo.GetCustomAttributes(typeof (DescriptionAttribute), false);
var result = (attributes.Length &gt; 0) ? attributes[0].Description : enumerate.ToString();</pre>
<p>Since it is inconvenient to write every time you select a class of extensions.</p>
<pre class="brush: csharp">public static class EnumExtenders {
    public static string ToStringX(this Enum enumerate) {
        var type = enumerate.GetType();
        var fieldInfo = type.GetField(enumerate.ToString());
        var attributes = (DescriptionAttribute[]) fieldInfo.GetCustomAttributes(typeof (DescriptionAttribute), false);
        return (attributes.Length &gt; 0) ? attributes[0].Description : enumerate.ToString();
    }
}</pre>
<p>Now we can write</p>
<pre class="brush: csharp">MyEnum.CompositeValue.ToStringX () // will compound the value</pre>
<p>Already much easier and can be used for any enum.</p>
<p>For a list of values​​, the code is not very complicated.</p>
<pre class="brush: csharp">public static List&lt;string&gt; Descriptions(this Enum enumerate) {
     var values = Enum.GetValues(enumerate.GetType());
     var descriptions = new List&lt;string&gt;(values.Length);

     foreach (var enumVal in values) {
          descriptions.Add(((Enum) enumVal).ToStringX());
     }

     return descriptions;
}</pre>
<p>Uses:</p>
<pre class="brush: csharp">var descriptions = MyEnum.Single.Descriptions();</pre>
<p>The only disadvantage that the use by any enumeration value.</p>
<p>Don&#8217;t you want to write this method?</p>
<pre class="brush: csharp">var actual = Enum.GetValues(typeof(MyEnum))
     .Cast&lt;MyEnum&gt;()
     .Select(i =&gt; i.ToStringX());</pre>
<p>Use directly in your production code.</p>
<h1>A result</h1>
<p>In my opinion submitted by the way is more compact and versatile. In addition, the test should be only one place, everything is compact.</p>
<ul>
<li>Do not be afraid of tipping over on the values ​​of the user interface, since all comes.</li>
<li>Visibility of use.</li>
<li>The code size is reduced at times</li>
</ul>
<p><a href="http://softblog.violet-tape.ru/download/EnumWithDescriptions.rar">Source code</a></p>
<p>Hard&#8217;n&#8217;heavy</p>
]]></content:encoded>
			<wfw:commentRss>http://softblog.violet-tape.net/2010/12/24/enum-with-a-human-face/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Win7 Jump List &#8211; II</title>
		<link>http://softblog.violet-tape.net/2010/10/10/win7-jump-list-ii/</link>
		<comments>http://softblog.violet-tape.net/2010/10/10/win7-jump-list-ii/#comments</comments>
		<pubDate>Sun, 10 Oct 2010 17:49:47 +0000</pubDate>
		<dc:creator><![CDATA[Koissakh Kadderah]]></dc:creator>
				<category><![CDATA[Utils]]></category>
		<category><![CDATA[Distributable]]></category>
		<category><![CDATA[Win7]]></category>

		<guid isPermaLink="false">http://softblog.violet-tape.net/?p=156</guid>
		<description><![CDATA[The last time we stayed on the fact that we have a program that can &#8220;group&#8221; icons from taskbar. If you run it and understood, it was noticed that the program has one unpleasant flaw in the usability . When you set the program to run by default &#8211; it … <a href="http://softblog.violet-tape.net/2010/10/10/win7-jump-list-ii/"> Continue reading <span class="meta-nav">&#8594; </span></a>]]></description>
				<content:encoded><![CDATA[<p>The last time we stayed on the fact that we have a program that can &#8220;group&#8221; icons from taskbar. If you run it and understood, it was noticed that the program has one unpleasant flaw in the usability . When you set the program to run by default &#8211; it can not be seen. Required to rely on their memories and habits. So we will correct this deficiency.</p>
<p>As you probably noticed last time, the images I have shown are mini-icons-default applications and those applications I have several. So let us consider in more detail how to achieve this for you too.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/jl-01.png"><img class="alignnone size-full wp-image-489" title="jl-01" src="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/jl-01.png" alt="" width="311" height="304" /></a></p>
<p><span id="more-156"></span></p>
<h1>Overlay</h1>
<p>The easiest way, which enables you to draw an extra icon on top of existing &#8211; to use an overlay of the Win API Codec Pack. For this we need only to know the path to the object,in which will contain an icon. The way we are still taken from our class to store list elements LinkInfo</p>
<pre class="brush: csharp">[Serializable]
public class LinkInfo {
    public string Name { get; set; }
    public string AppPath{ get; set; }
    public bool IsDefault{ get; set; }
}</pre>
<p>So, the code for the overlay will look like:</p>
<pre class="brush: csharp">private void SetOverlayIcon(LinkInfo linkInfo) {
    var icon = System.Drawing.Icon.ExtractAssociatedIcon(linkInfo.AppPath);
    TaskbarManager.Instance.SetOverlayIcon(this, icon, "Icon Name");
}</pre>
<p>The first mode of action you pull out the icon from the resource. The second action is putting it on top of a working application icons.</p>
<p>This can be used for running the program and the overlay will look very good. I personally like. But when you quit all at once disappear = (And it&#8217;s certainly not happy, because I will not know that the default program to start.</p>
<h1>Independent creation of icons</h1>
<p>Yes, we&#8217;ll have some work to create icons themselves. Even more, in real time to create your new icon from the available material and make it of default for the program.</p>
<p>I have just showed you how to rip out icons from programs and it&#8217;s not a problem. Now we need to put them nicely to each other, and one of them reduced. Let&#8217;s start with the latter problem.</p>
<p>I think it is meaningful to ask here is not the absolute size and relative, that is, to be able to say, I decreased the icon-image by 50%. It turns out this is not so difficult. It is necessary to calculate how much these 50% will be in pixels, and ordered to redraw the calculated values.</p>
<pre class="brush: csharp">public Bitmap ResizeBitmap(Bitmap b, int nWidth, int nHeight) {
    var w = (int) (b.Width*(nWidth/100M));
    var h = (int) (b.Height*(nHeight/100M));

    var result = new Bitmap(w, h);
    using (var g = Graphics.FromImage(result)) {
          g.DrawImage(b, 0, 0, w, h);
    }

    return result;
}</pre>
<p>We&#8217;re getting icon image size. With such a repaint is likely to appear black opaque background and it can remove a single line of code:</p>
<pre class="brush: csharp">mini.MakeTransparent();</pre>
<p>Next you need to put the mini image on the current . For a good look I have made ​​a 2-pixel padding on the bottom and right.</p>
<pre class="brush: csharp">public Bitmap OverlayBitmap(Bitmap background, Bitmap overlay) {
    using (var g = Graphics.FromImage(background)) {
         g.DrawImage(overlay, background.Width - overlay.Width - 2, background.Height - overlay.Height - 2);
    }
    return background;
}</pre>
<p>Now we have the final image and you want to save as an icon. The original version was quite simple and I&#8217;m even glad that everything is so easily obtained.</p>
<pre class="brush: csharp">var intPtr = bitmap.GetHicon();
System.Drawing.Icon.FromHandle(intPtr).Save(fileWriter);</pre>
<p>We took a pointer to create icons, icons created and saved to disk. Yes, the icon will be created, but very poor quality, only 16 colors. This is clearly not what I wanted. It was necessary to look in the Internet on the subject of new knowledge and libraries) and a library was found &#8211; <a href="http://www.codeproject.com/KB/cs/IconLib.aspx" target="_blank">IconLib</a></p>
<p>Without going into details, the library can be applied as follows:</p>
<pre class="brush: csharp">var sIcon = new MultiIcon().Add("Icon");
sIcon.CreateFrom(bitmap, IconOutputFormat.Vista);
sIcon.Save(iconPath);</pre>
<p>Icon is a much better! In this it was decided to stop at will and is slightly worse than the original. Now you only have to replace the icon with the shortcut!</p>
<h1>Creating shortcuts</h1>
<p>.Net has no means to create and edit shortcuts.</p>
<p>Yes, there is an omission. I do not know why, but true. For a long time I used the library Interop.IWshRuntimeLibrary.dll and creating shortcuts in my whole suit. But the way has stopped working when used. Net 4.0, so it will not even talk about it and. Had once again to seek new ways to create shortcuts. If it was only a banal xml or some other human-readable format, but no.</p>
<p>In the end, I found an archive with source code, which unfortunately did not want to decompressed but luckily at the site you can view the source code. It turned out that it is necessary only two files and create a shortcut becomes to child&#8217;s play:</p>
<pre class="brush: csharp">using (var shortcut = new ShellLink()) {
    shortcut.Target = appPath;
    shortcut.WorkingDirectory = Path.GetDirectoryName(appPath);
    shortcut.Description = name;
    shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
    shortcut.IconPath = iconPath;
    shortcut.Save(linkPath);
}</pre>
<p>To me everything is clear without words. With Interop.IWshRuntimeLibrary.dll shortcuts created as follows:</p>
<pre class="brush: csharp">WshShell shell = new WshShellClass();
IWshShortcut link =  (IWshShortcut)shell.CreateShortcut(shortcutFullName);

link.TargetPath = target;
link.Description = description;
link.Save();</pre>
<h1>About the program</h1>
<p>During the development I have not managed to identify patterns in how the same to make the icons in the taskbar updated quickly. A couple of times managed to do, but to fix the result failed. Update icon is when you reboot, login, out of sleep.</p>
<p>When you fasten the program to the taskbar, the label is created at % USER_DIR% \ AppData \ Roaming \ Microsoft \ Internet Explorer \ Quick Launch \ User Pinned \ TaskBar, and accordingly there to look for the label and update it.</p>
<p>Now the program can only work with one sheet of programs and program by default, you can specify only one. The latter limitation is very easy to remove, but to an executable file has worked with several sheets and attached to the taskbar will probably more difficult. The fact that the jump list is created in relation to the window / program. And there is speculation that can create derived windows, and for them to create lists and attach them to the taskbar. So far I&#8217;ve just copypased program to another folder and rename the executable file, then set up another jump list)) the program helps me and yet do not want to bother with supplementary windows and others, as it is easier to configure everything by hand. Lazy programmer &#8211; a good programmer!</p>
<p><a href="http://softblog.violet-tape.ru/download/WBR_QuickLists_II.zip">Source code</a>, <a href="http://softblog.violet-tape.ru/download/JumpList.zip">Application</a>, <a href="http://softblog.violet-tape.ru/download/Shortcuts_classes.zip">Files for icons creation</a></p>
<p>Hard’n’heavy!</p>
]]></content:encoded>
			<wfw:commentRss>http://softblog.violet-tape.net/2010/10/10/win7-jump-list-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Win7 Jump List</title>
		<link>http://softblog.violet-tape.net/2010/10/06/win7-jump-list/</link>
		<comments>http://softblog.violet-tape.net/2010/10/06/win7-jump-list/#comments</comments>
		<pubDate>Wed, 06 Oct 2010 16:01:04 +0000</pubDate>
		<dc:creator><![CDATA[Koissakh Kadderah]]></dc:creator>
				<category><![CDATA[Utils]]></category>
		<category><![CDATA[Distributable]]></category>
		<category><![CDATA[win 7]]></category>

		<guid isPermaLink="false">http://softblog.violet-tape.net/?p=153</guid>
		<description><![CDATA[Probably about the new Win7 features just lazy person hasn’t written, and a lot of reviews on the internet on how to apply it. I noticed that reading technical articles, which simply tell show to apply, or that tool is not very interesting. Much more interesting when technology is used … <a href="http://softblog.violet-tape.net/2010/10/06/win7-jump-list/"> Continue reading <span class="meta-nav">&#8594; </span></a>]]></description>
				<content:encoded><![CDATA[<p>Probably about the new Win7 features just lazy person hasn’t written, and a lot of reviews on the internet on how to apply it. I noticed that reading technical articles, which simply tell show to apply, or that tool is not very interesting. Much more interesting when technology is used on a particular useful example, resulting in a small useful program. Of course, this turns out not always, but lately I&#8217;ve been more and more I try to do.</p>
<p>Thus, we&#8217;ll solve the following problem: I have a lot of icons in the taskbar is attached. 2 studios, SQL Server, Expression studio, office applications, browsers &#8211; all this would be helpful to group and to the default run basic applications.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/jl-01.png"><img class="alignnone size-full wp-image-489" title="jl-01" src="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/jl-01.png" alt="" width="311" height="304" /></a></p>
<p><span id="more-153"></span></p>
<h1>The main functional</h1>
<p>To get started with a Quick Jump List you need to download Windows API Code Pack. After this create any project which in the end will create the window for user, it’s no need to show. I decided to train on WPF. So we have a project that creates a window. As a result, empirically it was found that the code to create &#8220;jump list&#8221; may be placed only after fully initialize at least one window (usually main). So in my opinion, to create a suitable response to the end of the loading window.</p>
<pre class="brush: csharp">private void Window_Loaded(object sender, RoutedEventArgs e) {
    CreateJumpList();
}</pre>
<p>The list of actions (programs) will be based on some of the data entered by the user.You need to know:</p>
<ul>
<li>The Way to the program</li>
<li>Name to display</li>
<li>Will it be the default action</li>
</ul>
<p>For these data, I created a small class</p>
<pre class="brush: csharp">[Serializable]
public class LinkInfo {
    public string Name { get; set; }
    public string AppPath{ get; set; }
    public bool IsDefault{ get; set; }
}</pre>
<p>I did not bother to check and so on, because this example, and remember that only 20% of the time spent on writing the functional. I did not want to spend more time than you need, everything else can be finished alone.</p>
<p>Suppose we have already a list of items LinkInfo, and we build the actual &#8220;just list.&#8221;First, add references to namespaces and Microsoft.WindowsAPICodePack.Shell and Microsoft.WindowsAPICodePack.Taskbar, then it is already possible to write real code.</p>
<p>Let&#8217;s start with the creation of the Jump List and categories.</p>
<pre class="brush: csharp">var JList = JumpList.CreateJumpList();
JList.ClearAllUserTasks();

var category = new JumpListCustomCategory("Tools");

JList.AddCustomCategories(category);</pre>
<p>Все просто и логично, вот что я люблю! =) Создание элементов списка тоже не будет rocket science.</p>
<pre class="brush: csharp">settings.Links.ForEach(item =&gt; {
     var link = new JumpListLink(item.AppPath, item.Name) {
                     IconReference = new IconReference(item.AppPath, 0 );  };
     category.AddJumpListItems(link);
});</pre>
<p>If an application has a few icons, you can specify it through a resource id when creating indetificator IconReference.<br />
To separate one category from another, you can use the following code:</p>
<pre class="brush: csharp">JList.AddUserTasks(new JumpListSeparator());</pre>
<p>You can add links to websites, and the folder. The way is a string, and the system will calculate what meant.</p>
<pre class="brush: csharp">JList.AddUserTasks(new JumpListLink("http://violet-tape.net", "Violet Tape"));

JList.AddUserTasks(new JumpListLink("C:\\temp", "Temp") {
            IconReference = new IconReference(setTools, 0)
});</pre>
<p>In general, the behavior of clicking on links can be described like this: &#8220;Run this is where I show and how – puzzle out youself!&#8221;</p>
<h1>Additional Functionality</h1>
<p>Do not dwell in detail on how to save and load settings and stuff like that. Let&#8217;s talk about the very small nuances of the application.<br />
Once we have assigned the default application, call our program should run the necessary program and this complete its activity (close). And at the same time we must be able to tweaking the program after the appointment of CDS programs. Yes, let’s look at the start arguments .<br />
It is necessary to make the point in &#8220;just list&#8221; to launch the program in setup mode. Let us for this parameter will be «-s». Then the entry in jump list will be such</p>
<pre class="brush: csharp">var setTools = Assembly.GetExecutingAssembly().Location;

var link = new JumpListLink(setTools, "Set tools") {
         IconReference = new IconReference(setTools, 0),
         Arguments = "-s"
};</pre>
<p>As you can see, nothing does not restrict us in the construction of list items. You can pass the start arguments to the applications, the working directory, as well as the form in which to show the window &#8211; minimize, maximize, as it is (and more)<br />
About how to work with arguments and application properties discussed earlier, so do not dwell on it.</p>
<h1>Conclusion</h1>
<p>This could be the starting point of the program. You can still realize a lot of things and of course to work on optimizing the code. Do not update the data as done in this program, use MVVMLight! =) The next article will continue to work on this program, to use the new features done Win 7.</p>
<p>Hard’n’heavy!</p>
]]></content:encoded>
			<wfw:commentRss>http://softblog.violet-tape.net/2010/10/06/win7-jump-list/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Notepad – –</title>
		<link>http://softblog.violet-tape.net/2010/10/02/notepad/</link>
		<comments>http://softblog.violet-tape.net/2010/10/02/notepad/#comments</comments>
		<pubDate>Sat, 02 Oct 2010 04:00:37 +0000</pubDate>
		<dc:creator><![CDATA[Koissakh Kadderah]]></dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Utils]]></category>
		<category><![CDATA[IPC]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[Win7]]></category>

		<guid isPermaLink="false">http://softblog.violet-tape.net/?p=151</guid>
		<description><![CDATA[This article is somewhat unusual in comparison to all previous ones, because it&#8217;s more like a conclusion and the summaryzing of the previous articles of this season. This is an example of interaction between the components of which I wrote recently: interprocess communication, command manager, the registration of extensions. Example … <a href="http://softblog.violet-tape.net/2010/10/02/notepad/"> Continue reading <span class="meta-nav">&#8594; </span></a>]]></description>
				<content:encoded><![CDATA[<p>This article is somewhat unusual in comparison to all previous ones, because it&#8217;s more like a conclusion and the summaryzing of the previous articles of this season. This is an example of interaction between the components of which I wrote recently: interprocess communication, command manager, the registration of extensions. Example I named so because it was chosen as an example of Notepad++, but due to the fact that this program only shows the options capability in close to real-life, we get a minus-minus.</p>
<p>You can name the current compilation of the backbone for further development. Now the program can open by clicking on the file with a registered extension, the file opens in new tabs, or, if you ask, then close all other tabs and the file will open in a single tab. There will always be running only one instance at one time.</p>
<p>I think that I should still consider how it works in reality. Focusing only on the differences that have emerged in real life. At the same time and will be seen asdescriptive material is different from a working prototype.</p>
<p><span id="more-151"></span></p>
<p>Once again on the &#8220;purpose&#8221; of the program: run only one instance, opened file sare in a new tab, if the program is already running.<br />
The program deliberately complicated in some places, as will surely be a live project. I will focus on programming in entered these places. So &#8230;</p>
<h1>The uniqueness of the instance</h1>
<p>The example in the article was based on WinForms and everything was quite simple, with WPF a different approach. Arguments passed to the program at startup are processed in the class App, then goes to show the main window MainWindow. When necessary to complete the second instance, we must call the completion of the application class App. This is not a problem, but we must somehow transmit knowledge about how to close the application or not. To do this, select an interface from a base class.</p>
<pre class="brush: csharp">public interface IApp {
    bool IsOriginal { get; }
}</pre>
<p>Now there would be a link from the main window of the application.</p>
<pre class="brush: csharp">public MainWindow() {
    if (((IApp) Application.Current).IsOriginal) {
        ...
        InitializeComponent();
        ...
    }
    else {
        Application.Current.Shutdown();
    }
}</pre>
<p>Thus the window of the second program and the user does not seem to notice anything, which is run a second instance.</p>
<h1>Pending commands</h1>
<p>In a real project, you will not use one set of commands. Yes, they will be inherited from an interface, for example ICommand, but there is only one method, so as not to contaminate all the other possible commands.</p>
<pre class="brush: csharp">public interface ICommand {
    void Execute();
}</pre>
<p>In this case we consider a principled approach when there is a command with parameters and commands without parameters. In this case, it does not matter how many parameters will be in the command.</p>
<pre class="brush: csharp">public class Command : ICommand {
     public Action Action { get; set; }

     public void Execute() {
         if (Action == null) return;

         Action();
    }
}

public class Command&lt;T&gt; : ICommand {
     public Action&lt;T&gt; Action { get; set; }
     public object ParameterT { get; set; }

     public void Execute() {
         if (Action == null) return;

         Action((T)ParameterT);
     }
}</pre>
<p>So far you could not see any problem with the use of commands. Command with parameters made in a generic style, because commands produce each type would not be rational, and simply lazy. A laziness &#8211; that&#8217;s what should be a programmer to develop!<br />
In a simple command is invoked there is no problem because of the signature you call correctly and without problems. But we have the program starts with initial parameters, they are parsed at the beginning of work and in the form of specific types of data to be transmitted to future performance.</p>
<blockquote><p>There can be debate, it is easier to store settings in a class or service as long as needed in a particular place, but we believe that there is no such possibility.</p></blockquote>
<p>Since the beginning of the program no commands are not yet registered, you have to put them in a queue for execution (the order must be preserved). And here begins the most interesting.</p>
<p>CommandManager not parameterized types, but the command looks like</p>
<pre class="brush: csharp">public void Execute&lt;T&gt;(CommandName commandName, Type type, T parameter) {
     var key = CreateKey(commandName, type);
     if (!commands.ContainsKey(key)) return;

     var command = ((Command&lt;T&gt;) commands[key]);
     command.ParameterT = parameter;
     command.Execute();
}</pre>
<p>You should clearly specify the type parameter, or it is computed automatically. We select the inner class for pending commands, there must be all the values for this command, so, name, type, and, if necessary, the parameter(s).</p>
<pre class="brush: csharp">public class CommandManager : ICommandManager {
     private class DelayedCommaind&lt;T&gt; {
         public Tuple&lt;CommandName, Type&gt; Key { get; set; }
         public T Parameter { get; set; }
     }

     ...

}</pre>
<p>If we make the parameter type as object, there will be no match for the target commands. On the other hand you can not declare a variable of typeDelayedCommaind</p>
<pre class="brush: csharp">public class CommandManager : ICommandManager {
     ...
     private readonly Queue&lt; DelayedCommaind&lt;T&gt; &gt; delayed = new Queue&lt; DelayedCommaind&lt;T&gt; &gt;();
     ...
}</pre>
<p>as the class itself is not parameterized and that for T we mean the compiler is not clear. On the way out we will have a new language feature 4.0 &#8211; dynamic!</p>
<pre class="brush: csharp">public class CommandManager : ICommandManager {
     private readonly Queue&lt;dynamic&gt; delayed = new Queue&lt;dynamic&gt;();
     private void Execute&lt;T&gt;(DelayedCommaind&lt;T&gt; delayed) {
     if (!commands.ContainsKey(delayed.Key)) return;

     if (delayed.Parameter.GetType() == typeof (NullParameter)) {
         var command = ((Command) commands[delayed.Key]);
         command.Execute();
     }
     else {
         var command = ((Command&lt;T&gt;) commands[delayed.Key]);
         command.ParameterT = delayed.Parameter;
         command.Execute();
    }
}</pre>
<p>Actually it turns out that the commands works as proxies, so, for each action does not create its own command and called ready, but with different parameters. I like this approach more than one time create commands and to pass parameters to the constructor (if any).</p>
<h1>WCF сервис</h1>
<p>Since the server and client are working with a class assembly, it will not autogenereticproxies classes and not have to bother with the data types. Here, too, was not withoutnuance. The parameters of the secondary to the primary instance of the applicationpassed by a class StartParameter. And the interface service method looks like this:</p>
<pre class="brush: csharp">[ServiceContract]
public interface ISingleInstanceService {
    [OperationContract]
    void PerformRemoteActions(List&lt;StartParameter&gt; commands);
}</pre>
<p>Class StartParameter, as you might imagine, also must somehow transmit meta-information about the command parameter, and for this type of object is not very suitable. Dynamic type again will help.</p>
<pre class="brush: csharp">[DataContract]
public class StartParameter {
    [DataMember] public CommandName CommandName;
    [DataMember] public dynamic Parameter;
    [DataMember] public bool HasParameter = true;
}</pre>
<p>The main thing that a variable passed Parameter serialized data type.</p>
<blockquote><p>Again there is scope for debate whether this method is limited, or create a bunch of methods according to needs. Or transfer all simple string, and parse the arguments run on the server side.</p></blockquote>
<h1>Commands registry</h1>
<p>There really is nothing special, just want to mention the bonuses that get in Win7.<br />
The main bonus &#8211; it is certainly quick access to documents is built automatically.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/nt_01.png"><img class="alignnone size-full wp-image-480" title="nt_01" src="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/nt_01.png" alt="" width="270" height="243" /></a></p>
<p>And from the context menu after registration of extension, you can get</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/nt_02.png"><img class="alignnone size-full wp-image-481" title="nt_02" src="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/nt_02.png" alt="" width="270" height="243" /></a></p>
<pre class="brush: csharp">public RegisterExtensions() {
    const string extension = ".ntpad";

    var location = Assembly.GetEntryAssembly().Location;
    var builder = new FileAssociateInfoBuilder("Notepad--", location)
         .AddCommand("Open", "-o", PassSelectedFile.ToApplication);
         .AddCommand("OpenExclusivelly", "-ox", PassSelectedFile.ToApplication);
         .AddExtension(extension);

    var service = new FileAssociateService();
    //service.DeleteAssociation(extension);
    if (!service.Exists(extension))
        service.CreateAssociation(builder.Result());
}</pre>
<h1>Outro</h1>
<p>That’s all what I wanted to tell you further.<br />
I hope it was not too messy and all turned out was similar to what I’ve described earlier.<br />
In order to test the program, create a text file and change it the extension to the one shown in the program. Than you can just open them by double-clicking or by right-clicking and watch what happens.</p>
<p><a href="http://softblog.violet-tape.ru/download/notepad--.zip">Source Code</a></p>
<p>Hard’n’heavy</p>
]]></content:encoded>
			<wfw:commentRss>http://softblog.violet-tape.net/2010/10/02/notepad/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Command Manager</title>
		<link>http://softblog.violet-tape.net/2010/09/28/command-manager/</link>
		<comments>http://softblog.violet-tape.net/2010/09/28/command-manager/#comments</comments>
		<pubDate>Tue, 28 Sep 2010 15:19:55 +0000</pubDate>
		<dc:creator><![CDATA[Koissakh Kadderah]]></dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Newbie]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">http://softblog.violet-tape.net/?p=149</guid>
		<description><![CDATA[Today I want to tell you about the pattern Command and Command Manager. All this went smoothly. In the last article, this is so and suggests itself, but I was too lazy to twist it back, I decided to tell apart. Although at first I had doubts as to whether … <a href="http://softblog.violet-tape.net/2010/09/28/command-manager/"> Continue reading <span class="meta-nav">&#8594; </span></a>]]></description>
				<content:encoded><![CDATA[<p>Today I want to tell you about the pattern Command and Command Manager. All this went smoothly. In the last article, this is so and suggests itself, but I was too lazy to twist it back, I decided to tell apart. Although at first I had doubts as to whether to tell all. Because I go to distribute the 5 ways to implement (as the complexity and development of the idea, but then one still rejected), and this functionality is even more developed and built in WPF. In the end, I think it will be useful to beginners, to be better understood how to use it in the future, in WPF, and in general.</p>
<p>Let&#8217;s start with the official part, that&#8217;s what Wikipedia tells us about the purpose of this template:</p>
<blockquote><p>Command &#8211; a design pattern used in object-oriented programming, which is for an action. The command object contains the action itself and its parameters. Provides processing commands in the form of an object that allows you to save her, to pass as a parameter of the method, and return it as a result, like any other object.</p></blockquote>
<p>From the definition we can say that with the help of commands to make the application less connected with each other. This can be useful for writing plug-ins when there are different implementations of a single action, when to run the program, with arbitrary initial actions identified in the command line, for example.</p>
<p><span id="more-149"></span></p>
<p>Most, if not all, interaction with the user in Visual Studio is built on the commands. As proof, you can open Tools &gt; Options &gt; Environment &gt; Keyboard and you see commands that can be binded to hotkeys. The same action can make the menu. Some acts are of plug-ins to the studio. Something makes the studio itself, as a result of remembering your actions (opening the latest working files for the project is opened) &#8211; all this is the result of a template. Otherwise would have been just a terrible linkage\references and Overobject &#8211; Oriented Programming.</p>
<p>In the disadvantages to this method can be written using non-obviousness in the final code and code complexity investigation without executing it.<br />
General view of the pattern shown in the diagram below.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/cm_01.gif"><img class="alignnone size-full wp-image-467" title="cm_01" src="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/cm_01.gif" alt="" width="388" height="254" /></a></p>
<p>Do not worry, in real life it would be simplier.</p>
<h1>Beginning</h1>
<p>Let&#8217;s start with the simplest and elementary way.<br />
Command will be without any parameters, just content for some action.</p>
<pre class="brush: csharp">public class Command {
    private readonly Action action;

    public Command(Action action) {
        this.action = action;
     }

    public void Execute() {
        if (action == null) return;
        action();
    }
}</pre>
<p>In this example, the action specified by the constructor, but you can do the same through the property, no problem in that I do not see.</p>
<p>In view of the fact that I prefer the interface polymorphism, for the latitude of the interface I&#8217;ve highlighted in this class, only to put the first command to complete.</p>
<pre class="brush: csharp">public interface ICommand {
    void Execute();
}</pre>
<p>On this backbone will be built and all the rest, the evolution in action .In order to have access to pre-established command, you need a centralized repository. This is so that you can reach of anywhere up to him and call the appropriate command in the least action. This store is said to be Command Manager.</p>
<pre class="brush: csharp">public static class CommandManager {
    private static readonly Dictionary&lt;string, ICommand&gt; commands = new Dictionary&lt;string, ICommand&gt;();

    public static void RegisterCommand(string commandName, ICommand command) {
        commands[commandName] = command;
    }

    public static void Execute(string commandName) {
        commands[commandName].Execute();
    }
}</pre>
<p>In its simplest form, the class is also simple. In this case, the class is made static, as in the example does not present the service locator. Heh, even though by itself it is also the manager and will have the same structure, only to give services on interfaces.</p>
<p>So, the command manager is used to store a dictionary key is the name of the command. Commands themselves are written on the interface. To make life more comfortable, I suggest to define a static class with the names of commands. Or you can use this enumerator.</p>
<pre class="brush: csharp">var command = new Command(DoJob);
CommandManager.RegisterCommand("Job", command);</pre>
<p>Using the same will be in this way</p>
<pre class="brush: csharp">CommandManager.Execute("Job");</pre>
<h1>The first improvement</h1>
<p>The second method extends the possibilities for recognition and usage. You will need only a little to improve Command Manager. , a unique key will be not only a command name and its associated type. This will create the same command for different data types. This will be achieved by using the type sequence.</p>
<pre class="brush: csharp">public static class CommandManager {
    private static readonly Dictionary&lt;Tuple&lt;string ,Type&gt;, ICommand&gt; commands = new Dictionary&lt;Tuple&lt;string ,Type&gt;, ICommand&gt;();

    public static void RegisterCommand(string commandName, ICommand command, Type type) {
        commands[new Tuple&lt;string, Type&gt;(commandName,type)] = command;
    }

    public static void Execute(string commandName, Type type) {
        commands[new Tuple&lt;string, Type&gt;(commandName,type)].Execute();
    }
}</pre>
<p>Otherwise, all the same.</p>
<h1>Second improvement</h1>
<p>As a further evolution of the command, it would still set conditions on action execution. To do this, extend the class of Command. The condition will be given as an option. So we finish in the Command class property</p>
<pre class="brush: csharp">public Func&lt;bool&gt; CanExecute { get; set;  }</pre>
<p>Now you can change the Execute method and make use of a new property there.</p>
<pre class="brush: csharp">public void Execute() {
    if(CanExecute() &amp;&amp; action != null)
    action();
}</pre>
<h1>The third improvement</h1>
<p>The logical development of all of this will have an opportunity to pass parameters to the command.</p>
<pre class="brush: csharp">public class Command&lt;T&gt; : ICommand {
    public Action&lt;T&gt; Action { private get; set; }
    public Func&lt;bool&gt; CanExecute { private get; set; }

    private T parameter;

    public void SetParameter(object parameter) {
        this.parameter = (T) parameter;
    }

    public Command() {
        CanExecute = () =&gt; { return true; };
    }

    public void Execute() {
        if (CanExecute() &amp;&amp; Action != null)
            Action(parameter);
    }
}</pre>
<p>The command is now a generic class that can be applied to any type of parameters.</p>
<p>CommandManager changes, respectively. Now, before a call is transferred to the command will be an optional parameter.</p>
<pre class="brush: csharp">public static void Execute(string commandName, Type type,object parameters = null) {
    var command = commands[new Tuple&lt;string, Type&gt;(commandName, type)];
    command.SetParameter(parameters);
    command.Execute();
}</pre>
<p>In this case I used a new feature of the fourth framework, autoinitialization parameter. With this declaration the parameter can be optional, but the parameters of this type should always go after a set of mandatory parameters.</p>
<p>And as the test case (though degenerate in this case)</p>
<pre class="brush: csharp">internal class MyClass {
    public MyClass() {
        var command = new Command&lt;string&gt; { Action = SomeAction };

        CommandManager.RegisterCommand(CommandNames.Open, command, GetType());

        CommandManager.Execute(CommandNames.Open, GetType());
        CommandManager.Execute(CommandNames.Open, GetType(), @"c:\temp\default.txt");
    }

    public void SomeAction(string s) {
        Console.Out.WriteLine("MC: " + s);
    }
}</pre>
<p>If it is used in another class, it will be in this way</p>
<pre class="brush: csharp">CommandManager.Execute(CommandNames.Open, typeof(MyClass), "from main thread");</pre>
<p>Such the manager of the command would have to be on the idea in a previous article about interprocess communication.<br />
<a href="http://softblog.violet-tape.ru/download/wbr_commandManager.zip">Source code</a> examples</p>
<p>Hard’n’heavy.</p>
]]></content:encoded>
			<wfw:commentRss>http://softblog.violet-tape.net/2010/09/28/command-manager/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Interprocess Communications</title>
		<link>http://softblog.violet-tape.net/2010/09/25/interprocess-communications/</link>
		<comments>http://softblog.violet-tape.net/2010/09/25/interprocess-communications/#comments</comments>
		<pubDate>Sat, 25 Sep 2010 13:37:45 +0000</pubDate>
		<dc:creator><![CDATA[Koissakh Kadderah]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[IPC]]></category>
		<category><![CDATA[mutex]]></category>
		<category><![CDATA[single application]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://softblog.violet-tape.net/?p=144</guid>
		<description><![CDATA[I have been interested for a long time how to do so that the one instance was running only. I mean I have known in theory with the help of what it should be done, but I haven’t tried yet..Another very interesting thing is how to do as for instance … <a href="http://softblog.violet-tape.net/2010/09/25/interprocess-communications/"> Continue reading <span class="meta-nav">&#8594; </span></a>]]></description>
				<content:encoded><![CDATA[<p>I have been interested for a long time how to do so that the one instance was running only. I mean I have known in theory with the help of what it should be done, but I haven’t tried yet..Another very interesting thing is how to do as for instance I open an Excel spreadsheet and  it does not open in another application, but the fact that is already open. This course  enrages sometimes, but still technology is interesting.</p>
<p>The rustling in the Internet has brought to what is called Interprocess Communication (IPC) and there are many ways how to implement it, depending on the ultimate goal, whether you have only one instance, or as in Excel, or something else. Further study of the issue and gave birth to this article.</p>
<p><span id="more-144"></span></p>
<h1>The theory</h1>
<p>Windows OS provides opportunities for fellowship programs and use of shared data between applications. In the most general case, this results in a client-server circuit, with one application acts as a server and a client. To address the issue of what type of communication to choose, you can ask yourself the following questions to help in choosing:</p>
<ul>
<li>o	Whether the application will interact with other applications on the network or only on your computer.</li>
<li>Will the application interact with applications written for other operating systems.</li>
<li>Should the application itself to determine with whom to interact, or choose to place on the user.</li>
<li>Will there be cooperation on the principle of copy-paste from other applications orinteraction will be severely limited in action.</li>
<li>How critical is performance.</li>
<li>Will the laying of a console or user interface. Some methods require the interaction ofa graphical interface.</li>
</ul>
<p>Windows supports the following mechanisms for data exchange:</p>
<ul>
<li>Clipboard</li>
<li>COM</li>
<li>Data Copy</li>
<li>DDE</li>
<li>File mapping</li>
<li>Mailslots</li>
<li>Pipes</li>
<li>RPC</li>
<li>Windows Sockets</li>
</ul>
<h5>Clipboard</h5>
<p>Acts as a common data store. When something is copied to the clipboard, the application puts data into one or more formats. Any other application can pick them out. For example pad, and the last Word.   <a href="http://msdn.microsoft.com/ru-ru/library/ms648709.aspx">Clipboard</a>.</p>
<h5>COM</h5>
<p>This application support model OLE &#8211; compound documents. The basis of OLE is a component object model (COM). Application that uses this technology can interact with a lot of applications, even those that are yet to be written. With this model you can run other applications, for which data do you have.</p>
<h5>Data Copy</h5>
<p>The application can send a message with a marker WM_COPYDATA. This requires cooperation throughout between the sending and the receiving side, based on the Windows Messaging.  <a href="http://msdn.microsoft.com/ru-ru/library/ms648710.aspx">Data Copy</a>.</p>
<h5>DDE</h5>
<p>Dynamic Data Exchange &#8211; can be presented as an extension of the mechanism of the clipboard. It can be used for network and local communication. Dynamic Data Exchange and Dynamic Data Exchange Management Library.  <a href="http://msdn.microsoft.com/ru-ru/library/ms648711.aspx">Dynamic Data Exchange</a> и <a href="http://msdn.microsoft.com/ru-ru/library/ms648712.aspx">Dynamic Data Exchange Management Library</a>.</p>
<h5>File Mapping</h5>
<p>Through this process, you can submit the file contents as a memory in the address segment of the process. The process can use a simple pointer to a file. If two applications are looking at one and the same file, you can modify the data by one application that another then gets an update. This is a very efficient mechanism that supports security at the OS level. Works locally and to provide synchronization between processes. <a href="http://msdn.microsoft.com/ru-ru/library/aa366556.aspx">File Mapping</a> и <a href="http://msdn.microsoft.com/ru-ru/library/ms686353.aspx">Synchronization</a>.</p>
<h5>Mailslot</h5>
<p>Provides a one-sided way of communication, there is a server and client messages go only from the client. But nothing prevents to make a server on the two sides. Supported by the communication network, and broadcast messages can be done, but no more than 400 bytes.  <a href="http://msdn.microsoft.com/ru-ru/library/aa365576.aspx">Mailslots</a>.</p>
<h5>Pipes</h5>
<p>There are two types &#8211; anonymous pipes and named pipes. Anonymous pipes can communicate related processes. For full-duplex communication is required to create two channels. Named pipes can be used for network communication between unrelated processes.  <a href="http://msdn.microsoft.com/ru-ru/library/aa365780.aspx">Pipes</a>.</p>
<h5>RPC</h5>
<p>Remote Process Call &#8211; allows you to remotely manage the application both locally and across the network. This method is compatible with the Open Software Foundation (OSF) Distributed Computing Environment (DCE) that makes it possible to exchange messages with other operating systems. Supports automatic data conversion for different platforms. Client and server are connected very weakly, but still show the high efficiency at work. <a href="http://msdn.microsoft.com/ru-ru/library/aa374169.aspx">Microsoft RPC Components</a></p>
<h5>Windows Sockets</h5>
<p>This is independent of the protocol data interface. You can exchange messages withany system that supports the implementation of this protocol. <a href="http://msdn.microsoft.com/ru-ru/library/ms740673.aspx">Windows Sockets 2</a>.</p>
<p>Yes, being a freshman, I would not rack brains with all this zoo and slapped a code to create and delete a file in the root folder of the program. And would gain application which doesn&#8217;t work after the first emergency shutdown of the program! =D</p>
<h1>The aim</h1>
<p>On the local computer to be able to send the arguments a second instance of the program first. That is implementing any functional program that opens a document in one of his window. For example, it can be Excell, Notepad + +, WinAmp.</p>
<p>Reach the goal we will with named pipes and RPC. In a specific implementation, this will make the WCF Named Pipes and Mutex for RPC. Two methods for comparing the implementation. Looking ahead to say that I like WCF is much more. Easier to code and its smaller.</p>
<p>In pursuit of the goal, we will have two primary objectives:</p>
<ol>
<li>Determine whether there is already an instance of the program in memory;</li>
<li>If you run a second instance, his arguments to pass in the first instance.</li>
</ol>
<h1>Preparation</h1>
<p>In both implementations will be on two projects for a better separation of functionality. One WinForms, which will check and data processing. The second project in fact with the necessary functionality.</p>
<h1>Mutex approach</h1>
<p>The first method is based on the use of RPC. To create the solution we need some design and visual components (WinForm, WPF) and a class library. </p>
<p>To solve the problem number one will use a mutex. </p>
<p>When two or more threads simultaneously need to access a shared resource, the system needs a synchronization mechanism to ensure the use of the resource only one thread at a time. Mutex &#8211; primitive, which provides exclusive access to a shared resource to only one stream synchronization. if thread gets the semaphore, the second thread, wishes to obtain the semaphore, suspended until such time until the first thread releases the semaphore. </p>
<p>A named mutex in the system can be only one, and on this name, you can find it .Accordingly, immediately comes the idea that the existence check it in the system will tell us whether there is a system already running instance of the application. </p>
<p>Let&#8217;s start with a basic class that will create mutexes. </p>
<pre class="brush: csharp">public class SingleInstanceTracker : Idisposable {
    private bool disposed;
    private Mutex singleInstanceMutex;
    private bool isFirstInstance;

    public SingleInstanceTracker(string name){
        if (string.IsNullOrEmpty(name))
            throw new ArgumentNullException("name", "name cannot be null or empty.");
        try {
            singleInstanceMutex = new Mutex(true, name, out isFirstInstance);
        }
       catch (Exception ex) {
           throw new SingleInstancingException("Failed to instantiate a new SingleInstanceTracker object", ex);
       }
    }

    ~SingleInstanceTracker() {
       Dispose(false);
    }

    protected virtual void Dispose(bool disposing) {
        if (!disposed) {
          if (disposing) {
            if (singleInstanceMutex != null) {
              singleInstanceMutex.Close();
              singleInstanceMutex = null;
            }
          }
         disposed = true;
       }
    }

    public void Dispose() {
        Dispose(true);
       GC.SuppressFinalize(this);
    }

    public bool IsFirstInstance {
        get { return isFirstInstance;  }
    }
}</pre>
<p>Creating the mutex limited to one line.</p>
<pre class="brush: csharp">singleInstanceMutex = new Mutex(true, name, out isFirstInstance);</pre>
<p>The same line of code and tell us this is the only instance or not. Well, the first point of the program is made super-fast. But it does not have moved the problem to transfer data from one instance to another.</p>
<p>For data transfer we use a special namespace <strong>System.Runtime.Remoting.Channels.Ipc</strong>. It defines a class <em>IpcServerChannel </em>by means of which will go to data transfer.</p>
<p>The data transmitted over this channel to be inheriting from the class <em>MarshalByRefObject</em>, so they can remotely create, and to enable them to travel outside the application domain. Data must also be serializable. Yet it would be nice to define a delegate that will perform the methods in the first application, but run from second. Thus, the proxy class</p>
<pre class="brush: csharp">internal class SingleInstanceProxy : MarshalByRefObject {
    private readonly ISingleInstanceEnforcer enforcer;

    public SingleInstanceProxy(ISingleInstanceEnforcer enforcer) {
        if (enforcer == null)
            throw new ArgumentNullException("enforcer", "enforcer cannot be null.");

       this.enforcer = enforcer;
    }

    public override object InitializeLifetimeService() {
       return null;
    }

    public ISingleInstanceEnforcer Enforcer {
       get { return enforcer; }
    }
}

public delegate ISingleInstanceEnforcer SingleInstanceEnforcerRetriever();

public interface ISingleInstanceEnforcer {
    void OnMessageReceived(MessageEventArgs e);
    void OnNewInstanceCreated(EventArgs e);
}</pre>
<p>Create and register a channel is as follows:</p>
<pre class="brush: csharp">Var ipcChannel = new IpcServerChannel(name);
ChannelServices.RegisterChannel(ipcChannel, false);</pre>
<p>Where the <strong>name </strong>- the name of the channel.</p>
<p>The algorithm works with the channels, after creating the mutex will be:</p>
<p>If this is the first instance, it is necessary</p>
<ul>
<li>create a channel</li>
<li>register a channel</li>
<li>register the proxy type as a known type</li>
<li>create a proxy and make a link to it through the address icp</li>
</ul>
<p>If we have a second instance, then</p>
<ul>
<li>create a channel</li>
<li>register a channel
<ul>
<li>obtain a proxy from the first instance</li>
<li>send data through a proxy</li>
</ul>
</li>
</ul>
<pre class="brush: csharp">const string proxyObjectName = "WBRSingleInstanceProxy";
var proxyUri = "ipc://" + name + "/" + proxyObjectName;

if (isFirstInstance) {
    ipcChannel = new IpcServerChannel(name);
    ChannelServices.RegisterChannel(ipcChannel, false);

    RemotingConfiguration.RegisterWellKnownServiceType(typeof (SingleInstanceProxy), proxyObjectName,WellKnownObjectMode.Singleton);

    var enforcer = enforcerRetriever();

    if (enforcer == null)
       throw new InvalidOperationException("The method must return an ISingleInstanceEnforcer object.");

    proxy = new SingleInstanceProxy(enforcer);
    RemotingServices.Marshal(proxy, proxyObjectName);
}
else {
    ipcChannel = new IpcClientChannel();
    ChannelServices.RegisterChannel(ipcChannel, false);

    proxy = (SingleInstanceProxy) Activator.GetObject(typeof (SingleInstanceProxy), proxyUri);

    proxy.Enforcer.OnNewInstanceCreated(new EventArgs());
}</pre>
<h5>Transmission and message processing</h5>
<p>Determine the uniqueness and originality of the program in memory will run at, so in <strong>Program.cs</strong>.</p>
<pre class="brush: csharp">private static void Main(params string[] args) {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    SingleInstanceTracker tracker = null;
    try {
       tracker = new SingleInstanceTracker("SingleInstanceSample", GetSingleInstanceEnforcer);
       if (tracker.IsFirstInstance)
          Application.Run((MainForm) tracker.Enforcer);
       else
          tracker.SendMessageToFirstInstance(args);
    }
    catch (SingleInstancingException ex) {
        MessageBox.Show("Could not create a SingleInstanceTracker object:\n" + ex.Message + "\nApplication will now terminate.");
        return;
    }
   finally {
        if (tracker != null)
            tracker.Dispose();
   }
}

private static ISingleInstanceEnforcer GetSingleInstanceEnforcer() {
     return new MainForm();
}</pre>
<p>First, try to create a tracker to determine its uniqueness. If the process is alreadyrunning previously, passing the parameters of this process using the SendMessageToFirstInstance.</p>
<p>Processing of this message will occur at the application form (for simplicity). The form must implement the interface ISingleInstanceEnforcer.</p>
<pre class="brush: csharp">void ISingleInstanceEnforcer.OnMessageReceived(MessageEventArgs e) {
    OnMessageReceivedInvoker invoker = delegate(MessageEventArgs eventArgs) {
        var msg = eventArgs.Message as string[];
        if (msg == null) return;
        listBox1.Items.Clear();
        listBox1.Items.AddRange(msg);
    };

    if (InvokeRequired)
         Invoke(invoker, e);
    else
         invoker(e);
}</pre>
<p>In the delegate defined actions that must be take when receiving a message. In life, there will need to use a template &#8220;command manager&#8221;, so you can pretty handle different messages.</p>
<h1>WCF approach</h1>
<p>The second way we favor the use of the WCF service. It will be an indicator of the primary instance and the method for sending messages. We again need the visual design and WCF library.</p>
<p>WCF service wrapper can work so many things and can be applied to almost any situation when you have to organize the interaction between parts of a program or between programs. That&#8217;s what Windows Communication Service, and to think about it.</p>
<p>To work within a single machine will be used Binding NetNamedPipeBinding. Ideally suited for our task, as a named pipe can be a very easy and there is.</p>
<p>We start from a distance of some semblance of Command Manager. For simplicity, all the same it will be a static class. And yes, in this case, start with the second problem, data.</p>
<pre class="brush: csharp">public static class ActionManager {
    public static Action&lt;string[]&gt; ItemsAction;
}</pre>
<p>We now make the registration of this action on the main form. Or in a more complicated case in ViewModel.</p>
<pre class="brush: csharp">public partial class Form1 : Form {
    public Form1() {
       InitializeComponent();
       ActionManager.ItemsAction = array =&gt; {
                          listBox1.Items.Clear();
                          listBox1.Items.AddRange(array);
                       };
    }
}</pre>
<p>ТNow for the actual implementation of the WCF service. The project is already the default template Service1, it can be freely renamed or leave as is, without any damage. I renamed it SingleInstanceService.</p>
<p>The service so far there is only one method that will accept a string array.</p>
<pre class="brush: csharp">[ServiceContract]
public interface ISingleInstanceService {
    [OperationContract]
    void SomeArgs(params string[] args);
}

public class SingleInstanceService : ISingleInstanceService {
    public void SomeArgs(params string[] args) {
         ActionManager.ItemsAction(args);
    }
}</pre>
<p>That&#8217;s the whole service. There will be no more than a single line of code! In fact, we all built to the acceptance and processing of data. Now we must learn to pass them. This functionality will be placed in Program.cs.</p>
<p>First will have to specify a unique name for the channel. Then, create a host for WCFservice. We can say that setting the WCF service is a fully manual mode. When you create a service specify which class is the main functionality..</p>
<pre class="brush: csharp">var address = new Uri("net.pipe://localhost/WBRSingleInstanceService");

var serviceHost = new ServiceHost(typeof (SingleInstanceService), address);</pre>
<p>Next, specify the binding. It will be named pipes. Here you can specify the behavior of the binding, the maximum waiting time, buffer size and stuff like that.</p>
<pre class="brush: csharp">var binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);

var localMbehave = new ServiceMetadataBehavior();

serviceHost.Description.Behaviors.Add(localMbehave);</pre>
<p>The next step is to create the endpoints. At the beginning of the development will create two points: one service MEX, in order to be able to configure a service reference. Another would be the end point of the service. After setting up and in the final release MEX point can be removed.</p>
<pre class="brush: csharp">serviceHost.AddServiceEndpoint(typeof (IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), "mex");
serviceHost.AddServiceEndpoint(typeof (ISingleInstanceService), binding, address);

serviceHost.Open();

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());

serviceHost.Close();</pre>
<p>After run the service and do not forget to close it after the end of the application. Now we must create a link to the service. Run the application without debug Ctrl-F5 and add a link to the service.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/ipc_01.png"><img class="alignnone size-full wp-image-458" title="ipc_01" src="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/ipc_01.png" alt="" width="284" height="260" /></a></p>
<p>Trying to drive a service address, which we have indicated in the code and click &#8220;GO&#8221;. It should look something like in the picture.</p>
<p><a href="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/ipc_02.png"><img class="alignnone size-full wp-image-459" title="ipc_02" src="http://softblog.violet-tape.ru/wp-content/uploads/2010/09/ipc_02.png" alt="" width="631" height="510" /></a></p>
<p>Select the namespace for the service and finish the job with this dialog box. Done!</p>
<p>We can now solve the first problem, the uniqueness of the service. Just try to join him by creating client-side.</p>
<pre class="brush: csharp">var client = new SingleInstanceServiceClient("NetNamedPipeBinding_ISingleInstanceService");
client.SomeArgs(args);</pre>
<p>If this fails, then just complete the application, if not, then create a new host. If it is not carried out the operation will be an exception of type SomeArgsEndpointNotFoundException, which clearly indicates that the host is not running.</p>
<p>That&#8217;s all folks!</p>
<h1>How to verify that everything works</h1>
<p>In the first method, all checked OK by pressing a button on the form, then creates a process and there is an exchange of information.</p>
<p>In the second method is not a trick when you run into laminates debug. I guess the whole reason for this is correct but it is too lazy in this example. The main thing that it works, and check it out as follows. Go to the folder bin, where the application has already been collected. Do link to an executable file and the label in the properties of Target after the path to the file write anything you want.</p>
<p>Run the main file, then run through the same label and see that the main application to update the data.</p>
<h1>Conclusion</h1>
<p>In my opinion the second method is much simpler to create and operate. In an improved version of the second method can not pass a set of arguments from the command line and have formed their own team, which will handle the primary copy. It is also the service itself is richer, all typed and transparently, that comes and where sent.</p>
<p>For both methods is to write a good team manager, that there is no rigid bundles with fiber interface for instance</p>
<p>Source code of <a href="http://softblog.violet-tape.ru/download/WBR_SingleInstancingWithIpc.zip">the first example</a>, <a href="http://softblog.violet-tape.ru/download/WBR_SingleInstanceWCF.zip">the second example</a>.</p>
<p>Hard’n’heavy!</p>
]]></content:encoded>
			<wfw:commentRss>http://softblog.violet-tape.net/2010/09/25/interprocess-communications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
