Friday, 30 January 2015

Reset AD User Password with C#

We can reset Active Directory User password using DirectoryEntry class and UserPrincipal class. In this article, I am going to write C# code snippets to reset AD user password and Reset Bulk AD users password in different methods.

Summary:


Reset AD User Password in C# using UserPrincipal

To use this class, you need to add reference System.DirectoryServices.AccountManagement.dll. The below C# code enable an Active Directory user if it is disabled and reset its password. It also force user to change password at next logon, remove the line user.ExpirePasswordNow(); if you don't want to force user to change password at next logon.
public static void ResetPassword1(string userName, string newPassword)
{
    PrincipalContext context = new PrincipalContext(ContextType.Domain);
    UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
    //Enable Account if it is disabled
    user.Enabled = true;
    //Reset User Password
    user.SetPassword(newPassword);
    //Force user to change password at next logon
    user.ExpirePasswordNow();
    user.Save();
}

Reset AD User Password in C# using DirectoryEntry

You can also reset Active Directory user password by invoking SetPassword method through DirectoryEntry class, To use this class, you need to add reference System.DirectoryServices.dll.
public static void ResetPassword(string userName, string password)
{
    DirectoryEntry domainEntry = Domain.GetCurrentDomain().GetDirectoryEntry();
    DirectorySearcher dirSearcher = new DirectorySearcher(domainEntry);
    string filter = string.Format("(SAMAccountName={0})", userName);
    dirSearcher.Filter = filter;
    SearchResult result = dirSearcher.FindOne();
    if (result != null)
    {
        DirectoryEntry userEntry = result.GetDirectoryEntry();

        //Enable Account if it is disabled
        userEntry.Properties["userAccountControl"].Value = 0x200;
        //Reset User Password
        userEntry.Invoke("SetPassword", new object[] { password });
        //Force user to change password at next logon
        userEntry.Properties["pwdlastset"][0] = 0;
        userEntry.CommitChanges();
        userEntry.Close();
    }
    else
    {
        // User not found
    }
}

Reset Bulk AD Users Password From CSV File

The below C# function read bulk ad user's samAccountName from csv file and reset its password. We are using the Visual basic class TextFieldParser to read CSV file, so we need to add reference dll Microsoft.VisualBasic.

public static void ResetBulkADUsersPasswordFromCSVFile()
{
    string csvFilePath = @"C:\ADUsers.csv";
    string randomPwd = "MyP@ssw0rd";
    using (TextFieldParser csvReader = new TextFieldParser(csvFilePath))
    {
        csvReader.SetDelimiters(new string[] { "," });
        csvReader.HasFieldsEnclosedInQuotes = true;
        // reading column fields 
        string[] colFields = csvReader.ReadFields();
        int index_samaccountName = colFields.ToList().IndexOf("samAccountName");
        PrincipalContext context = new PrincipalContext(ContextType.Domain);
        while (!csvReader.EndOfData)
        {                
            try
            {
                // reading user fields 
                string[] fieldData = csvReader.ReadFields();
                string userName = fieldData[index_samaccountName];
                UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
                //Enable Account if it is disabled
                user.Enabled = true;
                //Reset User Password
                user.SetPassword(randomPwd);
                //Force user to change password at next logon
                user.ExpirePasswordNow();
                user.Save();
            }
            catch (Exception ex)
            {
            }
        }
    }
}
Read More...

Thursday, 22 January 2015

Find Disabled Active Directory Users using Powershell

We can find and list disabled Active Directory users using Powershell cmdlet Search-ADAccount with the AccountDisabled parameter. In this article, I am going to write Powershell script samples to List all the Disabled AD Users, Export Disabled AD Users to CSV file, and Enable all the Disabled AD Users.

Powershell command to list disabled AD Users:
Search-ADAccount –AccountDisabled -UsersOnly
Search-ADAccount cmdlet lists both users and computers, we need to pass the parameter -UsersOnly to list only users.

Summary:


Find and List All Disabled AD Users

The following command find all the disabled AD users by passing the parameter AccountDisabled into Powershell cmdlet Search-ADAccount and list the selected properties of all disabled Active Directory users.
Import-Module ActiveDirectory
Search-ADAccount –AccountDisabled -UsersOnly |
 Select -Property Name,DistinguishedName
Find Disabled AD Users using Powershell

Find Disabled AD Users from specific OU using Powershell

We can set target OU scope by using the parameter SearchBase in Search-ADAccount cmdlet. This following command select and list all the disabled AD users from the Organization Unit 'TestOU'.
Import-Module ActiveDirectory
Search-ADAccount  -SearchBase "OU=TestOU,DC=TestDomain,DC=Local" –AccountDisabled -UsersOnly |
 Select -Property Name,DistinguishedName

Export Disabled AD Users to CSV using Powershell

We can export powershell output into CSV file using Export-CSV cmdlet. The following command export selected properties of all disabled Active Directory users to CSV file.
Import-Module ActiveDirectory
Search-ADAccount –AccountDisabled -UsersOnly |
 Select -Property Name,DistinguishedName |
 Export-CSV "C:\\DisabledADUsers.csv" -NoTypeInformation -Encoding UTF8
