SharePoint 2010: Get Selected Items from List View in Visual Web Part

While working in SharePoint 2010, we had a requirement to get all the selected items from List View [XSLTListView] to my Visual Web Part to do some functioning on them… Now we thought to use default selection checkbox and get all items by SP.ListOperation.Selection.getSelectedItems, here is the code used in Visual Web Part to get all selected items:

function setSelectedItemsOld() {
    try {
    var ctx = SP.ClientContext.get_current();
    var items = SP.ListOperation.Selection.getSelectedItems(ctx);
    //alert(items);
    var myItems = '';
    var i;

    for (i in items) {
    myItems += '|' + items[i].id;
    }

    document.getElementById("<%= hdnItemsToSend.ClientID %>").value = myItems;
    }
    catch (e) {
    alert('Exception Occured' + e.Message);
    }
}

where “hdnItemsToSend” is the HiddenField’s ID… So item id’s separated by ‘|’ were stored inside the Hidden field.

But the problem was whenever user clicks outside the List View, all the selection is gone! We had a Visual Web Part before the List View where we were taking some input and after that List View for selecting Items need to be forwarded! Sometimes user just makes selection in Items and then go back to enter details, which results in No Selection… The default selection assumes to work with Ribbon Controls, unfortunately we wanted them to use with Visual Web Part…

A workaround was to insert own Selection checkbox with each item, using Calculated Field to generate HTML inside the XSLTListView using Christophe’s Path to SharePoint JavaScript: HTML Calculated Column, so created a Calculated Column in list with formula as:

=CONCATENATE("<div><input type=’checkbox’ name=’chkSelect’ id=’", customIdColumn, "’ /></div>")

We have to put the Christophe’s: HTML Calculated Column JavaScript at the bottom of our XSLTListView, maybe in a Content Editor Web Part… And once you have your custom checkbox ready, you can see on checking items from it and clicking somewhere else now, doesn’t remove the selections!

Now you can access the selections from your Visual Web Part like [JavaScript below is inside Visual Web Part]:

<script type="text/javascript">

function setSelectedItems() {
		try {
			var items = "";
			var selectedItems = document.getElementsByName("chkSelect");

			for (var index = 0; index < selectedItems.length; index++) {
				if (selectedItems[index].checked) {
					items += selectedItems[index].id + "|";
				}
			}

			if (items.length > 0) {
				document.getElementById("<%= hdnItemsToSend.ClientID %>").value = items;
				return true;
			}
			else {
				document.getElementById("<%= lblErrorShow.ClientID %>").innerText = "Please select items to proceed!";
			}
		}
		catch (ex) {
		}
		return false;
    }

</script>

Oh, and I forgot to tell where will you call setSelectedItems JavaScript function from, it was a custom button in Visual Web Part which was clicked to process the items, which looked like:

<asp:Button ID="btnSubmit" runat="server" OnClientClick="setSelectedItems" 
     OnClick="btnSubmit_Click" Text="Submit" />

If the JavaScript function will return true only then the btnSubmit_Click event will be called, this is simply from ASP.NET area! And, you can access the items from code behind on btnSubmit_click by splitting the id’s from hidden field… I hope this helps someone!

SharePoint 2013 with Office Web Apps–New feature

If you have SharePoint 2013 setup and Office Web Apps installed and configured to run with SP 2013, then you have very nice features available on Documents on SP 2013…

Here is a screenshot of the new feature with Office Web Apps:

SharePoint 2013 Office Web Apps

SharePoint 2013 Office Web Apps documents

This is all Out of the box – yes, all out of box… You do not need to do any configuration on SharePoint 2013, just Office Web Apps to work with SharePoint 2013… And all the office documents when clicking “…” give you this pop-up and inside this you can navigate the slides and see if this is the document you are looking for! It works with all the office documents, if it is a Word Document it will show you all the pages and you can navigate through them…

Here is a screenshot when you search for a term and if it brings some documents in search results:

office-web-app-search

So it works with search as well, its quite a cool feature in search as with just the title and little description one cannot figure if this is exactly the document they are looking for, they can just hover the document and see the contents inside the document, as I said if its Power point slide you can navigate the slides, if it’s a word document you can view all the pages of the document etc.

