Friday, 24 February 2017

Comparison Operators using Powershell


The following operators are all Case-Insensitive by default:
 -eq             Equal
 -ne             Not equal
 -ge             Greater than or equal
 -gt             Greater than
 -lt             Less than
 -le             Less than or equal
 -like           Wildcard comparison
 -notlike        Wildcard comparison
 -match          Regular expression comparison
 -notmatch       Regular expression comparison
 -replace        Replace operator
 -contains       Containment operator
 -notcontains    Containment operator
 -shl            Shift bits left (PowerShell 3.0)
 -shr            Shift bits right – preserves sign for signed values.(PowerShell 3.0)
 -in             Like –contains, but with the operands reversed.(PowerShell 3.0)
 -notin          Like –notcontains, but with the operands reversed.(PowerShell 3.0)
To perform a Case-Sensitive comparison just prefix any of the above with "c"
for example -ceq for case-sensitive Equals or -creplace for case-sensitive replace.
Similarly prefixing with "i" will explicitly make the operator case insensitive.
Types
 -is     Is of a type
 -isnot  Is not of a type
 -as     As a type, no error if conversion fails

Logical operators
 -and    Logical And
 -or     Logical Or
 -not    logical not
  !      logical not

Bitwise operators 
 -band   Bitwise and
 -bor    Bitwise or
 
Format Operator
 "format_string" -f Object1, Object2,...
The format_string is in the form: {0,-5} {1,-20} {2,-10}
In each set of braces, the first number, before the comma refers to the column.
The second number, after the comma determines the padding (how many characters)
If the second number is negative, it not only pads the element, but aligns it vertically. Optionally the second number can be used for formatting :hh :mm :C :p


Examples
$demo = $null
if (-Not ($demo)) { write "Zero, null or Empty"}
if (!($demo)) { write "Zero, null or Empty"}
$myVar -is "String"
$myVar -eq 123
$myVar -ceq $myVar2
"abcdef" -like "abc*"
"abcdef" -replace "dEf","xyz"
$myVar1 -is "String" -and $myVar2 -is "Int"
"{2:N}" -f 24.4567
(1 -eq 1) -and -not (2 -gt 2)

$mycmd = ps | select id,ProcessName
foreach ($proc in $mycmd) {"{0,-8}{1,-20}" -f $proc.id, $proc.ProcessName}
“The 50-50-90 rule: Anytime you have a 50-50 chance of getting something right, there's a 90% probability you'll get it wrong” ~ Andy Rooney


Related:
if - Conditionally perform a command
Assignment Operators ( $variable = X, $variable += Y )
PowerShell Regular Expressions
Format-Table

Wednesday, 22 February 2017

Copy data from once column to another using conditions


Write-host "Copying Data from abc to defs field"
Write-host "------"
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$WebSite = Read-host "Please enter the Site URL "
$ListName = Read-host "Please enter the Source List Name"
$SrcFieldName = Read-host "Please enter the Source Field Name to copy the data"
$DestFieldName = Read-host "Please enter the Destination Field Name to copy the data"

#Using Get-SPSite
function global:Get-SPSite($url)
 {
    return new-Object Microsoft.SharePoint.SPSite($url)
 }

Function global:Get-SPWeb($url)
{
  $site= New-Object Microsoft.SharePoint.SPSite($url)
        if($site -ne $null)
            {
               $web=$site.OpenWeb();
            }
    return $web
}

 #Parameters
 $web = Get-SPweb $WebSite
 $listName = $ListName

 #Use the Display Names
 $CopyFromColumnName = $SrcFieldName #"Claim" #column copy source
 $CopyToColumnName = $DestFieldName #"FEPClaims"  #destination column

  #Get the List
  $list = $web.lists[$ListName]

  #Get all Items
  $Items = $list.Items

#initialize count;
$Count=0

     foreach ($Item in $items)
        {
if($item["Content Type"] -eq "Content type name")
{
  Write-Host "The Content Type is: " $item["Content Type"]

$Count++
            #copy data from one column to another
            $item[$copyToColumnName] = $item[$copyFromColumnName]

            #Do a system update to avoid Version and to Keep same metadata
            $item.SystemUpdate($false)
Write-Host $Count "record copied"
        }
}
Write-Host "Total " $Count "records copied."
Write-host "Completed copying of the records."
Write-host "------"