Find Disabled Active Directory Users using Powershell

CSV Output of Disabled AD User Accounts:

Find Disabled AD Users using Powershell

Enable All Disabled AD Users using Powershell

You can enabled the disbaled Active Directory user account by using Powershell cmdlet Enable-ADAccount. The following command find all the disabled AD user accounts using Search-ADAccount cmdlet with AccountDisabled parameter and enable all the disabled user accounts by using Enable-ADAccount cmdlet.
Import-Module ActiveDirectory
Search-ADAccount –AccountDisabled -UsersOnly | Enable-ADAccount
Use the below command, if you want to enable users only from specific OU.
Import-Module ActiveDirectory
Search-ADAccount  -SearchBase "OU=TestOU,DC=TestDomain,DC=Local" –AccountDisabled -UsersOnly | 
   Enable-ADAccount
Read More...

Monday, 12 January 2015

Find Locked-Out AD Users using Powershell

We can Find and List Lockout-Out AD Users using Powershell cmdlet Search-ADAccount with the lockedout parameter. In this article, I am going to write Powershell script samples to List all Locked-Out AD Users, Export Locked-Out AD Users to CSV file, and Unlock all the Locked-Out AD Accounts.

Powershell command to list all Locked-Out AD Users:
Search-ADAccount –LockedOut

Summary:

Find and List All Locked-Out AD Users

The following command find the locked-out ad users by passing the parameter LockedOut into Powershell cmdlet Search-ADAccount and list the selected properties of all locked-out Active Directory users.
Import-Module ActiveDirectory
Search-ADAccount –LockedOut |
 Select -Property Name,DistinguishedName
Find and Export Locked-Out AD Users using Powershell

Find Locked-Out AD Users from specific OU using Powershell

We can set target OU scope by using the parameter SearchBase in Search-ADAccount cmdlet. This following command select and list all the Locked-Out Active Directory users from the Organization Unit 'TestOU'.
Import-Module ActiveDirectory
Search-ADAccount  -SearchBase "OU=TestOU,DC=TestDomain,DC=Local" –LockedOut |
 Select -Property Name,DistinguishedName

Export Locked-Out AD Users to CSV using Powershell

We can export powershell output into CSV file using Export-CSV cmdlet. The following command export selected properties of all locked-out Active Directory users to CSV file.
Import-Module ActiveDirectory
Search-ADAccount –LockedOut |
 Select -Property Name,DistinguishedName |
 Export-CSV "C:\\LockedOutADUsers.csv" -NoTypeInformation -Encoding UTF8
Find and Export Locked-Out AD Users using Powershell
CSV Output of Locked-Out AD User Accounts:

Find and Export Locked-Out AD Users using Powershell

Unlock All Locked-Out AD Users using Powershell

You can unlock the locked-out Active Directory user account by using Powershell cmdlet Unlock-ADAccount. The following command find all the locked-out AD user accounts using Search-ADAccount cmdlet with LockedOut parameter and unlock the locked-out accounts by using Unlock-ADAccount cmdlet.
Import-Module ActiveDirectory
Search-ADAccount –LockedOut | Unlock-ADAccount
Use the below command, if you want to unlock users only from specific OU.
Import-Module ActiveDirectory
Search-ADAccount  -SearchBase "OU=TestOU,DC=TestDomain,DC=Local" –LockedOut | 
   Unlock-ADAccount
Read More...

Saturday, 10 January 2015

How to Deploy Registry Settings via Group Policy

In this article, I am going to explain how to deploy registry settings into group of computers via Group Policy. This is a very common task in any GPO based Active Directory domain environment for either all of your user’s computer or to a certain group of user’s computer. You can do it easily via Group Policy's Computer Preferences setting Registry (SampleGPO\Computer Configuration\Preferences\Windows Settings\Registry). You can update existing registry value, add new registry value, add new registry key and import existing registry values from one computer and update imported registry values into group of computers via Group Policy.

Summary:

Update existing Registry Value via Group Policy

Before configuring Group Policy, group the computers those you want to deploy registry settings and move into single OU so that we can easily link new gpo into that OU.

Follow the below steps to update existing registry value through gpo:

1. Open the Group Policy Management console by running the command gpmc.msc.

2.  Expand the tree and right-click on the OU you want this policy to be applied to. Now, I am going to apply computers which are under the OU ManagementTeam. so right-click on the OU ManagementTeam, and click Create a GPO in this domain, and Link it here...

How to Deploy Registry Settings via Group Policy

3. Give the new policy name and click OK. Here, I am giving new policy name Deploy Registry Policy
  
How to Update Registry Settings via Group Policy

4. Now right-click on the newly created gpo Deploy Registry Policy and click edit.

How to Update Registry Settings through Group Policy

5. In the Group Policy Management Editor window, expand Computer Configuration and go to the node Registry (Computer Configuration/Preferences/Windows Settings/Registry).

