Thursday, September 15, 2011

Programatically Getting url of site


SPSite osite = new SPSite(Request.QueryString["SiteURL"]);
            SPWeb rWeb = osite.RootWeb;
            //siteName.Text = rWeb.Title;
            SPWeb oweb = osite.OpenWeb();
           // webName.Text = oweb.Title;
            SPList ilist = oweb.Lists[new Guid(Request.QueryString["ListID"])];
            SPListItem iitem = ilist.GetItemById(Convert.ToInt16(Request.QueryString["ItemId"]));
           // listName.Text = ilist.Title;

            lblurl.Text = rWeb.Url + "/" + oweb.Title + "/" + ilist.Title;

Thursday, August 4, 2011

How to print a panel in SharePoint 2010



<Script type="text/javascript">
        function printform() {
            var printContent = document.getElementById("<%= pnlFullForm.ClientID %>");
            var windowUrl = "about:blank";
            var uniqueName = new Date();
            var windowName = "Print" + uniqueName.getTime();
            var printWindow = window.open(windowUrl, windowName, "left=50000,top=50000,width=0,height=0");
            printWindow.document.write(printContent.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();
        }
</script>

**********************************************

<input type="button" value="Print" id="btnPrint" title="Print" onclick="printform();"
                    class="ms-ButtonHeightWidth" />

Monday, July 26, 2010

How to implement Paging and sorting with SPQuery and SPListItemCollectionPosition in SharePoint 2010


Step One :

Create a user control or a webpart that will have datagrid for displaying the paged and sorted results , next and previous link buttons , label to show the current page values and drop down list for sort column / sort order.








I have used visual webpart and added these lines for the controls shown in this image

Sort By  :
<asp:DropDownList ID="DropDownListSortColumns" runat="server"
    onselectedindexchanged="DropDownListSortColumns_SelectedIndexChanged" AutoPostBack=true>
    <asp:ListItem>ID</asp:ListItem>
    <asp:ListItem>Title</asp:ListItem>
    <asp:ListItem>Created</asp:ListItem>
    <asp:ListItem>Modified</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownListSortOrder" runat="server"
    onselectedindexchanged="DropDownListSortOrder_SelectedIndexChanged" AutoPostBack=true>
    <asp:ListItem Value="True">Ascending</asp:ListItem>
    <asp:ListItem Value="False">Descending</asp:ListItem>
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns=true class="style1">
</asp:GridView>
<table style="float:right; width:100px">
    <tr>
        <td>
            <asp:LinkButton ID="LinkButtonPrevious" runat="server"
                onclick="LinkButtonPrevious_Click"><<</asp:LinkButton>
        </td>
        <td>
           <asp:Label ID="LabelPaging" runat="server" Text="Label"></asp:Label></td>
        <td>
            <asp:LinkButton ID="LinkButtonNext" runat="server"
                onclick="LinkButtonNext_Click">>></asp:LinkButton>
        </td>
    </tr>
</table>
Step Two:

Now we need to handle the data load events , sort column change events and the paging buttons events . For that we need to write event handlers
 protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadData(1);
            }
        }
        private void LoadData(int currentPage)
        {
            ViewState["CurrentPage"] = currentPage;
            FillData(ViewState["Next"] as string, DropDownListSortColumns.SelectedValue,Convert.ToBoolean( DropDownListSortOrder.SelectedItem.Value));
        }
        private void FillData(string pagingInfo, string sortColumn, bool sortAscending)
        {
            int currentPage = Convert.ToInt32(ViewState["CurrentPage"]);
            uint rowCount = 5;
            string columnValue;
            string nextPageString = "Paged=TRUE&p_ID={0}&p_" + sortColumn + "={1}";
            string PreviousPageString = "Paged=TRUE&PagedPrev=TRUE&p_ID={0}&p_" + sortColumn + "={1}";
            SPListItemCollection collection;
            //first make a call to fetch the desired result set
            //here is the actual call to the dal function
            collection = DAL.GetTestItems(sortColumn, sortAscending, pagingInfo, rowCount);
            DataTable objDataTable = collection.GetDataTable();
            GridView1.DataSource = objDataTable;
            GridView1.DataBind();
            //now we need to identify if this is a call from next or first
            if (null != collection.ListItemCollectionPosition)
            {
                if (collection.Fields[sortColumn].Type == SPFieldType.DateTime)
                {
                    columnValue = SPEncode.UrlEncode( Convert.ToDateTime(collection[collection.Count - 1][sortColumn]).ToUniversalTime().ToString("yyyyMMdd HH:mm:ss"));
                }
                else
                {
                    columnValue = SPEncode.UrlEncode( Convert.ToString(collection[collection.Count - 1][sortColumn]));
                }
                nextPageString = string.Format(nextPageString, collection[collection.Count - 1].ID, columnValue);
            }
            else
            {
                nextPageString = string.Empty;
            }
            if (currentPage > 1)
            {
                if (collection.Fields[sortColumn].Type == SPFieldType.DateTime)
                {
                    columnValue = SPEncode.UrlEncode(Convert.ToDateTime(collection[0][sortColumn]).ToUniversalTime().ToString("yyyyMMdd HH:mm:ss"));
                }
                else
                {
                    columnValue =SPEncode.UrlEncode(  Convert.ToString(collection[0][sortColumn]));
                }
                PreviousPageString = string.Format(PreviousPageString, collection[0].ID, columnValue);
            }
            else
            {
                PreviousPageString = string.Empty;
            }
            if (string.IsNullOrEmpty(nextPageString))
            {
                LinkButtonNext.Visible = false;
            }
            else
            {
                LinkButtonNext.Visible = true;
            }
            if (string.IsNullOrEmpty(PreviousPageString))
            {
                LinkButtonPrevious.Visible = false;
            }
            else
            {
                LinkButtonPrevious.Visible = true;
            }
            ViewState["Previous"] = PreviousPageString;
            ViewState["Next"] = nextPageString;
            LabelPaging.Text = ((currentPage - 1) * rowCount) + 1 + " - " + currentPage * rowCount;
        }
        protected void LinkButtonPrevious_Click(object sender, EventArgs e)
        {
            LoadData(Convert.ToInt32(ViewState["CurrentPage"]) - 1);
        }
        protected void LinkButtonNext_Click(object sender, EventArgs e)
        {
            LoadData(Convert.ToInt32(ViewState["CurrentPage"]) + 1);
        }
        protected void DropDownListSortColumns_SelectedIndexChanged(object sender, EventArgs e)
        {
            ViewState.Remove("Previous");
            ViewState.Remove("Next");
            LoadData(1);
        }
        protected void DropDownListSortOrder_SelectedIndexChanged(object sender, EventArgs e)
        {
            ViewState.Remove("Previous");
            ViewState.Remove("Next");
            LoadData(1);
        }
