Showing posts with label Sharepoint. Show all posts
Showing posts with label Sharepoint. Show all posts

Wednesday, May 15, 2013

jQuery SPServices to get current user sharepoint groups

In this post we are going to get information of all the sharepoint user groups in which current user belongs using SPServices.

Below is the jQuery code snippet which will do this action.
In this example we will be looping all the groups which the current user is present and adding it to the variable  loggedinUserGroup.

// add the ref of jQuery file
<script type="text/javascript" src="/style library/jquery-1.7.2.js"></script>
// add the ref of jQuery SPServices file
<script type="text/javascript" src="/style library/jquery.SPServices-0.7.0.min.js"></script>
<script type="text/javascript">
var loggedinUserGroup;
$(document).ready(function() {
 Getrolesforuser();
 alert(loggedinUserGroup);
});
function Getrolesforuser()
{
 loggedinUserGroup="";
 $().SPServices({ 
  operation: "GetGroupCollectionFromUser", 
        userLoginName: $().SPServices.SPGetCurrentUser(), 
        async: false, 
        completefunc: function(xData, Status)
        {
         $(xData.responseXML).find("Group").each(function()
         {
              if(loggedinUserGroup=="")
              {
                  loggedinUserGroup = $(this).attr("Name");
              }
              else
              {
                  loggedinUserGroup = loggedinUserGroup + "\n"+ $(this).attr("Name");
              }
         });
               
  }
 });
}

</script>

Hope this helps... Follow this page for more updates.
Related post- jQuery spservices to get current user name for sharepoint site
Related post- How to display user information using ProfilePropertyLoader in sharepoint

Saturday, February 23, 2013

TreeView with the nodes as document library names using Sharepoint2010


In this post we are going to construct a TreeView with the nodes as sharepoint document library names using Sharepoint2010
Root Node will be the Site Url. 

Before we proceed with the code add a treeview with ID as myTreeView to your page. 
Below is the code snippet.

try
            {
                using (SPSite site = new SPSite("<<http://site Url>>"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPListCollection docLibraryColl = web.GetListsOfType(SPBaseType.DocumentLibrary);

                        List<string> docLibrariesList = new List<string>();
                        foreach (SPList list in docLibraryColl)
                        {
                            if (!list.Hidden)
//if you don’t want style library and Forms templates then use below condition instead of above
                            //if (!list.Hidden && list.title != "Style Library" && list.title != "Form Templates")
                            {
                                SPDocumentLibrary doclib = (SPDocumentLibrary)list;
                                string docLibTitle = doclib.Title;
                                int docsCount = doclib.ItemCount;
                                docLibrariesList.Add(docLibTitle);
                            }
                        }

                        TreeNode RootNode = new TreeNode();
                        //Here we are binding the root node as Site Url
   RootNode.Text = "<<http://site url>>";

                        foreach (string docLibrary in docLibrariesList)
                        {
                            TreeNode childNode = new TreeNode();
                            childNode.Text = docLibrary;
                            RootNode.ChildNodes.Add(childNode);
                        }
   // myTreeView is treeview controls ID present on the aspx page
                        myTreeView.Nodes.Add(RootNode);

                    }
                }
            }
            catch (Exception ex)
            {

            }


Hope this helps..

Tuesday, December 4, 2012

How to Add a Favicon to a SharePoint Site or any regular website

In this post we are going to Add a Favicon to a SharePoint Site or any regular website.



A favicon is an image(.ico extension) associated with a particular Web page or a complete Web site. Favicon (pronounced fav-eye-con) is short for 'Favorites Icon.'
In Internet Explorer the Favicon is displayed on the Address bar and in the Tab.

Below are the steps to achieve this.
Step1:
Create a .ico image file with the below link by uploading your Logo.
Once the .ico file is created save it as favicon.ico and make sure it is of 16*16 Pixels.

Step2:
Adding the favicon reference to our website.
Add the below reference in the <head> section of your master page so that favicon will be displayed across the website. Or if you want to show it on particular page only, then add it to respective page itself.
<link rel="shortcut icon" href="your_path_to_favicon/favicon.ico" type="image/vnd.microsoft.icon" />

