My online notes – Section 0006

Note 1: Sony Ericsson PC Suite for Z610i
http://www.megaupload.com/?d=V7II5C41

Note 2: Set autostart for program

private Boolean SchreibeinAutostart( String dateipfad )
{
    try
    {
        String samAccountName;
        {
            var currentWindowsIdentity = WindowsIdentity.GetCurrent( );
            if ( currentWindowsIdentity == null )
            {
                return false;
            }

            samAccountName = currentWindowsIdentity.Name;
        }

        var registrySecurity = new RegistrySecurity( );
        {
            registrySecurity.AddAccessRule( new RegistryAccessRule( samAccountName,
                    RegistryRights.WriteKey | RegistryRights.ChangePermissions, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow ) );
        }

        var targetRegistryKey = Registry.CurrentUser.CreateSubKey( "Software\\Microsoft\\Windows\\CurrentVersion\\Run\\" );

        if ( targetRegistryKey == null )
        {
            return false;
        }

        targetRegistryKey.SetValue( dateipfad.Remove( 0, dateipfad.LastIndexOf( @"\" ) + 1 ), dateipfad );

    }
    catch ( Exception )
    {
        return false;
    }

    return true;
}

Note 3: Insert DatePickerContentControl into table of Word

r.Cells[1].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlDate);

Note 4: Creating Shell Extension Handlers
http://msdn.microsoft.com/en-us/library/windows/desktop/cc144067%28v=vs.85%29.aspx

Note 5: Portable Class Libraries
http://msdn.microsoft.com/en-us/library/gg597391.aspx

Note 6: Create zip file with Shel32

– Add reference to “Microsoft Shell Controls and Automation” at COM-Tab

private static void Main(string[] args)
{
	string sourceFolder = @"D:\Temp";
	string fileZip = @"D:\Temp.zip";
	byte[] emptyzip = new byte[] { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	FileStream fs = File.Create(fileZip);
	fs.Write(emptyzip, 0, emptyzip.Length);
	fs.Flush();
	fs.Close();
	fs = null;

	Shell32.ShellClass sc = new Shell32.ShellClass();
	Shell32.Folder destFolder = sc.NameSpace(fileZip);

	int totalFiles = Directory.GetFiles(sourceFolder).Length;
	int index = 0;
	foreach (string fileName in Directory.GetFiles(sourceFolder))
	{
		index += 1;
		destFolder.CopyHere(fileName, 20);
		while (destFolder.Items().Count < index)
			System.Threading.Thread.Sleep(100);
	}
	Console.WriteLine("Finished");
	Console.ReadLine();
}

Note 7: Run a programm on wake up event
Declaration:

/// <summary>
/// This function starts running an application when a specified event occurs.
/// </summary>
///  <param name="application">The application. eg: @"\Program Files\testapp\testapp.exe"</param>
///  <param name="notificationEvent">Event at which the application is to be started. Use 'NotificationEvent' enum to get values.</param>
///  <returns>TRUE indicates success. FALSE indicates failure.</returns>
[DllImport("coredll.dll", SetLastError = true)]
public static extern int CeRunAppAtEvent(
            string application,
            NotificationEvent notificationEvent);

///  <summary>
/// Enum used in the "CeRunAppAtEvent" native method
/// </summary>
public enum NotificationEvent
{// Commented values are not common to all devices
    None = 0,
    TimeChange = 1,
    SyncEnd = 2,
    //START = 3,
    //SHUTDOWN = 4,
    //NETCONNECT = 5,
    //NETDISCONNECT=  6,
    DeviceChange = 7,
    RS232DEtected = 9,
    ResotreEnd = 10,
    Wakeup = 11,
    TimeZoneChange = 12,
    //MachineNameChange = 13
}

Usage:

string kioskApplication = @"\Program Files\testapp\testapp.exe";
Win32.CeRunAppAtEvent(kioskApplication, NotificationEvent.Wakeup);

Note 8: Read big .csv file
Use ReadLine to read line by live and split string to “;” then map to object. That’s the fastest way.

Note 9: NullSafe extensions

public static class NullSafeExtensions
{
    /// <summary>
    /// Tests for null/empty strings without re-computing values or assigning temporary variables
    /// </summary>
    /// <typeparam name="TResult">resulting type of the expression</typeparam>
    /// <param name="check">value to check for null</param>
    /// <param name="valueIfNotNullOrEmpty">delegate to compute non-null value</param>
    /// <returns>null if check is null, the delegate's results otherwise</returns>
    public static TResult CheckNullOrEmpty<TResult>(this string check, Func<string, TResult> valueIfNotNullOrEmpty)
        where TResult : class
    {
        return string.IsNullOrEmpty(check) ? null : valueIfNotNullOrEmpty(check);
    }
    /// <summary>
    /// Tests for null/empty collections without re-computing values or assigning temporary variables
    /// </summary>
    /// <typeparam name="TResult">resulting type of the expression</typeparam>
    /// <typeparam name="TCheck">type of collection or array to check</typeparam>
    /// <param name="check">value to check for null</param>
    /// <param name="valueIfNotNullOrEmpty">delegate to compute non-null value</param>
    /// <returns>null if check is null, the delegate's results otherwise</returns>
    public static TResult CheckNullOrEmpty<TCheck, TResult>(this TCheck check, Func<TCheck, TResult> valueIfNotNullOrEmpty)
        where TCheck : ICollection
        where TResult : class
    {
        return (check == null || check.Count == 0) ? null : valueIfNotNullOrEmpty(check);
    }

    /// <summary>
    /// Tests for null objects without re-computing values or assigning temporary variables.  Similar to
    /// Groovy's "safe-dereference" operator .? which returns null if the object is null, and de-references
    /// if the object is not null.
    /// </summary>
    /// <typeparam name="TResult">resulting type of the expression</typeparam>
    /// <typeparam name="TCheck">type of object to check for null</typeparam>
    /// <param name="check">value to check for null</param>
    /// <param name="valueIfNotNull">delegate to compute if check is not null</param>
    /// <returns>null if check is null, the delegate's results otherwise</returns>
    public static TResult NullSafe<TCheck, TResult>(this TCheck check, Func<TCheck, TResult> valueIfNotNull)
        where TResult : class
        where TCheck : class
    {
        return check == null ? null : valueIfNotNull(check);
    }
}
string s = h.MetaData
            .NullSafe(meta => meta.GetExtendedName())
            .NullSafe(s => s.Trim().ToLower())

Note 10: Table Excel to image

worksheet.UsedRange.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlPicture);

Note 11: Learn jQuery in 30 days
http://tutsplus.com/course/30-days-to-learn-jquery/

Note 12: Return detailed information of a terminal server

– Does the program run under terminal server?
– Environment
– Client Machine
– Client User
– Client Addr
– Client Family (for example AF_INET)
– Client Protocol (for example RDP)
– Client SessionID
– Domain Name

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace SomeNameSpace
{
    class TerminalServerSupport
    {
        private const int SM_REMOTESESSION = 0x1000;

        [DllImport("user32.dll", EntryPoint = ("GetSystemMetrics"))]
        private static extern bool GetSystemMetrics(int nIndex);

        /// <summary>
        /// Gibt den Domänennme zurück.
        /// </summary>
        public static string GetDomainName()
        {
            return SystemInformation.UserDomainName;
        }

        /// <summary>
        /// Gibt an, ob die Anwendung in einer Terminal Session läuft.
        /// </summary>
        public static bool IsTerminalService()
        {
            return SystemInformation.TerminalServerSession;
        }

        /// <summary>
        /// Gibt den angemeldeten Benutzername zurück.
        /// </summary>
        public static string GetUserName()
        {
            return SystemInformation.UserName;
        }

        /// <summary>
        /// Gibt die aktuelle Session ID zurück.
        /// </summary>
        public static string GetSessionID()
        {
            return Process.GetCurrentProcess().SessionId.ToString();
        }

        /// <summary>
        /// Gibt den Maschinenname des Client Systems zurück.
        /// </summary>
        public static string GetClientMachineName()
        {
            IntPtr ptrBuffer = IntPtr.Zero;

            string szClientName = string.Empty;
            int nBytesReturned = 0;

            bool bSuccess = WTSMethods.WTSQuerySessionInformation(
                WTSMethods.WTS_CURRENT_SERVER_HANDLE,
                WTSMethods.WTS_CURRENT_SESSION,
                WTSMethods.WTS_INFO_CLASS.WTSClientName,
                out ptrBuffer,
                out nBytesReturned);

            if (bSuccess)
            {
                szClientName = Marshal.PtrToStringUni(
                    ptrBuffer,
                    nBytesReturned / 2 // Weil der DllImport CharSet.Unicode benutzt
                    );
                WTSMethods.WTSFreeMemory(ptrBuffer);
                int nIndexOfESC = szClientName.LastIndexOf('\0');
                if (nIndexOfESC != -1)
                {
                    szClientName = szClientName.Substring(0, szClientName.Length - 1);
                }
            }

            return szClientName;
        }

        /// <summary>
        /// Gibt das Protocol der Verbindung an.
        /// </summary>
        public static string GetClientProtocol()
        {
            IntPtr ptrBuffer = IntPtr.Zero;

            short nProtocol = -1;
            string szProtocol = string.Empty;
            int nBytesReturned = 0;

            bool bSuccess = WTSMethods.WTSQuerySessionInformation(
                WTSMethods.WTS_CURRENT_SERVER_HANDLE,
                WTSMethods.WTS_CURRENT_SESSION,
                WTSMethods.WTS_INFO_CLASS.WTSClientProtocolType,
                out ptrBuffer,
                out nBytesReturned);

            if (bSuccess)
            {
                nProtocol = Marshal.ReadInt16(ptrBuffer);
                switch (nProtocol)
                {
                    case WTSMethods.WTS_PROTOCOL_TYPE_CONSOLE:
                        szProtocol = "Console";
                        break;
                    case WTSMethods.WTS_PROTOCOL_TYPE_ICA:
                        szProtocol = "ICA";
                        break;
                    case WTSMethods.WTS_PROTOCOL_TYPE_RDP:
                        szProtocol = "RDP";
                        break;
                    default: szProtocol = "No WTS";
                        break;
                }

                WTSMethods.WTSFreeMemory(ptrBuffer);
            }


            return szProtocol;
        }

        /// <summary>
        /// Gibt an in welcher Umgebung die Anwendung läuft.
        /// (Remote oder Console)
        /// </summary>
        public static string GetEnviroment()
        {
            if (GetSystemMetrics(SM_REMOTESESSION))
            {
                return "Remote"; // remote
            }
            else
            {
                return "Console"; // console
            }
        }

        /// <summary>
        /// Gibt die IP-Adresse und die Family des Client Systems zurück.
        /// </summary>
        /// <param name="szAdressFamily">Gibt die Adressfamilie zurück</param>
        public static string GetClientIPAdress(out string szAdressFamily)
        {
            IntPtr pServer = IntPtr.Zero;
            IntPtr pAddress = IntPtr.Zero;
            int nReturned = 0;
            string szIPAddress = string.Empty;

            WTSMethods.WTS_CLIENT_ADDRESS clientAddress = new WTSMethods.WTS_CLIENT_ADDRESS();

            if (WTSMethods.WTSQuerySessionInformation(pServer, WTSMethods.WTS_CURRENT_SESSION, WTSMethods.WTS_INFO_CLASS.WTSClientAddress, out pAddress, out nReturned) == true)
            {
                clientAddress = (WTSMethods.WTS_CLIENT_ADDRESS)Marshal.PtrToStructure(pAddress, clientAddress.GetType());
                szIPAddress = clientAddress.baAddress[2] + "." + clientAddress.baAddress[3] + "." + clientAddress.baAddress[4] + "." + clientAddress.baAddress[5];
            }
            szAdressFamily = ((WTSMethods.AddressFamily)clientAddress.nAddressFamily).ToString();
            return szIPAddress;
        }
    }

    internal static class WTSMethods
    {
        internal static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
        internal const int WTS_CURRENT_SESSION = -1;
        internal const int WTS_PROTOCOL_TYPE_CONSOLE = 0;
        internal const int WTS_PROTOCOL_TYPE_ICA = 1;
        internal const int WTS_PROTOCOL_TYPE_RDP = 2;

        internal enum AddressFamily
        {
            AF_UNSPEC = 0,  //(unspecified)
            AF_INET    = 2, //(internetwork: UDP, TCP, etc.)
            AF_IPX     = 6, // = AF_NS (IPX protocols: IPX, SPX, etc.)
            AF_NETBIOS = 17 //(NetBios-style addresses)
        }

        internal enum WTS_INFO_CLASS
        {
            WTSClientName = 10,
            WTSClientAddress = 14,
            WTSClientProtocolType = 16
        }

        //Structure for Terminal Service Client IP Address
        [StructLayout(LayoutKind.Sequential)]
        internal struct WTS_CLIENT_ADDRESS
        {
            public int nAddressFamily;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
            public byte[] baAddress;
        }

        [DllImport("Wtsapi32.dll", CharSet = CharSet.Unicode)]
        internal static extern bool WTSQuerySessionInformation(
            IntPtr hServer,
            Int32 sessionId,
            WTS_INFO_CLASS wtsInfoClass,
            out IntPtr ppBuffer,
            out Int32 pBytesReturned);

        /// <summary>
        /// The WTSFreeMemory function frees memory allocated by a Terminal
        /// Services function.
        /// </summary>
        /// <param name="memory">Pointer to the memory to free.</param>
        [DllImport("wtsapi32.dll", ExactSpelling = true, SetLastError = false)]
        internal static extern void WTSFreeMemory(IntPtr memory);
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *