The built-in validation in Silverlight 3.0 is a great new feature that can be used on essential Silverlight controls such as TextBox. Using this feature, it is possible to nicely display an error message and highlight the TextBox that has bad value.

In this post I will only cover validating data in TextBox controls, which are simply used in most forms to receive basic information such as Name, Surname and Email address. The completed and working version of this project can be downloaded from CodePlex from here. I will explain and provide solution on how to validate ComboBox, Radio Button controls or etc in another post soon, so please keep yourself updated on new posts here.

1. Create a basic form with a few TextBox controls in the xaml

2. Create a class, call it CustomValidation
Add the following code to your CustomValidation class:

private string message;
public CustomValidation(string message)
{
    this.message = message;
}
public bool ShowErrorMessage
{
    get;
    set;
}
public object ValidationError
{
    get
    {
        return null;
    }
    set
    {
        if (ShowErrorMessage)
        {
            throw new ValidationException(message);
        }
    }
}

 

3. Create an Extension class (Extensions)
To understand what is an Extension class and for more information about them visit my tutorial post “Extension methods in Silverlight and C#”.

In brief: Extensions will be your Extension class to extend any object of type FrameworkElement like TextBox controls within your application framework. It means you can use the public methods within this class as a “built-in” method for your TextBox.

Create a static public method and call it SetValidation. This method receives an instance of a FrameWorkElement and a string value, and returns nothing:

public static void SetValidation(this FrameworkElement frameworkElement, string message)
{
    CustomValidation customValidation = new CustomValidation(message);
    Binding binding = new Binding(“ValidationError”)
    {
        Mode = System.Windows.Data.BindingMode.TwoWay,
        NotifyOnValidationError = true,
        ValidatesOnExceptions = true,
        Source = customValidation
    };
    frameworkElement.SetBinding(Control.TagProperty, binding);
}

 

CustomValidation is the class we defined earlier.

“Binding” is a class in System.Windows.Data assembly which gets or sets a value that indicates whether to raise the error attached event on the bound object.

What are we doing? Here we have a CustomValidation class that has one property (“ShowErrorMessage”) and one public methods (“ValidationError”). “ValidationError” is our source binding object and what we want to be able to do in the future is to bind our frameworkElement, which is a TextBox, to ValidationError. We are in simple words binding the CustomValidation class to our TextBox once we call this method on our TextBox.

For more information on Binding and BindingExpression visi msdn article here.

Create another two methods for displaying validation error and also for clearing validation error when the error was corrected:

public static void RaiseValidationError(this FrameworkElement frameworkElement)
{
    BindingExpression b =
    frameworkElement.GetBindingExpression(Control.TagProperty);
    if (b != null)
    {
        ((CustomValidation)b.DataItem).ShowErrorMessage = true;
        b.UpdateSource();
    }
}

public static void ClearValidationError(this FrameworkElement frameworkElement)
{
    BindingExpression b =
    frameworkElement.GetBindingExpression(Control.TagProperty);
    if (b != null)
    {
        ((CustomValidation)b.DataItem).ShowErrorMessage = false;
        b.UpdateSource();
    }
}

 

By creating a new BindingExpression you will be creating an instance of your binding so you can control the properties and public methods of your binding source/target. In above case, we are casting the BindingExpression.DataItem as CustomValidation. This enables us to access the properties of this class, “ShowErrorMessage” in this case.

4. RaiseValidationError() and ClearValidationError()
So now we have our TextBox, a method in our Extension class to bind the TextBox to our CustomValidation class and passes our error message, and a method in our Extension class that fires throw new ValidationException(message); from the CustomValidation class.

All we need to do now is to check if a specific TextBox is valid or not. If the TextBox was not valid we can simply use the RaiseValidationError() and ClearValidationError() methods, which should now be available from the intellisense in Visual Studio, to throw the validation exception and display a suitable error message and we do that by following code when the submit button was pressed:

