Tuesday 18 June 2013

SharePoint 2013 Apps: Accessing Data in the Host Web in a SharePoint-Hosted App

How to get the hosting  web title in sharepoint app ?


refer here

var context;
var web;
var user;
function sharePointReady() {
context = new SP.ClientContext.get_current();
web = context.get_web();
context.load(web,"Title");
context.executeQueryAsync(onGetWebSuccess, onGetWebFail)
}
function onGetWebSuccess() {
$('#message').text('The title of this App is ' + web.get_title());
}
function onGetWebFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
This code results in the following output:
This is the easy scenario. If I’m developing a SharePoint-hosted app, then I can easily get to the App Web through the clientcontext.get_current( )method which returns the current context that the user is running in.
However, if you want to access information in the Host Web, a different approach is required. You might think that you can just load the context of the app using SP.ClientContext and passing the string of the Host Web like so…
var web;
var hostcontext;
function sharePointReady() {
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
hostcontext = new SP.ClientContext(hostUrl);
web = hostcontext.get_web();
hostcontext.load(web, "Title");
hostcontext.executeQueryAsync(onGetWebSuccess, onGetWebFail);
}
function onGetWebSuccess() {
$('#message').text("The title of the host web of this app is " + web.get_title());
}
function onGetWebFail(sender, args) {
alert('Failed to get lists. Error:' + args.get_message());
}
//this is just the sample function that's in all the MS samples
function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
 …But nope. As soon as you try to execute a query against anything in that context, this is what you get:

