RaSor's Tech Blog

May 10, 2016

VS: Libraries and APIs

Filed under: NET, Visual Studio — rasor @ 12:28 pm

This post will contain some .NET libraries / APIs, that I want to remember.

The end.

May 3, 2016

SQL: Using a trigger to ensure data integrity.

Filed under: SQL — rasor @ 6:22 pm

This trigger will on insert and update look at to fields (e.employerid and e.companyid).
The e.employerid is related to e.companyid though h.companyid.
If there is not match between e.companyid and h.companyid (meaning one of the fields are invalid)
then an error will be thrown back to .NET telling the values of the mismatched ids.


March 27, 2016

ChromeCast with NetGear R7000

Filed under: HW — rasor @ 8:49 am

I couldn’t get ChromeCast R1 working using setup from Windows 10 and default settings.

To get it working I did the following: (more…)

February 7, 2016

CZ8. SublimeText : Add Snippets

Filed under: Blog, SublimeText — rasor @ 1:51 pm

This post is part of a series starting with

In this post I will add snippets to SublimeText.

Snippets should be divided into folders, that has the same name as the syntax, so they appear in the right context.

  • Create snippet template with
    • Tools – New snippet…

Snippets without scope

WordPress snippets


The snippet is for posting souce code into WordPress.

The below snippet don’t show right in the browser.

