peschuster

Technology, .NET and Web

  • Info

.NET

Force HttpWebRequest to IPv4

April 24, 2016 by peter

Here’s how you can enforce the usage of IPv4 in Dual Stack environments with HttpWebRequests in C#/.NET:

string host = @"www.peschuster.de";
IPHostEntry ipHostEntry = Dns.GetHostEntry(host);
IPAddress address = ipHostEntry.AddressList.FirstOrDefault(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
    ?? ipHostEntry.AddressList.FirstOrDefault();
                
var request = HttpWebRequest.Create("http://" + address.ToString() + "/2016/04/force-httpwebrequest-to-ipv4") as HttpWebRequest;
request.Host = host;

request.GetResponse();

This is a very basic example. You should add some checks, whether the address could actually be resovled, etc. for use in production.

Posted in: .NET Tagged: .NET, c#

WinForms ListView DoubleClick Event for Empty Lists

January 2, 2014 by peter

The WinForms ListView control fires double click events only if the user clicked on a selected item. This is also documented on the MSDN site: “The mouse pointer must be over a child object (TreeNode or ListViewItem).” (Control.DoubleClick Event).

Sometimes it is useful to perform actions on double click events for empty ListView controls, too.

To achieve this you have to implement a custom ListView control which inherits from the original WinForms ListView control:

using System;
using System.Security.Permissions;
using System.Windows.Forms;

internal class CustomListView : ListView
{
    private const int WM_LBUTTONDBLCLK = 515;

    private bool doubleClickFired;

    protected override void OnDoubleClick(EventArgs e)
    {
        base.OnDoubleClick(e);

        this.doubleClickFired = true;
    }

    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
    protected override void WndProc(ref Message m)
    {
        this.doubleClickFired = false;

        base.WndProc(ref m);

        if (m.Msg == WM_LBUTTONDBLCLK && !this.doubleClickFired)
        {
            this.OnDoubleClick(EventArgs.Empty);
        }
    }
}

This custom control checks whether a double click event was triggered for double clicks of the left mouse button on the control. If this is not the case, it triggers a double click event “manually”.

Posted in: .NET, UI Tagged: .NET, ListView, UI, WndProc

How to configure ConnectionStrings in web.config per developer/user

December 9, 2012 by peter

One thing Martin Fowler states in his article about Evolutionary Database Design is that every developer needs to have its own database instance.

For .NET Windows client projects you can simply change the ConnectionStrings configuration in the App.config file inside the bin directory. But for web/ASP.NET projects this is not possible, because the root directory for debugging the project is the project directory itself (being under source control). I.e. you would have to checkout the web.config file from source control and edit it. This itself is not such a problem, but you always have to watch out to not check the changed web.config file into source control.

The Solution

A solution to make this work is to split the web.config configuration into multiple files and extend the build process by editing the project file of the web project to create a configuration file which is not in source control and therefore can be customized per developer.

1. Split the configuration

Replace the connectionStrings configuration in your web.config file with the following line:

  <connectionStrings configSource="connectionStrings.config" />

2. Create a default configuration

Create a new configuration file “connectionStrings.default.config” with your configured ConnectionStrings (example):

<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
    <add 
      name="MyDbConnection" 
      connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=MyAppDb;User ID=myapp;Password=123pw" />
</connectionStrings>

3. Extend the build process

Edit the project file and include a new target “BeforeBuild” (at the bottom of the file, but inside the “project” node):

<Target Name="BeforeBuild">
  <Copy 
      Condition="!Exists('connectionStrings.config')" 
      SourceFiles="connectionStrings.default.config" 
      DestinationFiles="connectionStrings.config" />
</Target>

This extends the build process with a new step which checks whether the file “connectionStrings.config” exists and (if not) copies the file “connectionStrings.default.config” to “connectionStrings.config“. When you want to change a ConnectionString in your local development environment you can simply edit the file “connectionStrings.config” and adjust it to your environment.

4. Add a transformation for publishing

For publishing/deploying your project you can create a web.config transformation which “inlines” the ConnectionStrings again:

<?xml version="1.0" encoding="utf-8"?>

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings xdt:Transform="Replace">
    <add 
      name="MyDbConnection" 
      connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=MyAppDb;User ID=myapp;Password=123pw" />
  </connectionStrings>
</configuration>

Summary

Summing it up, the solution consists of the following parts

  • An outsourced ConnectionString configuration not under source control.
  • A default ConnectionString configuration under source control.
  • A build step ensuring a ConnectionString configuration exists at the expected path.
  • (Optional) A web.config transformation for cleaning everything up on publishing/deploying the project.
Posted in: .NET, ASP.NET Tagged: .NET, ASP.NET, Build, Configuration

How to Debug OnStart of .NET Windows Services during Development

October 25, 2012 by peter

Have you ever tried to debug a .NET Windows Service during development?

Of course you can attach a debugger to the service process using Debug –> Attach to Process*. But it is practically impossible to debug the OnStart method this way.

One possible solution is to “request” a debugger in your code by using Debugger.Launch(). When you wrap this statement in a conditional precompiler directive you can control when to attach a debugger through your current build configuration:

protected override void OnStart(string[] args)
{
#if DEBUGGER
    Debugger.Launch();
#endif

    // Your code here...
}

To use it, you can create a new build configuration and set this symbol in the build configuration settings of the project:

image

* Note: When the service runs under the SYSTEM user account you need to run Visual Studio “as Administrator” to see the service process in the “Attach to Process” window or attach a debugger instance to it.

Posted in: .NET Tagged: .NET, Debugging, Visual Studio

Interop type ‘iTunesAppClass’ cannot be embedded.

June 7, 2012 by peter

iTunes comes with an api you can access from any (.NET) program by adding the COM reference “iTunes 1.xx Type Library” (see iTunes COM for Windows SDK) to your Visual Studio project:

using iTunesLib;
iTunesApp app = new iTunesAppClass();

When trying to instantiate an ‘iTunesAppClass’ object the compiler initially outputs the following error message, although creating an instance of this class is the only way to access iTunes:

“Interop type ‘iTunesLib.iTunesAppClass’ cannot be embedded. Use the applicable interface instead.”

 

This is due to a setting in the reference properties:

  1. Go to the Solution Explorer.
  2. Right click on References –> iTunesLib and hit Properties.
  3. Set “Embed Interop Types” to False.

image

This solves the described error and you can go on automating iTunes.

Remarks: For German localization settings the error message is “Der Interoptyp “iTunesLib.iTunesAppClass” kann nicht eingebettet werden. Verwenden Sie stattdessen die entsprechende Schnittstelle.”

Posted in: .NET Tagged: .NET, Interop, iTunes

How to add an uac shield icon to a MenuItem

December 8, 2011 by peter

Since Windows Vista an application needs administrator privileges to perform some system operations like starting or stopping a Windows service. To gain these privileges you can add an “app.manifest” file to your project in Visual Studio and set the requestedExecutionLevel to requireAdministrator.

In Windows there is always the small shield icon to inform the user that administrator privileges are required for the desired action:

image

To add this icon to your own context menu in a WinForms project the following steps are required:

1. Check that the user currently has no administrator privileges:

public bool HasAdministratorRights
{
    get
    {
        var pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

        return pricipal != null && pricipal.IsInRole(WindowsBuiltInRole.Administrator);
    }
}

2. Use a ContextMenuStrip and ToolStripMenuItems instead of the old ContextMenu and MenuItems.

3. Import the SHGetStockIconInfo method from shell32:

private static class NativeMethods
{
    [DllImport("Shell32.dll", SetLastError = false)]
    public static extern Int32 SHGetStockIconInfo(SHSTOCKICONID siid, SHGSI uFlags, ref SHSTOCKICONINFO psii);

    public enum SHSTOCKICONID : uint
    {
        SIID_SHIELD = 77
    }

    [Flags]
    public enum SHGSI : uint
    {
        SHGSI_ICON = 0x000000100,
        SHGSI_SMALLICON = 0x000000001
    }

    [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct SHSTOCKICONINFO
    {
        public UInt32 cbSize;
        public IntPtr hIcon;
        public Int32 iSysIconIndex;
        public Int32 iIcon;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szPath;
    }
}

4. Fetch the shield icon and create a bitmap out of the HIcon:

private void SetUacShield(ToolStripMenuItem menuItem)
{
    NativeMethods.SHSTOCKICONINFO iconResult = new NativeMethods.SHSTOCKICONINFO();
    iconResult.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(iconResult);

    NativeMethods.SHGetStockIconInfo(
        NativeMethods.SHSTOCKICONID.SIID_SHIELD, 
        NativeMethods.SHGSI.SHGSI_ICON | NativeMethods.SHGSI.SHGSI_SMALLICON, 
        ref iconResult);

    menuItem.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
    menuItem.Image = Bitmap.FromHicon(iconResult.hIcon);
}

That’s all. Now you can restart you application with administrator rights or call another executable with the “runas” verb:

private void RunAsAdmin(string fileName, string args)
{
    var processInfo = new ProcessStartInfo
    {
        Verb = "runas",
        FileName = fileName,
        Arguments = args,
    };

    try
    {
        Process.Start(processInfo);
    }
    catch (Win32Exception)
    {
        // Do nothing...
    }
}
Posted in: .NET, UI Tagged: .NET, UAC, UI, WinForms

New line bug in ASP.NET MVC Textarea helper

November 6, 2011 by peter

To render a textarea for a model property in ASP.NET MVC you usually perform a call to @Html.TextAreaFor(…):

@Html.TextAreaFor(m => m.MyProperty)

Recently I encountered the strange behavior that it always adds a new line at the beginning of the textarea. How comes?

Analysis

Note: if you just look for a workaround for this bug scroll down to “Conclusion and solution”.

Internally the TextAreaFor(…) method uses the TextAreaExtensions class in System.Web.Mvc.Html. The code responsible for generating the html output looks roughly like the following:

private static MvcHtmlString TextAreaHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string name, IDictionary<string, object> rowsAndColumns, IDictionary<string, object> htmlAttributes)
{
    // Some initialization here...

    TagBuilder tagBuilder = new TagBuilder("textarea");

    // Some more logic...
 
    tagBuilder.SetInnerText(Environment.NewLine + attemptedValue);
    return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);
}

