Monday 30 December 2013

DataSheet View And People Picker issue

Hi All,
 Today i will share a weird issue i had gone through. Surely U will have to face it in some point of time.

Certainly everyone would have used Datasheet View. Have U ever checked People picker column in DataSheet View?

Bcoz when i tried, i got "Column Mismatch" error. When i tried the same entry in a Standard view, it got saved... So what is the prob and how to fix???

Finally, I fixed that after checking it for a Whole Day.
The Fix is ,
 U have to give atleast Read rights for the User to be entered in the People Picker.

People picker can validate user by name,email, id etc. in Standard View. But when you open it in Datasheet view then it does not validate the person by name,email. And instead of validating you will see small picker at person or group something like a choice column. You have to select from that.


Small one. But this will be certainly useful for you sometime..
Happy SharePointing...

Tuesday 24 December 2013

Programmatically Hiding the "Overwrite existing files" checkbox for a single library

Hi All,
Last week i got a challenge for hiding the "Overwrite existing files" checkbox for a particular library.
First i thought it would be very easy , because my option was like adding a simple javascript to hide for that library.
I opened SharePoint Designer and tried adding javascript to that. It was not reflecting.. :(:(

On digging deep, I came to know that Upload.aspx is an application page and it is coming from the Layouts folder.
Ok finally i thought i found out the solution and tried changing the Upload.aspx page in the layouts folder. But the checkbox got hidden on all the pages..

Again i have to give a check on that so that it gets reflected for only one library. Finally i pointed out the List GUID in the URL of the page.

Then i tried and found 2 solutions for hiding checkbox for a single library.

Solution 1) Use this script in your master page

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready( function () {
        if (location.href.indexOf('0ABCE757-34A6-409D-A230-72382C924651') >= 0)
 // you must need to change GUID of your lib above
       {
            $("label:contains('Add as a new version to existing files')").prev('input').hide();
            $("label:contains('Add as a new version to existing files')").hide();
            $("a:contains('Upload Multiple Files...')").hide();
        }
    });
</script>

For easily finding the GUID of a library u can refer my post here


The second solution I will share on my next post. C ya!!!!


Thursday 21 November 2013

Programmatically Export data from SharePoint List to Excel SpreadSheet

Hi All,
 Today I will give you the code for exporting data from SharePoint List to Excel.

Ok Without delay, directly going to the code...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Data;
using System.IO;
using System.Web.UI;

namespace Excel
{
    class Program
    {
        private static DataTable dataTable;
        private static SPList list;

        static void Main(string[] args)
        {
            try
            {
                SPSite Osite = new SPSite("http://wf13staging.myhcl.com/sites/BPRCreatives/Creative%20CR%20Tracker");
                SPWeb oWeb = Osite.OpenWeb();
                string _siteUrl = oWeb.Url.ToString();
                if (!string.IsNullOrEmpty(_siteUrl))
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(oWeb.Url))
                        {
                            if (site != null)
                            {
                                SPWeb web = site.OpenWeb();
                                if (web != null)
                                {
                                    #region Export List
                                    string _listName = "Excel List"; // Name of your List
                                    if (!string.IsNullOrEmpty(_listName))
                                    {
                                        list = web.Lists["Excel"];
                                        if (list != null)
                                        {
                                            dataTable = new DataTable();
                                            InitializeExcel(list, dataTable);
                                            string _schemaXML = list.DefaultView.ViewFields.SchemaXml;

                                            if (list.Items != null && list.ItemCount > 0)
                                            {
                                                foreach (SPListItem _item in list.Items)
                                                {
                                                    DataRow dr = dataTable.NewRow();
                                                    foreach (DataColumn _column in dataTable.Columns)
                                                    {
                                                        if (dataTable.Columns[_column.ColumnName] != null && _item[_column.ColumnName] != null)
                                                        {
                                                            dr[_column.ColumnName] = _item[_column.ColumnName].ToString();
                                                        }
                                                    }
                                                    dataTable.Rows.Add(dr);
                                                }
                                            }
                                        }
                                    }
                                    System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
                                    grid.HeaderStyle.Font.Bold = true;
                                    grid.DataSource = dataTable;
                                    grid.DataBind();
          // U can modify the name of the excel file according to ur wish :)

                                    using (StreamWriter streamWriter = new StreamWriter(@"F:\Chandra\Excel" + list.Title + ".xls", false, Encoding.UTF8))
                                    {
                                        using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(streamWriter))
                                        {
                                            grid.RenderControl(htmlTextWriter);
                                        }
                                    }

                                    #endregion
                                }
                            }
                        }
                    });
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }

        public static void InitializeExcel(SPList list, DataTable _datatable)
        {
            if (list != null)
            {
                string _schemaXML = list.DefaultView.ViewFields.SchemaXml;
                if (list.Items != null && list.ItemCount > 0)
                {
                    foreach (SPListItem _item in list.Items)
                    {
                        foreach (SPField _itemField in _item.Fields)
                        {
                            if (_schemaXML.Contains(_itemField.InternalName))
                            {
                                if (_item[_itemField.InternalName] != null)
                                {
                                    if (!_datatable.Columns.Contains(_itemField.InternalName))
                                    {
                                        _datatable.Columns.Add(new DataColumn(_itemField.StaticName, Type.GetType("System.String")));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}



That's it... Directly paste the code and Ur work is done.... ;)

Monday 11 November 2013

SPListItem.Delete() Vs SPListItem.Recycle()

Hi All,
Good Day. Hope u all are doing good. Today we will see about 2 ways of deleting an item programmatically, which ofcourse are significant on their own ways.

While doing coding , 
SPListItem.Delete() is the most used method to delete an item. There is one more method - SPListItem.Recycle().

SPListItem.Recycle() :
When we use this method, the item gets moved to the Recycle Bin. So that , it can be restored if needed.

SPListItem.Delete() :
When we use this method, the item gets permanently deleted.

Under the hood :

Internally there isn’t much difference between the SPListItem.Delete and SPListItem.Recycle methods. Both call an internal SPListItem.Delete method with a different parameter which determines whether an item should be moved to the Recycle Bin or permanently deleted.


public override void Delete()   
{   
      if (this.HasExternalDataSource)   
      {   
            SPUtility.ValidateFormDigest();   
            string bdcid = (string) ((string) this.GetValue("BdcIdentity"));   
            this.ParentList.DataSource.DeleteItem(bdcid);   
      }   
      else   
      {   
            this.DeleteCore(DeleteOp.Delete);   
      }   
}   
public System.Guid Recycle()   
{   
      if (this.HasExternalDataSource)   
      {   
            SPExternalList.ThrowNotSupportedExceptionForMethod("Recycle", base.GetType());   
      }   
      return this.DeleteCore(DeleteOp.Recycle);   

}   

I hope you will be getting a good use of Recycle method in your forthcoming challenges.

Thanks for reading. 

Thursday 17 October 2013

Users vs AllUsers vs SiteUsers in SharePoint

Hi All,

Today we will see about the Usercollections in SharePoint.Lets we see the Scenario

Scenario:

You want to get all the users who have access to the site. An SPWeb object exposes three different collections of users, as shown in this code below.

Code:

SPWeb web = SPContext.Current.Web;

SPUserCollection c1 = web.Users;

SPUserCollection c2 = web.AllUsers;

SPUserCollection c3 = web.SiteUsers;



Ok.... So what is the difference among these 3 collections.

The "Users" collection has the smallest membership of these three collections. This collection includes all the external principals that have been explicitly assigned permissions within the current site.


The "AllUsers" collection includes all members of the Users collection, plus external users that have accessed objects within the site using implicit permissions through group or role membership. For example, imagine a user named Sachin with the login of Company\Sachin that has never been given explicit permissions to access a site and view a particular list. However, he might still be able to view the list because of his membership within an Active Directory group that has been configured with list view permissions. When Sandeep first accesses the site or one of its objects (say, a list using implicit permissions), he is added as a member of the AllUsers collection, but he is not added as a member of the Users collection.

The "SiteUsers" collection is an aggregation that combines membership for each AllUsers collection within the current site collection. The membership of this collection includes all external principals that have been assigned permissions to any object within the site collection as well as all external users that have been granted access to any of the site collection's objects using implicit permissions.

I hope now u will get an idea about these collections.

Obviously there, u will get this doubt.


-----What will the SharePoint UserInfoList contain - AllUsers or SiteUsers or Users?

And the answer is, Actually it contains cached information about the users logged in at least once to the site collection.

See u on my next post :) byeee....


Wednesday 2 October 2013

DateTime Fields and CAML Queries , OffsetDays...

Hi Friends,
 Today I will share you some tips regarding CAML queries in SharePoint. Most of you would have played with CAML Queries.
OK , Now I will tel you how to deal with the Dates in CAML Query.

Scenario 1 : If you are checking for the items having "Due Date" field value as "Today", then this would be the query for u.

<Where>
<Eq>
<FieldRef Name="DueDate" />
<Value Type="DateTime">
<Today/>
</Value>
</Eq>
</Where>

Scenario 2 : what if u want something dynamic???
 EX: if u want to get the items, having "Due Date" 5 days before Today. For this you can't give a static day, because "Today" changes daily.
     Option is "OffsetDays".
The Query goes like this :

<Where>
<Eq>
<FieldRef Name="DueDate" />
<Value Type="DateTime">
<Today OffsetDays="-5" />  ----------> for future dates the value should be positive.
</Value>
</Eq>
</Where>

In many documents they have mentioned Offset instead of "OffsetDays"... better be careful while checking...

Have a good Day :)

Saturday 14 September 2013

Sharepoint Designer Workflow - Empty Date field value

Hi All,
 Today we will see a peculiar behaviour of Sharepoint Date Field in Designer Workflow.

ok,, lets consider this scenario. There is a list with a DateTime column(Say, "Publishing Date") and that is a not a mandatory field.
My requirement is to get the value of the "Publishing date" in mail..
I retrieved the value and showed that in mail..

Now the problem comes,,,

1) If the "Publishing Date" is filled , then it is well and good. It is also shown in the mail.
2) If "Publishing Date" is not filled and left empty in SharePoint then the mail is showing "1/1/0001" in that area.

   Note : No exception comes, No blank field comes in that area of the mail.

So obviously my requirement was to show a blank space when the "Publishing Date" is empty...

Workaround for this is shown in the below image.. this is done by adding a WorkFlow Variable- "stored variable" and setting its value to an blank (i.e) "one empty space" in its value assigning area.



Its doneee... Thank you.. See u all on next post...

Saturday 7 September 2013

What is SharePoint\System account?


Hi All,
  Today we will see about the "System Account" which we used to come accross while working on SharePoint...

Some interesting things about it...


 What is SharePoint\System account?


1) SHAREPOINT\System account is the same account used by application pool of your SharePoint web application in IIS at the time of creation/extension of respective web application.

2) This is the account which is used when you run your code in under elevated privileges by SPSecurity.RunWithElevatedPrivileges. (Most of the people think that it runs under the Farm Administrator credentials, which is no true..)

3) When you create/extend a web application in SharePoint and specify an Application Pool then the identity (Network Account) used by that Application pool becomes the SHAREPOINT\System account.

