Trikks

The digital adventures of Eric Herlitz

Archive for the ‘.net’ Category

Mapping Dictionary to Typed object using c#

Posted by trikks on December 31, 2012

There are some good frameworks that may help you mapping dictionaries and alike to typed objects but in some cases you simply want something simpler or custom for that matter.

The most important thing here is to transfer our dictionary to a typed object.

Example dictionary

Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("Id", "1");
dictionary.Add("Name", "Trikks");
dictionary.Add("EMail", "info@example.com");

Example class

public class ExampleClass
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string EMail { get; set; }
}

Method

private static T DictionaryToObject<T>(IDictionary<string, string> dict) where T : new()
{
    var t = new T();
    PropertyInfo[] properties = t.GetType().GetProperties();
 
    foreach (PropertyInfo property in properties)
    {
        if (!dict.Any(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)))
            continue;
 
        KeyValuePair<string, string> item = dict.First(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase));
 
        // Find which property type (int, string, double? etc) the CURRENT property is...
        Type tPropertyType = t.GetType().GetProperty(property.Name).PropertyType;
 
        // Fix nullables...
        Type newT = Nullable.GetUnderlyingType(tPropertyType) ?? tPropertyType;
 
        // ...and change the type
        object newA = Convert.ChangeType(item.Value, newT);
        t.GetType().GetProperty(property.Name).SetValue(t, newA, null);
    }
    return t;
}

Full example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.Add("Id", "1");
            dictionary.Add("Name", "Trikks");
            dictionary.Add("EMail", "info@example.com");
 
            ExampleClass example = DictionaryToObject<ExampleClass>(dictionary);
        }
 
        private static T DictionaryToObject<T>(IDictionary<string, string> dict) where T : new()
        {
            var t = new T();
            PropertyInfo[] properties = t.GetType().GetProperties();
 
            foreach (PropertyInfo property in properties)
            {
                if (!dict.Any(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)))
                    continue;
 
                KeyValuePair<string, string> item = dict.First(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase));
 
                // Find which property type (int, string, double? etc) the CURRENT property is...
                Type tPropertyType = t.GetType().GetProperty(property.Name).PropertyType;
 
                // Fix nullables...
                Type newT = Nullable.GetUnderlyingType(tPropertyType) ?? tPropertyType;
 
                // ...and change the type
                object newA = Convert.ChangeType(item.Value, newT);
                t.GetType().GetProperty(property.Name).SetValue(t, newA, null);
            }
            return t;
        }
    }
 
    public class ExampleClass
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string EMail { get; set; }
    }
}

Thats it, happy coding!

Posted in C# | Leave a Comment »

The undocumented MediaSettings class from Microsoft.Rtc

Posted by trikks on December 16, 2012

This is a media settings object used by Lync servers among others to handle settings for real time clients (rtc).

Namespace

Microsoft.Rtc.Management.WritableConfig.Settings.Media

The MediaSettings object

using Microsoft.Rtc.Management.WritableConfig;
using System;
using System.Xml.Linq;
 
namespace Microsoft.Rtc.Management.WritableConfig.Settings.Media
{
    public sealed class MediaSettings : WritableConfigDocument, ICloneable
    {
        public MediaSettings();
 
        public bool EnableQoS { get; set; }
        public bool EnableSiren { get; set; }
        public EncryptionLevel EncryptionLevel { get; set; }
        public MaxVideoRateAllowed MaxVideoRateAllowed { get; set; }
        public static Microsoft.Rtc.Management.Core.SchemaId StaticSchemaId { get; }
 
        public static MediaSettings Create(XElement element);
    }
}

EncryptionLevel property class

using System;
 
namespace Microsoft.Rtc.Management.WritableConfig.Settings.Media
{
    public enum EncryptionLevel
    {
        SupportEncryption =  0,
        RequireEncryption = 1,
        DoNotSupportEncryption = 2,
    }
}

MaxVideoRateAllowed property class

using System;
 
namespace Microsoft.Rtc.Management.WritableConfig.Settings.Media
{
    public enum MaxVideoRateAllowed
    {
        CIF250K =  0,
        VGA600K = 1,
        Hd720p15M = 2,
    }
}

Posted in C#, Lync | Tagged: , | Leave a Comment »

How to handle the error “Handler “PageHandlerFactory-Integrated” has a bad module “ManagedPipelineHandler” in its module list”

Posted by trikks on September 8, 2012

I did port some of my development environments to a new virtual machine with a brand new 2008 R2 Server and a Visual Studio 2012. Everything seemed fine until I tried to load one of my Umbraco labs.

