Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, December 24, 2007

Integrating Web Browser with WPF Forms

There are so many situations where you need to render an HTML in your forms. It may happen when you'd want, for example, to show an external web page, feed or a locally generated content like XML or an HTML. The Web Browser is extremely handy for the Web Automation (I’ll talk about it in future posts) since you have full HTML DOM available for control at your fingertips. So, having WPF now out there is not changing a thing – it’s still possible to host Web Browser inside a form.

Look how easy it is. Let’s say you want to show your blog on an application form. To do so:

  1. Create a WPF application with a Form.
  2. From the toolbox drop a WindowsFormsHost on the form. Give it a name, let’s say, “windowsFormsHost”. Make sure that the references to the WindowsFormsInteroperability and System.Windows.Forms were added to your project. To make a better presentation make the Margin = 0 – the control will fill in all the available form’s space.
  3. In the XAML source add “Loaded” attribute with “Window_Loaded” value to the tag.
  4. Add the following code to the Window_Loaded handler in the .cs file:


       1:  WebBrowser wb = new WebBrowser();
    2: wb.Navigate(ConfigurationManager.AppSettings["Feed"]);
    3: windowsFormsHost.Child = wb;

Build, run and enjoy!


Source code can be found as usual on my site.

Sunday, December 23, 2007

RSS is not only for the news

The new Syndication libraries, provided in the .NET 3.5, making creation of the RSS feeds a walk in a park. By combining them with the power of the WCF you can get an amazing results.
RSS technology allows you to reverse the client/server tandem from push to pull paradigm. Instead of client sending data to server you can publish the available data and make server to decide what to pull(download) and what to ignore, This can save a lot of valuable resources like time, network bandwidth, data transfer and processing.

To make my case more interesting and appealing let’s imagine a situation where you want to make a back-up agent that will be archiving all the text files. In order to do so, all the desktops will publish all the newly changed files that need to be archived. The server will subscribe to all the relevant feeds. In this article I’ll cover, for starters, only the client’s side and in the following articles we’ll talk about different discovery and subscription mechanisms that we have in our disposal in .NET for the server.

The following snippet shows you how to create s simple syndication feed:



1: SyndicationFeed feed = new SyndicationFeed();
2: List<SyndicationItem> items = new List<SyndicationItem>();
3: ...
4: SyndicationItem item = new SyndicationItem(title, path, GetFileUri(path));
5: items.Add(item);
6: feed.Items = items;



As you can see it’s extremely easy, but this was just a half of the job. The other half is to publish the feed. There are a lot of ways to do it, but I’m going to cover one of them. Since WCF is one of the best things to use in windows services (as well as in Web services), I’m going to use it to publish the feed. Here how you will initialize the WCF host with the Feed Service as a singleton (single-instance):


   1:  FileChangeFeedService service = new FileChangeFeedService();
2: ServiceHost serviceHost = new ServiceHost(service);
3: serviceHost.Open();



Note: don’t forget to mark the service class as a single-instance service by adding ServiceBehavior attribute –


   1:  [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
2: IncludeExceptionDetailInFaults = true)]



Announce: I’ll be talking about REST in the following posts as well as a new “Give it a REST” presentation is ready for broader public to attend.

One of the beautiful things that became available with .NET 3.5 is Url templates. This allows to put HTTP verbs on the methods of a web service as well as to map the Url parts (not only parameters) to a method parameters. This in many cases will eliminate any need for parsing of the data. All the mentioned above, make the WCF Web Services REST compatible.

For example:


   1:  [OperationContract]
2: [WebGet(UriTemplate = "?format={format}")]
3: SyndicationFeedFormatter Feed(string format);


This contract method will be called if a web request will come to the following URL:

http://localhost/feed?format=rss

The format parameter (“rss” in our case) will be extracted from the URL and passed as a parameter to the Feed method. This allows us to seamlessly provide different feed formatting (thanks to the new WCF libraries):



1: public SyndicationFeedFormatter Feed(string format)
2: {
3: if ((format != null) && (format.ToLower() == "rss"))
4: return new Rss20FeedFormatter(feed);
5:  
6: return new Atom10FeedFormatter(feed);
7: }