Step 3

Now the last step is to add the DAL class for this solution to complete
public class DAL
    {
        public static SPListItemCollection GetTestItems(string sortBy, bool sortAssending, string pagingInfo, uint rowLimit)
        {
          
            SPWeb objWeb = SPContext.Current.Web;
            SPListItemCollection collection;
            SPQuery objQuery = new SPQuery();
            objQuery.RowLimit = rowLimit;
            objQuery.Query = "<OrderBy><FieldRef Name='" + sortBy + "' Ascending='" + sortAssending + "' /></OrderBy>";
            objQuery.ViewFields = "<FieldRef Name='Title' />";
            if (!string.IsNullOrEmpty(pagingInfo))
            {
                SPListItemCollectionPosition position = new SPListItemCollectionPosition(pagingInfo);
                objQuery.ListItemCollectionPosition = position;
            }
            collection = objWeb.Lists["CustomList"].GetItems(objQuery);
            return collection;
        }
    }


  The source code can be found here

Saturday, July 17, 2010

Getting SharePoint User's Profiles


 SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite oSite = new SPSite(SPContext.Current.Site.ID, SPContext.Current.Site.SystemAccount.UserToken))
                    {
                        SPServiceContext context = SPServiceContext.GetContext(oSite);
                        UserProfileManager myProfileManager = new UserProfileManager(context);
                        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;
                        UserProfile myProfile = myProfileManager.GetUserProfile(CurrentUser);
                        dt.Rows.Add(Convert.ToString(myProfile["FirstName"].Value), Convert.ToString(myProfile["Department"].Value));
                        //dt.Rows.Add(Convert.ToString(myProfile["LastName"].Value), Convert.ToString(myProfile["FirstName"].Value), Convert.ToString(myProfile["Department"].Value), Convert.ToString(myProfile["WorkEmail"].Value), Convert.ToString(myProfile["WorkPhone"].Value), Convert.ToString(myProfile["CellPhone"].Value));

                    }
                    CurentUserGrd.DataSource = dt;
                    CurentUserGrd.DataBind();
                }
                catch (Exception ex)
                {
                    lblError.Text = ex.Message;
                }
            });

