Skip to content

What to do if OnOrientationChanged is not fired on windows phone 7 emulator?

If you debug your windows phone application, and the OnOrientationChanged event is not fired, just press Page Up or Page Down. Those keys are used to activate/deactivate the phone keyboard. If the phone keyboard is active, the following code will be executed. Strange thing...

protected override void OnOrientationChanged(OrientationChangedEventArgs e)
{ 
   base.OnOrientationChanged(e);
}

Found(after some time) on the microsoft forum.

Get the current directory from a c# application

Sometimes i have to read/write files from the root directory of my application. Usually i did this with Environment.CurrentDirectory. Unfortunately, this only works if the application is a standalone application(.exe). In case the application is a windows service or a asp.net website, the path from Environment.CurrentDirectory is wrong.

There are several ways to get the root directory of an application, but so far i found only one which works in all scenarios. The only one which always works is:

//works...
IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath)

Here is a (incomplete) list of ways to get the root path of a c# application:

1. Windows service

Environment.CurrentDirectory:
//C:\Windows\system32
System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath)

//D:\project\WindowsServiceTest\WindowsServiceTest\bin\Debug AppDomain.CurrentDomain.BaseDirectory: //D:\project\WindowsServiceTest\WindowsServiceTest\bin\Debug\ Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\")): //D:\project\WindowsServiceTest\WindowsServiceTest\bin\Debug

2. Console application
Environment.CurrentDirectory:
//D:\project\ConsoleApplication3\ConsoleApplication3\bin\Debug
System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath):
//D:\project\ConsoleApplication3\ConsoleApplication3\bin\Debug
AppDomain.CurrentDomain.BaseDirectory:
//D:\project\ConsoleApplication3\ConsoleApplication3\bin\Debug\
Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\")):
//D:\project\ConsoleApplication3\ConsoleApplication3\bin\Debug
3. asp.net mvc3 website vs2010 integrated webserver (Debug mode)
Environment.CurrentDirectory:
//C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0
System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath):
//D:\project\MvcApplication1\MvcApplication1\bin
AppDomain.CurrentDomain.BaseDirectory:
//D:\project\MvcApplication1\MvcApplication1\
Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\")):
//C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0
4. asp.net mvc3 website IIS (Release mode)
Environment.CurrentDirectory: 
//c:\windows\system32\inetsrv 
System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath): 
//d:\project\MvcApplication1\MvcApplication1\bin 
AppDomain.CurrentDomain.BaseDirectory: 
//d:\project\MvcApplication1\MvcApplication1\ 
Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\")): 
//c:\windows\system32\inetsrv 

c# and vb.net sample to remove eventhandler with reflection

This is a sample how to remove a (non-public) eventhandler in c# and vb.net.

//c# sample
using System;
using System.Reflection;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Form2 form2 = new Form2();
            //remove eventhandler with reflection
            EventInfo ei = form2.GetType().GetEvent("Load");
            Delegate d = Delegate.CreateDelegate(typeof(EventHandler), form2, "Form2_Load", false);
            ei.RemoveEventHandler(form2, d);

            //messagebox is not shown, since the eventhandler for load was removed
            form2.ShowDialog();
        }
    }
}

using System;
using System.Windows.Forms;
namespace WindowsFormsApplication5
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            this.Load += new EventHandler(Form2_Load);
        }

        void Form2_Load(object sender, EventArgs e)
        {
            MessageBox.Show("Hello World");
        }
    }
}
'vb.net sample
Imports System.Reflection

Public Class Form1
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        Dim myForm As New Form2
        Dim type As Type = GetType(Form2)

        'remove eventhandler with reflection
        Dim eventInfo As EventInfo
        eventInfo = type.GetEvent("Load")
        Dim loadHandler As System.Delegate
        loadHandler = System.Delegate.CreateDelegate(GetType(EventHandler), myForm, "Form2_Load", False)
        eventInfo.RemoveEventHandler(myForm, loadHandler)

        'messagebox is not shown, since the eventhandler for load was removed
        myForm.ShowDialog()

    End Sub