You must replace “<“code with “[“code. And likewise for the rest of the <> brackets used with “code”.

<code language="${1:javascript}">
  • ctrl-s – “WordPress-code.sublime-snippet” -Save
  • To use: write “wp” ctrl-space

Snippets with scope

JavaScript snippets


<!-- From https://code.tutsplus.com/courses/perfect-workflow-in-sublime-text-2/lessons/your-first-snippet -->
(function() {
  • ctrl-s – <make dir “JavaScript”> – goto \JavaScript\ – “SelfInvokingAnonymousFunction.sublime-snippet” -Save
  • To use: In .js write “siaf” ctrl-space

Thanks to NetTuts for the lesson.

The End.

WF5. Express: HowTo Add bootstrap

Filed under: Mean, Node/Express, SublimeText — rasor @ 1:10 am

This HowTo is notes taken from Chapter 3 in “Getting Mean With Mongo, Express, Angular, and Node“.

Express by default delivers almost no styling in .\public\stylesheets\style.css.

So it is nice to get started with bootstrap


  • ST3 – ctrl-alt-n “public\javascripts\jquery.min.js” //Create and opens new file
  • ST3 -ctrl-shift-p “fetf” – enter – jquery – enter //Download content into file
  • ST3 -ctrl-shift-p “fetp” – enter – Bootstrap – “\public\bootstrap”
  • ST3 -ctrl-shift-p “fetp” – enter – Bootstrap_Amelia – “\public\bootstrap\css”

Now you got jQuery, bootstrap and the amelia theme downloaded.


  • ST3 – ctrl-p “layoj” – enter //Opens .\app_server\views\layout.jade
  • Add the missing parts: meta, link, script:
    meta(name='viewport', content='width=device-width, initial-scale=1.0')
    title= title
    link(rel='stylesheet', href='/bootstrap/css/amelia.bootstrap.css')
    link(rel='stylesheet', href='/stylesheets/style.css')
    block content

Now you got


The End.

January 23, 2016

Mean stack: Preparing workflow on Windows

Filed under: Bat, Mean, MongoDB, SublimeText — rasor @ 2:41 pm

Updated: 2016-02-07

I am preparing a development setup for the Mean-stack on Windows 10.

That is for developing along with the book “Getting Mean With Mongo, Express, Angular, and Node“.

With this blog I will customize tool settings, so they minimize the work needed, while developing. (more…)

January 1, 2016

Two step authentication

Filed under: Mobile — rasor @ 9:14 pm

My cell phone died.

I did not backup the phone, so I could restore its settings. Guess I’ll backup on the new one.

So how do I turn off Two step/factor authentication for the apps that has it turned on, so live without it until I get a new phone?

The apps where I want to turn it off – or at least its binding to a phone are:

  • Google
  • Facebook
  • Microsoft
  • Apple
  • WordPress

After reading through the resources below, it seems like it is not needed to remove 2 step authentication – but the Facebook Code Generator and the Google Authenticator app might be better to replace with SMS, so the phone don’t have the codes on the device, if the phone is lost.

Also you should go through list of sessions and apps granted access and revoke those accesses. (more…)

December 7, 2015

Online logo

Filed under: GraphicDesign — rasor @ 5:32 pm

I needed a logo without having to draw anything myself and without breaking copyrights.

Found this online logo service:
http://www.picturetopeople.org/p2p/logo_editor.p2p/sticker-maker (more…)

December 4, 2015

SQL: Joins

Filed under: SQL — rasor @ 10:28 am

Nice overview of SQL joins:


Thanks for the image to C.L. Moffatt


The End

November 23, 2015

C#: Changing local timezone temporarily

Filed under: C#/Xaml — rasor @ 1:08 pm

Changing local timezone temporarily

            CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
            if (currentCulture.Name != &quot;sv-SE&quot;)
                // Change the current culture to sv-SE and serialize the date.
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(&quot;sv-SE&quot;);

            // Do something with a date in swedish timeZone
            var swedishNow = DateTime.Now;

            // Restore back to the original culture, when finished
            Thread.CurrentThread.CurrentCulture = currentCulture;

The End.

November 12, 2015

C#: Check if a generic type is an enum

Filed under: C#/Xaml, Generics — rasor @ 9:43 am

Sample: Check if a generic type is an enum:

public T GetEnumFromString<T>(string value) where T : struct, IConvertible
   if (!typeof(T).IsEnum) 
      throw new ArgumentException("T must be an enumerated type");


Thanks to Vivek


The end

October 8, 2015

C#: converting string[] args to Dictionary

Filed under: C#/Xaml, Generics — rasor @ 8:59 am

Sample for converting string[] args to Dictionary<string, string>.

Notice both keys and values are converted to UPPER and separated by “:” in args.


October 6, 2015


Filed under: SQL — rasor @ 1:59 pm

Sample for converting GUID to UNIQUEIDENTIFIER


October 5, 2015

Async worker for a Windows Service

Filed under: Async — rasor @ 11:16 am

Sample for a Windows Service using Task’s


October 2, 2015

Self-hosting WCF over named pipes

Filed under: Visual Studio, WCF — rasor @ 10:48 am

In VS13:
I want to call a WCF service (via a WCF service library) either from a test app or from a windows service.
Both should self-host using a named pipes port.

I keep getting timeout in the client:
There was an error reading from the pipe: The pipe has been ended.

So What are reasons for local Windows named-pipes to fail?

Well I haven’t found
– PipeFirewall
– File sharing service not running
– Windows firewall blocking

So now I’ll just store this sample for another time.

Intersting is that the WCF service library app.config is read by VS13 and it starts the service on those endpoints (basicHttp), too.

Note: InProcFactory is a library from iDesign.com. Using that made no difference.

Server and Client code:

        private void buttonStart_Click(object sender, EventArgs e)
            ICleanUpMiniService wcfSvc = null;
            textBox1.Text = "";

            bool useInProFactory = false;

            if (!useInProFactory)
                // Create the ServiceHost.
                Uri baseAddress = new Uri("net.pipe://localhost/mysln/" + Guid.NewGuid() + "/");
                //Uri baseAddress = new Uri("net.pipe://" + Environment.MachineName + "/mysln/" + Guid.NewGuid() + "/");
                using (ServiceHost host = new ServiceHost(typeof(CleanUpMiniService), baseAddress))
                    var binding = new NetNamedPipeBinding();
                    binding.ReceiveTimeout = new TimeSpan(0, 0, 15); //Cilent timeout
                    //binding.TransactionFlow = true;
                    const string relAddress = "cleanupminiservice";
                    ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof (ICleanUpMiniService), binding, relAddress);

                        // Open the ServiceHost to start listening for messages. Since
                        // no endpoints are explicitly configured, the runtime will create
                        // one endpoint per base address for each service contract implemented
                        // by the service.

                        Debug.WriteLine("Service started. Available in following endpoints");
                        foreach (var serviceEndpoint in host.Description.Endpoints)
                        //Create service

                        Debug.WriteLine(endpoint.Name); //NetNamedPipeBinding_ICleanUpMiniService

                        //Open client using server endpoint
                        var factory = new ChannelFactory<ICleanUpMiniService>(endpoint);
                        //Open client using app.config client settings
                        //var factory = new ChannelFactory<ICleanUpMiniService>("NetNamedPipeBinding_ICleanUpMiniService");
                        wcfSvc = factory.CreateChannel();

                        //Use service
                        string[] args = {};
                        textBox1.Text = wcfSvc.Hallo("sss"); //.OnStop();//.OnStart(args);

                        Debug.WriteLine("returned from server");
                        // Close the ServiceHost.
                    wcfSvc = InProcFactory.CreateInstance<CleanUpMiniService, ICleanUpMiniService>();

                    //Use service
                    string[] args = { };
                    textBox1.Text = wcfSvc.Hallo("sss");//.OnStop();//.OnStart(args);

                    Debug.WriteLine("returned from server");
                    if (wcfSvc != null)

August 4, 2015

VS2013 – DB Project – Issues and Tips

Filed under: SQL, Visual Studio — rasor @ 7:23 am

Last updated: 2015-09-14


I’ve recently stumpled upon a couple of problems in a DB project in Visual Studio

1) Could not update DB with a script after Schema Compare.

Solution: Remove build errors.
In my case it was a matter of commenting out some users and permissions.

2) Could not build. Got error

System.MethodAccessException: Attempt by method ‘Microsoft.Data.Tools.Schema.Sql.Build.SqlTaskHost.OnCreateCustomSchemaData

Solution was: Install Latest SQL Server Data Tools (SSDT)
Download Latest SQL Server Data Tools

3) Schema Compare script gave “The default schema does not exist”

Solution was change your default schema to dbo:



1) Ignore GRANTs in Schema Compare


Unselect Permissions

Thanks to http://stackoverflow.com/users/65775/keith

2) Data compare with VS

– Tools – SQL Server – New data comparison – select DBs and compare