4) It is highly recommended that end user should not be allowed to use this account to avoid unexpected errors.

5) If you change the identity of App Pool account after creating/extending the SharePoint web application, the new account will not become the SHAREPOINT\System.


 I hope you will be having these points in mind, while coming accross apt situations...

See u on my next post... Biiiii....

Monday 12 August 2013

PreSaveAction for Sharepoint Form Fields Validations

HI All,

 Today I will share you one very useful in-built JavaScript functionality, which is used for validating the form fields. Obviously u can go for “Calculated columns”, “Column Validations”, “List Validations” for some validations and required result.

But,,,,,,, Sometimes, the requirement could be quite complicated..

Eg :
#“Start Date” less than “End Date”
##Out of two fields, if one is filled then save the item else cancel.
Likewise this can be used for many validations which we cannot do OOTB.

Ok, now I will give the basic code,
if the requirement is “End date” should not be earlier than “Start Date”..

========================================================================
<script language=”javascript” type=”text/javascript”>
function PreSaveAction()
{
var date1 = getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”Start Date”);
var date2 = getTagFromIdentifierAndTitle(“INPUT”,”DateTimeFieldDate”,”End Date”);
var arrDate1 = date1.value.split(“/”);
var useDate1 = new Date(arrDate1[2], arrDate1[1]-1, arrDate1[0]);
var arrDate2 = date2.value.split(“/”);
var useDate2 = new Date(arrDate2[2], arrDate2[1]-1, arrDate2[0]);
if(useDate1 > useDate2)
{
alert(“The End Date cannot happen earlier than the Start Date”);
return false; // Cancel the item save process
}
return true; // OK to proceed with the save item
}
function getTagFromIdentifierAndTitle(tagName, identifier, title) {
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == “” || tempString.indexOf(identifier) == tempString.length – len)) {
return tags[i];
}
}
return null;
}
</script>
========================================================================

