Sharepoint

When or How to Use Run With Elevated Privileges (RWEP) in SharePoint

Posted on Updated on

The scope of this article is to explain the usage of RunWithElevatedPrivileges() [RWEP] – a method for security elevation for custom SharePoint components.

“The RWEP method enables you to supply a delegate that runs a subset of code in the context of an account with higher privileges than the current user”, this is the definition from Microsoft MSDN. Basically the code executed inside this method has “System Account” privileges in addition to the current user privileges or in a better way – we can tell that this method runs under the Application Pool identity, which has site collection administrator privileges on all site collections hosted by that application pool.

For a detailed explanation please go through my article published on www.mssharepoints.com or Click here

Advertisements

Multiple listing controls with a single datasource – InfoPath

Posted on Updated on

The scope of this article is to explain how to populate multiple InfoPath listing controls like a Drop-Down List and a List Box with only one datasource. The scenario can be like this:

Assume we have 2 to 3 SharePoint lists with data on our SharePoint site and we have some listing controls on our InfoPath form. The aim is to populate all these listing controls using only a single InfoPath datasource.

Solution

By default we do have four “Receive Data” options for InfoPath datasource like an XML document, DataBase,Web Service, and SharePoint Lists & Libraries. As mentioned in the “Problem”, our aim is to populate data from different SharePoint lists to different listing controls on an InfoPath form. Usually, everyone will create different datasources from SharePoint lists for each listing control, but we can utilize the “Web service” option for populating many listing controls with a single datasource. Click here for the entire article that i have published on www.mssharepointtips.com

Html Editor Control for SharePoint Web parts

Posted on Updated on

Hello SharePoint Developers,

This time i have a simple stuff on SharePoint , it is regarding the rich text editor control on SharePoint.  During our custom webpart developement if we want a HTML Editor/rich text editor on our webpart, we can utilize InputFormTextBox Class of the SharePoint Object Model.

Please read my article regarding InputFormTextBox on the MSSHAREPOINTTIPS.COM

Cascading dropdowns in InfoPath from SharePoint.

Posted on Updated on

It is very common for every developer to have a situation to  develop cascading dropdowns during their development life. It can be Category –Product scenario, Country-State scenario etc.  Here the case is something different; cascading is not on regular ASP.NET Page or not a simple web part. But it’s on a InfoPath form…..!  You will ask, what makes the difference?  I say, if the InfoPath is browser enabled, the filter option of the InfoPath won’t work or it won’t support.  Any how we developers have to accomplish this cascading task. Below, i have a scenario and its solution step by step.

Scenario:  I have two SharePoint lists “Categories “and “Products”. “Categories” SharePoint list have a column named “Category” and “Product” SharePoint list have 2 columns – Product and Category, out of which Category is a look up column from “Categories” SharePoint List. Now we have to develop a InfoPath form with 2 dropdowns, Categories and Products and we need to make it work in a cascading style. Means when the user selects a particular category on the Categories dropdown, related set of products should be populated on the Products dropdown. This is the scenario.

Solution: Follow the simple steps to accomplish this task.

  1. Open Microsoft InfoPath 2007 from Start à All Programs à Microsoft Office.
  2. Create a blank InfoPath form template using the option “Design a Form Template”. Don’t forget to check the option “Enable Browser Compatible Features” while creating the blank template.
  3. Now we have a blank InfoPath form in front of us. Drag and Drop two dropdowns from the toolbox and name them as Categories and Products.
  4. After step 3 , we need to populate the dropdowns with data. For that we need to create data connections with in the InfoPath form. “Categories” dropdown can be populated directly from the “Categories” SharePoint list. But Products dropdown can’t be populated from products SharePoint list, because its need to populated according to the selected category. In the next 2 steps we will create data connections for the dropdowns.
  5. In this step we will create data connection for the Categories dropdown. Select “Dataconnections… ” option from the “Tools” menu [menu available on the top portion] of the InfoPath form. From the “Dataconnections” window click add and on the DataConnection wizard select “Create new dataconnection” option with “Receive Data” Selection. On the “select the source of your data” step ,  go with the option “Sharepoint Library or List”. The coming steps of the wizard are self informative and proceed with selection of our Categories SharePoint List. Once we finish with the DataConnection wizard steps, Bind the created Categories dataconnection  with “Categories” Dropdown by right clicking on the control and from “Dropdown  list properties”  , select “Look up values from the external datasources” option. Now there will be a selection  with available dataconnections. Select our categories dataconnection and select category field  for  “Entries” option. Check on the InfoPath preview, whether data is populated correctly or not. So population of the  Categories dropdown is over.
  1. In this step we will create dataconnection for the Products dropdown. Here  we have to do some more work to create Products dataconnection. This is the portion we have to look on. Before going to create dataconnection for Products, we have to create a webservice that have function which return set  of  products according to the category passed. So, Create a WSPBuilder project and  add a Webservice item to the project  from WSPBuilder project templates or you can go with other webservice creation techniques and deploy it to the sharepoint site. Usually I create SharePoint components with the WSPBuilder . If it is with WSPBuilder, packaging and deployment is quite easy.