So what is the right way? You need to use an object called the AppSiteContext. If you swap out the sharePointReady function from the previous example with this…
function sharePointReady() {
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
currentcontext = new SP.ClientContext.get_current();
hostcontext = new SP.AppContextSite(currentcontext, hostUrl);
web = hostcontext.get_web();
currentcontext.load(web, "Title");
currentcontext.executeQueryAsync(onGetWebSuccess, onGetWebFail);
}
Additionally, you must give the app read access to the Host Site Collection through the App Manifest.
Once you configure this, then you get the output we’re expecting:
The AppContextSite uses the current context to load the Host Web Context. In the background, the SharePoint client object model is brokering all the tokens and fun Oauth security for you so that the App can act on your behalf when it accesses the Host Web.
For those of you who are REST purists, an example of doing the same thing is on the this Technet article [http://msdn.microsoft.com/en-us/library/fp179927.aspx]. But in my app, I’m using the Client Object Model and there really weren’t any examples out there that showed how to do this using CSOM.

Monday 25 March 2013

Error occurred in deployment step 'Activate Features' Attempted to perform an unauthorized operation.


Having this error was so annoying since I tried to google it but no step-by-step instructions how to fix it. Anyway, I had this error while trying to deploy thevisual web part for Sharepoint 2010 within VS 2010. There are at least 2 reasons why you’re getting this error:
1.    Bear in mind that you can only deploy the solution of the visual web part at a farm level. You will get this error while trying to deploy the solution at a site level. This is related to the correct site url you enter while creating the project. It is recommended that you always click on “Validate”.
2.    It is so obvious from the message that your windows login does not have the right “site collection” permission.
What I’m going to talk about and step through is point #2 (not having the right permission). Reason being is whichever the windows login that you’re using to deploy the solution, Sharepoint will use it to check if you’re authorised to deploy any solutions or not (not just deploying actually).
Step 1
Fire up the Sharepoint 2010 Central Administration.
Step 2
Go to Application Management –> Change site collection administrations
Step 3
Select the correct site collection and type your windows account as the secondary site collection administrator
Now try to deploy the solution again and it should work! 


Number validation using javascript


<HTML>
   <HEAD>
   <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>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
   </BODY>
</HTML>

Use of caml query with datetime


 string[] dates;
      try
      {
          SPSecurity.RunWithElevatedPrivileges(delegate
          {

              using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))
              {
                  using (SPWeb oWeb = oSite.OpenWeb())
                  {
                     
                      SPList list = SPContext.Current.Web.Lists["General Tasks"];
                      CustomListViewByQuery.List = list;
                      string query = null;
                      SPQuery qry = new SPQuery(list.DefaultView);
                      int iCnt = 0;
                      // Prepare start and end dates
                       DateTime startDate = new DateTime();
                       DateTime endDate = new DateTime();
                       if (ddlReports.SelectedValue == "Monthly")
                       {                        

                           dates = this.GetRange(FrequencyType.Monthly, DateTime.Today);
                           startDate = Convert.ToDateTime(dates[0]);
                           endDate= Convert.ToDateTime(dates[1]);
                           //startDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
                           //endDate = startDate.AddMonths(1).AddMinutes(-1);
                       }
                     
                       else if (ddlReports.SelectedValue == "Weekly")
                       {
                           dates = this.GetRange(FrequencyType.Weekly, DateTime.Today);
                           startDate = Convert.ToDateTime(dates[0]);
                           endDate = Convert.ToDateTime(dates[1]);
                       }
                   
                      Response.Write(startDate.ToString());
                       Response.Write(endDate.ToString());

                      // Format dates
                      string startDateFx = startDate.ToString("yyyy-MM-ddTHH:mm:ssZ");
                      string endDatFx = endDate.ToString("yyyy-MM-ddTHH:mm:ssZ");
                       Response.Write(startDateFx);
                       Response.Write(endDatFx);

                      try
                      {
//                         query = @" <Where>    
//         <Eq>
//            <FieldRef Name='Priority' />
//            <Value Type='Choice'>(1) High</Value>
//         </Eq>            
//   </Where>";
                          query = @"<Where><And><Leq><FieldRef Name='DueDate' /><Value Type='DateTime'   IncludeTimeValue='FALSE'>"+endDatFx+"</Value></Leq><Geq><FieldRef Name='DueDate' /><Value Type='DateTime'  IncludeTimeValue='FALSE'>"+startDateFx+"</Value> </Geq></And></Where>";

                          //query = @"<View>" +
                          //              "<Query>" +
                          //                  "<Where>" +
                          //                  "<And>"+
                          //                       "<Eq>"+
                          //                          "<FieldRef Name='Priority' />"+
                          //                          "<Value Type='Choice'>(1) High</Value>"+
                          //                       "</Eq>"+
                          //                       "<Eq>"+
                          //                              "<And>" +
                          //                                  "<Geq>" +
                          //                                      "<FieldRef Name='DueDate'/>" +
                          //                                      "<Value Type='DateTime' IncludeTimeValue='FALSE'>" + startDateFx + "</Value>" +
                          //                                  "</Geq>" +
                          //                                  "<Leq>" +
                          //                                      "<FieldRef Name='DueDate'/>" +
                          //                                      "<Value Type='DateTime' IncludeTimeValue='FALSE'>" + endDatFx + "</Value>" +
                          //                                  "</Leq>" +
                          //                              "</And>" +
                          //                      "</Eq>"+
                          //                  "</And>"+                                                      
                          //                  "</Where>" +
                          //              "</Query>" +
                          //       "</View>";
                          qry.Query = query;
                          CustomListViewByQuery.Query = qry;
                          CustomListViewByQuery.List = list;
                          CustomListViewByQuery.DisableFilter = true;
                          CustomListViewByQuery.DisableSort = true;
                          iCnt++;

                          if (iCnt > 0)
                          {

                              CustomListViewByQuery.Visible = true;

                          }
                      }
                      catch (Exception ex)
                      {
                      }
                  }
              }
          });
      }
      catch { }
   

Check browser in sharepoint pages


function BrowserCheck()
{

   if (navigator.appName == "Microsoft Internet Explorer") {        
    }
    else {      
        alert("Please login to Microsoft Internet Explorer for submitting PM's Weekly Status Sheet. You will be redirected to a blank page");
        window.location = "../../Redirect.aspx";
        //var date_WeekStartDate_1=document.getElementById('<%=WeekStartDate_1.Controls[0].ClientID%>');
//var date_WeekEndDate_1=document.getElementById('<%=WeekEndDate_1.Controls[0].ClientID%>');

        return false;
    }
}

Sharepoint multiline textbox validation