In Sharepoint to achieve the same we can use either the above code snippet or we can make use of below Sharepoint control SPShortcutIcon.
<SharePoint:SPShortcutIcon ID="SPShortcutIcon1" runat="server" IconUrl="/_layouts/images/favicon.ico"/>

You can give the IconUrl reference by placing the image either in the 14 hive or in the Image Library of your site collection. Both will workout.


Hope this helps...

Wednesday, September 26, 2012

How to use XSLT in sharepoint 2010


In this post we are going to see how to use XSLT in Sharepoint 2010, to display the list data in a customized way on a webpart page.
This article will be helpful for those who are just starting with XSLT in MOSS 2010.

Consider the below list EmployeeDetails







At the end of this post we will be displaying the above list data as below in the web part page.
Expected Result:











Step1:
To start with, whenever we talk about creation of XSLT we must be ready with the HTML markup how we want to display.
In order to achieve the above expected result I have created the HTML markup as below.

<table border="1">
        <tr>
            <td rowspan="3" valign="top" width="30%">
                <img src="" />
            </td>
            <td style="text-align: left" valign="top" width="70%">
                Name
           </td>
        </tr>
        <tr>
            <td style="text-align: left" valign="top" width="70%">
                Skills
            </td>
        </tr>
        <tr>
            <td style="text-align: left" valign="top" width="70%">
                Summary
            </td>
        </tr>
</table>

Step2:
Now let’s start with the creation of XSLT. The above highlighted yellow fields will be replaced by XSL values of the fields.
Lets create the below XSLT Template with the name MyCustomStyle.

<xsl:template name="MyCustomStyle" match="Row[@Style='MyCustomStyle']" mode="itemstyle">
    <table border='1'>
      <tr>
        <td rowspan="3" valign="top" width="30%">
          <img>
            <xsl:attribute name="src">
              <xsl:value-of select="substring-before(@UserImage,',')" />
            </xsl:attribute>
          </img>
        </td>
        <td style="text-align: left" valign="top" width="70%">
          <h3>
            <xsl:value-of select="@UserName" />
          </h3>
        </td>
      </tr>
      <tr>
        <td style="text-align: left" valign="top" width="70%">
          <xsl:value-of disable-output-escaping="yes" select="@UserSkillset" />
        </td>
      </tr>
      <tr>
        <td style="text-align: left" valign="top" width="70%">
          <xsl:value-of disable-output-escaping="yes" select="@UserSummary" />
        </td>
      </tr>
    </table>
</xsl:template>

Step3:
Now we are going to add this XSL Template to a existing XSLT(ItemStyle) present in XSL Style Sheets which is present under Style Library.
Download the ItemStyle xslt and add the above template at the end of the style sheet.
You can even create a new XSLT rather than adding in any existing one.

Step4:
With the above steps we are ready with our XSLT changes and ready to add this to a webpart page.
      A)     Create a webpart page.
      B)      Add a Content Query Webpart.
      C)      Open the tool pane of the above webpart(Edit Webpart).
      D)     Select the list EmployeeDetails in the source section.
      E)      Expand the Styles Section which is present under Presentation Group.
      F)      In the Item Style Drop down, you will be able to see the XSLT template name MyCustomStyle and select it.
      G)     Once after you select our custom created style, You must be able to see the green colored highlighted variables present in XSLT in the Fields to display section.
      H)     Add the respective Field internal name to the respective Variables.
       I)        Finally Click Apply and Press Ok button.

Your expected result will be available now.


Hope this helps...



Monday, September 3, 2012

What is a Property Bag in sharepoint 2010


In this post we are going to discuss what is Property Bag in sharepoint 2010.

Basically this property bag is a feature available in Windows SharePoint Services 3.0.
It is a Hash Table where in we will maintain key-Value information. The basic fundu of this Property bag is to add the properties to the objects of the SharePoint site.

Why Property bag instead of web.config?
While defining the property bag we said it is an Hash Table where we will maintain Key-Value information. The question arises here is, when we can maintain key-value information in web.config(appsettings section-Ref below appsettings) why should we go for Property bag.

