Category: ASP.NET

Preventing client-side caching

Posted on 3:46pm 4/25/2008 by Bruno Silva in .NET, ASP.NET, Programming, Web

During this week I’ve been experiencing some problems with browser caching.

I’ve a dynamically generated XML file which contents change a lot (it is a photo gallery based on Slide.Show), and I want the people who see this gallery to see newly added photos immediately. Today someone asked me how to prevent the client-side caching (regarding Slide.Show too), so I did some searches and testing in order to enlight us both. :)

I’ve found reference to a few lines of code which should be used in ASP.NET web pages to prevent caching.

Response.CacheControl = “no-cache”;
Response.AddHeader(”Pragma”, “no-cache”);
Response.Expires = 0;

I tried the first one alone both in IE 7 and Firefox 2 and it seamed to be enough, nevertheless, being care is never enough,so I’ll probably use the 3 lines together!

Just try to be careful and don’t feel tempted to prevent caching in every single web page in your web site, it leads to poor perfomance in both your servers and in the client side. And every one likes to see the content of a previously visited page rendered quickly, right? :)

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.

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.

Microsoft Press Free E-Book

Posted on 4:42pm 12/19/2007 by Bruno Silva in .NET, ASP.NET, Microsoft, Programming, Silverlight

Microsoft Learning

MS Press has just released an e-book on Visual Studio 2008 technologies and are giving it away for free. The e-book includes excerpts from three recent book releases and provides a wealth of information and insights from top experts:

You can see the first chapter of these books for free. When you register, you’ll be able to download a lot more content of those books, packaged as an e-book.

© Bruno Silva | Powered by Wordpress