Lars Holm Jensen's Code Blog

Just another WordPress codeblog on C#, Silverlight and all things .NET

[NOT CODE] How to use Nordea netbank with Adblock Plus for android

without comments

Just add “nordea.com, danid.dk” in the “bypass proxy for” text field in the proxy settings.

Tilføj “nordea.com, danid.dk” i “bypass proxy for” i proxyindstillingerne.

Written by larsholm

August 18th, 2013 at 7:26 pm

[Danish post] DMR webservice fra .NET / C#

with 2 comments

Det kan være udfordrende at forbinde til DMRs webservice for sekundære erhvervsmæssige brugere fra .NET / C# med WCF. Vejledningerne på interessent-sitet er ikke særligt brugbare.

Derfor har jeg valgt at lægge et lille testprojekt ud, som kræver minimale tilretninger. Du skal bruge et gyldigt certifikat fra SKAT (som også er aktiveret hos SKAT) og du skal bruge service/server-certifikatet, som ligger på interessent-sitet i Dokumenter->Produktionscertifikater (dmr_virksomhedscertifikat_prod).

Efter installation af begge på klientsiden behøver du kun at ændre thumbprintet i app.config under clientCertificate findValue=”” til jeres udstedte certifikats thumbprint. Pas på ved kopiering fra certifikatdetaljerne et usynligt tegn i slutningen af thumbprintet kan let snige sig med.

ADVARSEL: flere forskellige sikkerhedsforanstaltninger er slået fra i testprojektet, disse skal naturligvis være slået til i produktion.

Written by larsholm

August 7th, 2012 at 10:57 am

Posted in Uncategorized

C# string to alphanumeric

with one comment

Short and easy way to get the alphanumeric content of a string:

public static string ToAlphaNumeric(this string str)
{
    return new string(str.Where(c => char.IsLetterOrDigit(c)).ToArray());
}

Written by larsholm

June 16th, 2011 at 9:32 pm

Posted in .NET

Tagged with , , , ,

Persist .NET objects to XML

without comments

Here’s two extensions I use to easily persist objects to XML string in C#. Although it looks like it, it does not seem to require that the class of the object is decorated with the DataContract attribute, it just works.

public static string ToXml(this object o)
{
    StringWriter sw = new StringWriter();
    XmlWriter xw = XmlWriter.Create(sw);
    DataContractSerializer dcs = new DataContractSerializer(o.GetType());
    dcs.WriteObject(xw, o);
    xw.Close();
    return sw.ToString();
}

public static T FromXmlTo(this string s) where T : class
{
    DataContractSerializer dcs = new DataContractSerializer(typeof(T));

    StringReader sr = new StringReader(s);
    XmlReader xtr = XmlReader.Create(sr);

    return dcs.ReadObject(xtr) as T;
}

Let me here how it works out for you guys..

Written by larsholm

June 16th, 2011 at 9:06 pm

Posted in .NET

Tagged with , , , , ,

Embed managed dlls easily in a .NET assembly

with 31 comments

Here’s a very quick and dirty way to include managed dlls in your .exe-file. Just right-click your project in Visual Studio, choose Project Properties -> Resources -> Add Resource -> Add Existing File

Add all your dependencies and finally include the code below in your App.xaml.cs or equivalent.. everything else is taken care of.

public App()
{
    AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll","");

    dllName = dllName.Replace(".", "_");

    if (dllName.EndsWith("_resources")) return null;

    System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());

    byte[] bytes = (byte[])rm.GetObject(dllName);

    return System.Reflection.Assembly.Load(bytes);
}

The code is a little bit more complicated than need be. But I wanted to avoid using a named namespace in order to keep the code copy-paste-ready. By the way LINQPad uses a similar method, though Joe Albahari has gone a step further and encrypted his resources.

Written by larsholm

June 15th, 2011 at 8:10 pm

Posted in .NET

Tagged with , , , , , ,

Avoid incorrect Silverlight XAP file caching

with 47 comments