<configuration>
    <appSettings>
        <add key="MyKey" value="MyValue" />
    </appSettings>
</configuration>

And the answer is, When we add key-value in web.config which will become common to the entire web application.

What, if there is any setting specific to individual site in the web application?
In this scenario we will have to adopt either of the below cases.
è        1) Maintain multiple key-value entries in web.config.
è        2) Use sharepoint property bag. With this we can store the properties in several levels like SPFarm, SPWebApplication, SPSite, SPWeb and SPList.

Property Bag in sharepoint 2010:
There is no specific user interface available to add/modify the property bag settings. We have to do it through object model.
Also there is an option available in SharePoint designer to add/modify the property bag settings. Go to Site -> Site Settings. click on the Parameters tab.  On this tab, you will be able to manipulate all of your custom property bag values.

Add/Modify Property bag with Object model:
In the below example we are adding/reading/updating/deleting the properties at the farm level. Similarly we can do it for rest all the scopes mentioned above.

Adding:
SPFarm myFarm = SPFarm.Local;
myFarm.Properties.Add("myFarmKey", "myFarmValue");
myFarm.Update();

Reading:
SSPFarm myFarm = SPFarm.Local;
if (myFarm.Properties != null && myFarm.Properties.Count > 0)
{
if (myFarm.Properties.ContainsKey("myFarmKey"))
{
String myFarmValue= myWebApplication.Properties["myFarmKey"];
}
}

Updating:
SPFarm myFarm = SPFarm.Local;
myFarm.Properties["myFarmKey"] = "myNewFarmValue";
myFarm.Update();

Deleting:
SPFarm myFarm = SPFarm.Local;
myFarm.Properties["myFarmKey"] = null;
myFarm.Properties.Remove("myFarmKey");
myFarm.Update();


Hope this helps…

Tuesday, September 27, 2011

How to programmatically send an email in SharePoint using C#


In this post I will discuss about Sending an e-mail in SharePoint 2010 using C#

public static bool SendMail(string Subject, string Body, bool IsBodyHtml, string From, string To, string Cc, string Bcc)
        {
            bool mailSent = false;
            try
            {
                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Host = SPContext.Current.Site.WebApplication.
                OutboundMailServiceInstance.Server.Address;
                MailMessage mailMessage = new MailMessage(From, To, Subject, Body);
                if (!String.IsNullOrEmpty(Cc))
                {
                    MailAddress CCAddress = new MailAddress(Cc);
                    mailMessage.CC.Add(CCAddress);
                }
                if (!String.IsNullOrEmpty(Bcc))
                {
                    MailAddress BCCAddress = new MailAddress(Bcc);
                    mailMessage.Bcc.Add(BCCAddress);
                }
                mailMessage.IsBodyHtml = IsBodyHtml;
                smtpClient.Send(mailMessage);
                mailSent = true;
            }
            catch (Exception) { return mailSent; }
            return mailSent;
        }

Hope this helps..
Next Post- Programatically set the welcome page in Sharepoint

Tuesday, September 6, 2011

How to Create a Custom Timer Job in SharePoint 2010


Creating Custom Timer Job in SharePoint 2010

Quantcast
In this post I will show you how to create Custom Timer Job in SharePoint 2010 but you must know this post is based on Creating Custom SharePoint Timer Jobs ,So let us start
Create Custom List and name it  ListTimerJob

Open Visual Studio 2010 >File > New >Project >SharePoint 2010>Empty SharePoint Project. >Name it Custom_TimerJob>Ok

Check Deploy as farm solution>Finish

create a class that inherits from the Microsoft.SharePoint.Administration.SPJobDefinition class. To implement this class, you need to create a few constructors and override the Execute() method as following