Ref: https://shipoint.com/2013/02/25/find-and-replace-content-types-in-sharepoint-2010-using-powershell/

Tuesday, 21 February 2017

Copy data from one column to another column


Write-host "Copying Data from abc to abc1"
Write-host "------"
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$WebSite = Read-host "Please enter the Site URL "
$ListName = Read-host "Please enter the Source List Name"
$SrcFieldName = Read-host "Please enter the Source Field Name to copy the data"
$DestFieldName = Read-host "Please enter the Destination Field Name to copy the data"

#Using Get-SPSite
function global:Get-SPSite($url)
 {
    return new-Object Microsoft.SharePoint.SPSite($url)
 }

Function global:Get-SPWeb($url)
{
  $site= New-Object Microsoft.SharePoint.SPSite($url)
        if($site -ne $null)
            {
               $web=$site.OpenWeb();
            }
    return $web
}

 #Parameters
 $web = Get-SPweb $WebSite
 $listName = $ListName

 #Use the Display Names
 $CopyFromColumnName = $SrcFieldName #"Claim" #column copy source
 $CopyToColumnName = $DestFieldName #"FEPClaims"  #destination column

  #Get the List
  $list = $web.lists[$ListName]

  #Get all Items
  $Items = $list.Items

#initialize count;
$Count=0

     foreach ($Item in $items)
        {
$Count++
            #copy data from one column to another
            $item[$copyToColumnName] = $item[$copyFromColumnName]

            #Do a system update to avoid Version and to Keep same metadata
            $item.SystemUpdate($false)
Write-Host $Count "record copied"
        }
Write-Host "Total " $Count "records copied."
Write-host "Completed copying of the records."
Write-host "------"


Monday, 20 February 2017

Upload multiple list items at a time using webpart in Moss 2007 (Coding)

Introduction:

A custom SharePoint list can be configured to collect any type of data and SharePoint automatically generates the forms for adding new items, editing items and viewing items.

Team Web site comes with a built-in List Calendar, Task, which is listed on the Quick Launch bar. A new custom list has to be created for storing the files.

Steps creating custom list:


Custom list created


Custom Column Creation

  1. While creating custom list Named as FileList default column will create Title.
  2. Modify column name Title as Filename.
  3. Create one more column as Filedate.
  4. Create one more column as FileSize.
Implementation of Web part

The files are added to the custom GridView (list) in web part level using browse file upload button. You can add and delete multiple files in this list. Finally all the files are uploaded in custom share point list Filelist using submit button in webpart.

The steps to create a web part
  • Make sure installed VS.net 2005.
  • Make sure installed Web part Project Library in your system.
  • Start VS.Net 2005 and create a new project.
  • Select Project Type as Visual C#-->SharePoint.
  • Visual Studio Installed templates as Web Part.
  • Change Name as MultipleUploadWebpart.
  • Change Location as e:\ MultipleUploadWebpart.
  • Change Solution name as FileUploadWebPart.

Using the Render method

The Web part base class seals the Render method of System.Web.UI.Control because the Web Part infrastructure needs to control rendering the contents of a Web Part. For this reason, custom Web Parts must override the Render method of the Web part base class.

The Complete Web part Code

