Tuesday, September 24, 2013

jQuery spservices to get current user name for sharepoint site

Hi peeps,
In this post we are going to write a script which will give us the current user loggedin name for a sharepoint site using jQuery SPServices.
Below is the script:

// 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 currentuserName = $().SPServices.SPGetCurrentUser({
   fieldName: "Title",
   debug: false
});
</script>


Hope this helps...
RELATED Post : How to display user information using ProfilePropertyLoader in sharepoint

Javascript Launch compose new email on button click

Hi Folks,
In this post we are going to see, how to launch compose new email page of your default mail client.
Below is the javascript which will do the trick. You just need to call this function on onclick property of the button present in your webpage.
In this example we will be adding the body of the mail as "{document url}" and subject as "My Subject"
Here we go..

<script type="text/javascript">
function mailThisMsg()
{
var recpt = ""
var subj = "My Subject"
var text = encodeURIComponent(document.URL)
var bcc = ""
var content = new Array()  
content[0] = "mailto:"
content[1] = recpt
content[2] = "?subject="
content[3] = subj
content[4] = "&body="
content[5] = text
content[6] = "&bcc="
content[7] = bcc
content = content.join("")
window.location = content
}
</script>


Hope this helps...

Javascript Hide recent changes section sharepoint 2010

Hi Folks,
In this post we are going to write a script which will hide Recently Modified Items from the Quick launch of sharepoint site.


Below is how we are going to acheive.

Add a HTML Form Web Part to any section of the page(preferably master page) and then add the below style.

<style>
.s4-recentchanges
{  
  display:none;
}
</style>

Below is the output without Recently Modified Items



Hope this helps...

JavaScript Back to Previous Page functionality on a button click

Hi Pals,
In this post we are going to see How to go back to previous page using Javascript on click of anchor button.

Below is the script which will take you to the previous page upon clicking on Back to previous page button.

<a href="#" onClick="history.go(-1)"> Back to Previous Page </a>

Monday, June 10, 2013

Differences Between Sandboxed and Farm Solutions

Hi Guys,
In this post we are going to list out the differences between Sandboxed and Farm based Solutions.

Farm based Solutions:
Farm solutions are hosted in the IIS worker process (W3WP.exe).It runs the code that can affect the whole farm.So whenever you deploy a farm solution you must restart the application pool or ISS Server.
If you deploy any feature or retract any feature the whole application pool got recycled.
W3WP is the worker process to which you should attach while debugging Farm based solutions.

Sandboxed Solutions:
Sandboxed solutions are hosted in the SharePoint user code solution worker process (SPUCWorkerProcess.exe).It runs the code that can only affect the site collection of the solution.
Whenever you deploy a sandbox solution, no need of restarting neither the IIS application pool nor the IIS server as sandboxed solutions do not run in the IIS worker process.
SPUCWorkerProcess is the worker process to which you should attach while debugging sandbox solutions.

Points to be noted:
•One major difference is we can't create Aplication pages in Sandbox solutions.Beacuse Application pages are stored in the 14\TEMPLATES\_LAYOUTS and when we deploy as sandbox we dont have permissions to the physical folder.
•Also we cant create VISUAL web parts in Sandbox soultions.
•We cant use code to connect to the external web services or to database in the sandbox soltion
•Farm solutions are installed and deployed. Sandboxed solutions are uploaded and activated.
runwithelevatedprivileges doesn't work in Sandboxed solutions.
• Site collection adminstrator can deploy a Sandboxed solutions, where as Farm administrator can only deploy Farm based Solutions.

Hope this helps...

Wednesday, May 15, 2013

How to export DataTable to Excel using C#

In this post we will be exporting the DataTable to an Excel using C#
Below is the method which will do the trick. Just pass the parameters datatable and the filename.

