Search This Blog

Sunday, August 27, 2017

Insert Data in SQL Table Using PowerShell

function DataSuccessErrorFunction ([Data.SqlClient.SqlConnection] $OpenSQLConnection) {
     $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 (Domain,WindowsLoginID,PowerShellExcutionMessage) VALUES (NGO,NGO\shrawan','Successfully'); "
    $sqlCommand.ExecuteNonQuery()
# close connection
}
# Open SQL connection (you have to change these variables)
$DBServer = "NGOMan"
$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 -ne [Data.ConnectionState]::Open) {
    "Connection to DB is not open."
    Exit
}
# Call the function that does the inserts.
DataSuccessErrorFunction ($sqlConnection)
# Close the connection.
if ($sqlConnection.State -eq [Data.ConnectionState]::Open) {
    $sqlConnection.Close()
}

Saturday, August 12, 2017

Use Session Storage Object over Local Storage in JavaScript


In few instances, we might come across such requirement where we have to retain/store variable values specific to browser tab over successive post back. Normally, If we open same HTML page in multiple tabs in same browser, then variable value retained over successive post back would be same across all opened tabs. But if requirement is to have different variable values for each opened tab then how would we handle? Lets go through it:

Resolution: As we know, there are two options available in JavaScript to retain values over successive post back.
1. Local Storage
2. Session Storage

We can use Local Storage for saving data in browser over successive post back but there are certain limitations. It will save data in browser but data will remain same for all tabs in browser. In such scenario, where we need separate values for each browser tab, we have to use Session Storage object in JavaScript.
Local Storage:
•  It can store data locally within the user's browser.
• Storage limit is far larger (at least 5 MB) and information is never transferred to the server.
• Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.
Syntax & Examples for Local Storage:
How to store the value to Local Storage in JavaScript?
Syntax: localStorage.setItem("VariableName", "Value");
Example: localStorage.setItem("BR", "Binary Replublik");
How to retrieve value from Local Storage variable in JavaScript?
Syntax: localStorage.getItem("VariableName") // Returns Object.
Example: document.getElementById("BRTeam").innerHTML = localStorage.getItem("BR");
How to remove Local Storage variable?
Syntax: localStorage.removeItem("VariableName");
Example: localStorage.removeItem("BR");
Session Storage
The Session Storage object is equal to the Local Storage object, except that it stores the data for only one session. So, the value retained with Session Storage is browser tab specific.
The data will be deleted when the user closes the specific browser tab.
Syntax & Examples for Session Storage:
How to store the value to Session Storage in JavaScript?
Syntax: sessionStorage.setItem("VariableName", "Value");
Example: sessionStorage.setItem("BR", "Binary Replublik");
How to retrieve value from Session Storage variable in JavaScript?
Syntax: sessionStorage.getItem("VariableName") //Returns Object.
Example: document.getElementById("BRTeam").innerHTML = sessionStorage.getItem("BR");
How to remove Session Storage variable?
Syntax: sessionStorage.removeItem("VariableName");
Example: sessionStorage.removeItem("BR");

Conclusion: To store variable value specific to browser tab, we have to deal with session storage over local storage.



JavaScript Best Practice Tips

