Joonas Kirsebom
- The World From A Kirsebom Perspective

If you need to drop users to certain resources on your computer, have a look at this example.

using System.Runtime.InteropServices;
using Interop.NetAPI32;

namespace MySerie_Commons
{
        public class ConnectionShare
        {
                public int id;
                public int numLocks;
                public string path;
                public string username;

                public ConnectionShare(int id, int numLocks, string path, string username)
                {
                        this.id = id;
                        this.numLocks = numLocks;
                        this.path = path;
                        this.username = username;
                }

                public static List<ConnectionShare> BuildConnectionShareList()
                {
                        List<ConnectionShare> list = new List<ConnectionShare>();
                        const int MAX_PREFERRED_LENGTH = -1;

                        int dwReadEntries;
                        int dwTotalEntries;
                        IntPtr pBuffer = IntPtr.Zero;
                        NetAPI.FILE_INFO_3 pCurrent = new NetAPI.FILE_INFO_3();

                        NetAPI.NET_API_STATUS dwStatus = NetAPI.NetFileEnum
                                                                                        (
                                                                                                "localhost",
                                                                                                null,
                                                                                                null,
                                                                                                3,
                                                                                                ref pBuffer,
                                                                                                MAX_PREFERRED_LENGTH,
                                                                                                out dwReadEntries,
                                                                                                out dwTotalEntries,
                                                                                                IntPtr.Zero
                                                                                        );

                        if (dwStatus == NetAPI.NET_API_STATUS.NERR_Success)
                        {
                                for (int dwIndex = 0; dwIndex < dwReadEntries; dwIndex++)
                                {
                                        IntPtr iPtr = new IntPtr(pBuffer.ToInt32() + (dwIndex * Marshal.SizeOf(pCurrent)));
                                        pCurrent = (NetAPI.FILE_INFO_3)Marshal.PtrToStructure(iPtr, typeof(NetAPI.FILE_INFO_3));

                                        list.Add(new ConnectionShare(pCurrent.fi3_id, pCurrent.fi3_num_locks, pCurrent.fi3_pathname, pCurrent.fi3_username));
                                }
                                NetAPI.NetApiBufferFree(pBuffer);
                        }

                        return list;
                }
        }
}
 

and this class:

using System;
using System.Runtime.InteropServices;

namespace Interop.NetAPI32
{
        public class NetAPI
        {
                public const int MAX_PREFERRED_LENGTH = -1;

                public enum NET_API_STATUS:uint
                                {
                                        NERR_Success = 0,

                                        /// <summary>
                                        /// This computer name is invalid.
                                        /// </summary>
                                        NERR_InvalidComputer = 2351,

                                        /// <summary>
                                        /// This operation is only allowed on the primary domain controller of the domain.
                                        /// </summary>
                                        NERR_NotPrimary = 2226,

                                        /// <summary>
                                        /// This operation is not allowed on this special group.
                                        /// </summary>
                                        NERR_SpeGroupOp = 2234,

                                        /// <summary>
                                        /// This operation is not allowed on the last administrative account.
                                        /// </summary>
                                        NERR_LastAdmin = 2452,

                                        /// <summary>
                                        /// The password parameter is invalid.
                                        /// </summary>
                                        NERR_BadPassword = 2203,

                                        /// <summary>
                                        /// The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements.
                                        /// </summary>
                                        NERR_PasswordTooShort = 2245,

                                        /// <summary>
                                        /// The user name could not be found.
                                        /// </summary>
                                        NERR_UserNotFound = 2221,
                                       
                                        ERROR_ACCESS_DENIED = 5,
                                        ERROR_NOT_ENOUGH_MEMORY = 8,
                                        ERROR_INVALID_PARAMETER = 87,
                                        ERROR_INVALID_NAME = 123,
                                        ERROR_INVALID_LEVEL = 124,
                                        ERROR_MORE_DATA = 234 ,
                                        ERROR_SESSION_CREDENTIAL_CONFLICT = 1219
                                }

