Search This Blog

Friday, December 8, 2017

Angular JS ,2.0,4.0 Journey:



Angular JS PROS and CONS:
Angular JS Features List
1.       Introduction
Angular JS 1.X is the most popular JavaScript framework to build web applications. It was released by Google on October 20, 2010. Angular 1 is developed using TypeScript and JavaScript and uses traditional HTML. Angular 1 uses Controllers and Scope object.
2.       Prerequisites - to learn Angular 1 – JavaScript, HTML only
3.       Binding
4.       One-Way binding – you are required to use ng-bind for one way data binding in Angular 1
For Ex. <div ng-bind=”message”></div>
5.       Two-Way Binding – you are required to use {{ message }} for two way data binding in Angular 1
For Ex. <div ng-model=”message”> </div>
6.       Bootstrapping
There are two ways to bootstrap Angular app in Angular 1.

Via ng-app
For Ex. <html ng-app=”myAngularApp”></html>

Via code
For Ex. 
7.        <script>  
8.        angular.element(document).ready(function() {  
9.        angular.bootstrap(document, ['smyAngularApp']);  
10.     });  
11.     </script>  
12.   Performance
Angular 1 is slow if you have used too many watchers in your angular 1 app. You need to reduce watchers to make it faster.
13.   For more information about Watchers & Digest Cycle in AngularJS, Read the below article -       

15.   Mobile Support
Angular1 is responsive but, does not have mobile support. It was not built for mobile devices. It is possible to run Angular 1 on mobile, but using 3rd party frameworks.
16.   Services
There are various ways to create services in Angular 1 like Service, Factory, Provider etc.
17.   Filters 
Filters are used to filter a result set in Angular 1.

Angular 2 Features List
  1. Angular 2 is five times faster than Angular 1
  2. By default, it support for one-way data binding.
  3. In optional, it support for two-way data binding.
  4. It widely support for Typescript and ES6.
  5. It contains component-based architecture.
  6. Less coding requires that is more application focus.
  7. Angular 2 is based on Mobile First approach.
  8. It is oriented on the apps with a big amount of interactive client side code.
  9. Best for dynamic apps with a single page.
  10. It offers fast development process.
  11. Offers advanced testing features.
  12. In most of the cases, demands less coding.
  13. Perfect for server side rendering.
  14. The framework approach that offers everything a developer needs to build apps.
  15. Being ES2015, it already takes advantage of many latest language features.
  16. Easy to test.
  17. Improved data binding.
  18. Components based.
Angular 4 Features List
  1. Angular 4 are five times faster and smaller as compared to Angular 2..
  2. It is possible to view engine and how AOT generated code looks like.
  3. Improved nglf and ngFor.
  4. Running Angular on a server.
  5. Source maps for templates.
  6. Typescript 2.1 and 2.2 compatibility.
  7. Flat ESM/FESM modules for tree shaking and reducing size of generated bundles.
  8. Experimental Closure compatibility to take advantage of advanced Closure optimizations, getting smaller bundle sizes and better tree shaking.
  9. Backward compatible as PATCH increased when some troubleshooting is done even without changing the API.
  10. It is possible to request for the route and query parameter assigned to a route because of Router PARAM Map.
  11. Dynamic components with NgComponentOutlet to build dynamic components in a declarative way.
  12. Forms get assigned “no validate” automatically.
  13. Availability of source maps for templates.


Friday, November 10, 2017

Get Logged User / Current user Details Using Rest Api


//Call  the function  Where You Want to use 

getUser(_spPageContextInfo.userId);
 
 // Fuction Body
function getUser(id){
var returnValue;
  jQuery.ajax({
   url: vUrl +"/_api/Web/GetUserById(" + id + ")",
   type: "GET",
   async:false,
   headers: { "Accept": "application/json;odata=verbose" },
   success: function(data) {
           var dataResults = data.d;
      //get login name 
      var loginName  = dataResults.LoginName.split('|')[1];
      var Email=dataResults.Email;
      returnValue=loginName+";"+Email;
     // returnValue=loginName;
   }
  
 });
return returnValue;
 
}

Consume WCF and REST WCF Services in Console and C#