Name.ClearValidationError();
bool isFormValid = true;
if (Name.Text == “”)
{
    Name.SetValidation(“Please enter your name”);
    Name.RaiseValidationError();
    isFormValid = false;
}

 

use isFormValid variable to check if you have to submit the form or not. The Name.ClearValidationError() makes sure you clear the form everytime you press submit, so if the form was valid the error message had already been cleaned.

I have some extra validation extensions on this project and have organised the code in different class files. Download the project from here.

http://www.silverlighttips.com/post/2009/10/08/SilverlightValidationTextBox.aspx

Click on pen to Use a Highlighter on this page
Tagged with:
 

Tito y la FIFA…

Widget FIFA World Cup 2010 for SharePoint!

Si bien hace unos días les comentaba del WebPart de Tam-Tam para seguir el mundial en nuestros sitios de SharePoint, ahora les dejo una solución, mas simple, efectiva y actualizada al Minuto…

Lo que tenemos que hacer es sumamente simple, solo vamos al Sitio donde queremos tener el Widget publicado, editamos la página y agregamos un nuevo WebPart Editor de Contenido, luego vamos a las propiedades y seleccionamos Código Fuente y en la ventana, solo tienen que copiar el siguiente código : Descargar Widget.txt

El resultado es el siguiente y podrán ver el siguiente Widget en su Portal de SharePoint :

Aquí les dejo un par de Screenshots de Como se Ve ya en SharePoint, si quieren cambiar el País de Referencia, solamente seleccionan Añadir Widget, seleccionan su país, y copian el código fuente que se genera automáticamente.

uru chile

Desde aquí, pueden ver los Comentarios, Resultados, Fechas de los Partidos y cuando se juega el partido, los resultados en tiempo Real. Para que funcione, se debe contar con acceso a Internet en los equipos de los usuarios para que se visualice correctamente.

Espero les sea de utilidad. Lógicamente, funciona en SharePoint 2007 y 2010.

Comentarios de la casa: buena Tito, ahora nos enteramos que funciona en 2007 y yo llorando por un 2010….je..je..

http://hinsua.blogspot.com/2010/06/widget-fifa-world-cup-2010-for.html

Click on pen to Use a Highlighter on this page
Tagged with:
 

Para trabajar con LINQ para SharePoint 2007 (por ahora ya viene el 2010 a todo full)

Tienes que descargar el VS 2008 SDK.

http://www.microsoft.com/downloads/details.aspx?FamilyID=59EC6EC3-4273-48A3-BA25-DC925A45584D&displayLang=en

Y si no has descargado el proyecto en CodePlex… hazlo ya! mucha productividad.

http://linqtosharepoint.codeplex.com/

Introduction

The LINQ to SharePoint project provides a custom query provider for LINQ that allows to query SharePoint lists using familiar LINQ syntax. LINQ stands for Language Integrated Query and is one of the core features of Microsoft’s .NET Framework 3.5 release. More information can be found via the MSDN website on http://msdn.microsoft.com.

Visit our team blog at http://blogs.bartdesmet.net/LINQtoSharePoint. Also check out this Channel 9 geekSpeak video.

Features

  • Custom query provider that translates LINQ queries to CAML, the Collaborative Application Markup Language used by SharePoint for querying.
  • Support for LINQ in C# 3.0 and Visual Basic 9.0.
  • Entity creation tool SpMetal to export SharePoint list definitions to entity classes used for querying.
  • Visual Studio 2008 integration for entity creation (a.k.a. SPML).
  • Can connect to a SharePoint site either using the SharePoint object model or via the SharePoint web services.
  • Planned support for updating through entity types.

