Tuesday, December 4, 2012

Monday, July 2, 2012

Using SPServices to Query a list in SharePoint 2010

  1. Create 2 lists.
     1a. Coolcities List
     1b. SelectCity List












     2.   Download, Refer and test SPServices.
     2a. Follow the link to download the SPServices js file.
     2b. Refer the file similar the way done for the jquery.js file

    <script src="/Shared%20Documents/jquery-1.7.2.js" type="text/javascript"></script>
<script src="/Shared%20Documents/jquery.SPServices-0.7.1a.js" type="text/javascript"></script>


     2c. Test the SPServices file has been properly refered or the file is properly loading during the page    load. For this run the small script which alerts the user who is logged in during the page load.
Edit the newform.aspx and add the content editor webpart







Then paste the following code inside it

<script src="/Shared%20Documents/jquery-1.7.2.js" type="text/javascript"></script>
<script src="/Shared%20Documents/jquery.SPServices-0.7.1a.js" type="text/javascript"></script>



$(document).ready(function() {

var thisUserName = $().SPServices.SPGetCurrentUser({
fieldName: "Title",
debug: false
});

alert(thisUserName);

});

So the above code will alert the user who is logged in, once you get the alert that means the spservices is being loading properly, and you can remove the test code.

3. Building up the SPServices inside the onchange jQuery function.


<script src="/Shared%20Documents/jquery-1.7.2.js" type="text/javascript"></script>
<script src="/Shared%20Documents/jquery.SPServices-0.7.1a.js" type="text/javascript"></script>


<script type="text/javascript">


$(document).ready(function() {
$("select").change(function() {

var selectedValue = this.value;

$().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "CoolCities",
    CAMLViewFields: "<ViewFields><FieldRef Name='Description' /></ViewFields>",
     CAMLQuery: "<Query><Where><Eq><FieldRef Name='City'/><Value Type='Text'>" + selectedValue + "</Value></Eq></Where></Query>",
CAMLRowLimit: 1,
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {
        var liHtml = $(this).attr("ows_Description");
        alert(liHtml);
 $("input[title='Description1']").val(liHtml);
    });
    }
  });
});

});</script>

Output


-So when the drop down value is changed, on that event the CoolCities list is queried and the description of the selected city is displayed in the Description1 column of the SelectCity list.

Note :
The above code takes into consideration, that there is only one dropdown box in the SelectCity list,
if there are more than one then it would need some check before running the code.

Monday, February 13, 2012

The Sudden Death Error1:The server returned a non specific error when trying to get the data from the data source.check the format and the content of your query and try again.If the problem persists, contact the server administrator

From the production environment i created a template of a custom list l1(.stp file)  and then used this template to create a list in the dev machine, now the names of the sitecollection and the server in the dev machine are different than those from the prod machine ..
After i created a list based from the custom list template l1...i opened the list forms in the designer, as soon as i open the newform.aspx "BOOM" i was blinded with the vague,cryptic,horrifying Error--> "the server returned a non specific error when trying to get the data from the data source.check the format and the content of your query and try again.
If the problem persists, contact the server administrator"
I had no clue, probably even the designer did not know what exactly is wrong, but knew something is not well..After researching on it, i came to a solution in one of the forums which suggestion to change the weburl property ..so i checked the weburl property and there it was, the weburl sparkled as a twinkle in the dark..Default Value was still pointing to the production server site so i changed it to dev server site...and BINGO!..off in a flash it worked!

Below is the tag in the newform.aspx

<SharePoint:SPDataSource runat="server" DataSourceMode="ListItem" SelectCommand="&lt;View&gt;&lt;Query&gt;&lt;Where&gt;&lt;Eq&gt;&lt;FieldRef Name=&quot;ContentType&quot;/&gt;&lt;Value Type=&quot;Text&quot;&gt;Item&lt;/Value&gt;&lt;/Eq&gt;&lt;/Where&gt;&lt;/Query&gt;&lt;/View&gt;" UseInternalName="True" UseServerDataFormat="True"><SelectParameters><WebPartPages:DataFormParameter ParameterKey="ListItemId" PropertyName="ParameterValues" DefaultValue="0" Name="ListItemId"></WebPartPages:DataFormParameter><WebPartPages:DataFormParameter ParameterKey="weburl" PropertyName="ParameterValues" DefaultValue="http://site.internal.com" Name="weburl"></WebPartPages:DataFormParameter><WebPartPages:DataFormParameter ParameterKey="ListID" PropertyName="ParameterValues" DefaultValue="{40B40CDB-593E-4142-8AEA-B25032DE54D1}" Name="ListID"></WebPartPages:DataFormParameter>




Saturday, February 11, 2012

Hidding the Quick Launch on a web part Page Sharepoint

First Edit the webpart page and add the content editor webpart to the page,then copy paste this CSS in it.

  <style type="text/css"> 
  body #s4-leftpanel { display: none; } 
  .s4-ca { margin-left: 0px; } 
  </style>
  

The Hidden Gem : SPHttpUtility.ConvertSimpleHtmlToText()