Sharepoint multiline textbox validation


function PreSaveAction()    {

var checkItem = $('#<%=lblTrueFalse.ClientID%>').val();  
         if (checkItem == "true")
         {
var value1=GetV3TextField('Approval Comments');
var Approvalvalue="";
if(navigator.appName == "Microsoft Internet Explorer")
{
Approvalvalue=$(value1).closest("span").find("iframe[Title='Rich Text Editor']").contents().find("body").text();

}
else
{
Approvalvalue=$(value1).val();
}
//var Approvalvalue=$(value1).val();

if(Approvalvalue =='' || Approvalvalue ==null)
{
alert('Please add some comments');
return false;
}
else
{

return true;
}

}
}

Export to pdf and export to excel in sharepoint webaparts using itextsharp


using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

using System.Collections;
using System.Drawing.Imaging;
using System.Web;
using System.Text;  


protected void btnExportToPdf_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = (DataTable)ViewState["GeneralTask"];
                BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
                iTextSharp.text.Font font = new iTextSharp.text.Font(bfTimes, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                //Create a dummy GridView CssClass="grdStyle"
                GridView GridView1 = new GridView();
                GridView1.AllowPaging = false;
                GridView1.DataSource = dt;
                GridView1.DataBind();
                GridView1.CssClass = "grdStyle";


                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=ActivityExport.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                using (StringWriter sw = new StringWriter())
                {
                    using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                    {
                        GridView1.RenderControl(hw);
                        StringReader sr = new StringReader(sw.ToString());
                        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                        pdfDoc.SetPageSize(PageSize.A4.Rotate());
                        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                        pdfDoc.Open();
                        htmlparser.Parse(sr);
                        pdfDoc.Close();
                        Response.Write(pdfDoc);
                        Response.End();
                    }
                }

            }
            catch { }
        }

        protected void btnExportToExcel_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = (DataTable)ViewState["GeneralTask"];
                GridView GridView1 = new GridView();
                GridView1.AllowPaging = false;
                GridView1.DataSource = dt;
                GridView1.DataBind();

                Response.Buffer = true;

                Response.AddHeader("content-disposition", string.Format("attachment;filename=ActivityReport.xls"));
                Response.Charset = "";

                Response.Cache.SetCacheability(HttpCacheability.NoCache);

                Response.ContentType = "application/vnd.xls";
                using (StringWriter stringWrite = new System.IO.StringWriter())
                {
                    using (HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite))
                    {
                        GridView1.RenderControl(htmlWrite);
                        Response.Write(stringWrite.ToString());

                        Response.Flush();
                        Response.Clear();
                        Response.End();
                    }
                }

            }
            catch { }
        }

Find the dll's here :---Itextsharp 5.3.0.0

Dropdown Unchanged event in share point for lookup exceeding value 20



http://social.technet.microsoft.com/Forums/en/sharepointadmin/thread/7003ef85-38bf-450b-91b4-4725733c5384


function getField(fieldType,fieldTitle) {
    var docTags = document.getElementsByTagName(fieldType);
    for (var i=0; i < docTags.length; i++) {
        if (docTags[i].title == fieldTitle) {
            return docTags[i]
        }
    }
}

2. I use the following lines of code to determine if the control is a lookup with < 19 options or one with > 19 options and accordingly set my function to be called either on "onchange" event or on "onblur" event

if(getField('select','Role') != null){   //incase of lookup having < 19 options
 if(getField('select','Role').type == 'select-one'){
  getField('select','Role').onchange = function() {syncDropDowns()};
 }
}else if(getField('input','Role') != null){  //incase of lookup having > 19 options
 if(getField('input','Role').type == 'text'){
  getField('input','Role').onblur = function() {syncDropDowns()};
 }
}




function getField(fieldType,fieldTitle) {
    var docTags = document.getElementsByTagName(fieldType);
    for (var i=0; i < docTags.length; i++) {
        if (docTags[i].title == fieldTitle) {
            return docTags[i]
        }
    }
}

2. I use the following lines of code to determine if the control is a lookup with < 19 options or one with > 19 options and accordingly set my function to be called either on "onchange" event or on "onblur" event

