Category Archives: ASP.Net

ASP.Net IIS

“Page cannot be found” when browsing aspx pages in Windows Server 2003 with IIS 6.0

logo asp.netYou may get a Page cannot be found message when you browse aspx pages in a Windows Server 2003 environment.

That is because in Windows 2003, all the webservice extensions are “Prohibited” by default to ensure security.

To resolve this, do the following steps:

1. From your Run command, type inetmgr and press enter.
2. Expand the appropriate nodes in the IIS to locate the “Webservice Extensions” Node
3. Click on the same.
4. You will find a list of “prohibited” extensions in the right.
5. Click on ASP.NET and “allow” it

That should resolve this issue.

This article applies for Windows Server 2003, IIS 6.0 environment.

ASP.Net

Server.Transfer Vs. Response.Redirect

If you read a lot of industry magazines and ASP.NET code samples, you may find that, although the majority use Response.Redirect to send the user to another page, some seem to prefer the rather mysterious-sounding Server.Transfer. So, what’s the difference?

Well, Response.Redirect simply sends a message down to the browser, telling it to move to another page. So, you may run code like:

Response.Redirect("WebForm2.aspx")

or

Response.Redirect("http://www.karlmoore.com/")

to send the user to another page.

Server.Transfer is similar in that it sends the user to another page with a statement such as Server.Transfer(“WebForm2.aspx”). However, the statement has a number of distinct advantages and disadvantages.

Firstly, transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the “focus” on the Web server and transfers the request. This means you don’t get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.

But watch out: because the “transfer” process can work on only those sites running on the server, you can’t use Server.Transfer to send the user to an external site. Only Response.Redirect can do that.

Secondly, Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging.

That’s not all: The Server.Transfer method also has a second parameter—”preserveForm”. If you set this to True, using a statement such as Server.Transfer(“WebForm2.aspx”, True), the existing query string and any form variables will still be available to the page you are transferring to.

For example, if your WebForm1.aspx has a TextBox control called TextBox1 and you transferred to WebForm2.aspx with the preserveForm parameter set to True, you’d be able to retrieve the value of the original page TextBox control by referencing Request.Form(“TextBox1”).

This technique is great for wizard-style input forms split over multiple pages. But there’s another thing you’ll want to watch out for when using the preserveForm parameter. ASP.NET has a bug whereby, in certain situations, an error will occur when attempting to transfer the form and query string values. You’ll find this documented at http://support.microsoft.com/default.aspx?id=kb;en-us;Q316920.

The unofficial solution is to set the enableViewStateMac property to True on the page you’ll be transferring to, then set it back to False. This records that you want a definitive False value for this property and resolves the bug.

So, in brief: Response.Redirect simply tells the browser to visit another page. Server.Transfer helps reduce server requests, keeps the URL the same and, with a little bug-bashing, allows you to transfer the query string and form variables.

Top Tip: Don’t confuse Server.Transfer with Server.Execute, which executes the page and returns the results. It was useful in the past, but, with ASP.NET, it’s been replaced with fresher methods of development. Ignore it.

ASP.Net ASP.Net 2.0

Provider Model Design Pattern

Na versão 2.0 do ASP.NET, com a grande gama de controles a nosso dispor para melhor trabalharmos o front-end (UI), temos ainda classes para manipular os usuários em nossa Base de Dados. Classes que utilizam o Provider Model Design Pattern, e assim conseguímos ter um código genérico, independentemente de que Banco de Dados (ou qualquer outro tipo de repositório) estamos a utilizar na nossa aplicação.

Assim como o Profile, o ASP.NET também utiliza o Providers para gerenciar a segurança, sendo eles, dois providers: MembershipProvider e o RoleProvider. O MembershipProvider é utilizado para gerir os usuários (armazenando, criando, excluindo e alterando) e passwords. O RoleProvider é utilizado para gerenciar as Roles (Regras) dos usuários dentro da aplicação.

Para versão Beta 1, o Provider padrão é o AccessMembershipProvider. Como o Microsoft Access não suporta um grande volume de usuários “pendurados”, ele foi substituído pelo SqlMembershipProvider na versão Beta 2 do Visual Studio .NET 2005, e como o próprio nome diz, é voltado para o Banco de Dados SQL Server. Se ainda há alguém que pretende utilizar o AccessMembershipProvider, é possível encontrá-lo neste endereço.

