streda 3. októbra 2007

LINQ to XML - XDocument a String

V tomto príspevku sú vyzdvihované XML literály jazyka VB9 v porovnaní s C# 3.0. Hlavnou výhodou XML literálov je sprehľadnenie kódu. Podobný výsledok môžeme však jednoducho dosiahnúť aj v C# 3.0 vytvorením vlastnej rozšírujúcej metódy (extension method), ktorá bude parsovať reťazec na XDocument takto:


   1:  using System;

   2:  using System.Xml.Linq;

   3:   

   4:  namespace StringToXDocument

   5:  {

   6:      public class Program

   7:      {

   8:          static void Main(string[] args)

   9:          {

  10:              XDocument doc = @"<book>

  11:                                    <title>Pro WCF</title>

  12:                                    <publisher>APress</publisher>

  13:                                </book>".ToXDocument();

  14:          }

  15:      }

  16:   

  17:      public static class StringExtensions

  18:      {

  19:          public static XDocument ToXDocument(this string text)

  20:          {

  21:              return XDocument.Parse(text);

  22:          }

  23:      }

  24:  }

pondelok 1. októbra 2007

IL Merge - Quick Start

ILMerge is utility that merges set of .NET assemblies into single .NET assembly. To use ILMerge download it from here and run installation. Using of ILMerge ilustrates following command:

ILMerge /out:MergedAssembly.exe Application.exe Library1.dll Library2.dll Library3.dll

ILMerge is a console application, but it can be also used as library. Assemblies containing unmanaged code can't be merged.

DoEvents in WPF

I developed some WPF application with ProgressBar control and I solved problem how to realize the equivalent of Application.DoEvents() method in WPF. WPF based solution using dispatcher is described here. But I discovered that for this purposes can be also well known System.Windows.Forms.Application.DoEvents() method used. It is very easy, just add reference to system.windows.forms.dll assembly and use this method exactly like in WinForms.
APress - Pro WPF in C# 2008Sams - Windows Presentation FoundationO'Reilly - Programming WPFWrox - Professional WPF Programming

utorok 14. augusta 2007

ASP.NET - DataGrid rendered with thead, tbody, th, ....

By default DataGrid is rendered with tags <table>, <tr> and <td>. To make styling with CSS easier it would also suitable to render also tags <thead>, <tbody>, <th> etc. To solve this problem I created custom DataGrid derived from System.Web.UI.WebControls.DataGrid, where in overriden method OnPreRender are realized modifications:


   1:  using System;

   2:  using System.Reflection;

   3:  using System.Web.UI;

   4:  using System.Web.UI.WebControls;

   5:   

   6:  namespace NMarian.Controls

   7:  {

   8:      public class DataGrid : System.Web.UI.WebControls.DataGrid

   9:      {

  10:          protected override void OnPreRender(EventArgs e)

  11:          {

  12:              Table table = Controls[0] as Table;

  13:   

  14:              if (table != null && table.Rows.Count > 0)

  15:              {

  16:                  table.Rows[0].TableSection = TableRowSection.TableHeader;

  17:                  table.Rows[table.Rows.Count - 1].TableSection = TableRowSection.TableFooter;

  18:   

  19:                  FieldInfo field = typeof(WebControl).GetField("tagKey", BindingFlags.Instance | BindingFlags.NonPublic);

  20:   

  21:                  foreach (TableCell cell in table.Rows[0].Cells)

  22:                  {

  23:                      field.SetValue(cell, HtmlTextWriterTag.Th);

  24:                  }

  25:              }

  26:   

  27:              base.OnPreRender(e);

  28:          }

  29:      }

  30:  }

nedeľa 12. augusta 2007

ASP.NET AJAX - Script compression doesn't work in IE6

I try to enable compression in script resource handler in web.config file:


   1:  <system.web.extensions>

   2:      <scripting>

   3:          <scriptResourceHandler enableCompression="true" enableCaching="true" />

   4:      </scripting>

   5:  </system.web.extensions>


Analyzing the network traffic I discover that this works fine under Opera, Mozilla Firefox, IE7 but doesn't work under IE6. Response headers for Mozilla Firefox:

HTTP/1.1 200 OK
Content-Length: 23423
Expires: Mon, 11 Aug 2008 11:35:45 GMT
Date: Sun, 12 Aug 2007 11:35:45 GMT
Content-Type: application/x-javascript
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Content-Encoding: gzip
Cache-Control: public
Last-Modified: Sat, 04 Aug 2007 12:23:19 GMT

Response headers for IE6:

HTTP/1.1 200 OK
Content-Length: 84019
Expires: Mon, 11 Aug 2008 11:44:23 GMT
Date: Sun, 12 Aug 2007 11:44:23 GMT
Content-Type: application/x-javascript
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Cache-Control: public
Last-Modified: Sat, 04 Aug 2007 12:23:19 GMT

Can anybody explain this behavior of ASP.NET AJAX?

sobota 14. júla 2007

.NET - spustenie súkromnej metódy rodičovskej triedy pomocou reflexie

Raz som pri unit testoch potreboval spustiť súkromnú metódu rodičovskej triedy pomocou reflexie. Problémom je, že metóda GetMethod triedy System.Type nevráti MethodInfo pre súkromné metódy definované na úrovni rodičovskej triedy. Môj trik spočíva v tom, že MethodInfo je vytvorené pre rodičovskú triedu a Invoke je volané s parametrom kde je odkaz na triedu potomka:


   1:  // Faq inherits from BusinessObject

   2:  Faq faq = new Faq();    

   3:  RunPrivateMethodOnBusinessObject(faq, "CreateInsertCommand")

   4:   

   5:  private object RunPrivateMethodOnBusinessObject(object obj, string methodName)

   6:  {

   7:      MethodInfo method = typeof(BusinessObject).GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);

   8:      return method.Invoke(obj, null);

   9:  }