if(getField('select','Role') != null){   //incase of lookup having < 19 options
 if(getField('select','Role').type == 'select-one'){
  getField('select','Role').onchange = function() {syncDropDowns()};
 }
}else if(getField('input','Role') != null){  //incase of lookup having > 19 options
 if(getField('input','Role').type == 'text'){
  getField('input','Role').onblur = function() {syncDropDowns()};
 }
}


or simple call the spservices j query and use following method to convert the input field to select.

$().SPServices.SPComplexToSimpleDropdown({
 columnName: "State"
});

Get Lookupvalue in client context using ecma script


<script language="ecmascript" type="text/ecmascript">

        var listItem;
        var list;
        var clientContext;

        function getLookUp() {
            this.clientContext = SP.ClientContext.get_current();
            if (this.clientContext != undefined && clientContext != null) {
                var webSite = clientContext.get_web();
                this.list = webSite.get_lists().getByTitle("Custom");
                this.listItem = list.getItemById(5);
                clientContext.load(this.listItem);
                this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
            }
        }

        function OnLoadSuccess(sender, args) {
            var lookup = this.listItem.get_item("LookupSingleValue");
            alert("Lookup Id: " + lookup.get_lookupId() + "\n Lookup Value: " + lookup.get_lookupValue());


        }

        function OnLoadFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    <input id="btnGetLookUp" onclick="getLookUp()" type="button" value="Get Look Up" />

Build dynamic query string in sharepoint


public string BuildQueryString()
    {
        string url = HttpContext.Current.Request.Url.AbsoluteUri;
        string[] separateURL = url.Split('?');

        NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString("");
        if (ddlLegalAdvisor.SelectedIndex > 0)
        {
            queryString["LegalAdvisor"] = ddlLegalAdvisor.SelectedValue;
        }
        if (ddlAreaOfLaw.SelectedIndex > 0)
        {
            queryString["Areaoflaw"] = ddlAreaOfLaw.SelectedValue;
        }
        if (ddlFundingStream.SelectedIndex > 0)
        {
            queryString["FundingStream"] = ddlFundingStream.SelectedValue;
        }
        if (ddlInterviewRoom.SelectedIndex > 0)
        {
            queryString["InterviewRoom"] = ddlInterviewRoom.SelectedValue;
        }
        url = separateURL[0] + "?" + Convert.ToString(queryString);
        return url;

    }

Change heading of share point sitepages


Add the below placeholder in sharepoint application pages to change the heading of the pages

<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
Test heading
</asp:Content>

How to Call Workflow from event Receiver in share point


 SPWorkflowAssociation associationTemplate = parentList.WorkflowAssociations.GetAssociationByName("Data Processing", new CultureInfo
                                                                                    (Convert.ToInt32(parentList.ParentWeb.RegionalSettings.LocaleId)));
                                       oSite.WorkflowManager.StartWorkflow(oSourceListItem, associationTemplate, String.Empty);

Programatically get User From Modified by Field


SPFieldUser userField = (SPFieldUser)oSourceListItem.Fields.GetField("Modified By");
                                                        SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(oSourceListItem["Modified By"].ToString());

use of share point date time field


<SharePoint:DateTimeControl ID="DateTimeControl1" runat="server" TabIndex="1" IsRequiredField="false"
                                                    CssClassDescription="ms-formvalidation" LocaleId="2057" DateOnly="true" />



 if (!dtQueryDate.IsDateEmpty)
                                        {
                                            itemToUpdate["Query_x0020_date"] = SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtQueryDate.SelectedDate);
                                        }

SharePoint Large File Upload Configuration

http://blogs.technet.com/b/sharepointcomic/archive/2010/02/14/sharepoint-large-file-upload-configuration.aspx

Programmatically close dialogue box in share point


private void CloseDlg()
        {
            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, 'cancelled');</script>");
                    //context.Response.Write("<script type=\"text/javascript\">window.frameElement.commitPopup();</script>");
                    //context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()</script>");
                    context.Response.Flush();
                    context.Response.End();
                    this.Page.Response.End();
                }
                else
                {
                    Response.Redirect(SPContext.Current.Web.Url);
                }
            }
            catch { }
        }

