Category Archives: Windows 7

Microsoft Windows

Enable Claims Based on existing Web Application with Classic Mode (Access denied Error)

Recently i encountered a situation in which i need to enable the claim based authentication for the existing web application which has windows authentication. From the central administration there is no way or option to enable it. This can be achieved only by the powershell script.

$WebAppName = “http://yourWebAppUrl”
$wa = get-SPWebApplication $WebAppName
$wa.UseClaimsAuthentication = $true
$wa.Update()

The above code will enable the claims based authentication to the existing web application. But once enabled when try to Login the user might get Access Denied Error. This is because the users are stored in the different format in the claims based authentication.

Need to execute the below commands to migrate all the users from existing windows user to the claim based.

Warning: Once migrated it will change the user information in all the content databases. This change is permanent.

$account = “yourDomain\yourUser”
$account = (New-SPClaimsPrincipal -identity $account -identitytype 1).ToEncodedString()
$wa = get-SPWebApplication $WebAppName
$zp = $wa.ZonePolicies(“Default”)
$p = $zp.Add($account,”PSPolicy”)
$fc=$wa.PolicyRoles.GetSpecialRole(“FullControl”)
$p.PolicyRoleBindings.Add($fc)
$wa.Update()

$wa.MigrateUsers($true)
$wa.ProvisionGlobally()

Revert Back from Claims Authentication to Windows.

$WebAppName = “http://yourWebAppUrl”
$wa = get-SPWebApplication $WebAppName
$wa.UseClaimsAuthentication = $false
$wa.Update()

The above code will only revert back the web application. But the users are not migrated. Need to convert back to the windows user. But when i tried MigrateUsers($false) i got the below error

image

So we cannot use that method to revert the users. So i followed the approach given in the blog below

http://sharepointegg.blogspot.sg/2011/01/reverting-claim-based-authentication-to.html

Basically use the stsadm command and strip off the unwanted text before the user name in the site collection

Below is the code taken from that blog.