                [DllImport("Netapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
                public static extern NET_API_STATUS NetFileEnum
                                                        (
                                                                string servername,
                                                                string basepath,
                                                                string username,
                                                                int level,
                                                                ref IntPtr bufptr,
                                                                int prefmaxlen,
                                                                out int entriesread,
                                                                out int totalentries,
                                                                IntPtr resume_handle
                                                        );

                [DllImport("Netapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)]
                public static extern int NetFileClose(string servername, int id);

                [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
                public struct FILE_INFO_3
                                        {
                                                public int fi3_id;
                                                public int fi3_permission;
                                                public int fi3_num_locks;
                                                [MarshalAs(UnmanagedType.LPWStr)]
                                                public string fi3_pathname;
                                                [MarshalAs(UnmanagedType.LPWStr)]
                                                public string fi3_username;
                                        }

                [StructLayout( LayoutKind.Sequential )]
                public struct SESSION_INFO_502
                {
                        /// <summary>
                        /// Unicode string specifying the name of the computer that established the session.
                        /// </summary>
                        [MarshalAs(UnmanagedType.LPWStr)]
                        public string si502_cname;

                        /// <summary>
                        /// <value>Unicode string specifying the name of the user who established the session.</value>
                        /// </summary>
                        [MarshalAs(UnmanagedType.LPWStr)]
                        public string si502_username;

                        /// <summary>
                        /// <value>Specifies the number of files, devices, and pipes opened during the session.</value>
                        /// </summary>
                        public uint si502_num_opens;

                        /// <summary>
                        /// <value>Specifies the number of seconds the session has been active. </value>
                        /// </summary>
                        public uint si502_time;

                        /// <summary>
                        /// <value>Specifies the number of seconds the session has been idle.</value>
                        /// </summary>
                        public uint si502_idle_time;

                        /// <summary>
                        /// <value>Specifies a value that describes how the user established the session.</value>
                        /// </summary>
                        public uint si502_user_flags;

                        /// <summary>
                        /// <value>Unicode string that specifies the type of client that established the session.</value>
                        /// </summary>
                        [MarshalAs(UnmanagedType.LPWStr)]
                        public string si502_cltype_name;

                        /// <summary>
                        /// <value>Specifies the name of the transport that the client is using to communicate with the server.</value>
                        /// </summary>
                        [MarshalAs(UnmanagedType.LPWStr)]
                        public string si502_transport;
                }

                [DllImport("netapi32.dll", SetLastError=true)]
                public static extern int NetSessionEnum
                                                (
                                                        [In,MarshalAs(UnmanagedType.LPWStr)]
                                                        string ServerName,
                                                        [In,MarshalAs(UnmanagedType.LPWStr)]
                                                        string UncClientName,
                                                        [In,MarshalAs(UnmanagedType.LPWStr)]
                                                        string UserName,
                                                        Int32 Level,
                                                        out IntPtr bufptr,
                                                        int prefmaxlen,
                                                        ref Int32 entriesread,
                                                        ref Int32 totalentries,
                                                        ref Int32 resume_handle
                                                );

                [DllImport("Netapi32.dll", SetLastError=true)]
                public static extern int NetApiBufferFree(IntPtr Buffer);

                [DllImport("kernel32.dll", EntryPoint="GetLastError", CallingConvention=CallingConvention.StdCall, SetLastError=true)]
                public static extern uint GetLastError();       //Recommended use:Marshal.GetLastWin32Error !!

                [DllImport("kernel32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
                private static extern uint FormatMessage
                                                (
                                                        uint dwFlags,
                                                        IntPtr lpSource,
                                                        uint dwMessageId,
                                                        uint dwLanguageId,
                                                        ref string lpBuffer,
                                                        uint nSize,
                                                        IntPtr Arguments
                                                );

                public static string GetErrorMessage(uint errorCode)
                {
                        /*
                        Purpose:        GetErrorMessage formats and returns an error message corresponding to the input errorCode.
                        See:            http://pinvoke.net/default.aspx/kernel32.FormatMessage
                        */

                        uint FORMAT_MESSAGE_ALLOCATE_BUFFER     = 0×00000100;
                        uint FORMAT_MESSAGE_IGNORE_INSERTS      = 0×00000200;
                        uint FORMAT_MESSAGE_FROM_SYSTEM         = 0×00001000;
                        //uint FORMAT_MESSAGE_ARGUMENT_ARRAY    = ????

                        uint messageSize = 255;
                        string lpMsgBuf = "";
                        uint dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;

                        IntPtr ptrlpSource = IntPtr.Zero;
                        IntPtr prtArguments = IntPtr.Zero;
                       
                        uint retVal = FormatMessage(dwFlags, ptrlpSource, errorCode, 0, ref lpMsgBuf, messageSize, prtArguments);
                        if (retVal == 0)
                        {
                                throw new Exception("Failed to format message for error code " + errorCode + ".");
                        }

                        return lpMsgBuf;
                }
        }
}
 

And the code for running a demo:

public static void closeConnectionToPath(string path)
{
        List<ConnectionShare> connections = ConnectionShare.BuildConnectionShareList();
        IEnumerator myEnumerator = connections.GetEnumerator();
        while (myEnumerator.MoveNext())
        {
                NetAPI.NetFileClose("localhost", ((ConnectionShare)myEnumerator.Current).id);
        }
}
 

Thanks to Manfred Braun for helping me out with this problem.

Tags: ,

I have tried to have my PC in sleep mode during nights, but every time I woke up i found that my machine was running. Something had waked my machine from sleeping.

To find process which was waking my PC was fairly simple. Just start cmd in “administrator mode” and type “powercfg -lastwake”, it will show you the process which started the PC.

In my case it was Media Center and the task can be found “Task Scheduler Library\Microsoft\Windows\MediaCenter\” and the task named “mcupdate_scheduled”. Just remove the check “Wake the computer to run this task”.

Related Posts

  • No Related Post

It happens to me often that the TV-out, s-video, only has black and white color on the screen. It happens each time I install a new nVidia driver, and I always forget what is the problem. It often takes me long time to find what I have to do, to fix the problem.

The problem in the new drivers (my: 258.96) is that the Digital Vibrance value is default 0, when it should be something else. Try to set it to 50 in you nVidia Control Panel for your TV.

Hope this helps you.

Related Posts

  • No Related Post
Tags:

Ti kamerater spiste middag sammen på restaurant hver dag. Regningen kom alltid på 1.000 kroner totalt.

Siden det var stor forskjell i inntekt og formue hos de ti, ble de enige om å dele regningen på samme måte som skattesystemet. De fire fattige slapp å betale. Den femte betalte kr. 10, den sjette kr. 30, den syvende kr. 70, den åttende kr. 120, den niende kr. 180 og den tiende og rikeste skulle betale kr. 590.

Alle var fornøyd med ordningen inntil restauranteieren en dag tilbød dem rabatt. De var stedets beste kunder, så han tilbød et avslag på kr. 200,- per middag. Fortsatt ville gruppen dele regningen etter skattemodellen, så de fire fattigste skulle ikke betale. Spørsmålet var hva som skulle skje med de seks andre, hvordan skulle rabatten fordeles?

Kr. 200 delt på seks ble kr. 33,33 i avslag. Det betød at person fem og seks ville få betalt for å spise, og det var klart urimelig. Restauranteieren foreslo å redusere regningen omlag likt for alle, og ville utarbeide et forslag. Det innebar at også den femte fikk spise gratis, og den sjette skulle betale kr. 20, den syvende kr. 50, den åttende kr. 90, den niende kr. 120, mens den rikeste fikk redusert regningen fra kr. 590 til kr. 520. Alle fikk lavere pris og ingen kom dårligere ut enn før.

Utenfor restauranten begynte de imidlertid å sammenligne hva de hadde spart.

Jeg sparte bare en tier, mens han sparte kr. 70 sa sjettemann og pekte på den rike tiendemannen.

Akkurat, sa femtemann, som også fikk kr. 10 i avslag. Han er rik, men fikk likevel syv ganger så mye som jeg. Hvorfor skal de rike alltid få mest, ropte den syvende, som fikk kr. 20 i rabatt. Og vi fikk jo ingenting, ropte de fire fattigste i kor. Dette systemet utnytter de fattigste.

Stemningen ble rask så hatsk at de ni banket opp tiendemann. Neste kveld kom han ikke på middagen, så de spiste uten ham.

Da regningen kom oppdaget de noe enda viktigere. Det manglet 520 kroner.

Kilde: debatt på dn.no

Related Posts

  • No Related Post

I have made my first application for N900, and its possible to download it if you want to try it.

The application will download data about the water temperatures in the Oslo area, and show them to you in a list. You can additionally get details about the beach just by pushing the *-button. I till open the browser with additional information.

Download Oslobadetemp-0.1 here.

Tags: ,

The mighty N900 gets an update. I have waited a long time for this, and finally it is coming :)

It starts today with UK, and the rest of the world tomorrow.

http://conversations.nokia.com/2010/05/25/nokia-n900-software-update-release-1-2/

Tags:

The Visual Studio 2010 where launched some weeks ago, and as a user of VS2009 I really wanted to try the new version. I downloaded it from msdn, and installed it. I really like the new look of Visual Studio. But I have to admit that I haven’t used it much, because of the the Media Center SDK is not fully supporting VS2010 yet. So I will be waiting for the next MC SDK update before I will move my development over to VS2010.

So, to you all that are developing Media Center application I will suggest you wait for a new SDK version before you swap to VS2010.

I don’t know when the next version of MC SDK is coming out, but the version which is out today is SDK6 (8/19/2009).

I have been quite unhappy with the lack of support for launch conditions on 64bit applications. I used Visual Studio 2008 for a long time with this problem. I hoped that Microsoft would fix this problem when they released Visual Studio 2010, but as I can see, they have not done anything with this problem.

UPDATE v2

New version uploaded here (msi64v2).

The new version allows you to have multiple Registry Searches in Launch Conditions. It will also allow you to differ between 64bit and 32 bit searches.

All you have to do is to name your 64bit Registry Searches so they are ending on “_X64″. Ex SERVICEINSTALLED_X64.

Put msi64v2 file in your solution(!) folder. Open your solution explorer and find your Setup and Deployment (x64) project. Find the property called PostBuildEvent and fill inn

"$(ProjectDir)..\msi64v2.js" "$(BuiltOuputPath)"

or

wscript.exe "$(ProjectDir)..\msi64v2.js" "$(BuiltOuputPath)"

and set RunPostBuildEvent to “On Successful build”.

Now you are ready to go :)

Old v1

After much googling i found a way to fix this efficiently. First you will need to download this JScript. Put this JScript in your Solution/Project directory.

You have to edit the .js file and search for “SERVICEINSTALLED”, change this name to your search property name.

Open your solution explorer and find your Setup and Deployment (x64) project. Find the property called PostBuildEvent and fill inn “..\..\msi64.js <output_file_x64>.msi” and set RunPostBuildEvent to “On Successful build”.

This will edit your msi file so it searches the x64 bit registry.

PS: if you got an error on compiling, the path might be wring, try only using ..\msi64.js

I have written a blog post about this earlier, but it only worked for the RC version. This is just an update so you can find the right url for the RTM version.

To enable multiple simultaneous users, follow this link.

Tags:

I got some problems with the map loader and the N900. The problem accur when using Windows 7 64bit. What is needed on the pc is:

Pc suite: http://www.nokia.no/support-og-programvare/programvare/nokia-pc-suites

Map Loader: http://www.nokiausa.com/get-support-and-software/product-support/maps-support/compatibility-and-download#/default/

If you get an error with the map loader when you have connected the N900, try this. This did the trick for me:

- Run terminal and type: cp /home/user/MyDocs/.qf /home/user/MyDocs/qf
- Connect the N900 to PC in PC Suite Mode
- Open Map Loader and load your maps!

Tags:

Powered by Wordpress
Theme © 2005 - 2009 FrederikM.de
BlueMod is a modification of the blueblog_DE Theme by Oliver Wunder