Tuesday, November 22, 2011

Delete All Tables MSSQL

While working on ASP.Net application, I came across a situation where I had to delete all the Tables of the MSSQL 2008 database, and it was really painful process. 

In this case I had to delete all the SPs and all views as well. As I started searching like "Truncate database Sql 2008" or "Delete all tables in MSSQL" I came across two things and it worked for me.

(I am really not sure whether it works in all the cases but for Deleting all tables in SQL, this worked for me.) 
Firstly we need to remove all indexs from SQL table, I found following code when I Google the term 


DECLARE @indexName NVARCHAR(128)
DECLARE @dropIndexSql NVARCHAR(4000)

DECLARE tableIndexes CURSOR FOR
SELECT name FROM sysindexes
WHERE id = OBJECT_ID(N'tableName') AND
  indid > 0 AND indid < 255 AND
  INDEXPROPERTY(id, name, 'IsStatistics') = 0
ORDER BY indid DESC

OPEN tableIndexes
FETCH NEXT FROM tableIndexes INTO @indexName
WHILE @@fetch_status = 0
BEGIN
  SET @dropIndexSql = N'DROP INDEX tableName.' + @indexName
  EXEC sp_executesql @dropIndexSql

  FETCH NEXT FROM tableIndexes INTO @indexName
END

CLOSE tableIndexes
DEALLOCATE tableIndexes

After this we need to delete all the tables in SQL, for this I used following SP
EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

It seems that this is a HIDDEN stored procedure in MSSQL.
Submit this story to DotNetKicks

Read more...

Sunday, November 20, 2011

Access userName asp.net-membership without using Membership.getUser()

While I was working on Membership and User Management in Asp.Net 2010
Following Scenario
  • After creating user, admin sets subscribtion for the user.
  • User logs in with id and password, after validating user, I check for subscription details.
  • If user is logging in with subscription period he/she has access to the application else he/she will be redirected to Subscription Expired page.
To check subscription, I had requirement to get username and check it in Subscription table.
I did not want to use getUser function, as I just wanted to get user name of currently logged in user.

To get user name I used following line of code

System.Web.HttpContext.Current.User.Identity.Name


Submit this story to DotNetKicks

Read more...

Friday, November 18, 2011

Error : Could not find any resources appropriate for the specified culture or the neutral culture

Just recieved this error:
Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "AjaxControlToolkit.Properties.Resources.NET4.resources" was correctly embedded or linked into assembly "AjaxControlToolkit" at compile time, or that all the satellite assemblies required are loadable and fully signed. 

Could not find any resources appropriate for the specified culture or 
the neutral culture.  Make sure 
"AjaxControlToolkit.Properties.Resources.NET4.resources" 
was correctly embedded or linked into assembly "AjaxControlToolkit" 
at compile time, or that all the satellite assemblies required are
loadable and fully signed.

Ajax Tool kit realted .Net errors look a lot more worse than they really are.
What we have to do is simply add scriptManager ;)
 
<ajax:ToolkitScriptManager 
ID="ToolkitScriptManager1" 
runat="server" />
Submit this story to DotNetKicks

Read more...

Tuesday, November 8, 2011

Use Membership for user management - Basics

In this article we shall discuss the membership feature in ASP.NET applications. Asp.net has reduced the development drastically by introducing this. Membership feature of Asp.Net drastically reduces the amount of code we have to write to authenticate users at our Web site. In this article we are going to develop User Management system membership class, and SqlMembershipProvider.

Membership feature of Asp.net provides a membership API that simplifies the task of validating user credentials. SqlMembershipProvider uses SQL Database for storing membership details.

Step1: Install Membership Database for SQLMembershipProvider.
To install Membership Database we have to log on to our server with an account that has authority to administer SQL server. After this open Visual Studio 2010 Command prompt.


Run following command
aspnet_regsql.exe -E -S localhost -A m

Where:
    -E indicates authenticate using the Windows credentials of the currently logged on user.
    -S (server) indicates the name of the server where the database will be installed or is already installed.
    -A m indicates add membership support. This creates the tables and stored procedures required by the membership provider.

Above command mainly generates database naming "aspnetdb" with following  schema structure and related stored procedures