The code below appends the last-write filedate of the Silverlight Application XAP file to the path in the source parametre of the Silverlight object tag.
This will ensure that poorly constructed caching functionality of webbrowsers and proxy servers doesn’t incorrectly use old, wrong builds of the XAP file.
However it will still allow these caches to work. Furthermore a check is performed to avoid XAP file path alteration during debugging, this is to allow debugging tools such as Silverlight Spy to continue functioning.

<object id="Xaml1" data="data:application/x-silverlight-2," type="application/x-silverlight-2"

width="100%" height="100%">

<%––<param name="source" value="ClientBin/SilverlightApp.xap"/>––%>

<%

string orgSourceValue = @"ClientBin/SilverlightApp.xap";

string param;

if (System.Diagnostics.Debugger.IsAttached)

param = "<param name=\"source\" value=\"" + orgSourceValue + "\" />";

else

{

string xappath = HttpContext.Current.Server.MapPath(@"") + @"\" + orgSourceValue;

DateTime xapCreationDate = System.IO.File.GetLastWriteTime(xappath);

param = "<param name=\"source\" value=\"" + orgSourceValue + "?ignore="

+ xapCreationDate.ToString() + "\" />";

}

Response.Write(param);

%>

<param name="onError" value="onSilverlightError" />

Written by larsholm

February 1st, 2010 at 8:06 pm

FocusHelper

with one comment

Here is a little helper class I use when implementing tab navigation in Silverlight. When FocusHelper.Start() is called at application startup it simply creates a timer which attempts to give the focused element a red border and a slightly red background. When I say attempts it’s because themes and styles may prevent the changes from showing. I have often found it helpful, because it is almost never clear which element in Silverlight has the focus. Notice that the functionality is disabled if your browser’s zoom is different from 100%.

public static class FocusHelper
{
    public static void Start()
    {
        focusBorderBrush = new SolidColorBrush(Colors.Red);
        focusBackground = new SolidColorBrush(Colors.Red);
        focusBackground.Opacity = 0.1;
 
        focusTimer = new Timer(new TimerCallback((o) =>
        {
            try
            {
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    object temp = null;
 
                    if (System.Windows.Application.Current.Host.Content.ZoomFactor==1)
                        temp = FocusManager.GetFocusedElement();
 
                    if (temp != lastFocus)
                    {
                        if (temp is Control)
                        {
                            //Give the last control back its original color
                            if (lastFocus != null)
                            {
                                lastFocus.BorderBrush = lastBrush;
                                lastFocus.BorderThickness = lastThickness;
                                lastFocus.Background = lastBackground;
                            }
 
                            lastFocus = temp as Control;
                            lastBrush = lastFocus.BorderBrush;
                            lastThickness = lastFocus.BorderThickness;
                            lastBackground = lastFocus.Background;
 
                            lastFocus.BorderBrush = focusBorderBrush;
                            lastFocus.BorderThickness = new Thickness(1);
                            lastFocus.Background = focusBackground;
                        }
                    }
                });
            }
            catch
            {
            }
 
        }), null, 0, 100);
    }
 
    private static System.Threading.Timer focusTimer;
    private static Control lastFocus = null;
    private static Thickness lastThickness;
    private static Brush lastBrush;
    private static Brush lastBackground;
    private static Brush focusBorderBrush;
    private static Brush focusBackground;
}

Written by larsholm

December 16th, 2009 at 6:46 pm

PostponingTimer

with one comment

This is a small timer class that I have found useful a couple of times.

It takes a job and a timeout in its Run() method, which it executes

after the timeout, unless you call the Run() method again, in which

case it postpones the execution of the job. I have mostly used this

in connection with some type of user input. For instance, doing

something when there has been a sufficient pause in scrolling or typing.

 

/// <summary>

/// This class can be used to execute a job just once after a specified

/// time since the last of a series of events has fired.

/// For instance, when implementing an Auto-Save feature in a textbox you

/// might want to avoid saving on every keypress event. In this case you can

/// call Run(() => Save(), 5000) in each keypress event. The PostPoningTimer

/// will then make sure that Save() is executed one time when 5 seconds has

/// past since the last keypress event. Any new keypresses will of course

/// repeat the process.