Above will only work if table schemas match.

If you have unselected Permissions like above, then schemas don’t match.

3) Export data script with SSMS

If above won’t work you can export data script with SSMS.

– RightClick DB – Tasks – Genrate Scrips – Next

– Select Specific DB objects – Select Tables – Next

– Advanced – General – Type of data to scripts: Data only – OK – Next – Finish

The End.

July 28, 2015

Async Tasks over WCF

Filed under: Async, WCF — rasor @ 11:16 am

This is a sample of using async tasks over WCF.
The client handles possible errors (exceptions) from the server in a separate task.


        private async void button1_Click(object sender, EventArgs e)
            button1.Enabled = false;
            txtResponse.Text = "";
            Task<string> t1 = null;
            Task<Task<string>> t2 = null;
                string testErr = "None";
                //testErr = "ThrowArgumentException";
                //testErr = "ThrowApplicationExceptionErr";

                t1 = SomeMethod(new SomeMethodRequest() { DocId = testErr });
                t2 = t1.ContinueWith<Task<string>>(ShowError, TaskContinuationOptions.OnlyOnFaulted);
                List<Task> tasks = new List<Task>() { t1, t2 };
                await Task.WhenAll(tasks);
                //Following is Not exec if faulted

                Debug.WriteLine("t1 status:" + t1.Id.ToString() + "-" + t1.Status);
            catch (Exception ex)
                //outer task (t1) is faulted - goto continue on faulted (t2)
                switch (t1.Status)
                    case TaskStatus.RanToCompletion:
                        txtResponse.Text = t1.Result;
                    case TaskStatus.Faulted: 
                        //Then the errortask ran
                        if (t2.Status == TaskStatus.RanToCompletion)
                            txtResponse.Text = t2.Result.Result;

                txtResponse.Text += "\r\n"+ "t1.Status:" + t1.Status;
                button1.Enabled = true;

        private async Task<string> SomeMethod(SomeMethodRequest request)
            string retVal = "";
                //Using WCF service
                using (var svc = new MyService.MyServiceClient())
                    //Exec Async service
                    //SomeMethodResponse x = await svc.SomeMethodAsync(request); or

                    Task<SomeMethodResponse> task = svc.SomeMethodAsync(request);
                    Debug.WriteLine("task:" + task.Id.ToString());
                    await Task.WhenAll(task);
                    //Following is Not exec if faulted

                    Debug.WriteLine("task status:" + task.Id.ToString() + "-" + task.Status);

                    if (task.Result != null)
                        //Status: RanToCompletion
                        retVal = "OperationSuccess: " + task.Result.OperationSuccess.ToString();
                        retVal = "Timed out" + "\r\n" + "Status: " + task.Status;
            catch (Exception ex)
                //Fault the inner task by bubling up ex
                throw ex;
            return retVal;

        private async Task<string> ShowError(Task task)
            string retVal = "";
            foreach (var ex in task.Exception.Flatten().InnerExceptions)
                retVal += "\r\n" + "InnerEx: " + ex.Message;
            //return Task.Factory.StartNew(() => retVal);

            return retVal;

The server just runs in sync, but it can be changed to await some async response. The client already have just set up an Async call anyway.

When the server throws an error the task in the client will be faulted and the client takes action on that.

        public async Task<SomeMethodResponse> SomeMethod(SomeMethodRequest request)
                //await Task.Delay(2000).ConfigureAwait(continueOnCapturedContext: false);

                if (request.DocId == "ThrowArgumentException")
                    throw new ArgumentException("ArgumentException thrown");
                if (request.DocId == "ThrowApplicationExceptionErr")
                    throw new ApplicationException("ApplicationException Error when creating doc in target");
                //ToDo: Do some stuff to retrieve a response
                var response = new SomeMethodResponse()
                    OperationSuccess = true

                return response;
                //return await Task.Run(() => response);
            catch (Exception ex)
                //Fault the service task by bubling up ex
                throw ex;


The End.

July 23, 2015

Linq: Articles and Blogs

Filed under: LINQ — rasor @ 11:06 am

Here is stored some Linq links.



My own posts:

The End

July 22, 2015

WCF: Enable WSDL on a WCF Service (Ajax-enabled)

Filed under: Visual Studio, WCF — rasor @ 7:04 am

WCF Service (Ajax-enabled):

            <behavior name="MyServiceAspNetAjaxBehavior">
               <enableWebScript />
      <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
         <service name="MyService">
            <endpoint address="" behaviorConfiguration="MyServiceAspNetAjaxBehavior"
               binding="webHttpBinding" contract="MyService" />

WCF Service (Ajax-enabled) – with WSDL / Metadata enabled:

            <behavior name="MyServiceAspNetAjaxBehavior">
               <enableWebScript />
           <behavior name="MyServiceMexBehavior" >
             <serviceMetadata httpGetEnabled="true" />
      <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
         <service name="MyService" behaviorConfiguration="MyServiceMexBehavior">
            <endpoint address="" behaviorConfiguration="MyServiceAspNetAjaxBehavior"
               binding="webHttpBinding" contract="MyService" />
            <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />

The End.

July 20, 2015

VS: Convert WebForms WebSite to WebApp