* Please Note that Related stored procedures also get created with above command. These stored procedures get called internally from Membership provider. 

Step2: Configure Forms Authentication
Set following authentication mode in Web.config file
<authentication mode="Forms">
    <forms loginUrl="Login.aspx" 
           protection="All" 
           timeout="30" 
           name="AppNameCookie" 
           path="/FormsAuth" 
           requireSSL="false" 
           slidingExpiration="true" 
           defaultUrl="default.aspx"
           cookieless="UseCookies"
           enableCrossAppRedirects="false"/>
</authentication>

If so many options are not required we can simply use following Tag for authentication

<authentication mode="Forms">
      <forms loginUrl="Login.aspx" timeout="2880" />
    </authentication>

Add the following <authorization> element after the element. This will allow only authenticated users to access the application. The previously established loginUrl attribute of the <authentication> element will redirect unauthenticated requests to the Login.aspx page.


<authorization> 
   <deny users="?" />
   <allow users="*" />
</authorization>
  
Step 3: Configuring SQLMembership Provider
In Step 1, we created SQL Database for Membership Provider, in this step we will configure SQLMembership Provider in Web.config file.


<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=MySqlServer;Initial Catalog=aspnetdb;Integrated Security=SSPI;" />
</connectionStrings>
<system.web>
...
  <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
    <providers>
      <clear />
      <add 
        name="SqlProvider" 
        type="System.Web.Security.SqlMembershipProvider" 
        connectionStringName="MyConnectionString"
        applicationName="/"
        enablePasswordRetrieval="false"
        enablePasswordReset="true"
        requiresQuestionAndAnswer="true"
        requiresUniqueEmail="true"
        passwordFormat="Hashed" />
    </providers>
  </membership>

Default passwordFormat is "Hashed", if we remove it from Configuration then by default Passwords are stored in Hashed format. We can change passwordFormat to Encrypted. (This is not the scope of this Article; I shall put another article for it.)

Step 4: Start using Membership class
Upto step 3 we were only doing configuration for using Membership class. After we done with step 3; whenever we use Membership class, if by default uses Database structure generated in Step 1. It internally manages all the Database calls.
e.g.
Membership.CreateUser("UserName","Password");
//This will create user in Database.
Check out following Membership APIs for user management in Asp.net.
MethodParametersNotes
CreateUserstring username–User name to create.

string password–Password for new user


string email–E-mail for new user.

string passwordQuestion

string passwordAnswer

bool IsApproved

object providerUserKey
Used to create a new user.
DeleteUserstring username–User to delete.

bool removeAllRelatedData
Used to immediately remove a user identified by the supplied username. Returns true if the user was deleted or false if not found.
FindUsersByNamestring usernameToMatch

int pageIndex

int pageSize
Returns a collection of users where the string parameter passed matches part of the username.

Wildcard support depends on how each data store handles characters such as "*", "%" and "_".
FindUsersByEmailstring emailToMatch

int pageIndex

int pageSize
Returns a collection of users whose e-mail addreses matches any part of the string parameter passed.

Wildcard support depends on how each data store handles characters such as "*", "%" and "_"
GeneratePasswordint length

Int numberOfNonAlpha

NumericCharacters
Returns a password of the specified length that contains the specified number of non-alphanumeric characters.
GetAllUsersint pageIndex

int pageSize
Returns a subset of users from the collection of all users. The subset is based on the pageIndex and pageSize methods.
GetNumberOfUsersOnlineNoneReturns a count of all the users who are currently online

The Active Directory provider does not implement this functionality
GetUsernameByEmailstring email–Email of user to lookup.Return a member's username.
UpdateUserMembershipUser user–Membership user to updateUpdates a member's properties; for example, an e-mail address.
ValidateUserstring username–User name to validate.

string password–User password to validate.
Validates a user's credentials. Returns true if the credentials are valid and false if they are not.


With Active Directory, regardless of the configured connection credentials, the provider connects to the directory with the username and password parameter as the connection credentials.
(Note: Above table is picked up from MSDN)

This is how we can use Membership class for User management in Asp.net using SQLMembershipProvider.

Submit this story to DotNetKicks

Read more...