Will cover more new features in SP 2013 in next posts!

External List with BCS & Search Filters

Business Connectivity Services let us to show our external data to SharePoint List, that external data may belong to any database or come through any web service, the most easily integrate able is Microsoft SQL Server database which is quite obvious as both are Microsoft technologies…

Moving forward, in this post we will see how can we make an External List and using Content Editor web part implement searching on the External List, so lets get started.

Making an External Content Type:

Using SharePoint Designer we will be making an External Content Type [which will then let us to make an External List], we will also on the way use Filter Parameters to support our searching feature.

1- Go to External Content Type section in SharePoint Designer

ExternalContentType

2- On the top, click New External Content Type

NewExternalContentType

3- Name the External Content Type [highlighted section] and then click on “Click here to discover external data sources and define operations

NewExternalContentType1

4- Now click Add Connection and you see a pop up like this:

image

We are selecting SQL Server in this case, now you will see a pop up like this,

image

Give all the necessary information here, you database server, database name and it will connect to your database showing your schema like this:

DBSchema

We will select our proper view or table we want to make External List for, and right clicking on it will show menu like Create All Operations etc. We will for now just create New Read List Operation and New Read Item Operation, because that will be useful in searching, you can create all operations and see the magic of Business Connectivity Services [BCS] in SharePoint.

5- On clicking New Read List Operation, will show a pop up with something like this:

ReadListOperation

Give proper name and move to Next Step, Filter Parameters. This section is important for searching as we will describe on what parameters the search will be made, click Add Parameters to add as many parameters you want to search on, the parameters actually refer to the fields in the View or Table you want searching on, this goes something like this:

FilterParams

On the right box Properties, select proper field you want the parameter on, in this case it is Access Number [one of the fields from view], now click (Click to Add) button in Filter property, this will open a pop up like this:

image

New Filter, name the filter according to the field – you can put any name [I put it to AccessNumber just for ease]. In Filter Properties, select Filter Type to Wildcard, Filter Field should be auto populated and check Ignore filter if Value is: and select Null. This is really important to make the search work, if the filter parameter value is nothing then it should ignore the filter and show all the results. We can add as many parameters as we like on different fields. I have added 4 parameters for now, the final result should be like this:

FilterParamsFinal

You can also specify whether it should be AND or OR between the parameters. After this click Finish.

6- Make New Read Item Operation, that will open up a pop up, just click Next Next Next three times and the operation will be ready for you. Now Save your External Content Type.

Your External Content Type is ready now, you can make an External List from it.

Making External List:

1- Come to External Content Type section in SharePoint Designer and Right click your External Content Type and click External List

ExternalListMaking

This will open a pop up for you to enter Name and Description for the External List:

image

Quickly you will get the External List ready, now navigate to your SharePoint website and look how this External List shows your items:

EmptyExternalList

You will see that the External List is empty, does that means the View did not return any results, NO! Your view may have results but the External List will show empty, because searching parameters are not set yet, what should you do now, we will update the External List aspx page to get this working with some JavaScript, lets do it Smile

Making the Search work:

1- In SharePoint designer go to External List here:

MoveToExternalList

Select it and you will be inside a detail window, here look into the Views section, you have to customize the default view for the External List, right click on the default view page, and click Edit File in Advanced Mode [or simply select it to go edit this page]:

EditViewListPage

2- Here you need to insert a Content Editor Web Part to allow some JavaScript and HTML to be embedded into the page, click after <ZoneTemplate> and in the Insert Tab you can see, Web Parts section like this:

image

Click on Web Part drop down and select Content Editor in Media and Content:

image

The page should look like this:

image

Now start typing something on “To add content, select this text and replace it by typing…” section and you will get the Content Tag ready.

3- In the content editor web part, insert some HTML Input Text box and an HTML button so that we can take input from user, in the Insert Tab find HTML section and select Input (Text) for textbox and Input (Button) for a button, as shown here:

image

Your content editor web part should look like this:

image

I have put it into a table for formatting, insert as many input textboxes as you have defined the filter parameters. This will generate some HTML in the Content Editor Web Part, go to Code mode to insert JavaScript to it.