private void ExportDataTableToExcel(DataTable thetable, string fileName)
        {
            string attachment = "attachment; filename=" + fileName + ".xls";

            Response.ClearContent();

            Response.AddHeader("content-disposition", attachment);

            Response.ContentType = "application/vnd.ms-excel";

            //write columns from DataTable to Excel      
            string tab = "";
            foreach (DataColumn dc in thetable.Columns)
            {
                string title = string.Empty;
                if (dc.ColumnName.Contains("Meta"))
                    title = "Metadata Properties";
                else
                    title = dc.ColumnName;
                Response.Write(tab + title);
                tab = "\t";
            }
            Response.Write("\n");

            //write rows from DataTable to Excel  
            int i;
            foreach (DataRow dr in thetable.Rows)
            {
                tab = "";
                for (i = 0; i < thetable.Columns.Count; i++)
                {
                    Response.Write(tab + dr[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            //To throw the excel file generated
            Response.End();

        }


Hope this helps...

Deleting all versions of a document present in document library except last 2 major and 1 minor versions Moss2007/Sharepoint2010

Recently i came across a requirement to develop a admin component which will delete all the versions of the document except some major and minor verisons present in a Sharepoint document library. Thought of sharing with you guys aswell.
In this post we are going to Delete all versions of a document present in document library except last 2 major and 1 minor versions
Below is the code snippet which performs the action.
You can made the variables int majorVersionsRequired and int minorVersionsRequired are as configurable depending on the versions you require.

try
{
   using (SPSite site = new SPSite("<<http://siteurl/>>"))
   {
      using (SPWeb web = site.OpenWeb())
      {
         SPList list = web.Lists["<<Doc Lib Name>>"];
         int majorVersionsRequired = 2;
         int minorVersionsRequired = 1;

         foreach (SPListItem item in list.Items)
         {
            SPListItemVersionCollection versionCol = item.Versions;
            int count = versionCol.Count;
            int tempMajorVersionsRequired = 0;
            int tempMinorVersionsRequired = 0;
            int versionSiNo = 0;
                           
            for (int i = 0; i <= count - 1; i++)
            {
               if (versionCol[i - versionSiNo].Level == SPFileLevel.Published)
               {
                  // this is a major version
                  tempMajorVersionsRequired++;
                  if (tempMajorVersionsRequired > majorVersionsRequired)
                  {
                     SPListItemVersion version = versionCol[i - versionSiNo];
                     version.Delete();
                     versionSiNo++;
                  }
               }
               else if (versionCol[i - versionSiNo].Level == SPFileLevel.Draft)
               {
                  //this is a minor version
                  tempMinorVersionsRequired++;
                  if (tempMinorVersionsRequired > minorVersionsRequired)
                  {
                     SPListItemVersion version = versionCol[i - versionSiNo];
                     version.Delete();
                     versionSiNo++;
                  }
               }
            }
          } 
      }
   }
}
catch (Exception ex)
{

}


Hope this helps...

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

Monday, March 18, 2013

Implementing Google chrome frame Plugin to your website


Google Chrome frame lets web developers create web features based on technologies that are not yet available in some versions of Internet Explorer, such as rich text editing and faster Javascript execution. If you use Internet Explorer, you can still use it to view websites that contain such features, by first downloading the Google Chrome Frame plugin.
This google chrome frame plugin is also used to avoid the memory leakage in IE if our site is using AJAX,jQuery. If once we have installed this plugin we just need to change the meta tag so that IE browser will render using chrome engine. Ref this link for more details.
In this Post we are going to Implement Google chrome frame Plugin to our website wherein we will be showing a div(ref figure below) on top of our page, only in Internet Explorer and if Google chrome frame Plugin is not installed.

Below are the steps:
Step1: Create a above div and place it at the top of the page. Make the div style as display:none

Step2: Checking google chrome frame plugin is installed on the machine or not.

Below is the function that can do the trick
function IsGoogleChromePluginInstalled() {
    try {
        var i = new ActiveXObject('ChromeTab.ChromeFrame');
        if (i) {
            return true;
        }
    }
    catch (e) {
    }
    return false;
}

Call the above function in the document.ready function. If the function above function returns false(means GCF plugin not installed) then make the above created div style as display:block. So that it will display the above div to the user.

Step3: Call the below function on the onclick= installGoogleChromeFrame(); for Install Now button

function installGoogleChromeFrame() {   
    if ($(".chromeFrameOverlayContent").length > 0) {
        $(".chromeFrameOverlayContent, .chromeFrameOverlayUnderlay").show();
    }
    else {
        CFInstall.check({
            url: document.location.protocol + "//" + {SingleUser Or Multi User url},
            mode: "overlay",
            destination: window.location
        });

        $(".chromeFrameOverlayContent, .chromeFrameOverlayUnderlay").show();
        var chromeframeheight = document.body.scrollHeight;
        $('.chromeFrameOverlayUnderlay').css('height', chromeframeheight);
        $("#chromeFrameCloseButton").click(function () {
            $(".chromeFrameOverlayContent, .chromeFrameOverlayUnderlay").css({ display: "none" });
        });

    }
}

Single user installation:

Multiple user installation:

Step4:
With the above three steps we are good to show a message to install the Google chrome frame Plugin.
When user clicks on Install Now button an overlay will comes up on top of our webpage asking user to install.

Hope this helps…


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..

Set this url as default/Home page of your browser


In this post we are going to set any url as default/Home page of your browser.
Recently one of my friend asked me to do this. So thought of sharing with you guys as well.
Consider we are going to set the http://www.google.co.in as the Default/Home page of the browser.

Add a below anchor tag to your webpage
<A style="CURSOR: hand; font-decoration: underline" href="#" onclick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.google.co.in');">set as your home page</A>

So when user clicks on this button, a popin will appear asking to set google as the home page.
Just click on Ok. That's it, your browser has been updated with the default/Home page as google.com


Hope this helps...


Popular Posts