Tuesday, 27 August 2013

Bulk Insert into SQL Server using SqlBulkCopy in C#

    Recently, I was in need to fetch and insert data in a specific interval (day or hour) from another DataBase system. First I tried to fetch row and pull into my DataBase one by one. But when I test with huge data, I have faced performance issue due to continues inserting process. Then I googled and find better way with SQL Bulk Copy operation in C# by using .NET DataTable.

A .NET DataTable is basically an in memory representation of an MS SQL Server table. DataTable allow you to create the table in memory, add rows to it, edit values in specific columns of a row, etc, until all the data is exactly what you want. Once the DataTable is ready, it is just a simple statement to insert all the data at once. So rather than hundreds of thousands of insert statements, it is just one bulk copy, and rather than taking minutes or longer to run, it just takes seconds to dump all the data into MS SQL Server. Also, because the data is all in memory, it makes it very easy to test all of our stats. We simply pass in the data we would receive and assert on the values in the DataTable.

The following code is a simple example where we are saving daily prodcut sales data for each product.

Create SQL Table

CREATE TABLE [dbo].[ProductSalesData](
 [SaleDate] [smalldatetime] NOT NULL,
 [ProductName] [nvarchar](1000) NOT NULL,
 [TotalSales] [int] NOT NULL)

Bulk Insert into MS SQL Server using SqlBulkCopy in C# with DataTable

using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlBulkInsertExample
{
    class Program
    {
      static void Main(string[] args)
        {
            DataTable prodSalesData = new DataTable("ProductSalesData");

            // Create Column 1: SaleDate
            DataColumn dateColumn = new DataColumn();
            dateColumn.DataType = Type.GetType("System.DateTime");
            dateColumn.ColumnName = "SaleDate";

            // Create Column 2: ProductName
            DataColumn productNameColumn = new DataColumn();
            productNameColumn.ColumnName = "ProductName";

            // Create Column 3: TotalSales
            DataColumn totalSalesColumn = new DataColumn();
            totalSalesColumn.DataType = Type.GetType("System.Int32");
            totalSalesColumn.ColumnName = "TotalSales";

            // Add the columns to the ProductSalesData DataTable
            prodSalesData.Columns.Add(dateColumn);
            prodSalesData.Columns.Add(productNameColumn);
            prodSalesData.Columns.Add(totalSalesColumn);

            // Let's populate the datatable with our stats.
            // You can add as many rows as you want here!

            // Create a new row
            DataRow dailyProductSalesRow = prodSalesData.NewRow();
            dailyProductSalesRow["SaleDate"] = DateTime.Now.Date;
            dailyProductSalesRow["ProductName"] = "Nike";
            dailyProductSalesRow["TotalSales"] = 10;

            // Add the row to the ProductSalesData DataTable
            prodSalesData.Rows.Add(dailyProductSalesRow);

            // Copy the DataTable to SQL Server using SqlBulkCopy
            using (SqlConnection dbConnection = new SqlConnection("Data Source=ProductHost;Initial Catalog=dbProduct;Integrated Security=SSPI;Connection Timeout=60;Min Pool Size=2;Max Pool Size=20;"))
            {
                dbConnection.Open();
                using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
                {
                    s.DestinationTableName = prodSalesData.TableName;

                    foreach (var column in prodSalesData.Columns)
                        s.ColumnMappings.Add(column.ToString(), column.ToString());

                    s.WriteToServer(prodSalesData);
                }
            }
        }
    }
}

The Output is

select * from dbo.ProductSalesData

SaleDate               ProductName  TotalSales
27/08/2013 00:00:00    Nike         10

Related Articles:

Import CSV File Into SQL Server Using SQL Bulk Copy
How to read data from csv file in c# 
Get current time on a remote system using C# 
Convert DateTime to Ticks and Ticks to DateTime in C#
Convert Object To Byte Array and Byte Array to Object in C#
Add or Remove programs using C# in Control Panel 
Show balloon tooltip c#


Thanks,
Morgan
Software Developer

Monday, 26 August 2013

How to read data from csv file in c#

 We can read data from CSV file in many of custom ways. In this article, I am going to write the code to read data from CSV file into .NET DataTable by using TextFieldParser. don't try to search this class in C# library because which is not available in C#. TextFieldParser is the Visual basic class. So we need to add reference dll Microsoft.VisualBasic.

  • Open Visual Studio
  • Go to File ->New ->Project.
  • Then go to Visual C# ->Windows and select Console Application
  • Rename the project name as ReadCSVFile.
  • Right-click the Reference, click Add Reference,select Microsoft.VisualBasic, and click OK button

Import CSV file into DataTable C#

You can use the following code example to read data from CSV file in C#