U can just do some simple tweaks in this piece of code and can do magicsss :)
See you next time… byyyeee..:)

JavaScript for DateTime Picker - SharePoint

Hi All,
 In my previous post, i shared about the "onchange" event.
If u had tried this on "DateTime" field, u would have faced the difficulty.
I faced the same and it took time for me to sort this out:P

Ok, i will tell u the tweak to make that working.

In a Datetime picker there are two ways of changing the date.
Condition 1) Picking from the Image which is on the right side of the control.
Condition 2) Directly changing the date in the Textbox.

"onchange" works for the condition 2).

But condition 1) is mostly preferred by the users.

For this situation we have to use "onvaluesetfrompicker" event. I will show you one sample code.

There is one Datetime picker field - "Publishing date". This field should not be less than today. If it is less then, an alert has to come and "Save" button should be hided.

========================================================================

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
<script language="javascript">

$(document).ready(function()
{
 today = new Date();

getTagFromIdentifierAndTitle("input","DateTimeFieldDate","Publishing Date").onvaluesetfrompicker = function() {ChangeEvent1()}; //This checks condition 2
getTagFromIdentifierAndTitle("input","DateTimeFieldDate","Publishing Date").onchange = function() {ChangeEvent1()};  //This checks condition 1

});


function ChangeEvent1()
{

var dateSelected = document.getElementById("ctl00_m_g_5cee28ab_e950_4028_95bc_0cb0d55ec872_ctl00_ctl05_ctl09_ctl00_ctl00_ctl04_ctl00_ctl00_DateTimeField_DateTimeFieldDate");
var pubdate = new Date(dateSelected.value);

if(pubdate<=today)
{
$("input[value$='Save']").attr('disabled', true); //button hides
alert("Publishing Date should be greater than Today's Date");
}

else
{
$("input[value$='Save']").attr('disabled', false); //button shown
}
}

