Monday, June 3, 2013

Get a count of ALL Lists and Document Libraries in your SharePoint Site



I needed to provide a report of all List and Document Libraries from my SharePoint Site/Child Sites and SharePoint Out of the Box does not provide this feature.
There are however, various options to getting this report, some which are listed below. The various options may give you site count from the top-level sites, but not child sites.
Options:
1.  Use SharePoint Designer reports:– Only gives top-level result
2.  Use SPSite  and SPWebCollection:– This involves writing code and iterating though your collection.
3.       Use Client Object Model as shown here on MSDN:- http://msdn.microsoft.com/en-us/library/ee538683%28v=office.14%29.aspx. Here again you have to iterate and get your data.
4.       My favorite is using good old SQL. This assumes that you have access to SQL Server management Studio and that you have the necessary credentials to your SharePoint SQL. Note that accessing your SQL directly is not recommended by Microsoft, but sometimes you have to do what you have to doJ So here is the SQL that will give you ALL List and Documents throughout your Site:

SELECT     AllLists.tp_Title, Webs.SiteId, Webs.FullUrl, AllLists.tp_RootFolder, Webs.ParentWebId
FROM         AllLists INNER JOIN
                      Webs ON AllLists.tp_WebId = Webs.Id
ORDER BY Webs.FullUrl

Feel free to refine it to your needs and share your successes.
I hope this helps someone out there.

Friday, May 3, 2013

SPWeb.EnsureUser Method throws Access Denied Error

According to Microsoft, SPWeb.EnsureUser  Checks whether the specified login name belongs to a valid user of the Web site, and if the login name does not already exist, adds it to the Web site.

Well, this will not work in an environment where you have membershipprovider enabled. to get around this issue please use the following code. 


#region Add user to a group
        /// <summary>
        /// addUserToGroup
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="userLoginName"></param>
        public void addUserToGroup(string groupName, string userLoginName)
        {
            SPSite site = new SPSite(RootWebUrl);
            SPWeb web = site.OpenWeb();
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                          {
                              web.AllowUnsafeUpdates = true;
                              SPUser spUser = web.AllUsers[userLoginName];

                              if (spUser != null)
                              {
                                  SPGroup spGroup = web.Groups[groupName];
                                  if (spGroup != null)
                                      spGroup.AddUser(spUser);
                              }
                          });
            }
            catch (Exception ex)
            {
                ErrorLogger.LogFeatureError("Error Adding user to SharePoint Group: " + groupName + " Name: " + userLoginName, ex);
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
                site.Close();
                web.Close();
            }
        }
        #endregion



 #region Create user
        /// <summary>
        /// CreateUser - Create a SharePoint User and assign role
        /// </summary>
        /// <param name="strLoginName"></param>
        /// <param name="strEMail"></param>
        /// <param name="strName"></param>
        /// <param name="strNotes"></param>
        /// <param name="strSiteURL"></param>
        /// <returns></returns>
        private SPUser CreateUser(string strLoginName, string strEMail,
                    string strName, string strNotes, string strSiteURL)
        {

            SPUser spReturn = null;
            SPSite spSite = null;
            SPWeb spWeb = null;

            try
            {
                //Open the SharePoint site
                spSite = new SPSite(RootWebUrl);
                spWeb = spSite.OpenWeb();

                SPSecurity.RunWithElevatedPrivileges(delegate()
                       {

                           spWeb.AllowUnsafeUpdates = true;
                           spWeb.SiteUsers.Add(strLoginName, strEMail, strName, strNotes);
                           //Update site
                           spWeb.Update();
                           spReturn = spWeb.AllUsers[strLoginName];
                       });
                //Response.Write("User Successfully Created= " + strLoginName + "<br>");
                ErrorLogger.LogFeatureMessage("User Created", "User Successfully Created= " + strLoginName);
            }
            catch (Exception ex)
            {
                //Response.Write(ex.Message.ToString());
                ErrorLogger.LogFeatureError("Error Creating SharePoint User", ex);
            }
            finally
            {
                spWeb.AllowUnsafeUpdates = false;
                spWeb.Close();
                spSite.Close();
            }

            return spReturn;
        }
        #endregion

Server Error in '/adfs' Application


Ok , all of a sudden our SharePoint refused to render pages, I mean drop dead with this error.