Para utilizar o SqlMembershipProvider, é necessário termos dentro do SQL Server os objetos (Tabelas e Stored Procedures) necessários para que seja possível o uso deste Provider. Junto ao Microsoft .NET que é instalado na máquina, existe uma ferramenta chamada “aspnet_regsql.exe”, que faz todo este processo automaticamente, onde apenas precisamos informar o servidor e o Banco de Dados onde serão instalados estes objetos.

Depois do provider escolhido, ainda é necessário definirmos no arquivo Web.Config qual será o provider a ser utilizado.

Nota: É importante mencionar que dentro do .NET Framework, também já temos implementada a classe ActiveDirectoryMembershipProvider, que faz o mesmo trabalho, mas agora, utilizando o Active Directory como repositório.

Os Controles

O ASP.NET 2.0 contém um conjunto completo de controles para trabalharmos com a segurança, contendo inclusive uma Tab chamada Security dentro da ToolBox do Visual Studio .NET 2005 para armazenar estes controles. Vamos neste artigo, analisar superficialmente alguns destes novos controles, como por exemplo o ChangePassword, CreateUser, LogIn, LoginView e o PasswordRecovery. Estes controles também tem a grande vantagem de trabalharem diretamente com o Provider que definimos no arquivo Web.Config, e assim, fazem todo o processo, inclusive as queries necessárias para manipular os dados na Base de Dados.

  • ChangePassword
  • CreateUser
  • LogIn
  • LoginView
  • PasswordRecovery


A classe Membership

Como já vimos anterioramente, está é uma classe abstrata, contendo uma série de métodos compartilhados. Esta classe recebe em runtime a instância da classe concreta, ou seja, do provider que definimos o arquivo Web.Config. Claro que estes métodos serão invocados da classe concreta, pois é onde se encontram os métodos implementados para uma Base de Dados específica.

Membro Descrição
Public MethodShared CreateUser Cria um novo usuário.
Public MethodShared DeleteUser Exclui um usuário.
Public MethodShared FindUsersByEmail Resgata os usuários baseando-se em um endereço de email.
Public MethodShared FindUsersByName Resgata os usuários baseando-se em um userName.
Public MethodShared GeneratePassword Gera um password aleatório.
Public MethodShared GetAllUsers Retorna todos os usuários.
Public MethodShared GetNumberOfUsersOnline Retorna um número inteiro representando todos os usuários online.
Public MethodShared GetUser Resgata um determinado usuário baseando-se em um userName.
Public MethodShared GetUsernameByEmail Resgata um determinado usuário baseando-se em um endereço de email.
Public MethodShared UpdateUser Atualiza as informações de um determinado usuário.
Public MethodShared ValidateUser Retorna um valor booleano indicando se o usuário existe ou não.

artigo completo

ASP.Net ASP.Net 2.0

aspnet_regsql

ASP.NET SQL Server Registration Tool (Aspnet_regsql.exe) The ASP.NET SQL Server Registration tool is used to create a Microsoft SQL Server database for use by the SQL Server providers in ASP.NET, or to add or remove options from an existing database.

The Aspnet_regsql.exe file is located in the [drive:]\WINDOWS\Microsoft.NET\Framework\versionNumber folder on your Web server.

You can run Aspnet_regsql.exe without any command-line arguments to run a wizard that will walk you through specifying connection information for your SQL Server installation, and installing or removing the database elements for the Membership, Role Manager, Profile, Web Parts Personalization, and Health Monitoring features. (Setting session state and SQL cache dependency are not covered by the wizard.) You can also run Aspnet_regsql.exe as a command-line tool to specify database elements for individual features to add or remove, using the options listed in the table below.

 SYNTAX   Aspnet_regsql.exe   

[DRIVE:]\WINDOWS\Microsoft\.NETFrameworkv2.0.50215\Aspnet_regsql.exe

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Aspnet_regsql.exe

Artigo completo

ASP.Net

ASP to ASP.NET: Code Behind

