Thursday, January 5, 2012

Client object Model Using Silverlight in SharePoint (Getting Records From SharePoint List)



ClientContext context = new ClientContext(ApplicationContext.Current.Url);  
  context.Load(context.Web);
  List Projects = context.Web.Lists.GetByTitle("Opportunity Financial Data");
  context.Load(Projects);           
  CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
  string startDateFx = FirstDate.ToString("yyyy-MM-dd");
  string endDatFx = LastDate.ToString("yyyy-MM-dd");
  camlQueryXml = "<View><Query><Where><And><Geq><FieldRef Name='Created' /><Value IncludeTimeValue='FALSE' Type='DateTime'>" + startDateFx + "</Value></Geq><Leq><FieldRef Name='Created' /><Value IncludeTimeValue='FALSE' Type='DateTime'>" + endDatFx + "</Value></Leq></And></Where></Query></View>";
  query.ViewXml = camlQueryXml;
  _financialData = Projects.GetItems(query);
  context.Load(_financialData);

 context.ExecuteQueryAsync(new ClientRequestSucceededEventHandler(OnRequestSucceeded), null);


///

private void OnRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
 {        
     Dispatcher.BeginInvoke(BindData);
 }
//The BindData method will refer the Items which are going to bind to GridView
//Note : To bind the data to gridview use the "_financialData" collection

Tuesday, January 3, 2012

Manage blocked file types (SharePoint Server 2010)


Add or remove blocked file types
Use this procedure when you want to prohibit files of a specific type from being saved or retrieved from any Web application on a server.
To add or remove blocked file types by using Central Administration
  1. Verify that you have the following administrative credentials.(You must be a farm administrator on the server.)
  2. In Central Administration, click Security.
  3. On the Security page, in the General Security section, click Define blocked file types.
  4. On the Blocked File Types page, if you want to change the selected Web application, on the            Web Application menu, click Change Web Application. Use the Select Web Application page to select a Web application.
  5.  Do one of the following:
  • To block an additional file type, scroll to the bottom of the Type each file extension on a separate line text box, type the file extension you want to block, and then click OK.
Note:
You do not have to type a file extension in the list in alphabetical order. The next time you open the list, the file extension you added will be correctly sorted in alphabetical order.

· To stop blocking a file type, select a file type from the list, press the Delete key, and then click OK.

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;
                }
            });