My PhotoBruno Brás Silva

09, April 1986

info@brunosilva.net

Sintra Lisbon Portugal

Category: .NET

Slide.Show - Generate data.xml using ASP.NET

Posted on 4:33pm 3/19/2008 by Bruno Silva in .NET, ASP.NET, Programming, Silverlight, Web

A while ago I talked about Slide.Show. Some one asked me how to dynamically look into a folder and create a slide show based on its contents. I suggested using an ASP.NET page that looks into the folder and generates a XML output that can be used by Slide.Show as a data source.

I’ve implemented a simple version that shows how to do it. Download it and change it as you wish.

Take a look at DataProvider.js where I have changed the Data.xml reference to Data.aspx file.

In the Data.aspx file I’ve deleted all the HTML output, and in the Page_Load event handler generated XML output.

Response.ClearContent();
Response.ContentType = “Application/xml”;
Response.Write(”{XML output}”);
Response.End();

I’ve included in the zip file only the required files to let the example work. It has only 1 image. I hope it will be useful to someone. :)

Joining Windows Live ID and ASP.NET Membership Provider

Posted on 1:28pm 3/08/2008 by Bruno Silva in .NET, ASP.NET, Programming, Windows Live

Windows Live ID - ASP.NET Membership Provider

As you might know, it is possible to use Windows Live ID Web Authentication SDK in your websites as an authentication mechanism. You put an iframe in your homepage, which links to the Windows Live ID sign in page. After a successful authentication the user is redirected back to your website, where you receive the user’s ID. With this ID you can find your user data in your database, and do whatever you need.

Since ASP 2.0, you can use the ASP.NET Membership/Roles Provider as an authentication/authorization mechanism in your websites. You even have controls that make these tasks easy. If you are not familiar with these functionalities take a look at a nice video available in the ASP.NET website: Securing your Web Site with Membership and Login Controls.

Yesterday I started to build a new website, and I wanted to use Windows Live ID as the authentication mechanism. But since I was using an existing website framework that used ASP.NET Membership/Roles Provider not only for authentication but also for authorization purposes, I tried to integrate both. I wanted to eliminate the need for a new user/password for the user to remember, and maintain the benefits of Membership Provider.

You can download the demo website that I wrote which is a simplified version of the website that I am building. It is pretty simple. Do not forget to register you application and change the corresponding parameters in web.config.

The first step is to configure ASP.NET Membership provider. You can use a tool that allows you to add the membership provider tables to your database (C:\Windows\Microsoft.NET\Framework\v2.XXXXXX\aspnet_regsql.exe) or use Web Site > ASP.NET Configuration menu in Visual Studio that creates an SQL Server Express database to store the data.

In your web.config file you must setup the Membership Provider. I’ve done some configuration which allows you to create users using just an user name and a password (eliminating the usual e-mail, question and answer of password recovery, etc). You will be using Forms authentication.

I have a default.aspx page which has an iframe that has a link to Windows Live ID sign in page. When you click the sign in link you are redirected to the sign in page, and the forwarded back to your website, to a authentication handler page named webauth-handler.aspx. This page is part of a sample that comes with Windows Live ID Web Authentication SDK.

Windows Live ID - Sign In

You will have just to add a few lines of code, that maps the Windows Live ID authentication to the Forms authentication of your website. You can see these lines in the demo website.

When you sign in with an account that is not registered in your website, a user account is created (only using the user ID as username and password), and you are redirected to a page where you can edit your profile.

Profile Provider is another great functionality of ASP.NET that allows you to assign custom data to your website users. In web.config you define which properties does a user profile has. Then you can access the Profile object from anywhere in your code, and read/write the current user profile properties. These properties can be changed, and Profile object has a Save method that persists the profile information into the Profile Provider (usually a database).

In default.aspx the current user profile is printed out into the page.

Visual Studio Color Schemes

Posted on 11:41pm 2/16/2008 by Bruno Silva in .NET, Programming

Visual Studio Color Schemes

Nowadays we are used to customize a lot of the software we use by applying theming and skinning along with other settings. This kind of customization is present in the operating systems, messaging applications, web applications, etc.

Well, when it comes to development environments it is also possible to do that, and many people do.

Take a look at this blog where you can find several color schemes that can be used in Visual Studio. Just code with the colors that make you comfortable, or as your boss would demand: productive. :-P

These kind of setting can be imported/exported in the Tools menu in both Visual Studio 2005 and 2008.

Visual Studio Import Settings

Sharp Develop

Posted on 11:12am 1/30/2008 by Bruno Silva in .NET, Open Source, Programming, Software

SharpDevelop

#develop (short for SharpDevelop) is a free and open-source IDE for C#, VB.NET and Boo programming language projects on Microsoft’s .NET platform. Of course that Microsoft Visual Studio Express Editions are freeware and are better that this IDE, but with #develop you get a chance to take a look a the source code and who knows, adapt it to develop in another language. #develop in written in C#.

SharpDevelop

The list of main features can be found in the project’s community website.

.NET Framework Library Source Code Debugging

Posted on 9:47am 1/17/2008 by Bruno Silva in .NET, Microsoft, Programming

.NET Framework