Filed under: Visual Studio — rasor @ 9:58 am

Converting a Visual Studio Web Site to a Web Application makes it easier to have control of all the references.

Here are steps todo for that procedure

  1. Create an empty ASP.NET application with WebForms selected
  2. Drag’n’drop files from the old website project into your new webapp project (except for web.config)
  3. On the imported .cs files change Build Action from Content to Compile
  4. Close Visual Studio
  5. For each <MyPage>.aspx.cs, <MyMaster>.master.cs and <MyControl>.ascx.cs file:
    1. Edit the .cs file – change CodeFile=… to CodeBehind=…
    2. Create an empty file called <MyPage>.aspx.designer.cs
    3. In the .csproj file paste link to the new file just below the include of the MyPage.aspx:
    4. <Compile Include=”MyPage.aspx.designer.cs”>
    5. Open Visual Studio
    6. Dran’n’drop a Label control from the Toolbox to the end of your markup
    7. Open the designer.cs file – now all (or most) the controls should be auto-generated in there
    8. Delete the label you just added from the markup
    9. You might have non-asp webcontrols like normal html controls where you would need to add the control in the non-designer file e.g.
      protected global::System.Web.UI.HtmlControls.HtmlAnchor lnkAbout;
      for a markup a hyperlink “<a href=…”
    10. If in doubt or lost: Create a new page or control – paste content and rename it.
  6. Paste content from the website web.config into the webapp web.config
  7. Add missing references
  8. Compile and run


The End

June 24, 2015

TeamCity: Cleanup

Filed under: Continues Integration — rasor @ 12:43 pm

In our TeamCity setup our BuildAgent ran out of disk space.

To find the problem I had to learn how our setup was.

It was a single server with two folders:

  • Program folder in c:\teamcity
  • Data folder in c:\programdata\jetbrains\teamcity


June 19, 2015

EPiServer – Changing hostname on single website

Filed under: EPiServer — rasor @ 11:25 am

Re-add “*” to Hostname in EPiServer

Have you tried to delete websites in EPiServer then added a new one and not adding “*” as hostname?

In my case our code failed somewhere deep down, so it felt as the easiest solution to add the “*” directly in the DB

-- Print current sites and hostnames
select * from tblSystemBigTable
where [StoreName] = 'EPiServer.Web.SiteDefinition'
select * from tblBigTableReference
where ElementStoreName = 'EPiServer.Web.HostDefinition'--pkid = <from above>
select * from tblBigTable
where [StoreName] = 'EPiServer.Web.HostDefinition'
-- Add * as hostname for all sites, where language code is not set
update tblBigTable 
SET [String02] = '*'
where [StoreName] = 'EPiServer.Web.HostDefinition'
AND [String01] is null

The End.

May 26, 2015

Using Curl

Filed under: Debugging — rasor @ 1:55 pm

Some links for Curl

Download Curl for win64

Install Curl

Use Curl


  • Use e.g. Fiddler for catching a request send from a client on localhost.
  • Save request to xml file
  • use xml file from curl


The end.

April 24, 2015

EPiServer7.x: Get Aboslute Url from page

Filed under: EPiServer — rasor @ 12:55 pm

Sometimes you need an absolute url from a page within EPiServer.

Dejan Caric made this nice HowTo: http://www.dcaric.com/blog/episerver-how-to-get-external-page-url

Here the same code is put in an extension method and a method including wanted language is added: (more…)

April 7, 2015

EPiServer7x: Hooking up to Quicknavigator

Filed under: EPiServer — rasor @ 9:53 am

Alf Nilsson provided this great post about Hooking up to EPiServer Quicknavigator.


March 30, 2015

ASP.NET: Base Url and Absolute Url

Filed under: C#/Xaml, NET — rasor @ 1:25 pm

Seems like I have to dig everytime I need an absolute url.

From http://stackoverflow.com/questions/689678/request-url-host-and-applicationpath-in-one-call :

public static Uri GetBaseUrl(HttpRequest request)
    if (request == null || request.Url == null || request.ApplicationPath == null)
        throw new ArgumentException("Cannot be null", "request");

    Uri contextUri = new Uri(request.Url, request.RawUrl);
    UriBuilder realmUri = new UriBuilder(contextUri) { Path = request.ApplicationPath, Query = null, Fragment = null };
    return realmUri.Uri;

public static string GetAbsoluteUrl(HttpRequest request, string relativeUrl)
    return new Uri(GetBaseUrl(request), VirtualPathUtility.ToAbsolute(relativeUrl)).AbsoluteUri;

Other links:

The End.

March 17, 2015

EPiServer: Change block on page

Filed under: EPiServer — rasor @ 2:56 pm


In this use case I had a page: OverviewPage with a block: PageHeader.


Other pages were still using PageHeader, while OverviewPage page needed to have PageHeader replaced with a new block: PageHeaderMandatory. Here is the code: (more…)

March 15, 2015

VS: Xml transforms with SlowCheetah

Filed under: Visual Studio — rasor @ 2:48 pm

In ASP.NET projects you can tranform Web.config files out-of-the-box in VisualStudio.