Os arquivos criados em ASP.NET possuem a extensão .aspx . Você pode usar qualquer editor de texto para digitar o código de uma página ASP.NET.

No ASP tinhamos o código que era executado dentro das tags <% ... %> que atualmente não é mais compilado e seu uso não aconselhado, pois evita a mescla de código de servidor juntamente com o código HTML.

codebehind

Uma das grandes inovações é o CodeBehind . Com ele é possível separarmos o código da programação do código HTML. O CodeBehind (neste artigo escrito em VB.Net) ao compilar o aplicativo esse código é “encapsulado” dentro da DLL, sendo necessário apenas o envio do arquivo ASPX para o servidor de produção. Ao criar um novo WebForm no Visual Studio .NET, são criados dois arquivos: o arquivo Arquivo.aspx (arquivo que contém o código HTML) e o Arquivo.aspx.vb (arquivo de código propriamente dito).
Nota: A extensão do arquivo de CodeBehind vai depender da linguagem escolhida pelo desenvolvedor. Para VB.Net temos .aspx.vb, C# temos .aspx.cs.

ASP.Net

ASP.NET 2.0 (Whidbey) new features

Uma mudança fundamental no processo de desenvolvimento é a possibilidade de se criar aplicações web SEM A NECESSIDADE DE SE TER O IIS INSTALADO. Isto se deve ao fato de o Whidbey possuir seu próprio servidor web embutido de forma que não é necessário o acesso administrativo para o debug das aplicações. Este servidor visa, entre outros objectivos, aumentar a segurança no desenvolvimento uma vez que estas aplicações não poderão ser acedidas remotamente, só estando disponíveis ao navegador local. Ao se fechar o Whidbey, o servidor embutido é removido da memória.

Este recurso não proíbe àqueles que desejam continuar a criar suas aplicações directo no IIS de fazê-lo: apenas abre uma nova possibilidade. Na figura abaixo vemos os repositórios das aplicações web, entre os quais percebemos projectos criados directamente no File System e executados pelo servidor http embutido além do Local IIS, FTP Sites e Remote Sites.

mais info aqui

ASP.Net

Purpose of Session variables

logo asp.net

In most of the web sites, when a user log In in the login page, they set few variables to session.

if (bLoginSuccess = true) then
Session("UserId") = txtLoginName.Text
Session("Name") = GetUserNameFromDatabase(txtLoginName.Text)
else
Response.Redirect ("LoginError.aspx")
end if

The above code stores the user’s userid into a session variable called “UserId”. All other pages will check if the user id is set in the session and if not, it will give an error message saying “you have not logged in”.

dim userId as string = Session("UserId")
if ( userId = "" ) then
Response.Redirect("Login.aspx")
else
Response.Write ("Welcome " & Session("Name"))
end if


The above validation will be required only in the pages which needs user login. For example, in AspSpider.com, you can access m
ost of the pages without logging in. Only when you submit an article or feedback, we will use the above code and validate your login. If you are not logged in, we will redirect you to login page automatically.

If you look at the top left corner of this site, you can either see ‘Login” or “Welcome “. We have used a logic similar to what is shown below, to display appropriate message.