6. Right-click on the node Registry, click New > Registry Item.

How to Update Registry Settings through GPO

7. In new window, select the Registry Hive where your registry key exist and click browse (...) button to select existing registry value.

how to update existing registry settings through GPO

8. Select the registry value which you want update new value. Here, I have selected the registry value Debug from Software\MorganApp.

how to update existing registry value through GPO

9. Set new value data (I have set it as 1) and click Apply to complete process.

how to update existing registry value through gpo

10. That's all, now you can login into any one of the computer which is located under the OU where this group policy is linked and see the updated registry value. If you already logged-in, just run the command gpupdate/force to refresh GPO settings and see the updated registry value.

how to update existing registry value using gpo

Add new Registry Value through Group Policy

Adding new registry value via GPO is same process like updating existing registry value. Here, we are just giving new registry value and its value data instead of selecting registry value.

1. Open the Group Policy in which you want to configure deploy registry settings.
2. In the Group Policy Management Editor window, expand Computer Configuration and go to the node Registry (Computer Configuration/Preferences/Windows Settings/Registry).
3. Right-click on the node Registry, click New > Registry Item.

how to add new registry value through gpo

4. In new window, select the Registry Hive where your registry key is exist.
5. Type existing registry key path (Software\MorganApp) and type new registry value. Here, I have given new registry value 'Description'.
6. Set new value data (I have set it as 'This is new description') and click Apply to complete process.

how to add new registry value through gpo

7. That's all, now you can login into any one of the computer which is located under the OU where this group policy is linked and see the created new registry value. If you already logged-in, just run the command gpupdate/force to refresh GPO settings and see the newly created registry value.

how to add new registry value through gpo

Deploy Registry settings by Importing Registry via Group Policy

This method will be very useful if you want to update group of related registry values. Just configure the required registry values in local machine (The machine where you are editing GPO) and you can import the registry settings via import wizard in GPO.
1. Open the Group Policy in which you want to configure deploy registry settings.
2. In the Group Policy Management Editor window, expand Computer Configuration and go to the node Registry (Computer Configuration/Preferences/Windows Settings/Registry).
3. Right-click on the node Registry, click New > Registry Wizard.

how to apply registry settings by resgistry import through gpo

4. In new window, select Local Computer and click Next.
5. Expand My Computer and Registry Hive, select the Registry setting which you want to import (I have selected MorganApp1 and its registry values) and click Finish to complete process.

how to apply registry settings by resgistry import through gpo

6. That's all, now you can login into any one of the computer which is located under the OU where this group policy is linked and see the created new registry settings. If you already logged-in, just run the command gpupdate/force to refresh GPO settings and see the newly created registry settings.
Read More...

HTTP Error 500.19 - Internal Server Error - 0x80070005

You could see the web page error HTTP Error 500.19 - Internal Server Error in different scenarios when accessing a web page which hosted in IIS Server. This is generic http error,  you can find the exact reason from error code under Detailed Error Information section of the error page. This article gives fix/solution for error code 0x80070005 in HTTP Error 500.19 - Internal Server Error.

The error code 0x80070005 indicates insufficient permissions to read web configuration file. You will get the below detailed information.
Error Code: 0x80070005
Config Error:  Cannot read configuration file due to insufficient permissions 
Config File:   \\?\C:\Users\Administrator.DC1\Documents\MorganApp\web.config
Fix/Solution HTTP Error 500.19 - Internal Server Error - 0x80070005

Steps to Fix HTTP Error 500.19 - Internal Server Error - 0x80070005

From the Detailed Error Information section, it clearly indicates the error 0x80070005 occurs due insufficient permissions to read web configuration file. So to fix this issue, we need to give required permissions to web configuration file for the Identity (user account or service) of the Application Pool that is used in Web Application.

Follow the below steps to give proper permissions for Application Pool Identity.

1. Open the Internet Information Services (IIS) by running the command inetmgr 

2. Expand the root node, expand Sites, and right-click on your Application, click Manage Web Site ->Advanced Settings


Fix HTTP Error 500.19 - Internal Server Error - 0x80070005


3. Note down the Application Pool name under General settings and close the window

Fix HTTP Error 500.19 - Internal Server Error - 0x80070005

4. Now go to Application Pools section, here you can see what Identity is used in the corresponding Application Pool (MorganAppPool).

Fix HTTP Error 500.19 - Internal Server Error - 0x80070005

5. Here, the user account testuser1 is configured in MorganAppPool. So we need give required permissions for this user in the website directory "C:\Users\Administrator\Documents\MorganApp".

6. Go the web directory folder MorganApp, right-click on the folder and click Properties.

Fix HTTP Error 500.19 - Internal Server Error - 0x80070005

7. Set required permissions for the Identity that used in ApplicationPool (In my case testuser1).

Fix HTTP Error 500.19 - Internal Server Error - 0x80070005

8. Restart Application Pool and Web Application, and browse the web page again . Hope, the error 'HTTP Error 500.19 - Internal Server Error - 0x80070005' will get fixed and everything will work fine now.
Read More...