Note: if no parameters will be provided (i.e.: http://localhost/feed) the Feed method will be called with a NULL value.

And here is what will glue everything together – the config file:



<configuration>
<system.serviceModel>
<services>
<service name="FileChangeFeed.FileChangeFeedService">
<endpoint address="http://localhost:8080/feed" binding="webHttpBinding"
bindingConfiguration="" contract="FileChangeFeed.IFileChangeFeed" behaviorConfiguration="webBehavior" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>


Note the endpoint behavior. As you can guess the feed can be published over any protocol, but if you’ll want to view the feed using standard RSS feed readers, it’s better to publish it over HTTP.

As soon as you’ll start the application and the service will be published – put the base Uri (http://localhost:8080/feed) in IE’s address box and you’ll see a rendered RSS feed view.

Have fun with RSS feeds and don’t be afraid to explore your possibilities.

The source code can be found on my site.

Wednesday, November 21, 2007

Part 2 - Securing Server with SSL


It's not a walk in the park to work with certificates. There are a lot of bells and whistles to it than it meets the eye, but I'll try to walk you through this nightmare step-by-step in the set of the following posts. But first, I'll show you how you can jump-start your development and encrypt your traffic with some hand-made and self-issued certificates.

There are a lot of ways to self-issue a test certificate, but I'm going to share with you the EASIEST one I use myself. Follow these simple steps, one by one, to create a test certificate:

  1. Create a root certificate:

    makecert -pe -n "CN=Igor Cert Authority" -ss my -sr LocalMachine -a sha1 -sky signature -r "Igor Cert Authority.cer"

    If you'll run the MMC console with Certificates Add-in (Computer Account/Local Computer) and navigate to Certificates/Personal/Certificates node, you will see that the "Igor Cert Authority" certificate already installed:


  2. Create a certificate for the encryption purposes:

    makecert -pe -n "CN=myhost" -ss my -sr LocalMachine -a sha1 -sky exchange -eku 1.3.6.1.5.5.7.3.1 -in "Igor Cert Authority" -is my -ir LocalMachine myhost.cer

    Note: the best way to use your machine's DNS name in all the places I've used "myhost"

    If you'll refresh the MMC console with Certificates Add-In - you'll see that the new "myhost" certificate will be configured for you as well.

The result of the exercise above is the "myhost.cer" file that you can use now to encrypt your communication.

For the sake of this demonstration, let's use the NULL SMTP server I've put together. This server will receive all the incoming SMTP requests and will process them as if it's a real SMTP server. The server will encrypt the incoming communication with the certificate that was created in the steps above.

  1. Create a certificate object from the CERT file:

       1:  X509Certificate serverCertificate = X509Certificate.CreateFromCertFile("myhost.cer");

  2. As soon as the new client connection is established - encrypt the stream with this certificate:

       1:  TcpListener listener = new TcpListener(IPAddress.Loopback, port);
    2: ...
    3: TcpClient client = listener.AcceptTcpClient();
    4: ...
    5:
    6: // Create the SslStream using the client's network stream.
    7: SslStream sslStream = new SslStream(client.GetStream(), false);
    8:
    9: // Authenticate the server but don't require the client to authenticate.
    10: sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, false);

In order to test the server, I've used the Outlook Express (it is in most cases installed by default on every machine). Don't forget to tell the Outlook Express that the communication should be secure (note the check box in the Outgoing SMTP mail section):


After the configuration is complete - have fun by sending e-mails. The sever will process all the outgoing traffic over the encrypted channel:

You can download the source of the NULL SMTP Server from my site - here.

Tune-in for the upcoming set of articles that will show you a lot of new and cool staff.

Tuesday, November 20, 2007

Visual Studio 2008 and .NET 3.5 Released

I don't want to announce the obvious, but just point you to a great blog to check for the news. Go to Scott Gu's Blog for the latest news about the Visual Studio and .NET features.

Sunday, November 11, 2007

Part 1- Securing Client Stream with SSL


Most of the communications outside of your home network are secured and encrypted. The most popular kind of a secured communication today is the SSL. In most cases it is not even required to do any configuration for the end user.

Let's assume: we have a server that requires that all the incoming connections be secured with SSL. The following post shows an example of how this can be accomplished.

I'll show you the implementation by securing the POP3 communication while retrieving e-mails from the Gmail POP3 servers by the POP3 tunneling client. This client was introduced by Bart De Smet in this series of posts:
Pop3 Tunneling

Note that authentication of the client is optional. This allows us to use the SSL only for the channel encryption without any client authentication and authorization. This is why the HTTPS (HTTP over SSL) is widely popular - the end users are not required to issue and configure their own certificates and the server-side issued certificates are used to encrypt the traffic.

   1:  // The following method is invoked by the RemoteCertificateValidationDelegate.
2: private bool ValidateServerCertificate(
3: object sender,
4: X509Certificate certificate,
5: X509Chain chain,
6: SslPolicyErrors sslPolicyErrors)
7: {
8: if (sslPolicyErrors == SslPolicyErrors.None)
9: return true;
10:
11: Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
12:
13: // Do not allow this client to communicate with unauthenticated servers.
14: return false;
15: }
16:
17: SslStream sslStream = new SslStream(client.GetStream(), false,
18: new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
19: sslStream.AuthenticateAsClient(server);
20: stream = sslStream;


The modified Pop3Client (Pop3ClientSecured) code can be downloaded here. The package includes a test application as well, so you're welcome to try it against your Gmail account (if you have it or any other POP3 account).