#region File Information
///<summary>
/// ------------------------------------------------------------------------------------------------------
/// Namespace : MultipleFileUploadWebPart
///
/// Purpose   : To Create Webpart to programmatically upload MultipleFiles to Custom SharePoint List
///        
/// Change History
/// -------------------------------------------------------------------------------------------------------
/// Date            Edit            Author            Comment             
/// -------------+--------+-------------------------------------------------------------------------------
/// 12-July-2007    [100]          Saravanan_Gajendran     Create Webpart
/// -------------+--------+-------------------------------------------------------------------------------
///</summary>
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Data;
using System.IO;
using System.Text;
using System.Web.SessionState;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace MultipleUploadWebpart
{
     [Guid("2115a405-ff46-4040-8370-6e4fcb7b9194")]
     public class MultipleUploadWebpart : System.Web.UI.WebControls.WebParts.WebPart
     {
          #region Variables
          private HtmlInputFile inputFile;
          private Button btnUpload;
          private Label lblMessage;
          private GridView dgdUpload;
          private string fileName = "";
          private Button btnSubmit;
          private HyperLinkField hlnkFileName;        
          private BoundField bndFileSize;
          private BoundField bndFileKb;
          private ButtonColumn btnclmDelete;
          private CommandField cmdDelete;
          private double length;
          byte[] contents;
          DataTable dt;//datatable use for multiple file upload
          DataRow dr;//datarow use for multiple file upload
          DataColumn dc;//datacolumn use for multiple file upload
          double count = 0;//count of file size
          #endregion
          #region Create Child Control
          protected override void CreateChildControls()
          {
               #region inputfile
               this.inputFile = new HtmlInputFile();
               this.inputFile.ID = "_fileUpload";
               #endregion           
               #region message label
               this.lblMessage = new Label();
               this.lblMessage.ID = "_lblMessage";
               this.lblMessage.Text = "";
               #endregion
   
               #region
  Button
               this.btnUpload = new Button();
               this.btnUpload.ID = "_btnUploadUpload";
               this.btnUpload.Text = "Upload";
               this.btnUpload.Click += new EventHandler(btnUploadUploadClick);
               this.btnSubmit = new Button();
               this.btnSubmit.ID = "_btnSubmit";
               this.btnSubmit.Text = "Submit";
               this.btnSubmit.Click += new EventHandler(btnSubmit_Click);
               #endregion
               #region GridView
               this.dgdUpload = new GridView();
               this.hlnkFileName = new HyperLinkField();
               this.hlnkFileName.DataTextField = "FileName";
               this.hlnkFileName.DataNavigateUrlFormatString = "FilePath";
               this.hlnkFileName.HeaderText = "FileName";
               this.bndFileSize = new BoundField();
               this.bndFileSize.HeaderText = "FileSize";
               this.bndFileSize.DataField = "FileSize";
               this.bndFileKb = new BoundField();
               this.bndFileKb.HeaderText = "";
               this.bndFileKb.DataField = "KB";
               this.cmdDelete = new CommandField();
               this.cmdDelete.HeaderText = "Delete";
               this.cmdDelete.ButtonType = ButtonType.Link;
               this.cmdDelete.InsertImageUrl = "delete.gif";
               this.cmdDelete.DeleteText = "Delete";
               this.cmdDelete.ShowDeleteButton = true;
               this.dgdUpload.ID = "_dgdFileUpload";
               this.dgdUpload.Columns.Add(hlnkFileName);
               this.dgdUpload.Columns.Add(bndFileSize);
               this.dgdUpload.Columns.Add(bndFileKb);
               this.dgdUpload.Columns.Add(cmdDelete);
               this.dgdUpload.AutoGenerateColumns = false;          
               this.dgdUpload.RowDeleting += new GridViewDeleteEventHandler
               
(dgdUpload_RowDeleting);
               #endregion
               #region Add Controls
               this.Controls.Add(dgdUpload);
               this.Controls.Add(inputFile);
               this.Controls.Add(lblMessage);
               this.Controls.Add(btnUpload);
               this.Controls.Add(btnSubmit);
               base.CreateChildControls();
               #endregion
          }
          #endregion
          #region RowDeleting
          private void dgdUpload_RowDeleting(object sender, GridViewDeleteEventArgs e)
          {
               int recordToDelete= e.RowIndex;
               dt = (DataTable)Page.Session["Files"];
               int cn = dt.Rows.Count;
               dt.Rows.RemoveAt(recordToDelete);
               dt.AcceptChanges();
               Page.Session["Files"] = dt;
               this.dgdUpload.DataSource = dt
               this.dgdUpload.DataBind();
           }
           #endregion
           #region OnLoad
           protected override void OnLoad(EventArgs e)
           {
                base.OnLoad(e);
           }
           #endregion
           #region File in SharePoint List
           private void btnSubmit_Click(object sender, EventArgs e)
           {
                SPWeb site = SPContext.Current.Web;
                SPList list = site.Lists["FileList"];
                SPListItem myNewItem ;          
                dt = (DataTable)Page.Session["Files"];
                int _dtcnt = dt.Rows.Count;
                string strDate="";
                foreach (DataRow dr in dt.Rows)
            {
                 strDate = System.DateTime.Now.Date.TimeOfDay.ToString();
                 myNewItem = list.Items.Add();
                 fileName = dr["Filename"].ToString();              
                 string strFilepath= dr["FilePath"].ToString()
                 StreamReader sr = new StreamReader(strFilepath);
                 Stream fStream=sr.BaseStream ;               
                 contents = new byte[fStream.Length];
                 fStream.Read(contents, 0, (int)fStream.Length);
                 fStream.Close();
                 myNewItem["Filename"] = dr["Filename"].ToString();
                 myNewItem["FileSize"] = dr["FileSize"].ToString();
                 myNewItem["Filedate"] = strDate;
                 myNewItem.Attachments.Add(fileName, contents);
                 myNewItem.Update();
                 System.IO.File.Delete(strFilepath);
             }
             lblMessage.Text = "Sucessfully Submited";
             }
             #endregion
             #region Upload File Add in List
             protected void btnUploadUploadClick(object sender, EventArgs e)
             {
                  fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
                  if (fileName != "")
             {
                  string _fileTime = DateTime.Now.ToFileTime().ToString();
                  string _fileorgPath =  System.IO.Path.GetFullPath
                  (inputFile.PostedFile.FileName);
                  string _newfilePath = _fileTime + "~" + fileName;
                  length = (inputFile.PostedFile.InputStream.Length) / 1024;
                  string tempFolder = Environment.GetEnvironmentVariable("TEMP");
                  string _filepath = tempFolder + _newfilePath;               
                  inputFile.PostedFile.SaveAs(_filepath);
                  AddRow(fileName, _filepath, length);
                  lblMessage.Text = "Successfully Added in List";
             }
             else
  
           {
                  lblMessage.Text="Select a File";
                  return;
             }
        }
        #endregion
        #region Render
        protected override void Render(HtmlTextWriter writer)
        {
             // TODO: add custom rendering code here.
             EnsureChildControls();
             this.inputFile.RenderControl(writer);
             this.btnUpload.RenderControl(writer);
             this.lblMessage.RenderControl(writer);
             this.dgdUpload.RenderControl(writer);
             this.btnSubmit.RenderControl(writer);
        }
        #endregion
        #region AddMoreRows for file upload
        private void AddMoreColumns()
        {
             dt = new DataTable("Files");
             dc = new DataColumn("FileName"Type.GetType("System.String"));
             dt.Columns.Add(dc);
             dc = new DataColumn("FilePath"Type.GetType("System.String"));
             dt.Columns.Add(dc);
             dc = new DataColumn("FileSize"Type.GetType("System.String"));
             dt.Columns.Add(dc);
             dc = new DataColumn("KB"Type.GetType("System.String"));
             dt.Columns.Add(dc);
             Page.Session["Files"] = dt;
        }
        #endregion
        #region AddRow for file upload
        private void AddRow(string file, string path, double length)
        {
             dt = (DataTable)Page.Session["Files"];
             if (dt == null)
            {
                 AddMoreColumns();
            }
            dr = dt.NewRow();
            dr["FileName"] = file;
            dr["FilePath"] = path;          
            dr["FileSize"] = Convert.ToString(length);
            dr["KB"] = "KB";         
            dt.Rows.Add(dr);
            Page.Session["Files"] = dt;
            this.dgdUpload.DataSource = dt;
            this.dgdUpload.DataBind();//bind in grid
       }
       #endregion
   }
}

Deploy File Upload Web part in the share point server
  1. Right click solution file then select properties. 
  2. Select Debug Start browser with URL selects your respective SharePoint Site.

  3. Select Signing option.

  4. Ensure the strong name key and sign the assembly check box.
  5. Right Click properties select Deploy.

  6. It is automatically deployed the web part in respective site.
  7. Deploy will take care of .Stop IIS, Buliding solution, Restarting Solution, Creating GAC, Restarting IIS like that.

  8. Multiple Upload Webpart is new one.
  9. New MultipleUploadWebpart Web Part.

Events
1. Browse Button 
It is used to browse and select the particular file.

2. Upload Button
It is used to upload file to the windows temp folder then list the files.
3. Submit Button
It is used to store all files in share point custom list.


All the files are listed
Delete
using this option you need to delete the file in this list.Whenever you give the submit only it will go to SharePoint list.



All the files are uploading in respective share point custom list.