/// </summary>

public class PostponingTimer

{

    private Timer timer;

 

    private Dispatcher CurrentDispatcher

    {

        get

        {

#if SILVERLIGHT

            return System.Windows.Deployment.Current.Dispatcher;

#else

            return Dispatcher.CurrentDispatcher;

#endif

        }

    }

 

    private void Execute(Action job, Dispatcher dispatcher)

    {

#if SILVERLIGHT

        dispatcher.BeginInvoke(job);

#else

        dispatcher.Invoke(job);

#endif

    }

 

    /// <summary>

    /// If you keep calling Run() within timeout, job never gets executed.

    /// Only when you stop calling Run() job will run once after timeout

    /// milliseconds.

    /// <para>Job will run on calling threads dispatcher. If in silverlight

    /// the UI threads dispatcher is used.</para>

    /// </summary>

    /// <param name=”job”></param>

    /// <param name=”timeout”></param>

    public void Run(Action job, int timeout)

    {

        //Make sure the timer from last call is prevented from running.

        if (timer != null) timer.Dispose();

 

        //When not in SILVERLIGHT the line below makes sure to use the

        //dispatcher of the calling thread.

        //In silverlight the UI thread dispatcher is used.

        Dispatcher dispatcher = CurrentDispatcher;

 

        timer = new Timer(new TimerCallback((o) =>

            {

                Execute(job, dispatcher);

            }), null, timeout, Timeout.Infinite);

    }

 

    /// <summary>

    /// If you keep calling Run() within timeout, job never gets executed.

    /// Only when you stop calling Run() job will run once after timeout

    /// milliseconds.

    /// <para>Job will run on the timer’s thread.</para>

    /// </summary>

    /// <param name=”job”></param>

    /// <param name=”timeout”></param>

    public void RunNonUI(Action job, int timeout)

    {

        //Make sure the timer from last call is prevented from running.

        if (timer != null) timer.Dispose();

 

        timer = new Timer(new TimerCallback((o) =>

            {

                job();

            }), null, timeout, Timeout.Infinite);

    }

 

    /// <summary>

    /// If you keep calling Run() within timeout, job never gets executed.

    /// Only when you stop calling Run() job will run once after timeout

    /// milliseconds.

    /// <para>Actions will run on calling threads dispatcher. If in

    /// silverlight the UI threads dispatcher is used.</para>

    /// </summary>

    /// <param name=”job”></param>

    /// <param name=”timeout”></param>

    /// <param name=”callback”></param>

    public void Run(Action job, int timeout, Action callback)

    {

        //Make sure the timer from last call is prevented from running.

        if (timer != null) timer.Dispose();

 

        //When not in SILVERLIGHT the line below makes sure to use the

        //dispatcher of the calling thread.

        //In silverlight the UI thread dispatcher is used.

        Dispatcher dispatcher = CurrentDispatcher;

 

        timer = new Timer(new TimerCallback((o) =>

            {

                Execute(job + callback, dispatcher);

            }), null, timeout, Timeout.Infinite);

    }

 

    /// <summary>

    /// If you keep calling Run() within timeout, job never gets executed.

    /// Only when you stop calling Run() job will run once after timeout

    /// milliseconds.

    /// <para>Actions will run on the timer’s thread.</para>

    /// </summary>

    /// <param name=”job”></param>

    /// <param name=”timeout”></param>

    /// <param name=”callback”></param>

    public void RunNonUI(Action job, int timeout, Action callback)

    {

        //Make sure the timer from last call is prevented from running.

        if (timer != null) timer.Dispose();

 

        timer = new Timer(new TimerCallback((o) =>

            {

                (job + callback)();

            }), null, timeout, Timeout.Infinite);

    }

 

}

Written by larsholm

December 16th, 2009 at 12:55 am

Posted in .NET,Silverlight

Tagged with , , , , , , ,

Clean install of Windows 7 on your PDC 2009 Acer Tablet PC

with one comment

When I put an Intel SSD in the laptop I received at Microsoft PDC2009 I spend a lot of time trying to get the existing partitions moved to the new drive. I was convinced that this would be the easiest. I would have VS2010, Windows 7 activated, Office 2010, and all the drivers needed.