Friday, 9 January 2015

How to Track Registry Changes in Windows

Monitoring Registry changes, find who accessed, modified, added, or deleted a Registry value is one of the important task in Windows Auditing. In Windows, we can easily track and find who and when the particular registry value was accessed or changed by using built-in Windows Auditing. The registry change auditing is controlled by Object Access Audit Policy of Group Policy and Audit Security (SACL) of the registry key which we want to monitor. Once we configured these two settings, we will get following events for registry changes.

4656 - A handle to a Registry key or Registry Value was requested.
4657 - A registry value was modified.
4660 - An registry key or value was deleted or removed.
4663 - An attempt was made to access a Registry key or Registry Value

Summary:

Steps to Enable Object Access (Registry Access) Audit Policy

This audit security setting determines whether the OS audits user attempts to access Registry and other File System. Registry change events are only generated for registry scope that have system access control lists (SACL) specified, so don't forget to configure Registry Access Audit Security (SACL) for the registry scope which you want to monitor registry access and registry changes.

Follow the below steps to configure Registry Access Audit Policy to monitor registry access, registry delete, registry value modification and registry creation:

Note: You should also configure Registry Access Audit Security settings on the registry scope which you want to monitor registry access to get the events.

1. Open the Local Security Policy by running the command secpol.msc.

How to Track Registry Changes

2. Navigate to the node Audit Policy (Security Settings/Local Policies/Audit Policy). In right-hand side, select the setting Audit object access.

How to Track Registry Changes

3. Double-click on Audit object access, and check the Audit options Success and Failure to monitor successful registry accesses and access denied registry accesses.

How to Track Registry Changes

4. Click the button Apply to configure setting.

Steps to Enable Registry Access Audit Security (SACL)


System Access Control Lists (SACL) determines registry access events for the particular Registry scope should generated or not. So that, you should enable SACL for the single registry value or the root registry scope which you want monitor or track chnage events.

Follow the below steps to enable Registry Access Audit Security:

1. Open Registry editor by running the command regedit

1. Right-click on the Registry key which you want to configure audit events, and click Permissions.

How to Track Registry Access

2. In Security window, click Advanced button.

How to Track Registry Access

3. Navigate to the tab Auditing, and click Add button.

Find Registry Changes

4. Select the account Everyone, and check Successful and Failed Audit options which are you want to audit, click the button OK, and click Apply. 

Track and Find Registry Changes

Registry Change Auditing Event IDs

Once you configured above two settings, now you can see the actual events, to view the registry change events, follow the below steps.

1. Open the Run window, type the command eventvwr.msc, and click OK.

Track and Find Registry Changes, Registry Delete, Registry Modification

2. You can see the Event Viewer Management Console, expand the tree node Windows Logs and select Security.
Track and Find Registry Changes, Registry Delete, Registry Modification

3. Now, you can see lot of events in right-hand side window, but to track only registry access and registry change, we need to check only these event ids, 4656, 4657, 4660 and 4663. To filter only these four events, right-click on the Security node and click Filter Current Log.
4. Type the event ids 4656, 4657, 4660 and 4663 as comma separated values and click.

Track and Find Registry Changes, Registry Delete, Registry Modification

5. Now, result window lists only registry access and registry change events, you can double-click on any event and check what type action made on the particular registry key.

Track and Find Registry Changes, Registry Delete, Registry Modification

4656: This is the first event logged when an user attempts to access registry key, this event gives information about what type of access was requested by the user and it will not give info about what type access actually made by user (which is given by the event id 4663).

4657 - A registry value was modified.

4660 - An registry key or value was deleted or removed.

4663: This event gives the info of what type actual operation is done by user on a file. it tells whether the registry key or registry value was created, modified, deleted, or it simply accessed,


Sample Event 4657 - Registry Change Event:
Log Name:      Security
Date:          1/9/2015 10:39:27 PM
Event ID:      4657
Task Category: Registry
Keywords:      Audit Success
Computer:      hp-PC
Description:
A registry value was modified.

Subject:
 Security ID:  hp-PC\Administrator
 Account Name:  Administrator
 Account Domain:  hp-PC
 Logon ID:  0x2a81c

Object:
 Object Name:  \REGISTRY\MACHINE\SOFTWARE\MorganApp
 Object Value Name: SampleKey
 Handle ID:  0x134
 Operation Type:  Existing registry value modified

Process Information:
 Process ID:  0x8b0
 Process Name:  C:\Windows\regedit.exe

Change Information:
 Old Value Type:  REG_SZ
 Old Value:  sss
 New Value Type:  REG_SZ
 New Value:  ttt
The above sample event 4657 was generated when I change the value of registry \REGISTRY\MACHINE\SOFTWARE\MorganApp\SampleKey from sss to ttt.
Read More...

Can Ping but Cannot Connect using Remote Desktop (RDP)