End Class

Public Class Form2
    Private Sub Form2_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        MessageBox.Show("hello world")
    End Sub
End Class


RemoveEventHanlderWithReflection.zip

Generic c# Json serializer/deserializer sample

  1.  
  2. public class JsonSerializer
  3.     {
  4.         /// <summary>
  5.         /// Serializes a given object into a json string
  6.         /// </summary>
  7.         /// <typeparam name="T">Type to serialize</typeparam>
  8.         /// <param name="objectToSerialize">Object to serialize</param>
  9.         /// <returns>Serialized Json string of the given object</returns>
  10.         public static string SerializeToJson<T>(T objectToSerialize) where T : class
  11.         {
  12.             if(objectToSerialize==null)
  13.             {
  14.                 throw new ArgumentException("objectToSerialize must not be null");
  15.             }
  16.             MemoryStream ms = null;
  17.             try
  18.             {
  19.                 DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());
  20.                 ms = new MemoryStream();
  21.                 serializer.WriteObject(ms, objectToSerialize);
  22.                 return Encoding.UTF8.GetString(ms.ToArray());
  23.             }
  24.             finally
  25.             {
  26.                 if (ms != null)
  27.                 {
  28.                     ms.Close();
  29.                 }
  30.             }
  31.         }
  32.  
  33.         /// <summary>
  34.         /// Deserialize a given json string
  35.         /// </summary>
  36.         /// <typeparam name="T">Type to deserialize</typeparam>
  37.         /// <param name="jsonStringToDeserialize">Json String representation</param>
  38.         /// <returns>Deserialized object</returns>
  39.         public static T DeserializeFromJson<T>(string jsonStringToDeserialize) where T : class
  40.         {
  41.             if(string.IsNullOrEmpty(jsonStringToDeserialize))
  42.             {
  43.                 throw new ArgumentException("jsonStringToDeserialize must not be null");
  44.             }
  45.             MemoryStream ms = null;
  46.             try
  47.             {
  48.                 ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStringToDeserialize));
  49.                 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
  50.                 return (T)serializer.ReadObject(ms);
  51.             }
  52.             finally
  53.             {
  54.                 if (ms != null)
  55.                     ms.Close();
  56.             }
  57.         }
  58.     }
  59.  

MSBuild problem: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)

Problem:

I tried to build a .net(c#) solution with MSBuild, and got the following error:

The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)

Even with a valid using to System.Linq.

The problem seems to be Visual Studio. It seems Visual Studio implicit adds a reference to System.Core, whereas MSBuild does not.

The screenshot shows a small solution, which should be built by MSBuild.

LinqMsbuild1

Buildscript used(master.proj):

<?xml version="1.0" encoding="utf-8"?>

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <GenerateResourceNeverLockTypeAssemblies>true</GenerateResourceNeverLockTypeAssemblies> <TargetType>Rebuild</TargetType> <ConfigurationType>Debug</ConfigurationType> </PropertyGroup> <Target Name="CompileTest" > <MSBuild Targets="$(TargetType)" Properties="Configuration=$(ConfigurationType)" Projects= "D:\project\ConsoleApplication3\ConsoleApplication3.sln" /> </Target> </Project>

#Batch to start the build
SET MSBUILD="C:\WINDOWS\Microsoft.NET\Framework\v3.5\msbuild.exe"
SET LogDll="c:\windows\Microsoft.Net\Framework\v2.0.50727\Microsoft.Build.Engine.Dll"
%MSBUILD% master.proj /tv:3.5  /target:CompileTest /l:FileLogger,Microsoft.Build.Engine;logfile=MyLog.log;verbosity=q;encoding=utf-8 /P:NOWARN=
pause

Building this, the following error is shown from MSBuild:

MSBuildError2

Solution:

Add via notepad(++) a reference to System.Core directly to the csproj/vbproj file:

MSBuildError3

After that, build with MSBuild works fine.

If anyone has a better solution for this problem, please leave a comment.

 

cheers