Search This Blog

Friday, November 20, 2015

How to deploy and retract Sharepoint solutions programmatically

using Microsoft.SharePoint.Administration;
using System.Collections.ObjectModel;

Deploy

 try
 {
     SPSolution spSolution = SPFarm.Local.Solutions.Add(wspOutputFile);
     Collection<SPWebApplication> selectedWebApps = new Collection<SPWebApplication>();
     SPWebApplication spWebApp = SPWebApplication.Lookup(new Uri("http://localhost"));
     selectedWebApps.Add(spWebApp);
     spSolution.DeployLocal(true, true);
 }
 catch (Exception ex)
 {
     throw ex;
 }


Retract

 try
 {
     SPSolution spSolution = SPFarm.Local.Solutions[wspName];
     spSolution.RetractLocal();
     SPFarm.Local.Solutions.Remove(wspName);
  }
  catch (Exception ex)
 {
     throw ex;
 }

Number Validation Using Javascript


<script language="javascript">      
function isNumberKey(evt)      
{
  var charCode = (evt.which) ? evt.which : event.keyCode        
  if (charCode > 31 && (charCode < 48 || charCode > 57))
  {
   alert("Enter Only Numbers");            
   return false;
  }          
   return true;      
}        
</script >  

 <asp:Button ID="btnSubmit" Text="Submit" onkeypress="return isNumberKey(event)" runat="server" OnClick="Submit_Onclick" />

How to get the current username programmatically in share point

HttpContext.Current.User.Identity.Name

How to close Modal Dialog in sharepoint Programmatically

private void ClosePopUpDialog()
{
  try
  {
    HttpContext context = HttpContext.Current;
    string strSelUser = string.Empty;
    if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
    {
     context.Response.Write("<script   type=\"text/javascript\">window.frameElement.commonModalDialogClose(0, 'Close');</script>");
     context.Response.Flush();
     context.Response.End();
     this.Page.Response.End();
    }
    else
    {
      Response.Redirect(SPContext.Current.Web.Url);
    }
  }
  catch(Exception ex)
  {
     throw ex;
    }
}

How to Set DropDownList zero index with custom value programatically

dropdownId.Items.Insert(0, "--Select--");
dropdownId.SelectedIndex = dropdownId.Items.IndexOf(dropdownId.Items.FindByText("--Select--"));

SharePoint Modal Dialog

How to use SharePoint Modal Dialog i.e. SPModalDialog

Here are some of the common functions related with this

To open a dialog use the below function in javascript on the html part of the page

function ShowModalDialog(url, title)
 {
        var options = {
             url: url,
             width: 700,
             height: 500,
             title: title,
            dialogReturnValueCallback: DialogCallback
        };
        
        SP.UI.ModalDialog.showModalDialog(options);

 }

Here options are used to set the properties of the dialog. Some more properties are  showClose, allowmaximize etc.

Most imaportant thing is the "dialogReturnValueCallback" this property is used to get the dialog return value when the dialog is closed.

I called this function from code behind and setting the url and title described below:

string url = SPContext.Current.Web.Url + "/SitePages/NewForm.aspx?PID=" + tocid; lnknewitem.NavigateUrl = "javascript: NewItemDialog('" + url + "','New Item');";

IN above code snippet i used a link button and set its navigate url programmatically and called the Dialog open function.

And the DialogCallback function is


 function DialogCallback(dialogResult, returnValue) 
 {
       if (returnValue == "1")
      {
            var meesageId = SP.UI.Notify.addNotification("Loading", false);
            SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
       }
  }

If you want to return value from the modal dialog while closing then use the below function on the modal dialog close function

SP.UI.ModalDialog.commonModalDialogClose(dialogResult, returnVal);

ie.  SP.UI.ModalDialog.commonModalDialogClose(1, "1");

Now when dialogcallback function will fire it will check the return value if it is "1" then it will add notification and refresh the parent page.

you can pass dialogResult, returnVal according to your choice and you can get these values on the parent form using DialogCallback function as described above

To simply close the dialog use the below function on client click event of the button

    function CloseForm() 
   {
        window.frameElement.cancelPopUp();
        return false;
    }

If you want to open the new custom page in modal dialog and ribbon is displayed on the modal dialog then use this css trick to hide ribbon

 #s4-ribbonrow
 {
      display: none;
 }

Read and Get Values from Excel File using PowerShell Script


What do I use to read data or values from excel file?  And what if I want to read every row on multiple columns? Example data is like this..


                                       NAME         AGE           CITY
                                       Akash           25             Bangalore
                                       Adarsh          26            Coimbatore
                                       Rafiq             57            Chennai


