Sharepoint 2010: Creating a Visual WebPart


imageSharepoint 2010 comes with huge enhancements in the development experience, exists a feature that i am sure a lot of programmers were waiting, this is the capability to create Webparts using a visual interface, in Sharepoint 2010 this is done and is called Visual WebParts

To create  a Visual Webpart, first we should create a Visual Studio Project, i selected the Empty Project template for Sharepoint 2010, when the project is created the Sharepoint Customization Wizard is launched, the first innovation are the 2 kinds of solutions that we can create and deploy to our Sharepoint Site: Sandboxed Solutions and Farm Solutions (the complete explanation about the differences need a new post) but a quick explanation is that the Sandboxed Solutions running on an isolated environment with limited resource access of this way if exists any exception in the solution, the entire farm is not affected just an inferior level, for this sample choose the second option.

 

I have to say that i LOVE the new Sharepoint development tools in VS2010, the Solution explorer is completely descriptive and useful to manage features of the solution. Add a new item to the solution, choose the Visual Webpart Template from the dialog  and edit the .webpart file to customize the name and description of our WebPart.

   1: private const string _ascxPath = @"~/_CONTROLTEMPLATES/Gotchas.Webparts/ListSummary/ListSummaryUserControl.ascx";
   2:  
   3:         public ListSummary()
   4:         {
   5:         }
   6:  
   7:         protected override void CreateChildControls()
   8:         {
   9:             Control control = this.Page.LoadControl(_ascxPath);
  10:             Controls.Add(control);
  11:             base.CreateChildControls();
  12:         }

image

What’s a Visual Webpart?, such as you can see in the webpart code file exists a reference to an ASP.Net UserControl, this control is loaded dynamically in the call to CreateChildControls method.

This approach allows edit visually the Webpart interface using the ASP.Net Control, but brings new challenges, first let me create the UI for the webpart, this is a really simple interface for this webpart, the goal for this webpart is show the total number of items from any list, for this i need create a custom property that allows set the input list, the name for this property is InputList, this property is decorated with various attributes that defines the behavior of the property in Browse Time.

 

The custom property is defined into the Settings category in the webpart properties window, this property stores the name of the list to get the total of items. The most easy way to set this value to be used in the UserControl is creating a public property in the UserControl and overwriting the code to load the UserControl, in the call to CreateChildControls method, in my case i have created the public property InputList in the user control to store the value from the webpart custom property, our code should like to this

   1: protected override void CreateChildControls()
   2:         {
   3:             SurveyBoardUserControl control = (SurveyBoardUserControl)this.Page.LoadControl(_ascxPath);
   4:             control.InputList = InputList;
   5:             Controls.Add(control);
   6:             base.CreateChildControls();
   7:         }

 

 

 

 

 

The code in the UserControl looks like

   1: public partial class SurveyBoardUserControl : UserControl
   2:     {
   3:         protected void Page_Load(object sender, EventArgs e)
   4:         {
   5:  
   6:             if (!String.IsNullOrEmpty(InputList))
   7:             {
   8:                 using (SPWeb currentWeb = SPContext.Current.Web)
   9:                 {
  10:                     SPList inputList = currentWeb.Lists.TryGetList(InputList);
  11:                     if (inputList != null)
  12:                     {
  13:                         totalItemsLabel.Text = inputList.ItemCount.ToString();
  14:                         listNameLabel.Text = InputList;
  15:                     }
  16:                     else
  17:                     {
  18:                         listNameLabel.Text = "Not found list";
  19:                     }
  20:                 }
  21:             }
  22:  
  23:  
  24:         }
  25:  
  26:         public String InputList { get; set; }
  27:     }

Finally only need deploy our solution, add our webpart to home page and set the Input List property, to see the results

image

See u

author: Juan Mestas J. (aka gotchas) | posted @ Monday, December 28, 2009 12:32 AM | Feedback (0)

Sharepoint 2010: New Branching feature in Surveys


I just installed Sharepoint 2010 on Windows 7 and i’m looking for the new features in the Information Worker area as first step. My first impressions are very favorable to the new look & feel and Content Management, i love the ribbon-based interface.

Well, i begun my Sharepoint quest adding Lists to my site. The new interface to add lists to content is so cool, completely based on Silverlight

image

I added a new Survey List to my Site and i can observe the new branching feature for customize the flow of the questions in the survey, i just say simple and cool

First you should create the survey’s questions using the Add Questions option in the Settings menu image

 

Once we have completed the questions, we have add Branching Logic using the Setting menu and editing the questions. In my case i have 4 questions about programming languages, the second question have the branching logic to continue with the survey flow

image

As we can see this is a really simple and useful feature to manage the content of the surveys in Sharepoint Foundation