Give a user-friendly name to the webservice and in the code behind of the Webservice file add the following piece of code.

[WebMethod]
        public DataSet GetProducts(string Category)
        {

            DataSet dsProducts = new DataSet();
            DataTable dtProducts = new DataTable();
            DataColumn dcCategory = new DataColumn("Category");
            DataColumn dcProduct = new DataColumn("Product");
            dtProducts.Columns.Add(dcCategory);
            dtProducts.Columns.Add(dcProduct);

            SPSite site = SPContext.Current.Site;
            SPList list = site.OpenWeb().Lists["Products"];
            SPQuery query = new SPQuery();
            query.Query = @"<Where>
      <Eq>
         <FieldRef Name='Category' />
         <Value Type='Lookup'>"+ Category  +@"</Value>
      </Eq>
   </Where>";
            SPListItemCollection itemCol = list.GetItems(query);

            DataRow drCategory;
            foreach (SPListItem item in itemCol)
            {
                drCategory = dtProducts.NewRow();
                drCategory[dcCategory] = Convert.ToString(item["Category"]);
                drCategory[dcProduct] = Convert.ToString(item["Product"]);
                dtProducts.Rows.Add(drCategory);
            }

            dsProducts.Tables.Add(dtProducts);
            return dsProducts;
  }

This webservice method will return set of products for the given category. Build this project, build the WSP and deploy to the sharepoint site. After the deployment of the WSP , we can find the webservice in the _layouts virtual directory of the sharepoint site on the IIS. It will look like this http://localhost:5050/_layouts/CascadingDDLService.asmx .   Browse that .asmx  file and check whether  the “GetProducts” webservice method  is working on invoking. If it is working, we can proceed with it during the creation of “Products” dataconnection.

Now we can start creating dataconnection for Products. Follow the procedures mentioned on the step 5,till you reach “select the source of your data” step on the dataconnection wizard. On this step you have to select “Web service” option rather than “Sharepoint Library or List” option that we have taken on the step 5. After selecting  “Web Service” option , on this next step it will ask us to provide the webservice URL. Provide our webservice url that we have deployed before, it will give set of web- methods in the web service, in our case it will be only method ,“GetProducts”. Click next , it will ask for the  default parameter values and go on with the steps with clicking Next. But on the last step we have to consider one important thing , uncheck the option “Automatically retreive data when form is opened.” and click Finish to end dataconnection wizard.Now the Products dataconnection is created and we can bind this dataconnection to the Product dropdown list. Follow the same procedures mentioned on the step 5 to bind the dataconnection on the dropdown.

  1. Next step is to create the “Rules” for the Categories Dropdown. This step is very important for the cascading to work.
    • Right click on the Categories dropdown, select “Rules” option. From the rules window, click “Add” button to add a rule for the categories dropdown.
    • On the click of the “Add” button, you will see a window like this

Name the rule with a user-friendly name. Click on the “Set Condition” button and set a condition as per the below mentioned image.


