Archive for category C#
How to ignore whitespace formatting in merge conflicts in TFS in Visual Studio 2010.
Posted by Brian Seekford in C# on December 2, 2011
Hate when you see all Blue because someone reformatted the code?
Fix it.
In Visual Studio, select Tools / Options / Source Control / Visual Studio Team Foundation System and click the Configure User Tools button.
In the dialog, Add an item with the following settings.
- Extension : .*
- Operation : Compare
- Command : C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\diffmerge.exe
- Arguments : %1 %2 %6 %7 %5 /ignorespace
If you are 64 bit,
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\diffmerge.exe
Happy Coding!
How To Fix:Error 39 The type or namespace name ‘Contracts’ does not exist in the namespace ‘XXX’ (are you missing an assembly reference?)
Posted by Brian Seekford in .NET Development, C# on June 6, 2011
So….Just got done mentally disintegrating my computer and various items around it. This lovely error kept appearing to tell me ABSOLUTELY NOTHING.
I checked my references, of course they were included. It’s how I had intellisense, and every other feature that leads me to believe everything is A OK. That is, until you actually compile. You then get the awesomely descriptive error above.
Oh, It appears descriptive right? You say, oh, I must have done something wrong and somehow removed the assembly reference. Let me check it? Nope, it’s there.
Well, it turns out the answer is simple and the stupid compiler could have added one more suggestion. Here is how I would write it.
The type or namespace name ‘Contracts’ does not exist in the namespace ‘XXX’ (are you missing an assembly reference? Are the assemblies built using the same .NET Runtime Profile?)
Yup! One assembly was using the .NET 4.0 CLIENT profile and the other the .NET 4 Full profile. Awesome huh!!!
So, if you come across this with one eye bleeding because you stabbed yourself and missing hair, now you know the simple resolution.
Happy Coding!
How to fix Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list
Posted by Brian Seekford in C# on February 9, 2011
If you did what I did, and just picked the default IIS installation options for your Windows 7 box, then you probably get a bunch of fun errors.
This one is if you didn’t install IIS support for asp.net. (WHICH SURPRISE, IS NOT DEFAULT SELECTED)
This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".
The fix is to install ASP.NET support. Easy.
Now, why the error from the title? Why no PageHandlerFactory blah blah blah? Well, .NET didn’t register itself with IIS the way it wants, so you need to rectify that.
That is also easy. Never hard if you have the right tool, it’s finding the right tool that is hard.
Open a Command prompt with Administrative Privileges. (Key, otherwise it doesn’t work).
go to your Framework folder. %WINDIR\Microsoft.NET
Pick the one you are working with, and the right bit type. i.e. 64 if your on 64 bit. Then the right version. I use 4.0
Call aspnet_regiis.exe -i
Voila, your done. Restart IIS and try your page again.
ToObservableCollection for Linq and other purposes
Posted by Brian Seekford in C# on August 3, 2010
Easily convert your Lists and enumerable collections and queries into an observable collection. I use this all the time for simplifying my Linq statements for inline calls.
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Seekford.Extensions
{
/// <summary>
/// Class for helping the conversion of types to observable collections, easier linq coding.
/// </summary>
public static class ObservableExtension
{
/// <summary>
/// Exports the observable collection.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection">The collection.</param>
/// <returns></returns>
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> collection)
{
return new ObservableCollection<T>(collection);
}
/// <summary>
/// Exports the observable collection.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list.</param>
/// <returns></returns>
public static ObservableCollection<T> ToObservableCollection<T>(this List<T> list)
{
return new ObservableCollection<T>(list);
}
}
}
Happy Coding!
How to connect to a WCF service that has a mismatched Identity in code…
Posted by Brian Seekford in .NET Development, C# on February 10, 2010
I had an issue where my client was connecting to a WCF service that was using certificate authentication, but the certificate was for a different dns name.
i.e. server was foobar.comp and the certificate was for foo.foobar.comp.
This presented an issue. Of course, you can change the Identity tag in the configuration file, but I wanted my program to be a little smarter. I grab the error from the WCF service and switch the Identity on the fly. Mainly I did this for a test application in a load balancing scenario due to the load balancer having a different DNS name than the servers. (Obviously!)
Hopefully you have written your own proxy class with a constructor that takes in the configuration name and an EndPointAddress.
You can then use the following style code to create your proxy with the Identity mismatch taken care of.
protected override MyProxyClient CreateConnection(string Server, string altIdentity)
{
if (string.IsNullOrEmpty(altIdentity))
altIdentity = Server;
return new MyProxyClient ("MyServiceBindingConfiguration",
new EndpointAddress(
new Uri(
string.Format("net.tcp://{0}:8090/seekford/2.0/SeekfordService",
Server)
),
EndpointIdentity.CreateDnsIdentity(altIdentity))
);
}
We only are using the configuration for the primary settings, such as binding info. The actual server endpoint is being set on the fly with the altIdentity param being used to allow the server to masquerade with a different certificate.
Happy Coding!
How to use underline text on a label in WPF…
Posted by Brian Seekford in .NET Development, C# on February 9, 2010
It was driving me nuts to do such a simple task as setting the font on the label to Underline in WPF. Well, its not that easy. You can’t just set the TextDecoration on the label since the label is a container control. Yes, you can set text to its Content property, but that just implicitly creates a TextBlock.
So, I wrote a quick helper function to let me set underlined text to any label.
Simple usage:
lblServer.Content = CreateUnderlinedTextBlock( "Your Text Here" );
The actual function
/// Creates the underlined text block.
private TextBlock CreateUnderlinedTextBlock(string text)
{
// Create an underline text decoration. Default is underline.
TextDecoration myUnderline = new TextDecoration();
// Create a linear gradient pen for the text decoration.
Pen myPen = new Pen();
myUnderline.Pen = new Pen(Brushes.Gray, 1);
myUnderline.PenThicknessUnit = TextDecorationUnit.FontRecommended;
// Set the underline decoration to a TextDecorationCollection and add it to the text block.
TextDecorationCollection myCollection = new TextDecorationCollection();
myCollection.Add(myUnderline);
TextBlock blockHead = new TextBlock();
blockHead.TextDecorations = myCollection;
blockHead.Text = text;
return blockHead;
}
I hope this helps!
Happy coding!
How to use SSL transport security using a certificate in your WCF hosted service…
Posted by Brian Seekford in .NET Development, C# on January 26, 2010
So you want to use some channel security in your WCF service. Maybe you even want to guarantee the server your are talking to is who they say they are.
Well, transport security is what you are looking for. It is really quite easy to implement.
Things you will need:
1) A certificate from a trusted signing authority (thawte,godaddy, verisign,etc)
2) A WCF service (duh)
You will need to make changes to the server app.config and the client app.config.
On the Server:
You will need to add this tag to the binding:
<security mode=”Transport”>
<transport clientCredentialType=”None”/>
</security>
We are basically saying here, use transport security but don’t look for a client certificate.
You will also need to create a service behavior.
<behaviors>
<serviceBehaviors>
<behavior name=”MyServiceBehavior”>
<serviceCredentials>
<serviceCertificate findValue=”CN=server.contoso.com” storeLocation=”LocalMachine” storeName=”My” x509FindType=”FindBySubjectDistinguishedName” />
<clientCertificate>
<authentication certificateValidationMode=”None” />
</clientCertificate>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
Notice the serviceCertificate tag. This is the important one. the CN=XXXXX is the portion you need to change to your servers certificate subject.
Now the service is setup. You will need to modify the Client app.config as follows:
You need to change the bindings on the client the same way as the server. Example.
<bindings>
<netTcpBinding>
<binding name=”TCP_Binding” …..>
<security mode=”Transport”>
<transport clientCredentialType=”None” />
</security>
</binding>
</netTcpBinding>
</bindings>
Now you have your service protected with SSL and validation.
Happy coding!
How to read the Distributed Transaction Coordinator settings from C#…
Posted by Brian Seekford in .NET Development, C#, IT Knowledge on January 21, 2010
I wrote a nice helper utility class for reading the settings from the MSDTC in .NET. My WCF service requires distributed transactions, so I want to make sure my server was able detect if it was on. If its not, I throw an error and shutdown.
So, here is the class for your pleasure.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Threading;
namespace SeekfordsNamespace
{
/// <summary>
/// Used to get the DTC settings on a machine
/// </summary>
internal static class DTCUtility
{
/// <summary>
/// Reads the DTC settings.
/// </summary>
/// <returns></returns>
public static DTCSettings ReadDTCSettings()
{
//Lets grab the DTC settings from the registry and then populate our entity
try
{
//we work from the local machine key
var localReg = Registry.LocalMachine;
//set the root dtc key
string rootKey = @"Software\Microsoft\MSDTC";
string securityKey = rootKey +@"\Security";
var dtcReg = localReg.OpenSubKey(rootKey, false);
var securityReg = localReg.OpenSubKey(securityKey, false);
DTCSettings settings = new DTCSettings();
try
{
//is network dtc access even turned on at all
settings.NetworkDTCAccess = ((int)securityReg.GetValue("NetworkDtcAccess", 0)) == 1;
//default to false, then prove it is on.
settings.AllowInbound = false;
settings.AllowOutbound = false;
//check to see if network access is on at all and transactions allowed
if (settings.NetworkDTCAccess &&
(((int)securityReg.GetValue("NetworkDtcAccessTransactions", 0)) == 1))
{
//so we can talk to network, can we allow outbound?
if (settings.NetworkDTCAccess &&
(((int)securityReg.GetValue("NetworkDtcAccessOutbound", 0)) == 1))
{
settings.AllowOutbound = true;
}
//same as above, but inbound connections allowed
if (settings.NetworkDTCAccess &&
(((int)securityReg.GetValue("NetworkDtcAccessInbound", 0)) == 1))
{
settings.AllowInbound = true;
}
}
//grab authentication values
bool allowOnlySecureRPCCalls = (int)dtcReg.GetValue(@"AllowOnlySecureRpcCalls", 0) == 1;
bool fallbackToUnsecuredRPC = (int)dtcReg.GetValue(@"FallbackToUnsecureRPCIfNecessary", 0) == 1;
bool turnOffRpcSecurity = (int)dtcReg.GetValue(@"TurnOffRpcSecurity", 0) == 1;
//process the logic to determine which mode is active.
settings.MutualAuthenticationRequired = (allowOnlySecureRPCCalls && !fallbackToUnsecuredRPC && !turnOffRpcSecurity);
settings.IncomingCallerAuthenticationRequired = (!allowOnlySecureRPCCalls && fallbackToUnsecuredRPC && !turnOffRpcSecurity);
settings.NoAuthenticationRequired = (!allowOnlySecureRPCCalls && !fallbackToUnsecuredRPC && turnOffRpcSecurity);
}
finally
{
try
{
//close but not a failure if there is an error
dtcReg.Close();
securityReg.Close();
}
catch { }
}
return settings ;
}
catch
{
return null;
}
}
}
/// <summary>
/// DTC Settings
/// </summary>
internal class DTCSettings
{
/// <summary>
/// Determines whether DTC on the local computer is allowed to access the network.
/// This setting must be enabled in combination with one of the other settings to
/// enable network DTC transactions.
/// </summary>
/// <value><c>true</c> if [network DTC access]; otherwise, <c>false</c>.</value>
public bool NetworkDTCAccess { get; set; }
/// <summary>
/// Allows a distributed transaction that originates from a remote computer to run on this computer.
/// Default setting: Off
/// </summary>
/// <value><c>true</c> if [allow inbound]; otherwise, <c>false</c>.</value>
public bool AllowInbound { get; set; }
/// <summary>
/// Allows the local computer to initiate a transaction and run it on a remote computer.
/// </summary>
/// <value><c>true</c> if [allow outbound]; otherwise, <c>false</c>.</value>
public bool AllowOutbound { get; set; }
/// <summary>
/// Adds support for mutual authentication in future versions and is the highest secured
/// communication mode. In the current versions of Windows and Windows Server, it is
/// functionally equivalent to the Incoming Caller Authentication Required setting.
/// This is the recommended transaction mode for clients running Windows XP SP2 and
/// servers running a member of the Windows Server 2003 family.
/// </summary>
/// <value>
/// <c>true</c> if [mutual authentication required]; otherwise, <c>false</c>.
/// </value>
public bool MutualAuthenticationRequired { get; set; }
/// <summary>
/// Requires the local DTC to communicate with a remote DTC using only encrypted messages
/// and mutual authentication. This setting is recommended for servers running Windows Server
/// 2003 that are operating in a cluster.
/// Only Windows Server 2003 and Windows XP SP2 support this feature, so you should only use
/// this if you know that the DTC on the remote computer runs either the Windows Server 2003
/// or Windows XP SP2 operating system.
/// </summary>
/// <value>
/// <c>true</c> if [incoming caller authentication required]; otherwise, <c>false</c>.
/// </value>
public bool IncomingCallerAuthenticationRequired { get; set; }
/// <summary>
/// Provides system compatibility between previous versions of the Windows operating system.
/// When enabled, communication on the network between DTCs can fall back to a non-authentication
/// or non-encrypted communication if a secure communication channel cannot be established.
/// This setting should be used if the DTC on the remote computer runs a Windows 2000 operating system
/// or a Windows XP operating system earlier than SP2. This setting is also useful when the DTCs
/// that are involved are located on computers that are in domains that do not have an established
/// trust relationship or if the computers are part of a Windows workgroup.
/// </summary>
/// <value>
/// <c>true</c> if [no authentication required]; otherwise, <c>false</c>.
/// </value>
public bool NoAuthenticationRequired { get; set; }
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
StringBuilder state = new StringBuilder();
state.AppendFormat("NetworkDTCAccess: {0}\r\n", NetworkDTCAccess);
state.AppendFormat("AllowInbound: {0}\r\n", AllowInbound);
state.AppendFormat("AllowOutbound: {0}\r\n", AllowOutbound);
state.AppendFormat("MutualAuthenticationRequired: {0}\r\n", MutualAuthenticationRequired);
state.AppendFormat("IncomingCallerAuthenticationRequired: {0}\r\n", IncomingCallerAuthenticationRequired);
state.AppendFormat("NoAuthenticationRequired: {0}\r\n", NoAuthenticationRequired);
return state.ToString();
}
}
}
Happy coding!
Copy one List to another List in one line of code using Linq and lambdas!
Posted by Brian Seekford in .NET Development, C# on January 18, 2010
I find it pretty useful to try and incorporate time and code line saving features where it is beneficial to my productivity and the code readability. One thing I need to do often is convert lists from one type to another.
Here is a one liner to convert an object with a VendorID property on it into a List of integers.
var list = (List<VendorInvoice>)Context.Items["VendorInvoices"];
List<int> intList = new List<int>();
list.ForEach(l => intList.Add(l.VendorInvoiceID));
See the Foreach processes each element of the List using the Lambda. The l variable (you can name it something more useful) is then fed to the function body which is simply an Add to the other list. More complex operations are easily accomplished using the same pattern.
Less code, easy to read.
Enterprise Library Caching Block. Contains or to not Contains, that is the question!
Posted by Brian Seekford in C# on January 15, 2010
I am working on a project where a few developers decided to use the Caching block in an interesting way.
The code I saw was basically:
if(cache.Contains[MyKey])
return cache.GetData(MyKey);
fill cache code....
Contains….hmmm. Sounds innocent, right? You do it with a Dictionary.
This code will work, granted not optimally, but works OK if you always use never-expiring caching. i.e. the default Add. (Of course the scavenger could run between the Contain and GetData and you get screwed) If however you decide to actually use caching with AbsoluteTimeout or SlidingTimeout or other cache timeouts; you get false positives.
Why? Well, the Contains does exactly as you might expect, it see if the key is valid. What it doesn’t do though, is check to see if the cached value is actually expired. Since the scavenger runs only every XX seconds, it is possible your key was expired.
So you do the GetData call on the cache and you get back a null. Gee, why a null? Well, if the cache item was expired, which the GetData enforces before returning, then you get back a null.
So Brian, how should I use the the caching block’s cache manager?
Well, fellow reader, you should use the following. Amazingly simple, eh?
var myValue = cache.GetData(MyKey);
if(myValue != null)
return myValue;
Do fill and add code here............
A lot easier than you expected, and it even works every time. Now, of course you will need to incorporate your own locking strategy around this if you are thread re-entrant.
And yes….GetData is the same as the indexer. cache[MyKey] = cache.GetData[MyKey] Use whatever way you prefer.
Happy Coding!