01
namespace DotnetFinder
02
{


03
    class ListTimerJob : SPJobDefinition
04
    {


05
         public ListTimerJob()
06
  


07
            : base()
08
        {


09
  
10
        }

11
  
12
        public ListTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)

13
  
14
            : base(jobName, service, server, targetType)

15
        {
16
  


17
        }
18
  


19
        public ListTimerJob(string jobName, SPWebApplication webApplication)
20
  


21
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
22
        {


23
  
24
            this.Title = "List Timer Job";

25
  
26
        }

27
  
28
        public override void Execute(Guid contentDbId)

29
        {
30
  


31
            // get a reference to the current site collection's content database
32
  


33
            SPWebApplication webApplication = this.Parent as SPWebApplication;
34
  


35
            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
36
  


37
            // get a reference to the "ListTimerJob" list in the RootWeb of the first site collection in the content database
38
  


39
            SPList Listjob = contentDb.Sites[0].RootWeb.Lists["ListTimerJob"];
40
  


41
            // create a new list Item, set the Title to the current day/time, and update the item
42
  


43
            SPListItem newList = Listjob.Items.Add();
44
  


45
            newList["Title"] = DateTime.Now.ToString();
46
  


47
            newList.Update();
48
  


49
        }
50
}


51
}
As you can see this job just add a new item to a ListTimerJob list every time it’s executed
Now that you have the job built> Right click on the Features >Add Feature

Right click on the Feature1 ” you can rename the Feature1 to any name” > Add Event Receiver

As you can see the event Receiver class inherits from the Microsoft.SharePoint.SPFeatureReceiver and This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade. But we only need FeatureActivated & FeatureDeactivated event handler to install/uninstall our custom timer job as following

01
namespace DotnetFinder.Features.Feature1
02
{


03
[Guid("9a724fdb-e423-4232-9626-0cffc53fb74b")]
04
public class Feature1EventReceiver : SPFeatureReceiver

05
    {
06
        const string List_JOB_NAME = "ListLogger";

07
        // Uncomment the method below to handle the event raised after a feature has been activated.
08
  


09
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
10
        {


11
            SPSite site = properties.Feature.Parent as SPSite;
12
  


13
            // make sure the job isn't already registered
14
  


15
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
16
            {


17
  
18
                if (job.Name == List_JOB_NAME)

19
  
20
                    job.Delete();

21
  
22
            }

23
  
24
            // install the job

25
  
26
            ListTimerJob listLoggerJob = new ListTimerJob(List_JOB_NAME, site.WebApplication);

27
  
28
            SPMinuteSchedule schedule = new SPMinuteSchedule();

29
  
30
            schedule.BeginSecond = 0;

31
  
32
            schedule.EndSecond = 59;

33
  
34
            schedule.Interval = 5;

35
  
36
            listLoggerJob.Schedule = schedule;

37
  
38
            listLoggerJob.Update();

39
  
40
        }

41
  
42
        // Uncomment the method below to handle the event raised before a feature is deactivated.

43
  
44
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

45
        {
46
            SPSite site = properties.Feature.Parent as SPSite;

47
  
48
            // delete the job

49
  
50
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)

51
            {
52
  


53
                if (job.Name == List_JOB_NAME)
54
  


55
                    job.Delete();
56
  


57
            }
58
  


59
}
60
  

61
   }
Before Deploying you should select the right scope of the Feature in other words in which scope you will activate the Feature(Farm,Site,Web,WebApplication) in our case we will activate Feature1 on Site which is mean Site Collection.

Note : if you trying to activate the feature in the wrong scope will get the following error

Now let us deploy our custom timer job >Right Click on Custom_TimerJob project > Click Deploy

Open now your SharePoint site and select ListTimerJob List and you should see something similar to the following image


Our custom timer job is working fine now you can go and check it and modify the schedule as following
Go to SharePoint 2010 central administration >Monitoring >in the Timer Jobs Section Select Review Job Definitions
and you should See our Custom Timer Job

Click on it and you should see Edit Timer Job Page ,Modify Timer Job schedule based on your requirement
Note : you can also modify schedule of your custom Timer Job from the code but you need to add one of the following class in FeatureActviated Event Handler as following

After Specific Minutes use SPMinuteSchedule class
Hourly use SPHourlySchedule class
Daily use SPDailySchedule class
Weekly use SPWeeklySchedule class
Monthly use SPMonthlySchedule class

Hope this helps...

Popular Posts