We need to set the condition that Rule need to shoot when Categories is not blank.

    • After setting the Condition we can set the “Actions” for that rule.Here we need to set 3 actions. Click on the “Add Action” button to set an action.
    • In first action we will set the Products Field previously set value to Null. Select “Set a field’s value” from the action’s dropdown.For that select Products Field from main datasource and click OK without setting the value.

    • On the second action we need to set the Category parameter for the “GetProducts”  dataconnection, which is a secondary datasource. Select “Set a field’s value” from the action’s dropdown. In the Field section select Category parameter

and set its value to the Main datasource Category Field.

    • In the third action we will populate the “GetProducts” datasource . For that Select “Query using a dataconnection” from action’s dropdown and select “GetProducts” dataconnection from Data connection’s dropdown.

Finally the Rule window will be like this

Now save InfoPath Form and publish to any SharePoint site. Browse the InfoPath form from any of your browser, cascading of dropdown will work with charm…. 🙂

Asynchronous Sharepoint List Insert / Update.

Posted on Updated on

Hello SharePoint developers… This time I have a new stuff to a share with you all. Two weeks back I met with one of my friends, who is also working as Software developer in SharePoint Technology. In between our talks he explained about a technical issue that he is facing in his project. The issue was regarding the use of AJAX in MOSS 2007. Actually his requirement is to update a SharePoint List asynchronously through a web part and he was using ASP.NET AJAX ScriptManager, UpdatePanel to accomplish this task. But it gives some cross browser issues, JavaScript issues like “ScriptResource.axd” file issue etc. I have also read that there are some issues of ASP.NET AJAX with MOSS 2007. Any how that night I also sat down along with him to find a solution. After a few trouble shooting and “googling” we come to a conclusion that it can’t be done with a small span of time. We started thinking for a new solution and into my mind it came like shooting star. “ICallbackEventHandler”…….. Yes, we started creating a new web part that implements the interface ICallbackEventHandler.

Here we can look into some small piece of code that explains “How to update a SharePoint List asynchronously using ICallbackEventHandler?”. This post assumes that readers have idea regarding the SharePoint Web Part development. Please go through the following steps to know how things are done.

This is simple example where we will add SP List Item to a SP List asynchronously through a Webpart.

1. Create a SharePoint Custom List having 2 columns [Name, Age] on your SharePoint Site.

2. Create a new SharePoint WSP Project from your Visual Studio IDE. [Please install WSPBuilder from CodePlex, if you don’t have a WSPBuilder Template ].

3. Add a Web Part Feature into the project from the “Add new Item” option on the created project.

4. Switch to the webpart code .cs file . This will be under the WebPartCode folder in the project, if we use the WSPBuilder Template.

5. Utilize the CreateChildControls() Method to develop the UI for the webpart with 2 Textboxes and a button. One textbox is for input value of the “Name” and other for “Age”. The button will be used to Submit the input values.The below mentioned will be the code inside the CreateChildControls() Method.

protected override void CreateChildControls()
        {
                try
                {
                    base.CreateChildControls();

                    txtName = new TextBox();
                    txtName.ID = "txtName";

                    txtAge = new TextBox();
                    txtAge.ID = "txtAge";

                    btnSubmit = new HtmlButton();
                    btnSubmit.ID = "btnSubmit";
                    btnSubmit.InnerText = "Submit";
                    btnSubmit.Attributes.Add("onclick", "javascript:CallServer2();");

                    Table tbl = new Table();
                    TableRow tr1 = new TableRow();
                    TableRow tr2 = new TableRow();
                    TableRow tr3 = new TableRow();

                    TableCell cell11 = new TableCell();
                    TableCell cell12 = new TableCell();
                    TableCell cell21 = new TableCell();
                    TableCell cell22 = new TableCell();
                    TableCell cell31 = new TableCell();
                    TableCell cell32 = new TableCell();

                    tr1.Cells.Add(cell11);
                    tr1.Cells.Add(cell12);
                    tr2.Cells.Add(cell21);
                    tr2.Cells.Add(cell22);
                    tr3.Cells.Add(cell31);
                    tr3.Cells.Add(cell32);

                    cell11.Text = "Name";
                    cell12.Controls.Add(txtName);

                    cell21.Text = "Age";
                    cell22.Controls.Add(txtAge);

                    cell32.Controls.Add(btnSubmit);

                    tbl.Rows.Add(tr1);
                    tbl.Rows.Add(tr2);
                    tbl.Rows.Add(tr3);

                    this.Controls.Add(tbl);

                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }

        }

