Tuesday, 29 April 2014

String or binary data would be truncated the statement has been terminated

Description:

This SQL error occurs when database field's datatype,size does not match with the inserting or updating value. Suppose we have declared a SQL column field named username varchar[10] and when we trying to inserting username of more than 20 characters then we will get an error like "String or binary data would be truncated the statement has been terminated". So in that case, we have to increase datatype length 20 or decrease length of username value before insertion to avoid the error "String or binary data would be truncated".

Example:
DECLARE @UserData TABLE(UserId INT, UserName VARCHAR(10))
INSERT INTO @UserData VALUES(1,'James Anderson')
SELECT * FROM @UserData
From above query, it clearly indicates we have declared datatype VARCHAR(10) for UserName. Now we can insert usernames only with 10 characters or less. but here, we are trying to insert the user 'James Anderson' it has more than 10 characters. so we should get the following error when execute above statement.
Msg 8152, Level 16, State 14, Line 3
String or binary data would be truncated.
The statement has been terminated.

(0 row(s) affected)

Fix error String or binary data would be truncated:

To fix this sql error we need to increase the UserName column's datatype size from VARCHAR(10) to VARCHAR(20)
DECLARE @UserData TABLE(UserId INT, UserName VARCHAR(20))
INSERT INTO @UserData VALUES(1,'James Anderson')
SELECT * FROM @UserData

Fix SQL error: String or binary data would be truncated the statement has been terminated

Monday, 28 April 2014

Run a Program as Different User

Description:

   Running a Program as Different User is one of the easiest way to Impersonate a Program/Application with some other user's privilege. For every administrators, this would be the common need either for testing or to impersonate different user privilege. In this article, I am going to write and explain about how to Run a Program as Different User and how to Run a Program as System account.

Summary:


Run a Program as Different User

You can execute a program under a different user account by using the command line tool RunAs. Use the below command to open new CMD window under different user
C:\> RunAs /user:rtest cmd
Run program under Different User

You will prompted to enter password when you execute this command. type password and click 'Enter' to open new cmd window under the different user 'rtest'.

Run Program as Different User

Run a Program as System Account

You can execute or run a program under local system account by using sysinternals's Psexec utility. you can download at http://technet.microsoft.com/en-us/sysinternals/bb897553. You can use the -s switch to run a program as the system account. The following example shows how to start a cmd.exe session under the system account:
C:\PSTools> PsExec -s cmd.exe

PsExec v2.1 - Execute processes remotely
Copyright (C) 2001-2013 Mark Russinovich
Sysinternals - www.sysinternals.com

Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Windows\system32>whoami
nt authority\system

C:\Windows\system32>exit
cmd.exe exited on HP-PC with error code 0.
Run as Local System Account

Once you have completed the work you can revert to current user by executing exit command.

Run a Program as Different Domain User for Remote Connections

You can execute a program under different domain user for remote connections by using the parameter /netonly in RunAs command. Use the below command to open new CMD window under different domain user
RunAs /netonly  /user:work2008\RDtest cmd
Run as Different Domain User for Remote Connections

When you start a program with RunAs /netonly, the program will execute on your local computer as the user you are currently logged on as, but any connections to other computers on the network will be made using the user account specified.



Thanks,
Morgan
Software Developer

Sunday, 27 April 2014

Insert DataTable into SQL Table in C#

Description:

A .NET DataTable is an memory representation of an MS SQL Server table. DataTable object allows 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. In this article, I am going write C# code examples to Insert DataTable into SQL Table using SQLBulkCopy and using SQL Table-Valued Parameters.

Summary:


Insert DataTable into SQL Table using SQLBulkCopy in C#

This is an easy and recommended method to Insert DataTable content into SQL Table in C#. Once the DataTable is ready, it is just a simple statement to insert all the rows 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 records into sql table.