Introduction
In this article, I'll share important factors to be taken into considerations while working with JavaScript. This information will help you to prevent most common mistakes in web development.
Quick Tips
  1. Use === while comparing two variable instead of ==
  2. Remember undefined is not null
  3. Remember JavaScript falsy value:   0, '', NaN, null, undefined
  4. Remember JavaScript truthy value:   '0', 'any string', [] (Empty array), {} (Empty object), 0 (any non-zero number)
  5.  Always declare all variables at the beginning of every scope
  6.  "use strict"; In JavaScript to avoid unwanted bug due to a variable.
  7. Avoid global variable declaration
  8. Reduce global variables e.g var name='abc', isValid=false; Should be written as var common={name:'abc', isValid:false};
  9. Always declare local variables
  10. Never declare Number, String or Boolean Objects ( e.g. Never use: new Number(1), new String("abc"), new Boolean() )
  11. Use {} instead of new Object()
  12. Use "" instead of new String()
  13. Use 0 instead of new Number()
  14. Use false instead of new Boolean()
  15. Use [] instead of new Array()
  16. Use /()/ instead of new RegExp()
  17. Use function (){} instead of new Function()
  18. Avoid Using eval()
  19. Don't use short hand (e.g Always use curly bracket with conditional operation)
  20. Place scripts at the Bottom of the page
  21. Declare variables outside of the loops and conditionals (such as if, for, while, switch and try)
  22. Properly comment your code
  23. Never pass a string to SetInterval and SetTimeOut. Instead, pass a function name
  24. Always, Always Use Semicolons
Reference Links

Get Folder count

function GetAllFileCountInParticularFolder(folderName,element)
{
    var TotalfileCount=0; 
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('" + folderName + "/')/Files?$orderby=Title&$expand=ListItemAllFields,ListItemAllFields/ParentList", //?$expand=Files",
        type: "Get",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },
        success: function(dataresult) {
            $.each(dataresult.d.results, function(key, value) {
            if (value.Name != "Forms") {
            if(value.ListItemAllFields["OData__ModerationStatus"] == 0)
            {
               
              TotalfileCount+=1;
             $(element).append( "<strong>( "+TotalfileCount+" )</strong>" );
            }
            }
            });
         
        },
        error: function(error) {
            //                                                alert(JSON.stringify(error));
        }
    });
   
    
}

Return function in Jquery

Call Function :

Var strbname= GetAllFileCountInParticularFolder(“NGO/Ram”,element);


Function :
function GetAllFileCountInParticularFolder(folderName,element)
{
    var TotalfileCount=0; 
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('" + folderName + "/')/Files?$orderby=Title&$expand=ListItemAllFields,ListItemAllFields/ParentList", //?$expand=Files",
        type: "Get",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },
        success: function(dataresult) {
            $.each(dataresult.d.results, function(key, value) {
            if (value.Name != "Forms") {
            if(value.ListItemAllFields["OData__ModerationStatus"] == 0)
            {
               
              TotalfileCount+=1;
             $(element).append( "<strong>( "+TotalfileCount+" )</strong>" );
            }
            }
            });
         
        },
        error: function(error) {
            //                                                alert(JSON.stringify(error));
        }
    });
   
  return TotalfileCount;
}


Get Folder and File Using JSOM Bind Dynamic Table

Call On Document ready Function
 
  //GetFolders("NGO",1);
 