6. Implement the ICallbackEventHandler interface to the webpart class. Implementation of this interface will add functions, 1. RaiseCallbackEvent 2. GetCallbackResult.

RaiseCallbackEvent – This function will be used to write code logic to update/insert the item to the Sharepoint List. This method have a parameter of type string which bring client side input data to the server side.

GetCallBackResult – This function is used to return the server side feedback to the client side as string.

Along with these 2 server side functionalities there are 2 client side JavaScript functions also needed for the orchestra. These Javascript functions are used to Call Server [here we will create JS function CallServer] functionalities from client side and for receiving the server feedback[JS function name will be ReceiveServerdata]. These JS functionalities need to register to Page Client Script block as follows.

protected override void OnLoad(EventArgs e)
        {

                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();

                    ClientScriptManager cm = Page.ClientScript;
                    String cbReference = cm.GetCallbackEventReference(this, "arg",
                        "ReceiveServerData", "");
                    String callbackScript = "function CallServer(arg, context) {" +
                        cbReference + "; }";
                    cm.RegisterClientScriptBlock(this.GetType(),
                        "CallServer", callbackScript, true);

                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }

        }

7. Also we need to write our own JavaScript function [SetInputValues]to create appended a global string variable with all input values delimited by semi colon “;”. This global string variable is passed through the CallServer JS Function to reach the server side.
To accomplish this client side functionalities cleaner we will create a JS Function CallServer2 to call previously mentioned CallServer JS function and SetInputValues JS function. This CallServer2 JS function will be called on the onclick of the submit button.

//global variable
            var inputValues;

            function SetInputValues()
            {

                inputValues='';
                var txtName = document.getElementById('ctl00_m_g_cebf30d1_69b5_4c77_b9ef_4c5dea6aa649_txtName');
                var txtAge = document.getElementById('ctl00_m_g_cebf30d1_69b5_4c77_b9ef_4c5dea6aa649_txtAge');

                var Name=txtName.value;
                var Age=txtAge.value;

                inputValues=Name+';'+Age;

            }
            function CallServer2()
            {
                SetInputValues();
                CallServer(inputValues,'');

            }

            function ReceiveServerData(arg, context)
            {
                        alert(arg);
            }

All these JS Functions will be written on the code file of the webpart as a string variable and these JS functions are registered to the page on the OnInit event.

private string jsString = @"
            //global variable
            var inputValues;

            function SetInputValues()
            {

                inputValues='';
                var txtName = document.getElementById('ctl00_m_g_cebf30d1_69b5_4c77_b9ef_4c5dea6aa649_txtName');
                var txtAge = document.getElementById('ctl00_m_g_cebf30d1_69b5_4c77_b9ef_4c5dea6aa649_txtAge');

                var Name=txtName.value;
                var Age=txtAge.value;

                inputValues=Name+';'+Age;

            }
            function CallServer2()
            {
                SetInputValues();
                CallServer(inputValues,'');

            }

            function ReceiveServerData(arg, context)
            {
                        alert(arg);
            }
           ";
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "callback", jsString, true);
        }

8. From the Server side we can take this input string[global variable “inputValues”] values through the previously mentioned RaiseCallbackEvent method’s parameter and we split this string with semicolon to get the array of input values to insert into the SP List.

 public void RaiseCallbackEvent(string eventArgument)
        {

            char[] delimiter = new char[1];
            delimiter[0] = Convert.ToChar(";");
            string[] inputData = new string[2];
            inputData = eventArgument.Split(delimiter);

            string siteUrl = "http://galaxian:5050/default.aspx";
            string libName = "NameList";
            // Open the site
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {

                    SPList list = web.Lists[libName];
                    SPListItem item = list.Items.Add();
                    item["Title"] = inputData[0];
                    item["Age"] = inputData[1];
                    item.Update();

                }
            }
        }

9. After the inserting the item we can intimate the client side using the GetCallbackResult() method

public string GetCallbackResult()
        {
            return "Data inserted successfully...!";
        }