The error “Handler “PageHandlerFactory-Integrated” has a bad module “ManagedPipelineHandler” in its module list” showed up.

This is quite simple to resolve for Umbraco,

  • ensure your application pool runs in .net 4 classic mode in IIS
  • run the aspnet_regiis.exe -i command, to run the aspnet_regiis command
    • navigate to C:\Windows\Microsoft.NET\Framework\v4.0.30319 (or whatever .net 4 framework version you have)
    • type aspnet_regiis.exe -i and press enter

Thats it

 

 

Posted in IIS, Umbraco | Tagged: , , | Leave a Comment »

Creating a (very) random password generator in c#

Posted by trikks on April 24, 2012

It’s not as hard as it seems. There are some things to think of but I’d like to say that this snippet will solve the most common issues of password generation. I also see a lot of questions on the net where the .net Random() doesn’t generate random numbers as it should. Well it does, the problem is that most peeps implement it inside some method which is bad. Declare it OUTSIDE the methods to get random working as it should, alright…

This little baby generates passwords like this
Stronger passwords (12 characters)
$te++3t0hWqa
*8ujWeqLno)b
:gX0zZb47Z)X

Simpler passwords (12 characters)
AcpO8g8UOK4R
oQbLmN2bodCP
CfORDnaNvwC2

Snippet

/// <summary>
/// Random declaration must be done outside the method to actually generate random numbers
/// </summary>
private static readonly Random Random = new Random();

/// <summary>
/// Generate passwords
/// </summary>
/// <param name="passwordLength"></param>
/// <param name="strongPassword"> </param>
/// <returns></returns>
private static string PasswordGenerator(int passwordLength, bool strongPassword)
{
    int seed = Random.Next(1, int.MaxValue);
    //const string allowedChars = "ABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
    const string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
    const string specialCharacters = @"!#$%&'()*+,-./:;<=>?@[\]_";

    var chars = new char[passwordLength];
    var rd = new Random(seed);

    for (var i = 0 ; i < passwordLength; i++)
    {
        // If we are to use special characters
        if (strongPassword && i % Random.Next(3, passwordLength) == 0 )
        {
            chars[i] = specialCharacters[rd.Next(0 , specialCharacters.Length)];
        }
        else
        {
            chars[i] = allowedChars[rd.Next(0 , allowedChars.Length)];
        }
    }

    return new string(chars);
}

Cheers! :)

Posted in C# | 2 Comments »

Getting the previous and next record from list using linq

Posted by trikks on December 1, 2011

Generic lists, you just gotta love them, especially if using linq!

Well to the point. Lets say you got a list with Guid’s of which you know one and based on that knowledge want to get either the one before or after.

Guid a = new Guid("709DBFA9-88B3-4518-A32F-C21B6AAE2917");
Guid b = new Guid("B9956FC6-FD9B-4F52-B96E-C1D0C29E1E55");
Guid c = new Guid("BFB9054A-AB18-4349-BCB4-19979D3486BB"); // <-- you know this one, the c guid
Guid d = new Guid("1A8D6CAB-FD42-4517-A0EA-08D3F64DCD69");
Guid e = new Guid("02A8CA8A-5BC8-41BE-8AB8-332EF0B5407B");
List<Guid> guidList = new List<Guid> {a, b, c, d, e};

Solution

Oh wow, now I need to start building indexes pushing and popping yada yada. Well no, a better way to solve this is by using linq.
Getting the record after the one you search for

private static Guid GetNext(IEnumerable<Guid> guidList, Guid current)
{
    return guidList.SkipWhile(i => !x.Equals(current)).Skip(1).First();
}
And to get the record before...
private static Guid GetPrevious(IEnumerable<Guid> guidList, Guid current)
{
    return guidList.TakeWhile(i => !x.Equals(current)).Last();
}

Using Generics (you should)

Whilst separated methods can be neat sometimes a lot of time and engineering can be saved using some generics instead, this means you can dynamically change the type of list you want to search for a certain record.

In example

private static T GetNext<T>(IEnumerable<T> list, T current)
{
    try
    {
        return list.SkipWhile(x => !x.Equals(current)).Skip(1).First();
    }
    catch
    {
        return default(T);
    }
}

private static T GetPrevious<T>(IEnumerable<T> list, T current)
{
    try
    {
        return list.TakeWhile(x => !x.Equals(current)).Last();
    }
    catch
    {
        return default(T);
    }
}

Some usage

String example