See u

author: Juan Mestas J. (aka gotchas) | posted @ Sunday, December 27, 2009 8:15 PM | Feedback (0)

Microsoft Live Labs “Pivot”


As usual in my walk trough Live Labs, i found “Pivot”, well what is it? in the own words from Live Labs, Pivot is a new way to interact with massive amount of data in the web using “Collections”. “Collections” are the heart the Pivot, they combine large groups of similar items on the Internet, so we can begin viewing the relationships between individual pieces of information in a new way.

image

Conceptually, a collection is just like any other web content. There’s a set of files on a server, and a local client that knows how to display them. In the current web, the files are traditionally HTML and images. In the collection case, the files are CXML and Deep Zoom-formatted (DZC) images. Depending on whether the user browses web pages or collections, the Pivot client will either use the embedded IE rendering engine (IE 8) or the collection browser to display the files.

New collections can be created with no code because they are only data. exists three types of Collections:

Simple, up to 3000 items

Linked, limited by storage complexity

Dynamics, unbounded

The types differ primarily in size and their ability to respond to custom user queries. Structurally, they are composed of either previously generated or static XML, or XML generated dynamically in response to a query

To begin to work with Collections and create your custom collection Pivot offers the Collection Design Tool that works how an add-in for Excel, this add-in works nice with Office 2010 Beta

If you want join to the technical discussion panel and interact with the Pivot Team you can click here

See you

author: Juan Mestas J. (aka gotchas) | posted @ Sunday, December 27, 2009 1:06 PM | Feedback (0)

MS Research Entity Cube


Entity Cube is an entity search and summarization engine, which automatically summarizes the Web for the long tail, not just celebrities! The Chinese-language version is called Renlifang.

I just look/used the Entity Cube and i can say that it’s VERY COOL!!!!, in like way that an analysis cube, Entity Cube summarizes all results and generates a profile of them

EntityCube automatically generates:

  • A biography page for a person.
  • A social-network graph for a person.
  • A shortest-relationship path between two people.
  • All titles of a person that are found on the Web.

Not more words, you try it!!

See you

author: Juan Mestas J. (aka gotchas) | posted @ Monday, December 07, 2009 4:59 PM | Feedback (0)

To my wish list for .Net 4.0: Linq to Entities


I am working with Entity Framework as model in a REST service, using the CollectionService<T> and i found a little issue in the behavior of Linq to Entities,this is well know but i hope a change in .Net 4.0

Currently Linq to Entities not supports projections that returns types with parameterized constructors, by instance for a method that return a IEnumerable<KeyValuePair<string, Course>> i wanna make

   1:  .Select(c => new KeyValuePair<string, CustomType>(c.StringProperty, c))
 

This projection for me is pretty natural, but thrown the next error: “Only parameterless constructors and initializers are supported in LINQ to Entities”

My workaround (model is an instance of my Entity Framework ObjectContext)

   1:  protected override IEnumerable<KeyValuePair<string, Course>> OnGetItems()
   2:          {
   3:                        
   4:              List<Course> Course = model.Courses.Select(c => new Course() { Code = c.Code, Description = c.Description, Name = c.Name, OpenDate = c.OpenDate }).ToList();
   5:              Dictionary<string, Course> returnCourse = new Dictionary<string, Course>();
   6:              Course.ForEach((Course item) =>
   7:              {
   8:                  returnCourse.Add(item.Code, item);
   9:              });
  10:   
  11:              return returnCourse;
  12:   
  13:   
  14:          }

See you

author: Juan Mestas J. (aka gotchas) | posted @ Sunday, October 11, 2009 11:18 PM | Feedback (1)

Microsoft TechCamp 09


Hi Folks,

This Tuesday 13th (yeah, i know good day for the supernatural) will be the first TechCamp at Lima-Peru, i am in charge of the session about Silverlight 3 in the develop of LOB Applications with Manuel Miranda (aka Mani) that will go to talk about UX (beyond decorations).

I would love hear your feedback for this session, what want you see? RIA Services? OOB Approach?

See you

author: Juan Mestas J. (aka gotchas) | posted @ Sunday, October 11, 2009 11:02 PM | Feedback (0)

Querying to XML structures that have a namespace