I am using a Windows Server 2008 R2 machine for my Administrative task, I used to connect different machines via Remote Desktop Connection (RDP) tool, it was worked well before, I can connect any computer or server (i.e Windows 7, Windows Server 2008 R2) from my Server machine. But today, I can't connect any machine from my server machine via Remote Desktop Client (RDP) tool.

Note:
- I can ping the Remote machine from my Local server.
- I cannot connect Remote Desktop (RDP) only from my server machine that I am using for Administrative task but I can connect same machines from other Server machine.

After search through internet, I have got below steps as solution.
On the target machine, make sure that Port 3389 is not being blocked by a firewall.  If you are using Windows Firewall, go to the Windows Firewall control panel, verify that "Don't Allow Exceptions" is not checked under the "General" tab, then click on the "Exceptions" tab and make sure there is a check mark beside "Remote Desktop".
In remote machine, you can also make sure that a program is running to accept incoming remote desktop connections by bringing up a command prompt (Start -> Run -> "cmd") and entering the following command:

   netstat   -an   |    find   "3389"
If all is well, you should see the following line returned:
     TCP    0.0.0.0:3389           0.0.0.0:0              LISTENING 
The above solution will solve the issue only if the problem persists in Remote Machine, but as I stated earlier, I cannot connect Remote Desktop (RDP) only from one Server machine but I can connect the same remote machine from my other Server machine. So, in my case the problem is in my own Server machine not in Remote machine since it can be connected from different servers.

Fix/Solution: Can Ping but Cannot Connect using Remote Desktop (RDP)

The Remote Desktop Connection failure problem was solved by simply restarting the windows service Remote Desktop Configuration. The Remote Desktop Configuration service (RDCS) is responsible for all Remote Desktop Services and Remote Desktop related configuration and session maintenance activities that require SYSTEM context. These include per-session temporary folders, RD themes, and RD certificates.

- Open Service Manager by running the command services.msc
- Search and find the service Remote Desktop Configuration and Restart it.

Can Ping but Cannot Connect using Remote Desktop (RDP)

Note: If this solution didn't fix your problem and if you fixed the same issue by different solution, please write that solution as comment below.  
Read More...

Thursday, 8 January 2015

Get Process Name from PID using Command Prompt in Windows

You can find Process Name from Process ID (PID) using the command tasklist in command line windows, apart from command prompt, you can even get process name for the associated Process ID (PID) using either Task Manager or Resource Monitor.

Find Process Name from PID through Command Prompt

You can get Process Name from Process ID (PID) using the command tasklist in command prompt. TaskList command displays all running applications and associated services with their Process ID (PID).

The following command displays the associated Process Name for the Process ID 488.
tasklist /svc /FI "PID eq 488"
Get Process Name from PID using Command Prompt in Windows

Get Process Name by Process ID (PID) from Remote Computer:

Use below command If you want to get Process Name from Process ID (PID) from Remote Computer.
tasklist /s "remote-pc" /svc /FI "PID eq 488"

Find Process Name from PID through Task Manager

1. Open the Task Manger, click the menu View and click Select Columns.

Get Process Name from PID using Task Manger

2. Select the column Process Identifier(PID) and click OK.

Get Process Name from PID using Task Manger

3. Now you can find Process Name (Image Name) by mapping PID value.

Get Process Name from PID using Task Manger

Read More...

Wednesday, 7 January 2015

Delete Rows from SQL Server Table

In SQL, the DELETE statement is used to remove one or more rows from a table or view.

DELETE statement syntax:
DELETE FROM table_Name WHERE search_condition
table_Name - source table to delete records
search_condition - search filter to select only particular rows to delete.
Note: if you ignore the WHERE clause, all records will be deleted.

The following query deletes all rows from the User table because a WHERE clause is not used to limit the number of rows to delete.
DELETE FROM UserDetails
The following statment deletes only the rows which has the value 5 in the column ID.
DELETE FROM UserDetails Where ID=5

Delete Multiple Rows:

You can delete multiple rows from SQL Server Table by using suitable search condition. The following statement deletes the rows which has the value 1 0r 2 in the column ID.
DELETE FROM UserDetails Where ID=1 or ID=2
To make simple query, you can use IN in where clause to select multiple records.
DELETE FROM UserDetails Where ID IN ('1','2')
You can even delete rows from one table with a search condition which depends on different table.
DELETE FROM UserDetails Where ID IN (SELECT ID SomeOtherTable Where search_condition)

Delete All Rows from SQL Server Table:

You can delete all the records by ignoring where clause.
DELETE FROM UserDetails
But above Delete statement will be very slow because it works one row at a time. So you can use Truncate if it possible. Truncate delete all the rows from table, and it is faster than delete since it uses fewer system and transaction log resources than DELETE.
Truncate Table UserDetails
There are a few situations where truncate doesn't work and may not suitable. See this article to know the difference between Delete vs Truncate.
Read More...

Tuesday, 6 January 2015

How to find a computer is joined to an Active Directory domain or not

We can easily find whether a computer is joined to an Active Directory domain or not by various methods. In this article, I am going to write simple steps to determine whether your computer is joined to an Active Directory domain or not, and whether you are logged in to a computer by domain account or local account.