dim userId as string = Session("UserId")
if ( userId = "" ) then
Response.Write("Login")
else
Response.Write ("Welcome " & Session("Name") & ")
end if

As you can see from the above examples, session variables are used to store small key-value pairs in the memory. You can use session variables to store values from one page and access the values from other pages for the same user. If you set a value in session variable from one page, you can retrieve the value from any other page in the same session.

The most important point to remember is, whatever value you store in session will be valid only until the session expires. Also, this value will not be accessible for another user/session.


ASP.Net

ASP.NET Session Object

logo asp.netASP.NET provides a class called HttpSessionState, which is part of the namespace System.Web.SessionState.

Just like Request and Response objects, an HttpSessionState object is also created automatically for you in ASP.NET pages. This object is called “Session”. You can access various methods and properties of this object.
What is in a session ?

A session has several information including a session ID. Some information is created and used by the server itself. But the most important use of session is, it allows to store custom information.
You can store any key-value pairs in session.

How to store and retrieve values in ASP.NET session ?

Just like you can store values in variables, you can store values in session. Basically, you can assign values to session variables. See the following example:
The following code sample shows how to store a string value in session:
Session(“UserId”) = “john”

In the above sample, the value “john” is assigned to a session variable called “UserId”. One important different here is, you do not declare the session variable as any datatype. Just assign any value to any session variable. The session variables will be automatically created when you simply assign values to them.
How long a session variable is valid ?

A session variable retains it’s value as long as the session is valid. Session variables are valid across all pages, as long as you access all those pages from the same browser and within the timeout period.

If you assign a value into a session variable from Page1.aspx and try to retrieve it from Page2.aspx, it will work. But if you try to access the Page2.aspx from another browser or close your original browser and open again, the session variable would have lost it’s value because a new session is created.

What can be stored in a session? The above examples show storing and retrieving simple strings in session. But you can store complex datatypes like Dataset also into session. Many websites retrieve lot of user data from database and store into session so that it can be accessed faster from memory (session) rather than retrieving from database.

However, it is not reccommded to store lot of data into session for large websites. Session data is stored in memory and if there are thousands of online users at the same time, server may run out of memory.

ASP.Net

ASP.NET Session Object

ASP.NET provides a class called HttpSessionState, which is part of the namespace System.Web.SessionState.

Just like Request and Response objects, an HttpSessionState object is also created automatically for you in ASP.NET pages. This object is called “Session”. You can access various methods and properties of this object.
What is in a session ?

A session has several information including a session ID. Some information is created and used by the server itself. But the most important use of session is, it allows to store custom information.
You can store any key-value pairs in session.

How to store and retrieve values in ASP.NET session ?

Just like you can store values in variables, you can store values in session. Basically, you can assign values to session variables. See the following example:
The following code sample shows how to store a string value in session:
    Session(“UserId”) = “john”

In the above sample, the value “john” is assigned to a session variable called “UserId”. One important different here is, you do not declare the session variable as any datatype. Just assign any value to any session variable. The session variables will be automatically created when you simply assign values to them.
How long a session variable is valid ?

A session variable retains it’s value as long as the session is valid. Session variables are valid across all pages, as long as you access all those pages from the same browser and within the timeout period.

If you assign a value into a session variable from Page1.aspx and try to retrieve it from Page2.aspx, it will work. But if you try to access the Page2.aspx from another browser or close your original browser and open again, the session variable would have lost it’s value because a new session is created.

What can be stored in  a session? The above examples show storing and retrieving simple strings in session. But you can store complex datatypes like Dataset also into session. Many websites retrieve lot of user data from database and store into session so that it can be accessed faster from memory (session) rather than retrieving from database.

However, it is not reccommded to store lot of data into session for large websites. Session data is stored in memory and if there are thousands of online users at the same time, server may run out of memory.

ASP.Net

Handling Errors

Quando ocorre um erro numa pagina. o ASP.NET envia informação sobre o erro para o cliente. Os erros são divididos em 4 categorias:

  • Configuration errors: Occur when the syntax or structure of a Web.config file in the configuration hierarchy is incorrect.
  • Parser errors: Occur when the ASP.NET syntax on a page is malformed.
  • Compilation errors: Occur when statements in a page’s target language are incorrrect.
  • Run-time errors: Occur during a page’s execution, even though the errors could not be detected at compile time.

By default, the information shown for a run-time error is the call stack (the chains of procedure calls leading up to the exception). If debug mode is enabled, ASP.NET displays the line number in source code where the run-time error originated. Debug mode is a valuable tool for debugging your application. You can enable debug mode at the page level, using the following directive:

>

Note: Running debug mode incurs a heavy performance penalty. Be sure to disable it before deploying your finished application.
Depending on the circumstances, you might want to handle application errors in different ways. For example, at development time you probably want to see the detailed error pages that ASP.NET provides to help you identify and fix problems. However, once an application is being served in a production environment, you probably do not want to display detailed errors to your customer clients. You can use ASP.NET to specify whether errors are shown to local clients, to remote clients, or to both. By default, errors are shown only to local clients (those clients on the same computer as the server). You can also specify a custom error page to redirect clients to if an error occurs.

---------
artigo completo aqui