Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

2017-04-19

Get time for given country

This code gets the first time zone for a country (meaning it probably won't work if your country has more than one), and calculates the date/time given the UTC date/time.

The method is an extension to the DateTime type, meaning you can use it by typing .AsLocalTimeForGivenCountryFromUtc(countryCode) after a variable or function returning that type. The countryCode parameter is a string, and must be a two-letter ISO 3166-1 country code.

You need to import John Skeets NodaTime library from NuGet.

Code:
using NodaTime.TimeZones;
using System;
using System.Linq;

namespace MyNameSpace
{

    public static class DateTimeExtension
    {

        public static DateTime AsLocalTimeForGivenCountryFromUtc(this DateTime utcDateTime, string countryCode)
        {
            //no matter what tz info is on the date, assume it is UTC
            var dte = new DateTime(utcDateTime.Year, utcDateTime.Month, utcDateTime.Day, utcDateTime.Hour, utcDateTime.Minute, utcDateTime.Second, DateTimeKind.Utc);
            var tzMapping = TzdbDateTimeZoneSource.Default.WindowsMapping.MapZones.FirstOrDefault(t => t.Territory == countryCode); //NodaTime
            var tz = TimeZoneInfo.FindSystemTimeZoneById(tzMapping.WindowsId);
            return TimeZoneInfo.ConvertTimeFromUtc(dte, tz);
        }
    }
}

2010-12-16

SoapExceptionWrapper

I wrote this code quite a while ago, but since it’s quite reusable (and very simple) here it is:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Services.Protocols;
using System.Xml;

namespace SupportLibrary.ExceptionHandling
{

    /// <summary>
    /// Wrapper Class for Soap Exception from JBoss.
    /// Parses the XML in the Detail XML Node, exposing StatusCode and StatusDescription as properties.
    /// </summary>
    /// <example>
    /// int errorCode = -1;
    /// try
    /// {
    ///     WebService.DoSomething();
    /// }
    /// catch(SoapException soapex)
    /// {
    ///     SoapExceptionWrapper wrapper = new SoapExceptionWrapper(soapex);
    ///     int errorCode = wrapper.StatusCode;
    ///     string errorDescription = wrapper.StatusDescription;
    /// }  
    /// </example>
    public class SoapExceptionWrapper
    {
        private SoapException _ex;

        /// <summary>
        /// The XmlNode containing the Detail information about the error.
        /// </summary>
        public XmlNode DetailXml
        {
            get
            {
                return _ex.Detail.FirstChild;
            }
        }

        /// <summary>
        /// Status code from SoapException Detail XML.
        /// </summary>
        public int StatusCode
        {
            get
            {
                string codeStr = "-1";
                if(DetailXml != null && DetailXml.ChildNodes.Count > 0)
                    codeStr = DetailXml.SelectSingleNode("StatusCode").InnerText;
                int codeInt = -1;
                int.TryParse(codeStr, out codeInt);
                return codeInt;
            }
        }

        /// <summary>
        /// Status description from SoapException Detail XML.
        /// </summary>
        public string StatusDescription
        {
            get
            {
                if (DetailXml != null && DetailXml.ChildNodes.Count > 0 && DetailXml.SelectSingleNode("StatusDescription") != null && DetailXml.SelectSingleNode("StatusDescription").InnerText != "")
                {
                    return DetailXml.SelectSingleNode("StatusDescription").InnerText;
                }
                return _ex.Message;
            }
        }

        /// <summary>
        /// Constructor using default values.
        /// </summary>
        /// <param name="soapex"></param>
        public SoapExceptionWrapper(SoapException soapex)
        {
            _ex = soapex;
        }
    }
}

2010-04-13

Syncroniziong files with FreeCommander and Compare It!

Up until now I have mostly used SourceSafe and TFS for comparing files. Recently I had a situation where I had to do a so called “Baseless Merge” in TFS. This worked quite well for most files. Then there were some files that were not as easy to merge. So a manual merge was required. Not being quite happy with the file comparing offered by VS, I searched and found a nice option:

  • Use FreeCommander to find all files that have differences.
  • Use Compare It! to compare and syncronize the contents of files.

To be able to use the “Compare left and right sides” option in FreeCommander, you need to go into Extras –> Settings in FreeCommander, in the Programs section, and set “Compare files” to “C:\Program Files\Compare It!\wincmp3.exe” assuming that’s where Compare It! is installed.

FreeCommander may be found at http://www.freecommander.com.

Compare It! may be found at http://www.grigsoft.com.

I think using these two great tools together is synergy in action!

2010-02-16

Experiences on upgrading EPiServer 4.51 to 4.62B part 2

Ok, so the upgrade has been done, but will the project compile?

Sadly the answer is no.

I got the exact same problems described here: http://world.episerver.com/templates/forum/pages/thread.aspx?id=19575&epslanguage=en. It took some time for me to understand the answer to the part they did give an answer to. They didn’t answer the second question at all.

Problem 1: WsrpHelper doesn’t exist any more

My solution, which saves me from having to go through 8-10 places and correct the code, was to create a new class inside the WsrpPortal.aspx.cs file:

class WsrpHelper
{
    public static IConsumerEnvironment ConsumerEnvironment
    {
        get { return ElektroPost.Wsrp.Consumer.ConsumerContext.ConsumerEnvironment; }
        set { ElektroPost.Wsrp.Consumer.ConsumerContext.ConsumerEnvironment = value; }
    }

    public static void EnsureConsumerEnvironment()
    {
        if (ElektroPost.Wsrp.Consumer.ConsumerContext.ConsumerEnvironment == null)
        {
            ElektroPost.Wsrp.Consumer.ConsumerContext.ConsumerEnvironment = ConsumerFactory.ConsumerEnvironmentInstance();
        }
    }
}

Problem 2: LanguageManager.GetContextLanguage() is obsolete

It says in the error message that you should use LanguageContext.Current as a replacement, but that would create a type conversion exception.

I am guessing that you can to use LanguageContext.Current.CurrentUILanguageID as a replacement for GetContextLanguage() (please do correct me if I’m wrong).

DISCLAIMER:
I haven’t been able to test my solution, since the webs I am working on don’t actually use the portal framework. My code compiles now, so the web is up and running, and I am happy for the time being. If anyone finds any flaw in my solutions please don’t hesistate to leave a comment.

2009-11-06

Generic Object Factory

The following class is a generic object factory. It is used for creating instances of objects from configured or otherwise provided strings.

The “User Guide” is in the comments.

/// <summary>
/// Generic object factory that creates instances of objects from configured or otherwise provided strings.
/// </summary>
public class ObjectFactory
{
    /// <summary>
    /// Creates an instance of a class from a string "[namespace.[...].className], [component without filname extension],[Version],[Culture],[…]".
    /// </summary>
    /// <typeparam name="T">The type to create.</typeparam>
    /// <param name="configuredClassAndAssembly">Format: [namespace.[...].className], [component without filname extension]</param>
    /// <returns>An object of type T.</returns>
    /// <remarks>This method uses generics!</remarks>
    public static T CreateClassInstance<T>(string configuredClassAndAssembly)
    {
        //Get type to instanciate
        Type tp = Type.GetType(configuredClassAndAssembly, true);

        //load assembly
        Assembly assembly = Assembly.GetAssembly(tp);

        //create class instance
        T instance = (T)assembly.CreateInstance(tp.FullName);

        //return instance
        return instance;
    }
}

I am using it to create instances of objects that implement certain interfaces, so that I can swap the implementation, or even mock it, by changing the configuration.

The string that tells which object to create uses the format of the Type.GetType(string) string.

Some error handling should be added.

2009-09-11

Getting paths for an application

I am creating an application that needs to load an assembly dynamically from the bin-folder of the application. This is not as straight forward as one might think.

So I tried the following:

string s1 = Directory.GetCurrentDirectory();
string s2 = Environment.CurrentDirectory;
string s3 = Assembly.GetExecutingAssembly().Location;
string s4 = new DirectoryInfo("~/bin").FullName;
string s5 = new DirectoryInfo("/bin").FullName;
string s6 = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string s7 = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string s8 = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

Results:

s1 = s2 = “C:\Windows\system32”

s3 = "C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\Temporary ASP.NET Files\\root\\101551d3\\93890f66\\assembly\\dl3\\f2069ce7\\fe4f0aea_dc32ca01\\MyAssemblyName.DLL"

s4 = "C:\\WINDOWS\\system32\\~\\bin"

s5 = "C:\\bin"

s6 = "C:\\Documents and Settings\\MyMachineName\\ASPNET\\Local Settings\\Application Data" (getting desperate, I know)

s7 = "C:\\Documents and Settings\\MyMachineName\\ASPNET\\Application Data"

Finally found one that worked:

s8 = “file:\\C:\\DevProjects\\…\\MyAppDir\\bin”

2009-04-27

Using TryParse

I just figured out a way to use int.TryParse in an if-sentence.

string myInputString = myTextBox.Text;
int i = –1;
if(int.TryParse(myInputString, out i) && i > 0)
{

//do cool stuff

}

This only works with the “&&” operator. If the parse fails, the second part that uses the “out” parameter from the parse, will not be run.

2009-04-20

SendHttpRequest

I made a little console application using .NET 1.1, that sends a request to an address given as parameter. It is to be used to simulate traffic on a web site. Probably could use some refinement of the code (just consider it my alpha, and that there will be no beta, RTM, etc.).

using System;
using System.Web;
using System.IO;
using System.Net;

namespace SendHttpRequest
{
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class EntryPoint
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            if(args.Length > 0)
            {
                string url = args[0];

                Uri uri = null;
                try
                {
                    uri = new Uri(url);
                }
                catch
                {
                    Console.WriteLine("Invalid URL. No request sent.");
                    return;
                }

                WebRequest request = WebRequest.Create(uri);
                request.Method = "GET";

                WebResponse response = null;
                try
                {
                    response = request.GetResponse();
                    StreamReader rdr = new StreamReader(response.GetResponseStream());
                    string content = rdr.ReadToEnd();
                    Console.WriteLine(content);
                }
                catch (Exception ex)
                {   
                    Console.WriteLine(ex.Message);
                    return;
                }
            }
            else
            {
                Console.WriteLine("Usage: SendHttpRequest {url}");
            }
        }
    }
}