Check whether a computer is joined to Active Directory or not:

1. Click Start menu, right-click on the Computer icon and select Properties.

How to find a computer is joined to an Active Directory domain or not

2. Look under the region Computer name, domain, and workgroup settings for the entry Domain:
3. If the Domain: entry exists, then your computer is connected with Active Directory domain or if you have an entry that starts with Workgroup: then your device is not joined to an Active Directory.

How to find a computer is joined to an Active Directory domain or not

Check whether you are logged in to a computer by domain account or local account:

Even if your computer is joined to the Active Directory domain, you may not logged in by Active Directory account. Follow the below steps to check whether you are logged in to your computer by domain account or local account.

1. Open Command Prompt window (Click Start menu, then type cmd in the Search box and press Enter).
2. In the command line window, type the command set user and press Enter.
3. Look at the entry USERDOMAIN:. If the USERDOMAIN entry contains your computer's name, then you're logged in to the computer by local account. If it contains the Active Directory domain name, then you're logged in by Active Directory domain account.

Check whether you are logged in to a computer by domain account or local account

Read More...

Sunday, 4 January 2015

Create Desktop Shortcut using C#

 In C#, you can easily create desktop shortcut icon using Windows Script Host library. In this article, I am going write C# code examples to create desktop shortcut for Current User and All Users profile.

Summary:

Create Desktop Shortcut for Current User

The below C# method creates desktop shortcut icon to open Application settings UI. The function call of Environment.DesktopDirectory gives current user's desktop profile path, so the created shortcuts will be available only in current user's Desktop location.

Note: To use Windows Script Host library, you need to add a reference under References > COM tab > Windows Script Host Object Model.
using IWshRuntimeLibrary;
-----------------------
public static void CreateDesktopShortcut()
{
  string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
    WshShellClass shellClass = new WshShellClass();
    //Create Desktop Shortcut for Application Settings
    string settingsLink = Path.Combine(desktopFolder, "Settings.lnk");
    IWshShortcut shortcut = (IWshShortcut)shellClass.CreateShortcut(settingsLink);
    shortcut.TargetPath = @"C:\Program Files\MorganTechSpace\MyAppSettings.exe";
    shortcut.IconLocation = @"C:\Program Files\MorganTechSpace\settings.ico";
    shortcut.Arguments = "arg1 arg2";
    shortcut.Description = "Click to edit MorganApp settings";
    shortcut.Save();
}

Create Desktop Shortcut Icon for All Users

You can get common desktop profile path for All Users by using API function SHGetSpecialFolderPath. The below C# method creates desktop shortcut, since the function call of SHGetSpecialFolderPath returns common desktop profile path for All Users, so the created shortcuts will be available in all user's desktop location.
using IWshRuntimeLibrary;
using System.Runtime.InteropServices;
---------------------------------
[DllImport("shell32.dll")]
static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, [Out] StringBuilder lpszPath, int nFolder, bool fCreate);
const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x19;

public static void CreateDesktopShortcutForAllUsers()
{
    StringBuilder allUserProfile = new StringBuilder(260);
    SHGetSpecialFolderPath(IntPtr.Zero, allUserProfile, CSIDL_COMMON_DESKTOPDIRECTORY, false);
    //The above API call returns: C:\Users\Public\Desktop 
    string settingsLink = Path.Combine(allUserProfile.ToString(), "Settings.lnk");
    //Create All Users Desktop Shortcut for Application Settings
    WshShellClass shellClass = new WshShellClass();
    IWshShortcut shortcut = (IWshShortcut)shellClass.CreateShortcut(settingsLink);
    shortcut.TargetPath = @"C:\Program Files\MorganTechSpace\MyAppSettings.exe";
    shortcut.IconLocation = @"C:\Program Files\MorganTechSpace\settings.ico";
    shortcut.Arguments = "arg1 arg2";
    shortcut.Description = "Click to edit MorganApp settings";
    shortcut.Save();
}
Create Desktop Shortcut using C#

Delete Desktop Shortcut Icon using C#

The below C# method deletes desktop shortcuts from both current user profile and all user's common profile.
[DllImport("shell32.dll")]
static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, [Out] StringBuilder lpszPath, int nFolder, bool fCreate);
const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x19;

public static void DeleteDesktopShortcut()
{
    //Current User: Delete current user's Desktop shortcut
  string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
    string shortcut_link = Path.Combine(desktopFolder, "Settings.lnk");
    if (System.IO.File.Exists(shortcut_link))
    {
        System.IO.File.Delete(shortcut_link);
    }
    //All Users: Delete All User's Desktop shortcut
    StringBuilder allUserProfile = new StringBuilder(260);
    SHGetSpecialFolderPath(IntPtr.Zero, allUserProfile, CSIDL_COMMON_DESKTOPDIRECTORY, false);
    string common_shortcut_link = Path.Combine(allUserProfile.ToString(), "Settings.lnk");
    if (System.IO.File.Exists(common_shortcut_link))
    {
        System.IO.File.Delete(common_shortcut_link);
    }
}