This message will be displayed as a JS alert after the insertion of the data. This server side feedback will be received by the ReceiveServerData() JS Function as mentioned on the Step 7.

The whole Code file for the webpart will look as below.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;

namespace Asynchronous_SharepointListUpdate
{
    [Guid("6e22a748-4b74-481f-8b08-98106f869cf3")]
    public class Asynchronous_SPWebPart : Microsoft.SharePoint.WebPartPages.WebPart, ICallbackEventHandler
    {
        private bool _error = false;
        private string _myProperty = null;

        public Asynchronous_SPWebPart()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        TextBox txtName;
        TextBox txtAge;
        HtmlButton btnSubmit;

        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {
                try
                {
                    base.CreateChildControls();

                    txtName = new TextBox();
                    txtName.ID = "txtName";

                    txtAge = new TextBox();
                    txtAge.ID = "txtAge";

                    btnSubmit = new HtmlButton();
                    btnSubmit.ID = "btnSubmit";
                    btnSubmit.InnerText = "Submit";
                    btnSubmit.Attributes.Add("onclick", "javascript:CallServer2();");

                    Table tbl = new Table();
                    TableRow tr1 = new TableRow();
                    TableRow tr2 = new TableRow();
                    TableRow tr3 = new TableRow();

                    TableCell cell11 = new TableCell();
                    TableCell cell12 = new TableCell();
                    TableCell cell21 = new TableCell();
                    TableCell cell22 = new TableCell();
                    TableCell cell31 = new TableCell();
                    TableCell cell32 = new TableCell();

                    tr1.Cells.Add(cell11);
                    tr1.Cells.Add(cell12);
                    tr2.Cells.Add(cell21);
                    tr2.Cells.Add(cell22);
                    tr3.Cells.Add(cell31);
                    tr3.Cells.Add(cell32);

                    cell11.Text = "Name";
                    cell12.Controls.Add(txtName);

                    cell21.Text = "Age";
                    cell22.Controls.Add(txtAge);

                    cell32.Controls.Add(btnSubmit);

                    tbl.Rows.Add(tr1);
                    tbl.Rows.Add(tr2);
                    tbl.Rows.Add(tr3);

                    this.Controls.Add(tbl);

                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }

        }

        private string jsString = @"
            //global variable
            var inputValues;

            function SetInputValues()
            {

                inputValues='';
                var txtName = document.getElementById('ctl00_m_g_cebf30d1_69b5_4c77_b9ef_4c5dea6aa649_txtName');
                var txtAge = document.getElementById('ctl00_m_g_cebf30d1_69b5_4c77_b9ef_4c5dea6aa649_txtAge');

                var Name=txtName.value;
                var Age=txtAge.value;

                inputValues=Name+';'+Age;

            }
            function CallServer2()
            {
                SetInputValues();
                CallServer(inputValues,'');

            }

            function ReceiveServerData(arg, context)
            {
                        alert(arg);
            }
           ";
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "callback", jsString, true);
        }

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {

                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();

                    ClientScriptManager cm = Page.ClientScript;
                    String cbReference = cm.GetCallbackEventReference(this, "arg",
                        "ReceiveServerData", "");
                    String callbackScript = "function CallServer(arg, context) {" +
                        cbReference + "; }";
                    cm.RegisterClientScriptBlock(this.GetType(),
                        "CallServer", callbackScript, true);

                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }

        }

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }

        #region ICallbackEventHandler Members

        public string GetCallbackResult()
        {
            return "Data inserted successfully..!";
        }

        public void RaiseCallbackEvent(string eventArgument)
        {

            char[] delimiter = new char[1];
            delimiter[0] = Convert.ToChar(";");
            string[] inputData = new string[2];
            inputData = eventArgument.Split(delimiter);

            string siteUrl = "http://galaxian:5050/default.aspx";
            string libName = "NameList";
            // Open the site
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {

                    SPList list = web.Lists[libName];
                    SPListItem item = list.Items.Add();
                    item["Title"] = inputData[0];
                    item["Age"] = inputData[1];
                    item.Update();

                }
            }
        }

        #endregion
    }
}

This was the workaround that we have done for the asynchronous insert on the sharepoint list.

Hope you have enjoyed this post…Thanks for reading.