function getTagFromIdentifierAndTitle(tagName, identifier, title) {
 var len = identifier.length;
 var tags = document.getElementsByTagName(tagName);
 for (var i=0; i < tags.length; i++) {
 var tempString = tags[i].id;
 if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {
 return tags[i];
 }
 }
 return null;
}

</script>
========================================================================

Have a great day :)
See u all on the Next post :D

JavaScript onchange event - SharePoint

Hello guys,
  Today also, I am going to share one interesting thing in JavaScript combined with SharePoint.

Let’s say, U r working on an Edit form. There is a Text box field(Title) and u need to do something when there is a change in the Textbox value.
How to do it????

Hmm, there is an JavaScript event to check this – “onchange”.


========================================================================
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
<script language="javascript">

$(document).ready(function()
{

getTagFromIdentifierAndTitle("input","TextField","Title").onchange = function() {ChangeEvent()};

});


function ChangeEvent()
{

//do something
alert('hi');
}

function getTagFromIdentifierAndTitle(tagName, identifier, title) {
 var len = identifier.length;
 var tags = document.getElementsByTagName(tagName);
 for (var i=0; i < tags.length; i++) {
 var tempString = tags[i].id;
 if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {
 return tags[i];
 }
 }
 return null;
}

</script>
========================================================================

Check the below post for validating different type of fields like Choice (dropdown),Lookup etc..
http://blogs.msdn.com/b/sharepointdesigner/archive/2007/06/13/using-javascript-to-manipulate-a-list-form-field.aspx

Have a good Day :)


Monday 5 August 2013

Excel Sheet to SharePoint List

Hi All,
Today i am going to share one useful and interesting thing about, Excel and Sharepoint...

Okay, Let's come to the situation...
U have a Sharepoint List and U are asked to generate an Excel spreadsheet from that..
AAAhh, i know u will say easyyyyy.. 
Single step : Ribbon control- Export to Excel :)

Ok Now, the other way around.. U r given an Excel sheet and asked to make a Sharepoint List from that...
There are some ways, 
U will first think to create a List and go to the datasheet view of that.. Copy paste that data into this view...


HMMM, That’s good.. But there is one easy and clean way to do this....
*****************************************************************************************
Make that Excel data into a table.. Steps are below

1) Select all the Data in the sheet.
2)Go to Insert Tab and Select "Table".
3)Save this.

Tip: U have to change the Default headers “Column1,Column2..”. This will be reflected as Column names in Sharepoint List...

Ok Now, Go to Sharepoint à Site ActionsàMore OptionsàListàImport Spreadsheet

1)Try creating a list based on this template
2)Next screen u will be asked to give the file location. There specify the location of Excel Sheet and select “Import”.
3)Your Excel will open with this dialog box. You can select the range of the data and range type from the dropdowns. Finally click on “Import”.
4)You have got your Sharepoint List ready….


Happy SharePointinggggg :DJ

Saturday 3 August 2013

Trick for Fixing Broken Sharepoint Pages

Hi All,