However after pretty much a whole weekend I gave up, having destroyed the MBRs of both disks and set a mixture of both Windows and Linux boot flags on random partitions. I was thinking that it would be another two days before I could enjoy my new laptop fortified with a 160 GB Intel SSD and an extra 2 gigs of ram, but then I stumpled upon this guide and after a very short time the little box was up and running.. with everything. New Windows 7, Drivers, VS, Office, LINQPad and so forth. All the drivers needed magically appeared in Windows Update, maybe not so weird, it sort of is a Microsoft laptop.

If I should do it again, here’s how (or in other words ‘my guide to the guide’):

Skip Step 1.

Optionally skip step 2. (I never seem to use restore images anyway)

Do step 3.

In step 4 choose B (Not really a choice) and I highly recommend Method 1. I don’t know why it says time consuming !? AH.. of course when formatting your new drive choose quick format. So in the step 5 of the ‘How-to install Windows 7 from an USB stick’ guide  the format line should be:

Format FS=FAT32 QUICK

Please select the RIGHT DRIVE, that is; your new, presumably empty drive. Use an external HDD enclosure/case/thing.

In step 5 (of the main guide)

Ignore all talk about Vista.

Do step 6. For me section B failed because my default printer wasn’t working, so I chose the XPS printer, and it ran fine. All done.

Written by larsholm

December 8th, 2009 at 12:09 am

Posted in Uncategorized

ValueEquals() extension

with one comment

I have done what I almost never do. I have made an extension method. I don’t like extensions, I believe they increase code complexity and decrease code portability.

Why allow static methods to disguise themselves as instance methods? Well, on the other hand Linq is awesome.

Another move from Hejlsberg & co. that I’m no fan of, is that it is left to the creator of a class to decide if Equals() should mean that two objects are the same (ReferenceEquals()) or simply equal. And when I want the ‘equal’ functionality, I have to implement it.

So I created this:

An extension method that recursively runs through all public fields and properties and check for value equality at node level. It does not support indexed properties, at least not yet and please notice that this uses the MoreLinq extensions.

  258         public static bool ValueEquals(this object o, object o2)

  259         {

  260             Type oType = o.GetType();

  261             if (!oType.Equals(o2.GetType())) return false;

  262 

  263             if (o == o2) return true;

  264 

  265             if (o is ValueType || o is string)

  266             {

  267                 return (o.Equals(o2));

  268             }

  269             else if(o is Array)

  270             {

  271                 return (o as Array).Cast<object>().ZipLongest((o as Array).Cast<object>(), (i1, i2) => i1.ValueEquals(i2)).All(b => b);

  272             }

  273             else

  274             {

  275                 return oType.GetFields().All(f =>

  276                 {

  277                     object v = f.GetValue(o);

  278                     if (v == null)

  279                     {

  280                         return f.GetValue(o2) == null;

  281                     }

  282                     else if (v is ValueType || v is string)

  283                     {

  284                         return v.Equals(f.GetValue(o2));

  285                     }

  286                     else

  287                     {

  288                         return v.ValueEquals(f.GetValue(o2));

  289                     }

  290                 }) &&

  291                     oType.GetProperties().All(p =>

  292                     {

  293                         object v = null;

  294                         try

  295                         {

  296                             v = p.GetValue(o, null);

  297                         }

  298                         catch (TargetParameterCountException)

  299                         {

  300                             throw new Exception("Indexed properties are not supported yet");

  301                         }

  302                         if (v == null)

  303                         {

  304                             return p.GetValue(o2, null) == null;

  305                         }

  306                         else if (v is ValueType || v is string)

  307                         {

  308                             return v.Equals(p.GetValue(o2, null));

  309                         }

  310                         else

  311                         {

  312                             return v.ValueEquals(p.GetValue(o2, null));

  313                         }

  314                     });

  315             }

  316         }

Let me know how it works for you..

Written by larsholm

September 19th, 2009 at 1:44 am

Posted in .NET

Tagged with , , , , ,