class Program
    {
        static void Main(string[] args)
        {
            
            string ngoServiceUrl ="https://ngo.com/NGO/ngo_services.svc/GetUserinfoData"
            int oprtype = 3;
            string txtEmp="ngo\\\\shrawan";
            WebRequest req = WebRequest.Create(ngoServiceUrl );
            req.ContentType = "application/json; charset=utf-8";
            req.Method = "POST";
            string da = "{\"userid\":\"" + txtEmp + "\",\"oprtype\":" + oprtype + "}";
            using (var streamWriter = new StreamWriter(req.GetRequestStream()))
            {
                streamWriter.Write(da);
                streamWriter.Flush();
            }
            var httpResponse = (HttpWebResponse)req.GetResponse();
            if (httpResponse.StatusCode == HttpStatusCode.OK)
            {
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var responseText = streamReader.ReadToEnd();
                    string[] res=responseText.Split(':');
                    string msg = res[2].Split('}')[0];
                    if (msg.Equals("1"))
                    {
                        Console.WriteLine("Redirect");
                    }


                }
            }


                                        
        }


        }

Using SharePoint Lists vs. Database Tables

An important decision in the design of the Training Management application was deciding whether to store information in lists or in a database. SharePoint lists consist of rows and columns that store data in a similar fashion to a traditional relational database management system such as SQL Server. However, a benefit of lists is that SharePoint includes Web Parts that provide simple methods for managing the data. If the data was stored in a database, it would require custom user interface components to access it and manipulate it. Also, specialized skills are required to design, implement, and maintain a custom database. Another advantage of using lists is that custom workflow and event handlers can easily be registered to them.
There are also advantages to storing data inside of a database. One is the availability of all the ACID (Atomic, Consistent, Isolated and Durable) properties of transactions. If your business logic requires transactions, storing data in a database is preferable to using lists. Also, SharePoint lists are meant to store simple data structures. If you require a complex data model with intricate relationships, a database is more appropriate. The Training Management application has three data storage requirements. It stores data related to training courses, registrations, and registration approval tasks. All the data is relatively simple and does not use transactions. The registration data also requires that there be a workflow. All these reasons make SharePoint lists the appropriate choice.
In general, reading and writing to a custom database provides an overall performance advantage. Although SharePoint has made significant strides in its performance, there is still a certain amount of overhead involved in processing lists. The SharePoint product team recommends limiting the number of items in a list to 2,000 for each list container. (A container is the root of the list and any folders in the list.) You may be able to manage larger lists by using views that are filtered so that no single view contains more than 2,000 items. Another way to circumvent this performance degradation is to write custom interfaces to manage and retrieve the data. (It is important to note that the 2,000 item threshold has more to do with HTML rendering performance than with the underlying performance of lists as a storage mechanism.) For more information about the performance of SharePoint lists, see the SharePoint product group's white paper, Scaling to Extremely Large Lists and Performance Access Methods.
The following table summarizes the benefits of using databases and SharePoint lists.
Benefits
Database
SharePoint list
Handles complex data relationships
Yes
No
Handles large numbers of items
Yes
No
Handles transactions
Yes
No
Is easy to use
No
Yes
Accommodates workflows
No
Yes
Includes a standard interface
No
Yes
Can easily add binary data
No
Yes


Best Practices for jQuery Developers

Following are some of the best practices that you could follow while working with jQuery:
  • Plugins:
    • Please avoid unnecessary use of plugins
    • If a plugin is being used, respect the authors work and ensure that the plugin file is reused with the license comments intact
    • If you are writing a reusable functionality in the code, always move it into a jQuery plugin format, to be reused across the site
  • Coding:
    • Use jQuery CDN (google or Microsoft or jQuery) as much as possible for script registration, if its fine with clients. To be on the safer side, you could have a fallback code as well:
      <!– Grab Google CDN jQuery. fall back to local if necessary –> 