We checked all the necessary culprits but no resolution. Our environment had just recently been Virtualized, which introduced a lot of unknowns into the equation.

After much digging around, come to fine out the time on our server were out of synch, go figure.
So, I hope this saves someone precious time out there.......:)

Friday, June 8, 2012

How to Extract PowerPoint documents from SharePoint”SQL Database”


How to Extract PowerPoint documents from SharePoint ”SQL Database”


What do you do when your SharePoint (WFE) for whatever reason decides to go bunkers? Your users cannot retrieve their documents because they cannot get to it. In the mean time your System Administrators are working diligently to bring the site back online.
To make matters worse, your marketing department has a presentation to potential investors and all the PowerPoint slides are dead in SharePoint world.
Well, do not despair. This little tool will enable you to retrieve your PowerPoint slides or any other document stored in SharePoint.
Warning: This assumes that your SQL database is intact and not corrupted.
Credit goes to these guys PaulM  and markjen

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
 
// replace this string with your Sharepoint content DB connection string
string DBConnString = “Server=YOURSHAREPOINTSERVER;Database=CONTENTDATABASE;Trusted_Connection=True;”;
 
// create a DB connection
SqlConnection con = new SqlConnection(DBConnString);
con.Open();
 
// the query to grab all the files.
// Note: Feel free to alter the LeafName like ‘%.extension’ arguments to suit your purpose
SqlCommand com = con.CreateCommand();
com.CommandText = “select DirName, LeafName, Content from Docs where (LeafName like ‘%.doc’ or LeafName like ‘%.xls’ or LeafName like ‘%.pdf’ or LeafName like ‘%.ppt’) and Content is not NULL”;
 
// execute query
SqlDataReader reader = com.ExecuteReader();
 
while (reader.Read())
{
    // grab the file’s directory and name
    string DirName = (string)reader["DirName"];
    string LeafName = (string)reader["LeafName"];
 
    // create directory for the file if it doesn’t yet exist
    if (!Directory.Exists(DirName))
    {
        Directory.CreateDirectory(DirName);
        Console.WriteLine(“Creating directory: “ + DirName);
    }
 
    // create a filestream to spit out the file
    FileStream fs = new FileStream(DirName + “/” + LeafName, FileMode.Create, FileAccess.Write);
    BinaryWriter writer = new BinaryWriter(fs);
 
    // depending on the speed of your network, you may want to change the buffer size (it’s in bytes)
    int bufferSize = 1000000;
    long startIndex = 0;
    long retval = 0;
    byte[] outByte = new byte[bufferSize];
 
    // grab the file out of the db one chunk (of size bufferSize) at a time
    do
    {
        retval = reader.GetBytes(2, startIndex, outByte, 0, bufferSize);
        startIndex += bufferSize;
 
        writer.Write(outByte, 0, (int)retval);
        writer.Flush();
    } while (retval == bufferSize);
 
    // finish writing the file
    writer.Close();
    fs.Close();
 
    Console.WriteLine(“Finished writing file: “ + LeafName);
}
 
// close the DB connection and whatnots
reader.Close();
con.Close();


Monday, November 21, 2011

Microsoft Ajax Content Delivery Network

If you like jQuery like I do, here is a library hosted by Microsoft  that might help. 
"The Microsoft Ajax Content Delivery Network (CDN) hosts popular third party JavaScript libraries such as jQuery and enables you to easily add them to your Web applications. For example, you can start using jQuery which is hosted on this CDN simply by adding a <script> tag to your page that points to ajax.aspnetcdn.com."

Read More here !

Sunday, October 16, 2011

SharePoint Developer Tools you must have

Okay these are just the ones I have used and liked. I am sure they are countless others out there.
  1. SPDisposeCheck   is a tool that helps developers and administrators check custom SharePoint solutions that use the SharePoint Object Model helping measure against known Microsoft dispose best practices. This tool may not show all memory leaks in your code and may produce false positives which need further review by subject matter experts. 
  2. U2U Caml Query Builder  Helps you build your CAML Queries. very handy.
  3. Stramit SharePoint 2007 Caml Viewer This generates CAML based on the views you have set up on your SharePoint List.
  4. WSPBuilder (SharePoint WSP tool) for building Features 
  5. .NET Reflector   is a class browser, decompiler and analysis tool for .NET, that allows you to navigate, search, disassemble and analyze .NET components.