0 Comments

This post covers storing and retrieving settings with a WPF combobox for the UI. If you are looking for a solution to store settings across devices, for instance a Windows Surface tablet and a Windows Phone powered device, you should check out the blog of Mike Taulty. That is called roaming data storage. And if you are not working on an app for Windows RT/metro or Windows Phone but are just coding some WPF application, you should read this post from Scott Hanselman.

Let’s start with some code now that it’s clear what this post covers and what it doesn’t cover.

Here is my XAML from my userinterface:

<ComboBox x:Name="cbCountry" 
    SelectionChanged="ComboBox_SelectionChanged" 
    PlaceholderText="Select country" SelectedValuePath="Tag">
    <ComboBoxItem Content="Australia" Tag="au"/>
    <ComboBoxItem Content="New Zealand" Tag="nz"/>
</ComboBox>

Please note the ‘SelectedValuePath’ is being set to ‘Tag’, otherwise it would grab the ‘comboboxitem’ or ‘content’ like this:

var comboboxContent = ((ComboBoxItem)cbCountry.SelectedValue).Content;

With the value path set to tag, it will grab ‘au’ or ‘nz’ as selected value.

This is the constructor of the xaml page containing my settings.

var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

this.InitializeComponent();

if (localSettings.Values.ContainsKey("country"))
{
    cbCountry.SelectedValue = localSettings.Values["country"];
}

and this is the code for the selectionchanged event of the combobox.

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    localSettings.Values["country"] = cbCountry.SelectedValue;
}

Good luck with this small code sample. If this is not what you are looking for, please check the links mentioned at the start. I strongly believe that they take you to the code that you are looking for (if the code above is insufficient)

Post on LinkedIn
0 Comments

Here is a small C# code snippet to upload an XML file to an explicit SSL secured FTP server.

When you search nuget for FTP you will get:

image

But which one do you need? Not all of them support FTPS. Well the checkbox gives it away.

If you search for FTPS you will only get these seven results (at this moment):

image

So you need the System.Net.FtpClient from https://netftp.codeplex.com/

And here is the C# code to upload an XDocument to an FTPS server:

private void UploadFile(XDocument xDoc, string filename)
{
    using (FtpClient fc = new FtpClient())
    {
        fc.Credentials = new NetworkCredential(username, password);
        fc.Host = hostname;
        fc.EncryptionMode = FtpEncryptionMode.Explicit;
        fc.ValidateCertificate += fc_ValidateCertificate;
        fc.Connect();
        fc.SetWorkingDirectory("/uploaddir");

        using (var ftpStream = fc.OpenWrite(filename, FtpDataType.Binary))
        {
            if (ftpStream != null)
            {
                xDoc.Save(ftpStream);
                ftpStream.Close();
            }
        }
    }
}

static void fc_ValidateCertificate(FtpClient control, FtpSslValidationEventArgs e)
{
    e.Accept = true;
}

Self signed certificates will otherwise always cause an exception in the ftp libraries because the certificates are not really valid. So you manually have to “validate” it.


Good luck!

Post on LinkedIn
0 Comments
  •   Posted in: 
  • C#

Dymo has some great label printing hardware and has a nice .Net SDK. It seems that they are moving away from the .Net SDK and more towards the JavaScript SDK. In my situation I wanted to host a small Rest service on a Windows 2012 server so that I can make an Ajax call with jQuery to it to print a label from my web application. So it is a kind of printing proxy with REST. We had previously only Internet explorer support in our web application, so using the Active X component was easy for us. Though it required a client installation and the client to configure the network shared printer.

The strange thing is that this code looks good at first sight. Also if you compare it with the Dymo label code. It even works great on my machine, but when I put it live on our production server it failed. No exception or whatsoever, but it simply said that there is no label writer.

StringBuilder sb = new StringBuilder
var label = DYMO.Label.Framework.Label.Open(System.Web.HttpContext.Current.Server.MapPath(@"~/Content/thelabel.label")); // mvc webapplication
label.SetObjectText("Address", sb.ToString());
label.Print(ConfigurationManager.AppSettings.Get("printername"));
// printername = \\pcname\dymo
  

Even when I list the label printer, it does not show up in the list. Printing with the default label printing software from dymo (version 8.x) works great on my machine and the server, but not by code.

StringBuilder sbPrinters = new StringBuilder();
DYMO.Label.Framework.Printers p = new DYMO.Label.Framework.Printers();
foreach(var printer in p.ToList())
{
    sbPrinters.AppendLine(printer.Name);
    sbPrinters.AppendLine(printer.ModelName);
    sbPrinters.AppendLine(printer.IsConnected.ToString());
    sbPrinters.AppendLine(printer.IsLocal.ToString());
    sbPrinters.AppendLine("-==========-");
}
return sbPrinters.ToString(); // empty...