Status

  • 11/29/2007 – v0.2.4.0 alpha release for .NET Framework 3.5 and Visual Studio 2008 RTM (release bulletin)
  • 08/13/2007 – v0.2.3.0 alpha release available for Orcas Beta 2 (release bulletin).
  • 08/01/2007 – Sources updated for Orcas Beta 2. A new release targeting Orcas Beta 2 will be provided soon.
  • 07/20/2007 – v0.2.2.0 alpha release available for Orcas Beta 1 (release bulletin).
  • 07/06/2007 – We’re currently working on an interim release that focuses on code maintainability and some design changes to enable the 0.3 update feature set. This interim release will be the first to cover SPML and Visual Studio 2008 integration with a code generator and an improved debugger visualizer.
  • 06/30/2007 – v0.2.0.0 alpha release available for Orcas Beta 1 (release bulletin).
  • 06/08/2007 – The 0.2 release is planned to become available later this month; the (draft of the) technical spec is now under source control too (/Specs folder).
  • 05/04/2007 – Work has started on the 0.2 release. The 0.2 release will cover enhanced support for different field types in SharePoint, including Lookup fields, and extended overall test coverage.
  • 04/23/2007 – v0.1.2.0 alpha release available for Orcas March 2007 CTP (update for Beta 1 coming soon).

Samples

For a list of samples and a quick-start guide, see Samples.

C# sample

    // updated for the 0.2.2.0 alpha release
    var ctx = new SharePointDataContext(new Uri("http://wss.mycompany.local"));
    ctx.Log = Console.Out;
    var users = ctx.GetList<Users>(ctx);

    var res = from u in users
              orderby u.Birthdate descending
              where u.FirstName.StartsWith("B") && u.Age >= 24 && u.FavoriteFood == FavoriteFood.Pizza
              select new { u.FullName, u.Age, Interest = u.AccountBalance * 0.07 };

    foreach (var u in res)
        Console.WriteLine(u);

Visual Basic sample

    ' updated for the 0.2.2.0 alpha release
    Dim context As New SharePointDataContext(New Uri("http://wss.mycompany.local"))
    context.Log = Console.Out
    Dim users = context.GetList(Of User)()

    Dim res = From u In users _
              Order By u.Birthdate Descending _
              Where u.FirstName.StartsWith("B") And u.Age >= 24 And u.FavoriteFood.Value = FavoriteFood.Pizza _
              Select u.FullName, u.Age, Interest = u.AccountBalance.Value * 0.07

    For Each u In res
        Console.WriteLine(u)
    Next

About the project founder

A former Visual C# MVP, Bart De Smet now works at Microsoft Corporation on the WPF dev team in an SDE role. Prior to this new challenge, Bart was active in the Belgian community evangelizing various Microsoft technologies, most of the time focusing on CLR, language innovation and frameworks. In his evangelism role, he’s been speaking at various events and attended several international conferences including TechEd Europe, IT Forum and the PDC. In 2005, Bart graduated as a Master of Informatics from Ghent University, Belgium. Two years later, Bart became a Master of Computer Science Software Engineering from the same university.

You can visit Bart’s blog on http://blogs.bartdesmet.net/bart

Last edited Nov 29 2007 at 3:37 AM by bdesmet, version 33
Click on pen to Use a Highlighter on this page
Tagged with:
 

LINQ to SharePoint – Part II

Windows SharePoint Services 3.0