using System;
using System.Data;
using Microsoft.VisualBasic.FileIO;

namespace ReadDataFromCSVFile
  {
    static class Program
      {
        static void Main()
        {
            string csv_file_path=@"C:\Users\Administrator\Desktop\test.csv";
            DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
            Console.WriteLine("Rows count:" + csvData.Rows.Count);            
            Console.ReadLine();
        }
    private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
        {
            DataTable csvData = new DataTable();
            try
            {
              using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
                 {
                    csvReader.SetDelimiters(new string[] { "," });
                    csvReader.HasFieldsEnclosedInQuotes = true;
                    //read column names
                    string[] colFields = csvReader.ReadFields();
                    foreach (string column in colFields)
                    {
                        DataColumn datecolumn = new DataColumn(column);
                        datecolumn.AllowDBNull = true;
                        csvData.Columns.Add(datecolumn);
                    }
                    while (!csvReader.EndOfData)
                    {
                        string[] fieldData = csvReader.ReadFields();
                        //Making empty value as null
                        for (int i = 0; i < fieldData.Length; i++)
                        {
                            if (fieldData[i] == "")
                            {
                                fieldData[i] = null;
                            }
                        }
                        csvData.Rows.Add(fieldData);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return csvData;
        }
      }
    }

Related Articles:

Bulk Insert into SQL Server using SqlBulkCopy in C#
Import CSV File Into SQL Server Using SQL Bulk Copy
Read CSV File and Insert Into SQL Server using Bulk Insert
Convert Object To Byte Array and Byte Array to Object in C#
Add or Remove programs using C# in Control Panel 
Show balloon tooltip c#



Thanks,
Morgan
Software Developer

Friday, 23 August 2013

Authenticated Users vs Domain Users

Both are built-in groups introduced in windows to control security of objects like user,computer and service account at different level.

Authenticated Users

The Authenticated Users group contains users who have authenticated to the domain or a domain that is trusted by the computer domain. Authenticated Users will contain all manually created user accounts in all trusted domains regardless of whether they are a member of the Domain Users group or not.  Authenticated Users specifically does not contain the built-in Guest account, but will contain other users created and added to Domain Guests.
 
The following list shows the members who are fall under this group
  1. All the domain users and  users who are in trusted domain.
  2. Local computers.
  3. Built-in system accounts.

The local computer account is always a member of the Authenticated Users group even when disconnected from the network.  However, just like Domain Users, the local computer account must first authenticate to the domain to be considered part of the Authenticated Users token when connecting remotely to other computers within its trusted domains.
                           
The SID for Authenticated Users is S-1-5-11.  Authenticated Users is available when applying permissions directly to an object, or can be placed in Built-in and user created Local computer groups.  Authenticated Users cannot be added as a member to another user created domain groups (Global, Domain Local, or Universal).  However, the Authenticated Users group can be added to the Built-in Domain Local groups.

When working with domain user accounts and local user accounts remember that the local user accounts will also be members of Authenticated Users, and will therefore have access to local resources secured with this permission.  However, the scope of the local user accounts’ access will not extend onto remote computers via the Authenticated Users group.  This is because while the local user account includes the SID for the Authenticated User group, the local user must still authenticate to any remote computer prior to access being granted.

 Recommendation for Security: Use the Authenticated Users group instead of the Everyone group to prevent anonymous access to a resource.

Domain Users

Domain Users is the group in which we can add or remove members that we can not do in Authenticated Users group . In a domain environment, the Administrator account and all new user accounts are automatically included as members of this group. This group is also a member of the Users local group for the domain and for every Windows computer in the domain

By default all users created in the domain are automatically members of this group.  However, the default Guest account in the domain is not a member of this group, instead it is placed in the Domain Guest group

The SID for Domain Users is S-1-5-<domain>-513.  The Domain Users group can be added to other domain groups, and can be given permissions directly to objects, as well as placed in Local computer groups.


You can refer this article http://technet.microsoft.com/en-us/library/dd277461.aspx to know about other built-in groups.

Thanks,
Morgan
Software Developer

Group Policy Infrastructure failed error in Resultant Set of Policy

I have got this Group Policy Infrastructure failed error in Windows 7 machine while working with GPO to configure Audit Policy settings. I was in need of configure Audit logon events policy as Success,Failure to audit logon,logoff and logon failure of every users with their workstation by the Event IDs 4624,4634. So that I have decided to apply Audit logon events policy to workstations through Default Domain Policy.

After edit the Audit logon events policy in Default Domain Policy as Success,Failure, I run the command GPUpdate /force in domain controller. then I moved to one of the workstation Windows 7 computer which is in the Domain Network, to check whether the Audit logon events policy is applied or not through Default Domain Policy. To check final result I run the command rsop.msc to view Resultant Set of Policy. I see the following output with Group Policy Infrastructure failed error.

Group Policy Infrastructure failed error in Resultant Set of Policy

The error detail is

Group Policy Infrastructure failed due to the error listed below.
The system cannot find the file specified.
Note:  Due to the GP Core failure, none of the other Group Policy components processed their policy.  Consequently, status information for the other components is not available.


Solution 1 : Group Policy Infrastructure failed error

I got resolved this issues by removing my Windows-7 PC from Domain Group, and changed to Work Group. Then again added the machine to Domain Group.

Steps to fix Group Policy Infrastructure failed error in Resultant Set of Policy:

1. Right-click the My Computer, click Change Settings, click the button Change, then now change the Member of from Domain to Work group. and click OK..

Group Policy Infrastructure failed error in Resultant Set of Policy


2. Restart the Computer

3. Login into PC with Local computer account

4. Again right-click the My Computer, click Change Settings, click the button Change, then now change the Member of from Work group to Domain . and click OK..

5.Again Restart the Computer

6.Now login with Domain user account and check Resultant Set of Policy by running the command rsop.msc. now you will get resolved from issue.


Solution 2 : Group Policy Infrastructure failed error

After I haved researched through google, I got many suggestions to edit hosts file.

The HOSTS file located in C:\Windows\System32\drivers\etc contained entries for my domain controllers. I simply removed entries which relevant to domain controller from the HOSTS file and now my Windows 7 pc get rid off Resultant Set of Policy issue.

Hope this will help some of you. and also I simply request you to comment if you got any other solution as it will help others.

Note: Please be cautious while you edit HOSTS file since it will make unwanted network issue if you edited with fault settings.

Thanks,
Morgan
Software Developer

Wednesday, 21 August 2013

How to create custom attribute in Active Directory

Active Directory structure contains different type schema attributes which are used to store unique information about the AD object. By default, Active Directory schema contains all the essential attributes to manage entire organization. But need of every organization will change day by day depends upon various business activity. So that modifying Active Directory schema is inevitable.

In this article I am going to explain about how to create Custom Attribute and how to add custom attribute to User Class.

Required Permission

Adding custom attribute involves modification in Active Directory schema which requires the modifying user to be a member of Schema Administrators and Enterprise Administrators groups. By default, the Administrator account is a member of the Schema Administrator group.

Adding custom attribute to user object includes the following procedures
  • Register Schema snap-in
  • Creating Custom Attribute
  • Adding Custom Attribute to User Class
  • Restarting Active Directory Domain Services

Register Schema snap-in

  1. Press the keys 'Windows' + 'R'.
  2. Type the command RegSvr32 SchmMgmt.dll in text field and click OK button.

     3. On successful Schema snap-in registration you can see the following confirmation message box.



Creating Custom Attribute

  1. Press the keys 'Windows' + 'R' to open Run Window.
  2. Type the command mmc.exe and click OK button.
  3. Go to File -> Add/Remove snap-in...or simply press the keys 'Ctrl' + 'M' to open Add/Remove snap-in.
  4. Select the snap-in Active Directory Schema,  click Add >,  and click the button OK.
        
     5. Expand the Active Directory Schema root node, right-click the node Attributes, click Create Attribute....(Go to Active Directory Schema ->Attributes ->Create Attribute...)

  6. If you receive Schema Object Creation warning message,click continue to proceed.

   7. Generating OID: To create custom attribute we need to give new OID. To create new OID, check this article http://www.morgantechspace.com/2013/08/generate-oid-to-create-custom-attribute.html to know about how to create new OID using VBScript. Copy the script code from above article and paste it in Notepad file and save the file with the extension .vbs like GenerateOID.vbs 

Run this VBScript file and you will see the output window like below screen.
     Note this OID: 1.2.840.113556.1.8000.2554.53105.25931.2174.18205.37173.12892922.10177807 and in your case you may get different OID depends upon your Domain.

8. Now I am going to create custom attribute panID .Fill the following parameters.
  • Common Name: Pan ID
  • LDAP Display Name: panID - (This value automatically populates while you typing Common Name but you can change it if you want give other value)
  • Unique X500 Object ID: 1.2.840.113556.1.8000.2554.53105.25931.2174.18205.37173.12892922.10177807
       

 9. Click the button OK. Now the new custom attribute panID created successfully and displayed in child node of Attributes. see the below image.



Adding Custom Attribute to User Class

 To add newly created attribute to User Class follow the below steps.

   1. Navigate to the node Active Directory Schema->Classes, select the class user


2. Right-click the user class, select properties, navigate to Attributes tab, and click Add button.


   3. Select the schema object panID and click OK button.
  
  

  4. Now, you have added panID as optional attributes for user class. click Apply to complete process.


 5. Now you have successfully added the panID attribute to user class. once again right-click the user class, select properties, navigate to Attributes tab and check your change has been updated or not.

Restarting Active Directory Domain Services

Now you have created custom attribute and added it into user class to apply these schema changes in complete Active Directory structure we need to restart the AD Domain Services.

1. Press the keys 'Windows'+ 'R' to open Run Window.
2. Type the command services.msc and click OK button.
3. Select the service Active Directory Domain Services,  right-click the service, click Restart, and click Yes to Restart all the related services.


Checking new attribute in Active Directory Users and Computers Console

1. Press the keys 'Windows'+ 'R' to open Run Window.
2. Type the command dsa.msc and click OK button.
3. Select the user object Administrator, Right-click->Properties ->Attributes and check the attribute panID.


Now, you have successfully created custom attribute panID and linked that attribute into user class.


Thanks,
Morgan
Software Developer

Generate OID to create Custom Attribute

This article contains vb script code to generate new OID using the Guid and the OID prefix 1.2.840.113556.1.8000.2554. I have got this source code from microsoft galary, thanks to Omar Sinno. I have removed some comments and modified the source as it below.


Function GenerateOID()
   'Initializing Variables
    Dim guidString, oidPrefix
    Dim guidPart0, guidPart1, guidPart2, guidPart3, guidPart4, guidPart5, guidPart6
    Dim oidPart0, oidPart1, oidPart2, oidPart3, oidPart4, oidPart5, oidPart6
    On Error Resume Next
    'Generate GUID
    Set TypeLib = CreateObject("Scriptlet.TypeLib")
    guidString = TypeLib.Guid
 'If no network card is available on the machine then generating GUID can result with an error.

  If Err.Number <> 0 Then
   Wscript.Echo "ERROR:Guid could not be generated, please ensure machine has a network card."
     Err.Clear
     WScript.Quit
  End If
    'Stop Error Resume Next
    On Error GoTo 0
    'The Microsoft OID Prefix used for the automated OID Generator
    oidPrefix = "1.2.840.113556.1.8000.2554"
    'Split GUID into 6 hexadecimal numbers
    guidPart0 = Trim(Mid(guidString, 2, 4))
    guidPart1 = Trim(Mid(guidString, 6, 4))
    guidPart2 = Trim(Mid(guidString, 11, 4))
    guidPart3 = Trim(Mid(guidString, 16, 4))
    guidPart4 = Trim(Mid(guidString, 21, 4))
    guidPart5 = Trim(Mid(guidString, 26, 6))
    guidPart6 = Trim(Mid(guidString, 32, 6))
    'Convert the hexadecimal to decimal
    oidPart0 = CLng("&H" & guidPart0)
    oidPart1 = CLng("&H" & guidPart1)
    oidPart2 = CLng("&H" & guidPart2)
    oidPart3 = CLng("&H" & guidPart3)
    oidPart4 = CLng("&H" & guidPart4)
    oidPart5 = CLng("&H" & guidPart5)
    oidPart6 = CLng("&H" & guidPart6)
    'Concatenate all the generated OIDs together with the assigned Microsoft prefix and return
    GenerateOID = oidPrefix & "." & oidPart0 & "." & oidPart1 & "." & oidPart2 & "." & oidPart3 & _
        "." & oidPart4 & "." & oidPart5 & "." & oidPart6
End Function
'Output the resulted OID with best practice info
Wscript.Echo "Your root OID is: " & VBCRLF & GenerateOID 

Generate OID

  • Copy this code and save it in Notepad file with the extension .vbs. something like GenerateOID.vbs
  • Run the script file then you will get output something like below image
Generate OID to create Custom Attribute


      You can use this OID for new attribute creation or some other purpose. 

Tuesday, 20 August 2013

How to Press Ctrl Alt Del in Remote Desktop Connection

Ctrl Alt Del in Remote Desktop 

           Remote Desktop Connection or Microsoft Terminal Services Client is an useful protocol that allows user to connect and manage remote computer with full screen support. However, as the Remote Desktop Connection screen is effectively running within the host Windows system desktop, users who use keyboard shortcuts frequently may get confused with keyboard shortcuts to use when working on remote PC’s desktop, or getting incorrect, erroneous or unexpected behavior with keyboard shortcuts and accelerators.

When we trying to trigger Ctrl Alt Del function on remote system connected via Remote Desktop Connection, the keyboard shortcut combination pressed will bring up the Ctrl-Alt-Del function on the local machine instead of the machine remotely logged on via RDC.

To get the intended result, a slightly different keyboard shortcuts are used when applied to a remote desktop session window.

The below table document lists the commonly used keyboard shortcuts key combination to use in Remote Desktop Connection.


Local Machine Remote Desktop Connection Usage
CTRL+ALT+DEL CTRL+ALT+END To Open Microsoft Windows NT Security dialog box.
CTRL+PAGE UP ALT+PAGE UP Switch between programs from left to right.
CTRL+PAGE DOWN ALT+PAGE DOWN Switch between programs from right to left.
ALT+TAB ALT+INSERT Cycle through the programs in most recently used order.
CTRL+ESC ALT+HOME Display the Start menu.
ALT+DELETE Display the Windows menu.
CTRL+ALT+BREAK Switch the client computer between a window and a full screen.


Note : This article is applies to Windows Server 2003, Windows Server 2008,Windows Server 2008 R2, Windows Server 2012, Windows 7 and Windows 8.

Thanks,
Morgan
Software Developer

Monday, 19 August 2013

How to Sign out and Switch User in Windows 8

Hi, Welcome to the Windows 8 world. Microsoft introduced many of new features in Windows 8, it also changed most of its basic User Interface design in a way to give easy support for touch screen mode.
In this article I am going to write about the basic options Sign out and Switch User.

You can do these basic actions in many ways.

Solution 1 to Sign out and Switch User in Windows 8 From CTRL ALT DEL Screen

Press the CTRL+ALT+DEL keys. From here you can select  Sign out (Log off) and Switch user.

NOTE: A Switch user option will not be available unless you have already added the user account

How to Switch User in Windows 8


Solution 2 to Sign out and Switch User in Windows 8 From Start Screen Screen

1.Go to the Start screen by clicking Windows key or CTRL+ESC 
2.Click your user name to select the Sign out (Log off),Switch user,Lock, option.

How to Switch User in Windows 8



Solution: 3 - From Shut Down Windows Dialog Box

1.Press the Windows+keys(Go to the desktop)
2.Press the ALT+F4 keys.
3.Now, you can select Sign out (Log off) and Switch user.

How to Switch User in Windows 8


Note : This article is applies to Windows Server 2012 and Windows 8.

Thanks,
Morgan
Software Developer

Saturday, 17 August 2013

Active Directory Change and Security Event IDs

Active Directory build-in change auditing events categorized under following three policy settings.
  • Audit account management
  • Audit directory service access
  • Audit directory service changes (available only from Win 2008 R2 or later)
Audit account management

The Audit account management events provides the high level auditing of user,computer and group maintenance changes. This policy events also categorized as following ways.
  1. User Account Management
  2. Computer Account Management
  3. Security Group Management
  4. Distribution Group Management
1.User Account Management

The following table document lists the event IDs of the user account management category.
Event ID Reason
4720 A user account was created.
4722 A user account was enabled.
4723 An attempt was made to change an account's password.
4724 An attempt was made to reset an accounts password.
4725 A user account was disabled.
4726 A user account was deleted.
4738 A user account was changed.
4740 A user account was locked out.
4767 A user account was unlocked.
4780 The ACL was set on accounts which are members of administrators groups.
4781 The name of an account was changed.
4794 An attempt was made to set the Directory Services Restore Mode administrator password
5376 Credential Manager credentials were backed up.
5377 Credential Manager credentials were restored from a backup.

2.Computer Account Management

The following table document lists the event IDs of the Computer Account Management category.

Event ID Reason
4741 A computer account was created.
4742 A computer account was changed.
4743 A computer account was deleted.

3.Security Group Management

The following table document lists the event IDs of the Security Group Management category.
Event ID Reason
4727 A security-enabled global group was created.
4728 A member was added to a security-enabled global group.
4729 A member was removed from a security-enabled global group.
4730 A security-enabled global group was deleted.
4731 A security-enabled local group was created.
4732 A member was added to a security-enabled local group.
4733 A member was removed from a security-enabled local group.
4734 A security-enabled local group was deleted.
4735 A security-enabled local group was changed.
4737 A security-enabled global group was changed.
4754 A security-enabled universal group was created.
4755 A security-enabled universal group was changed.
4756 A member was added to a security-enabled universal group.
4757 A member was removed from a security-enabled universal group.
4758 A security-enabled universal group was deleted.
4764 A groups type was changed.

4.Distribution Group Management

The following table document lists the event IDs of the Distribution Group Management category.

Event ID Reason
4744 A security-disabled local group was created.
4745 A security-disabled local group was changed.
4746 A member was added to a security-disabled local group.
4747 A member was removed from a security-disabled local group.
4748 A security-disabled local group was deleted.
4749 A security-disabled global group was created.
4750 A security-disabled global group was changed.
4751 A member was added to a security-disabled global group.
4752 A member was removed from a security-disabled global group.
4753 A security-disabled global group was deleted.
4759 A security-disabled universal group was created.
4760 A security-disabled universal group was changed.
4761 A member was added to a security-disabled universal group.
4762 A member was removed from a security-disabled universal group.
4763 A security-disabled universal group was deleted.

Audit directory service access

Audit directory service access events provides the low-level auditing for all types of objects in AD. Directory service access events not only logs the information of an object that was accessed and by whom but also logs exactly which object properties were accessed.

The following table document lists the event IDs of the Distribution Group Management category.

Event ID Reason
4661 A handle to an object was requested
4662 An operation was performed on an object.
5139 A directory service object was moved.

Directory Service Changes

The events which are comes under this category includes the extra details like Old Value and New Value of the changed properties.This Advanced Audit Policy comes under the subcategory of  Directory Service Access.

The following table document lists the event IDs of the Directory Service Changes subcategory.

Event ID Reason
5136 A directory service object was modified.
5137 A directory service object was created.
5138 A directory service object was undeleted
5139 A directory service object was moved.
5141 A directory service object was deleted.



Thanks,
Morgan
Software Developer

How to enable Active Directory Change Events

Active Directory security event audit is vital in order to prevent security incidents and malpractices.Active Directory itself includes build-in auditing that lets you track the various changes within Directory.The build-in auditing events mainly controlled by the following two policy settings via Group Policy.

     1.Audit account management
     2.Audit directory service access

Audit account management

    The Audit account management events provides the high level auditing of user,computer and group maintenance changes. This policy makes to log the events for the following maintenance related changes.
  • Created and Deleted
  • Enabled and Disabled
  • Password Change
  • Password Reset
  • Locked out
  • Unlocked
  • Rename
  • Members Added
  • Members Removed

Audit directory service access

Audit directory service access events provides the low-level auditing for all types of objects in AD. Directory service access events not only logs the information of an object that was accessed and by whom but also logs exactly which object properties were accessed. Since the Audit directory service access policy makes to log the events for changes on every object we must enable auditing on object level and audit policy at the system level.


Enable Audit Policy for AD Change Audit


To enable Audit Policy settings in every Domain Controller, We need to configure audit settings in Default Domain Controllers Policy, or you can create new GPO and links it to the Domain Controllers OU via GPMC console, or else you can configure the corresponding policies on Local Security Policy of every Domain Controllers which are in the domain that you are going to enable change auditing.

Follow the below steps to enable change auditing via Default Domain Controllers Policy.

    1. Press the key 'Window' + 'R'

    2. Type the command gpmc.msc, and click OK.

         Note: Skip the above steps by clicking Start -->Administrative Tools -->Group Policy Management.

    3. Right-click the Default Domain Controllers Policy, and click Edit. - refer the below image.

How to enable Active Directory Change Events


    4. Navigate to the node Audit Policy (Computer Configuration->Policies->Windows Settings->Security Settings->Local Policies->Audit Policy).

    5. Now edit Audit account management and Audit directory service access as Success to enable active directory change auditing. - refer the below image.

How to enable Active Directory Change Events

    6. Run the command gpupdate /force from command prompt to update group policy settings.


Enable Object Level Security Audit 


    As we discussed earlier about Audit directory server access, Since the Audit directory service access policy makes to log the events for every object change we must enable auditing on object level. You can enable auditing on single object, or OU level, or  Domain level.

Follow the below steps to enable Domain level auditing.

    1. Press the key 'Window' + 'R'

    2. Type the command dsa.msc, and click OK.

        Note: Skip the above steps by clicking Start -->Administrative Tools -->Active Directory Users and Computers.

    3. Right-click the Domain object, and click the properties

    4. Click the Security tab.
  
        Note: If the Security tab is not available, Ensure the option Advanced Features is checked                  under the View menu.

    5. Click the button Advanced, and select the tab Auditing.

    6. Click the button Add, find the user Everyone, and click OK.

    7.  Check the Successful auditing for Write all properties,Delete,Delete Subtree,Modify Permissions,Modify Owner,Create all child objects,Delete all child objects. -refer below image.

       Note: You can configure these settings as per your requirement.

Steps to enable Active Directory Change Events

    8. Click the button OK, and click Apply.

Now we have successfully configured the change auditing for complete Active Directory domain.You can see the Security event logs for whatever the changes happened in every AD objects.

Audit directory service changes


    Besides these two policy settings, we can also fine tune the auditing by Audit directory service changes which is available from  Windows Server 2008 R2 and later versions.The events which are comes under this category includes the extra details like Old Value and New Value of the changed properties.This Advanced Audit Policy comes under the subcategory of  DS Access.

You can enable Advanced Audit Policy setting in the following two ways.

    1. Go to the node DS Access (Computer Configuration->Policies->Windows Settings->Security Settings->Advanced Audit Policy Configuration -> DS Access)

    2. Now edit Audit directory service changes as success as shown in below image.

Steps to enable Active Directory Change Events




You can also enable this Advanced Audit policy setting by using Auditpol.exe.
Run this command in an elevated command prompt:
Auditpol /set /subcategory:"Directory Service Changes" /success:enable
You can refer this article http://www.morgantechspace.com/2013/08/active-directory-change-audit-events.html to know about various Event IDs.

Note : This article is applies to Windows Server 2003, Windows Server 2008,Windows Server 2008 R2 and Windows Server 2012.

Related Articles:

How password policy works in Active Directory
Account Lockout Policy in Active Directory
Logon/Logoff Events in Active Directory
Active Directory Change Event IDs
LastLogon vs LastLogonTimeStamp
How to create Fine Grained Password Policy

Thanks,
Morgan
Software Developer

Friday, 16 August 2013

What is .tmp file ?

Temporary file

The .tmp file is nothing but the Temporary file or foo file, a temporary file is a file created to hold information temporarily while a file is being created. After the program has been closed, the temporary file should be deleted. Temporary files are used to help recover lost data if the program or computer is abnormally halted.

How to remove temporary (.tmp) files

     If you are using the operating system Windows 98 or later you can use Windows Disk Cleanup utility to delete temporary files and cleanup other portions of your computer.
 
Windows Disk Cleanup utility first introduced with Microsoft Windows 98 and included in all future releases of Microsoft Windows that enables users to remove files that are no longer needed or that can be safely deleted.

Follow the below steps to open the Microsoft Disk Cleanup.

1.Click the Start button.
2.Click Programs, then go to Accessories -> System Tools
3. In System Tools, click Disk Cleanup then you could see the below dialog, select the Drive which you want clean up.

How to delete .tmp files

4.Once Disk Cleanup is open check the option Temporary file in Files to delete: section like shown on below image.To the right of each option you can see the disk drive space each of the items are taking on your hard drive.

How to delete .tmpfiles


Note: We highly recommend that users DO NOT check the option to Compress old files. Often this option causes more issues than the small amount of space it recovers is worth.

5.Click OK to start the cleanup process.


Thanks,
Morgan
Software Developer

What is Autorun.inf file

Autorun.inf is a configuration file which is used to tell windows about what should happen if a specified action takes place in the respective drive.Normally, it will be used to run the executable file after the CD or DVD or USP device loaded successfully in the computer. This file must be located in the root directory of a volume. As Windows has a case-insensitive view of filenames, the autorun.inf file can be stored as AutoRun.inf or Autorun.INF or any other case combination.

When you open the Autorun.inf file, you could see the following inputs

Autorun inf

The AutoRun section contains the default AutoRun commands. An autorun.inf file must contain this section to be valid.

Open = [exepath\]exefile [param1 [param2 ...]]
Specifies the path, file name and optional parameters to the application that AutoRun launches when a user inserts a disc in the drive. It is the CreateProcess function that is called by AutoRun.

icon = iconfilename[,index]
The name of a file resource containing an icon. This icon replaces the standard drive icon in Windows Explorer. This file must be in the same directory as the file specified by the open key.

The following image shows the files while opening the USB device that contains Autorun.inf file.

Autorun configuration file


To disable the Autorun functionality in windows you can refer this Microsoft KB article http://support.microsoft.com/kb/967715


Thanks,
Morgan
Software Developer





Microsoft Office MIME Types

This article describes MIME Types and the corresponding file extension of the Microsoft Office documents. It will very be useful for document analysis, and you can easily define ContentType for the Microsoft Office associated documents in ASP.NET applications. Also you can use this details to customize MIME types in IIS server configuration.

 For Microsoft Office Excel, you can define content type like this example.
 Aspx page
<%response.ContentType="application/vnd.ms-excel"%>

 C#
  Response.ContentType = "application/vnd.ms-excel";

The following table lists the MIME types and file extensions that are associated  with the Microsoft Office documents.


Extension MIME Type
.doc application/msword
.dot application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm application/vnd.ms-word.document.macroEnabled.12
.dotm application/vnd.ms-word.template.macroEnabled.12
.xls application/vnd.ms-excel
.xlt application/vnd.ms-excel
.xla application/vnd.ms-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm application/vnd.ms-excel.sheet.macroEnabled.12
.xltm application/vnd.ms-excel.template.macroEnabled.12
.xlam application/vnd.ms-excel.addin.macroEnabled.12
.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12
.ppt application/vnd.ms-powerpoint
.pot application/vnd.ms-powerpoint
.pps application/vnd.ms-powerpoint
.ppa application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm application/vnd.ms-powerpoint.template.macroEnabled.12
.ppsm application/vnd.ms-powerpoint.slideshow.macroEnabled.12


Thanks,
Morgan
Software Developer

Wednesday, 14 August 2013

Remote Group Policy update using gpupdate in C#

You can update or refresh the GPO easily by the command line utility tool gpupdate. By using  following  commands we can update GPO on local machine.

 gpupdate /force -update user and computer configuration
 gpupdate /target:computer /force -update only computer configuration
 gpupdate /target:user /force -update only user configuration

Remote Group Policy update in C#

You can use the below C# function to update GPO on remote machine.
Note: For local machine don't use username,password and Impersonation

private static void UpdateGPO(string machinename)
        {
           try
            {
                ConnectionOptions connectionOptions = new ConnectionOptions();

                connectionOptions.Username = @"Domain\Administrator";
                connectionOptions.Password = "password";
                connectionOptions.Impersonation = ImpersonationLevel.Impersonate;

                ManagementScope scope = new ManagementScope("\\\\" + machinename + "\\root\\CIMV2", connectionOptions);

                scope.Connect();

                ManagementClass clas = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions());

                ManagementBaseObject inparams = clas.GetMethodParameters("Create");

                inparams["CommandLine"] = "GPUpdate /force";

                ManagementBaseObject outparam = clas.InvokeMethod("Create", inparams, null);
            }
            catch (Exception ex)
            {

            }
        }

Local Group Policy update in C#

You can use the below C# function to update GPO on local machine.

private static void UpdateGPO()
  {
try
    {
      Process proc = new Process();
      ProcessStartInfo procStartInfo = new ProcessStartInfo(@"cmd.exe","/c"+"gpupdate/force");
      procStartInfo.RedirectStandardOutput = true;
      procStartInfo.UseShellExecute = false;
      procStartInfo.CreateNoWindow = true;
      procStartInfo.LoadUserProfile = true;
      proc.StartInfo = procStartInfo;
      proc.Start();
      proc.WaitForExit();
    }
   catch (Exception ex)
    {

    }
}

Related Articles:

Active Directory Attribute mapping with Friendly name - user
Active Directory Search Filter Examples
Create new Active Directory User in C#
How to get list of all domain controllers in C#
Restore a deleted Active Directory object using C#
Active Directory search filter by ObjectGuid 


Thanks,
Morgan
Software Developer

Tuesday, 13 August 2013

Event ID 4656 - Repeated Security Event log - PlugPlayManager

   I have got an issue while working with File System Auditing where the event ID is being repeatedly logged on my server 2008 R2 machine. Since I was in need of analyzing every events by manually, I have really stuck with huge amount of 4656 events for the object PlugPlayManager. So that I have decided to analyze reason for generating these events.

See the event in this picture

PlugPlayManager Event 4656 Object Access

Possible Solution: 1
Event 4656 should occur if the Success or Failure audit was enabled for Handle Manipulation using command line tool Auditpol.
Subcategory: Handle Manipulation
You will get following three Event IDs if Handle Manipulation enabled
4656 A handle to an object was requested.
4658 The handle to an object was closed.
4690 An attempt was made to duplicate a handle to an object.
If you would like to get rid of these Object Access event 4656 then you need to run the following command:
Auditpol /set /subcategory:"Handle Manipulation" /Success:disable
Possible Solution: 2
    You can also check the Advanced Audit Policy Configuration in Local Security Policy.
1.Press the key Windows + R
2.Type command secpol.msc and click OK
3.Then go to the node Advanced Audit Policy Configuration->Object Access.
4.Check the audit setting Audit Handle Manupulation. If it is configured as Success, you can revert it Not Configured and Apply the setting.
  
Event ID 4656 - Repeated Security Event log - PlugPlayManager


Possible Solution: 3
    If the setting is inherited from any other GPO to Local Security Policy,You need to edit the specific GPO which is configured with the Setting Audit Handle Manupulation. You can find the GPO by running Resultant Set of Policy. 
   
1.Press the key Windows + R 
   
2.Type command rsop.msc and click OK.
   
3.Now you can the below result window. Then go to the node Computer Configuration ->Windows Settings ->Local Polices-> Audit Policy.
   
Event ID 4656 - Repeated Security Event log - PlugPlayManager


  4.Now, you can see the Source GPO of the setting Audit Object Access which is the root Setting for Audit Handle Manipulation.
  5.Then you can edit the Audit Handle Manupulation of corresponding GPO by running GPMC.msc command through Run window or command window.
Note:You need run the command GPUpdate /force after every changes to apply group policy to system immediately.