I have tried an Asp.Net web application 4.5 with WebApi on Windows 2012 and a 4.0 Webforms application on Windows 2003. Both did not work. So what is wrong? I used the build in Visual Studio development server and on both windows servers (2003 and 2012) I used IIS. So that might be the problem. I have heard about Katana and OWIN and started a small test project with this guide. Somehow it works when you are not using IIS! I also tried Asp.Net impersonation in the web.config. Maybe running in full trust works, but I prefer a tiny Windows Service with Owin. So go check out the project page of Katana on codeplex or simply pull down this Nuget package of Microsoft Owin. This Channel9 video of 43 minutes is also a great online source to learn more about the Katana project, OWIN for Asp.Net.

Good luck with the Dymo .Net SDK!

Post on LinkedIn
1 Comments

Since we moved from an on premises SQL Server to SQL Azure we experienced a lot of timeouts. This is the exact errormessage:


Connection Timeout Expired.  The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement.  This could be because the pre-login handshake failed or the server was unable to respond back in time.  The duration spent while attempting to connect to this server was - [Pre-Login] initialization=3; handshake=29995;

After searching the web for a while it appeared that it is recommended to use the Microsoft Enterprise Library. Version 6 was released last April. So there are not so much code samples at the moment. But there is a free e-book! Developer's Guide to Microsoft Enterprise Library, 2nd Edition. You can download it for free from Microsoft's website or order a paperback from amazon.


I installed two nuget packages for the enterprise library.2014-01-03 16_35_03-Shop - Manage NuGet Packages

My data access class required these two additions to the usings:

using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.SqlAzure;
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;
  

And my function which returns a simple datatable looks like this now:

public static DataTable GetDatatable(SqlCommand com)
{
    DataTable dt = new DataTable();

    RetryStrategy retryStrategy = new Incremental("fixed", 5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
    RetryPolicy retryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(retryStrategy);
    retryPolicy.Retrying += new EventHandler<RetryingEventArgs>(retryPolicy_Retrying);

    List<RetryStrategy> retryStrategies = new List<RetryStrategy> { retryStrategy };

    var manager = new RetryManager(retryStrategies, "fixed"); // this name must match the name of the incremental

    try
    {
        RetryManager.SetDefault(manager); // you have to set the default
    }
    catch { } // but you cannot check if it is already set, that's why I used a try, catch

    try
    {
        retryPolicy.ExecuteAction(() =>
        {
            using (SqlConnection con = new SqlConnection(GetConStr()))
            {
                com.Connection = con;
                SqlDataAdapter da = new SqlDataAdapter(com);

                con.OpenWithRetry();
                da.Fill(dt);
            }
        });
    }
    catch (Exception e)
    {
        WriteDbError(e, com);
    }
    return dt;
}

I know that you can configure the enterprise library to use settings from the web.config. I decided to use hardcoded “variables” because they do not change (much). Please let me know if you have more improvements for the code above. I have a simple GetConStr() method which just returns the connection string from the web.config file.

So this code will solve about 99% of your azure timeouts!

Good luck! Let me know your opinion in the comments!

ps. Happy new year!

Shout it kick it on DotNetKicks.com

Post on LinkedIn
0 Comments

but COM was not at home, so COM could not answer ;)we_not_alone_02

This was my error (it was actually a warning according to Visual Studio 2013):

Warning 13 Generation of the designer file for MagazineDetails.aspx failed: Error HRESULT E_FAIL has been returned from a call to a COM component. C:\www\myproject\MagazineDetails.aspx

It is the same error as the following people have/had:

I am not alone, so I decided to blog about it. My configuration contains a Windows 8.1 x64 install with all the latest updates and have Visual Studio 2013 (version 12.0.21005.1) and I had this issue with just one aspx file.

The error was not even visible at first. I had to lower the warning level (it was 4, and error was visible at 3)

project-settings

The thing is that this invisible error broke my intellisense and when I added controls like literals, buttons, labels etc. to the aspx. The “codebehind” (aspx.cs) did not recognize them. It was frustrating! And this was only an issue with one or two aspx files. (out of 30 or something)

On stackoverflow there were three rather nice suggestions:

  • (re-)convert to web application the project
  • switch to the designer and back to re-generate
  • restart visual studio

Unfortunately, none of the above fixed my problem. I found an other suggestion and cannot find the source, so I am sorry that I can not give credits to the person who pointed me in the right direction. But the solution is to add a classname to the page directive. Somehow it caused the IDE to recognize all the controls in the code behind and re-enabled the intellisense in the code behind.

<%@ Page Title="Magazine details" Language="C#" MasterPageFile="~/nl.Master" AutoEventWireup="true" CodeBehind="MagazineDetails.aspx.cs" Inherits="NikkiLissoni.MagazineDetails" ClassName="NikkiLissoni.MagazineDetails" %>

I hope this will help out other developers and might save them an hour or two searching for a solution for this strange behaviour.

Good luck!

kick it on DotNetKicks.com Shout it

Post on LinkedIn