June 6, 2017

Windows 8/10: Hibernate automatic wakeup

I wanted to publish this post about 2 years ago. Somehow I forgot it in the drafts so I published it today...

Some time ago I had a very nasty problem with my notebook. The notebook was set to hibernate and stored in my backbag. However, during the night the battery ran out and the notebook started (I don't know why the battery can run out in hibernate mode, anyhow). As a result, the notebook overheated because it was stored in the backbag and I had to replace one of the RAM modules.

Just to prevent anyone else having the same problem, this setting might save your notebook's RAM modules :-)
Energy Settings
-> Change Plan Settings
-> Change advanced power settings
-> Allow wake timers = Disabled

If you run a German version of Windows, the last option is called "Zeitgeber für Aktivierung zulassen"

Fortunately this setting is disabled in Windows 10 by default (at least it was on mine). Windows 8 users might want to adjust this setting.

September 17, 2012

AppDomain AppendPrivatePath [obsolete]

Have you ever tried to append a private path to your default AppDomain using .NET 4.0? Well this worked for a long time without getting any warnings
AppDomain.CurrentDomain.AppendPrivatePath("plugins");
For some security reasons this method has been set obsolete and should not be used anymore. I found much posts on the internet regarding this issue but almost every post demonstrated how to create a new AppDomain using the AppDomainSetup where the PrivateBinPath can be set easily.

Well I don't want to create a new AppDomain but use the default AppDomain and append a private path. Today I found a solution to this problem which can be solved easily through the application configuration file.
<configuration> <!-- ... --> <runtime> <assemblybinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatepath="plugins;otherFolder;more"></probing> </assemblybinding> </runtime> <!-- ... --> </configuration>

September 15, 2012

WP7: Changing the Windows Live ID without loosing anything

Hey folks!

Background
I think I'm not the only one who created a cool email address Windows Live ID which is associated to an anime or comic character. As I got older I wanted to start using my real name which can be useful when applying for a job etc.

Well, I created a new Windows Live ID and started using it for everything - except my Xbox Live account was still connected to my old email address. And that's the point. When I bought my Windows Phone 7 I associated it with the Windows Live ID which was connected to my Xbox Live account - the old one.

In the end I wanted my Xbox Live account being associated to my new Windows Live ID which I want to use on my Windows Phone. After some investigation I found out how I was able to do that without lossing anything. I kept my applications and games I purchased as well as all Microsoft Points!

Now let's re-associate our Xbox Live account and finally change the Windows Live ID on our Windows Phone!


Solution
prereq
1) Xbox
2) Windows Phone 7 + Connection Cable for your PC/Notebook
3) Internet Connection
4) Patience

September 1, 2012

Abstract Language

Today a friend asked me how to create a German and a separated English abstract in LaTeX. Sure, you would say: Just write one abstract in German and the other one in English, where is the problem? Well that was not the problem. The problem was that LaTeX did always print "Zusammenfassung" (which is the German word for "Abstract") for both, the German and English version when using the abstract command:
\begin{abstract}
Long story short, it's very easy to use another language for all your commands - in case the requested language is installed.
\begin{abstract} Das ist meine Kurz- oder Zusammenfassung auf Deutsch... \end{abstract} \begin{otherlanguage}{english} \begin{abstract} This is my abstract written in English... \end{abstract} \end{otherlanguage}
Last make sure you defined you languages correctly in your main document as shown below
\usepackage[english,ngerman]{babel}
You see, only one additional command is necessary to accomplish this task.

August 30, 2012

C# Office Communication without COM Reference

