Search This Blog

Monday, May 23, 2011

Adding Calculated Field in SharePoint List Programmatically


To Add Calculated Field in SharePoint List you need to use the following code snippet:

string URL = "SITE_URL";
            string strListName = "LIST_NAME";
            string strCalculatedFieldname = "CalcField";
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(URL))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        SPList objSPList = web.Lists[strListName];
                        objSPList.Fields.Add(strCalculatedFieldname, SPFieldType.Calculated, false);
                        SPFieldCalculated CalcField = (SPFieldCalculated)objSPList.Fields[strCalculatedFieldname];
                        CalcField.Formula = @"=CONCATENATE("" Calculated : "",[Title])";
                        CalcField.Update();
                        objSPList.Update();
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });

Error: moss MA not found


Error: moss MA not found

If facing this error, then sure solution for this is to restart the following services.
  • Forefront Identity Manager Service
  • ForeFront Identity Manager Synchronization Service

Tuesday, May 17, 2011

Sorting SPListItemCollection using LINQ

Using LINQ to sort SPLiStItemCOllection:

SPList objRelationShipList;
SPListItemCollection objRelationShipListItems;
objRelationShipList = SPContext.Current.Web.Lists["ListName"];
objRelationShipListItems = objRelationShipList.Items;
List<SPListItem> results = (from SPListItem item in objRelationShipListItems           
                            orderby item.ID
                            select item).ToList();
foreach(SPListItem in results)
{
....
}

Cheers

Monday, May 16, 2011

Show Attachments in Custom List Form - Display Form using SharePoint Designer

Basically when you clone the list display form in SharePoint "dispform.aspx" to show up custom list form you will not able to able to see some of the controls like attachments . 


Here is the workaround to achieve this:



To show up attachments just add this line of code using SharePoint designer

<SharePoint:AttachmentsField ControlMode="Display" FieldName="Attachments" runat="server" Visible="true"/>
and this will show you the attachments for the list items exists.

Tuesday, May 10, 2011

How to delete all items from site recycle bin permanently : Sharepoint 2007

We often need to empty the recycle bin of the site collection in sharepoint to free up space.Now, in sharepoint, there are 2 stages in the recycle bin.The first stage is the user recycle bin where all the deleted items are added when they are deleted in the site.
The second stage is the admin recycle bin and is used to retain all deleted items for a configurable period of time (usually 30 days).In order to delete all the items from the admin recycle bin permanently,we have to first move the items to the second stage and then delete them permanently

We can use the following code to accomplish the same:

private void btnEmptyRecyclebin_Click(object sender, EventArgs e)
        {
            string siteURL = txtSiteUrl.Text;
            EmptySiteRecycleBin(siteURL);
        }

        public void EmptySiteRecycleBin(string siteURL)
        {
           
            try
            {

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(siteURL))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;

                            site.RecycleBin.MoveAllToSecondStage();

                            //Empty the items from the SiteRecycleBin (the second stage recycle bin)                          
                            if (site.RecycleBin.BinType == SPRecycleBinType.SiteRecycleBin)
                            {
                                //Delete all the items                         
                                site.RecycleBin.DeleteAll();
                            }




                        }

                    }

                });

                MessageBox.Show("Recycle bin cleaned up!!.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while emptying recycle bin.");
              

            }


        }


The code first moves all items to the second stage and then deletes them permanently.

This is the code for a windows application but can also be used in sharepoint after making a few changes.



Monday, May 9, 2011

Get “RichTextField” Control Value in SharePoint 2007

When building custom application pages in SharePoint you may need to put the BaseFieldControl objects for a SPListItem. If the application page is performing add or edit functions you will need to iterate through the Fields and get values from the BaseFieldControls. It works well for most of the BaseFieldControl but there’s some problem to get value from RichTextField.
Here is the right way to get value back from RichTextField control in SharePoint:


private string GetRichTextBoxControlValue(Control control)
        {
            string returnValue = string.Empty;

            foreach (System.Web.UI.Control ctrl in control.Controls)
            {
                if (ctrl is TemplateContainer)
                {
                    foreach (System.Web.UI.Control templateCtrl in ctrl.Controls)
                    {
                        if (templateCtrl is HtmlContainerControl)
                        {
                            foreach (System.Web.UI.Control hdnCtrl in templateCtrl.Controls)
                            {
                                if (hdnCtrl is HtmlInputHidden)
                                {
                                    returnValue = ((HtmlInputHidden)hdnCtrl).Value;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return returnValue;
        }

Save publishing site a template

By default share point doesn't allow to save the site as template.

To save site as template open the "_layouts/savetmpl.aspx" from site setting and save the site as template.

Handling Access Denied / Authorization Failures

Many a times we are into a situation that we have to handle Authorization Failures. Let’s see how we can handle it by using SPUtility.

·         SPUtility has a method that handles “Access Denied” exceptions and redirects the user to the “Access Denied” page. This method takes Exception object as a parameter. If any kind of Security Exception occured than this methos will handle it as shown below:
        try {
                 //Code
             }
             catch (SecurityException secExptn)
             {
                 SPUtility.HandleAccessDenied(secExptn);
             }

·         SPUtility.Redirect Method can also be used if you want to redirect the user to Sharepoint AccessDenied Page. We can use this method as shown below:

SPUtility.Redirect(SPUtility.AccessDeniedPage,SPRedirectFlags.RelativeToLayoutsPage,httpContext);

·         SPUtility.EnsureSiteAdminAccess(objSPWeb);

This method can be used to determine whether the current user is a site administrator of the specified web or not. If the current user is not the administrator than it will prompt for the administrator credentials and if the user fails to supply the administrator’s credentials than it will open the error page. It will take SPWeb onject as a parameter.

·         SPUtility.SendAccessDeniedHeader(SecExp);

This method is used to send an HTTP 401 (Access Denied) header to the user.
This method will prompt for the new credentials to the user. If the user fails to supply the correct credentials than this methods takes the user to “Access Denied” page.

Monitor User Profile Changes

Hi,

Recently , I have visited a good post for tracking the user profile changes.SharePoint does not support out of box any functionality to monitor the changes happens in the user profile. This need coding and custom development.The below details will help you for retrieve the changes done in the user profile.

UserProfileManager objuserProfileManager = new UserProfileManager(ServerContext.Default);
UserProfile userProfile = objuserProfileManager.GetUserProfile("Login name");

DateTime startDate = DateTime.Today - 5;

UserProfileChangeQuery userProfileChangeQuery = new UserProfileChangeQuery(true, true);
UserProfileChangeToken userProfileChangeToken = new UserProfileChangeToken(startDate);
userProfileChangeQuery.ChangeTokenStart = userProfileChangeToken;
userProfileChangeQuery.UserProfile = true;
userProfileChangeQuery.PersonalizationSite = true;
userProfileChangeQuery.SingleValueProperty = true;
userProfileChangeQuery.MultiValueProperty = true;
userProfileChangeQuery.Colleague = true;
userProfileChangeQuery.Update = true;
userProfileChangeQuery.Add = true;
userProfileChangeQuery.Delete = true;
userProfileChangeQuery.SiteMembership = true;
userProfileChangeQuery.Anniversary = true;

UserProfileChangeDictionary userProfileChangeDictionary = userProfile.GetColleagueChanges(userProfileChangeQuery);

Dictionary.Enumerator userProfileChangeCollection = userProfileChangeDictionary.GetEnumerator();
while (userProfileChangeCollection.MoveNext())
{
UserProfileChangeCollection userProfileChanges = userProfileChangeCollection.Current.Value;
foreach (UserProfileChange userProfileChange in userProfileChanges)
{
if (userProfileChange is UserProfileSingleValueChange)
{
UserProfileSingleValueChange propertyChange = (UserProfileSingleValueChange)userProfileChange;
//propertyChange will have the new and old value of profile fileds
}
else if (userProfileChange is UserProfileMultiValueChange)
{
UserProfileMultiValueChange propertyChange = (UserProfileMultiValueChange)userProfileChange;
//propertyChange will have the new and old value of profile fileds
}
else if (userProfileChange is UserProfileWebLogChange)
{
UserProfileWebLogChange listChange = (UserProfileWebLogChange)userProfileChange;
//listChange will have the newly added/modifed list item url
}
}
}

Friday, May 6, 2011

Modifying Sharepoint Web.Config Programmatically


Web.config modification is not an easy task, a small mistake can mess all the web.config and application can go dumb, so while modifying the web.config extra precaution is needed. This post is written keeping in mind how you can edit the web.config in most easiest way , by focusing on very common mistakes committed by most.
To modify web.config programmatically you need to use SPWebConfigModification - it updates columns in the Object table with your values and SharePoint modify web.config itself across all servers. Unfortunately, this method is really poor documented, so you need to Google for the samples.
So here is the code snippet: It shows the entry that modifies the Log4Net entry in the web.config
Public void CreateModification ()
{
SPWebConfigModification modification = new SPWebConfigModification();
modification.Owner = "OwnerOfTheModification";
modification.Sequence = 0;
modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
modification.XPath = "configuration";
modification.Name = "log4net [@debug='true']";
modification.Value = @"<Log4Net>
<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<appendToFile value="true" />
<datePattern value="-dddd" />
<file value="c:\Log.txt" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t]%-5p %c [%x] - %m%n" />
layout>
<rollingStyle value="Date" />
appender>
<logger name="Web.Logging">
<appender-ref ref="RollingLogFileAppender" />
<level value="ALL" />
logger>
<root>
<appender-ref ref="RollingFileAppender" />
<level value="ALL" />
root>
log4net>";
SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}
Explaination of the code
The Modification requires some important values , if not correctly set can fail the whole process.
Name
Gets or sets the name of the attribute or section node to be modified or created. This is an XPath expression relative to the parent node (specified by the Path property). Sometimes this is nothing more than the name of the new or existing node you want to change. This is to be set wisely because in 90% of the cases the removing process fails because it is not kept correct .
Every modification has an Owner. Every change made the web.config can be assigned an owner. The owner is nothing more than a string value that uniquely identifies your changes from any other changes that have been made, or may be made in the future. So choose wisely the name so that it could remain unique to your entries.
Path
Gets or sets the XPath expression that is used to locate the node that is being modified or created. This value usually contains simple XPath expression to the parent node of the item you intend to change or create. For example: “system.web/httpHandlers” or “system.web/customErrors”.
Value
Gets or sets the value of the item to set. This is usually the complete xml element tag or attributes value for the node specified in the Name property (or as the name parameter in the constructor).
Type
Gets or sets the type of modification for this object instance. The three values available are defined via the SPWebConfigModification. SPWebConfigModificationType and are EnsureChildNode, EnsureAttribute, and EnsureSection. I have used only EnsureChildNode and it works fine. Not for sure but entries made using the EnsureSection cannot be removed.
Sequence
Gets or sets the sequence number of the modification. I have always used zero (0) for this.

Note: For applying the modifications , we can perform it in two different ways :
  1. SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
  2. SPWebApplicationObject.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
Since I have found many Posts saying which one works, but I'll suggest try with both the ways and check it out(for me point 1 works)