You can download the Windows SharePoint Services 3.0 here (http://www.microsoft.com/technet/windowsserver/sharepoint/download.mspx ). Please read the installation notes carefully. When installing SPS 3.0, the installer will make you aware of any prerequisites that are needed.

The idea is to execute LINQ-queries against lists in SharePoint. I’ve created a list of books on my SharePoint site and added some data to it. The list consists of 4 columns: Title, Author, number of pages and ISBN.

clip_image002

First LINQ to SharePoint application

By using simple code examples, I will teach you how to create and configure a connection to a SharePoint site and how to build and execute queries. We’ll start with an example of how to connect to the SharePoint site, execute a simple query and display the results of the query.

First, create a new Console Application (I’ve named it LinqToSharePointExample1) in Microsoft Visual Studio 2008. Then right-click on your project’s name in the Solution Explorer and choose “Add New Item…” to add a new LINQ to SharePoint file.

clip_image0022

Give the file an appropriate name, by default the name will be DataClasses1.spml. I’ve named my file Books.spml, because that’s the name of the list on the SharePoint site.

When clicking the Add-button, the wizard starts. After connecting to your SharePoint site, you will be given a list of available lists. You can choose the list(s), and per list you can specify individual fields you want to use.

clip_image0041

The SPML (which stands for SharePoint Mapping Language)file itself describes all the fields of the list in XML. You will notice that there are more fields than you’ve created. In this example, I’ve created a list of books, with columns for author, title, number of pages and ISBN-number. SharePoint will keep some other information for you, such as the content type and the creation and modification date.

For each SPML file another file, called [name].designer.cs (in my case Books.designer.cs), is generated. The generated code forms the backend of the link to your SharePoint site (the bridge between your application and the SharePoint site, if you will). I will not go into further detail, as the content and generation of that file are a chapter of their own.

To create a connection, you must instantiate  the SharePointDataContext that has been generated by LINQ to SharePoint. The default constructor will connect to the SharePoint site over web services, while an overloaded version is available which uses the SharePoint Object Model. But this is only available if your program is running on the same machine as your SharePoint site. In my case (SharePoint is running on another server), it’s something like this:

var ctx = new LinqToSharePointExample1.BooksSharePointDataContext();

If you are using Windows Authentication, this is all you need to do. If, however, your SharePoint site requires a username and password, Network Credentials need to be added by doing the following:

Add a System.Net using statement:

using System.Net;

In the code, add new credentials to the connection:

ctx.Credentials = new NetworkCredential(“dimitri”,”LinqToSharePoint”);

The first parameter represents the user name; the second parameter represents the password. You might notice that you already supplied your username and password at the beginning of the Entity Creation Wizard. Those credentials are only used at design time. This is done for security reasons and to emphasize the difference between design time and runtime.

Now a connection has been made, and we can create a query. I will simply use a variable to store the result of the query and refer to it using the C# 3.0 var keyword, used for local type inference. After that, I would like to check the content of that variable by displaying all the results. The query will request a list of all the books and their authors (so no number of pages, ISBN,…):

var res = from b in ctx.Books
          select new { b.Title, b.Author}; 

foreach (var u in res)
   Console.WriteLine(u);

When executing this code, the console-display shows the following set of results:

{ Title = Common Language Runtime, Author = Steven Pratschner }
{ Title = Programming .Net Components, Author = Juval Löwy }
{ Title = Design Patterns in C#, Author = Steven John Metsker }
{ Title = CLR via C#, Author = Jeffrey Richter }
{ Title = Professional ASP.NET 2.0, Author = Bill Evjen, Scott Hanselman, Farhan Muhammad, Devin Rader, Srinivasa Sivakumar }
{ Title = Patterns of Enterprise Application Architecture , Author = Martin Fowler }
{ Title = Windows Presentation Foundation Unleashed , Author = Adam Nathan }
{ Title = Managing Software Requirements, Author = Dean Leffingwell, Don Widrig }
{ Title = Microsoft SharePoint 2007 Unleashed , Author = Michael Noel, Colin Spence }

http://technoblogy.spaces.live.com/blog/cns!29F7CF27A98D236F!284.entry

Click on pen to Use a Highlighter on this page
Tagged with:
 

LINQ to SharePoint – Part I

 What is LINQ to SharePoint?

The LINQ to SharePoint project provides a custom LINQ query provider that allows you to query SharePoint lists using familiar LINQ syntax. LINQ stands for Language Integrated Query and is one of the core features of Microsoft’s .NET Framework 3.5 release. This project falls under Ms-LCL License.

To find the latest news, check the web site at http://www.codeplex.com/LINQtoSharePoint.

There is also a LINQ to SharePoint blog which can be found at http://blogs.bartdesmet.net/linqtosharepoint.

The project features:

  • Custom query provider that translates LINQ queries to CAML, the Collaborative Application Markup Language used by SharePoint for querying.
  • Support for LINQ in C# 3.0 and Visual Basic 9.0.
  • Entity creation tool SpMetal to export SharePoint list definitions to entity classes used for querying.
  • Visual Studio 2008 integration for entity creation (a.k.a. SPML).
  • Can connect to a SharePoint site either using the SharePoint object model or via the SharePoint web services.
  • Planned support for updating through entity types.

Development is done by Bart De Smet. He is Microsoft MVP for Visual C# and specializes in various Microsoft-related technologies, covering .NET Framework development, CLR, C#, SQL Server and Windows Server System. Since the year 2000, Bart evangelizes Microsoft technologies and delivers presentations on several technology events. Beside his evangelism efforts, he’s busy maintaining his blog, writing articles for the local MSDN website in Belgium and doing consultancy for various development projects, spending long and lonely nights with his computer. In 2005, Bart graduated as a Master Informatics from the university of Ghent, Belgium with a summa cum laude degree. Two years later he got a Master of Computer Science (Software Engineering) degree from the same university.

Blog: http://blogs.bartdesmet.net/bart

Where to get LINQ to SharePoint?

LINQ to SharePoint is available in several forms. Next to a regular installer (MSI-package) the project’s source code is also available for download. The reason for making the code available is to help others in implementing custom LINQ query providers. In order to use LINQ to SharePoint, one needs the .NET Framework 3.5. If you want to profit from the Visual Studio 2008 integration, you should have Visual Studio 2008 Professional or higher. (see http://go.microsoft.com/?linkid=7175502 to download Visual Studio 2008 Beta 2)

The installer and source for the latest release can both be found in the “Releases”-tab on http://www.codeplex.com/LINQtoSharePoint . The latest sources can be found via the “Source Code”-tab on the same web site.

If you’ve downloaded the source code, you will need the Visual Studio 2008 SDK in order to build the Visual Studio 2008 integration components. The SDK can be found here (http://www.microsoft.com/downloads/details.aspx?FamilyID=D9000E2C-BD3F-4717-A181-723960814E16&displaylang=en). If the SDK is not installed, you will get the following error:

clip_image002

To install the LINQ to SharePoint libraries, run the installer and this will automatically install the libraries and configure Visual Studio 2008. To use the library you can simply add a new LINQ to SharePoint file. You can do this by right-clicking the project, Add, New Item, selecting the LINQ to SharePoint file and clicking Add.

clip_image004

This will automatically add a reference to the library to your project.

If you want to manually add this reference, follow these steps::

1. Add the reference to the library by clicking the “Add Reference” item on the properties menu of your project (right-click on the project node in Solution Explorer and choose Add Reference…)
clip_image006

2. In the .NET-tab of the Add Reference dialog, select the LINQ to SharePoint runtime library (BdsSoft.SharePoint.Linq) and click OK.
clip_image008

3. In Solution Explorer, the library has been added to the references:
clip_image009

In your project’s source code, add a using-statement:

using BdsSoft.SharePoint.Linq;

Now the library is ready to be used.

Next week, there will be a post explaining SPMetal and some basic LINQ to SharePoint code samples to get you started.

http://technoblogy.spaces.live.com/blog/cns!29F7CF27A98D236F!274.entry

Click on pen to Use a Highlighter on this page
Tagged with:
 

Skype Online Status 

Contáctanos por Skype Call me! - Rolando Escobar: Offline
» Get Skype, call free! Servicios en Línea
 
 
Servicios Interdata Ltda. Colaboración e Inteligencia de Negocios, SQL Server 2008, Analysis Services, SharePoint, Excel Services, Reporting Services

Switch to our mobile site