Yesterday working in a demo about WCF-REST Starter Kit (http://www.asp.net/downloads/starter-kits/wcf-rest/) i had a little issue to make a query to a XML Structure that includes a xml namespace (aka xmlns), the trick is very simple to get the value from each element in the structure, you should pass the XName in Elements method including the XNamespace

This is my XML structure

<ItemInfoList xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
- <ItemInfo>
  <EditLink>http://localhost:17673/Services/Courses.svc/S02</EditLink> 
- <Item xmlns:a="http://schemas.datacontract.org/2004/07/DotNetUniversity">
  <a:Code>S02</a:Code> 
  <a:Description>La Transferencia de Estado Representacional (Representational State Transfer) o REST es una técnica de arquitectura software para sistemas hipermedia distribuidos como la World Wide Web. El término se originó en el año 2000, en una tesis doctoral sobre la web escrita por Roy Fielding, uno de los principales autores de la especificación del protocolo HTTP y ha pasado a ser ampliamente utilizado por la comunidad de desarrollo.</a:Description> 
  <a:Name>REST</a:Name> 
  <a:OpenDate i:nil="true" /> 
  </Item>
  </ItemInfo>
- <ItemInfo>
  <EditLink>http://localhost:17673/Services/Courses.svc/S01</EditLink> 
- <Item xmlns:a="http://schemas.datacontract.org/2004/07/DotNetUniversity">
  <a:Code>S01</a:Code> 
  <a:Description>La Arquitectura Orientada a Servicios (en inglés Service Oriented Architecture), es un concepto de arquitectura de software que define la utilización de servicios para dar soporte a los requisitos del negocio.</a:Description> 
  <a:Name>SOA</a:Name> 
  <a:OpenDate i:nil="true" /> 
  </Item>
  </ItemInfo>
  </ItemInfoList>

My custom collection

   1:  private ObservableCollection<CourseViewModel> courses = new ObservableCollection<CourseViewModel>();

 

This is the code to query this structure and populate a collection of a custom entities, BTW i’m using Silverlight 3 with MVVM approach

   1:  public void LoadCatalog()
   2:          {
   3:              courses.Clear();
   4:              WebClient client = new WebClient();
   5:              client.DownloadStringCompleted += (source, args) =>
   6:              {
   7:                  if (args.Error == null)
   8:                  {
   9:                      IEnumerable<XElement> coursesXml = XElement.Load(new StringReader(args.Result)).Descendants("ItemInfo");
  10:                      foreach (var item in coursesXml.Descendants("Item"))
  11:                      {
  12:                          XNamespace ns = "http://schemas.datacontract.org/2004/07/DotNetUniversity";
  13:   
  14:                          bool hasOpenDate = !String.IsNullOrEmpty(item.Element(ns + "OpenDate").Value);
  15:                          DateTime openDate = default(DateTime);
  16:                          if (hasOpenDate)
  17:                          {
  18:                              DateTime.TryParse(item.Element(ns + "OpenDate").Value, out openDate);
  19:                          }
  20:   
  21:                          courses.Add(
  22:                              new CourseViewModel(
  23:                                  new Course()
  24:                                  {
  25:                                      Name = item.Element(ns + "Name").Value,
  26:                                      Code = item.Element(ns + "Code").Value,
  27:                                      Description = item.Element(ns + "Description").Value,
  28:                                      OpenDate = openDate,
  29:                                      OpenDateSpecified = hasOpenDate
  30:                                  }));
  31:                      }
  32:                  }
  33:              };
  34:              client.DownloadStringAsync(new Uri("http://localhost:17673/Services/Courses.svc/"));
  35:          }

 

See you

author: Juan Mestas J. (aka gotchas) | posted @ Sunday, October 11, 2009 10:50 PM | Feedback (0)

Webcast MSDN: Integrating IE8 Features: Accelerators, Web Slices, Search Providers with our Web Sites / Integrando nuestros sitios con Windows Internet Explorer 8 usando Aceleradores, Web Slices y Proveedores de Búsqueda


Internet Explorer 8 exposes new ways for deliver features from our sites directly to our users. In this session we learn to use the new features of IE8 such as accelerators, web slices and search providers and how to integrate it with our sites

Internet Explorer 8 expone nuevas formas de entregar la funcionalidad que su sitio ofrece directamente a sus usuarios. Venga a esta sesión para aprender cómo usar nuestras nuevas actividades, Web slices y mucho más e integrarlas con nuestros sitios

Webcast Link

http://www.mslatam.com/latam/mediacenter/wcdetail.aspx?EventID=1032422247&p=&a=&k=&f=&t=

See you

author: Juan Mestas J. (aka gotchas) | posted @ Monday, October 05, 2009 3:14 PM | Feedback (0)

Extending Type class to get a type that implements an interface <IsImplementationOf>


Is really simple know if any type implements an interface in the traditional way we can use the “is” keyword to know if the class instance implements the interface, by instance

Interface

Code Snippet
  1. public interface IMarkable
  2.     {
  3.         void Mark();
  4.     }

 

Class that implements the interface

Code Snippet
  1. public class Marker : IMarkable
  2.     {
  3.         #region IMarkable Members
  4.  
  5.         public void Mark()
  6.         {
  7.             Console.Write("Do Mark!!");
  8.         }
  9.  
  10.         #endregion
  11.     }

 

Interface validation

Code Snippet
  1. Marker marker = new Marker();
  2.             if (marker is IMarkable)
  3.             {
  4.                 //Implements IMarkable
  5.             }

 

But if are we working with an instance of Type class, not exists a built-in method to determinate if the type implements the interface

A simple way to get this is extend the Type class using the Extensions Method feature, we can write something like this

Code Snippet
  1. public static class TypeExtension
  2.     {
  3.         public static Boolean IsImplemetationOf(this Type type, Type interfaceType)
  4.         {
  5.             Boolean returnBool = false;
  6.             Type[] interfaces = type.GetInterfaces();
  7.             for (int i = 0; i < interfaces.Length; i++)
  8.             {
  9.                 if (interfaces[i] == interfaceType)
  10.                 {
  11.                     returnBool = true;
  12.                     break;
  13.                 }
  14.             }
  15.             return returnBool;
  16.         }
  17.     }

In this manner we can make this validation when works with an instance of Type class

Code Snippet
  1. Assembly currentAssembly = Assembly.GetExecutingAssembly();
  2.             Type[] assemblyTypes = currentAssembly.GetTypes();
  3.             for (int i = 0; i < assemblyTypes.Length; i++)
  4.             {
  5.                 Type type = assemblyTypes[i];
  6.                 if (type.IsClass && type.IsImplemetationOf(typeof(IMarkable)))
  7.                 {
  8.                     //Implements IMarkable
  9.                 }
  10.             }

 

See you

author: Juan Mestas J. (aka gotchas) | posted @ Wednesday, September 30, 2009 12:21 AM | Feedback (2)

How to Load Application Templates dynamically from Resources files


Well on my last post, i talk about changes on controls in #Silverlight3, while i tried to use a demo about Navigation and Styles, Corrina and her team had developed 7 additional application templates, for the community to consume and they’ve put them up on the Expression Community Gallery for download:

Aurora

Frosted Cinnamon Toast

Lime Shocker

Pinky

Retro

Sky Line

Subdued

 

All templates are terrific and very easy to use only change the reference to the resource in the styles.xaml code file. But if we want work with all templates and load them, based on some policy or the user preference, in the same way that custom styles on ASP.Net? The easy way is get the template from the application host (ASP.Net), and pass it to Silverlight using the init parameters

Copy the styles.xaml files that you want use to the Assets folder in your project, rename each one of the files with a descriptive name, after define the logic for set the current theme in the Application Host (ASP.Net)

 

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Web;
   5:  using System.Web.UI;
   6:  using System.Web.UI.WebControls;
   7:   
   8:  namespace UIOne.Web
   9:  {
  10:    public partial class _Default : System.Web.UI.Page
  11:    {
  12:      protected void Page_Load(object sender, EventArgs e)
  13:      {
  14:          //Some sort of policy or user preference for get the current Theme
  15:          string applicationTheme = "Frosted.xaml";
  16:          this.Silverlight1.InitParameters = String.Format("applicationTheme={0}", applicationTheme);
  17:      }
  18:    }
  19:  }

 

Get the parameter in Silverlight code and rewrite the constructor of the Main class to receive one parameter

 
   1:    private void Application_Startup(object sender, StartupEventArgs e)
   2:          {
   3:              string applicationTheme = e.InitParams["applicationTheme"];
   4:              this.RootVisual = new MainPage(applicationTheme);
   5:          }

 

In the constructor of the Main class, get the resource file using the GetResourceStream method, create a StreamReader within the result and load the read content using the Load method from the XamlReader class

 

   1:   public MainPage(string applicationTheme)
   2:          {
   3:              string resurceUri = String.Concat("<<assembly>>;component/Assets/", applicationTheme);
   4:              StreamResourceInfo resourceInfo =
   5:                  App.GetResourceStream(new Uri(resurceUri, UriKind.Relative));
   6:              StreamReader resourceReader = new StreamReader(resourceInfo.Stream);
   7:              string xaml = resourceReader.ReadToEnd();
   8:              ResourceDictionary resourceTheme =
   9:                  XamlReader.Load(xaml) as ResourceDictionary;
  10:              App.Current.Resources.MergedDictionaries.Add(resourceTheme);
  11:   
  12:              InitializeComponent();
  13:          }

 

Now test the project, modifying the value for applicationTheme variable

See you

author: Juan Mestas J. (aka gotchas) | posted @ Thursday, July 30, 2009 3:17 AM | Feedback (3)