Wednesday, July 14, 2010

To Lock or Unlock a site collection by using Central Administration

TO LOCK A SITE COLLLECTION

1. Verify that you have the following administrative credentials. 
      • You must be a member of the Site Collection Administrators group for the site collection.

2. In Central Administration, click Application Management.

3. On the Application Management page, in the Site Collections section, click Configure quotas and locks. The Site Collection Quotas and Locks page opens.

4. If you want to change the selected site collection, in the Site Collection section, on the Site Collection menu, click Change Site Collection. Use the Select Site Collection page to select a site collection.

5. On the Site Collection Quotas and Locks page, in the Site Lock Information section, select one of the following options:
     •Not locked: To unlock the site collection and make it available to users.
     •Adding content prevented: To prevent users from adding new content to the 
       sitecollection. Updates and deletions are still allowed.
     •Read-only (blocks additions, updates, and deletions)
       To prevent users from adding, updating, or deleting content.
     •No access: To prevent access to content completely. 
       Users who attempt to access the site receive an access-denied message.

6. If you select Adding content prevented, Read-only (blocks additions, updates, and deletions), or No access, type a reason for the lock in the Additional lock information box.

7. Click OK.

TO UNLOCK A SITE COLLLECTION


1.Verify that you meet the following minimum requirements: See Add-SPShellAdmin.

2.On the Start menu, click All Programs.

3.Click Microsoft SharePoint 2010 Products.

4.Click SharePoint 2010 Management Shell.

5.At the Windows PowerShell 2.0 command prompt, type the following command:
      Set-SPSite -Identity "<SiteCollection>" -LockState "<State>"

Where:
•<SiteCollection> is the URL of the site collection that you want to lock or unlock.
•<State> is one of the following values:
Unlock: To unlock the site collection and make it available to users.
NoAdditions: To prevent users from adding new content to the site collection. Updates and deletions are still allowed.
ReadOnly: To prevent users from adding, updating, or deleting content.
NoAccess: To prevent access to content completely. Users who attempt to access the site receive an access-denied message.

Friday, February 12, 2010

How to consume Sharepoint Web Service through Javascript

Sharepoint 2010 has introduced Client Object Modal by which you can send a call to Sharepoint client API through code or through Javascript. But if you are calling the client API through Javascript, you can only do so by using asynchronous (executeQueryAsync) call to the native method.

Many a times you may need to get the data in the same method without leaving the control (means by a synchronous call without leaving the method). In that case, the best possible solution would be to use Web service calls.
Below is the code to accomplish this. For the sake of simplicity, I have called "Lists.asmx" web service to get an item by Id.

//Main Method
function GetItemByIdAndTitle(rootSiteUrl, ListTitle, itemId) {
var responseXML;
var ws;
try {
ws = InstanciateHttpRequest();
if (ws != null)
{
var soap = GetEnvelope(ListTitle, itemId); // create a web service envelope here
ws.open("POST", rootSiteUrl + "/_vti_bin/lists.asmx", false);
ws.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
ws.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetListItems");
ws.send(soap);
if (ws.readyState == '4' && ws.status == '200')
{
responseXML = ws.responseXML.xml;
//you can parse your XML here to get the data
}
}
}
catch (e)
{ }
return responseXML;
}


//This ensures the the object instanciation is supported by multiple browsers // (Mozilla, IE).
function InstanciateHttpRequest()
{
var Obj;
if (window.XMLHttpRequest)
{
Obj = new XMLHttpRequest();
}
else
{
Obj = new ActiveXObject("Microsoft.XMLHTTP");
}
return Obj;
}

//Soap Envelope

function GetEnvelope(listName,itemId)
<
var soap = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soap:Body>" +
"<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>"+
"<listName>" + listName + "</listName>"+
"<query><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + itemId + "</Value></Eq></Where></Query></query>" +
"<viewFields><ViewFields><FieldRef Name='ContentType' /></ViewFields></viewFields>" +
"<rowLimit>1</rowLimit>" +
"<queryOptions><QueryOptions><ViewAttributes Scope='Recursive'></ViewAttributes></QueryOptions></queryOptions>" +
"</GetListItems>"+
"</soap:Body>" +
"</soap:Envelope>";
return soap;
>