First we declare the path where the excel file is stored.  Also, declare the sheet name.

$file = "C:\Documents\FolderName\ExcelFileName.xls"
$sheetName = "Sheet1"

After that, create an instance using the COM Object Excel Application to open the excel file.

$objExcel = New-Object -ComObject Excel.Application
$workbook = $objExcel.Workbooks.Open($file)
$sheet = $workbook.Worksheets.Item($sheetName)
$objExcel.Visible=$false

We will also need the number of Rows that has values. We will need these to loop and check every value on every column.

$rowMax = ($sheet.UsedRange.Rows).count

And now declare the starting position for each column

$rowName,$colName = 1,1
$rowAge,$colAge = 1,2
$rowCity,$colCity = 1,3

We will now loop through each row and store each variable that you can use for anything you want (i.e. e-mail body variables)

for ($i=1; $i -le $rowMax-1; $i++)
{
$name = $sheet.Cells.Item($rowName+$i,$colName).text
$age = $sheet.Cells.Item($rowAge+$i,$colAge).text
$city = $sheet.Cells.Item($rowCity+$i,$colCity).text

}

For the last line of code, we will close the excel file after opening and reading it. If we don’t close it, it will be locked for editing.

$objExcel.quit()

You can check the output by using Write-Host. For the full code below:

#Declare the file path and sheet name
$file = "C:\Users\kfeb\Documents\Textfile\ExcelFile.xlsx"
$sheetName = "Sheet1"
#Create an instance of Excel.Application and Open Excel file
$objExcel = New-Object -ComObject Excel.Application
$workbook = $objExcel.Workbooks.Open($file)
$sheet = $workbook.Worksheets.Item($sheetName)
$objExcel.Visible=$false
#Count max row
$rowMax = ($sheet.UsedRange.Rows).count
#Declare the starting positions
$rowName,$colName = 1,1
$rowAge,$colAge = 1,2
$rowCity,$colCity = 1,3
#loop to get values and store it
for ($i=1; $i -le $rowMax-1; $i++)
{
$name = $sheet.Cells.Item($rowName+$i,$colName).text
$age = $sheet.Cells.Item($rowAge+$i,$colAge).text
$city = $sheet.Cells.Item($rowCity+$i,$colCity).text

Write-Host ("My Name is: "+$name)
Write-Host ("My Age is: "+$age)
Write-Host ("I live in: "+$city)
}
#close excel file
$objExcel.quit()

How to add a value to a lookup field in sharepoint 2013?

using (SPSite site = SPContext.Current.Site)
{
    SPFieldLookupValue value = new SPFieldLookupValue();
    site.AllowUnsafeUpdates = true;
    using (SPWeb web = site.OpenWeb())
   {
       web.AllowUnsafeUpdates = true;
       SPList list = web.Lists["ListName"];
       item = list.Items.Add();
       string fieldValue = "Enter the ID" + ";#" + "Enter the Name";
       value = new SPFieldLookupValue(fieldValue);
       item["Column Name"] = value;
       item.Update();
  }
}

Wednesday, November 18, 2015

How to Modify the SearchServiceApplication MaxRowLimit using Powershell Script

Decompiling the SearchServiceApplication we see that MaxRowLimit on that application defaults to 500 and that value is passed to the query.

The SearchServiceApplication MaxRowLimit can be modified as follows:

PS> $ssa = Get-SPEnterpriseSearchServiceApplication
PS> $ssa.MaxRowLimit = 1000
PS> $ssa.Update()
PS> iisreset

Retrieve value of a Sharepoint Choice Field in c# Visual Studio 2013

At this post i will elaborate how to create choice field and multi choice field  in SharePoint list then i go to visual studio to create new visual web part to retrieve it’s value to dropdownlist control or radiobuttonlist control  or checkboxlist control .

at our example we will use dropdownlist control .

create function called bind() and call it at page load event  of visual web part

code:

private void bind()
{
SPWeb site = SPContext.Current.Web;
SPList list = site.Lists["ListName"];
SPFieldChoice myChoicesfield = (SPFieldChoice)list.Fields["FieldName"];
for (int i = 0; i < myChoicesfield.Choices.Count; i++)
{
DropDownListName.Items.Add(myChoicesfield.Choices[i].ToString());
}
}

To create a checkboxlist from a multi choice field:

//create a check box list

  private void bind()
 {
     SPWeb site = SPContext.Current.Web;
     SPList list = site.Lists["ListName"];
     SPFieldMultiChoice choices = (SPFieldMultiChoice)list.Fields[FieldName];
     foreach (string str in choices.Choices)
     {
         cblCheckboxList.Items.Add(new ListItem(str, str));
     }
 }

Build Your Own User Interface Components Using The Taxonomy Controls

If you would like to use the built-in taxonomy controls of SharePoint 2010 your best choice might be to go with the TaxonomyWebTaggingControl. This is the class the field control of the TaxonomyField, TaxonomyFieldControl itself uses internally to render its content, although it does not expose the full capability of the control.

In this post I will show you some features of the TaxonomyWebTaggingControl using it in a visual web part project.

First, let’s see how to use it declaratively. Be sure Microsoft.SharePoint.Taxonomy is registered in your user control (.ASCX) file:

<%@ Register Tagprefix="Taxonomy" Namespace="Microsoft.SharePoint.Taxonomy" Assembly="Microsoft.SharePoint.Taxonomy, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

Having this registration, you can add TaxonomyWebTaggingControl using the following declaration:

<Taxonomy:TaxonomyWebTaggingControl AllowFillIn="true" IsMulti="true" SSPList="{29ff8c4f-37a6-4d42-8cef-f610f0a7c7e9}"  TermSetList="{a22cf1f5-427e-41d7-8af4-7aa4dc47197d}" AnchorId="{ec5ee636-f35c-43bd-92a0-56016a0a127c}" runat="server" />

This control instance allows multiple items and filling in values. The SSPList  attribute is to specify the Id of the term store(s) and the TermSetList attribute is to specify the Id of the term set(s). Note, that none of these two attributes are automatically suggested by IntelliSense or recognized by the compiler in Visual Studio 2010 beta 2, but they works as expected. You can specify multiple values in both of these attributes, separating them by semicolons (‘;’). It is a great way to combine multiple term sets even from multiple term stores. The AnchorId attribute sets the Id of the term that serves as the starting point of the term hierarchy used in the control. Only terms below the anchor will be suggested in the control.

Although it is not so hard to get these Ids using a little command line utility, specifying these settings by Guid values is not user friendly. So let’s switch to the coding approach, but before doing that, we add some additional content to the user control:

<Taxonomy:TaxonomyWebTaggingControl ID="TestTaxonomyControl" runat="server" />

<asp:Button ID="SendButton" runat="server" Text="Send"
    onclick="SendButton_Click" />
<br />
<br />
<asp:Label ID="MetaDataLabel" runat="server" Text=""></asp:Label>

Having this done, we can alter to the code behind of the user control to the following:


using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint;
using System.Drawing;

namespace VisualWebPartTest1.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SPContext context = SPContext.Current;
            SPSite site = context.Site;
            TaxonomySession session = new TaxonomySession(site);
            TermStore termStore = session.TermStores["MyTermStore"];
            Group group = termStore.Groups["MyGroup"];
            TermSet productsTermSet = group.TermSets["Products"];
            TermSet languagesTermSet = group.TermSets["Languages"];

            TestTaxonomyControl.SspId.Add(termStore.Id);
            TestTaxonomyControl.TermSetId.Add(productsTermSet.Id);
            TestTaxonomyControl.TermSetId.Add(languagesTermSet.Id);
            TestTaxonomyControl.AllowFillIn = true;
            TestTaxonomyControl.IsMulti = true;
        }

        protected void SendButton_Click(object sender, EventArgs e)
        {
            String validationMessage;
            bool valid = TestTaxonomyControl.Validate(out validationMessage);

            if (valid)
            {
                MetaDataLabel.Text = String.Empty;
                MetaDataLabel.ForeColor = Color.Black;
                TaxonomyFieldValueCollection values = new TaxonomyFieldValueCollection(String.Empty);
                values.PopulateFromLabelGuidPairs(TestTaxonomyControl.Text);

                foreach (TaxonomyFieldValue value in values)
                {
                    MetaDataLabel.Text += value.WssId + " / " + value.TermGuid + " / " + value.Label + "<br />";
                }
            }
            else
            {
                MetaDataLabel.ForeColor = Color.Red;
                MetaDataLabel.Text = validationMessage;
            }
        }
    }

}

As you can see we use the SspId and TermSetId properties of the TaxonomyWebTaggingControl control to specify the term store and term sets. Both of this properties are of type List<Guid>. We specify two term sets for this control, one for the Languages and another one for Products.