When you want app.config files and .xml files transformed in the same manner you can use SlowCheetah. (more…)

March 13, 2015

EPiServer: AccessDenied to language, if language role missing

Filed under: EPiServer — rasor @ 2:07 pm

If you in EPiServer 7.x have activated multiple languages via
http://webhelp.episerver.com/14-1/EN/Content/EN/CMS%20Admin/Admin_Languages.htm (more…)

February 19, 2015

Log4net, Elmah: HowTo Select surrounding trace rows

Filed under: Debugging, EPiServer, NET, SQL — rasor @ 8:40 am

HowTo Select surrounding trace rows from an Elmah table?


February 4, 2015

VS: Mocking tips

Filed under: Visual Studio — rasor @ 2:27 pm

When mocking with moq in Visual Studio

Moq4 QuickStart:


PM> Install-Package Moq


VS: WebAPI tips

Filed under: Visual Studio, Web API — rasor @ 8:06 am

This post will have some WebAPI tips

Last updated: 2015-02-12


January 23, 2015

NuGet tips

Filed under: Visual Studio — rasor @ 2:52 pm

Updated: 2015-07-09

Adding existing Nuget package to other project.

In a Visual Studio (VS) solution in \packages.config I had

<package id="log4net" version="1.2.10" targetFramework="net45" />

Now adding this same version (instead of latest) to another project in VS can be done from Package Manager Console:

PM> Install-Package log4net -Version 1.2.10 -ProjectName MySln.SomeOtherProject
'log4net 1.2.10' already installed.
Adding 'log4net 1.2.10' to MySln.SomeOtherProject.
Successfully added 'log4net 1.2.10' to MySln.SomeOtherProject.

Adding old DLL to GAC

At another time I wanted to install an old Enterprise Library, but the ones in the NuGet gallery was too new


Intead I chose to add to GAC, but even that is not easy anymore – the drag-n-drop has been barred. So back to a prompt

> "C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\gacutil" /i "C:\Program Files (x86)\Microsoft Enterprise Library 4.1 - October 2008\Bin\Microsoft.Practices.EnterpriseLibrary.Data.dll"



The End

December 22, 2014


Filed under: MVC, NET — rasor @ 10:04 am

To strongly type ASP.NET MVC Views, Models and Controllers you can use T4MVC.

When you rename a view, then you have to edit and Run Custom Tool on the T4MVC.tt file.

To avoid that you can use AutoT4MVC.

For even more advanced automation you can use Chirpy.

The End.

September 17, 2014

VS: ASP.NET Configuration Tool

Filed under: Visual Studio — rasor @ 11:07 am

Editing web.config can be done with ASP.NET Configuration Tool

VS2013:  http://blogs.msdn.com/b/webdev/archive/2013/08/19/asp-net-web-configuration-tool-missing-in-visual-studio-2013.aspx

VS2012:  http://rionscode.wordpress.com/2013/03/26/finding-the-asp-net-configuration-tool-in-visual-studio-2012/

ASP.NET Configuration

July 16, 2014

C#: Snippets

Filed under: Async, C#/Xaml — rasor @ 8:24 am

Last updated: 2015-10-09

DateTime snippets

Print as UTC

string foo = yourDateTime.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK");
//Without milisecs:
string foo = yourDateTime.ToUniversalTime().ToString("u");

Instanciation snippets

Reading with a static method into a class var

    public class SignicatSaml
        private static bool fileStoreEnabled = Convert.ToBoolean(WebConfigurationManager.AppSettings["Archive.FileStore.Enabled"]);

Debugging snippets

Fix for accepting Fiddler cert: The remote certificate is invalid according to the validation procedure.

    ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

Enable webservice calls to be sent through Fiddler
Web.Debug.config transformation

      <!-- Enable webservice calls to be sent through Fiddler http://docs.telerik.com/fiddler/configure-fiddler/tasks/configuredotnetapp -->
      <proxy bypassonlocal="False" usesystemdefault="True" xdt:Transform="SetAttributes"/>
      <proxy xdt:Transform="RemoveAttributes(autoDetect)" />

Convertion snippets

Converting Base64 string to byte array

byte[] bytes = Convert.FromBase64String(base64encodedstr);

Converting string to byte array and back

byte[] bytes = System.Text.Encoding.Default.GetBytes(str);
string str = System.Text.Encoding.Default.GetString(bytes);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
string str = System.Text.Encoding.UTF8.GetString(bytes);
UTF8Encoding ecoder = new UTF8Encoding();
string str = ecoder.GetString(bytes);

Async snippets

Complement and existing Synchroneous method with an Async one

//A synchroneus method changed to asynchroneus
public async Task<CompleteResponse> CompleteNew(string ticket)
        CompleteResponse response = new CompleteResponse();
        // Do something........
        return response;
    catch (Exception ex) {}

//The signature of the original synchroneus method.
//In this case we keep it, so the interface is backward compatible.
public CompleteResponse Complete(string ticket)
        //Call the async func. This will keep this sync func waiting....
        CompleteResponse response = Task.Run(async () =>; await CompleteNew(ticket)).Result;
        return response;
    catch (Exception ex) {}

The Js pattern do – then – then – catchall

Async error handlind