string f = "first";
string g = "second";
string h = "third";
string i = "fourth";
string j = "fifth";
List<string> stringList = new List<string>{f,g,h,i,j};

var prev = GetPrevious<string>(stringList, j);
var next = GetNext<string>(stringList, j);

Guid example

Guid a = new Guid("709DBFA9-88B3-4518-A32F-C21B6AAE2917");
Guid b = new Guid("B9956FC6-FD9B-4F52-B96E-C1D0C29E1E55");
Guid c = new Guid("BFB9054A-AB18-4349-BCB4-19979D3486BB");
Guid d = new Guid("1A8D6CAB-FD42-4517-A0EA-08D3F64DCD69");
Guid e = new Guid("02A8CA8A-5BC8-41BE-8AB8-332EF0B5407B");
List<Guid> guidList = new List<Guid> {a, b, c, d, e};

var prev = GetPrevious<Guid>(guidList, c);
var next = GetNext<Guid>(guidList, c);

-

Cheers!

Posted in C# | 2 Comments »

Failure adding assembly to the cache: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Posted by trikks on November 19, 2011

So you got the “Failure adding assembly to the cache: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.” when running Gacutil

Well good news is that this is easy to fix, you are simply running an old version of gacutil

open a terminal en enter gacutil, maybe something like
PS C:\Windows\Microsoft.NET\Framework\v1.1.4322> .\gacutil.exe
Microsoft (R) .NET Global Assembly Cache Utility. Version 3.5.30729.1
Copyright (c) Microsoft Corporation. All rights reserved.
Check the version

Now this option may vary a bit, but in my case the gacutil I should use was in this folder

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\x64

PS C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\x64> gacutil
Microsoft (R) .NET Global Assembly Cache Utility. Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.

So, by simply switching to this version my problems are solved!

Posted in .net | 10 Comments »

Compress a file using GZip and convert it to Base64 – and back – using C#

Posted by trikks on November 3, 2011

Sometimes you want to store a file in a database or even transfer stuff over the Internet through different protocols, maybe even to other platforms. In many of these cases the traditional methods simply wont do.

Storing files in databases is usually made by sending the file as a blob to the database and it usually works out pretty good to, but in some cases you simply want a different structure. I often tend to end up in projects with several platforms and languages, this means XML or similar languages like JSON. Anyway binary data is out, you need a different way to transfer or store files.

When it comes to files I recommend using GZip compression which is shipped as a standard with .NET. If you want more simple compression you should be looking at gzdeflate and gzinflate.

If you only want the source project download it here  
http://www.trikks.com/download.php?id=CompressConsole.zip

Compressing a file

string fileName = @"c:\test.pdf";
byte[] file = File.ReadAllBytes(fileName);

// Compress
byte[] compress = Compress(file);
public static byte[] Compress(byte[] data)
{
    using (var compressedStream = new MemoryStream())
    using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
    {
        zipStream.Write(data, 0, data.Length);
        zipStream.Close();
        return compressedStream.ToArray();
    }
}

Encode the byte array

string encoded = base64_encode(compress);
public string base64_encode(byte[] data)
{
	if (data == null)
		throw new ArgumentNullException("data");
	return Convert.ToBase64String(data);
}

The contents of “encoded” is your file but compressed and base64 encoded. You can take this string and send it through any protocol allowing strings.

If we print the encoded string it looks something like this

Decode and Decompress

// Decode and decompress
byte[] decoded = base64_decode(encoded);
byte[] decompressed = Decompress(decoded);
File.WriteAllBytes(@"c:\out.pdf", decompressed);
public static byte[] base64_decode(string encodedData)
{
    byte[] encodedDataAsBytes = Convert.FromBase64String(encodedData);
    return encodedDataAsBytes;
}
public static byte[] Decompress(byte[] data)
{
    using (var compressedStream = new MemoryStream(data))
    using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
    using (var resultStream = new MemoryStream())
    {
        var buffer = new byte[4096];
        int read;

        while ((read = zipStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            resultStream.Write(buffer, 0, read);
        }

        return resultStream.ToArray();
    }
}

Now that wasn’t hard was it :)

You can download a visual studio project here 
http://www.trikks.com/download.php?id=CompressConsole.zip

Posted in C# | Leave a Comment »

The type ” is ambiguous: it could come from assembly ” or from assembly ”. Please specify the assembly explicitly in the type name.

Posted by trikks on August 26, 2011

Ah the good old error

You most likely seen it looking something like this

