Monday, November 21, 2011

Sharepoint 2010 - Get Current User's sharepoint group information using javascript.

Goal

To retrieve the SharePoint Group information of Current User logged in using Javascript.

Solution

  1. Dowload the "jquery.SPServices-0.6.2.js" file from CodePlex. Save the file somewhere. I save it in "Style Library".
  2. Use the below given script to get the list of SharePoint Group using javascript.
<!--http://www.jquery.com-->
<script>    !window.jQuery && document.write('<script src="http://code.jquery.com/jquery-1.4.2.min.js"><\/script>');</script>
<!--http://spservices.codeplex.com/releases/view/64390-->
<script language="javascript" tye="text/javascript" src="/style library/jquery.SPServices-0.6.2.js"></script>
<!--Custom Script-->
<script language="javascript" tye="text/javascript">
    $(document).ready(function () {

        $().SPServices({
            operation: "GetGroupCollectionFromUser",
            userLoginName: $().SPServices.SPGetCurrentUser(),
            async: false,
            completefunc: function (xData, Status) {
                //Shows the XML returned from the server
                alert(xData.responseXML.xml);
                //Replace the "<<SHAREPOINT GROUP NAME>>" with your group name will tell that user is on a particular group or not.
                if ($(xData.responseXML).find("Group[Name='<<SHAREPOINT GROUP NAME>>']").length == 1) {
                    alert('User in a group');
                }
            }

        });

    });
</script>
This should be it. Happy Coding.

Saturday, November 12, 2011

JQuery - Destroy the cookies on browser close.

Challenge

Trying to destroy the cookies once the browser is closed. I tried a lot to find on internet doing that same thing using C# but finally i figured out using JQuery.



Solution

Please try the below given block to make this work. I found this on internet somewhere i forgot the place so using this same block.
<html>
<head>
    <title>Starting Cookie Page</title>
    <script type="text/javascript">
        function createCookie(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        }

        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

        function eraseCookie(name) {
            createCookie(name, "", -1);
        }
    </script>
    <script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body onload="
$(document).ready(function() {alert('loaded');});">
    <p>
        <button onclick='createCookie("ccSiteVisited", "1", "");'>
            Create Cookie</button>
        <button onclick='alert(readCookie("ccSiteVisited"));'>
            Read Cookie</button>
        <button onclick='eraseCookie("ccSiteVisited");'>
            Erase Cookie</button>
    </p>
    <p>
        Please note that once you set the cookie, that the cookie is maintained in all further
        browser instances you start.</p>
    <p>
        However, if you close all IE browsers and revisit page, you will see that cookie
        is NOT maintained.</p>
</body>
</html>

Friday, November 4, 2011

SharePoint 2010 - Get My Personal Site URL and all other settings programmatically.

Summary

Guys, I found out a good way to retrieve the My Site > My Content(Personal Site) url using C#.

Solution

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    //Trying to get the Personal Site link or Url
    //SPContext.Current.Site = http://sp2010/
    //_url = http://sp2010:50000/personal/administrator/
                
    //The main site.
    SPSite _site = SPContext.Current.Site;
                
    //Gets the service context of the site.
    SPServiceContext _serviceContext = SPServiceContext.GetContext(_site);
                
    //On the basis of Service Manager 
    UserProfileManager _userProfileManager = new UserProfileManager(_serviceContext);
               
    //Get the User profile from User Profile Manager
    //True is passed in the constructor to create a My Site User Profile if it doesnot exists.
    UserProfile _userProfile = _userProfileManager.GetUserProfile(true);

    //Check if the Personal Site exists
    if (_userProfile.PersonalSite != null)
    {
        //This should give the link in the my site                   
        string _url = _userProfile.PersonalUrl.OriginalString;
    }
    else
    {
        //My Content(Personal Site) Does Exists
    }
});

Hope this helps someone facing issue to find a piece of code to get the url. The same way we can use _userProfile to get all the many other My Site Settings.

Tuesday, November 1, 2011

SharePoint 2010 - Use custom ItemStyle settings in Content Query Web Part.