July 10, 2014

C#: XML snippets

Filed under: C#/Xaml, NET — rasor @ 11:07 am

Parsing some namespaced XML


<Response xmlns="urn:oasis:names:tc:SAML:1.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion" xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol" IssueInstant="2009-07-03T04:11:19.354Z" MajorVersion="1" MinorVersion="1" ResponseID="ab05928dfbba21e829f4778f22c9ec3f">
    <StatusCode Value="samlp:Success"></StatusCode>


XmlDocument saml;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(saml.NameTable);
nsmgr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:protocol");
string status = saml.SelectSingleNode("saml:Response/saml:Status/saml:StatusCode/@Value", nsmgr).Value;

The End

July 7, 2014

.NET: HowTo enable WebService calls to be sent through Fiddler

Filed under: Debugging, NET — rasor @ 7:22 am

Assuming you in Web.config have:

      <proxy autoDetect="True" />

Then in your transform file you change it with

      <!-- Enable webservice calls to be sent through Fiddler  http://docs.telerik.com/fiddler/configure-fiddler/tasks/configuredotnetapp -->
      <proxy bypassonlocal="False" usesystemdefault="True" xdt:Transform="SetAttributes"/>
      <proxy xdt:Transform="RemoveAttributes(autoDetect)" />

On the page, where you have a web service call you need to accept the Fiddler certificate, but only in your Debug mode:

        protected async void Page_Load(object sender, EventArgs e)
            //Fix for accepting Fiddler cert: The remote certificate is invalid according to the validation procedure.
            ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

The End.

June 1, 2014

D7: Update Core minor version 7.xx

Filed under: Drupal — rasor @ 7:24 pm

These are notes I made, when upgrading Drupal Core from 1.0-beta5 (7.22) from a TB Sirate Distribution to Core 7.28.

— Udate Core from 1.0-beta5 (7.22) to 7.28 ———
Running update.php is not possible due to a proper version number is missing
Unresolved dependency System (Version >=7.11 required). Currently using System version 1.0-beta5

So solution is to update core:
Instruction: https://drupal.org/node/1494290

  • Create folder mysite/administrator/backups
  • Web with http://backup.mysite.xx/ //An installed backup site
  • SQL with phpMyAdmin – mydb – Export: Custom – OutputCompression: gzipped – Go


  • Download 7.28 from https://drupal.org/project/drupal
  • Extract
  • admin/config/development/maintenance – Select set in maint mode – save
  • Delete all files except
    • /sites
    • /profiles/themebrain_profile
  • Move extracted files to root except /sites
  • If the update release includes changes to settings.php replace old settings.php in /sites/default/ with the new one, and edit site-specific entries (eg database name, user, and password)
  • If you modified files such as .htaccess or robots.txt re-apply those changes to the new files.
  • /user/login
  • Update http://mysite.xx/update.php
  • admin/config/development/maintenance – UnSelect set in maint mode – save

The End.

May 30, 2014

D7: Creating a starter theme – notes

Filed under: Drupal, Notes — rasor @ 12:44 pm

This is notes for Drupal 7 theeming.

The notes I made while creating a starter theme named plate_intl for the Restaurant Distribution based on Plate starter theme.

The procedure can be reused for creating any starter theme

  • Copy the base them to /sites/all/themes and rename the folder
  • Rename and edit the .info file
  • Optionally create an extra .css file with your extra styling
  • Edit the page template page.tpl.php

=== Theme ==============================================

– Copied /profiles/restaurant/themes/plate to
— /sites/all/themes
– Renamed /sites/all/themes/plate to
— /sites/all/themes/plate_intl
– Renamed /sites/all/themes/plate_intl/plate.info to plate_intl.info
– Edited /sites/all/themes/plate_intl/plate_intl.info:
name = Plate_intl
description = An international starter theme for the Restaurant Distribution based on Plate starter theme
regions[header_right] = Header Right
stylesheets[all][] = assets/stylesheets/screen-plate-intl.css
; Information added by rasor on 2013-12-29
version = “7.x-1.0-dev”
project = “plate_intl”

– Created file /sites/all/themes/plate_intl/assets/stylesheets/screen-plate-intl.css

– Edited /sites/all/themes/plate_intl/templates/page.tpl.php – Added two regions and enabled more icons in footer (not used, yet):
<div class=”inner pull-right”>
<?php if ($main_menu): ?>
<nav id=”main-menu” class=”main-menu” role=”navigation” style=”float:left”>
<?php print render($main_menu); ?>
</nav> <!– /#main-menu –>
<?php endif; ?>

<div class=”header-right” style=”float:left”>
<?php print render($page[‘header_right’]); ?>
<footer id=”footer” class=”footer” role=”footer”>
<div class=”container”>
<div class=”footer-links row-fluid”>
<div class=”span3″>
<h4><?php print t(‘Rate Us’); ?></h4>
<?php print ‘<a href=”‘ . restaurant_base_get_settings(‘twitter’) . ‘”>’; ?>
<?php print t(‘Ratings on TripAdvisor’); ?><i><img src=”#”></i></a>
<?php if (isset($footer_links)): ?>
<?php print $footer_links; ?>
<?php endif; ?>
<div class=”footer-bottom row-fluid”>
<?php print render($page[‘footer’]); ?>