The .NET Framework library source code for debugging is now available. Follow the instructions to enable this kind of debugging in Visual Studio in Shawn Burke’s Blog.

Reference: Scott Guthrie ’s Blog.

ASP.NET AJAX - Together at Last

Posted on 10:39pm 1/15/2008 by Bruno Silva in .NET, ASP.NET, Events, Microsoft

ASP.NET AJAX - Together at last

Hoje passei o dia no anfiteatro da Microsoft num evento de ASP.NET AJAX. O orador foi Dino Esposito, um dos grandes nomes do ASP.NET, autor de diversos livros sobre o tema publicados pela Microsoft Press.

Dedicou-se algum tempo para falar sobre o que é na realidade o AJAX. Não é uma tecnologia, mas sim um paradigma de programação que proporciona uma melhor experiência de utilização aos utilizadores de aplicações web reduzindo o tempo de espera e agilizando a interacção. O AJAX assenta sobre tecnologias existentes e bem consolidadas tais como o Document Object Model (DOM), Javascript e o objecto XMLHttpRequest já suportado pelos diversos browsers e que permitem a comunicação assíncrona com o servidor web.

A história do objecto XMLHttpRequest que já tive oportunidade de utilizar em alguns projectos foi, para minha surpresa, desenvolvido inicialmente pela Microsoft. Segundo o orador as tentativas iniciais da Microsoft de realizar pedidos assíncronos a servidores web recorreram a uma applet Java desenvolvida para o efeito. Este antepassado do objecto não chegou à versão 1.0 sequer (problemas legais com a Sun?…).

Da parte da manhã falou-se sobre Partial Rendering. Consiste em recarregar apenas parte do conteúdo de uma página web, para reduzir o trafego entre cliente e servidor, agilizar a interacção e eliminar o flikering da página existente quando é carregada uma página por completo. Em ASP.NET esta funcionalidade é conseguida através da utilização dos controlos ScriptManager e pelo UpdatePanel.

Em todas as páginas ASP.NET que utilizem AJAX deve existir 1 e só 1 ScriptManager cuja principal função é fazer a inclusão das bibliotecas Javascript necessárias para o funcionamento do AJAX. Permite fazer uns “tunnings”, mas não vou entrar em pormenores.

O UpdatePanel é uma zona da página que é actualizada de forma independente do resto da página. Quando existe uma submissão realizada pelos controlos existentes dentro deste painel, apenas esta zona da página é actualizada. Bem, na realidade não é bem assim. Podem existir diversos painéis numa página, e podemos definir o comportamento destes painéis. Podemos definir que quando um painel é actualizado os restantes também o são, ou se apenas o painel que despoletou a actualização é alterado. É também possível programaticamente forçar a actualização de um painel.

O funcionamento simplificado de um UpdatePanel é o seguinte. Quando é realizada uma submissão da página o evento é apanhado pela biblioteca AJAX que impede a submissão que o browser ia realizar. Em vez disso utiliza um objecto XMLHttpRequest para efectuar o pedido, obtém a resposta de forma assíncrona, e utilizando DOM substituí o troço de HTML actual pela versão actualizada enviada pelo servidor.

Os UpdatePanel’s podem ser aninhados. Uma actualização num painel pai implica a actualização dos filhos. O contrário não é verdade. (Faz sentido, não faz? :) ) A actualização de um painel podem ser despoletada por triggers. Podemos associar o clicar de um botão que não se encontra em nenhum painel à actualização de um UpdatePanel.

Um conselho dado pelo Dino Esposito para a definição de UpdatePanel’s foi a análise das zonas da página que necessitam de actualização e as dependências entre elas. Quando menor a quantidade da página abrangida por um UpdatePanel melhor, pois reduz o trafego entre cliente e servidor subjacente a uma actualização do mesmo.

Na parte da tarde deu-se mais ênfase à utilização de serviços (webservices e WCF) no contexto do AJAX. Os exemplos demonstrados passavam pela definição de serviços com a interface JSON que consiste num formato de serialização de dados utilizada em Javascript.

A definição de serviços com esta interface permite que sejam invocados serviços em Javascript como se métodos se tratassem (através de proxies geradas automaticamente, à semelhança dos webservices no contexto tradicional) e cujo resultado sejam objectos com atributos acessíveis em Javascript que se assemelham às classes de objectos manipulados pelos serviços. Vejam este vídeo para ficarem com uma ideia mais clara do que me estou a referir. Faz parte de uma colecção de vídeos sobre ASP.NET AJAX. Nesta abordagem orientada aos serviços a elaboração da interface é dificultada, pois do servidor para o cliente deixa de ir HTML pronto a “colar” no browser, passando a serem retornados dados que devem ser introduzidos na interface através de Javascript.

O Dino Esposito vê tecnologias baseadas em plugins cross-platform como o Silverlight 2.0 e o Flex da Adobe como o futuro das aplicações web, por permitir a flexibilidade no desenvolvimento de interfaces com a facilidade de programação bem como a segurança dada por uma “sand-box” de execução.

Foi uma boa oportunidade de ficar a conhecer melhor a aplicação do AJAX à plataforma .NET.

© Bruno Silva | Powered by Wordpress