Just a thought regarding the figure above. It seems that pressing Tab button to autocomplete the suggested value only works in the case of the first tag in taxonomy controls. I hope it is only a bug in beta 2 and will be corrected in the final version.

We handle the Click event of the SendButton control to validate the values specified in our taxonomy control. We can use the Validate method of the TaxonomyWebTaggingControl control for that. This method returns with a boolean value that represents the result of the validation, and an out String parameter that is the validation error message.


If the validation fails we display the error message. Note that the text box is empty now, since we don’t set its value on post back.








BTW, if you want the control to be able to add new terms:

There should be only a single term set attached to the control.
The term set must be open.
You should set the IsAddTerms property to true.

On success we display the selection values. The Text property of the TaxonomyWebTaggingControl control contains the label – Id pairs of the selected terms. To convert it to TaxonomyFieldValueCollection, we should use the PopulateFromLabelGuidPairs method.











Note, that the WssId is –1 for both values, since in this case the control is not bound to a site, not like in the case of a TaxonomyField (see my former post about the WssId).

Source: https://pholpar.wordpress.com/2010/02/15/build-your-own-user-interface-components-using-the-taxonomy-controls/

Add update and delete list items programmatically in sharepoint (Server Object Model) :

ADD UPDATE &DELETE SHAREPOINT LIST ITEM PROGRAMMATICALLY USING C# (SERVER OBJECT MODEL) :


First insert the following name space 

                 using Microsoft.SharePoint;

For Adding list item:

 protected void Page_Load(object sender, EventArgs e)
        {
          SPSite site = SPContext.Current.Site;
          SPWeb web = SPContext.Current.Web;
          SPList listobj = web.Lists["ListName"];

           //add new item
            SPListItem litem = listobj.AddItem();
            litem["ColumnName1"] = "one";
            litem["ColumnName2"] =  "two";
            litem["ColumnName3"] =  "three";
            web.AllowUnsafeUpdates = true;
            litem.Update();
        }

For Updating Listitem: 

 protected void Page_Load(object sender, EventArgs e)
        {
          SPSite site = SPContext.Current.Site;
          SPWeb web = SPContext.Current.Web;
          SPList listobj = web.Lists["ListName"];
          SPQuery qry=new SPQuery();
          qry.Query="<view/>";
          SPListItemCollection _coll=listobj.GetItems(qry);

            //update code 
            foreach (SPListItem item in _coll)
            {
                if (Convert.ToString(item["ColumnName"])=="one")
                {
                    int id = Convert.ToInt32(item["ID"]);
                    SPListItem litem = listobj.GetItemById(id);
                    litem["ColumnName"] = 10;
                    litem["ColumnName"] = 20;
                    web.AllowUnsafeUpdates = true
                    litem.Update();                   
                }
               
            }
        }

For Deleting List item: 

 protected void Page_Load(object sender, EventArgs e)
        {
          SPSite site = SPContext.Current.Site;
          SPWeb web = SPContext.Current.Web;
          SPList listobj = web.Lists["ListName"];
            SPQuery qry=new SPQuery();
            qry.Query="<view/>";
            SPListItemCollection _coll=listobj.GetItems(qry);

           

            foreach (SPListItem item in _coll)
            {
                if (Convert.ToString(item["ColumnName"])=="one")
                {
                    int id = Convert.ToInt32(item["ID"]);
                  //Delete code 
                    SPListItem litem = listobj.GetItemById(id);
                    web.AllowUnsafeUpdates = true
                    litem.Delete();   
                }
            }
        }
   

Programmatically get multi lookup values from SharePoint 2013 list item

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Microsoft.SharePoint;

namespace MultiLookup
{
    class Program
    {
        static void Main(string[] args)
        {          
            using (SPSite site = new SPSite("http://serverName/sites/projects"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("Test");
                    SPListItem item = list.Items[0];
                    SPFieldLookupValueCollection values = new SPFieldLookupValueCollection(item["MultiLookup"].ToString());
                    foreach (SPFieldLookupValue value in values)
                    {
                        Console.WriteLine(value.LookupValue);
                    }
                    Console.ReadLine();
                }
            }
        }
    }
}  

Monday, November 16, 2015

How to clear the querystring From Url

// Get the NameValueCollection 
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic); 
// make collection editable 
isreadonly.SetValue(this.Request.QueryString, false, null); 
// remove 
this.Request.QueryString.Remove("YourQueryStringParameter"); 

Don't forget to add following Using Statement 

using System.Collections; 
using System.Reflection;