Read More...

Thursday, 1 January 2015

Create Start Menu Shortcut (All Programs) using C#

By MSI setup, you can easily create Start Menu Shortcut for your application. But when it comes to custom installer setup, we need to write custom code to create All Programs shortcut. In C#, you can create shortcut using Windows Script Host library. In this article, I am going write C# code examples to create Start Menu (All Programs) shortcut for Current User and All Users profile.

Summary:

Create Start Menu Shortcut (All Programs) for Current User

The below C# method creates Start Menu >All Programs shortcuts to open Application settings UI and Uninstall setup shortcut. The function call of Environment.GetFolderPath gives current user's profile path, so the created shortcuts will be available only in current user's Start Menu (All Programs) location.

Note: To use Windows Script Host library, you need to add a reference under References > COM tab > Windows Script Host Object Model.
using IWshRuntimeLibrary;
-----------------------
public static void CreateStartMenuShortcut()
{
    string programs_path = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
    string shortcutFolder = Path.Combine(programs_path, @"MorganTechSpace\SampleApp");
    if (!Directory.Exists(shortcutFolder))
    {
        Directory.CreateDirectory(shortcutFolder);
    }
    WshShellClass shellClass = new WshShellClass();
    //Create First Shortcut for Application Settings
    string settingsLink = Path.Combine(shortcutFolder, "Settings.lnk");
    IWshShortcut shortcut = (IWshShortcut)shellClass.CreateShortcut(settingsLink);
    shortcut.TargetPath = @"C:\Program Files\MorganTechSpace\MyAppSettings.exe";
    shortcut.IconLocation = @"C:\Program Files\MorganTechSpace\settings.ico";
    shortcut.Arguments = "arg1 arg2";
    shortcut.Description = "Click to edit MorganApp settings";
    shortcut.Save();

    //Create Second Shortcut for Uninstall Setup
    string uninstallLink = Path.Combine(shortcutFolder, "Uninstall.lnk");
    shortcut = (IWshShortcut)shellClass.CreateShortcut(uninstallLink);
    shortcut.TargetPath = @"C:\Program Files\MorganTechSpace\Setup.exe";
    shortcut.IconLocation = @"C:\Program Files\MorganTechSpace\uninstall.ico";
    shortcut.Arguments = "u";
    shortcut.Save();
}

Create Start Menu Shortcut (All Programs) for All Users

You can get common profile path for All Users by using API function SHGetSpecialFolderPath. The below C# method creates All Programs shortcut, since the function call of SHGetSpecialFolderPath returns common profile path for All Users, so the created shortcuts will be available in all user's Start Menu (All Programs) location.
using IWshRuntimeLibrary;
using System.Runtime.InteropServices;
---------------------------------
[DllImport("shell32.dll")]
static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, [Out] StringBuilder lpszPath, int nFolder, bool fCreate);
const int CSIDL_COMMON_STARTMENU = 0x16;

public static void CreateShortcutForAllUsers()
{
    StringBuilder allUserProfile = new StringBuilder(260);
    SHGetSpecialFolderPath(IntPtr.Zero, allUserProfile, CSIDL_COMMON_STARTMENU, false);
    //The above API call returns: C:\ProgramData\Microsoft\Windows\Start Menu
    string programs_path = Path.Combine(allUserProfile.ToString(), "Programs");

    //You can even use below one line code to avoid api call
    //string programs_path= Path.Combine(Environment.GetEnvironmentVariable("ALLUSERSPROFILE"), @"Microsoft\Windows\Start Menu\Programs");
    string shortcutFolder = Path.Combine(programs_path, @"MorganTechSpace\SampleApp");
    if (!Directory.Exists(shortcutFolder))
    {
        Directory.CreateDirectory(shortcutFolder);
    }
    WshShellClass shellClass = new WshShellClass();
    //Create Shortcut for Application Settings
    string settingsLink = Path.Combine(shortcutFolder, "Settings.lnk");
    IWshShortcut shortcut = (IWshShortcut)shellClass.CreateShortcut(settingsLink);
    shortcut.TargetPath = @"C:\Program Files\MorganTechSpace\MyAppSettings.exe";
    shortcut.IconLocation = @"C:\Program Files\MorganTechSpace\settings.ico";
    shortcut.Arguments = "arg1 arg2";
    shortcut.Description = "Click to edit MorganApp settings";
    shortcut.Save();
}
Create Start Menu Shortcut (All Programs) using C#

Delete All Programs Shortcut using C#

The below C# method deletes start menu shortcuts from both current user profile and all user's common profile.
[DllImport("shell32.dll")]
static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, [Out] StringBuilder lpszPath, int nFolder, bool fCreate);
const int CSIDL_COMMON_STARTMENU = 0x16;