encode url sharepoint

SPHttpUtility.HtmlUrlAttributeEncode(url)

How to Fix lookup columns in SharePoint using powershell


Referred from : http://asharepointsolutions.blogspot.in/

How to Fix lookup columns in SharePoint
I have deployed some list templates and found that Lookups are got broken,
After googling, I found that here, that using PowerShell we can fix the Lookup:

//We can create PowerShell Function as follows:

Function Fix-LookupColumn ($webURL, $listName, $columnName, $lookupListName)
{
    #Get web, list and column objects
    $web = Get-SPWeb $webURL
    $list = $web.Lists[$listName]
    $column = $list.Fields[$columnName]
    $lookupList = $web.Lists[$lookupListName]
 
    #Change schema XML on the lookup column
    $column.SchemaXml = $column.SchemaXml.Replace($column.LookupWebId.ToString(), $web.ID.ToString())
    $column.SchemaXml = $column.SchemaXml.Replace($column.LookupList.ToString(), $lookupList.ID.ToString())
    $column.Update()
 
    #Write confirmation to console and dispose of web object
    write-host "Column" $column.Title "in list" $list.Title "updated to lookup list" $lookupList.Title "in site" $web.Url
    $web.Dispose()
}

By paasing parameters, we can execute the above function

Open SharePoint Powershell command prompt and execute above function
followed by this command to call the function for the particular list and column that you wish to fix:

Fix-LookupColumn -webURL <URL> -listName "<List name containing the lookup column>" -columnName "<Lookup column name>" -lookupListName "<List used by the lookup column>"

For example:

Fix-LookupColumn -webURL http://portal -listName "Vendor" -columnName "Company" -lookupListName "Company"

Where,
List Name :- Vendor
Lookup Column:- Company
Lookup List: Company

Absolute url of an item in sharepoint 2010


oList.Fields[SPBuiltInFieldId.FileRef].InternalName

 string folderUrl = Convert.ToString(item[SPBuiltInFieldId.FileRef]);

Programmatically remove duplicate values and blank spaces in dropdown


 public void RemoveDuplicateItems(DropDownList ddl)
        {
            for (int i = 0; i < ddl.Items.Count; i++)
            {
                ddl.SelectedIndex = i;
                string str = ddl.SelectedItem.ToString();
                for (int counter = i + 1; counter < ddl.Items.Count; counter++)
                {
                    ddl.SelectedIndex = counter;
                    string compareStr = ddl.SelectedItem.ToString();
                    if (str == compareStr)
                    {
                        ddl.Items.RemoveAt(counter);
                        counter = counter - 1;
                    }
                }
                if (str == "")
                {
                    ddl.Items.RemoveAt(i);
                    i--;
                }

            }
            ddl.SelectedIndex = 0;
        }

Set dropdown 1st index with default value programatically


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

Add days to sharepoint datetime fiels using javascript


var dateString1=$("input[title='Start Date']").attr('value');


 var arrStartDate = dateString1.split("/");
 var date=arrStartDate[1]+"/"+arrStartDate[0]+"/"+arrStartDate[2]

   var startDate = new Date(Date.parse(date));
    alert('start: ' + startDate);
    var expDate = startDate;
    expDate.setDate(startDate.getDate() + count);
    // alert('<br>expire: ' + expDate);

//Month will always return month-1 so add 1 to month
    var mm = expDate.getMonth()+1;
    var dd = expDate.getDate();
    var yyyy = expDate.getFullYear();
    var finaldate = dd + '/' + mm + '/' + yyyy;

  $("input[title='Due Date']").attr('value',finaldate);

Checkbox check changed event


<script>


 function handleEvents()
    {
        $("input[title$='Non PO Payments']").change(function(){
CheckNonPO();
});
    }


function CheckNonPO()
{
      if($("input[title$='Non PO Payments']").is(':checked'))
{
$("nobr:contains('Vendor')").parent('h3').parent('td').parent('tr').show();
$("h3.ms-standardheader:contains('PO Number')").closest("tr").show();

}
else
{
$("nobr:contains('Vendor')").parent('h3').parent('td').parent('tr').hide();

}


}
_spBodyOnLoadFunctionNames.push("handleEvents");
</script>