<script>!window.jQuery && document.write(‘<script src=”js/jquery-1.4.2.min.js”><\/script>’)</script>
  • Avoid unnecessary upgrades of jQuery, unless there are features, which you require or some plugins require. Stick to one version from the beginning. (ex. 1.5.1)
  • Avoid writing event handler attributes (onclick etc.), instead use live or bind methods to attach the respective event handlers.
  • Avoid mixing javascript code with jQuery code.
  • Cache any jQuery selector, if reused in multiple statements.
    Ex. Avoid $(“#x”).val(); $(“#x”).attr(“align”,”right”); Use var $x = $(“#x”); $x.val();$x.attr(“align”,”right”);
  • Ensure that you place ready function in your code. $(document).ready(function(){});
  • Use find method, instead of building a complex jQuery selector.
//Fine in modern browsers, though Sizzle does begin “running”
$(‘#someDiv p.someClass’).hide(); 
// Better for all browsers, and Sizzle never inits. 
$(‘#someDiv’).find(‘p.someClass’).hide(); 
  • Avoid misusing $(this).
    Ex. Use this.id instead of $(this).attr(‘id’)
  • Keep your code safe, by using noConflict() method or by passing jQuery.
    Ex. (function($){})(jQuery); or by wrapping it in a ready method.
  • Avoid declaring new jQuery selectors within foreach, instead declare them outside and reuse it inside the loop.
  • Use $.ajax instead of $.get or $.getJSON, because internally they call $.ajax.
  • Use JSON formats for communications.
  • Ensure that you move your jQuery codes to a separate javascript file, instead of inline scripts.
  • Compress javascript files for better performance.
  • Combine multiple css() calls or attr() calls into one. In case of attributes, you could also pass them as shown below: 
$(‘</a>’, {
    id : ‘myId’, 
    className : ‘myClass’, 
    href : ‘mytest.html’ 
});
  • Debugging:
    • Use Developer Toolbars and Inspectors to debug your code from client side. You do not need to perform deployments and builds to debug your jQuery code(s).
  • jQuery Cheat Sheet:
    • Always keep a jQuery cheat sheet handy with you to know about the list of functions available for you. Download here
Below are some more useful links you could check out:
Some words of caution:
  • $.ajax has issues in making cross domain AJAX calls. As a solution, you can get a patched version of $.ajax from the net.
  • Avoid http request on https sites. Your user will be prompted with a nagging security popup, which on rejection can break your request.
  • Avoid loading multiple jQuery versions.
  • Majority of the jQuery plugins are browser compatible, but NOT ALL. Read the plugin documentations carefully and use them judiciously.
This might appear to be a drop from the ocean. But it will guide them in the right direction.

Friday, October 20, 2017

SharePoint Server 2019

At Ignite Microsoft announced SharePoint Server 2019. It will arrive in the second half of 2018. Preview version is expected mid 2018. SharePoint will come with Office 2019, Exchange Server 2019 and Skype for Business Server 2019.
SharePoint 2019 focus on 4 pillars:
  • Share and work together
  • Inform and engage
  • Transform business process
  • IT/developer value
What we know so far:
  • SharePoint 2019 will support next gen sync client (for OneDrive files and sites synchronizations).
  • User interface will be modernized
  •  New sharing capabilities
  • Communications sites and team news for on-prem.
  • Transform business processes
  • Deeper integration with Power Apps/Flow
  • InfoPath will be supported in SharePoint 2019
  • Modernized metadata and filtering,
  • Column formatting
  • SharePoint Framework to extending business process
  • Hybrid configuration during configuration process
  • Expanding supporting characters
  • New max path limit 400
  • Upload web files
  • Enhanced security
  • SMTP email server authentication
  • New features in SharePoint Framework (new webparts, extensions)
These features are still in planning stage but next months will shows what will be implemented in final product.
Microsoft announced the TAP program for SharePoint Server 2019. Simply go to the Programs nomination portal. Use the private program code SPT232 (not all requests will be accepted).

PowerShell Pass Multiple Parameter using AddSript(store powershell OutPut In SQL table using Procedure and Table insertion Method)

By Procedure

param(
[string]$a,
[string]$CreatedBY,
[string]$LoginName,
[string]$RecID,
[string]$IsParticularsActionFlagvar
)
foreach ($i in $a
{
    #write  "User CN Parameter: $i" >>C:\NGOForm\NGOlogfile.txt
    $OU=$i
    #$OU='CN=NGOuser5,OU=ExitUsersOU,OU=NGO-TEST_OU,DC=NGO,DC=Test,DC=com'
}
foreach ($j in $CreatedBY
{
    #write  "User LoginName Parameter: $j" >>C:\NGOForm\NGOlogfile.txt
    #$VarCreatedBY='Shrawan'
    $VarCreatedBY=$j

}
foreach ($k in $LoginName
{
    #write  "User LoginName Parameter: $j" >>C:\NGOForm\NGOlogfile.txt
    #$UserName='NGO\ngoTest12'
    $UserName=$LoginName

}
foreach ($h in $RecID
{
    #write  "User LoginName Parameter: $j" >>C:\NGOForm\NGOlogfile.txt
    #$VarRecID=4
    $VarRecID=$h
}
foreach ($l in $IsParticularsActionFlagvar
{
    #write  "User LoginName Parameter: $j" >>C:\NGOForm\NGOlogfile.txt
    #$VarIsParticularsActionFlag=4
    $VarIsParticularsActionFlag=$l
}
# Start  Here Define The Passwoed Max Length
$length=Get-Content -Path C:\NGOForm\ResetPasswordMaxLength.txt
# End  Here Define The Passwoed Max Length
$currentDate = Get-Date
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue-eq $null) {
       Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
# End   Call The Fuction Of Rest Password
# Start  Fuction Of Rest Password

Function Set-ADAccountPassNew {
[CmdletBinding()]
param(

[parameter(ValueFromPipeline=$true,Position=0,Mandatory=$True,HelpMessage="Complete OU Path")][ValidateNotNullOrEmpty()] [string[]]$OU ,
[parameter(ValueFromPipeline=$true,Position=1,Mandatory=$True,HelpMessage="UserName")][ValidateNotNullOrEmpty()] [string[]]$UserName ,
[parameter(ValueFromPipeline=$true,Position=2,Mandatory=$True,HelpMessage="Length of Random Password which should be divisible by 3")][ValidateNotNullOrEmpty()] [int]$length ,
[parameter(ValueFromPipeline=$true,Position=3,Mandatory=$True,HelpMessage="Is Particulars Action Flag")][ValidateNotNullOrEmpty()] [int[]]$VarIsParticularsActionFlag ,
[parameter(ValueFromPipeline=$true,Position=4,Mandatory=$True,HelpMessage="Created BY")][ValidateNotNullOrEmpty()] [string[]]$VarCreatedBY ,
[parameter(ValueFromPipeline=$true,Position=5,Mandatory=$True,HelpMessage="Rec ID")][ValidateNotNullOrEmpty()] [int[]]$VarRecID )

process {

Function random-password {
[CmdletBinding()]
param[parameter(Position=0,Mandatory=$True,HelpMessage="Length of Random Password which should be divisible by 3")]
          [ValidateScript({if( ($_ % 3-eq 0 ) {  $TRUE  } else { Throw "Error!! Length of Random Password which should be divisible by 3" }})] [int]$length )
process {
       $len= $length/3
       $part1=-join ( (37..38+ (40..42| Get-Random -Count $len | % {[char]$_})
       $part2=-join ((65..90+ (97..122| Get-Random -Count $len | % {[char]$_})
       $part3=-join ((49..57| Get-Random -Count $len | % {[char]$_})
       $array = "$part1$part2$part3".ToCharArray()
       [array]::sort($array)
       $pass1 = "$array" | Get-Random -Count $length
       $password = $pass1.replace(' ','')
       return $password
}
}
$random=random-password -length $length
$NewPassword = ConvertTo-SecureString -AsPlainText $random -Force

# Start Log File
 write  "User CN Parameter: $OU" >>C:\NGOForm\NGOlogfile.txt
write  "User Employee Name Parameter: $VarCreatedBY" >>C:\NGOForm\NGOlogfile.txt
write  "User Windows Login Name : $UserName" >>C:\NGOForm\NGOlogfile.txt
write  "User Parent Rec ID Parameter: $VarRecID" >>C:\NGOForm\NGOlogfile.txt
write  "User Is Particulars Action Flag Parameter: $VarIsParticularsActionFlag">>C:\NGOForm\NGOlogfile.txt
write  "Length Of Password: $length" >>C:\NGOForm\NGOlogfile.txt
write  "Reset Password : $random" >>C:\NGOForm\NGOlogfile.txt
# End  Log File

$DBServer = Get-Content -Path C:\NGOForm\DBServer.txt
$DBName = Get-Content -Path C:\NGOForm\DBName.txt
$Password = Get-Content -Path C:\NGOForm\DBPassword.txt
$UserID =Get-Content -Path C:\NGOForm\DBUserID.txt
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=$DBServer;Database=$DBName;User ID=$UserID;Password=$Password; Integrated Security=True;"
$sqlConnection.Open()

if ($sqlConnection.State -ne [Data.ConnectionState]::Open) {
    Write-Error "SQL Connection Failed! Connection to DB is not open."
    Exit
}
if ($sqlConnection.State -eq [Data.ConnectionState]::Open) {
    Write-Output "SQL Connection successful! Connection to DB is open"
}
# Quit if the SQL connection didn't open properly.

$User = Get-Content -Path C:\NGOForm\AdminUserName.txt
$Pass = Get-Content -Path C:\NGOForm\AdminPassword.txt
$PWord = ConvertTo-SecureString -String "$Pass" -AsPlainText -Force
$mycred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User,$PWord
$error.clear()
Set-ADAccountPassword "$OU" -Server NGO.Test.com -Reset -Credential $mycred -NewPassword$NewPassword -ErrorVariable PRError
if($?)
{
   
   $PStatus = Write-Output "Success! Password reset successfully"
   $sqlCommand = New-Object System.Data.SqlClient.SqlCommand
   $sqlCommand.Connection = $sqlConnection
   $sqlCommand.CommandText = "[uspPowershellExecutionHistory] @NGORecID = '$VarRecID', @WindowsLoginID = '$UserName', @OUName = '$OU', @PowerShellExcutionMessage = 'Success! Password reset successful', @ResetPassword = '$random', @CreatedBy = '$VarCreatedBY', @IsParticularsActionFlag ='$VarIsParticularsActionFlag';"
   $sqlCommand.ExecuteNonQuery()
   # close connection
   $sqlConnection.Close()

   write  "****************************Success! Password reset successfully On : $currentDate  ******************************" >>C:\NGOForm\NGOlogfile.txt


   }
else
{
   Write-Output "Failed! Password reset failed"
   $errorval = $error.exception
   $errorval
   $sqlCommand = New-Object System.Data.SqlClient.SqlCommand
   $sqlCommand.Connection = $sqlConnection
   $sqlCommand.CommandText = "[uspPowershellExecutionHistory] @NGORecID = '$VarRecID', @WindowsLoginID = '$UserName', @OUName = '$OU', @PowerShellExcutionMessage = 'Failed! Password reset failed', @ResetPassword = '$random', @CreatedBy = '$VarCreatedBY', @IsParticularsActionFlag ='$VarIsParticularsActionFlag';"

   $sqlCommand.ExecuteNonQuery()
   # close connection
   $sqlConnection.Close()
   write  "****************************Failed! Password reset failed On : $currentDate  ******************************" >>C:\NGOForm\NGOlogfile.txt
}

#$sqlConnection.Close()
}
}
# End   Fuction Of Rest Password
# Start  Call The Fuction Of Rest Password 
Set-ADAccountPassNew -OU "$OU" -UserName "$UserName" -length "$length" -VarIsParticularsActionFlag "$VarIsParticularsActionFlag" -VarCreatedBY "$VarCreatedBY" -VarRecID "$VarRecID"


By Table

param(
[string]$a,
[string]$CreatedBY,
[string]$LoginName,
[string]$RecID,
[string]$IsParticularsActionFlagvar
)
foreach ($i in $a
{
    #write  "User CN Parameter: $i" >>c:\NGOlogfile.txt
    $VarCN=$i
}
foreach ($j in $CreatedBY
{
    #write  "User LoginName Parameter: $j" >>c:\NGOlogfile.txt
    $VarCreatedBY=$j
   
}

foreach ($k in $LoginName
{
    #write  "User LoginName Parameter: $j" >>c:\NGOlogfile.txt
    $varLoginName=$k
   
}

foreach ($h in $RecID
{
    #write  "User LoginName Parameter: $j" >>c:\NGOlogfile.txt
    $VarRecID=$h
   
}

foreach ($l in $IsParticularsActionFlagvar
{
    #write  "User LoginName Parameter: $j" >>c:\NGOlogfile.txt
    $VarIsParticularsActionFlag=$l
   
}

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue-eq $null) {
       Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

#$randomObj = New-Object System.Random
#$NewPassword=""
#1..12 | ForEach { $NewPassword = $NewPassword + [char]$randomObj.next(33,126) }
#$NewPassword



# Open SQL connection (you have to change these variables)
$DBServer = "111.22.33.54"
$DBName = "DB_NGO"
$Password = "NGO"
$UserID = "NGO"
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=$DBServer;Database=$DBName;User ID=$UserID;Password=$Password; Integrated Security=True;"
$sqlConnection.Open()
# Quit if the SQL connection didn't open properly.
if ($sqlConnection.State -eq [Data.ConnectionState]::Close) {
                $sqlConnection.Open()
            }


#if ($sqlConnection.State -ne [Data.ConnectionState]::Open) {
    #"Connection to DB is not open."
   # Exit
#}

#write  "Error: pa" >>c:\logfile.txt
$username = 'NGO\admin'
$Password = 'ngo' | ConvertTo-SecureString -Force -AsPlainText
$credential = New-Object System.Management.Automation.PsCredential($username, $Password)

Function random-password {
[CmdletBinding()]
param[parameter(Position=0,Mandatory=$True,HelpMessage="Length of Random Password which should be divisible by 3")]
          [ValidateScript({if( ($_ % 3-eq 0 ) {  $TRUE  } else { Throw "Error!! Length of Random Password which should be divisible by 3" }})] [int]$length )
process {
       $len= $length/3
       $part1=-join ( (37..38+ (40..42| Get-Random -Count $len | % {[char]$_})
       $part2=-join ((65..90+ (97..122| Get-Random -Count $len | % {[char]$_})
       $part3=-join ((49..57| Get-Random -Count $len | % {[char]$_})
       $array = "$part1$part2$part3".ToCharArray()
       [array]::sort($array)
       $pass1 = "$array" | Get-Random -Count $length
       $password = $pass1.replace(' ','')
       return $password
}
}
$random=random-password -length $length
$NewPassword = ConvertTo-SecureString -AsPlainText $random -Force
write  "User NewPassword  Pass Parameter: $NewPassword" >>c:\NGOlogfile.txt
try
{
   $job = Start-Job -scriptblock {
         
          #Set-ADAccountPassword $args[0] -Server "NGO.Test.com" -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $NewPassword -Force)
          #Set-ADAccountPassword  $args[0] -Server "NGO.Test.com" -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "vinay@3708" -Force)
          Set-ADAccountPassword 'CN=Exit User1,OU=ExitUsersOU,OU=NGO-TEST_OU,DC=NGO,DC=Test,DC=com' -Server "NGO.Test.com" -Reset -NewPassword(ConvertTo-SecureString -AsPlainText "vinay@8852" -Force)
         }-ArgumentList $a -credential $credential
         Receive-Job $job
         Wait-Job $job
           
            if($?)
            {
            write  "User CN Parameter: $VarCN" >>c:\NGOlogfile.txt
            write  "User Employee Name Parameter: $VarCreatedBY" >>c:\NGOlogfile.txt
            write  "User Windows Login Name : $varLoginName" >>c:\NGOlogfile.txt
            write  "User Parent Rec ID Parameter: $VarRecID" >>c:\NGOlogfile.txt
            write  "User Is Particulars Action Flag Parameter: $VarIsParticularsActionFlag">>c:\NGOlogfile.txt
          
            $currentDate = Get-Date
            $sqlCommand = New-Object System.Data.SqlClient.SqlCommand
            $sqlCommand.Connection = $sqlConnection
            # This SQL query will insert 1 row based on the parameters, and then will return the ID
            # field of the row that was inserted.""
            #$sqlCommand.CommandText ="INSERT INTO dbo.tblPowershellExecutionHistory (NGORecID,WindowsLoginID,CN,PowerShellExcutionMessage,ResetPassword,CreatedBy,CreatedDate,IsParticularsActionFlag) VALUES ('$VarRecID','$varLoginName','$VarCN','Password reset successfully: $job','$pass','$VarCreatedBY','$currentDate','$VarIsParticularsActionFlag'); "
            $sqlCommand.CommandText ="INSERT INTO dbo.tblPowershellExecutionHistory (NGORecID,WindowsLoginID,CN,PowerShellExcutionMessage,ResetPassword,CreatedBy,CreatedDate,IsParticularsActionFlag,IsActive) VALUES ('$VarRecID','$varLoginName','$VarCN','Password reset successfully','$NewPassword','$VarCreatedBY','$currentDate','$VarIsParticularsActionFlag','YES'); "
            $sqlCommand.ExecuteNonQuery()
            write  "Reset Password Success: Password reset successfully" >>c:\NGOlogfile.txt
               #"Password reset successfully"
            }


            else
            {
             $sqlCommand = New-Object System.Data.SqlClient.SqlCommand
             $sqlCommand.Connection = $sqlConnection
             # This SQL query will insert 1 row based on the parameters, and then will return the ID
             # field of the row that was inserted.""
              $sqlCommand.CommandText ="INSERT INTO dbo.tblPowershellExecutionHistory (NGORecID,WindowsLoginID,CN,PowerShellExcutionMessage,ResetPassword,CreatedBy,CreatedDate) VALUES ('$VarRecID','$varLoginName','$VarCN','Password Reset  failed','$NewPassword','$VarCreatedBY','$currentDate'); "
             $sqlCommand.ExecuteNonQuery()
              write  "Reset Password  Error: Password reset failed" >>c:\NGOlogfile.txt
              #"Password reset failed"
            }
            # close connection
            if ($sqlConnection.State -eq [Data.ConnectionState]::Open) {
                $sqlConnection.Close()
            }

        #Set-ADAccountPassword 'CN=Exit User1,OU=ExitUsersOU,OU=NGO-TEST_OU,DC=NGO,DC=Test,DC=com' -Server "NGO.Test.com" -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "vinay@8822" -Force)
}
catch [Exception]
{
            $sqlCommand = New-Object System.Data.SqlClient.SqlCommand
            $sqlCommand.Connection = $sqlConnection
            # This SQL query will insert 1 row based on the parameters, and then will return the ID
            # field of the row that was inserted.""
            $sqlCommand.CommandText ="INSERT INTO dbo.tblPowershellExecutionHistory (NGORecID,WindowsLoginID,CN,PowerShellExcutionMessage,ResetPassword,CreatedBy,CreatedDate) VALUES ('$VarRecID','$varLoginName','$VarCN','Error in  reset  password:$_.Exception.Message','$NewPassword','$VarCreatedBY','$currentDate'); "
            $sqlCommand.ExecuteNonQuery()
            write  "Error: $_.Exception.Message" >>c:\NGOlogfile.txt
   
}
      



Procedure


ALTER PROCEDURE [dbo].[uspPowershellExecutionHistory]
        @NGORecID                  int,
           @WindowsLoginID             nvarchar(200),
           @OUName                     nvarchar(500),
              @PowerShellExcutionMessage  nvarchar(4000),
              @ResetPassword              nvarchar(100)=null,
              @CreatedBy                  nvarchar(200),
              @IsParticularsActionFlag    int
       AS
BEGIN
INSERT INTO dbo.tblPowershellExecutionHistory
(
                     NGORecID,
                     WindowsLoginID,
                     CN,
                     PowerShellExcutionMessage,
                     ResetPassword,
                     CreatedBy,
                     CreatedDate,
                     IsParticularsActionFlag,
                     IsActive
)
 VALUES (
            @NGORecID,
                     @WindowsLoginID,
                     @OUName,
                     @PowerShellExcutionMessage,
                     @ResetPassword,
                     @CreatedBy,
                     GETDATE(),
                     @IsParticularsActionFlag,
                     'YES'
)

END



C# Code :

  // ps.AddScript(@"C:\temp\DisableUserAccountPSScript.ps1 '" + dynamicReplacementParameterInScript + "'");
                                        ps.AddScript(@"C:\temp\ChangePasswordPSScript.ps1 '" + dynamicReplacementParameterInScript + "' " + " '"+ CreatedBY + "' " + " '"+ LoginName + "' " + " '"+ RecID + "' ");

                                        var results = ps.Invoke();
                                        if (results.Count > 0)
                                        {
                                            ActionHappen = 1;
                                            PowerShellScriptOutPutResult = "Password reset successfully";
                                        }
                                        else
                                        {
                                            ActionHappen = 0;
                                            PowerShellScriptOutPutResult = " Password reset failed";
                                        }