I had a requirement which needed to extract only first 200 characters from a Richtextbox in a custom webpart.Now this RichtextBox may contain tables,images,white spaces..html. .... The approach was first to strip all the HTML from the RichTextBox.Text and then remove the white spaces ... 
           
                   //add the following namespace
                 using Microsoft.SharePoint.Utilities;
                 using System.Text.RegularExpressions;

                 //converts all HTML into TEXT
                string convertHtmlToText = SPHttpUtility.ConvertSimpleHtmlToText(RichTextBox.Text, RichTextBox.Length);

                //replace extra white space with single white space
                string removedExtraWhiteSpace = System.Text.RegularExpressions.Regex.Replace(convertHtmlToText , @"\s+", " ");

The Awesome PreSaveAction() javascript function in list form sharepoint 2010

PreSaveAction() in list forms runs before the list form data gets saved

How to define it?
If you are on one of the list forms(newitem.aspx,edititem.aspx,dispitem.aspx) in sharepoint designer-click on the "Edit In Advance Mode option"  find the "Main" content place holder in the page
Inside the content place holder copy paste below

<script type="text/javascript">
 function PreSaveAction()
{
alert('I will run before the form gets saved');
return true
}
</script>


Note : Don't forget to return true; otherwise the function won't fire ..

Programmatically create a Attachment functionality in Custom Visual WebPart Sharepoint 2010

After searching, endlessly for creating a custom attachment functionality, i finally came across a great article which explained creating attachment functionality in a webpart.below is the link

i modified it to suit my requirement

paste this code in the .aspx  page
<table> <tr><td>
<asp:HiddenField Value="hDeleteAttachs" ID="hHiddenFields"  runat="server" />
</td></tr>

<tr>
<td><span id="part1">
<SharePoint:AttachmentButton runat="server" ID="btnAttach" ControlMode="new" Text="Add Attachment">
</SharePoint:AttachmentButton> </span></td></tr>

<tr><td id='idAttachmentsRow'>
<SharePoint:AttachmentUpload runat="server" ID="uploadAttach" ControlMode="New">
</SharePoint:AttachmentUpload></td></tr>

<tr><td><SharePoint:AttachmentsField runat="server" ID="fieldAttach" ControlMode="new" FieldName="Attachments">
</SharePoint:AttachmentsField></td></tr>
</table>

 <asp:Button ID="submitButton" runat="server" Text="Submit" OnClick="submitButton_Click" />

Below in the c# page

namespace ProjectName.VisualWebPartName
{
    public partial class VisualWebPartNameUserControl: UserControl
    {

        SPSite Osite = null;
        SPWeb Oweb = null;
        SPSite noprevsite = null;
        SPWeb noprevweb = null;
        SPList Olist = null;
        SPListItem Osplistitem = null;

 protected void Page_Load(object sender, EventArgs e)
        {
             noprevsite = SPContext.Current.Site;
             noprevweb = noprevsite.OpenWeb();

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                Osite = new SPSite(noprevsite.ID);
                Oweb = Osite.OpenWeb(noprevweb.ID);
                Oweb.AllowUnsafeUpdates = true;
                Olist = Oweb.Lists["ListName"];
                btnAttach.ListId = Olist.ID;
                uploadAttach.ListId = Olist.ID;
                fieldAttach.ListId = Olist.ID;
                Osplistitem = Olist.Items.Add();
});
}

 protected void submitButton_Click(object sender, EventArgs e)
        {
          AddAttachments(ref Osplistitem);
        }
   void AddAttachments(ref SPListItem Osplistitem)
        {
            try
            {
                for (int i = 0; i < (Page.Request.Files.Count - 1); i++)
                {
                    try
                    {
                        //Get the list of files for attachments
                        HttpPostedFile newAttach = Page.Request.Files[i];
                        byte[] fileContents = new byte[newAttach.ContentLength - 1];
                        newAttach.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                        newAttach.InputStream.Read(fileContents, 0, newAttach.ContentLength - 1);
                        System.IO.FileInfo fInfo = new System.IO.FileInfo(newAttach.FileName);
                        Osplistitem.Attachments.Add(fInfo.Name, fileContents);
                    }
                    catch { continue; }
                }
            }
            catch
            {
            }

        }
}
}


Monday, January 23, 2012

Getting the properties from user profile information using sharepoint object model sharepoint 2010

Below is the code for retrieving the user profile properties using sharepoint object model 2010

                   SPSite Osite = SpContext.Current.Site;
                   SPWeb web = Osite.OpenWeb();
                   var strCurrentUser = web.CurrentUser.Name;

                   SPServiceContext serviceContext = SPServiceContext.GetContext(Osite);
                   UserProfileManager upm = new UserProfileManager(serviceContext);

                   if (!upm.UserExists(strCurrentUser))
                   {
                       UserProfile u = upm.GetUserProfile(strCurrentUser);
                       string uemail = u[PropertyConstants.WorkEmail].ToString();
                       string ufirstname = u[PropertyConstants.FirstName].ToString();
                       string ulastname = u[PropertyConstants.LastName].ToString();
                   }

Note :  If you are remotely logging into the development machine, while debugging you might encounter a pop error -"cannot connect to remote computer" just press f11 again and it will get the value from the user profile and you will be able to debug further without exiting.