How to catch share-point multiselector events in share point


function clearMultiBox()
{
    var IdMPOuter = GetIDOfMultipickOuterControl("columnname");
$('#'+IdMPOuter).empty();


}
 //Multipicker event
function ReRenderSelectObjects()
{
   
    var oSelect = document.getElementsByTagName('select');
    var replaceExp = new RegExp(/SelectCandidate/);
    for(var x=0; x<oSelect.length; x++)
    {
        CleanOptionsText(oSelect[x]);                
        if(oSelect[x].id.indexOf('SelectCandidate') > 0)
        {
            var selectId = oSelect[x].id;
            var btnId = selectId.replace(replaceExp,'RemoveButton');
            var spMasterName = selectId.replace(replaceExp,'MultiLookupPicker_m');
         
                var eventHandler = function(aa){
                CustomRemoveItemEventHandler(this);
                //alert('hi');
                //clear multiselect items
                clearMultiBox();
                //load  multiselect items
                // myCustomFunctionName();
               
                };
            var objRemoveBtn = document.getElementById(btnId);
   if(objRemoveBtn){objRemoveBtn.onclick = eventHandler}
   var objSelected = document.getElementById(selectId.replace(replaceExp,'SelectResult'));
   
   if(objSelected){objSelected.ondblclick = eventHandler}
   eventHandler = null;
         }
   
     }
 }
function CleanOptionsText(selectObj)
{
    var removeExp = new RegExp(/(<([^>]+)>)/ig);              
    for(var y=0; y<selectObj.options.length; y++)
    {                                    
                    if ((selectObj.options[y].text.indexOf("<DIV") == 0) && (selectObj.options[y].text.indexOf("</DIV>") >= 0))
                    {
                                    selectObj.options[y].text = selectObj.options[y].text.replace(removeExp,"");
                    }
    }
}
function CustomRemoveItemEventHandler(callingObj)
{

if(callingObj.tagName == 'BUTTON')
{
               var replaceExp = new RegExp(/RemoveButton/);
               var spMasterObj = window[callingObj.id.replace(replaceExp,'MultiLookupPicker_m')];
               GipRemoveSelectedItems(spMasterObj);
               var oSelect = document.getElementById(callingObj.id.replace(replaceExp,'SelectCandidate'));
               CleanOptionsText(oSelect);
}
else if(callingObj.tagName == 'SELECT')
{
               var replaceExp = new RegExp(/SelectResult/);
               var spMasterObj = window[callingObj.id.replace(replaceExp,'MultiLookupPicker_m')];
               GipRemoveSelectedItems(spMasterObj);
               var oSelect = document.getElementById(callingObj.id.replace(replaceExp,'SelectCandidate'));
               CleanOptionsText(oSelect);
}
}

Call Jquery After Update panel Trigger


<script type="text/javascript">
             function pageLoad() {

                 if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {

alert();
       }
}

            </script>

Hide Edit item Button from display page in share point list forms


<script type="text/javascript">

var elem = document.getElementById("Ribbon.ListForm.Display.Manage.EditItem-Large");
elem.style.display = "none";
</script>

How to catch event after submit button click


<input type="button" value="Form Action" name="btnFormAction0" onclick="javascript: {ddwrt:GenFireServerEvent('__commit)')};alert('Your request has been submitted and we will get back to you once it is done');window.parent.location='http://server/site/Lists/list_name/AllItems.aspx'" />







 <input type="button" value="Submit" class="ms-ButtonHeightWidth" name="btnSubmit">
                             <xsl:attribute name="onclick">
                                errmsg = checkSolution();
     if(errmsg.length &gt; 0) {      
     }
     else {
      <xsl:value-of select="ddwrt:GenFireServerEvent('__commit;__redirectsource')" />
     }
      </xsl:attribute>
                       </input>