Insert DataTable into SalesHistory SQL Table:
public static void InsertDataTableintoSQLTableusingSQLBulkCopy()
{
    DataTable salesData = GetSalesData();

    using (SqlConnection sqlconnection = new SqlConnection(@"Data Source=.\SQLExpress; 
Initial Catalog=MorganDB; Integrated Security=SSPI;"))
    {
        sqlconnection.Open();

      // create table if not exists 
        string createTableQuery = @"Create Table [SalesHistory] 
                        ( SaleDate datetime, ItemName nvarchar(1000),ItemsCount int)";
        SqlCommand command = new SqlCommand(createTableQuery, sqlconnection);
        command.ExecuteNonQuery();

     // Copy the DataTable to SQL Server Table using SqlBulkCopy
        using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlconnection))
        {
            sqlBulkCopy.DestinationTableName = salesData.TableName;

            foreach (var column in salesData.Columns)
                sqlBulkCopy.ColumnMappings.Add(column.ToString(), column.ToString());

            sqlBulkCopy.WriteToServer(salesData);
        }
    }
}
Get Sales History DataTable Content:
private static DataTable GetSalesData()
{
    DataTable salesHistory = new DataTable("SalesHistory");

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

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

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

    // Add the columns to the SalesHistory DataTable
    salesHistory.Columns.AddRange(new DataColumn[] { dateColumn, productNameColumn,
 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 = salesHistory.NewRow();
    dailyProductSalesRow["SaleDate"] = DateTime.Now.Date;
    dailyProductSalesRow["ItemName"] = "Nike Shoe-32";
    dailyProductSalesRow["ItemsCount"] = 10;

    // Add the row to the SalesHistory DataTable
    salesHistory.Rows.Add(dailyProductSalesRow);

    return salesHistory;
}

Insert DataTable into SQL Table using SQL Table-Valued Parameters in .NET C#

This is an another method to Insert DataTable rows into SQL Table in C#. SQL Table-valued parameters provide an easy way to marshal multiple rows of data from a client application to SQL Server without requiring multiple round trips or special server-side logic for processing the data. You can use Table-Valued parameters to encapsulate rows of data in a client application and send the data to the server in a single parameterized command.

Insert DataTable into SalesHistory SQL Table by Table-Valued Parameter:
public static void InsertDataTableintoSQLTable()
{
    DataTable salesData = GetSalesData();

    using (SqlConnection sqlconnection = new SqlConnection(@"Data Source=.\SQLExpress; 
Initial Catalog=MorganDB; Integrated Security=SSPI;"))
    {
        sqlconnection.Open();

      // create table if not exists 
        string createTableQuery = @"Create Table [SalesHistory] 
                ( SaleDate datetime, ItemName nvarchar(1000),ItemsCount int)";
        SqlCommand createCommand = new SqlCommand(createTableQuery, sqlconnection);
        createCommand.ExecuteNonQuery();

        // create type if not exists 
        string createTypeQuery = @"CREATE TYPE dbo.SalesHistoryTableType AS TABLE
            (SaleDate datetime, ItemName nvarchar(1000),ItemsCount int)";
        createCommand = new SqlCommand(createTypeQuery, sqlconnection);
        createCommand.ExecuteNonQuery();

    // Copy the DataTable to SQL Server Table using Table-Valued Parameter
        string sqlInsert = "INSERT INTO [SalesHistory] SELECT * FROM @SalesHistoryData";
        SqlCommand insertCommand = new SqlCommand(sqlInsert, sqlconnection);
        SqlParameter tvp= insertCommand.Parameters.AddWithValue("@SalesHistoryData",salesData);
        tvp.SqlDbType = SqlDbType.Structured;
        tvp.TypeName = "dbo.SalesHistoryTableType";
        insertCommand.ExecuteNonQuery();
    }
}
Get DataTable Content to Insert into SQL Table:
private static DataTable GetSalesData()
{
    DataTable salesHistory = new DataTable("SalesHistory");

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

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

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

    // Add the columns to the SalesHistory DataTable
    salesHistory.Columns.AddRange(new DataColumn[] { dateColumn, productNameColumn,
             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 = salesHistory.NewRow();
    dailyProductSalesRow["SaleDate"] = DateTime.Now.Date;
    dailyProductSalesRow["ItemName"] = "Nike Shoe-32";
    dailyProductSalesRow["ItemsCount"] = 10;

    // Add the row to the SalesHistory DataTable
    salesHistory.Rows.Add(dailyProductSalesRow);

    return salesHistory;
}

Saturday, 26 April 2014

Insert XML into SQL Server Table using SSMS and C#

Description:

  In SQL Server Relational Database Management System (RDMS), we always try to create best Database Table design. So we can easily avoid XML column by creating equivalent Table design. Querying XMl column by using XQuery will give performance overhead compared with normal T-SQL query. But in complex database design who have most dynamic need, we cannot avoid XML column. In this article, I am going write different examples to Insert XML Data into SQL Server Table using SSMS and .NET C# code.

Summmary:


Insert XML into SQL Table using SQL Server Management Studio

You can easily Insert XML data into SQL Table by using following SQL Insert query.
Use [MorganDB]

Create Table [MyTable] ( ID int, [myXmlColumn] xml);

Insert Into [MyTable] (ID,[myXmlColumn]) 
   Values(1,'<XmlRoot><childNode></childNode></XmlRoot>')

Select * From [MyTable]

Insert XML value into SQL Table using SSMS and .NET C#


Insert XML into SQL Table using SQL Parameter in .NET C#

If you have small size XML value, you can easily Insert XML data into SQL Table by using above SQL Query. But when it becomes large size XML file or XML data, it is very difficult and performance overhead to insert multiple XML records into SQL Table. In that case, we need go for alternative way. So we can use SQL Parameter approach to Insert Multiple XMl records into SQL table.
public static void InsertXMlDataIntoTableBySQLParameter()
{
    using (SqlConnection sqlconnection = new SqlConnection(@"Data Source=.\SQLExpress; 
Initial Catalog=MorganDB; Integrated Security=SSPI;"))
    {
        sqlconnection.Open();

        // create table if not exists 
        string createTableQuery = @"Create Table [MyTable] ( ID int, [myXmlColumn] xml)";
        SqlCommand command = new SqlCommand(createTableQuery, sqlconnection);
        command.ExecuteNonQuery();

        string xmlData = "<XmlRoot><childNode></childNode></XmlRoot>";

        string insertXmlQuery = @"Insert Into [MyTable] (ID,[myXmlColumn]) Values(1,@myXmlColumn)";

      // Insert XMl Value into Sql Table by SqlParameter
        SqlCommand insertCommand = new SqlCommand(insertXmlQuery, sqlconnection);
        SqlParameter sqlParam = insertCommand.Parameters.AddWithValue("@myXmlColumn", xmlData);
        sqlParam.DbType = DbType.Xml;
        insertCommand.ExecuteNonQuery();
    }
}

Insert XML Value into SQL Table using SQL Query in .NET C#

Use the below example to Insert XML value into SQL Server Table using SQL Query itself without SQL Parameter. This method is recommended only for small size XML data and small number of rows insertions at the same time.
public static void InsertXMlDataIntoTable()
{
    using (SqlConnection sqlconnection = new SqlConnection(@"Data Source=.\SQLExpress; 
        Initial Catalog=MorganDB; Integrated Security=SSPI;"))
    {
        sqlconnection.Open();

        // create table if not exists 
        //string createTableQuery = @"Create Table [MyTable] ( ID int, [myXmlColumn] xml)";
        //SqlCommand command = new SqlCommand(createTableQuery, sqlconnection);
        //command.ExecuteNonQuery();

        string insertXmlQuery = @"Insert Into [MyTable] (ID,[myXmlColumn])
                    Values(1,'<XmlRoot><childNode></childNode></XmlRoot>')";

        SqlCommand command2 = new SqlCommand(insertXmlQuery, sqlconnection);
        command2.ExecuteNonQuery();
    }
}

Thanks,
Morgan
Software Developer

Friday, 25 April 2014

Call ASP.NET WebService using JQuery and JavaScript

Description:

The AJAX functionality of ASP.NET enables you to call ASP.NET webservice's methods from JavaScript. This enhances the user experience for the Web application. The page can call server-based methods without a postback and without refreshing the whole page, because only data is transferred between the browser and the Web server. In this article, I am going to write different type of examples to call webservice from JavaScript client side code in ASP.NET.

To enable webservice calls from script, an .asmx webservice class should qualified with the ScriptService ([System.Web.Script.Services.ScriptService]) attribute and individual methods or functions should be qualified with [WebMethod] attribute.
 [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }

Summary:

Call WebService from JavaScript using ScriptManager without JQuery

   You can call WebService method from JavaScript using ScriptManager's ServiceReference. To use this you need to add ScriptManger tag in your page and include the ServiceReference. Here, I have written an example to get web server time via WebService method with ScriptManager's Ajax call in ASP.NET C#.

Default.aspx:
<head id="Head1" runat="server">
    <title>Call WebService method from JavaScript without JQuery</title>
    <script type="text/javascript">
        function CallWebService() {
            MorganWebApp.WebService1.GetServerTime(OnSuccess, OnFailure);
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = dateTime;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scriptmanager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WebService1.asmx" />
        </Services>
    </asp:ScriptManager>
    <div>
        <input type="button" value="Show Server Time" onclick="CallWebService()" />
        <label id="currentDate">
            Current Date Time in Web Server from WebService method</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
namespace MorganWebApp
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string GetServerTime()
        {
            return DateTime.Now.ToString();
        }
    }
}

Call WebService from JavaScript with Parameters using ScriptManager

Calling webservice method with multiple parameters from JavaScript is an another frequently required need . Here, I have written the example to pass two int type parameters to add value in WebService method without using JQuery.

Default.aspx:
<head id="Head1" runat="server">
    <title>Call WebService method from JavaScript without JQuery</title>
    <script type="text/javascript">
        function CallWebService() {
            var val1 = document.getElementById("val1").value;
            var val2 = document.getElementById("val2").value;
            MorganWebApp.WebService1.AddValues(val1,val2,OnSuccess, OnFailure);
        }
        function OnSuccess(result) {
            if (result) {
                document.getElementById("result").innerHTML = result;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scriptmanager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WebService1.asmx" />
        </Services>
    </asp:ScriptManager>
    <div>
    A:<input id="val1" type="text"/> B:<input id="val2" type="text"/>
        <input type="button" value="Add" onclick="CallWebService()" />
        <label id="result">
            Shows result calcuated from from WebService method</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
namespace MorganWebApp
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public int AddValues(int a,int b)
        {
            return a + b;
        }
    }
}

Call WebService method from JavaScript with multiple parameters



Call WebService from JavaScript using JQuery ajax in ASP.NET C#

   You can call webservice method from JavaScript client side using JQuery ajax method in C# ASP.NET.
Note: You need to add reference for JQuery script file to use JQuery ajax.

Default.aspx:
<head id="Head1" runat="server">
    <title>Call WebService from JavaScript using JQuery ajax</title>
    <script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        function CallWebService() {
            $.ajax({
                type: "post",
                url: "WebService1.asmx/GetServerTime",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = dateTime;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Show Server Time" onclick="CallWebService()" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
namespace MorganWebApp
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string GetServerTime()
        {
            return DateTime.Now.ToString();
        }
    }
}


Call WebService from JavaScript using JQuery ajax with Parameters

   You can call webservice from JavaScript in ASP.NET using JQuery ajax method with single or multiple parameters. Here, I have written JQuery ajax example to get add values in webservice by passing two int parameters.

Default.aspx:
<head id="Head1" runat="server">
    <title>Call WebService from JavaScript using JQuery ajax with Parameters</title>
    <script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        function CallWebService() {
            var val1 = document.getElementById("val1").value;
            var val2 = document.getElementById("val2").value;
            $.ajax({
                type: "post",
                data:"{'a':'" + val1 + "','b':'" + val2 + "'}",
                url: "WebService1.asmx/AddValues",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(result) {
            if (result) {
                document.getElementById("result").innerHTML = result;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       A:<input id="val1" type="text"/> B:<input id="val2" type="text"/>
        <input type="button" value="Add" onclick="CallWebService()" />
        <label id="result">
            Shows the result calculated from WebService method</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
namespace MorganWebApp
{

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {        
        [WebMethod]
        public int AddValues(int a,int b)
        {
            return a + b;
        }
    }
}

Related Articles:

Tuesday, 22 April 2014

Open Div as Popup using JavaScript

Showing Popup is the inevitable one in any kind of HTML based UI. If we want to show a html/aspx page as Popup, we can achieve this by using either Window.Showmodaldialog or Window.open. But most of the time our need is just to ask some inputs like username or mail id something like that. In HTML and JavaScript based applications, a DIV element is a very powerful HTML control that can be used to achieve to any complex UI design. In this article, I am going write and explain the example to Open Div as Popup using JavaScript and CSS without JQuery.

Open Div as Popup - HTML:
 
     This is the example to ask Login credential through Div Popup. Here, we have the button control to call JavaScript function 'OpenLoginPopup' to open loginDiv as Popup, the Div control which we are going to Show as Popup and the Close button it will call the JavaScript function 'ClosePopupDiv' to close the opened Popup.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Open Div as Popup using JavaScript</title>
    <!-- Use below CSS here -->
    <!-- Use below JavaScript here -->
</head>
<body>
    <input type="button" value="Open Popup" onclick="OpenLoginPopup()" />
    <!-- Login Div to show Popup-->
    <div id="loginDiv" style="display: none">
        <label>
            User name:</label><input id="tbUser" type="text" /><br />
        <label>
            Password:</label><input id="Text1" type="password" /><br />
        <input type="button" value="Close" style="background-color: #3D72C0" onclick="ClosePopupDiv('loginDiv')" /><br />
    </div>
</body>
</html>
Open Div as Popup - JavaScript:
 
     Here, we have three JavaScript functions, OpenLoginPopup it will set popupsettings for loginDiv, ShowPopup is a general function to Show any given div as Popup, and ClosePopupDiv to close the opened Div Popup.
<script type="text/javascript">
        function OpenLoginPopup() {
            var divToOpen = "loginDiv";
            var popupSetting = { width: '250', height: '130', title: 'Login Dialog',isFixed:true };
            ShowPopup(divToOpen, popupSetting);
        }
        // Function to Show Div Popup
        function ShowPopup(divId, popupSetting) {
            var divElt = document.getElementById(divId);
            divElt.style.display = 'block';
            var element = divElt.parentElement;
            popupSetting = popupSetting || {};
            if (!popupSetting.width) { popupSetting.width = divElt.offsetWidth };
            if (!popupSetting.height) { popupSetting.height = divElt.offsetHeight };
            if (!popupSetting.title) { popupSetting.title = 'Dialog' };
            var table = document.createElement('table');
            table.setAttribute('id', 'table' + divId);table.setAttribute('cellspacing', '0');table.setAttribute('cellpadding', '0');
            var tr1 = document.createElement('tr'); tr1.className = 'PopupHeader';
            var td1 = document.createElement('td'); td1.setAttribute('style', 'width: 90%; padding: 5px;');
            var span = document.createElement('span'); span.innerHTML = popupSetting.title;
            span.setAttribute('style', 'font-size: 14px; font-weight: bold;');
            td1.appendChild(span); tr1.appendChild(td1); table.appendChild(tr1);
            var tr2 = document.createElement('tr');
            var tdDynamic = document.createElement('td');
            tdDynamic.setAttribute('align', 'center');
            tdDynamic.setAttribute('style', 'padding-top: 10px; vertical-align:top;');
            var tempElt = document.createElement('div');
            tempElt.setAttribute('id', 'tempElt' + divElt.id);
            divElt.parentElement.insertBefore(tempElt, divElt);
            tdDynamic.appendChild(divElt);
            tr2.appendChild(tdDynamic);
            table.appendChild(tr2);
            var cssText = 'display: block; border:1px solid black;  z-index:92000; background-color:white; top:50%; left:50%;';
            cssText += 'width: ' + popupSetting.width + 'px; height: ' + popupSetting.height + 'px; margin-left: -' + Math.round(popupSetting.width / 2) + 'px; margin-top: -' + Math.round(popupSetting.height / 2) + 'px;';
            if (popupSetting.isFixed === true) { cssText += 'position: fixed;';}
            else { cssText += 'position: absolute;'; }
            table.setAttribute('style', cssText);
            element.appendChild(table);
            var shadeElt = document.createElement('div');
            shadeElt.id = "ShadedBG";shadeElt.className = "ShadedBG";
            tempElt.appendChild(shadeElt);
        }

        // Function to Close Div Popup
        function ClosePopupDiv(divId) {
            var table = document.getElementById('table' + divId);
            var element = table.parentElement;
            var divElt = document.getElementById(divId);
            divElt.style.display = 'none';
            var tempElt = document.getElementById('tempElt' + divId);
            tempElt.parentElement.insertBefore(divElt, tempElt);
            table.parentElement.removeChild(table);
            table.setAttribute('style', 'display: none');
            tempElt.parentElement.removeChild(tempElt);
        }

    </script>
Show Div as Popup - CSS:
<style type="text/css">
        .PopupHeader
        {
            color: white;
            background-color: #3D72C0;
        }
        .ShadedBG
        {
            width: 100%;
            height: 100%;
            position: fixed;
            z-index: 10000;
            opacity: 0.3;
            filter: alpha(opacity=80);
            -moz-opacity: 0.8;
            background-color: #B8C6B8;
            top: 0;
            left: 0;
            margin: 0;
            padding: 0;
        }
    </style>
Output: Open Div as Popup using JavaScript

Show Div as Popup using JavaScript without JQuery


Source File: Download HTML Source

Thanks,
Morgan
Software Developer

Sunday, 20 April 2014

Create Bulk AD Users from CSV using Powershell Script

Creating Bulk AD Users in Active Directory is one of the important task for every Administrator either for testing or for set of actual new employees. Normally you can create new AD user using ADUC console. But it is time consuming job if you want create multiple ad users at the same time. To overcome this every administrator should rely on any of the script technology like VBScript and Powershell. In this article. I am going write and explain Powershell Script to Create Bulk AD Users from CSV.

Before proceed, please ensure that the Active Directory module for Windows Powershell is installed or not in your machine. It will be installed by default in Domain Controller. In client machines, you need to install it through Remote Server Administration Tools.
Use below command to check Active Directory module is installed or not:
Get-Module -Listavailable
Create Multiple AD Users from CSV using Powershell Script
If you are newbie to Powershell, don’t forget to set your Execution Policy to unrestricted or you might get an error when you try run the script. Use the below command to set your Execution Policy:
Set-ExecutionPolicy Unrestricted
Powershell Script to Create Bulk Active Directory Users from CSV

Powershell Script to Create Bulk AD Users from CSV file

   1. Consider the CSV file NewUsers.csv which contains set of New AD Users to create with the attributes Name, samAccountName and ParentOU.

Create Bulk AD Users from CSV file using Powershell Script
Note: The value of ParentOU should be enclosed with double quote ("). like "OU=TestOU,DC=TestDomain,DC=Local" since it has the special character comma (,). because in csv file the comma (,) is the key character to split column headers. (Ex file: Download NewUsers.csv).

   2. Copy the below Powershell script and paste in Notepad file.
   3. Change the NewUsers.csv file path with your own csv file path.
   4. Change the domain name TestDomain.local into your own domain name
   5. SaveAs the Notepad file with the extension .ps1 like Create-BulkADUsers-CSV.ps1

Click to download Powershell script as file Download Create-BulkADUsers-CSV.ps1
Import-Module ActiveDirectory
Import-Csv "C:\Scripts\NewUsers.csv" | ForEach-Object {
 $userPrincinpal = $_."samAccountName" + "@TestDomain.Local"
New-ADUser -Name $_.Name `
 -Path $_."ParentOU" `
 -SamAccountName  $_."samAccountName" `
 -UserPrincipalName  $userPrincinpal `
 -AccountPassword (ConvertTo-SecureString "MyPassword123" -AsPlainText -Force) `
 -ChangePasswordAtLogon $true  `
 -Enabled $true
Add-ADGroupMember "Domain Admins" $_."samAccountName";
}
   6. Now run the Create-BulkADUsers-CSV.ps1 file in Powershell to create Bulk Active Directory users from CSV file.
PS C:\Scripts> .\Create-BulkADUsers-CSV.ps1
Create Bulk Active Directory Users from CSV Powershell Script

Note: I have placed script file in the location C:\Scripts, if you placed in any other location, you can navigate to that path using CD path command (like cd "C:\Downloads").

   7. Now you can check the newly Created AD Users though ADUC console.

Powershell Script to Create Bulk AD Users from CSV file

Add more AD Attributes to New User:

Here, we have Created Bulk AD Users from CSV with only three attributes Name, samAccountName and ParentOU by CSV input. If you want to give more attributes from CSV input, you can add that attributes into csv file and change the above Powershell script accordingly.

Example: if you want to add EmailAddress to new user, your csv file should be like below file.

Create Bulk AD Users from CSV Powershell Script

Change the Powershell script like this:
Import-Module ActiveDirectory
Import-Csv "C:\Scripts\NewUsers.csv" | ForEach-Object {
 $userPrincinpal = $_."samAccountName" + "@TestDomain.Local"
New-ADUser -Name $_.Name `
 -Path $_."ParentOU" `
 -SamAccountName  $_."samAccountName" `
 -UserPrincipalName  $userPrincinpal `
 -AccountPassword (ConvertTo-SecureString "MyPassword123" -AsPlainText -Force) `
 -ChangePasswordAtLogon $true  `
 -Enabled $true `
 -EmailAddress $_."EmailAddress"
Add-ADGroupMember "Domain Admins" $_."samAccountName";
}


Refer this technet article http://technet.microsoft.com/en-us/library/ee617253.aspx to Create Bulk AD Users with more AD attributes.

Next: Export AD users to CVS using Powershell

Export AD Group Members to CSV using VBScript

Description:

In this article, I am going to write vbscript code to find and get list of group members in Active Directory domain and export AD Group members into CSV file.

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

VBScript to Export AD Group Members into 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: ExportADGroupMembers.vbs
3. Run usage in CMD:
C:\> CScript <vbscript filepath> <groupName> <csvFilePath>
Example: CScript ExportADGroupMembers.vbs "Domain Admins" "C:\ADGroupMembers.csv"

4. Run the above command to export Active Directory group members into CSV file. It will export the members of Domain Admins group into the csv file C:\ADGroupMembers.csv. if you want to export any other group members into any other csv file path, you can just replace the group name and csv file path accordingly.

Click to get vbscript code as a file Download ExportADGroupMembers.vbs

' ExportADGroupMembers.vbs
' Sample VBScript to Export Active Directory Group Members into CSV file.
' CMD Usage: CScript <vbscript filepath> <groupName> <csvFilePath>
' Ex: CScript ExportADGroupMembers.vbs "Domain Admins" "C:\ADGroupMembers.csv"
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Dim groupName,strMember,csvFilePath
Dim objGroup,objMember
Dim objFSO, objCSVFile
if Wscript.arguments.count < 2 then
    Wscript.echo "Invalid input parameters"
    Wscript.echo "   "
    Wscript.echo "Script Usage:"
    Wscript.echo "-----------------------------"
    Wscript.echo "CScript <vbscript file path> <groupName> <csvFilePath>"
    Wscript.echo "   "
    Wscript.echo "Ex: CScript C:\Scripts\ExportADGroupMembers.vbs ""Domain Admins"" "&_
                      " ""C:\ADGroupMembers.csv"" "
    WScript.quit
else 
  ' Get the group name and csv file path from command line parameters
    groupName = WScript.Arguments(0)
    csvFilePath = WScript.Arguments(1)
end if
' Get the distinguished name of the group
Set objGroup = GetObject("LDAP://" & GetDN(groupName))
' Create CSV file 
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objCSVFile = objFSO.CreateTextFile(csvFilePath, _ 
    ForWriting, True)
' Write AD Attributes CN and distinguishedname 
' as CSV columns(first line)
 objCSVFile.Write "CN,distinguishedname"
 objCSVFile.Writeline ' New Line
' List the member’s full name in the group
For Each strMember in objGroup.Member
    Set objMember =  GetObject("LDAP://" & strMember)
   ' Retrieve values and write into CSV file.
     objCSVFile.Write objMember.CN & "," 
     objCSVFile.Write """" &strMember & """" 
     objCSVFile.Writeline  ' New Line
Next

Wscript.echo "AD Group '"&groupName&"' members are Exported into CSV file '"&_
             csvFilePath&"'"
WScript.quit
' Active Directory Group Members listed successfully using VBScript

'****************Function to Get DN of group****************
' 
Function GetDN(groupName)
Dim objRootDSE, adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim adoRecordset
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 & ">"
' Filter on group objects.
varFilter = "(&(objectClass=group)(|(cn="& groupName &")(name="& groupName &")))"
' Comma delimited list of attribute values to retrieve.
varAttributes = "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
IF(adoRecordset.EOF<>True) Then
   GetDN=adoRecordset.Fields("distinguishedname").value
Else 
   'No group found 
End if
' close ado connections.
adoRecordset.Close
adoConnection.Close
End Function
'****************End of Function to Get DN of group****************

Export Active Directory Group members CMD usage:

VBScript to Export Active Directory Group Members into CSV file

 AD Group members CSV file output:

Export AD Group Members into CSV file using VBScript

Note: Here, we have exported only two attributes CN and distinguishedname of AD Group Members. if you want more attributes to export you can just add that attribute in column header and write the value accordingly.
Example:

If you want to add Mail attribute, do the following changes
' Write AD Attributes CN and distinguishedname 
' as CSV columns(first line)
 objCSVFile.Write "CN,distinguishedname,Mail"
 objCSVFile.Writeline  ' New Line
and
' Retrieve values and write into CSV file.
     objCSVFile.Write objMember.CN & "," 
     objCSVFile.Write """" &strMember & """," 
     objCSVFile.Write objMember.Mail 
     objCSVFile.Writeline  ' New Line

Saturday, 19 April 2014

Create AD User using Powershell Script

Description

Creating new Active Directory user is one of the regular task for every Administrator either for testing or for actual new employee. For that case you can create new AD user using ADUC console. But some of us feel it is time consuming job. To overcome this I have planned to write Powershell Script to Create new AD User. You can see different powershell script samples to create AD user in following examples.

You can use the Active Directory module's cmdlet New-ADUser to create new AD user.
New-ADUser newUserName

Summary:

Before start, ensure that the Active Directory module for Windows Powershell is installed or not by using following command. It will be installed by default in Domain Controller. In client machines, you need to install it through Remote Server Administration Tools.
Get-Module -Listavailable
Create New AD User using Powershell Script
If you are newbie to powershell, don’t forget to set your execution policy to unrestricted or you might get an error when you try run the script. Use the below command to set your execution policy:
Set-ExecutionPolicy Unrestricted
Powershell Script to Add New Active Directory User

Create new Active Directory User using Powershell Script

   1. Copy the below Powershell script and paste in Notepad file.
   2. Change the Name, SamAccountName and DisplayName values into your own user name
   3. Change the Parent OU path with your own OU's DN
   4. SaveAs the Notepad file with the extension .ps1 like Create-ADUser.ps1

Click to download Powershell script as file Download Create-ADUser.ps1
Import-Module ActiveDirectory
New-ADUser `
 -Name "TestUser" `
 -Path  "OU=TestOU,DC=TestDomain,DC=Local" `
 -SamAccountName  "TestUser" `
 -DisplayName "Test User" `
 -AccountPassword (ConvertTo-SecureString "MyPassword123" -AsPlainText -Force) `
 -ChangePasswordAtLogon $true  `
 -Enabled $true
Add-ADGroupMember "Domain Admins" "TestUser";
   5. Now run the Create-ADUser.ps1 file in Powershell to create new Active Directory user using following command
PS C:\Scripts> .\Create-ADUser.ps1
Add new Active Directory User using Powershell Script
Note: I have placed script file in the location C:\Scripts, if you placed in any other location, you can navigate to that path using CD path command (like cd "C:\Downloads").

Create Bulk AD Users from CSV file using Powershell Script

   1. Consider the CSV file NewUsers.csv which contains set of new ad users to create with the attributes Name, samAccountName and ParentOU.
Create Bulk AD Users from CSV file using Powershell Script
Note: The value of ParentOU should be enclosed with double quote ("). like "OU=TestOU,DC=TestDomain,DC=Local" since it has the special character comma (,). because in csv file the comma (,) is the key character to split column headers. (Ex file: Download NewUsers.csv).

   2. Copy the below Powershell script and paste in Notepad file.
   3. Change the NewUsers.csv file path with your own csv file path.
   4. Change the domain name TestDomain.local into your own domain name
   5. SaveAs the Notepad file with the extension .ps1 like Create-BulkADUsers-CSV.ps1

Click to download Powershell script as file Download Create-BulkADUsers-CSV.ps1
Import-Module ActiveDirectory
Import-Csv "C:\Scripts\NewUsers.csv" | ForEach-Object {
 $userPrincinpal = $_."samAccountName" + "@TestDomain.Local"
New-ADUser -Name $_.Name `
 -Path $_."ParentOU" `
 -SamAccountName  $_."samAccountName" `
 -UserPrincipalName  $userPrincinpal `
 -AccountPassword (ConvertTo-SecureString "MyPassword123" -AsPlainText -Force) `
 -ChangePasswordAtLogon $true  `
 -Enabled $true
Add-ADGroupMember "Domain Admins" $_."samAccountName";
}
   6. Now run the Create-BulkADUsers-CSV.ps1 file in Powershell to create Bulk Active Directory users from CSV file.
PS C:\Scripts> .\Create-BulkADUsers-CSV.ps1
Create Bulk Active Directory Users from CSV Powershell Script
Note: I have placed script file in the location C:\Scripts, if you placed in any other location, you can navigate to that path using CD path command (like cd "C:\Downloads").

   7. Now you can check the newly created AD users though ADUC console.

Powershell Script to Create Bulk AD Users from CSV file

Powershell Script to Create Bulk AD Users for Testing

   1. Copy the below Powershell script and paste in Notepad file.
   2. Change the value for the variable $totalUsers as per your wish like 1000 or more
   3. Change the Parent OU path with your own Test OU's DN
   4. SaveAs the Notepad file with the extension .ps1 like Create-BulkADUsers.ps1

Click to download Powershell script as file Download Create-BulkADUsers.ps1
Import-Module ActiveDirectory
$totalusers = 10
for ($i=0; $i -lt $totalusers; $i++) 
 { 
 $userID = "{0:00}" -f ($i + 1)
 $userName = "TestUser$userID"

 Write-Host "Creating AD user" ($i + 1) "of" $totalusers ":" $userName

New-ADUser `
 -Name $userName  `
 -Path  "OU=TestOU,DC=TestDomain,DC=Local" `
 -SamAccountName $userName `
 -AccountPassword (ConvertTo-SecureString "MyPassword123" -AsPlainText -Force) `
 -Enabled $true
 Add-ADGroupMember "Domain Admins" $userName;
}
   5. Now run the Create-BulkADUsers.ps1 file in Powershell to create Multiple Active Directory users for Testing.
PS C:\Scripts> .\Create-BulkADUsers.ps1
Create Bulk AD Users for Testing using Powershell Script

Wednesday, 16 April 2014

VBScript to Get AD Group Members

Description:

In this article, I am going to write vbscript code to find and get list of group members in Active Directory domain. it contains vbscript samples to get list of Active Directory Group member names in command line output and vbscript to export AD Group members into CSV file.

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

Summary:

Get list of AD Group Members in command line output using VBScript

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: GetADGroupMembers.vbs
3. Run usage in CMD:
C:\> CScript <vbscript file path> <groupName>
Example: CScript C:\Scripts\GetADGroupMembers.vbs "Domain Admins"

4. Run the above command to get Active Directory members list

Click to get vbscript code as file Download GetADGroupMembers.vbs
' GetADGroupMembers.vbs
' Sample VBScript to Get List of AD Group Members.
' CMD Usage: 
'     CScript <vbscript file path> <groupName>
' Ex: CScript C:\Scripts\GetADGroupMembers.vbs "Domain Admins"
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Dim groupName,strMember
Dim objGroup,objMember

if Wscript.arguments.count = 0 then
    Wscript.echo "Invalid input parameters"
    Wscript.echo "   "
    Wscript.echo "Script Usage:"
    Wscript.echo "----------------------------------------"
    Wscript.echo "CScript <vbscript file path> <groupName>"
    Wscript.echo "---------------------------------------"
    Wscript.echo "Ex: CScript C:\Scripts\GetADGroupMembers.vbs ""Domain Admins"" "
    Wscript.echo "---------------------------------------"
    WScript.quit
else
 
  ' Get the group name from command line parameter
    groupName = WScript.Arguments(0)

end if

' Get the distinguished name of the group
Set objGroup = GetObject("LDAP://" & GetDN(groupName))

' List the member’s full name in the group
For Each strMember in objGroup.Member
    Set objMember =  GetObject("LDAP://" & strMember)
    Wscript.Echo objMember.CN
Next

WScript.quit
' Active Directory Group Members listed successfully using VBScript

'****************Function to Get DN of group****************
' 
Function GetDN(groupName)

Dim objRootDSE, adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim adoRecordset

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 & ">"

' Filter on group objects.
varFilter = "(&(objectClass=group)(|(cn="& groupName &")(name="& groupName &")))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "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

IF(adoRecordset.EOF<>True) Then
   GetDN=adoRecordset.Fields("distinguishedname").value
Else 
   'No group found 
End if

' close ado connections.
adoRecordset.Close
adoConnection.Close

End Function

'****************End of Function to Get DN of group****************

AD Group members command line output:

VBScript to Get Active Directory Group Members

VBScript to Export AD Group Members into 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: ExportADGroupMembers.vbs
3. Run usage in CMD:
C:\> CScript <vbscript filepath> <groupName> <csvFilePath>
Example: CScript ExportADGroupMembers.vbs "Domain Admins" "C:\ADGroupMembers.csv"

4. Run the above command to Export Active Directory members into CSV file

Click to get vbscript code as a file Download ExportADGroupMembers.vbs
' ExportADGroupMembers.vbs
' Sample VBScript to Export AD Group Members into CSV file.
' CMD Usage: CScript <vbscript filepath> <groupName> <csvFilePath>
' Ex: CScript ExportADGroupMembers.vbs "Domain Admins" "C:\ADGroupMembers.csv"
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Dim groupName,strMember,csvFilePath
Dim objGroup,objMember
Dim objFSO, objCSVFile

if Wscript.arguments.count < 2 then
    Wscript.echo "Invalid input parameters"
    Wscript.echo "   "
    Wscript.echo "Script Usage:"
    Wscript.echo "-----------------------------"
    Wscript.echo "CScript <vbscript file path> <groupName> <csvFilePath>"
    Wscript.echo "   "
    Wscript.echo "Ex: CScript C:\Scripts\ExportADGroupMembers.vbs ""Domain Admins"" "&_
                      " ""C:\ADGroupMembers.csv"" "
    WScript.quit
else
 
  ' Get the group name and csv file path from command line parameters
    groupName = WScript.Arguments(0)
    csvFilePath = WScript.Arguments(1)

end if

' Get the distinguished name of the group
Set objGroup = GetObject("LDAP://" & GetDN(groupName))

' Create CSV file 
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objCSVFile = objFSO.CreateTextFile(csvFilePath, _ 
    ForWriting, True)

' Write AD Attributes CN and distinguishedname 
' as CSV columns(first line)

 objCSVFile.Write "CN,distinguishedname"

 objCSVFile.Writeline ' New Line


' List the member’s full name in the group
For Each strMember in objGroup.Member
    Set objMember =  GetObject("LDAP://" & strMember)
   ' Retrieve values and write into CSV file.

     objCSVFile.Write objMember.CN & "," 
     objCSVFile.Write """" &strMember & """" 
     objCSVFile.Writeline  ' New Line
Next

Wscript.echo "AD Group '"&groupName&"' members are Exported into CSV file '"&_
             csvFilePath&"'"

WScript.quit
' Active Directory Group Members listed successfully using VBScript

'****************Function to Get DN of group****************
' 
Function GetDN(groupName)

Dim objRootDSE, adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim adoRecordset

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 & ">"

' Filter on group objects.
varFilter = "(&(objectClass=group)(|(cn="& groupName &")(name="& groupName &")))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "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

IF(adoRecordset.EOF<>True) Then
   GetDN=adoRecordset.Fields("distinguishedname").value
Else 
   'No group found 
End if

' close ado connections.
adoRecordset.Close
adoConnection.Close

End Function

'****************End of Function to Get DN of group****************

Export Active Directory Group members CMD usage:

VBScript to Export Active Directory Group Members into CSV file

AD Group members CSV file output:

Export Active Directory Group Members into CSV file using VBScript

Set Session value in JavaScript

Description:

In this article, I am going write examples to access and set Session variable Value in JavaScript and how to Set Session variable value from JavaScript in ASP.NET using PageMethods, XMLHttpRequest and JQuery Ajax call.

Summary:


Set Session value in JavaScript using PageMethods

You can get and set session variable value from JavaScript in ASP.NET using Ajax ScriptManager's PageMethods. To use this you need to add ScriptManger tag in your page and enable property EnablePageMethods="True".

Check the below example to set and get session value in JavaScript using PageMethods.

Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
    {
    }

    [System.Web.Services.WebMethod]
    public static void SetSessionValue(string key,string value)
    {
        HttpContext.Current.Session[key] = value;
    }

    [System.Web.Services.WebMethod]
    public static string GetSessionValue(string key)
    {
        if (HttpContext.Current.Session[key] != null)
        {
            return HttpContext.Current.Session[key].ToString();
        }
        else
        {
            return "Session value not found";
        }
    }
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Set Session Value from JavaScript in ASP.NET using PageMethods</title>
    <script type="text/javascript">

        function SetUserName() {
            var userName = document.getElementById("tbUserName").value;
            PageMethods.SetSessionValue('UserName', userName, null, null);
        }

        function GetUserName() {
            PageMethods.GetSessionValue('UserName', OnSuccess, OnFailure);
        }
        function OnSuccess(userName) {
            document.getElementById("lbUserName").innerHTML = userName;
        }
        function OnFailure(error) {
            alert(error);
        }
  
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scripman1" runat="server" EnablePageMethods="True">
    </asp:ScriptManager>
    <div>
        Enter an user name,
        <input id="tbUserName" type="text" />
<input type="button" value="Set User Name" onclick="SetUserName()" /><br />
        <input type="button" value="Show UserName" onclick="GetUserName()" />
    <label id="lbUserName">This is a username from session variable</label>
    </div>
    </form>
</body>
</html>

Set Session value in JavaScript using XMLHttpRequest in ASP.NET

You can set and get server side session variable value from JavaScript in ASP.NET using using XMLHttpRequest. The XMLHttpRequest object is used to exchange data with a server behind the scenes. You can access Server Side value from JavaScript client side by using this object without refreshing or reloading the page.

Check the below example to get and set session value in JavaScript in ASP.NET using XMLHttpRequest.

Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Method"] == "SetUserName")
        {
            SetUserName(Request.QueryString["Value"].ToString());
        }
        else if (Request.QueryString["Method"] == "GetUserName")
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            GetUserName();
        }
    }

    private void SetUserName(string userName)
    {
        Session["UserName"] = userName;
    }

    private void GetUserName()
    {
        Response.Clear();
        if (Session["UserName"] != null)
        {
            Response.Write(Session["UserName"].ToString());
        }
        else
        {
            Response.Write("Session Value not found");
        }
        Response.End();
    }
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Set Session variable value in JavaScript using XMLHttpRequest</title>
    <script type="text/javascript">
        function SetUserName() {
            var userName = document.getElementById("tbUserName").value;            
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "WebForm1.aspx?Method=SetUserName&Value=" + userName;
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);                     
        }

        function GetUserName() {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "WebForm1.aspx?Method=GetUserName";
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);
            document.getElementById("lbUserName").innerHTML = xmlhttp.responseText;
        }
 
    </script>
     
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Enter an user name,
        <input id="tbUserName" type="text" />
<input type="button" value="Set User Name" onclick="SetUserName()" /><br />
        <input type="button" value="Show UserName" onclick="GetUserName()" />
    <label id="lbUserName">This is a username from session variable</label>
    </div>
    </form>
</body>
</html>

Get and Set Session value in JavaScript using JQuery ajax call

You can access or set session variable value from JavaScript in ASP.NET using using JQuery ajax method.

Check the below example to set session variable value in JavaScript using JQuery ajax call.
Note: You need add reference for JQuery script file to use JQuery ajax method.

Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
    {
    }

    [System.Web.Services.WebMethod]
    public static void SetSessionValue(string key, string value)
    {
        HttpContext.Current.Session[key] = value;
    }

    [System.Web.Services.WebMethod]
    public static string GetSessionValue(string key)
    {
        if (HttpContext.Current.Session[key] != null)
        {
            return HttpContext.Current.Session[key].ToString();
        }
        else
        {
            return "Session value not found";
        }
    }
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Set Session value from JavaScript in ASP.NET using JQuery ajax</title>
    <script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        function SetUserName() {
            var userName = document.getElementById("tbUserName").value;
            $.ajax({
                type: "post",
                url: "WebForm3.aspx/SetSessionValue",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"key":"UserName","value":"' + userName + '"}',
                success: function (result) {
                    //Session value saved successfully
                },
                error: function (xhr, status, error) {
                    //Failed to save Session value
                }
            });
        }

        function GetUserName() {
            $.ajax({
                type: "post",
                url: "WebForm3.aspx/GetSessionValue",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"key":"UserName"}',
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(userName) {
            document.getElementById("lbUserName").innerHTML = userName;
        }
        function OnFailure(error) {
            alert(error);
        }
  
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Enter an user name,
        <input id="tbUserName" type="text" />
<input type="button" value="Set User Name" onclick="SetUserName()" /><br />
        <input type="button" value="Show UserName" onclick="GetUserName()" />
    <label id="lbUserName">This is a username from session variable</label>
    </div>
    </form>
</body>
</html>

samAccountName vs userPrincipalName

Description:

   In Active Directory based environment, everyone should come across the AD attribute names samAccountName and userPrincipalName or UPN. In this article, I am going to explain the difference between samAccountName and userPrincipalName(UPN).

The samAccountName is the User Logon Name in Pre-Windows 2000 (this does not mean samAccountName is not being used as Logon Name in modern windows systems). The userPrincipalName is a new way of User Logon Name from Windows 2000 and later versions. user Name part can be different for the same user like DomainName\testUser and userTest@DomainName.Com.

Before see the detailed explanation, we can check the summarized details of userPrincipalName and samAccountName.

SamAccountName

   - The samAccountName attribute is the user logon name used to support clients and servers from a previous version of Windows ( Pre-Windows 2000).
   - The user logon name format is : DomainName\testUser.
   - The samAccountName must be unique among all security principal objects within the domain.
   - The samAccountName should be less than 20 characters.
   - Query for the new name against the domain to verify that the samAccountName is unique in the domain.
   - The USERNAME environment variable is the samAccountName even when logging with UPN

UserPrincipalName - (UPN)

   - The UPN is an Internet-style login name for the user based on the Internet standard RFC 822.
   - The user logon name format is : testUser@DomainName.com.
   - The UPN must be unique among all security principal objects within the directory forest.
   - The advantage of using an UPN is that it can be the same as the users email address so that the user need to remember only a single name.
   - The UPN is optional, it can be assigned or not when the user account is created.
   - The userPrincipalName is unaffected by changes to other attributes of the user object, for example, if the user is renamed or moved, or changes to the domains in the tree, for example, if a parent domain was renamed or a domain was moved. Thus, a user can keep the same login name, although the directory may be radically restructured.

Working with samAccountName and userPrincipalName

Lets take the following test user whose samAccountName is Test2 and userPrincipalName is Test1@Work2008.local

samAccountName vs userPrincipalName in Active Directory
samAccountName vs userPrincipalName in Active Directory

Now, we can use the RunAs command to validate these two user logon names. To use RunAs command, you need to run the command prompt with an elevated privilege (Run As Administrator) and the Test user should be the member of Domain Admins group.

Use the below command to validate samAccountName login name
C:\> RunAs /user:work2008\Test2 cmd
difference between samAccountName and userPrincipalName(UPN)

Use the below command to validate userPrincipalName login name
C:\> RunAs /user:Test1@work2008.local cmd
difference between userPrincipalName and  samAccountName

USERNAME environment variable is the sAMAccountName even when logging with UPN:

    We have stated that the USERNAME environment variable is the sAMAccountName even when logging with UPN. To check this run the below command in new cmd window opened by RunAs command with userPrincipalName
C:\Windows\system32> Set UserName
userPrincipalName vs samAccountName


Thanks,
Morgan
Software Developer

Tuesday, 15 April 2014

Get List of Network Computer Names in C#

Description:

In this article, I am going write C# code to Get List of Network Computer Names using NetServerEnum API function and Get List of Active Directory based Network Computer Names in C# using DirectoryService.

Summary:


Get List of Computer Names in current Network using C#

You can easily list all the available computers in current network by using NetServerEnum API function. NetServerEnum function lists all servers of the specified type that are visible in a domain. You can specify what type of computers should be return in the results by using the parameter servertype. You can refer this article http://msdn.microsoft.com/en-us/library/windows/desktop/aa370623(v=vs.85).aspx to know about the structure of NetServerEnum and possible enum values of servertype.

Note: If your network uses Active Directory to authenticate , the Computer Browser Windows service must be running to get computers in Active Directory domain network.

       1 - Go to Control Panel > Administrative Tools > Services.
       2 - Double-click Computer Browser to open the Properties dialog box.
       3 - Set the Startup type to Automatic.
       4 - Click Start.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;

namespace MorganUtil
{
    class Program
    {
        //declare the Netapi32 : NetServerEnum method import
        [DllImport("Netapi32", CharSet = CharSet.Auto,
        SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]

        // The NetServerEnum API function lists all servers of the 
        // specified type that are visible in a domain.
        public static extern int NetServerEnum(
            string ServerNane, // must be null
            int dwLevel,
            ref IntPtr pBuf,
            int dwPrefMaxLen,
            out int dwEntriesRead,
            out int dwTotalEntries,
            int dwServerType,
            string domain, // null for login domain
            out int dwResumeHandle
            );

        //declare the Netapi32 : NetApiBufferFree method import
        [DllImport("Netapi32", SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        
        // Netapi32.dll : The NetApiBufferFree function frees 
        // the memory that the NetApiBufferAllocate function allocates.         
        public static extern int NetApiBufferFree(
            IntPtr pBuf);

        //create a _SERVER_INFO_100 STRUCTURE
        [StructLayout(LayoutKind.Sequential)]
        public struct _SERVER_INFO_100
        {
            internal int sv100_platform_id;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string sv100_name;
        }

        static void Main(string[] args)
        {
            List<string> networkComputers = GetNetworkComputerNames();
            foreach (string computerName in networkComputers)
            {
                Console.WriteLine(computerName);
            }
            Console.ReadLine();
        }

        private static List<string> GetNetworkComputerNames()
        {
            List<string> networkComputerNames = new List<string>();
            const int MAX_PREFERRED_LENGTH = -1;
            int SV_TYPE_WORKSTATION = 1;
            int SV_TYPE_SERVER = 2;
            IntPtr buffer = IntPtr.Zero;
            IntPtr tmpBuffer = IntPtr.Zero;
            int entriesRead = 0;
            int totalEntries = 0;
            int resHandle = 0;
            int sizeofINFO = Marshal.SizeOf(typeof(_SERVER_INFO_100));

            try
            {
                int ret = NetServerEnum(null, 100, ref buffer,
                    MAX_PREFERRED_LENGTH,
                    out entriesRead,
                    out totalEntries, SV_TYPE_WORKSTATION |
                    SV_TYPE_SERVER, null, out 
                    resHandle);
                //if the returned with a NERR_Success 
                //(C++ term), =0 for C#
                if (ret == 0)
                {
                    //loop through all SV_TYPE_WORKSTATION and SV_TYPE_SERVER PC's
                    for (int i = 0; i < totalEntries; i++)
                    {
                        tmpBuffer = new IntPtr((int)buffer +
                                   (i * sizeofINFO));

                    //Have now got a pointer to the list of SV_TYPE_WORKSTATION and SV_TYPE_SERVER PC's
                        _SERVER_INFO_100 svrInfo = (_SERVER_INFO_100)
                            Marshal.PtrToStructure(tmpBuffer,
                                    typeof(_SERVER_INFO_100));

                        //add the Computer name to the List
                        networkComputerNames.Add(svrInfo.sv100_name);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                //The NetApiBufferFree function frees the allocated memory
                NetApiBufferFree(buffer);
            }

            return networkComputerNames;
        }
    }
}


Get IP Address of all Computers in Current Network using C#

You can use .NET classes Dns and IPAddress to convert Hostname into IP Address in C#. Get function reference GetNetworkComputerNames from above code to get list of computers in local network.

Note: If your network uses Active Directory to authenticate , the Computer Browser Windows service must be running to get computers in Active Directory domain network.
static void Main(string[] args)
        {
            // GetNetworkComputerNames - use above code to get list of network computers
            List<string> networkComputers = GetNetworkComputerNames();
            foreach (string computerName in networkComputers)
            {
                IPAddress[] ipAddresses = Dns.GetHostAddresses(computerName);

                IPAddress ip = ipAddresses[1];

                string ipAdress = ip.ToString();

                Console.WriteLine(ipAdress);
            }
            Console.ReadLine();
        }

Get List of Computer Names in AD based Network using C#

If you are trying list the available computer names in Active Directory based domain Network, you can use System.DirectoryService namespace to get computer names.
using System;
using System.DirectoryServices;

namespace MorganUtil
{
    class Program
    {
        static void Main(string[] args)
        {
             DirectoryEntry root = new DirectoryEntry("WinNT:");
            foreach (DirectoryEntry obj in root.Children)
            {
                foreach (DirectoryEntry computer in obj.Children)
                {
                    if (computer.SchemaClassName.Equals("Computer"))
                    {
                        Console.WriteLine(computer.Name);
                    }
                }
            }

            Console.ReadLine();
        }
    }
}

Thanks,
Morgan
Software Developer