<script type="text/javascript">
function ApplySearchFilters()
{
     try
     {
       var accessNumber = document.getElementById("txtAccessNumber").value;
       var url = window.location.href;
         if(url.indexOf("?") > 0)
         {       url = url.split("?")[0];
         }
 
         if(accessNumber.length > 0)
         {       url = url + "?FltAccessNumber=" + accessNumber;
         }
 
         window.location.href = url;
 
     }
     catch(ex)
     {}
 }
 
 function GetQueryStringValue(variable)
 {      var qs = location.search.substring(1, location.search.length);
 
     var args = qs.split("&");
     var vals = new Object();
 
     for (var i=0; i < args.length; i++)      {      var nameVal = args[i].split("=");
         var temp = unescape(nameVal[1]).split('+');
         nameVal[1] = temp.join(' ');
         vals[nameVal[0]] = nameVal[1];
     }
 
     return vals[variable];
  }
 
  function SetQueryStringValues()
  {
      try
      {
          var url = window.location.href;
          if(url.indexOf("FltAccessNumber") > 0)
          {
             var accessNumber = GetQueryStringValue("FltAccessNumber");
             document.getElementById("txtAccessNumber").value = accessNumber;
          }
      }
      catch(ex)
      {}
  }
 
  setTimeout("SetQueryStringValues();",100);
  </script>

These are the three functions that will help us to work our search,

  • ApplySearchFilters() function

In this function we have taken the textbox value and embed it with the current URL of the browser with a Query String parameter set to the value of the TextBox. As expected this function will be called on click of our Search button we gave in HTML.

  • GetQueryStringValue() function

This function will be used when the URL is redirected with all the Query String parameters we need to give, this function will get all the Query String values and add them into kind of HashTable with Key being the Query String variable name and Value being the Query String value. We will use this function to get specific value of a Query String parameter.

  • SetQueryStringValues() function

This function will also be used when the URL is redirected with all the Query String parameters and values, this will set all the textboxes with their respective values that the user had given before pressing Search button.

We have setTimeout and called SetQueryStringValues function every 100 milliseconds.

NOTE: For simplicity I have used only one Parameter that is AccessNumber, you can do the same for all the Parameters you have got.

Update your HTML Search button code and insert onclick attribute and set to ApplySearchFilters(), it should look like this:

<input onclick="ApplySearchFilters();" type="button" value="Search"/>

We have completed all the HTML and JavaScript work, now we will add Parameters and use those filters that we set when we made the External Content Type’s Read List Operation.

4- Select the XsltListViewWebPart which we had already on the page and you should see Options like this:

image

Select Parameters in the above to use the Query String parameters we set through JavaScript, clicking Parameters will open a Pop up like this:

image

Set it to the Query String parameter [variable] name you gave in JavaScript and set Default Value to “**”, it should look like above. We will use this parameter to be dynamic value for the Filter Parameter.

5- As we selected Parameters, select Finder from the top menu Options:

image

This should open a pop up like this:

image

Now click on “Click here to add a new clause…” and in Filter Name column you should see all the Filters that you added in the External Content Type’s Read List Operation. Select AccessNumber from it, and in the Value column you should see all the Parameters that we added just in the previous step.

image

Now replace [FltAccessNumber] to *{FltAccessNumber}* and press Ok, this should like this:

image

We have set all the things to get our search work, lets see the magic on External List Page.

See the magic to work

Now that you navigate to the page, you will see that by default the External List XsltListViewWebPart shows all the results returned by your View or Table, this should look like this:

image

Type in the AccessNumber and see if the search works:

image

The search looks great, and if you see at the URL of the browser after search, this should look like this:

http://server-name/Lists/All%20Students%20Blog/AllStudentsFRead%20List.aspx?FltAccessNumber=E-22001

That’s all Smile, I hope you enjoyed the blog…

Other content to read:

Searching External Data in SharePoint 2010 Using Business Connectivity Services

Happy SharePointing…

Introduction to Microsoft Entity Framework 4.1 in VS 2010–Part 1

Today, what I came across with was quite a new thing. Entity Framework is not that old thing for guys who use to work on Data Access through Microsoft Standards. But Entity Framework 4.0/4.1 has brought ORM (Object Relational Modeling) within them.