$(document).ready(function()
 {
     $("nobr:contains('Archived')").parent('h3').parent('td').parent('tr').hide();
     $("nobr:contains('AssignedTo')").parent('h3').parent('td').parent('tr').hide();

 });
 function PreSaveAction() {
 $("input[title$='Archived']").attr('checked',false);
  var userName = $().SPServices.SPGetCurrentUser({
  fieldName: "Name"
 });
 $("textarea[title='People Picker']").val(userName);
 $("div[title='People Picker']").text(userName);
 return true;
 }
function checkSolution(){
 // alert('hi');
 

  //alert('Confirm?');
  //window.parent.location='/Lists/TechnicalChallengeFeedBack/SendMail.aspx'
   var answer = confirm ("This will submit the data and you are not able to edit the data in future.Click on save if you want to edit the data in future .")
   if (answer)
   {
     $("input[title$='Archived']").attr('checked','checked');
     var userName = $().SPServices.SPGetCurrentUser({
     fieldName: "Name"
 });

 $("textarea[title='People Picker']").val(userName);
 $("div[title='People Picker']").text(userName);
   return '';
   }
   else
   {
      $("input[title$='Archived']").attr('checked',false);
      return 'Thanks.';
   }
}
</script>


Best List page validation example


var answer = confirm ("Are you having fun?")
if (answer)
alert ("Woo Hoo! So am I.")
else
alert ("Darn. Well, keep trying then.")



// Validate the PTO Request input
function validateInput() {
    startDate = getValueWithFieldName('input', 'Request Start Date', 'ff1_new');
    endDate = getValueWithFieldName('input', 'Request End Date', 'ff2_new');
    //alert(startDate + endDate);
    startYear = startDate.substring(startDate.length, startDate.length - 4);
    endYear = endDate.substring(endDate.length, endDate.length - 4);
    //alert(startYear + endYear);
    if(startYear != endYear) {
        return 'Start date and end date must be in the same year.  To enter a PTO request which crosses into the next year, please enter two requests.';
    }
    if(startDate.length == 0) {
        return 'Please enter a start date.';
    }
    if(endDate.length == 0) {
        return 'Please enter an end date.';
    }
    return '';
}

// getValueWithFieldName: Get a form field value using its tagName, fieldname, and identifier to find it in the page
// Arguments:
//        tagName:    The type of input field (input, select, etc.)
//        fieldName:    The name of the list column
//        identifier:    The identifier for the instance of the fieldName (ff1, ff2, etc.)
//
    function getValueWithFieldName(tagName, fieldName, identifier) {
        //alert('getValueWithFieldName: tagName=' + tagName + ' fieldname=' + fieldName + ' identifier' + identifier);
        var theInput = getTagFromIdentifierAndFieldname(tagName, fieldName, identifier);
        //alert('getValueWithFieldName: theInput.id=' + theInput.id + ' theInput.value=' + theInput.value);
        return theInput.value;
    }

// getTagFromIdentifierAndFieldname: Get an input field's tag object using its tagName, fieldname, and identifier to find it in the page
// Arguments:
//        tagName:    The type of input field (input, select, etc.)
//        fieldName:    The name of the list column
//        identifier:    The identifier for the instance of the fieldName (ff1, ff2, etc.)
//
    function getTagFromIdentifierAndFieldname(tagName, fieldName, identifier) {
        //alert('getTagFromIdentifierAndTitle: tagName=' + tagName + ' fieldname=' + fieldName + ' identifier' + identifier);
        var len = identifier.length;
        var tags = document.getElementsByTagName(tagName);
        for (var i=0; i < tags.length; i++) {
            if (tags[i].title == fieldName) {
                //alert('HIT tags[' + i + '].title' + tags[i].title + ' tags[' + i + '].id=' + tags[i].id + ' identifier=' + identifier);
                if((tags[i].id == identifier) || (tags[i].id.indexOf(identifier) > 0)) {
                    return tags[i];
                }
            }
        }
        return null;
    }