Lately I needed to communicate with Microsoft Word from C#. Well most programmers would use a reference to the COM library which is provided by Microsoft. For some reasons I don't want to use these libraries. One reason is the version problem. Let's say I'm linking the COM library which was implemented for MS Word 2007 and use it's interfaces etc. I won't be able to run this program on a machine having MS Word 2003 or MS Word 2010 installed. To keep the whole story short, I'd like to show you a way how you can communicate with Microsoft Office without linking the COM libraries. The following sample shows how to search for a specific string in a Word document. Because I don't want to break the explanation of how the code works, I'll just post all DllImports, interface and class declarations here.
static readonly Guid IID_IDispatch=new Guid("{00020400-0000-0000-C000-000000000046}"); [Guid("00020962-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IWordWindow { } [DllImport("oleacc.dll")] public static extern int AccessibleObjectFromWindow(IntPtr hwnd, uint dwObjectID, byte[] riid, out IWordWindow ptr); [DllImport("user32.dll")] public static extern int BringWindowToTop(IntPtr hwnd); [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow); [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd); [DllImport("user32.dll")] public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); public delegate bool EnumChildCallback(IntPtr hwnd, ref IntPtr lParam); [DllImport("user32.dll")] public static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildCallback lpEnumFunc, ref IntPtr lParam);
The interface IWordWindow is the IDispatch COM interface for the Word COM object. If you want to use another Office Program, you'll have to adapt the Guid attribute (see MSDN). First of all we need the process of Word

August 1, 2012

C# File OpenAs Dialog (Win7)

Some time ago I ran into something weird. These lines of code worked perfectly the last years in order to show the open as dialog on Windows XP but stopped working on my x64 Windows 7 machine (it would have stopped working in Vista too, but I skipped this version).
ProcessStartInfo startInfo=new ProcessStartInfo() { WindowStyle=ProcessWindowStyle.Normal, FileName=fileName, Verb="openas", UseShellExecute=true, ErrorDialog=true, }; p=Process.Start(startInfo);
Well to solve this issue I needed to check how the system used to show the open as dialog. As a result, I ended up with this line of code which brings up the open as dialog as usual.
p=Process.Start("rundll32.exe", string.Format("shell32,OpenAs_RunDLL \"{0}\"", fileName));
By the way, you'll need both versions if you want that your application works on Windows XP and later versions. This line indicates whether the application is running on Windows Vista or later.
Environment.OSVersion.Platform==PlatformID.Win32NT && Environment.OSVersion.Version>=new Version(6, 0, 6000);

March 16, 2012

Skype [beta] for WP7

I was wondering where I can download Skype beta for my Windows Phone 7 but I just couldn't find it in the Windows Phone Marketplace. Well, if you are searching for it too, use this direkt link on your WP7 :-)
zune://navigate/?appid=c3f8e570-68b3-4d6a-bdbb-c0a3f4360a51
I found this link somewhere on the skype website - but very very hidden.

January 19, 2012

IntPtr Navigation

Have you ever wrote something like that?
IntPtr ptr=...
Marshal.PtrToStringUni((IntPtr)(ptr.ToInt32()+wDeviceOffset));

Such code is often necesary when invoking the Win32 API. Well this code works well unless you're not running this code on a x64 machine.
When running on a x64 machine you might get a nasty surprise as soon as the pointer's address is above int.MaxValue. To fix this problem you might use the following code.
IntPtr ptr=...
Marshal.PtrToStringUni(IntPtr.Add(ptr, wDeviceOffset));

There also exists a static Subtract method which let's you decrease the pointer's address.

January 10, 2012

Random <> Random

Yes, Random is not Random at all. The Random class in .NET gives you the functionality to produce random numbers. Anyway how is randomness being calculated? There are plenty of factors used for calculating a new random number. To read a little more, checkout the documentation on MSDN.
Even though the documentation recommends creating just one instance of the Random class and using this instead of creating a new instance every time you need one.
You don't think this is necessary? Well let's just do a simple experiment:

We will now create random numbers. Both snippets use a simple generic list of integers.
var items=new List<int>();

The first snippet creates a new instance of the Random type on each call. I also want to highlight that the loop will run 10.000 times creating random numbers from 1 to 30.
for (int i=0; i<10000; i++)
  items.Add(new Random().Next(1, 30));

The second snippet only creates one instance and reuses it on each call.
Random rnd=new Random();
for (int i=0; i<10000; i++)
  items.Add(rnd.Next(1, 30));

To get the results, we use a StringBuilder object and just write the distinct numbers into it
var sb=new StringBuilder();
foreach (var i in items.Distinct().OrderBy(x => x))
  sb.AppendFormat("{0},", i);
Console.WriteLine("Nums: {0}", sb.ToString());

Now, let's have a look at the results:
The first style returned the following output
3,6,11,16,22,28,

The second style this output
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,

So now you see that using the first style really doesn't provide random numbers. Only 6 numbers out of 30 have been used!
On the opposite the second style seems to return usable random numbers - all numbers have been used.

December 16, 2011

LaTeX Custom Bibliography Sorting

I'm currently writing a specialized paper to gain a bachelor's degree in Computer Science. The most painful part of writing was to sort the references which are stored in a bibliography using LaTeX.

I don't know whether I made a mistake or the sort styles just don't support ordering by the author's first name. Nevertheless here is a solution if you step into problems when sorting your references doesn't work like you'd expect :-)

First turn off sorting in your main .tex file
\bibliographystyle{unsrt}

When applying this, LaTeX will sort your references by its usage. So the reference used first, will be listed first. You turn this into an advantage. Now within your document, before you use any references in your paper, use this line for hidden text to apply your custom sorting.
\phantom
{
\cite{FirstRef}
\cite{SecondRef}
\cite{ThirdRef}
...
}

The only disadvantage you have to be aware of is that from now on you have to take care which references are really used in your paper to not reference anything unused.

Anyway this solution works good for me - if you know any better solution to this problem, please don't hesitate to write a comment :)

December 13, 2011

How to P/Invoke PrintDlg (x86 & x64)

Do you know the PrintDlg function?

Well, it shows a Print Dialog and also allows the user to setup printer options which are stored in hDevMode and hDevNames. Long story short, this function has been used in C++ and I now need this function in a C# library which has been ported from an equivilant C++ library.

PrintDlg worked fine using this method signature:
[DllImport("comdlg32.dll", CharSet=CharSet.Auto)]
static extern bool PrintDlg([In, Out] PRINTDLG lppd);

And the definition of the PRINTDLG structure (yes, it's defined as a class, not as struct because struct is not a reference type as it is used here) as the following:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto, Pack=1)]
class PRINTDLG
{
  public Int32 lStructSize;
  public IntPtr hwndOwner;
  public IntPtr hDevMode;
  public IntPtr hDevNames;
  public IntPtr hDC=IntPtr.Zero;
  public Int32 Flags;
  public Int16 FromPage=0;
  public Int16 ToPage=0;
  public Int16 MinPage=0;
  public Int16 MaxPage=0;
  public Int16 Copies=0;
  public IntPtr hInstance=IntPtr.Zero;
  public IntPtr lCustData=IntPtr.Zero;
  public IntPtr lpfnPrintHook;
  public IntPtr lpfnSetupHook=IntPtr.Zero;
  public IntPtr lpPrintTemplateName=IntPtr.Zero;
  public IntPtr lpSetupTemplateName=IntPtr.Zero;
  public IntPtr hPrintTemplate=IntPtr.Zero;
  public IntPtr hSetupTemplate=IntPtr.Zero;
}

Now, if you are running your C# application under x86, you can use these lines of code to make the Print Dialog appear
PRINTDLG pd=new PRINTDLG();
pd.lStructSize=Marshal.SizeOf(pd);
PrintDlg(pd);

Nevertheless this won't work when running the same code on a x64 machine - the Print Dialog just won't show up and the function returns 0 which just means "failure".

Let's check that out. After some time I started to check the struct size in the C++ code, where it actually worked - also on x64. When I counted the bytes of the PRINTDLG structure I got 66 bytes on x86 architecture. Also the sizeof(pd) returned 66 bytes. OK, you now think this is boring because on x64 it would just be the same too.
I counted 114 bytes. But sizeof(pd) returned 120 bytes. So a difference of 6 bytes which causes the PrintDlg to fail because in my C# application the Marshal.SizeOf(pd) also returned 114 bytes which is not equal to 120 bytes.

Did you notice the Pack=1 in the StructLayout attribute?
You can find the definition on MSDN.
To keep it simple, this parameter tells the compiler how the structure should be aligned in memory. After playing a little with this setting, I found out that Pack=8 is required for the PRINTDLG structure to work under x64.
We are nearly finished, but we got one problem left. Since we wan't the class library to run either on x86 and x64 we would need to specify the Pack value depending on the current processor's architecture. We are out of luck here when trying to set the Pack to the IntPtr.Size. So what we need now is a wrapper.

First define the same structure as above one more time and name it PRINTDLGx64 and set the Pack=8. Also create another method signature for PrintDlg accepting the PRINTDLGx64 structure as input.

The wrapper should look like that:
class PrintDlgWrap
{
  PRINTDLG dlg;
  PRINTDLGx64 dlg64;

  public static readonly bool Is64Bit;

  static PrintDlgWrap()
  {
    Is64Bit=IntPtr.Size==8;  // this works for .net 3.5 and 4.0
  }

  public PrintDlgWrap()
  {
    if (Is64Bit)
    {
      dlg64=new PRINTDLGx64();
      dlg64.lStructSize=Marshal.SizeOf(dlg64);
    }
    else
    {
      dlg=new PRINTDLG();
      dlg.lStructSize=Marshal.SizeOf(dlg);
    }
  }

  public int lStructSize { get { return Is64Bit?dlg64.lStructSize:dlg.lStructSize; } }
  public int Flags { get { return Is64Bit?dlg64.Flags:dlg.Flags; } set { if (Is64Bit) dlg64.Flags=value; else dlg.Flags=value; } }
  // ...

  public PRINTDLG Getx86() { return dlg; }
  public PRINTDLGx64 Getx64() { return dlg64; }
}

And now you just create an instance of this wrapper in your class and use the properties to access the PRINTDLG's fields which has been created in the constructor depending on the processor's architecture :)

All you need now to call the print dialog are the following lines
PrintDlgWrap dp=new PrintDlgWrap();
if (PrintDlgWrap.Is64Bit) PrintDlg(pd.Getx64());
else PrintDlg(pd.Getx86());

Hope you liked my first post and feel free to post comments :)

Welcome

Welcome to my blog!

I'm a software developer from Austria working mostly with C# and sometimes C++. I've started this blog to share my knowledge in C# and C++ (mostly p/invoke issues). What you can expect is green code - so well written code and algorithms :-)

I'm looking forward to my first post and hopefully many comments.