Linq To Sql was the ORM we used to access databases. I am going to discuss here, Entity Framework 4.1 in VS 2010.

So lets get started, for setting up your environment. Download the ADO.NET Entity Framework 4.1. Install the package and it will work with VS2010.

First, we are going to make a Class Library Project named CLEntityFrameworkDemo

image

this is how the Solution Explorer will look like:

SolutionExp

We are going to delete Class1.cs, and add New Item…

Add-Item

In this dialog, On the left we selected Data, and in data we are going to add ADO.NET Entity Data Model and name this Model MyModel.edmx.

NOTE: edmx stands for Entity Data Model XML (we will discuss why this XML is here, so don’t worry Smile )

image

As soon as we add MyModel.edmx, it asks whether we want and Empty Model or we already have a Database to which we want to Model.

image

The Empty Model lets you to insert Entities right inside the Entity Model designer and you can create database based on the Entity Model you have created. So now you can make your entities, define their relationships (0..1 to many, 1 to many, many to many etc.) and create database based on those entities.

We are going to select Empty Model for now, I just want you to show how we can create entities and then create a database from them. And this is how your VS will look like after adding:

image

Toolbox: We have got Association (Relationship), Entity (Object Model) and Inheritance. So now you can imagine a picture of what its all about Winking smile

Solution Explorer: The main reference we need to have is the System.Data.Entity class which is necessary for this. Note the MyModel.edmx has MyModel.Designer.cs file with it. So its just like we have dbml file in Linq to Sql having a Designer.cs file.

We will cover what we have in the Designer class so that we can play around with it. For now, lets make entities for our demo. You can drag and drop Entity from Toolbox.

image

I have changed name from Entity1 to Customers. Notice the properties we have Abstract = False, wow… So we can make Abstract Entities here… For Example, we have People’s Abstract Entity, and we can have Customers and Vendors having Base Type as People. Also, we do not have to care about database, it will be created by this Model automatically Smile. Here is the sample model:

image

I have changed Customers “Id” attribute to “CustomerId”, since we cannot have same attribute names as that of Base Type entity. Now we can generate database from this model, lets try this… Right click on Entity Designer and click ‘Generate database from model’.

Generate-db

This will open up the database connection dialog…

Connection

