Search This Blog

Thursday, 31 May 2012

AutoComplete TextBox using JQuery in SharePoint 2010 with SPList values


Hi All, 

In my previous post here, I have discussed to get AutoComplete TextBox using Jquery, where I have set an array of keywords to source. 

In this post, I get the values for the source from a SharePoint2010 lists. Refer my previous post here for basic details and complete code. Here I just posted new part of the code only.

To achieve this, we have to use SPServices. Get the script from below link:

Refer this script in your solution.
Instead of assigning array of keywords, call the method GetListItems(). Refer the below code snippet:

var availableTags = GetListItems();

Add the below function inside the wireEvents() function

///function to get list items using spservice

          function GetListItems()
          {

              var name = new Array();

              var index = 0;

              $().SPServices
              ({

                  operation: "GetListItems",

                  async: false,

                  listName: "Keyword Master",

                  CAMLQuery: "<Query><OrderBy><FieldRef Name='Title' Ascending='True' /></OrderBy></Query>",

                  CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",

                  completefunc: function (xData, Status) {

                      $(xData.responseXML).find("z\\:row,row").each(function () {

                          name[index] = $(this).attr("ows_Title");

                          index++;

                      });

                  }
                               $("#tags").autocomplete({   // tags - ID of textbox control
                               source:name
              });

              return name;
          }
Output:

























Done. here we get the values from SharePoint 2010 list.


Note : You should mention viewfields for the CAMLQuery, otherwise it looks only those fields which are available in default view.

AutoComplete TextBox using JQuery in SharePoint 2010


Hi All, 

Recently I had a situation to give an Auto Complete TextBox control in my application (Visual Web part) using JQuery. I have done this by refereeing the below link

Link: Reference
 
The Autocomplete widgets provides suggestions while you type into the field. Here the suggestions are tags for programming languages, give "ja" (for Java or JavaScript) a try.

The datasource is a simple JavaScript array, provided to the widget using the source-option.

Now get works the JQuery in SharePoint 2010 Visual webpart 

I have added two js files and one css file in my solution to work the JQuery and give proper style to the textbox and menu items. You can download the js files and css file from the below link




Then, I written the script and get the array of keywords (Programming languages) and assigned to the source option. Refer the below code snippet:

 <script src="/_layouts/1033/STYLES/jqueryCustom-1.7.1.min.js" type="text/javascript"></script>
<script src="/_layouts/1033/STYLES/jqueryCustom-ui-1.18.min.js" type="text/javascript"></script>
<SharePoint:CssRegistration ID="cssReg" runat="server" Name="/_layouts/1033/STYLES/jquery-uiCustom.css"> </SharePoint:CssRegistration>
  <script type="text/javascript">
      Sys.Application.add_load(wireEvents);

      function wireEvents()
      {
          $(function ()
          {
              var availableTags = ["ActionScript","AppleScript","Asp","BASIC","C",
                                   "C++","Clojure","COBOL","ColdFusion","Erlang",
                                  "Fortran","Groovy","Haskell","Java","JavaScript",
                                   "Lisp","Perl","PHP","Python","Ruby","Scala",                                  
                                   "Scheme"];
              function split(val)
              {
                  return val.split(/,/);
              }

              function extractLast(term)
              {
                  var nonSpaceTerm = split(term).pop().toString();
                  if (/^\s+\S*/.test(nonSpaceTerm))
                  {
                      nonSpaceTerm = nonSpaceTerm.replace(/\s+/, "");
                  }
                  return split(nonSpaceTerm).pop();
              }

              $("input[name*='txtKeyword']")
              // don't navigate away from the field on tab when selecting an item
                     .bind("keydown", function (event)
            {
                         if (event.keyCode === $.ui.keyCode.TAB &&
                                         $(this).data("autocomplete").menu.active) {
                             event.preventDefault();
                         }
                     })
                     .autocomplete(
            {
                         minLength: 0,
                         source: function (request, response)
                {
                             // delegate back to autocomplete, but extract the last term
                             response($.ui.autocomplete.filter(
                                         availableTags, extractLast(request.term)));
                         },
                         focus: function ()
                {
                             // prevent value inserted on focus
                             return false;
                         },
                         select: function (event, ui)
                {
                             var terms = split(this.value);
                             // remove the current input
                             terms.pop();
                             // add the selected item
                             terms.push(ui.item.value);
                             // add placeholder to get the comma-and-space at the end
                             terms.push("");
                             this.value = terms.join(",");
                             this.value += " ";
                             return false;
                         }
                     });
          });
      }           
        </script>

Then added a asp:TextBox control
<asp:TextBox ID="txtKeyword" runat="server"></asp:TextBox>

Done, now deployed and added the webpart in my application.

Output:
























I will post how to get the source items from SharePoint2010 list in my next post.

Cheers....................................

Wednesday, 30 May 2012

The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again


In SharePoint above exception is very common. Mentioned below are the causes of this exception
  1. Trying to update Sharepoint object Like SPSite, SPWeb etc on GET request. Actaully SharePoint doesnĂ¢€™t allow us to update SharePoint object in Get request to avoid cross-site scripting.
  2. While post request also you may encounter above exception. Let me share few real-time scenario:
·         If user having read/write permission on few list tries to update Security Groups or try to add new user into SharePoint site. Even if you put your code block inside SPSecurity.RunWithElevatedPrivileges, you might get same exception.
                  Sample Code:
          SPSecurity
.RunWithElevatedPrivileges(delegate()
          {
                using (SPSite oSite = new SPSite( SPContext.Current.Site.ID))
                {
                        using (SPWeb oWeb= oSite.OpenWeb())
                        {
                                SPUser oUser = oWeb.EnsureUser(LoginName);
                        }
                 }
});
·         We show popup using window.open method and if there is logic to update SPWeb , SPSite etc object in the code behind, you might encounter same exception.
Solution:
If you still want to allow updates to the database as a result of a GET request or without requiring a security validation, set "AllowUnsafeUpdates" of SPWeb or SPSite to true. But be careful while using this property always reset "AllowUnsafeUpdates" to false after unsafe update.

Sample Code:
SPWeb oWeb;
try
{
   using (
SPSite oSite = new SPSite(SPContext.Current.Site.ID))

   {
       using(oWeb = oSite.OpenWeb())

       {
                  oWeb.AllowUnsafeUpdates =
true;
                  // write Code
       }
   }
}

catch ( Exception ex)
{
      //Log Exception
}

finally

{
      oWeb.AllowUnsafeUpdates =
false;
}


Create Field and update List Item in SharePoint 2010 using PowerShell


Hi All,
Recently I had a situation to add a new field in an existing SharePoint Lists and update value to the newly added field for existing list items using power shell.
Then I created the following power shell script to achieve my requirement.

Script:
try
{
    $SPSite = New-Object Microsoft.SharePoint.SPSite("http://chesgh201tw1v:1605")
    $SPWeb = $SPSite.OpenWeb()
    $List = $SPWeb.Lists.TryGetList("Document Type Master")
    if($List -ne $Null)
    {
        $List.Fields.Add("DisplayOrder",[Microsoft.SharePoint.SPFieldType]::Number,$false)
        $List.Update()
        write-host "New Field Added in List" -foregroundcolor Green
       
        $ListView = $List.Views["All Items"];
        if($ListView -ne $Null)
        {
            $ListView.ViewFields.Add("DisplayOrder");
            $ListView.Update();
        }
        write-host "Field added in default View" -foregroundcolor Green
       
        $SPListItemCollection = $List.Items
        if($SPListItemCollection.Count -gt 0)
        {
            #Get list item collection
            $spListItemsCount = $SPListItemCollection.Count    #Get list items total count
            write-host "Updating values in the newly added field" -foregroundcolor Green
            for($Counter = $spListItemsCount-1; $Counter -ge 0; $Counter--)
            {
                $spListItem = $SPListItemCollection[$Counter]    #Get list item via index
                $Title = $spListItem["Title"]
                switch ($Title)
                    {
                        "Policy"
                        {
                            $spListItem["DisplayOrder"] = 1
                        }
                        "Script"
                        {
                            $spListItem["DisplayOrder"] = 2
                        }
                        "Job Aid"
                        {
                            $spListItem["DisplayOrder"] = 3
                        }
                        "Talking Points"
                        {
                            $spListItem["DisplayOrder"] = 4
                        }
                   }
               
                $spListItem.Update()
            }
            write-host "Value(s) updated successfully in the newly added field" -foregroundcolor Green
        }
        write-host "Operation completed successfully" -foregroundcolor Green
    }
    else
    {
        write-host "List is not found" -foregroundcolor Red
    }

}
catch [System.SystemException]
{
    write-host “Execution stopped due to: “+$_.Message -foregroundcolor Red
}

Result:














Done.  I have achieved that, now the new field added in SharePoint list and values updated in the field accordingly.

Happy Scripting ...........................................