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

Get the current username programmatically in share point

HttpContext.Current.User.Identity.Name

use of People Picker programmatically in web-parts and pages


Add
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
in the page.


 <SharePoint:PeopleEditor ID="spPeoplePickerUserName" Width="200" runat="server" SelectionSet="User"     AllowEmpty="true" MultiSelect="false" AutoPostBack="false" />




to store the data use

if (spPeoplePickerRespUser.ResolvedEntities.Count > 0)
                                        {
                                            PickerEntity selectedEntity = (PickerEntity)spPeoplePickerRespUser.ResolvedEntities[0];
SPUser user = oWeb.EnsureUser(selectedEntity.Key);
                                itemToAdd["Entered_x0020_By"] = user;
                                        }



for edit mode,

spPeoplePickerUserName.CommaSeparatedAccounts = Convert.ToString(itemToUpdate["User_x0020_Name"]);


 if (spPeoplePickerUserName.ResolvedEntities.Count > 0)
                        {
                            PickerEntity entity = (PickerEntity)spPeoplePickerUserName.ResolvedEntities[0];
                            accountName = entity.Key;
                            int pos = accountName.IndexOf('\\');
                            accountName = accountName.Substring(pos + 1);
                            SetContactInformation(accountName);

                        }

How to get the second people picker in a page through javascript and to populate the current username


var tags = document.getElementsByTagName('DIV');
  var count = 0;
  for(var i=0;i<tags.length;i++)
  {
  if(tags[i].title == 'People Picker')
  {
   count = count +1;  
   if(count == 2)
   {
     SetTheCurrentUser1(tags[i].id);

   }
  }
  }
function SetTheCurrentUser1(ctrlPeoplePicker)
{
  var currentUser = "";
  currentUser = $().SPServices.SPGetCurrentUser({
  fieldName: "Name"
 });
     // alert(currentUser);
  if(currentUser != "")
{  
svSetPeoplePickerValue(ctrlPeoplePicker,currentUser);
}
}
function svSetPeoplePickerValue(strControlId, strValue)
{
var ctlUpLevel = document.getElementById(strControlId);

// Get the portion of the ID preceeding '_upLevelDiv'
// all controls' ids for the people picker start with this
var subs = ctlUpLevel.id.substring(0, ctlUpLevel.id.indexOf("_upLevelDiv"));

// Magically set the value of the People Picker (and associated fields)
var ctlDownLevel = document.getElementById(getSubControlID(subs, g_EntityEditorDownLevelId));
ctlDownLevel.value = strValue;
SetInnerText(ctlUpLevel, strValue);
copyUplevelToHidden(subs);
}
// The functions getSubControlID, SetInnerText, copyUplevelToHidden and
// the variable g_EntityEditorDownLevelId are provided by SharePoint.

this form was customized not working with attachment sharepoint 2007

Source--http://support.microsoft.com/kb/953271




  1. For custom edit item forms and for custom new item forms
    1. In the XSL code block, locate the following code.
      <xsl:template name="dvt_1">
                                      <xsl:variable name="dvt_StyleName">ListForm</xsl:variable>
                                      <xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row"/>
                                      <table border="0" width="100%">
                                                      <xsl:call-template name="dvt_1.body">
                                                                      <xsl:with-param name="Rows" select="$Rows"/>
                                                      </xsl:call-template>
                                      </table>
                      </xsl:template>
      
    2. Replace the lines of code that you located in step 2a with the following lines of code.
                      <xsl:template name="dvt_1">
      
                                      <xsl:variable name="dvt_StyleName">ListForm</xsl:variable>
      
                                      <xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row"/>
      
                                      <div>
      
                                                      <span id="part1">
      
                                                                      <table border="0" width="100%">
      
                                                                                      <xsl:call-template name="dvt_1.body">
      
                                                                                                      <xsl:with-param name="Rows" select="$Rows"/>
      
                                                                                      </xsl:call-template>
      
                                                                      </table>
      
                                                      </span>
      
                                                      <SharePoint:AttachmentUpload runat="server" ControlMode="Edit"/>
      
                                                      <SharePoint:ItemHiddenVersion runat="server" ControlMode="Edit"/>
      
                                      </div>
      
                      </xsl:template>
      
      Note The XSLT code must have the ControlMode set to "New" for custom new item forms and to "Edit" for custom edit item forms.
    3. Locate the following line of code.
      <xsl:if test="$dvt_1_automode = '1'" ddwrt:cf_ignore="1">
    4. Paste the following code above the line of code that you located in step 2c.
      <tr id="idAttachmentsRow">
       <td nowrap="true" valign="top" class="ms-formlabel" width="20%">
         <SharePoint:FieldLabel ControlMode="Edit" FieldName="Attachments" runat="server"/>
        </td>
          <td valign="top" class="ms-formbody" width="80%">
           <SharePoint:FormField runat="server" id="AttachmentsField" ControlMode="Edit" FieldName="Attachments" __designer:bind="{ddwrt:DataBind('u','AttachmentsField','Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Attachments')}"/>
                             <script>
      var elm = document.getElementById("idAttachmentsTable");
              if (elm == null || elm.rows.length == 0)
                document.getElementById("idAttachmentsRow").style.display='none';
                            </script> </td>
           </tr>
      
      Note This code sample is for a custom edit item form. If you use a custom new item form, replace ControlMode=”Edit” with ControlMode=”New” in the code.

      Additionally, in the __designer:bind attribute, the first parameter for the ddwrtDataBind function should be "'i'" (insert) for a custom new item form and "'u'" (update) for a custom edit item form.

      For example, the code may resemble the following code.
      <SharePoint:FormField runat="server" id="AttachmentsField{$Pos}" ControlMode="New" FieldName="Attachments" __designer:bind="{ddwrt:DataBind('i',concat('AttachmentsField',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Attachments')}"/>
      
    5. Save the form.
    For display forms
    1. Open the Custom List form.
    2. Move the cursor to the table cell in the custom form control where you want the attachment to be displayed. Then, right-click the cell, point to Insert, and then click Row Below. A new table row that has two column cells is created.
    3. Move the cursor to the left table cell of the new row, and then type Attachments.
    4. Move the cursor to the right-side table cell of the new row, switch to Code view, and then enter the following code.
      <SharePoint:AttachmentsField ControlMode="Display" FieldName="Attachments" runat="server" Visible="true"/>
    5. Save the form.
Notes
  • If you make more changes to the page, SharePoint Designer 2007 may automatically add a unique ID to the attachment code that you added. For example, “<tr id="idAttachmentsRow">” is changed to “<tr id="idAttachmentsRow{generate-id}">.”

    This process may cause JavaScript errors on the page. If this issue occurs, delete the “{generate-id}” tags that are added automatically.
  • You may receive the following error message:
    An unexpected error has occurred
    To resolve this issue, move the Custom List form outside the Web Part zone.
  • You receive the following a JavaScript error message:
    Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus.
    If you receive this error message, make sure that the ListForm Web Part that is on the page by default is still there. Then, set the Layout to Hidden, and close the Web Part. To do this, follow these steps:
    1. Right-click the List form Web Part in SharePoint Designer.
    2. Click Web Part Properties, and then click Layout.
    3. In the Layout dialog box, click to select Hidden, and then close the Web Part.