2009-01-16

Mapping Cargos to Objects returned from a Web Service using Reflection

Background:

When working with webservices, we wanted to use a common library of cargo objects that would be used for sending data between the tiers of the application. The Middleware tier has all the web references, and also has methods that encapsulate the web references objects, essentially wrapping them to common cargo objects. After all, we would not like to have dependencies to types that are defined in the auto-generated web service proxies.

One way:

One way of creating the cargo objects is to copy the code for the classes from the Reference.cs file into the common cargo objects assembly. Then you could wrap the objects from the web service dependent object to the common cargo objects which would then be passed to the application tier.

Problem:

It's a lot of work to type all the code for wrapping the objects...

Solution:

Since the cargo objects have the same properties as the web service proxy objects with the same names, it is possible to do the wrapping by using reflection, for instance using a method like this:

private void wrapToCargo<T,U>(T source, U cargo)
{
//Gets all properties from the source object...
PropertyInfo[] props = source.GetType().GetProperties();
//Loops the properties...
for(int i = 0; i < props.Length; i++)
{
//Checks if a property with the same name is present on both the source and the cargo,
// and if the property is writeable.
string name = props[i].Name;
if (source.GetType().GetProperty(name) != null && cargo.GetType().GetProperty(name) != null && cargo.GetType().GetProperty(name).CanWrite)
{
//If so, set value of the cargo property to the value of the source property.
cargo.GetType().GetProperty(props[i].Name).SetValue(cargo, source.GetType().GetProperty(props[i].Name).GetValue(source, null), null);
}
}
}