<td nowrap="" class="ms-vb">
    <input type="button" value="Submit" name="btnSubmit">
     <xsl:attribute name="onclick">
      errmsg = validateInput();
      if(errmsg.length > 0) {
       alert(errmsg);
      } else {
       <xsl:value-of select="ddwrt:GenFireServerEvent('__commit;__redirectsource')" />
      }
     </xsl:attribute>
    </input>
    <input type="button" value="Cancel" name="btnCancel" onclick="javascript: {ddwrt:GenFireServerEvent('__cancel;__redirectsource')}" />
   </td>

Remove HTML Tags in SharePoint 2010


Always I’ve  faced the same problem and solved it in the same why when I deal with text fields in SharePoint which is remove the Html tags for the returned text to display it as a plain text. Each time my best solution is googling for the regular expression to replace Html tags with empty string

Unfortunately  I find a method in Microsoft.SharePoint namespace to do this and offer also sub string for the returned text which is:

SPHttpUtility.ConvertSimpleHtmlToText(HTMLText , maxLength);

To remove tags and sub string it to max length

or

SPHttpUtility.ConvertSimpleHtmlToText(HTMLText , -1);

To remove tags only

working with delegate controls

source --http://digsharepoint.blogspot.in/2012/02/what-is-delegate-controls-in-sharepoint.html





SharePoint provides a mechanism that allows developers to customize out-of-the-box functionality in pages, without the need for modifying the pages that come with SharePoint. This mechanism is provided with delegate controls. I am going to show you how to create a delegate control that you can use to override the Global Navigation bar at the top of standard SharePoint pages.

Definition

First off, it's important to understand what a delegate control is, so we can properly create and apply it in the specific situation we are developing for. A delegate control defines a region in an aspx page that allows the content to be replaced with our custom content. This custom content is created via a SharePoint feature, and when deployed and activated, replaces the standard content at runtime.

Development

The Global Navigation bar is located at the top of all the pages in a site, and the master page uses a delegate control in a placeholder to determine what to render at runtime. Here is the markup for the delegate control:
<SharePoint:DelegateControl runat="server" ControlId="GlobalNavigation"/>
Note that the ControlId value determines what delegate control is, so for our example the Global Navigation bar has a ControlId value of GlobalNavigation.
Once we know the name of the delegate control we are working with, we are ready to write code for our delegate control.
Open Visual Studio 2010 and create a new Empty SharePoint project. Map a folder to the CONTROLTEMPLATES directory in the SharePoint root (the 14 hive). Add a new SharePoint 2010 User Control by right-mouse clicking the CONTROLTEMPLATES mapped directory, from the Solution Explorer. Give the user control an appropriate name (I named it ucGlobNavDelegateControl). Once the control is created, open it in the Designer and add some markup:
Custom Delegate Control
You will also need to create an Elements.xml file, so add a module to the project, which will create the Elements.xmlfile as part of it (you can delete the Sample.txt file created).
Delete the markup between the Elements tags, and add the following markup:
<Control Id = "GlobalNavigation" Sequence="90"  ControlSrc="~/_ControlTemplates/ucGlobNavDelegateControl.ascx" />
This markup associates the delegate control we are creating with the delegate control placeholder defined in the master pages in a SharePoint site collection. Note that the ControlId value equals GlobalNavigation, which specifies that our custom delegate control is overriding the Global Navigation control. The Sequence value must be less than 100, since SharePoint will render the control with the lowest sequence (the default control is set at 100). The ControlSrc value indicates the location to our custom delegate control.

Deployment

Deploying our custom delegate control is done using a feature, so create a feature in Visual Studio and name itMyCustomGlobalNavigationFeature. Add the module you created to it, and set the feature scope to Web. Compile and deploy the project to your SharePoint site.
Once your feature is deployed successfully, you should be able to verify that your feature has been deployed and activated in your site by managing the Site Features, under Site Settings. Look for your deployed feature, as shown here:
Activating Feature
If your feature is properly activated, you should now see the Global Navigation replaced by your custom delegate control:
SharePoint Page with Custom Delegate Control

Conclusion

And that's all there is to it! Of course, the example here is basic, so there is a lot more that can be done with delegate controls. I am also including a screenshot of my Solution Explorer in Visual Studio, so you can get an idea of how my example project was structured:
Solution Explorer