The type ‘Prometer.Objects.AnalysisEngineData’ is ambiguous: it could come from assembly ‘C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\aa63ddac\c47315b5\App_Code.8t9ff09n.DLL’ or from assembly ‘C:\Projects\Webbprojects\Prometer\bin\Prometer.DLL’. Please specify the assembly explicitly in the type name.

In short

Now there are quite a few tricks out there that suggest how to solve this. None of them shows to be correct unless you are really lucky. In general this error depend on a structural error in your Visual Studio project. That means this can be solved by either moving the file or by changing the “Build Action” from Compile to Content.

In reasonable depth

This occur when an aspx page tries to reach a class (like an objectdatasource) and tries to (or actually do) compile the class. But since it’s already compiled everything will fail.

Now in the case shown above I had put my class libraries in the App_Code directory and set the “Build Action” to “Compile” on each library. This solution works but will fail if an aspx-page tries to reach a library since it will build it’s own version of the library (stupid). Now I can solve this by leaving my files in the App_Code folder just setting the ”Build Action” to “Content” instead. But other things might fail doing that.

The best option is to move the class libraries to a separate directory, in example “/Classes”. If so done remember to set the ”Build Action” to “Compile”.

If in App_Code

If in /Classes

So that should be it, please not that there are no work around for this. The structure has to be correct otherwise it simply wont work.
Good luck!

Posted in IIS | 6 Comments »

Programmatically check if an assembly is loaded in GAC with C#

Posted by trikks on July 13, 2011

Maybe you are writing an installer of some kind or are depending on some external assemblies to have your .net program or website to work, I often do. So with no further ado. Here is a small program which will lead you to success in these matters *fanfare*.

Example, running in console

 

Download VS project

Here

Source Code

using System;
using System.Runtime.InteropServices;

namespace ConsoleTestAssembly
{
    class Program
    {
        static void Main()
        {
            string response;

            var exist = AssemblyExist("Camelot.SharePointConnector", out response);
            Console.WriteLine(string.Concat(exist, Environment.NewLine, response, Environment.NewLine));

            exist = AssemblyExist("Camelot.SharePointIntegration", out response);
            Console.WriteLine(string.Concat(exist, Environment.NewLine, response, Environment.NewLine));

            exist = AssemblyExist("Camelot.NoExisting", out response);
            Console.WriteLine(string.Concat(exist, Environment.NewLine, response, Environment.NewLine));

            Console.ReadKey();
        }

        public static bool AssemblyExist(string assemblyname, out string response)
        {
            try
            {
                response = QueryAssemblyInfo(assemblyname);
                return true;
            }
            catch (System.IO.FileNotFoundException e)
            {
                response = e.Message;
                return false;
            }
        }

        // If assemblyName is not fully qualified, a random matching may be 
        public static String QueryAssemblyInfo(string assemblyName)
        {
            var assembyInfo = new AssemblyInfo {cchBuf = 512};
            assembyInfo.currentAssemblyPath = new String('', assembyInfo.cchBuf);

            IAssemblyCache assemblyCache;

            // Get IAssemblyCache pointer
            var hr = GacApi.CreateAssemblyCache(out assemblyCache, 0);
            if (hr == IntPtr.Zero)
            {
                hr = assemblyCache.QueryAssemblyInfo(1, assemblyName, ref assembyInfo);
                if (hr != IntPtr.Zero)
                {
                    Marshal.ThrowExceptionForHR(hr.ToInt32());
                }
            }
            else
            {
                Marshal.ThrowExceptionForHR(hr.ToInt32());
            }
            return assembyInfo.currentAssemblyPath;
        }
    }

    internal class GacApi
    {
        [DllImport("fusion.dll")]
        internal static extern IntPtr CreateAssemblyCache(
            out IAssemblyCache ppAsmCache, int reserved);
    }

    // GAC Interfaces - IAssemblyCache. As a sample, non used vtable entries 
    [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
    Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae")]
    internal interface IAssemblyCache
    {
        int Dummy1();
        [PreserveSig()]
        IntPtr QueryAssemblyInfo(
            int flags,
            [MarshalAs(UnmanagedType.LPWStr)]
            String assemblyName,
            ref AssemblyInfo assemblyInfo);

        int Dummy2();
        int Dummy3();
        int Dummy4();
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct AssemblyInfo
    {
        public int cbAssemblyInfo;
        public int assemblyFlags;
        public long assemblySizeInKB;

        [MarshalAs(UnmanagedType.LPWStr)]
        public String currentAssemblyPath;

        public int cchBuf;
    }

}

Thats it.

Posted in .net, C# | Tagged: | 3 Comments »

 
Follow

Get every new post delivered to your Inbox.