Monday, 9 December 2013

Validate Email Address in C#

Description:

In this article, I am going to write C# code examples to Check or Validate Email Address/Email ID using Regular Expressions and C# code example to Test EMail Address is valid or not by sending Test mail.

Summary:


Validate Email Address in C# using Regular Expressions

Here, we are using Regex class to represents Regular Expressions
public static bool IsValidEmailAddressByRegex(string mailAddress)
{
    Regex mailIDPattern = new Regex(@"[\w-]+@([\w-]+\.)+[\w-]+");

    if (!string.IsNullOrEmpty(mailAddress) && mailIDPattern.IsMatch(mailAddress))
    {
        return true;
    }
    else
    {
        return false;
    }
}

Validate Email Address/Email ID in C# using Regular Expressions(2)

public static bool IsValidEmailAddressByRegex2(string mailAddress)
{
    Regex mailIDPattern = new Regex(@"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
    + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
    + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$", RegexOptions.IgnoreCase);

    if (!string.IsNullOrEmpty(mailAddress) && mailIDPattern.IsMatch(mailAddress))
    {
        return true;
    }
    else
    {
        return false;
    }
}

Validate Email Address in C# using Regular Expressions(3)

public static bool IsValidEmailAddressByRegex3(string mailAddress)
{
    Regex mailIDPattern = new Regex("^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled);

    if (!string.IsNullOrEmpty(mailAddress) && mailIDPattern.IsMatch(mailAddress))
    {
        return true;
    }
    else
    {
        return false;
    }
}

Validate Email Address Pattern and Test Email ID is Valid or Not in C#

You can use this C# function to validate E Mail Address string pattern and to Test the given E Mail ID is Valid Address or not by sending the Test mail.
public static bool ValidateAndTestEmailAddress(string mailAddress)
{
    Regex mailIDPattern = new Regex(@"[\w-]+@([\w-]+\.)+[\w-]+");

    if (!string.IsNullOrEmpty(mailAddress) && mailIDPattern.IsMatch(mailAddress))
    {
        System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();

        // your mail server address
        smtpClient.Host = "smtp.server1.net";

        // your mail server port address
        smtpClient.Port = 25;

        // Credentials to use mail server if required
        smtpClient.Credentials = new NetworkCredential("admin@morgantechspac.com", "yourpassword");

        try
        {
            // Send Test Mail to Check Email Address/E mail ID is Valid or Not ...

            smtpClient.Send("admin@morgantechspac.com", mailAddress, "Mail ID testing", "Validate Mail Address");

            //  Email Address was Verified!

            return true;
        }
        catch (Exception exp)
        {
            //Failed to send test mail...
            Console.WriteLine(exp.Message);
            return false;
        }
    }
    else
    {
        //Invalid email address pattern...
        return false;
    }
}

Validate Email Address Pattern and Check Is Valid EMail Domain

You can use this Regex pattern to validate Email Address string pattern and also to check whether the given EMail Address contains Valid Email Domain or Not.

From http://www.regular-expressions.info/email.html
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@
(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|
biz|info|mobi|name|aero|asia|jobs|museum)\b

Thanks,
Morgan
Software Developer

Thursday, 5 December 2013

Event ID 2004 Resource Exhaustion Diagnosis Events

Description:

In this article, I am going to explain about Event ID 2004 Resource Exhaustion Diagnosis Events and how to configure or enable alert mail for this event. The Event ID 2004 falls under the category of Resource Exhaustion Detector component of Windows Resource Exhaustion Detection and Resolution (RADAR), it identifies the top three memory consuming programs and warns you when the system commit charge reaches a critical level.

Summary:


Event ID 2004 Log Source:

Log Name:      System
Source:        Microsoft-Windows-Resource-Exhaustion-Detector
Date:          04/12/2013 3:17:33 PM
Event ID:      2004
Task Category: Resource Exhaustion Diagnosis Events
Level:         Warning
Keywords:      Events related to exhaustion of system commit limit (virtual memory).
User:          SYSTEM
Computer:      myPC.myDomain.local
Description:
Windows successfully diagnosed a low virtual memory condition. The following programs consumed the most virtual memory: sqlservr.exe (1956) consumed 729833472 bytes, devenv.exe (3896) consumed 404164608 bytes, and w3wp.exe (2516) consumed 240144384 bytes.

Steps to Configure Alert Notification mail for Event ID 2004:

1. Open the Event Viewer MMC by running the command eventvwr.msc.
2. Expand the node Windows Logs, and select System
3. Search and and select the Event 2004, right-click on the event entry and click Attach Task To This Event..

Event ID 2004 Resource Exhaustion Diagnosis Events


4. Type the description like 'This is a warning alert message for high memory usage on the following programs' and click Next

event id 2004 resource exhaustion detector

event id 2004 resource exhaustion detector windows 7


5. Select Send an e-mail option and click Next.

event id 2004 source microsoft-windows-resource-exhaustion-detector


6.Go to Action -> Send an e-mail section, type the From and To Address and SMTP Server address for your Mail Server and click Next.

event id 2004 source microsoft-windows-resource-exhaustion-detector


7. Now click the Finish button to complete Alert Mail Notification for the Event ID 2004

event id 2004 source microsoft-windows-resource-exhaustion-detector





Thanks,
Morgan
Software Developr

Wednesday, 4 December 2013

Union vs Union ALL in SQL Server

Description:

In this article, I am going write the difference between Union vs Union All in SQL Server in multiple rows insert statement.

Union vs Union All in SQL

UNION ALL - It will not remove duplicate rows when you insert multiple rows or values by using Union All, it just combine all the rows.

UNION - Removes duplicate rows when you insert multiple rows or records by using Union.

Union ALL in SQL to Insert multiple rows or records

-- Check and Drop Existing Temp Table
IF EXISTS(SELECT 1 FROM tempdb.dbo.sysobjects WHERE ID = OBJECT_ID(N'tempdb..#tempTable'))
          DROP TABLE #tempTable

--Create temp table
CREATE TABLE #tempTable (ID INT, UserName NVARCHAR(50));

-- Insert Multiple Values into SQL Server using UNION ALL
INSERT INTO #tempTable (ID, UserName) 
Select 1, 'User1'
UNION ALL
Select 2, 'User2'
UNION ALL
Select 2, 'User2'
UNION ALL
Select 3, 'User3'

--Select inserted values from temp table 
Select * From #tempTable

Union vs Union All in SQL Server

Union in SQL to Insert multiple records/rows

-- Check and Drop Existing Temp Table
IF EXISTS(SELECT 1 FROM tempdb.dbo.sysobjects WHERE ID = OBJECT_ID(N'tempdb..#tempTable'))
          DROP TABLE #tempTable

--Create temp table
CREATE TABLE #tempTable (ID INT, UserName NVARCHAR(50));

-- Insert Multiple Values into SQL Server using UNION
INSERT INTO #tempTable (ID, UserName) 
Select 1, 'User1'
UNION 
Select 2, 'User2'
UNION 
Select 2, 'User2'
UNION 
Select 3, 'User3'

--Select inserted values from temp table 
Select * From #tempTable

Union vs Union All in SQL Server

Note: If you have no problem with duplicate rows, you can use Union All instead of Union for better performance. since Union query will check all the rows to find duplicates, it will takes more execution time compared with Union ALL.

Thanks,
Morgan
Software Developer

Insert Multiple Rows into Table in SQL Server

Description:

In this article, I am going to write T SQL Script to Insert Multiple Rows into Table in single statement with different ways in SQL Server. You can choose best way as per your wish. But If you have 1000 of records I would suggest you to go with SqlBulkCopy in C#.

Summary:


Insert Multiple Rows into Table in SQL Server by Single Statement

-- Check and Drop Existing Temp Table
IF EXISTS(SELECT 1 FROM tempdb.dbo.sysobjects WHERE ID = OBJECT_ID(N'tempdb..#tempTable'))
          DROP TABLE #tempTable

--Create temp table
CREATE TABLE #tempTable (ID INT, UserName NVARCHAR(50));

-- Insert Multiple Values into SQL Server by Single Statement
INSERT INTO #tempTable (ID, UserName) VALUES (1, 'User1');
INSERT INTO #tempTable (ID, UserName) VALUES (2, 'User2');
INSERT INTO #tempTable (ID, UserName) VALUES (3, 'User3');

--Select inserted values from temp table 
Select * From #tempTable


Insert Multiple Rows into Table with Union ALL

-- Check and Drop Existing Temp Table
IF EXISTS(SELECT 1 FROM tempdb.dbo.sysobjects WHERE ID = OBJECT_ID(N'tempdb..#tempTable'))
          DROP TABLE #tempTable

--Create temp table
CREATE TABLE #tempTable (ID INT, UserName NVARCHAR(50));

-- Insert Multiple Values into SQL Server using UNION ALL
INSERT INTO #tempTable (ID, UserName) 
Select 1, 'User1'
UNION ALL
Select 2, 'User2'
UNION ALL
Select 2, 'User2'
UNION ALL
Select 3, 'User3'

--Select inserted values from temp table 
Select * From #tempTable

Insert Multiple Rows into Table with Union ALL


Note: When you insert multiple rows using UNION ALL, it just combines the all the rows. It will not remove duplicate rows. So if you want to remove duplicate rows from multiple insert you need to use just UNION instead of  UNION ALL

Insert Multiple Rows into Table in SQL Server using Union by Single Statement

-- Check and Drop Existing Temp Table
IF EXISTS(SELECT 1 FROM tempdb.dbo.sysobjects WHERE ID = OBJECT_ID(N'tempdb..#tempTable'))
          DROP TABLE #tempTable

--Create temp table
CREATE TABLE #tempTable (ID INT, UserName NVARCHAR(50));

-- Insert Multiple Values into SQL Server using UNION
INSERT INTO #tempTable (ID, UserName) 
Select 1, 'User1'
UNION 
Select 2, 'User2'
UNION 
Select 2, 'User2'
UNION 
Select 3, 'User3'

--Select inserted values from temp table 
Select * From #tempTable

Insert Multiple Rows into Table with Union


Note: When you insert multiple rows using UNION, it removes the duplicate rows. So if you don't want to remove duplicate rows from multiple insert you need to use UNION ALL instead of  UNION.

Insert Multiple Rows into Table by select Rows from another Table

-- Check and Drop Existing Temp Table
IF EXISTS(SELECT 1 FROM tempdb.dbo.sysobjects WHERE ID = OBJECT_ID(N'tempdb..#tempTable'))
          DROP TABLE #tempTable

--Create temp table
CREATE TABLE #tempTable (ID INT, UserName NVARCHAR(50));

-- Insert Multiple Values into table in SQL Server using UNION
INSERT INTO #tempTable (ID, UserName) 
Select 1, 'User1'
UNION 
Select 2, 'User2'
UNION 
Select 3, 'User3'

IF EXISTS(SELECT 1 FROM tempdb.dbo.sysobjects WHERE ID = OBJECT_ID(N'tempdb..#tempTable2')) 
           DROP TABLE #tempTable2

--Create second temp table
CREATE TABLE #tempTable2 (ID INT, UserName NVARCHAR(50));

-- Insert Multiple Values into table by select rows from another table 
INSERT INTO #tempTable2 (ID, UserName) Select ID,UserName From #tempTable


--Select inserted values from second temp table 
Select * From #tempTable2



Insert Multiple Rows into Table using SqlBulkCopy in C# with DataTable

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
04/12/2013 00:00:00    Nike         10

Thanks,
Morgan
Software Developer

Monday, 2 December 2013

HTTP Error 503. The service is unavailable.

Description:

     I have hosted my Web Application in IIS 7.5. It was worked well for the past one or two months. But today, when I try connect my Web Application thorough URL I got the HTTP error page with the message HTTP Error 503. The service is unavailable.

HTTP Error 503. The service is unavailable.

Cause of HTTP Error 503. The service is unavailable:

    After I have analyzed some time, found the reason. The HTTP Error 503. The service is unavailable occurs if the Application Pool of the corresponding Wep Application is Stopped or Disabled or Paused.
Check the following two Fix/Solutions to resolve this issue.


Steps to fix HTTP Error 503. The service is unavailable: Solution 1

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


HTTP Error 503. The service is unavailable.


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

HTTP Error 503. The service is unavailable.

4. Now go to Application Pools section, here you can see the corresponding Application Pool is in Stopped state. right-click on the Application Pool and Start it, also restart your Web Application.

HTTP Error 503. The service is unavailable. Start Application Pool


5. Now your problem would be solved, if not solved then check the below solution.

Fix HTTP Error 503. The service is unavailable: Solution 2

      Issue may be solved for some of them after completed the above steps. But in my case, I have started Application Pool, then I restarted my Web Application. Then when I connect my webpage, once again I got the same problem, then I went to further analyze from the event log. I found three System Events, Event ID 5021, Event 5057, Event 5059.

 Event ID 5012 Source:
Source:        Microsoft-Windows-WAS
Event ID:      5021
Level:         Warning
Description:
The identity of application pool AuditAppPoolV4 is invalid. The user name or password that is specified for the identity may be incorrect, or the user may not have batch logon rights. If the identity is not corrected, the application pool will be disabled when the application pool receives its first request.  If batch logon rights are causing the problem, the identity in the IIS configuration store must be changed after rights have been granted before Windows Process Activation Service (WAS) can retry the logon. If the identity remains invalid after the first request for the application pool is processed, the application pool will be disabled. The data field contains the error number. 
Event 5017 Source:
 
Source:        Microsoft-Windows-WAS
Event ID:      5057
Level:         Warning
Description:
Application pool AuditAppPoolV4 has been disabled. Windows Process Activation Service (WAS) did not create a worker process to serve the application pool because the application pool identity is invalid.
Event 5019 Source:
Source:        Microsoft-Windows-WAS
Event ID:      5059
Level:         Error
Description:
Application pool AuditAppPoolV4 has been disabled. Windows Process Activation Service (WAS) encountered a failure when it started a worker process to serve the application pool.
 
From the above Event IDs, it clearly indicates the root cause of the problem is Identity of the Application Pool. The given user Identity may be invalid due to expired password or locked or some other reason. So now we need to change it to new user Identity

 1. Go to the Application Pools section, right-click on the Application Pool, click Advanced Settings.

HTTP Error 503. The service is unavailable. Set Identity

 2. You can see the Identity name under Process model section in the opened window. click Identity name to Edit.

HTTP Error 503. The service is unavailable. Set Identity

 3. Click the Set button, enter new user credentials, and click OK.

HTTP Error 503 The service is unavailable. Set Identity


 4. Now Restart the Application Pool and Restart your Web Application.

HTTP Error 503 The service is unavailable. Set Identity

Create Table in SQL Server Examples

Description:

In this article, I am going to write T-SQL query to Create Table in MS SQL Server in different methods.

Summary:


Sql Query to Create Table in SQL Server

Use [MS_SQLServer_DB]
GO
CREATE TABLE [TestSQLTable](
ID int NOT NULL,
UserName nvarchar(100) NOT NULL,
MailID nvarchar(100) NULL)

Create Table with Identity/Auto Increment column in MS SQL Server

Use [MS_SQLServer_DB]
GO
CREATE TABLE [TestSQLTable](
ID int IDENTITY NOT NULL,
UserName nvarchar(100) NOT NULL,
MailID nvarchar(100) NULL)

Create Table with Primary Key in MS SQL Server

Use [MS_SQLServer_DB]
GO
CREATE TABLE [TestSQLTable](
ID int PRIMARY KEY NOT NULL,
UserName nvarchar(100) NOT NULL,
MailID nvarchar(100) NULL)

T-Sql Query to Create Table with Primary Key and Identity Column in SQL Server

Use [MS_SQLServer_DB]
GO
CREATE TABLE [TestSQLTable](
ID int IDENTITY PRIMARY KEY NOT NULL,
UserName nvarchar(100) NOT NULL,
MailID nvarchar(100) NULL)

Create Table with Primary Key and Custom Primary Key Name in SQL Server

Use [MS_SQLServer_DB]
GO
CREATE TABLE [TestSQLTable](
ID int NOT NULL,
UserName nvarchar(100) NOT NULL,
MailID nvarchar(100) NULL,
CONSTRAINT [PK_ID_AATable] PRIMARY KEY CLUSTERED(ID))

Create Table with Date Time column in SQL Server

Use [MS_SQLServer_DB]
GO
CREATE TABLE [TestSQLTable](
ID int NOT NULL,
UserName nvarchar(100) NOT NULL,
LoginTime datetime NULL)

Create Table with Foreign Key in SQL Server

--Relative Table(Foreign Key Table)

CREATE TABLE [RTable](
CityID int PRIMARY KEY NOT NULL,
CityName nvarchar(1000) NOT NULL)

--Primary Key Table

CREATE TABLE [PTable](
ID int IDENTITY PRIMARY KEY NOT NULL,
UserName nvarchar(100) NOT NULL,
MailID nvarchar(100) NULL,
City int NULL,
FOREIGN KEY (City) REFERENCES [RTable] (CityID))



Create Table with Sparse Column in SQL Server

The Sparse column feature exists only from SQL Server 2008 and later versions.
Use [MS_SQLServer_DB]
GO

CREATE TABLE [TestSQLTable](
ID int IDENTITY PRIMARY KEY NOT NULL,
UserName nvarchar(100) NOT NULL,
MailID nvarchar(100) SPARSE NULL,SpecialPurposeColumns XML COLUMN_SET FOR ALL_SPARSE_COLUMNS)

Create Table with NonClustered Index Column in SQL Server

Use [MS_SQLServer_DB]
GO

CREATE TABLE [TestSQLTable](
ID int IDENTITY PRIMARY KEY NOT NULL,
UserName nvarchar(100) NOT NULL,
JoinDate datetime NOT NULL,
MailID nvarchar(100) NULL)

CREATE NonClustered  Index Index_JoinDate
ON [TestSQLTable] (JoinDate)


Create Table with Unique Index Column in SQL Server

Use [MS_SQLServer_DB]
GO

CREATE TABLE [TestSQLTable](
ID int IDENTITY PRIMARY KEY NOT NULL,
UserName nvarchar(100) NOT NULL,
JoinDate datetime NOT NULL,
MailID nvarchar(100) NULL)

CREATE Unique INDEX Index_JoinDate
ON [TestSQLTable] (JoinDate)




Thanks,
Morgan
Software Developer

Event ID 4098 - Group Policy Shortcut error

Description:

In this article, I am going to give the solution/fix/cause for error Event 4098. Event ID 4098 is an error event that related to the Group Policy Shortcuts.

Event ID 4098 Source:

I saw the Event ID 4098 with the following error.
The computer 'My Settings' preference item in the 'Default Domain Policy {31B2F340-016D-11D2-945F-00C04FB984F9}' Group Policy object did not apply because it failed with error code '0x80070002 The system cannot find the file specified.' This error was suppressed.

Event ID 4098:Fix/Solution

After I have analyzed for some time found the following things as root cause for the problem.
 1. Open the Group Policy Management Console by running the command GPMC.msc.

 2. Click the Edit option on Default Domain Policy (the above 4098 event source shows this policy as error, In your case, it may be different policy )

3. Go to the Computer Shortcuts node, Computer Configuration ->Preferences -> Windows Settings ->Shortcuts, in right side pane check the target path of the shortcut link that causes for the Event 4098.
In my case, the shortcut link is My Settings

Event ID 4098 - Group Policy Shortcut error -Fix/Solution

3. Now change file path in shortcut link settings which caused the Group Policy Shortcut error.



 Thanks,
 Morgan Software
 Developer

Friday, 29 November 2013

Cannot drop database because it is currently in use in MS SQL Server

Description:

In this article, I am going to give Fix/Solution for the error 'Cannot drop database because it is currently in use' in MS SQL Server.. This error occurs when we try Delete or Drop database while the database connection is used by other users or other resources. So we need to close existing connections first then we need to Drop or Delete the database.

Summary:


Fix/Solution: Cannot drop database because it is currently in use in MS SQL Server

USE [MorganDB]
GO
/****** Object:  Database [MorganDB]    Script Date: 11/29/2013 13:29:16 ******/
DROP DATABASE [MorganDB]
GO
When you run above script, you will get an error message
'Msg 3702, Level 16, State 4, Line 2 Cannot drop database "MorganDB" because it is currently in use. ' because here we are using USE [MorganDB] as source DB to delete itself, so we need to change it to USE [master].

Fix/Solution:

USE [master]
GO
/****** Object:  Database [MorganDB]    Script Date: 11/29/2013 13:29:16 ******/
DROP DATABASE [MorganDB]
GO
Perfect Fix/Solution:

After changing source database as master, the script should works successfully. But sometimes connection may be opened by any other user. So, in that case, we also need to close existing open connections.

USE [master]
GO
ALTER DATABASE [MorganDB] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
/****** Object:  Database [MorganDB]    Script Date: 11/29/2013 13:40:36 ******/
DROP DATABASE [MorganDB]
GO

Fix/Solution in C#: Cannot drop database because it is currently in use in MS SQL Server

You can use the following C# code to close existing database connections and Drop or Delete Database in MS Sql Server.
public static void DeleteDataBase()
{
    using (SqlConnection sqlconnection = new
        SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=master;Integrated Security=SSPI;"))
    {
        sqlconnection.Open();
        // if you used master db as Initial Catalog, there is no need to change database
        sqlconnection.ChangeDatabase("master");

        string rollbackCommand = @"ALTER DATABASE [MorganDB] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE";

        SqlCommand deletecommand = new SqlCommand(rollbackCommand, sqlconnection);

        deletecommand.ExecuteNonQuery();

        string deleteCommand = @"DROP DATABASE [MorganDB]";

        deletecommand = new SqlCommand(deleteCommand, sqlconnection);

        deletecommand.ExecuteNonQuery();
    }
}


Fix/Solution in Sql Server Management Studio for the error 'Cannot drop database because it is currently in use' in MS SQL Server

If you try to dropping a database in Sql Server Management Studio UI when an user connected to the SQL Server Database you will receive the below mentioned error message.

Cannot drop database because it is currently in use in MS SQL Server


 You can avoid this error by checking the option Close existing connections.

Cannot drop database because it is currently in use- Close existing connections


Thanks,
Morgan
Software Developer

Thursday, 28 November 2013

Convert Image to Byte Array and Byte Array to Image in c#

Description:

In this article, I am going to give C# code examples to Convert Image to Byte Array and Byte Array to Image using ImageConverter and MemoryStream.

Summary:


Convert Image File into Byte Array in C#

public static byte[] ImageToByteArrayFromFilePath(string imagefilePath)
    {
        byte[] imageArray = File.ReadAllBytes(imagefilePath);
        return imageArray;
    }

Convert Image to Byte Array in C# using ImageConverter

Note: To use the classes ImageConverter and Image, you need to add the reference System.Drawing
public static byte[] ImageToByteArray(string imagefilePath)
{
    System.Drawing.Image image = System.Drawing.Image.FromFile(imagefilePath);
    byte[] imageByte = ImageToByteArraybyImageConverter(image);
    return imageByte;
}

private static byte[] ImageToByteArraybyImageConverter(System.Drawing.Image image)
{
    ImageConverter imageConverter = new ImageConverter();
    byte[] imageByte = (byte[])imageConverter.ConvertTo(image, typeof(byte[]));
    return imageByte;
}

Convert Image to Byte Array in C# using MemoryStream

Note: To use the classes ImageConverter and Image, you need to add the reference System.Drawing;
public static byte[] ImageToByteArray(string imagefilePath)
{
    System.Drawing.Image image = System.Drawing.Image.FromFile(imagefilePath);
    byte[] imageByte = ImageToByteArraybyMemoryStream(image);
    return imageByte;
}

private static byte[] ImageToByteArraybyMemoryStream(Image image)
{
    MemoryStream ms = new MemoryStream();
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    return ms.ToArray();
}


Convert Byte Array to Image in C# using MemoryStream

public static Image ByteArrayToImagebyMemoryStream(byte[] imageByte)
{
    MemoryStream ms = new MemoryStream(imageByte);
    Image image = Image.FromStream(ms);
    return image;
}

Convert Byte Array to Image File in C# using MemoryStream

public static void ByteArrayToImageFilebyMemoryStream(byte[] imageByte)
{
    MemoryStream ms = new MemoryStream(imageByte);
    Image image = Image.FromStream(ms);
    image.Save(@"C:\Users\Administrator\Desktop\imageTest.png");
}

Monday, 25 November 2013

VBScript to Disable Active Directory User Account

Description:

In this article, I am going to explain and write vbscript  code to Disable Active Directory user account using user's objectguid, samAccountName and distinguishedname and also Disable Bulk AD Users from CSV File using vbscript.

Note: You should run this vbscript code on a machine with windows Active Directory domain.

Summary:


VBScript to Disable Active Directory user by DistinguishedName

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for strUserDN with your own user's DN which you are going to disable.
3. Save the file with a .vbs extension, for example: Disable-AD-User.vbs
4. Double-click the vb script file (or Run this file from command window) to disable AD user.
' Disable-AD-User.vbs
' Sample VBScript to disable Active Directory user
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
Dim strUserDN
Dim objUser 

strUserDN= "CN=TestUser,OU=TestOU1,DC=MyDomain,DC=Com"
Set objUser = GetObject("LDAP://"& strUserDN) 
objUser.AccountDisabled = True
objUser.SetInfo

MsgBox("AD user disabled successfully using VBScript code.")

WScript.Quit 

VBScript to Disable Active Directory user using by ObjectGUID

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for strUserGUID with your own user's ObjectGUID string which you are going to disable.
3. Save the file with a .vbs extension, for example: DisableADUserWithGUID.vbs
4. Double-click the vb script file (or Run this file from command window) to disable AD user.
' DisableADUserWithGUID.vbs
' Sample VBScript to disable AD user with ObjectGUID
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
Dim strUserGUID
Dim objUser 

strUserGUID= "A777394D-0B5C-4FD2-BDDC-B12DDFB570A4"
Set objUser = GetObject("LDAP://<guid="& struserguid&">")
objUser.AccountDisabled = True
objUser.SetInfo

MsgBox("AD user disabled successfully using VBScript code.")

WScript.Quit 

VBScript to Disable AD User Account by samAccountName

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for strUserName with your own user's samAccountName which you are going to disable.
3. Save the file with a .vbs extension, for example: DisableADUserWithsamAccountName.vbs
4. Double-click the vb script file (or Run this file from command window) to disable AD user.
' DisableADUserWithsamAccountName.vbs
' Sample VBScript to disable AD user .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset,strUserDN
Dim strSamAccountName,objUser

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

varDNSDomain = objRootDSE.Get("defaultNamingContext")
varBaseDN = "<LDAP://" & varDNSDomain & ">"

strSamAccountName="Test"

' Filter on user objects.
varFilter = "(&(objectCategory=person)(objectClass=user)(samaccountname="& strSamAccountName &"))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "samaccountname,distinguishedname"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF
    ' Retrieve values and display.
    strUserDN = adoRecordset.Fields("distinguishedname").value
    Set objUser = GetObject("LDAP://"& strUserDN) 
        objUser.AccountDisabled = True
        objUser.SetInfo

    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

  If strUserDN = "" then
      Msgbox "No user found with the name '"& strSamAccountName &"'"
    Else  Msgbox "The user '"& strSamAccountName &"' disabled successfully..."
   end if

' close ado connections.
adoRecordset.Close
adoConnection.Close

VBScript to Disable Bulk AD users From CSV File

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Save the file with a .vbs extension, for example: DisableBulkADUsersFromCSV.vbs
3. Change the CSV file path C:\Users\Administrator\Desktop\All_Users.csv with your own file path.
4. Double-click the VBScript file (or Run this file from command window) to disable Bulk AD users from CSV file.

Note: Your CSV file (All_Users.csv)  should contains the column objectguid as a first column, otherwise you need to change the index value 0 to other value ---> csvUserFields(0)... which depends on your column index of objectguid in CSV file

VBScript to Disable Bulk AD users From CSV File using VBScript
' DisableBulkADUsersFromCSV.vbs
' Sample VBScript to Disable AD Users from CSV file .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit

Dim strUserGUID,objUser 

' Variables needed for CSV File Information
Dim varFileName,objFSO,objFile,csvUserFields
Const ForReading = 1

' Specify the csv file full path.
varFileName = "C:\Users\Administrator\Desktop\All_Users.csv"

' Open the file for reading.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(varFileName, ForReading)

' Read the first line - csv columns -not needed for our proceess
objFile.ReadLine

' Skip the error if the user doesn't exist.....
on error resume next

' Read the file and create new user.
Do Until objFile.AtEndOfStream
    ' Splits prioperty values.
    csvUserFields = Split(objFile.ReadLine,",")

' All_Users.csv file should contains the column objectguid as first column
' Otherwise you need change the index value 0 to other value here...csvUserFields(0)...
' which depends on your column index of objectguid in CSV file.

     strUserGUID =  csvUserFields(0)
 Set objUser = GetObject("LDAP://<GUID="& strUserGUID &">")
     objUser.AccountDisabled = True
     objUser.SetInfo
Loop

MsgBox("Bulk AD Users Disabled from CSV file using VBScript.")

WScript.Quit 

Sunday, 24 November 2013

Set Logon As A Service right to User by Powershell, C#, CMD and VBScript

Description:

In this article, I am going to explain about how to set or grant user Logon As A Service permission/privilege using Local Security Policy, VBScript, Powershell, C# and Command Line tool.

Summary:


Set Logon As A Service right to user using Local Security Policy

Follow the below steps to set Log on As Service right via Local Security Policy

1. Open the Run window by pressing 'Windows' + 'R'  keys.
2. Type the command secpol.msc in the text box and click OK.

Set Logon As A Service right to User by Command Prompt, C#, Powershell and VBScript
3. Now the Local Security Policy window will be open, in that window navigate to the node User Rights Assignment (Security Settings -> Local Polices ->User Rights Assignment). In right side pane, search and select the policy Log on as a service.


Set Logon As A Service rights to User by Command Line, C#, Powershell and VBScript

4. Double-click on the policy Log on as a service, in the opened windows click the button Add User or Group, select the user which you want to set logon as a service right and click OK, and click Apply button to finish.

Set Log on As A Service right to User by Powershell, Command Prompt, C# and VBScript


Set or Grant User Logon As A Service right via Powershell

 We can set the Logon As A Service right to user in Powershell by importing the third party DLL ( Carbon ).  Before you run the below script you need to the download latest Carbon files from here Download Carbon DLL.

Steps to follow to set Logon As A Service right via Powershell :

  1. Download latest Carbon files from here Download Carbon DLL.
  2. If you have downloaded the files, extract the zip file and you could see the Carbon DLL inside bin folder (In my case: C:\Users\Administrator\Downloads\Carbon\bin\Carbon.dll).
  3. Copy the below Powershell script commands and place it notepad or textfile.
  4. Now you can replace your Carbon DLL path in following script for the variable $CarbonDllPath
  5. You can also replace the user identity that you are going to set logon as service right in the variable $Identity
  6. Now run as Powershell window with Admin Privilege (Run as Administrator)
  7. Copy the edited Powershell script and Run it in Powershell to set logon as a service right.

$Identity = "DomainName\Administrator"
$privilege = "SeServiceLogonRight"

$CarbonDllPath = "C:\Users\Administrator\Downloads\Carbon\bin\Carbon.dll"

[Reflection.Assembly]::LoadFile($CarbonDllPath)

[Carbon.Lsa]::GrantPrivileges( $Identity , $privilege)


Powershell output :

Set Logon As A Service right to User by Powershell


Other web site links for Carbon DLL:
 https://bitbucket.org/splatteredbits/carbon/downloads
 http://pshdo.com/
 http://get-carbon.org/help/Grant-Privilege.html

Set or Grant User Logon As A Service right/permission to user using C#

You can use the function GrantUserLogOnAsAService to set Logon as a Service right to user using C# code. This function uses the class LsaWrapper.

static void GrantUserLogOnAsAService(string userName)
{
    try
    {
        LsaWrapper lsaUtility = new LsaWrapper();

        lsaUtility.SetRight(userName, "SeServiceLogonRight");

        Console.WriteLine("Logon as a Service right is granted successfully to " + userName);
    }            
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
LsaWrapper class file
public class LsaWrapper
{
// Import the LSA functions

[DllImport("advapi32.dll", PreserveSig = true)]
private static extern UInt32 LsaOpenPolicy(
    ref LSA_UNICODE_STRING SystemName,
    ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
    Int32 DesiredAccess,
    out IntPtr PolicyHandle
    );

[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
private static extern long LsaAddAccountRights(
    IntPtr PolicyHandle,
    IntPtr AccountSid,
    LSA_UNICODE_STRING[] UserRights,
    long CountOfRights);

[DllImport("advapi32")]
public static extern void FreeSid(IntPtr pSid);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, PreserveSig = true)]
private static extern bool LookupAccountName(
    string lpSystemName, string lpAccountName,
    IntPtr psid,
    ref int cbsid,
    StringBuilder domainName, ref int cbdomainLength, ref int use);

[DllImport("advapi32.dll")]
private static extern bool IsValidSid(IntPtr pSid);

[DllImport("advapi32.dll")]
private static extern long LsaClose(IntPtr ObjectHandle);

[DllImport("kernel32.dll")]
private static extern int GetLastError();

[DllImport("advapi32.dll")]
private static extern long LsaNtStatusToWinError(long status);

// define the structures

private enum LSA_AccessPolicy : long
{
    POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L,
    POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L,
    POLICY_GET_PRIVATE_INFORMATION = 0x00000004L,
    POLICY_TRUST_ADMIN = 0x00000008L,
    POLICY_CREATE_ACCOUNT = 0x00000010L,
    POLICY_CREATE_SECRET = 0x00000020L,
    POLICY_CREATE_PRIVILEGE = 0x00000040L,
    POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L,
    POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L,
    POLICY_AUDIT_LOG_ADMIN = 0x00000200L,
    POLICY_SERVER_ADMIN = 0x00000400L,
    POLICY_LOOKUP_NAMES = 0x00000800L,
    POLICY_NOTIFICATION = 0x00001000L
}

[StructLayout(LayoutKind.Sequential)]
private struct LSA_OBJECT_ATTRIBUTES
{
    public int Length;
    public IntPtr RootDirectory;
    public readonly LSA_UNICODE_STRING ObjectName;
    public UInt32 Attributes;
    public IntPtr SecurityDescriptor;
    public IntPtr SecurityQualityOfService;
}

[StructLayout(LayoutKind.Sequential)]
private struct LSA_UNICODE_STRING
{
    public UInt16 Length;
    public UInt16 MaximumLength;
    public IntPtr Buffer;
}
/// 
//Adds a privilege to an account

/// Name of an account - "domain\account" or only "account"
/// Name ofthe privilege
/// The windows error code returned by LsaAddAccountRights
public long SetRight(String accountName, String privilegeName)
{
    long winErrorCode = 0; //contains the last error

    //pointer an size for the SID
    IntPtr sid = IntPtr.Zero;
    int sidSize = 0;
    //StringBuilder and size for the domain name
    var domainName = new StringBuilder();
    int nameSize = 0;
    //account-type variable for lookup
    int accountType = 0;

    //get required buffer size
    LookupAccountName(String.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);

    //allocate buffers
    domainName = new StringBuilder(nameSize);
    sid = Marshal.AllocHGlobal(sidSize);

    //lookup the SID for the account
    bool result = LookupAccountName(String.Empty, accountName, sid, ref sidSize, domainName, ref nameSize,
                                    ref accountType);

    //say what you're doing
    Console.WriteLine("LookupAccountName result = " + result);
    Console.WriteLine("IsValidSid: " + IsValidSid(sid));
    Console.WriteLine("LookupAccountName domainName: " + domainName);

    if (!result)
    {
        winErrorCode = GetLastError();
        Console.WriteLine("LookupAccountName failed: " + winErrorCode);
    }
    else
    {
        //initialize an empty unicode-string
        var systemName = new LSA_UNICODE_STRING();
        //combine all policies
        var access = (int) (
                                LSA_AccessPolicy.POLICY_AUDIT_LOG_ADMIN |
                                LSA_AccessPolicy.POLICY_CREATE_ACCOUNT |
                                LSA_AccessPolicy.POLICY_CREATE_PRIVILEGE |
                                LSA_AccessPolicy.POLICY_CREATE_SECRET |
                                LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION |
                                LSA_AccessPolicy.POLICY_LOOKUP_NAMES |
                                LSA_AccessPolicy.POLICY_NOTIFICATION |
                                LSA_AccessPolicy.POLICY_SERVER_ADMIN |
                                LSA_AccessPolicy.POLICY_SET_AUDIT_REQUIREMENTS |
                                LSA_AccessPolicy.POLICY_SET_DEFAULT_QUOTA_LIMITS |
                                LSA_AccessPolicy.POLICY_TRUST_ADMIN |
                                LSA_AccessPolicy.POLICY_VIEW_AUDIT_INFORMATION |
                                LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION
                            );
        //initialize a pointer for the policy handle
        IntPtr policyHandle = IntPtr.Zero;

        //these attributes are not used, but LsaOpenPolicy wants them to exists
        var ObjectAttributes = new LSA_OBJECT_ATTRIBUTES();
        ObjectAttributes.Length = 0;
        ObjectAttributes.RootDirectory = IntPtr.Zero;
        ObjectAttributes.Attributes = 0;
        ObjectAttributes.SecurityDescriptor = IntPtr.Zero;
        ObjectAttributes.SecurityQualityOfService = IntPtr.Zero;

        //get a policy handle
        uint resultPolicy = LsaOpenPolicy(ref systemName, ref ObjectAttributes, access, out policyHandle);
        winErrorCode = LsaNtStatusToWinError(resultPolicy);

        if (winErrorCode != 0)
        {
            Console.WriteLine("OpenPolicy failed: " + winErrorCode);
        }
        else
        {
            //Now that we have the SID an the policy,
            //we can add rights to the account.

            //initialize an unicode-string for the privilege name
            var userRights = new LSA_UNICODE_STRING[1];
            userRights[0] = new LSA_UNICODE_STRING();
            userRights[0].Buffer = Marshal.StringToHGlobalUni(privilegeName);
            userRights[0].Length = (UInt16) (privilegeName.Length*UnicodeEncoding.CharSize);
            userRights[0].MaximumLength = (UInt16) ((privilegeName.Length + 1)*UnicodeEncoding.CharSize);

            //add the right to the account
            long res = LsaAddAccountRights(policyHandle, sid, userRights, 1);
            winErrorCode = LsaNtStatusToWinError(res);
            if (winErrorCode != 0)
            {
                Console.WriteLine("LsaAddAccountRights failed: " + winErrorCode);
            }

            LsaClose(policyHandle);
        }
        FreeSid(sid);
    }

    return winErrorCode;
}    
}





Set Logon As A Service right to user via Command Line

You can use the NTRights.exe utility to grant or deny user rights to users and groups from a command line or a batch file. The NTRights.exe utility is included in the Windows NT Server 4.0 Resource Kit Supplement 3. Refer: http://support.microsoft.com/kb/266280

Set Logon As A Service right
ntrights +r SeServiceLogonRight -u "Domain\Administrator"
Revoke Logon As A Service right
ntrights -r SeServiceLogonRight -u "Domain\Administrator"

Set or Grant Logon As Service right/privilege to user via VBScript

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for strUserName if you want to give your own name otherwise simply leave it.
3. Save the file with a .vbs extension, for example: SetLogonAsAServiceRight.vbs
4. Double-click the VBScript file (or Run this file from command window) to Set Logon As Service right/permission to user.

' SetLogonAsAServiceRight.vbs
' Sample VBScript to set or grant Logon As A Service Right.
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Dim strUserName,ConfigFileName,OrgStr,RepStr,inputFile,strInputFile,outputFile,obj 
strUserName = "work2008\DevUser"
Dim oShell 
Set oShell = CreateObject ("WScript.Shell")
oShell.Run "secedit /export /cfg config.inf", 0, true 
oShell.Run "secedit /import /cfg config.inf /db database.sdb", 0, true

ConfigFileName = "config.inf"
OrgStr = "SeServiceLogonRight ="
RepStr = "SeServiceLogonRight = " & strUserName & ","
Set inputFile = CreateObject("Scripting.FileSystemObject").OpenTextFile("config.inf", 1,1,-1)
strInputFile = inputFile.ReadAll
inputFile.Close
Set inputFile = Nothing

Set outputFile =   CreateObject("Scripting.FileSystemObject").OpenTextFile("config.inf",2,1,-1)
outputFile.Write (Replace(strInputFile,OrgStr,RepStr))
outputFile.Close
Set outputFile = Nothing

oShell.Run "secedit /configure /db database.sdb /cfg config.inf",0,true
set oShell= Nothing

Set obj = CreateObject("Scripting.FileSystemObject")
obj.DeleteFile("config.inf") 
obj.DeleteFile("database.sdb")

Msgbox "Logon As A Service Right granted to user '"& strUserName &"' using Vbscript code"

Thanks,
Morgan
Software Developer
---------------------

Saturday, 23 November 2013

Event ID 5136 - Active Directory Object Change Event

In this article, I am going to explain about the Active Directory change audit Event ID 5136, how to enable or configure Event ID 5136 through Default Domain Controller Policy GPO and Auditpol.exe, and how to disable Event ID 5136.

Summary:


Event ID 5136 Source: Old Value (Deleted Attribute Value)

Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          23/11/2013 1:30:42 PM
Event ID:      5136
Task Category: Directory Service Changes
Level:         Information
Keywords:      Audit Success
User:          N/A
Computer:      myDC.myDomain.com
Description:
A directory service object was modified.
 
Subject:
 Security ID:  myDomain\Administrator
 Account Name:  Administrator
 Account Domain:  myDomain
 Logon ID:  0x2c8f4

Directory Service:
 Name: myDomain.local
 Type: Active Directory Domain Services
 
Object:
 DN: CN=TestUser,OU=Test,DC=myDomain,DC=Com
 GUID: CN=TestUser,OU=Test,DC=myDomain,DC=Com
 Class: user
 
Attribute:
 LDAP Display Name: physicalDeliveryOfficeName
 Syntax (OID): 2.5.5.12
 Value: TechPark
 
Operation:
 Type: Value Deleted
 Correlation ID: {cd1aa2fa-7d62-43c5-8c95-3ba03569a4f2}
 Application Correlation ID: -

Event ID 5136 Source: New Value (Added Attribute Value)

Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          23/11/2013 1:30:42 PM
Event ID:      5136
Task Category: Directory Service Changes
Level:         Information
Keywords:      Audit Success
User:          N/A
Computer:      myDC.myDomain.Com
Description:
A directory service object was modified.
 
Subject:
 Security ID:  myDomain\Administrator
 Account Name:  Administrator
 Account Domain:  myDomain
 Logon ID:  0x2c8f4

Directory Service:
 Name: myDomain.com
 Type: Active Directory Domain Services
 
Object:
 DN: CN=TestUser,OU=Test,DC=myDomain,DC=Com
 GUID: CN=TestUser,OU=Test,DC=myDomain,DC=Com
 Class: user
 
Attribute:
 LDAP Display Name: physicalDeliveryOfficeName
 Syntax (OID): 2.5.5.12
 Value: TechZone
 
Operation:
 Type: Value Added
 Correlation ID: {cd1aa2fa-7d62-43c5-8c95-3ba03569a4f2}
 Application Correlation ID: -

Mapping 5136 Old Value Event and New Value Event

Any Active Directory object's attribute change will logs the two 5136 events for Deleted attribute value and Added attribute value. You can find the old value (deleted value) for the corresponding new value (added value) by mapping these two events.

You can find the field section Operation:  in both events
In Old Value Event:
 Type: Value Deleted
 Correlation ID: {cd1aa2fa-7d62-43c5-8c95-3ba03569a4f2}
 Application Correlation ID: -
In New Value Event:
Operation:
 Type: Value Added
 Correlation ID: {cd1aa2fa-7d62-43c5-8c95-3ba03569a4f2}
 Application Correlation ID: -

Here, you could see the field Type: which tells Value Added or Deleted and Correlation ID which is unique between two events. So you can map these two events by using the value of Correlation ID.

After mapping the events, you can find changed attribute name from the field LDAP Display Name:. From the above event source, we can conclude the value of physicalDeliveryOfficeName (Office) attribute is changed from 'TechPark' to 'TechZone' for the user 'TestUser'

Enable Active Directory Change Event 5136 via Group Policy

    To enable event id 5136  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 each and every Domain Controller..

Follow the below steps to enable Active Directory change audit event 5136 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. Expand the domain node and Domain Controllers OU,  right-click on the Default Domain Controllers Policy, then click Edit. - refer the below image.

Enable Active Directory Change Audit Event ID 5136


    4. Expand Computer Configuration node and Security Settings and navigate to the node DS Access (Computer Configuration->Policies->Windows Settings->Security Settings-> Advanced Audit Policy Configuration -> Audit Policies->DS Access).

    5. Now edit Audit Directory Service Changes as Success to enable active directory change audit event 5136. - refer the below image.

Enable Active Directory Change Audit Event ID 5136


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

Enable Object Level Security Audit (SACL): 

    This event is also controlled by the access control entry (ACE) in the SACL requiring attribute modifications to be logged, even if the Directory Service Changes subcategory is enabled, no change auditing events are logged. For example, if there is no ACE in a SACL requiring Write Property access on the physicalDeliveryOfficeName attribute of a user object to be audited, no auditing events are generated when the physicalDeliveryOfficeName attribute is modified, even if the subcategory Directory Service Changes is enabled..

Follow the below steps to enable SACL for full Domain.

Note: You can also configure SACL for particular OU or User instead of full Domain.

   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. -refer below image.

Enable Active Directory Change Audit Event ID 5136


    8. Click the button OK, and click Apply.


Enable Event ID 5136 via Auditpol

Auditpol.exe is the command line utility tool to change Audit Security settings as category and sub-category level. It is available by default Windows 2008 R2 and later versions/Windows 7 and later versions.

By using Auditpol, we can get/set Audit Security settings per user level and computer level.

Note: You should run Auditpol command with elevated privilege (Run As Administrator);

You can enable Event ID 5136 through Directory Service Changes subcategory by using the following command
auditpol /set /subcategory:"Directory Service Changes" /success:enable
To update or refresh GPO settings, run the command gpupdate/force

How to disable/stop Event ID 5136

You can disable or stop the audit Event ID 5136 by removing success audit of Directory Service Changes subcategory by using the following command.
auditpol /set /subcategory:"Directory Service Changes" /success:disable
You can also stop this event by removing the success setting from the Default Domain Controller Policy in the setting path (Computer Configuration->Policies->Windows Settings->Security Settings-> Advanced Audit Policy Configuration -> Audit Policies->DS Access->Audit Directory Service Changes)


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

Thanks,
Morgan
Software Developer

Friday, 22 November 2013

Enable and Disable Active Directory User in C#

Description:

In this article, I am going to give C# code examples to Enable Active Directory user and Disable Active Directory user account in C# with two methods.

Summary:


Enable Active Directory User Account via userAccountControl using C#

To use DirectoryEntry class, you need to add reference System.DirectoryServices.ActiveDirectory
private static void EnableADUserUsingUserAccountControl(string username)
     {
        try
        {
            DirectoryEntry domainEntry = Domain.GetCurrentDomain().GetDirectoryEntry();
            // ldap filter
            string searchFilter = string.Format(@"(&(objectCategory=person)(objectClass=user)
                    (!sAMAccountType=805306370)(|(userPrincipalName={0})(sAMAccountName={0})))", username);

            DirectorySearcher searcher = new DirectorySearcher(domainEntry, searchFilter);
            SearchResult searchResult = searcher.FindOne();
            if (searcher != null)
            {
                DirectoryEntry userEntry = searchResult.GetDirectoryEntry();

                int old_UAC=(int)userEntry.Properties["userAccountControl"][0];

                // AD user account disable flag
                int ADS_UF_ACCOUNTDISABLE = 2;

                // To enable an ad user account, we need to clear the disable bit/flag:
                userEntry.Properties["userAccountControl"][0] = (old_UAC & ~ADS_UF_ACCOUNTDISABLE);
                userEntry.CommitChanges();

                Console.WriteLine("Active Director User Account Enabled successfully 
                                          through userAccountControl property");
            }
            else
            {
                //AD User Not Found
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }


Disable Active Directory User Account via userAccountControl using C#

private static void DisableADUserUsingUserAccountControl(string username)
    {
        try
        {
            DirectoryEntry domainEntry = Domain.GetCurrentDomain().GetDirectoryEntry();
            // ldap filter
            string searchFilter = string.Format(@"(&(objectCategory=person)(objectClass=user)
                  (!sAMAccountType=805306370)(|(userPrincipalName={0})(sAMAccountName={0})))", username);

            DirectorySearcher searcher = new DirectorySearcher(domainEntry, searchFilter);
            SearchResult searchResult = searcher.FindOne();
            if (searcher != null)
            {
                DirectoryEntry userEntry = searchResult.GetDirectoryEntry();

                int old_UAC = (int)userEntry.Properties["userAccountControl"][0];

                // AD user account disable flag
                int ADS_UF_ACCOUNTDISABLE = 2;

                // To disable an ad user account, we need to set the disable bit/flag:
                userEntry.Properties["userAccountControl"][0] = (old_UAC | ADS_UF_ACCOUNTDISABLE);
                userEntry.CommitChanges();

                Console.WriteLine("Active Director User Account Disabled successfully 
                                    through userAccountControl property");
            }
            else
            {
                //AD User Not Found
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }


Enable AD User Account via UserPrincipal using C#

To use PrincipalContext class, you need add reference System.DirectoryServices.AccountManagement which is available only from .NET 3.5;
private static void EnableADUserUsingUserPrincipal(string username)
    {
        try
        {                
            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);

            UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                    (principalContext, username);

            userPrincipal.Enabled = true;

            userPrincipal.Save();

            Console.WriteLine("Active Director User Account Enabled successfully through UserPrincipal");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }


Disable AD User Account via UserPrincipal using C#

 private static void DiableADUserUsingUserPrincipal(string username)
    {
        try
        {
            // To use this class, you need add reference System.DirectoryServices.AccountManagement which 
is available only from .NET 3.5;
            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);

            UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                    (principalContext, username);

            userPrincipal.Enabled = false;

            userPrincipal.Save();

            Console.WriteLine("Active Director User Account Disabled successfully through UserPrincipal");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
Note : This article is applies to Windows Server 2003, Windows Server 2008,Windows Server 2008 R2 and Windows Server 2012.

Thanks,
Morgan
Software Developer

Wednesday, 20 November 2013

Get current Date time in JQuery

Description:

  In this article, I am going to write JQuery code examples to get current DateTime, UTC DateTime, current Date, current Date with specific date time format.

Summary:

  1. Get current local Date Time in JQuery
  2. Get current UTC (Universal) Date Time in JQuery
  3. Get current Date in JQuery (without time part)

Get current local Date Time in JQuery

Note: We need add 1 with return value dNow.getMonth(), because the getMonth() method returns the month (from 0 to 11), January is 0, February is 1, and so on.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
function ShowLocalDate()
{
var dNow = new Date();
var localdate= (dNow.getMonth()+1) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();
$('#currentDate').text(localdate)
}

</script>
</head>
<body>

<h1>Get current local Date in JQuery</h1>
<label id="currentDate">This is current local Date Time in JQuery</p>
<button type="button" onclick="ShowLocalDate()">Show Local DateTime</button>

</body>
</html> 


Get current UTC (Universal) Date Time in JQuery

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>

<script>

function ShowUTCDate()
{
var dNow = new Date();
var utc = new Date(dNow.getTime() + dNow.getTimezoneOffset() * 60000)
var utcdate= (utc.getMonth()+1) + '/' + utc.getDate() + '/' + utc.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes();
$('#currentDate').text(utcdate)
}

</script>
</head>
<body>

<h1>Get UTC DateTime in JQuery</h1>
<label id="currentDate">This is UTC DateTime in JQuery</p>
<button type="button" onclick="ShowUTCDate()">Show UTC DateTime</button>

</body>
</html>


Get current Date in JQuery (without time part)

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>

function ShowDate()
{
var dNow = new Date();
var utcdate= (dNow.getMonth()+ 1) + '/' + dNow.getDate() + '/' + dNow.getFullYear();
$('#currentDate').text(utcdate)
}

</script>
</head>
<body>

<h1>Get current Date in JQuery</h1>
<label id="currentDate">This is current Date in JQuery</p>
<button type="button" onclick="ShowDate()">Show current Date</button>

</body>
</html>