Alas, this generic way of wrapping cargos comes at a cost. I would suggest that one should wrap from the target (loop through properties of the target, then match with properties belonging to the source object) in stead of the source as shown above, because you will have more control of what fields should be mapped.

2008-07-16

SandcastleGUI

I started using Sandcastle just a few days ago, and it was not very userfriendly, since it is a collection of command line utilities. Hence, I started looking for a GUI for Sandcastle, and found one at: http://www.inchl.nl/SandcastleGUI .

It's quite easy to use, and I was quite happy with it. I then started to create a web with documentation for one of my projects, and ran into some problems. It seems Sandcastle has problems with some long names, resulting in linebreaks in a file called "filetitles.js". This results in a javascript error saying something about unterminated string constants.

Thats why I created a small utility for fixing that file: FixFiletitlesJs.exe. Here's the code for my little utility (Console application):

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace FixFileTitlesJs
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 0 || (args.Length > 0 && args[0] == "?"))
            {
                Console.WriteLine("USAGE: fixfiletitlesjs filename [Y | N]");
                return;
            }

            string filename = args[0];

            //creates a new filname by replacing ".js" at the end of the filename with ".bak"
            string backupFilename = Regex.Replace(filename, @"\.js$", ".bak");
            try
            {
                //create a backup file
                FileInfo fi = new FileInfo(filename);
                fi.MoveTo(backupFilename);
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("File not found.");
                Console.ReadLine();
                return;
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("An exception was thrown while accessing the file: {0}", ex.Message));
                Console.ReadLine();
                return;
            }

            StreamWriter sw = null;
            try
            {
                sw = File.CreateText(filename);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("An exception was thrown while accessing the file: {0}", ex.Message));
                Console.ReadLine();
                return;
            }

            StreamReader sr = null;
            try
            {
                sr = File.OpenText(backupFilename);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("An exception was thrown while accessing the file: {0}", ex.Message));
                Console.ReadLine();
                return;
            }

            int i = 0,j = 0, k = 0;
            while (!sr.EndOfStream)
            {
                string line = sr.ReadLine();
                j++;
                Regex rx = new Regex("\",$");
                while (!sr.EndOfStream && !rx.IsMatch(line) && i > 0)
                {
                    line += sr.ReadLine();
                    j++;
                    k++;
                }
                sw.WriteLine(line);
                i++;
            }
            sw.Close();
            sr.Close();

            //write result
            Console.WriteLine(string.Format("Original file renamed to: {0}", backupFilename));
            Console.WriteLine(string.Format("New file created with original name: {0}", filename));
            Console.WriteLine(string.Format("Number of lines read from source: {0}", j));
            Console.WriteLine(string.Format("Number of lines written to destination: {0}", i));
            Console.WriteLine(string.Format("Number of concatenations of lines done: {0}", k));
            Console.WriteLine();

            string reply = string.Empty;

            if (args.Length >= 2 && !string.IsNullOrEmpty(args[1]))
            {
                reply = args[1];
            }

            while (reply.ToLower() != "y" && reply.ToLower() != "n")
            {
                if (reply != string.Empty) Console.WriteLine("You must answer Y or N.");
                Console.Write("Would you like to delete the backup of the original file (y/n)?");
                reply = Console.ReadLine();
            }

            if (reply.ToLower() == "y") File.Delete(backupFilename);
        }
    }
}