Friends, I know many might find it easy to use the Custom Item Style for a Content Query Web Part. But, still I will try and explain a small process in a simplified way. Let's see if this is helpful for the starters.

Goal

The main goal is to use a Custom List name "Sample" and use a Content Query Web Part to show it with custom design style.

Process

  1. Create a custom list with name "Sample". The should just have 3 fields.
    1. Title - This is the main text to be shown for the picture.
    2. Picture - This is the hyperlink column for the picture of the item.
    3. Skills - This is a simple multiple line comment for the item.
  2. Go to any page. Add a web part. Drop a Content Query Web Part(CQWP) on the page from "Content Rollup".
  3. Click "Open tool pane".
  4. Content Query Tool Part > Query > Source > Show items from the following list: > Select "SAMPLE"
  5. Content Query Tool Part > Query > Presentation > Please see the picture as a default setting. I am going to leave it as it is.
  6. Click "Save" and the view of the web part will be a default text one which is going to look like picture below.
  7. On Clicking the picture it goes to the display record screen.

But now moving back to our goal. We need to show the data in a custom design layout. So follow the below given steps.
  1. Open a SharePoint 2010 designer.
  2. All Files > Style Library > XSL Style Sheets > ItemStyle.xsl(Edit it in advance mode)
  3. Find this element, copy it and paste it at the bottom of the XSL.
    <xsl:template name="Default" match="*" mode="itemstyle">...</xsl:template>
  4. Change the name and match to Sample.
    <xsl:template name="Sample" match="Row[@Style='Sample']" mode="itemstyle">...</xsl:template>
  5. Also if you edit the web part you can now see the item in the ItemStyle list. Make changes to map the correct fields too.

  6. Make the changes to the xsl(As you want the view of the list) or can copy the whole block and paste it at the bottom of the ItemStyle.xsl.
    <xsl:template name="Sample" match="Row[@Style='Sample']" mode="itemstyle">
            <xsl:variable name="SafeLinkUrl">
                <xsl:call-template name="OuterTemplate.GetSafeLink">
                    <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
                </xsl:call-template>
            </xsl:variable>
            <xsl:variable name="SafeImageUrl">
                <xsl:call-template name="OuterTemplate.GetSafeStaticUrl">
                    <xsl:with-param name="UrlColumnName" select="'ImageUrl'"/>
                </xsl:call-template>
            </xsl:variable>
            <xsl:variable name="DisplayTitle">
                <xsl:call-template name="OuterTemplate.GetTitle">
                    <xsl:with-param name="Title" select="@Title"/>
                    <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
                </xsl:call-template>
            </xsl:variable>
            <table cellpadding="0" cellspacing="5" border="0" style="border:1px Solid #efefef;width:400px;">
                <tr>
                    <td style="width:100px" align="center">
                        <a href="{$SafeLinkUrl}" title="{@LinkToolTip}">
                            <img class="image" src="{$SafeImageUrl}" title="{@ImageUrlAltText}" />
                        </a>
                    </td>
                    <td valign="top" align="left"><a href="{$SafeLinkUrl}" title="{@LinkToolTip}">
                      <xsl:if test="$ItemsHaveStreams = 'True'">
                        <xsl:attribute name="onclick">
                          <xsl:value-of select="@OnClickForWebRendering"/>
                        </xsl:attribute>
                      </xsl:if>
                      <xsl:if test="$ItemsHaveStreams != 'True' and @OpenInNewWindow = 'True'">
                        <xsl:attribute name="onclick">
                          <xsl:value-of disable-output-escaping="yes" select="$OnClickTargetAttribute"/>
                        </xsl:attribute>
                      </xsl:if>
                      <xsl:value-of select="$DisplayTitle"/>
                    </a><br /><xsl:value-of select="@Description" disable-output-escaping="yes" /></td>
                </tr>
            </table> 
        </xsl:template>
    
  7. Once you are done with that you can see the below given view on the screen.
  8. Thats it.


I have tried my best to keep this as simple as possible for freshers who are learning SharePoint.