public static void DeleteShortcut()
{
    //Current User: Delete current user's start menu (All Programs) shortcut
    string programs_path = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
    string shortcutFolder = Path.Combine(programs_path, @"MorganTechSpace");
    if (Directory.Exists(shortcutFolder))
    {
        Directory.Delete(shortcutFolder, true);
    }
    //All Users: Delete all user's start menu (All Programs) shortcut
    StringBuilder allUserProfile = new StringBuilder(260);
    SHGetSpecialFolderPath(IntPtr.Zero, allUserProfile, CSIDL_COMMON_STARTMENU, false);
    string all_users_programs_path = Path.Combine(allUserProfile.ToString(), "Programs");

    string allusershortcutFolder = Path.Combine(all_users_programs_path, @"MorganTechSpace");
    if (Directory.Exists(allusershortcutFolder))
    {
        Directory.Delete(allusershortcutFolder, true);
    }
}

Read More...

Tuesday, 30 December 2014

Start, Stop and Restart Windows Service using C#

You can start, stop and restart a windows service programmatically in C# using .NET build-in class ServiceController. To use ServiceController class, you need to add the namespace "System.ServiceProcess".

Summary:

Start Windows Service using C#

Use the below C# method to start a service by passing service name as argument. This function start the given windows service and waits until the service is running or until given timeout occurs.
public static void StartService(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    // Wait Timeout to get running status
    TimeSpan timeout = TimeSpan.FromMinutes(1);
    if (service.Status != ServiceControllerStatus.Running)
    {
        // Start Service
        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
    }
    else
    {
        // Service already started;
    }
}

Stop Windows Service using C#

Use the below C# method to stop a service by passing service name as argument. This function stop the given windows service and waits until the service is stopped or until given timeout occurs.
public static void StopService(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    // Wait Timeout to get stopped status
    TimeSpan timeout = TimeSpan.FromMinutes(1);
    if (service.Status != ServiceControllerStatus.Stopped)
    {
        // Stop Service
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
    }
    else
    {
        // Service already stopped;
    }
}

Restart Windows Service using C#

There is no direct C# function to restart a service, so, we need do it by two step process, first stop the given service and start the service again. Use the below C# method to restart a service by passing service name as argument. You can give some extra timeout if your service takes more time to stop or start.
public static void RestartService(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    TimeSpan timeout = TimeSpan.FromMinutes(1);
    if (service.Status != ServiceControllerStatus.Stopped)
    {
        // Stop Service
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
    }
    //Restart service
    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
Read More...

Monday, 29 December 2014

Start, Stop and Restart Windows Service using Powershell

In Powershell, we have dedicated cmdlets for every operations to manage Windows Services like Start, Stop, Restart and to display information of a Windows Service and you can even easily manage Services from Remote Computer.

Summary:

Start Windows Service using Powershell

You can start a windows service by using Start-Service cmdlet.
Start-Service <service-name> -PassThru
The parameter -PassThru force the command to wait until service started and displays its running status.
Start-Service "RemoteRegistry" -PassThru
Start, Stop and Restart Windows Service using Powershell
If you want to start a service by its display name, you can do it by simply passing display name with the argument -displayname.
Start-Service -displayname <service-display-name> -PassThru
Below command start the RemoteRegistry service by using its -display name "Remote Registry".
Start-Service -displayname "Remote Registry" -PassThru

Stop Windows Service using Powershell

You can stop a windows service by using the Powershell cmdlet Stop-Service.
Stop-Service <service-name> -PassThru
Here, The parameter -PassThru force the command to wait until service stopped and displays status.
Stop-Service "RemoteRegistry" -PassThru

Restart Windows Service using Powershell

You can restart a windows service by using the Powershell cmdlet Restart-Service.
Restart-Service <service-name> -PassThru
Here, the parameter -PassThru force the command to wait until the service get restarted completed and displays its running status.
Restart-Service "RemoteRegistry" -PassThru
Start, Stop and Restart Windows Service using Powershell

Start, Stop and Restart Windows Service in Remote Computer

If you want to start, stop and restart a service in Remote machine, you can do it by using two Powershell cmdlets Get-Service and any one of the manage service cmdlet. First, you can get the windows service object from remote computer by using Get-Service cmdlet and you can do any action like Start,Stop and Restart by using Remote Service object.
Get-Service <service-name> -ComputerName <remote-pc-name> | Start-Service -PassThru
Start the RemoteRegistry service in Win7-PC by using below command:
Get-Service "RemoteRegistry" -ComputerName "Win7-PC" | Start-Service -PassThru
Restart the RemoteRegistry service in Win7-PC by using below command:
Get-Service "RemoteRegistry" -ComputerName "Win7-PC" | Restart-Service -PassThru
Stop the RemoteRegistry service in Win7-PC by using below command:
Get-Service "RemoteRegistry" -ComputerName "Win7-PC" | Stop-Service -PassThru

List all Windows Services and its running status

You can list all the services with display name and running status by using Powershell cmdlet Get-Service.
Get-Service
Start, Stop and Restart Windows Service using Powershell
Pass service name, if you want to get status of a single windows service.
Get-Service "RemoteRegistry"
Read More...