So, the intended output of TextAreaFor is:

<textarea>
This is the content...</textarea>

This should be fine and not add an extra new line at the beginning, right? Well, the actual html output looks like this:

<textarea>&#13;&#10;This is the content...</textarea>

There seems to be some more magic in place. And by risking a deeper look at TagBuilder.SetInnerText(…) we discover that it does a call to HttpUtility.HtmlEncode(…):

public void SetInnerText(string innerText)
{
    this.InnerHtml = HttpUtility.HtmlEncode(innerText);
}

Now the pieces come together and one important fact surfaces: the bug only appears when the popular AntiXssEncoder is used as HttpEncoder. The AntiXSS encoder encodes output in views in a safer way by using a white list approach for allowed characters. Till now you had to manually include the AntiXSSEncoder in your ASP.NET MVC project, but up from the next version (ASP.NET 4.5) it is already included and can be activated via web.config.

Conclusion and solution

In contrast to the default HttpEncoder the AntiXssEncoder also encodes new line characters to “&#13;&#10;”, but for the browser this is not the same like just a new line in the html markup. In ASP.NET MVC4 Developer Preview (and most likely also in the soon coming stable version) this is fixed, but till then the probably easiest workaround is to create your own helper for rendering textarea markup in views:

public static MvcHtmlString FixedTextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
    return new MvcHtmlString(htmlHelper.TextAreaFor(expression)
        .ToHtmlString()
        .Replace(">&#13;&#10;", ">" + Environment.NewLine));
}