Notice that the entity model has its own kind of connection string, containing the Database connection string as a part of it. Click next:

  1:
  2: -- --------------------------------------------------
  3: -- Entity Designer DDL Script for SQL Server 2005, 2008, and Azure
  4: -- --------------------------------------------------
  5: -- Date Created: 04/26/2011 13:59:20
  6: -- Generated from EDMX file: D:\PROJECTS\BLOGS\CLEntityFrameworkDemo\CLEntityFrameworkDemo\MyModel.edmx
  7: -- --------------------------------------------------
  8:
  9: SET QUOTED_IDENTIFIER OFF;
 10: GO
 11: USE [EFBlog];
 12: GO
 13: IF SCHEMA_ID(N'dbo') IS NULL EXECUTE(N'CREATE SCHEMA [dbo]');
 14: GO
 15:
 16: -- --------------------------------------------------
 17: -- Dropping existing FOREIGN KEY constraints
 18: -- --------------------------------------------------
 19:
 20:
 21: -- --------------------------------------------------
 22: -- Dropping existing tables
 23: -- --------------------------------------------------
 24:
 25:
 26: -- --------------------------------------------------
 27: -- Creating all tables
 28: -- --------------------------------------------------
 29:
 30: -- Creating table 'People'
 31: CREATE TABLE [dbo].[People] (
 32:     [Id] int IDENTITY(1,1) NOT NULL,
 33:     [Name] nchar(50)  NOT NULL,
 34:     [Address] nvarchar(max)  NOT NULL
 35: );
 36: GO
 37:
 38: -- Creating table 'People_Customers'
 39: CREATE TABLE [dbo].[People_Customers] (
 40:     [CustomerId] int IDENTITY(1,1) NOT NULL,
 41:     [Id] int  NOT NULL
 42: );
 43: GO
 44:
 45: -- Creating table 'People_Vendors'
 46: CREATE TABLE [dbo].[People_Vendors] (
 47:     [VendorId] int IDENTITY(1,1) NOT NULL,
 48:     [Id] int  NOT NULL
 49: );
 50: GO
 51:
 52: -- --------------------------------------------------
 53: -- Creating all PRIMARY KEY constraints
 54: -- --------------------------------------------------
 55:
 56: -- Creating primary key on [Id] in table 'People'
 57: ALTER TABLE [dbo].[People]
 58: ADD CONSTRAINT [PK_People]
 59:     PRIMARY KEY CLUSTERED ([Id] ASC);
 60: GO
 61:
 62: -- Creating primary key on [Id] in table 'People_Customers'
 63: ALTER TABLE [dbo].[People_Customers]
 64: ADD CONSTRAINT [PK_People_Customers]
 65:     PRIMARY KEY CLUSTERED ([Id] ASC);
 66: GO
 67:
 68: -- Creating primary key on [Id] in table 'People_Vendors'
 69: ALTER TABLE [dbo].[People_Vendors]
 70: ADD CONSTRAINT [PK_People_Vendors]
 71:     PRIMARY KEY CLUSTERED ([Id] ASC);
 72: GO
 73:
 74: -- --------------------------------------------------
 75: -- Creating all FOREIGN KEY constraints
 76: -- --------------------------------------------------
 77:
 78: -- Creating foreign key on [Id] in table 'People_Customers'
 79: ALTER TABLE [dbo].[People_Customers]
 80: ADD CONSTRAINT [FK_Customers_inherits_People]
 81:     FOREIGN KEY ([Id])
 82:     REFERENCES [dbo].[People]
 83:         ([Id])
 84:     ON DELETE NO ACTION ON UPDATE NO ACTION;
 85: GO
 86:
 87: -- Creating foreign key on [Id] in table 'People_Vendors'
 88: ALTER TABLE [dbo].[People_Vendors]
 89: ADD CONSTRAINT [FK_Vendors_inherits_People]
 90:     FOREIGN KEY ([Id])
 91:     REFERENCES [dbo].[People]
 92:         ([Id])
 93:     ON DELETE NO ACTION ON UPDATE NO ACTION;
 94: GO
 95:
 96: -- --------------------------------------------------
 97: -- Script has ended
 98: -- --------------------------------------------------

 

and it will generate a .sql file for creating all the entities. Cool isn’t it?

Lets look why edmx stands for Entity Data Model XML so why we have this XML here… Right click on the MyModel.edmx file in Solution Explorer and click Open With…

EDMX-Openwith

then select XML Editor….

image

At the first glance the XML will look quite complex

generated-xml

So, the edmx is actually an XML file, that’s why we have XML with edm Smile. Also, look at the above image, we have got SSDL Content i.e. the Storage Model, and CSDL Content i.e. Conceptual Model. Both are separately defined, Conceptual Model contains the entities and their relationship etc. information and Storage Model contains information on how to create these entities in database and how to cater relationships between entities in database.

That’s all for the first part Smile, in future parts we will look how to use this assembly to apply CRUD operations on database using this edmx we have generated.

Rich Text Box in Share Point 2010

As you guys know that in SharePoint 2010, we have pretty kool ribbon interface… and that the Rich Text Box used in sharepoint uses the functionality within ribbon… So how to add a Rich Text Box in Visual Web Parts or anywhere in Share Point 2010?

Well, the solution is quite simple… We can have a very known Share Point 2007 InputFormTextBox to use in Share Point 2010… Those who are new to SharePoint must know that this was an available control in SharePoint 2007…

   1: <SharePoint:InputFormTextBox ID="txtFeed" runat="server" RichText="true" 

   2: TextMode="MultiLine" RichTextMode="FullHtml" Columns="500" 

   3: Rows="10" />

But as I used this control in my Visual Web Part, I was not able to change the width of the control… neither by its Columns property nor by its Width property… So a work around to this is to have some CSS that is internally used by the control… i.e.

   1: table.ms-rtetoolbarmenu

   2: { width:100%; }

   3:  

   4: iframe.ms-rtelong

   5: { width:100%; } 

This will do the job… hope it might help some one Winking smile

Follow

Get every new post delivered to your Inbox.