– admin/appearance – Enabled&SetDefault Plate_intl 7.x-1.0-dev
! Footer links disappered!!!!
– Edited /sites/all/themes/plate_intl/template.php

Renamed from: function plate_preprocess_page
to: function plate_intl_preprocess_page

Moved html out to page.tpl.php. Changed to:
$footer_links = ”;//'<div class=”footer-links row-fluid”>’;

Used twitter for TripAdvisor:
‘twitter’ => array(
‘title’ => t(‘Ratings on TripAdvisor’),
‘sub_title’ => t(‘Rate Us’),
‘href’ => restaurant_base_get_settings(‘twitter’),
‘icon’ => ‘icon-tumblr’,
// Icon names: http://fortawesome.github.io/Font-Awesome/3.2.1/icons/

– admin/config/development/performance – ClearCache

//Demo regions
– admin/structure/block/demo/plate_intl

– admin/structure/block – Language Switcher – Region: Header Right
— Configure – Block Title: <none>

The End.

April 24, 2014

Wet keyboard – trying to fix

Filed under: HW — rasor @ 5:41 pm

A friend spilled milk on a Lenovo Ideapad Yoga 13 laptop.

Several keys on the keyboard either did not work or displayed on or two wrong characters.

Lots of vids shows howto remove the keyboard:

If cleaning and change keyboard won’t fix then you can use an external USB or bluetooth keyboard.

The end.

March 3, 2014

Convert Nokia VCF2.1 to iCloud VCF3.0

Filed under: iPhone, Symbian/Nokia — rasor @ 8:34 pm

From an old Nokia E71 I needed to copy contacts to IOS7.

The IPhone was set to sync with iCloud, so the task would be to import the contacts to iCloud.

Problem: With iCloud I could not import the Nokia VCF2.1 format.


February 23, 2014

Hyper-V and SystemCenter prep

Filed under: Hosting, Network, Virtual, Windows — rasor @ 11:15 am

MS is offering a free course (Server Virtualization with Windows Server Hyper-V and System Center) and
exam for Hyper-V and SystemCenter management (74-409). This blog contains my notes for the exam prep.

Course Instructors | Symon Perriman – Senior Technical Evangelist, Microsoft; Corey Hynes – Lead Architect and President, HOLSystems Related


February 20, 2014

VS2013 – Comparing ASP.NET project types

Filed under: C#/Xaml, Js/Html, MVC, Visual Studio, Web API — rasor @ 2:06 pm

In Visual Studio 2013 ASP.NET projects you can easily mix WebForms with MVC, WebAPI (Nondiscoverable REST via MVC) SPA and Facebook content. Read more…

This post just compares the default content.


November 26, 2013

Cloud services

Filed under: Cloud, Hosting — rasor @ 11:31 pm

Last updated: 2014-04-24

HowTo become an iPaaS host?

Here is how CloudBees does Integration:

CloudBees Integration (more…)

November 23, 2013

D7: Testing TB Mollise Starter

Filed under: Drupal — rasor @ 9:49 pm

This is a Drupal7 demo of TB Mollise installation profile.

TB Mollise Starter


November 20, 2013


Filed under: Js/Html — rasor @ 12:28 pm

Thought I wanted to collect a list of Access-Control-Allow-Origin fixes when doing Ajax calls

Give Chrome permission:

chrome.exe --allow-file-access-from-files

But you can’t do that on all clients in the world… – source and source


November 16, 2013

D7 Recipe: Installing a custom Drupal installation profile / distribution / starter kit

Filed under: Drupal, Hosting — rasor @ 12:58 am

This is a Drupal7 recipe for using a Drupal Distribution. As an example is used TB Mollise installation profile.
I am here installing onto domain vejviserne.dk, but of course you should replace that and similar settings with your own preferences.


November 8, 2013

CMS Synonyms. Drupal, SharePoint etc

Filed under: Drupal, EPiServer, N2CMS, Orchard, SharePoint — rasor @ 11:32 am

Updated: 2014-06-11

Did you ever notice that there is quite a lot of similarities between SharePoint and Drupal – and other CMS?

This list can be useful, when you are going from one to the other.

Drupal 7 / D8
SharePoint 2007/10/13
Orchard(.NET) Telerik Sitefinity 7
Kentico 8
EPi server
Node, Panel Node (Entity types) List Item Content Item (List) Item, Widget Content ContentItem
User (Entity type) User Profile User, Profile User User User (ContentItem)
Role .. Role (Content Part) Role Role Visitor Group Role
Nodes in block List WebPart Article List WebPart ContentList, Selection
Views List View, List, Document Library Projections, Queries Nope Transformations Nope Container (no customization!)
Content Type (a subtype of a Node Entity) Content Type
Content Type, Content Part Nope Document Type (Inheritable) Nope Nope Nope
Template, Listed type
Block or Pane Block or Fieldable Panel Pane WebPart Widget Content Block WebPart,
Block Part(Type), Widget, ZoneItem
Mini Panel (for nesting panels) Nope – can’t nest webparts Widget Layer CotentArea (for nesting blocks) Zones inside Parts
Region or Pane WebPart Zone Zone Zone (for webparts),
Editor Zone (for widgets)
CotentArea Zone
Main Menu TopLink bar Main Menu Top Menu
Book Navigation BlockPage w. View QuickLaunch Left Menu
Menu Menu Footer Menu
Page or Panel Page Page Page Widget, Page Page Page Content Page(Type), ContentItem
Token Token
Rules Workflow Workflow, Rules Workflow Workflow
Module (installable Plugin) WSP package (Farm or User solution),
ModuleLink Module (installable Plugin) Module Add-On Nope
Module (activateable) Feature Feature Module (activateable) Nope
Panels Everywhere MasterPage MasterPage MasterPage MasterPage
Theme Theme Theme Theme Nope Theme
 Panel Layout. Link – Link2 – Link3 Page Layout Layout Page Template Page Template = Layout + WebParts
Display Suite Content Template Form Layout Nope
Taxonomy, Tag Term Store Taxonomy, Tag Classification, Category, Tag Category Nope
Personalize User Profile Audience (only authenticated) Widget Layer Rules Content Personalization Content Personalization, Link Targeting
Site or one Organic Group Web (Scope) Site Site
Distribution Web Template Website template NuGet package
Multi Site (without common admin) or Organic Groups Site (Scope) = SiteCollection Multisite Sites Yes Multiple sites
Nope Site Template Nope Nope Nope
Nope WebApp (Scope) Nope Nope Nope Nope
Nope Farm (Scope) Nope Webfarm Nope Nope
Storage API, Cloud Files RBS Azure Blob Storage (Dropbox?) Azure Storage, Amazon S3 AmazonS3FileSystemContentProvider BLOB Provider Azure Blob storage
EPi server

  • Very modular
  • There is a module for everything
  • Module and Theme Deployment
  • Block can be nested with Panels


  • Having common permission for multisites is difficult
  • Setting Page level Permissions is difficult
  • No inheritance in Content Types
  • Sites don’t upgrade easily between major versions


Good webapp builder w. ContentTypes, Views, Panels, Rules.

Page handling is not intuitive.


  • Farm features
  • Inheritable Content Types
  • Packages, Sites and Features can have different scopes


  • Resource heavy
  • No personalization on anonymous
  • Difficult to work with MasterPages – due to SP provided HTML
  • Sites don’t upgrade easily between major versions


Outdated due to no ASP.NET MVC support




Good webapp builder w. ContentTypes, Projections, Layouts, Rules.

Looks a lot like Drupal



  • No customizable ContentTypes
  • Base on aspx – extended to mvc


Outdated due to born on WebForms.

Stands out with  having dev env in cloud and App Builder

No customizable ContentTypes => Not a complete CMS


  • Lots of rules for Personalization
  • Can Use Azure Web and Worker role making it easily PaaS scalable
  • Inheritable DocumentTypes


  • Base on aspx – extended to mvc


Outdated due to born on WebForms.

Possibly the cheepest .NET CMS to scale in public cloud due to PaaS deployment

Looks a lot like SharePoint


  • Mobile CMS using jQuery Mobile


  • No trial download or documentation


Seem to be a good mobile CMS


  • Blocks can be nested
  • Multisite Page handling
  • Site and Add-on Deployment
  • Responsive OOTB


  • No customizable ContentTypes
  • No customizable Pages
  • Developer centric
  • No themes


No customizable ContentTypes => Not a complete CMS


  • Multisite Page handling
  • Themes


  • No customizable ContentTypes
  • No customizable Pages
  • Developer centric
  • Little documentation
  • No edible workflow
  • No taxonomy


  • No customizable ContentTypes => Not a complete CMS
  • Use with existing webapp
  • Alpha version of Admin Web
My Blogs
My Blogs
My Blogs
Vids Tutorial, Guide, API PDF User Manual, API PDF User Guides PDF PDF

Maybe concepts like Sharepoint Shared Service Provider can map to services in D8 exposing WebServices?

Drupal Links

Orchard Links

Sitefinity Links

Kentico Links

MonoX Links

Ingeniux Links

EPiServer Links



Other Links


The End

Visiting Drupalhagen.dk 2013

Filed under: Drupal — rasor @ 12:34 am

Drupalhagen.dk is a conference in the center of Copenhagen.

My blog from 2012.

Sessions are:

Friday 8. November:

12:30 Välkomst bavl / Welcome to DrupalHagen!
12:45 Introduction to new technologies in Drupal 8
13:45 Editing Experience
15:00 Lightning talks

– Extending Google Drive to Drupal
– Destructible Developer Environments
– More to come.
16:00 Plugins into D8
17:00 – 17.45 Content strategy and platform architecture

Saturday 9. November:

11:00 Migrating bibliotek.dk to Drupal 7
12:00 Frokost
13:00 Front-end Automated Testing
14:00 Phone is ringing, oh my god! Give your clients support they need…
15:00  The Amazing Jeffrey A. McGuire a.k.a. jam
16:00 TWIG it


Older Posts »

The Silver is the New Black Theme. Blog at WordPress.com.


Get every new post delivered to your Inbox.

Join 55 other followers