(On demand you can just create fixed versions of TextAreaFor(…) for the other overloaded methods like in the example above.)

Posted in: .NET, ASP.NET Tagged: .NET, AntiXssEncoder, ASP.NET, MVC

WIF in depth: Validating Security Tokens outside of WIF

August 1, 2011 by peter

Sometimes it is necessary to validate SecurityTokens issued by an Windows Identity Foundation (WIF) driven Identity Provider (IdP) in a Service Provider (SP) application that has no reference to WIF.

When it came to validating the xml signature of the token I ran into an exception on calling the CheckSignature() method of the SignedXml class:

System.Security.Cryptography.CryptographicException: 
SignatureDescription could not be created for the signature algorithm supplied.

What this exception message basically states is that it does not know the specified signature algorithm. The name of this algorithm is set by the corresponding xml attribute in the raw token data as http://www.w3.org/2001/04/xmldsig-more#rsa-sha256.

The problem here is that this signature algorithm is not supported by the core .NET framework (http://blogs.msdn.com/b/shawnfa/archive/2008/08/25/using-rsacryptoserviceprovider-for-rsa-sha256-signatures.aspx). I found some blog posts on how to activate support for this algorithm, but it did not really work out for me.

So after I failed trying to adjust the code of the SP application to fit WIF, I had a look at the other side of the pipe: my Identity Provider implemented using WIF:

I did not tell WIF to use RSA-SHA256 as signature algorithm anywhere and my X.509 certificate also used RSA-SHA1. So obviously this algorithm must be set somewhere inside of WIF as default value. And indeed it is: If you do not explicitly specify the signature algorithm when calling a constructor of the X509SigningCredentials it is set to RSA-SHA256 by default:

public X509SigningCredentials(X509Certificate2 certificate, SecurityKeyIdentifier ski) 
    : this(
        new X509SecurityToken(certificate), 
        ski, 
        "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", 
        "http://www.w3.org/2001/04/xmlenc#sha256")
{
}

So the solution to this problem is to use another constructor of the X509SigningCredentials class on setting the SigningCredentials of the SecurityTokenService.

An example:

this.SigningCredentials = new X509SigningCredentials(
    certificate,
    "http://www.w3.org/2000/09/xmldsig#rsa-sha1",
    "http://www.w3.org/2000/09/xmldsig#sha1");

Another issue I was facing on manually validating the xml signature of a security token is that the default SignedXml class was not able to find the Id element of the security token. The following article did the trick for me: http://blogs.msdn.com/b/shawnfa/archive/2004/04/05/108098.aspx

Posted in: .NET, WIF Tagged: .NET, Security, SecurityToken, WIF, WIF in depth

WIF in depth: What’s a SecurityKeyIdentifierClause

July 29, 2011 by peter

Windows Identity Foundation (WIF) is a powerful framework for implementing a federated (i.e. distributed) authentication and authorization scheme into your application. It is fairly easy to use with already existing security token services (STS) like Windows Azure Access Control Services (ACS) or the Active Directory Federation Services 2.0 (ADFS 2.0), but when it comes to implementing your own STS it gets really tricky.

The first part – creating the SecurityTokenService class – is covered by several tutorials and blog posts on the web and the WIF SDK from Microsoft also contains a Visual Studio project template for this task. But when it comes to creating your own SecurityTokenHandler (required for custom security token formats) your pretty much on your own.

In this post I am gone explain what the purpose of the classes SecurityKey, SecurityKeyIdentifier and SecurityKeyIdentifierClause in the context of your own SecurityToken implementation is.

To understand the full concept of these SecurityKey concerned classes you have to be aware that there are several types of SecurityTokens. What is commonly referred to as security token are so called “Bearer Tokens” (carrying information with them, e.g. like claims). But a SecurityToken could for example also be a wrapped X.509 certificate (see also the other post about the IssuerNameRegistry).

SecurityKey

As the name already suggests a SecurityKey is just a “security key” for cryptographic operations (like signing or encrypting security tokens). This could be a X.509 certificate, a rsa key (pair) or anything similar. Returning a collection of SecurityKeys is required on a class inheriting from SecurityToken, but usually you just don’t care about security keys in your custom bearer SecurityToken implementation and return an empty, read-only list:

public override ReadOnlyCollection<SecurityKey> SecurityKeys 
{ 
    get { return new List<SecurityKey>().AsReadOnly(); }
}

SecurityKeyIdentifierClause

A SeurityKeyIdentifierClause is something like the unique identifier of a security key. It is used to reference a specific token (or security key) without including the whole content of the token.

You most probably stumble upon this the first time when implementing the CreateSecurityTokenReference method of your custom SecurityTokenHandler class.

As this method is called during issuing tokens and a SecurityTokenIdentifierClause is expected as return value, you have to take care of the logic behind it.

For Saml tokens the CreateSecurityTokenReference() implementation looks like the following:

public override SecurityKeyIdentifierClause CreateSecurityTokenReference(SecurityToken token, bool attached)
{
    if (token == null)
        throw new ArgumentNullException("token");

    return token.CreateKeyIdentifierClause<SamlAssertionKeyIdentifierClause>();
}

Purpose of a SecurityKeyIdentifierClause is to compare tokens. Therefore it has a Matches(object keyIdentifierClause) method. This method is used by a SecurityTokenResolver to return the corresponding SecurityToken for the specified SecurityKeyIdentifierClause.

Summing all this up: a SecurityKeyIdentifierClause is an identifier with some logic to compare equality with other SecurityKeyIdentifierClause objects. So the best implementation for your custom bearer SecurityToken is most probably to use the LocalIdKeyIdentifierClause with the id of your token as localId parameter.

SecurityKeyIdentifier

A SecurityKeyIdentifier is simply a collection of SecurityKeyIdentifierClauses. When ever needed you can use the implementation in System.IdentityModel.Tokens here. There is usually no need to take care of this by your self.

Posted in: .NET, WIF Tagged: .NET, Security, SecurityKey, SecurityToken, WIF, WIF in depth

Upgrading user settings

July 12, 2011 by peter

Or: Why your saved settings are always overridden by the previous ones

In an application of mine I persist user settings (like username, form position, window state, etc.) in a user configuration file (for more information on this topic in general have a look at this MSDN article).

In code you can access this settings like this:

var user = Properties.Settings.Default.User;

Properties.Settings.Default provides also methods for saving changed settings and upgrading persisted settings from a previous application version.

What upgrade does is to copy the settings file from a path like “path-to-settings/Company/MyApplication/1.0.0.1/user.config” to the path reflecting the current application version: “path-to-settings/Company/MyApplication/1.0.0.2/user.config”.

The crux of the matter is that copying the file is always performed, never the less whether there is already a user configuration file for the current version or not.

In conclusion this means you as the programmer have to make sure that Upgrade is only called once after you upgraded to a new version. Otherwise all changed values are always replaced by the last state from the old application version.

An easy solution to circumvent the described behavior of the upgrade method is to check whether a property in the user settings has still its default value, although it should have been set already:

if (String.IsNullOrEmpty(Properties.Settings.Default.User))
    Properties.Settings.Default.Upgrade();
Posted in: .NET Tagged: .NET, Configuration, UserSettings

Syndication

  • RSS 2.0

Recent Posts

  • Ubiquiti EdgeRouter™ X SFP – Teardown
  • Force HttpWebRequest to IPv4
  • Blackmagic Design ATEM GPI and Tally Interface Teardown
  • WinForms ListView DoubleClick Event for Empty Lists
  • Planning Center Online – Custom Plan Reports in Landscape Orientation

Tags

.NET AntiXssEncoder ASP.NET Build c# Configuration crawler Debugging EF ELMAH Expression tree Graphite Interop IssuerNameRegistry iTunes Linq ListView MVC pco pdf Security SecurityKey SecurityToken simulatebe sql server StatsD STS teardown TYPO3 UAC UI UserSettings Visual Studio WIF WIF in depth WinForms WndProc
profile for Peter at Stack Overflow, Q&A for professional and enthusiast programmers Peter Schuster

Copyright © 2023 peschuster.

Alpha WordPress Theme by themehall.com