public Program(string url)
{
    using (SPSite site = new SPSite(url))
    {
        using (SPWeb web = site.RootWeb)
        {
            foreach (SPUser user in web.AllUsers)
            {
                string username = GetClaimBasedUserName(user);
                if (!username.Equals(string.Empty))
                {
                    Console.Write(“Migrating {0} to {1}…”, user.LoginName, username);
                    try
                    {
                        SPFarm Farm = SPFarm.Local;
                        Farm.MigrateUserAccount(user.LoginName, username, false);
                        Console.WriteLine(“Done”);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
        }
    }
}
 
private string GetClaimBasedUserName(SPUser user)
{
    string username = string.Empty;
    try
    {
        if (user.IsDomainGroup)
        {
            if (user.LoginName.StartsWith(“c:0+.w|”))
            {
                username = user.Name;
            }
        }
        else
        {
            if (user.LoginName.StartsWith(“i:0#.w|”))
            {
                username = user.LoginName.Substring(7);
            }
        }
    }
    catch
    {
 
    }
    return username;
}

Get Logged In User while Impersonate or Run as Admin

Sometimes when a program is run as Administrator, using the System.Security.Principal.WindowsIdentity.GetCurrent().Name will return always System or NT Authority\System. This happens while running the exe under windows service or by Installer class in the windows application.

The below code will solve this issue.

Code Snippet
  1. public static string GetParentUser(int pid)
  2.         {
  3.             string parentUserAccount = null;
  4.             string queryString = String.Format("select ParentProcessId from win32_process where ProcessId={0}", pid);
  5.             using (ManagementObjectSearcher query = new ManagementObjectSearcher(new
  6.             SelectQuery(queryString)))
  7.             {
  8.                 foreach (ManagementObject mo in query.Get())
  9.                 {
  10.                     uint parentPid = (uint)mo.Properties["ParentProcessId"].Value;
  11.                     queryString = String.Format("select Handle from win32_process where ParentProcessId = {0}", parentPid);
  12.                     using (ManagementObjectSearcher subQuery = new ManagementObjectSearcher(new
  13.                     SelectQuery(queryString)))
  14.                     {
  15.                         foreach (ManagementObject mo1 in subQuery.Get())
  16.                         {
  17.                             string handle = (string)mo1.Properties["Handle"].Value;
  18.                             RelatedObjectQuery relatedQuery =
  19.                             new RelatedObjectQuery("associators of {Win32_Process.Handle=\"" + handle + "\"}");
  20.                             relatedQuery.RelatedClass = "Win32_LogonSession";
  21.                             using (ManagementObjectSearcher relQuery = new ManagementObjectSearcher(relatedQuery))
  22.                             {
  23.                                 foreach (ManagementObject mo2 in relQuery.Get())
  24.                                 {
  25.                                     RelatedObjectQuery relQuery2 =
  26.                                     new RelatedObjectQuery("associators of {Win32_LogonSession.LogonId='" +
  27.                                     mo2["LogonId"] + "'}");
  28.                                     relQuery2.RelationshipClass = "win32_LoggedonUser";
  29.                                     using (ManagementObjectSearcher searcher2 = new ManagementObjectSearcher(relQuery2))
  30.                                     {
  31.                                         foreach (ManagementObject mo3 in searcher2.Get())
  32.                                         {
  33.                                             parentUserAccount = String.Format(@"{0}\{1}", mo3["Domain"], mo3["Name"]);
  34.                                         }
  35.                                     }
  36.                                 }
  37.                             }
  38.                         }
  39.                     }
  40.                 }
  41.             }
  42.             return parentUserAccount;
  43.         }

 

You can download the code here

 

Hope the above code works. It works for me.

Thanks to the original post

http://bytes.com/topic/c-sharp/answers/631036-getting-currently-logged-user

How to create bootable VHD – Windows 7 or Windows 2008 R2

 

The below steps shows how to create a bootable VHD install for Windows 7 or Windows 2008 R2. With this step x64 OS can be installed, but requires a VT enabled machine in the BIOS.

1. Insert the Bootable Install DVD to the drive[Windows 7 or Windows 2008 R2]

2. Restart the machine, make sure the boot order is to DVD first in the BIOS to boot in DVD.

3. Once the windows is loaded, Select next in the Language selection screen

4. In the Install Now screen, Press Shift+F10 to enter into the command prompt

5. Type Diskpart and Enter

6. Type Create vdisk file=”c:\vhd\win7x64.vhd” type=expandable maximum=<vhd size in MB>

7. For differencing vhd shd add the parent=”VHD path” in the above command (optional)

8. Press Enter and Type Select vdisk file=”c:\vhd\win7x64.vhd”

9. Type attach vdisk

10. Press Alt+Tab

11. Now click on the Install Now Button

12. In the Drives windows select the virtual disk which we created, usually will be at the last. Ignore the warning which appears at the bottom.

13. Done, then follow the wizard to finish installation.

How to create Win 7 Themes

Creating themes in Windows 7 is much easier. Earlier version of windows don’t have this options. We can even export the theme and send to other people for sharing. In this blog i will explain first how to create a theme from Win 7 and later will explain how to share with other people.

Part – 1: How to create Theme in windows 7

Creating theme in Windows 7 is nothing but personalization of existing theme and save it with full name. Then later can export the theme to share with the people. To do that first go to the Desktop. Right click on the desktop and select “Personalize”. The Personalization window will appear to customize the theme. If any changes made to any of the existing theme(like changing wallpaper, transparency color, screen saver etc..) then Unsaved Theme will be selected and will appear as the first item. If nothing is customized will have default theme selected.

image

Under My Themes there are many themes installed. These are external themes i downloaded and installed it. I have made few modification in the screens so Unsaved Theme is present in the My Themes.

Initially when a Windows 7 is installed the default Win7 Theme will be selected as shown in the below screen

image

Now we will start creating the New Theme using the existing Win 7 Theme selected.

To create a new theme of our own we need to first select the existing theme. Modify the changes you want to do to the existing theme by changing the color, Wallpaper, screen saver etc. In my scenario i am going to change the Window Back color first. So click on the Window Color in the personalization page and a Windows Color Screen will appear. Select the desired color you want and save changes. I have selected Green and the color changes to Lime in the personalization window.

image

Now select the Desktop Background in the Personalization page, this will bring a wallpaper page. Browse the custom folder or select the wallpaper settings. Also you can select the Slideshow time picture settings etc and save the changes. Here in my window i selected Nature picture and opt not to use slideshow.

image

Now select the screensaver option from the Personalization page. Select the screensaver and save changes.

After doing all those changes now you can see Unsaved Theme in the My Themes Section of the Personalization page.

image

Now done!!! you new theme is ready almost. Now Right Click on the Unsaved Theme and select Save Theme. Enter a name and will be saved.

image

image

Now the theme creation is done. You can now share with anyone.

Part – 2 Sharing the Theme

Right click on the Renamed Theme and select Save Theme For Sharing menu, and provide the path to save the theme.

image

Then now the theme can be shared with anyone

WMI Provider in Hyper V

Windows 2008 server has a Hyper V to manage the Multiple Virtual Machines. The Hyper V manager helps to create Virtual machine and manage them. We can change the VHD and update the path using the Hyper V Manager. There are situation we need to write a program to do those tasks. Example when we do the DR using multiple Virtual Machines, some of the VM VHD path was not mapped exacted to the correct path. The VHD path was still pointing to old server while exporting the VM. So to update the VHD path programmatically i started looking to scripts and programs.

There are several options to write a program for Hyper V.

  • PowerShell Script
  • VBScript
  • WMI Provider Object using C#/VB.NET

PowerShell Script

PowerShell script is the most widely used approach to program any OS related operation. For Hyper V updating the VHD Path using PowerShell is a straight forward process. Just need to get the VM and the relevant Connections(vhd) and update the path property.

VBScript

Scripting through VB is similar to WMI programming. VBscript will createObject of WMIProvider dll and call the relevant method.

WMI Provider

I need to have UI to update the VHD path so i opted to use WMI Provider. System.Management namespace provides the whole new set of namespaces to manage the OS. Most of the operation which can be done by PowerShell can be done by WMI provider. The details of the provider can be found here http://msdn.microsoft.com/en-us/library/ms751442.aspx.

WMI Arch

Basically there is a COM/DCOM based WMI provider and the .NET Based WMI Provider. Depends on the client the WMI provider can be used. In my case my client program will be .NET windows Application so i opted to use .NET WMI provider. WMI provider consist of many namespaces to manage the OS operation. Below are few list of Namespaces taken from my Win 7.

image

To work with the Hyper V API, there is a separate namespace called root/Virtualization. This namespace provides all function to manage the VM operations. Each namespace has classess. These classes defines the specific operation to the namespace. Ex root/virtualization has classes below. Each class has properties and methods.

image

To explore the WMI namespaces and classes in the system please use the below tools. This WMI Tool allows the user to explorer all the namespaces available in the system.

http://www.microsoft.com/downloads/details.aspx?FamilyID=6430f853-1120-48db-8cc5-f2abdc3ed314&displaylang=en

To get any information from WMI objects we need to instantiate the WMI object and use the relevant namespace. Also WMI provide the Query provider which can be used to write a SQL kind of query to get the objects using the property. The WMI objects can be compared to a relational DB where we can query the object using a query provider and keys.

  WMIvsRelational DB

Microsoft has a tool to generate a c#, VB or VBScript code. WMI Code Creator lists down all the namespace available in the machine and generates the code based on the selection of operation. Using this tool i have generated the basic code to get the relevant device information.

image

using this we can create a windows application to update the VHD Path which will be published in the next blog.

Network Profile for XP

 

Currently switching between different Networks in XP is difficult. Unless we buy a thirty party tool it’s difficult to switch the profile. Here is the very simple solution to switch the profile in XP machine.

Save the Network Profile to a Text File

  • Open a DOS shell with start -> run; then type cmd
  • On shell use the following command netsh -c interface dump > c:\MyNetwork.txt
  • Using the above method any number of profile can be created and saved to the local machine

Creating a Desktop Shortcut for the Created Profile

  • On the Desktop Right Click New -> Shortcut.
  • Enter "%windir%\system32\netsh.exe -f c:\mynetwork.txt" in the location.

  • Enter a name for the shortcut. If want to change the icon, use the properties of the shortcut.