At times you may need to recover a page after a code change makes it impossible to render, or you might have some orphaned web parts (web parts that have been closed and not deleted) on a page that you need to restore.

You can try to open the page in Sharepoint designer in Maintenance mode.

To enter into Maintenance Mode ,
1) Usual Way : Open the browser and select the Page Tab on the ribbon menu. Then click the Edit Properties button. once the Menu changes, click the Open Webpart Page in Maintenance view link.

But, there may be some times , the page wouldn't get render due to some code changes done.

2) So the easiest way is by appending ?Contents=1 to the end of the page URL- for example. http://SharepointDesigner2010/default.aspx?Contents=1

Here you can delete the broken webpart to restore the page..



Thats it :D :) :)



Saturday 20 July 2013

Programmatically Checking the SharePoint List Attachments in a Synchronous Event

Hellooooo!!!!!
 Hope things are going great.
 I am working on Item Updating event receiver for a custom list : listitem , afterproperties , beforeproperties , blah , blah, blah.. And I am on the last step, and it is to find whether attachment is associated with the current item..

Simple????!!!!!    Lets see..
int attachmentcount1 = Convert.ToInt32(properties.BeforeProperties["Attachments"]);
int attachmentcoun2 = Convert.ToInt32(properties.ListItem["Attachments"]);
int attachmentcount3 = Convert.ToInt32(properties.AfterProperties["Attachments"]);
what I am getting, “0” on all the three variables..
So wat is the fix, to check for the “Attachments” in the “Synchronous” event..


public class MyEventReceiver : SPItemEventReceiver
 
{
HttpContext currentContext;

public MyEventReceiver()
{
currentContext = HttpContext.Current;
}
   
public override void ItemAdding(SPItemEventProperties properties)
 {
         
if (currentContext != null)
   {
       if (currentContext.Request.Files.Count > 0)
      {
            // Thers are attachments

      }
else
      {
        // no attachments
      }
   }                        
  }
 }


This works on the case of Item Adding also.. :D

See you again.. Cyaa...

Monday 15 July 2013

Hide "Upload Multiple Documents" tab in the Ribbon - SharePoint

Hello all,
Today i will tell you one small , but very intersting thing regarding the ribbon control..

In this post, i have told u how to hide a ribbon button for a specific library with ease.Now, The same thing but in a different requirement..

U r asked to hide "Upload Multiple Documents" tab which is a dropdown of "Upload Document" tab.




 My previous post was about hiding a entire button, not a dropdown option in it :P

No need to panic.. just copy the below lines and paste it in your Content Editor WebPart(refer this for help).


<style type="text/css">

#Ribbon\.Documents\.New\.AddDocument\.Menu\.Upload\.UploadMultiple-Menu32

{
display:none !important;
}

</style>


Now u can see, the dropdown option is gone... :D

Cooooooooool:D

Saturday 6 July 2013

GUID of a SharePoint List or Library


One fine Day,
 We were woking on something related to triggering a workflow through an event handler. We needed GUID of the List in that process. hhhmmmmmm.. How to get that?

My friend was trying something through object model or through JSOM or Poershell to get the GUID..
Any other ways???

Obviously Yes, I got one easy Detour...


Navigate to that SharePoint list in browser. Select the List Settings in Ribbon and copy the Url from the browser address into Notepad.

At the end of the URL, u will see something like:     List=%7B69238662%2D566D%2D4995%2D9927%2D5C47F16B22DB%7D

In that  

replace “%7B” with “{”
replace all “%2D” with “-“
replace “%7D” with “}”

Now you have the GUID of the list:



{69238662-566D-4995-9927-5C47F16B22DB}


Piece of cake...... Have a great day..

Saturday 29 June 2013

Hide the Ribbon Buttons for a single SharePoint Library


This post is about hiding the buttons in the ribbon panel of ur Sharepoint portal(2010)...


Lets say, Ur boss wants u to hide the "Upload" button in the ribbon panel , but for a single Library..

Single Library ..... hmmmmmm.. ok lets check it out...

Googling starts  -->  U refer this article from MSDN , but this will lead to hide the button for the whole site by activating a feature..

What can u do?????

Ok let us try something in Javascript .. open the document library page, add a content editor webpart to ur page.. add this Javascript to the webpart..

<style type="text/css">
#Ribbon\.Documents\.New\.AddDocument-Large
{
display: none !important;
}

</style>

Save the changes...

And u will get to see the above result...
ABRACADABRA..... Upload button is Gone....

Work is done within 2 mins... Enjoy ..... Have a great day:):):)