C# - podmienený preklad pomocou ConditionalAttribute

Podmienený preklad v C# môžeme zrealizovať pomocou kódu:


   1:  #if DEBUG

   2:  void ConditionalMethod()

   3:  {

   4:      // ....

   5:  }

   6:  #endif


Elegantnejšie riešenie je podľa mňa použitie atribútu [Conditional], pretože pokiaľ nebude definovaný symbol DEBUG, tak aj volania metódy ConditionalMethod budú pri preklade vynechané:


   1:  [Conditional("DEBUG")]

   2:  void ConditionalMethod()

   3:  {

   4:      // ....

   5:  }

WS-Security pomocou WSE 3.0 bez X.509 certifikátov

Nedávno som potreboval zabezpečiť webovú službu aspoň na takej úrovni, aby jej nemohol hocikto posielať správy. Rozhodol som sa použiť Web Services Enhancements 3.0 for Microsoft .NET. Chcel som, aby SOAP správy prichádzajúce k webovej službe boli digitálne podpísané (aby počas prenosu sieťou nikto nemohol meniť obsah správy), nechcel som však použiť X.509 certifikáty pretože by bol problém s ich použitím v prostredí kde mala byť aplikácia nasadená. Riešenie som našiel v článku Custom WSE 3.0 Policy Assertions for Signing and Encrypting SOAP Messages with Username Tokens. V riešení je na digitálny podpis použitý username token.

ASP.NET - DataGrid renderovaný s thead, tbody, th, ....

Štandartne sa DataGrid renderuje tagmi <table>, <tr> a <td>. Pre zjednodušenie štýlovania tabuľky pomocu CSS je vhodné okrem spomínaných tagov renderovať aj tágy <thead>, <tbody>, <th> a podobne. Na riešenie tohto problému som vytvoril vlastný DataGrid odvodený od System.Web.UI.WebControls.DataGrid pričom v prekrytej metóde OnPreRender sú vykonané všetky potrebné úpravy:


   1:  using System;

   2:  using System.Reflection;

   3:  using System.Web.UI;

   4:  using System.Web.UI.WebControls;

   5:   

   6:  namespace NMarian.Controls

   7:  {

   8:      public class DataGrid : System.Web.UI.WebControls.DataGrid

   9:      {

  10:          protected override void OnPreRender(EventArgs e)

  11:          {

  12:              Table table = Controls[0] as Table;

  13:   

  14:              if (table != null && table.Rows.Count > 0)

  15:              {

  16:                  table.Rows[0].TableSection = TableRowSection.TableHeader;

  17:                  table.Rows[table.Rows.Count - 1].TableSection = TableRowSection.TableFooter;

  18:   

  19:                  FieldInfo field = typeof(WebControl).GetField("tagKey", BindingFlags.Instance | BindingFlags.NonPublic);

  20:   

  21:                  foreach (TableCell cell in table.Rows[0].Cells)

  22:                  {

  23:                      field.SetValue(cell, HtmlTextWriterTag.Th);

  24:                  }

  25:              }

  26:   

  27:              base.OnPreRender(e);

  28:          }

  29:      }

  30:  }

ASP.NET - ako zistiť, či už stránka bola validovaná?

V niektorých situáciach potrebujeme zistiť, či už prebehla validácia stránky. Ak by sme zavolali Page.IsValid ešte predtým ako prebehla validácia, tak by sme dostali výnimku. Moje riešenie tohto problému znázornené v nasledujúcej utilite využíva mechanizmus reflexie:


   1:  using System.Web;

   2:  using System.Web.UI;

   3:  using System.Reflection;

   4:   

   5:  public class PageUtil

   6:  {

   7:      public static bool IsPageValidated()

   8:      {

   9:          Page page = HttpContext.Current.Handler as Page;

  10:          if (page == null) throw new HttpException("This method can be called only in classes derived from System.Web.UI.Page");

  11:          FieldInfo fieldValidated = typeof(Page).GetField("_validated", BindingFlags.Instance  BindingFlags.NonPublic);

  12:          return (bool)fieldValidated.GetValue(page);

  13:      }

  14:  }

streda 11. júla 2007

IL Merge - spájanie viacero .NET assemblies do jednej

Včera som potreboval spojiť viacero .NET assemblies (jedna .exe a viacero .dll) do jednej. Vytvoril som jednoduchú WinForms aplikáciu, ktorá sa mala distribuovať iba kopírovaním (nechcel som použiť inštaláciu ani ClickOnce). Obsahovala jeden .exe súbor, viacero .dll a konfiguračný súbor.

Na spájanie assemblies je určená utilita IL Merge. Pre konfiguračný súbor (app.config) som nastavil build action na embedded resource, čím sa stal súčasťou .exe súboru. Potom som v post-build event spustil IL Merge:

"c:\Program Files\Microsoft\ILMerge\ILMerge.exe"
/out:SingleAssembly.exe MyApp.exe Library1.dll Library2.dll Library3.dll


Výsledkom je jediný súbor SingleAssembly.exe

streda 27. júna 2007

Seriál o programovaní vo WCF

Od začiatku roka píšem seriál o programovaní vo Windows Communication Foundation (WCF) pre server vyvojar.cz.

Spustenie blogu

Dnes som spustil môj osobný blog. Plánujem tu uverejňovať príspevky najmä z oblasti programovania a vývoja softvéru.