ASP.Net 2.0

PasswordRegularExpression

CreateUserWizard.PasswordRegularExpression
Note: This property is new in the .NET Framework version 2.0.

Gets or sets a regular expression used to validate the provided password.

Namespace: System.Web.UI.WebControls
Assembly: System.Web (in system.web.dll)

<strong>Visual Basic (Declaration)</strong>
<span style="background-color: #dbdbdb">Public Overridable Property PasswordRegularExpression As String</span>
<strong>Visual Basic (Usage)</strong>
<span style="background-color: #dbdbdb">Dim instance As CreateUserWizard
Dim value As String
value = instance.PasswordRegularExpression
instance.PasswordRegularExpression = value</span>

Remarks

Use the PasswordRegularExpression property to define the requirements for passwords used to validate users on your Web site. A common use is to make sure that a user has included symbols other than letters in a password to make it harder for attackers to guess a password. The regular expression is used in addition to any restrictions placed on the password by the membership provider specified in the MembershipProvider property. If the membership provider rejects the password for any reason, the text contained in the InvalidPasswordErrorMessage property is displayed.If the password entered does not pass the regular expression, the error message contained in the PasswordRegularExpressionErrorMessage property is displayed to the user.
Example

The following code example uses the PasswordRegularExpression property to define a regular expression that checks passwords to ensure that they:

  • Are longer than seven characters.
  • Contain at least one digit.
  • Contain at least one special (nonalphanumeric) character.

If the password entered by the user does not meet these criteria, the text contained in the PasswordRegularExpressionErrorMessage property is displayed to the user.

passwordregularexpression='@\"(?=.{7,})(?=(.*d){1,})(?=(.*W){1,})'

LINKs


http://www.regular-expressions.info/http://www.4guysfromrolla.com/webtech/120400-1.shtmlÂ

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.

ATLAS Microsoft

ATLAS

atlas logo“Atlas” is a free framework for building a new generation of richer, more interactive, highly personalized standards based Web applications.


This new Web development technology from Microsoft integrates client script libraries with the ASP.NET 2.0 server-based development framework. In addition, ‘Atlas’ offers you the same type of development platform for client-based Web pages that ASP.NET offers for server-based pages. And because ‘Atlas’ is an extension of ASP.NET, it is fully integrated with server-based services. “Atlasâ€? makes it possible to easily take advantage of AJAX techniques on the Web and enables you to create ASP.NET pages with a rich, responsive UI and server communication. However, “Atlas” isn’t just for ASP.NET. You can take advantage of the rich client framework to easily build client-centric Web applications that integrate with any backend data provider.
Atlas” isn’t just for ASP.NET

View the “Atlas” architect’s vision video and other “Atlas” videos that show you how to take advantage of the rich client framework to easily build client-centric Web applications that integrate with any backend data provider.

  • “Atlasâ€? enables your site to take full advantage of modern browser capabilities.
  • “Atlasâ€? empowers ASP.NET developers to effortlessly create richer web experiences.
  • “Atlasâ€? includes a client-side Javascript framework for easy script creation and reuse.
  • “Atlasâ€? makes it super easy to consume services from ASP.NET.
  • “Atlasâ€? makes building composite applications from the programmable web a snap.
—————
Links:

AJAX ATLAS

Ajax (AJAX – Asynchronous Javascript And Xml)

Mas afinal, o que é esse tal de Ajax?

Ajax é a abreviação de Asynchronous JavaScript And XmlHttpRequest e se você nunca ouviu falar dessa tecnologia, é bom correr e começar a dar uma olhada em sites como o Gmail, Google Earth, dentre outros.

É claro que a Microsoft, que está atenta a esses “detalhes” não ficaria simplesmente olhando tudo acontecer, e tchã tchã tchã tchã… Atlas. Mas isso é assunto para um próximo artigo. Para os interessados, podem dar uma olhada no endereço Atlas.

Mas voltando ao Ajax, essa não é uma tecnologia recente pra falar a verdade, mas até então, não havia sido batizada por assim dizer.

Mas ainda não falei sobre o que na verdade o Ajax faz.

Bem, tecnicamente e resumidamente falando, consiste em utilizar Javascript, Xml e XmlHttpRequest para que suas páginas façam chamadas ao servidor sem precisar recarregar a página. (bem resumido não???)

Confuso? Nem um pouco…

Imagine como seria maravilhoso se um usuário do seu site realizasse uma pesquisa e o resultado simplesmente aparecesse em sua tela.

Com o Ajax isso é possível.

——-

links:

http://www.yourhtmlsource.com/javascript/ajax.html
http://www.xul.fr/en-xml-ajax.html
http://developer.mozilla.org/en/docs/AJAX:Getting_Started
http://en.wikipedia.org/wiki/AJAX#Tutorials

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.

<font size="2" face="Verdana">if (bLoginSuccess = true) then
Session("UserId") = txtLoginName.Text
Session("Name") = GetUserNameFromDatabase(txtLoginName.Text)
else
Response.Redirect ("LoginError.aspx")
end if</font>

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”.

<font size="2" face="Verdana">dim userId as string = Session("UserId")
if ( userId = "" ) then
Response.Redirect("Login.aspx")
else
Response.Write ("Welcome " & Session("Name"))
end if</font>


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.

<font size="2" face="Verdana">dim userId as string = Session("UserId")
if ( userId = "" ) then
Response.Write("<a href="http://www.galhano.com/blog/Login.aspx">Login</a>")
else
Response.Write ("Welcome <a href="http://www.galhano.com/blog/MyAccount.aspx">" & Session("Name") & "</a>)
end if</font>

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.