function GetFolders(folderName)
{
                //checkPermissions(folderName,selectedLink);
                this.folderName=folderName;
                //this.selectedLink=selectedLink;
                var context = new SP.ClientContext.get_current();
                var web = context.get_web();
                var list = web.get_lists().getByTitle(LibraryNameForUpdate);
                var query = new SP.CamlQuery();
                query.set_folderServerRelativeUrl(folderName);
                var q = '<View><Query><OrderBy><FieldRef Name=\'ID\' Ascending=\'True\' /></OrderBy></Query></View>';
                query.set_viewXml(q);
                allItems = list.getItems(query);
                this.listInfoArray=context.load(allItems);
                context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success()
{
   //checkPermissions(this.folderName,this.selectedLink);
                var resultGridHtml='';
                var vrSrNo = 1;
                var noRecords='true';
                var ListEnumerator = this.allItems.getEnumerator();
               
                while(ListEnumerator.moveNext())
                {
                var currentItem = ListEnumerator.get_current();
                                var _contentType = currentItem.get_fileSystemObjectType();
                     if(currentItem.get_fileSystemObjectType() == '1')
                                {
                                                               
                                                                if(vrSrNo==1)
                                                                {
                                                                                resultGridHtml +='<table width="100%" id="tablepaging" class="table">';
                                                                                resultGridHtml +=FolderHeader();
                                                                               
                                                                }
                                                                noRecords='false';
                                                                var selectedLink=1;
                                                                var fieldUserValueCreatedBy = currentItem.get_item("Author");
                var fieldUserValueModifiedBy = currentItem.get_item("Editor");
                var dateCreated = new Date(currentItem.get_item('Created'));
                                                                resultGridHtml += '<tr>';
                resultGridHtml += '<td>'+ currentItem.get_item('Title')+'</td>';
                resultGridHtml += '<td>' + dateCreated.getDate() + "-" + monthNames[dateCreated.getMonth()] + "-" + dateCreated.getFullYear() +  '</td>';
                resultGridHtml += '<td>' + fieldUserValueCreatedBy.get_lookupValue() + '</td>';
                resultGridHtml += '<td>' + fieldUserValueModifiedBy.get_lookupValue() + '</td>';
                resultGridHtml += '</tr>';           
                vrSrNo =vrSrNo + 1;
                
 
                                                //FolderNames  += currentItem.get_item('Title')+ '\n';
                                }
                                if(currentItem.get_fileSystemObjectType() == '0')
                                {
                                                               
                                                                var dateCreated = new Date(currentItem.get_item('Created'));
                                                                var selectedLink=1;
                                                                var fieldUserValueCreatedBy = currentItem.get_item("Author");
                var fieldUserValueModifiedBy = currentItem.get_item("Editor");
                noRecords='false';
                                                     if(vrSrNo==1)
                                                                                {
                                                                    resultGridHtml +='<table width="100%" id="tablepaging" class="table">';
                                                                                resultGridHtml +=FileHeader();
                                                                    }
                                                                                resultGridHtml += '<tr>';
                                                                                resultGridHtml += '<td>'+ currentItem.get_item('Title')+'</td>';
                                                                                resultGridHtml += '<td>' + dateCreated.getDate() + "-" + monthNames[dateCreated.getMonth()] + "-" + dateCreated.getFullYear() + '</td>';                    
                                                                                resultGridHtml += '<td>' + fieldUserValueCreatedBy.get_lookupValue() + '</td>';
                                                                                resultGridHtml += '<td>' + fieldUserValueModifiedBy.get_lookupValue() + '</td>';
                                resultGridHtml += '</tr>';
                                vrSrNo =vrSrNo + 1;
               
            }
    }
   
                                                                if(noRecords=='true')
                                                                {
                                                                                resultGridHtml +='<table width="100%" id="tablepaging" class="table">';
                                                                                resultGridHtml +=FileHeader();
                                                                    resultGridHtml +='<tr><td colspan="9">No records found</td><tr>';
                                                                   
                                                                }                                                                                             
                resultGridHtml +='<table>';
    $('#responsiveGrid').html(resultGridHtml);
}
function failed(sender, args)
{
                //alert("failed. Message:" + args.get_message());
}
 
function FileHeader()
{
                var vHeaderFile='';
                vHeaderFile +='<thead>';
                vHeaderFile +='<tr  valign="top">';
    vHeaderFile +='<th align="left">Name</th>';
    vHeaderFile +='<th align="left">Created On</th>';
    vHeaderFile +='<th align="left">Created By</th>';
    vHeaderFile +='<th align="left">Modified By</th>';
    vHeaderFile +='</tr>';
    vHeaderFile +='</thead>';
    return vHeaderFile;
 
}
function FolderHeader()
{
                var vHeaderFolder='';
                vHeaderFolder +='<thead>';
                vHeaderFolder +='<tr valign="top">';
    vHeaderFolder +='<th align="left">Name</th>';
    vHeaderFolder +='<th  align="left">Created On</th>';
    vHeaderFolder +='<th  align="left">Created By</th>';
    vHeaderFolder +='<th  align="left">Modified By</th>';
    vHeaderFolder +='</tr>';
    vHeaderFolder +='</thead>';
    return vHeaderFolder;
}