jQuery tip: Add an element as hidden and show on click.

If you want to add an element initially as hidden, just use CSS display: none.

In the onclick event, use jQuery to show the element.

 

TIP: Don’t use CSS visibility: hidden, because this will not work.

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Research</title>
<style type="text/css">
#page 
{
position: relative;
}
span.action 
{
cursor: pointer;
text-decoration: underline;
}
#elementToShow 
{
position: absolute;
width: 100px;
left: 30px;
top: 60px;
display: none;
/* visibility: hidden; */ /* <== This will not work*/
}
</style>
<script type="text/javascript" src="Scripts/jquery-2.0.0.min.js"></script>
<script type="text/javascript">
App = {};
$(document).ready(function ()
{
});
</script>
</head>
<body>
<div id="page">
<div id="elementToShow">Hello world!</div>
<span onclick="$('#elementToShow').show();" class="action">show</span>
<span onclick="$('#elementToShow').hide();" class="action">hide</span>
</div>
</body>
</html>

Initial

image

After clicking on "show"

image

Manually create the SQL Server tables used by de SimpleMembershipProvider

 

Below you will find the t-sql code needed to generate de SQL Server SimpleMembershipProvider tables.

 

 

set ansi_nulls on
go
set quoted_identifier on
go
if object_id('dbo.webpages_Membership') is null
begin
create table dbo.webpages_Membership
(
UserId                                    int not null constraint PK_Membership_UserId primary key,
CreateDate                                datetime null,
ConfirmationToken                        nvarchar(128) null,
IsConfirmed                                bit null constraint DF_Membership_IsConfirmed default (0),
LastPasswordFailureDate                    datetime null,
PasswordFailuresSinceLastSuccess        int not null constraint DF_Membership_PasswordFailuresSinceLastSuccess default (0),
[Password]                                nvarchar(128) not null,
PasswordChangedDate                        datetime null,
PasswordSalt                            nvarchar(128) not null,
PasswordVerificationToken                nvarchar(128) null,
PasswordVerificationTokenExpirationDate    datetime null
)
end
go
set ansi_nulls on
go
set quoted_identifier on
go
if object_id('dbo.webpages_Roles') is null
begin
create table dbo.webpages_Roles
(
RoleId int identity(1,1) not null,
RoleName nvarchar(256) not null,
constraint PK_Roles_RoleId primary key clustered 
(
RoleId ASC
) with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [PRIMARY],
constraint UQ_Roles_RoleName unique nonclustered 
(
RoleName asc
) with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [PRIMARY]
)
end
go
set ansi_nulls on
go
set quoted_identifier on
go
if object_id('dbo.webpages_OAuthMembership') is null
begin
create table dbo.webpages_OAuthMembership
(
Provider        nvarchar(30) not null,
ProviderUserId    nvarchar(100) not null,
UserId            int not null,
constraint PK_OAuthMembership_Provider_ProviderUserId primary key clustered 
(
Provider asc,
ProviderUserId asc
) with    (    pad_index = off, 
statistics_norecompute = off,
ignore_dup_key = off,
allow_row_locks = on,
allow_page_locks = on) on [PRIMARY]
)
end
go
set ansi_nulls on
go
set quoted_identifier on
go
if object_id('dbo.webpages_UserProfile') is null
begin
create table dbo.webpages_UserProfile
(
UserId int identity(1,1) not null,
UserName nvarchar(56) not null,
constraint PK_UserProfile_UserId primary key clustered 
(
UserId asc
) with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [PRIMARY],
constraint UQ_UserProfile_UserName unique nonclustered 
(
UserName asc
) with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [PRIMARY]
)
end
go
set ansi_nulls on
go
set quoted_identifier on
go
if object_id('dbo.webpages_UsersInRoles') is null
begin
create table dbo.webpages_UsersInRoles
(
UserId int not null constraint FK_UsersInRoles_UserId foreign key(UserId) references dbo.webpages_UserProfile (UserId),
RoleId int not null constraint FK_UsersInRoles_RoleId foreign key(RoleId) references dbo.webpages_Roles (RoleId),
primary key clustered 
(
UserId asc,
RoleId asc
) with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on PRIMARY]
)
end
go

ASP .NET MVC4 / Web Api – Create users and roles for SimpleMembershipProvider with PowerShell and C#

If you are using the SimpleMembershipProvider for FormAuthentication in a ASP .NET MVC4 / Web Api project, the following PowerShell / C# code can be used to create and delete users and roles.

  • Create an empty XML App.config file "C:\Temp\App.config".
  • Paste the XML below in the file and save it.
  • Create an empty PowerShell file "C:\Temp\Manage_MVC_users_and_roles.ps1".
  • Paste the PowerShell code below in the file and save it.
  • Create an empty C# file "C:\Temp\Manage_MVC_users_and_roles.cs".
  • Paste the C# code below in the file and save it.
  • Execute the file "C:\Temp\Manage_MVC_users_and_roles.ps1" with PowerShell.

 

This will create an user "test2" with password "test2" and a role "Administrators".

 

Note

  • Database tables will automatically be created if they don’t exist.
  • De folder "C:\Temp" should contain the assemblies "System.Web.WebPages.dll" and "WebMatrix.Data.dll" and "WebMatrix.WebData.dll", this assembly can be downloaded using NuGet.

App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<profile defaultProvider="SimpleProfileProvider">
<providers>
<add name="SimpleProfileProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"
connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
</assemblyBinding>
</runtime>
</configuration>

PowerShell code (Manage_MVC_users_and_roles.ps1)

 
# Get folder containing this script.
$scriptFolder = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
# Load App.config file from scriptfolder.
$appConfigPath = "$scriptFolder\App.config"
[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $appConfigPath)
# Compile C# code to dll.
$Assem = ( 
"WebMatrix.Data", 
"WebMatrix.WebData",
"System.Security",
"System.Web",
"System.Web.WebPages",
'System.Web.ApplicationServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35',
'System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
)
$codePath = "$scriptFolder\Manage_MVC_users_and_roles.cs"
$codeAssemblyName = "Manage_MVC_users_and_roles.dll"
Add-Type -OutputType Library –ReferencedAssemblies $Assem -OutputAssembly $codeAssemblyName -Path $codePath
# Load dll.
$codeAssemblyPath = "$scriptFolder\$codeAssemblyName"
Add-Type -Path $codeAssemblyPath
# Execute C# code.
$wrapper = New-Object Research.Rli.WebSecurityExecuter
$wrapper.Execute($scriptFolder);
pause

C# code

namespace Research.Rli
{
using System.Linq;
public interface IWebSecurityExecuter
{
void Execute(string scriptFolder);
}
public class WebSecurityExecuter : IWebSecurityExecuter
{
/// <summary>
/// Executes code found in the [WebSecurityWrapper] class in a new .net AppDomain, 
/// To prevent assembly load errors, a new AppDomain is created, with the ApplicationBase set to the folder containing this *.cs file.
/// </summary>
/// <param name="scriptFolder">
/// Folder containing this *.cs file.
/// </param>
public void Execute(string scriptFolder)
{
System.AppDomain childDomain = null;
try
{
var domainSetup = new System.AppDomainSetup()
{
ApplicationBase = scriptFolder,
ConfigurationFile = System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
ApplicationName = System.AppDomain.CurrentDomain.SetupInformation.ApplicationName,
LoaderOptimization = System.LoaderOptimization.MultiDomainHost
};
childDomain = System.AppDomain.CreateDomain("NewAppDomain", null, domainSetup);
IWebSecurityWrapper wrapper = (IWebSecurityWrapper)childDomain.CreateInstanceAndUnwrap(typeof(WebSecurityWrapper).Assembly.FullName, typeof(WebSecurityWrapper).FullName);
wrapper.Initialize();
wrapper.CreateUsers();
wrapper.CreateRoles();
}
finally
{
if (childDomain != null) System.AppDomain.Unload(childDomain);
}
}
}
public class WebSecurityWrapper : System.MarshalByRefObject, IWebSecurityWrapper
{
/// <summary>
/// Initializes the database connection and creates tabels, when these tables do not exist.
/// </summary>
public void Initialize()
{
DatabaseConnectionString = @"Data Source=(LocalDb)\v11.0;Initial Catalog=MyDatabase;Integrated Security=SSPI;";
Roles = new System.Collections.Generic.List<string>
{
"Administrators"
};
Users = new System.Collections.Generic.List<User> 
{ 
new User { Name = "test2", Password = "test2"}
};
UserIdColumnName = "UserId";
UserNameColumnName = "UserName";
UserTableName = "UserProfile";
// Creates user and role tables if they don't exist.
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(DatabaseConnectionString, "System.Data.SqlClient", UserTableName, UserIdColumnName, UserNameColumnName, true);
}
public string DatabaseConnectionString { get; set; }
public System.Collections.Generic.List<string> Roles { get; set; }
public System.Collections.Generic.List<User> Users { get; set; }
public string UserIdColumnName { get; set; }
public string UserNameColumnName { get; set; }
public string UserTableName { get; set; }
public void CreateRoles()
{
Roles.ForEach(x =>
{
var roles = (WebMatrix.WebData.SimpleRoleProvider)System.Web.Security.Roles.Provider;
if (roles.RoleExists(x))
{
System.Console.WriteLine("Role [{0}] already exists.", x);
}
else
{
roles.CreateRole(x);
}
});
}
public void CreateUsers()
{
Users.ForEach(x =>
{
if (WebMatrix.WebData.WebSecurity.UserExists(x.Name))
{
System.Console.WriteLine("User [{0}] already exists.", x.Name);
}
else
{
WebMatrix.WebData.WebSecurity.CreateUserAndAccount(x.Name, x.Password);
}
});
}
public void DeleteRoles()
{
Roles.ForEach(x =>
{
var roles = (WebMatrix.WebData.SimpleRoleProvider)System.Web.Security.Roles.Provider;
if (roles.RoleExists(x))
{
System.Collections.Generic.List<string> usersInRole = roles.GetUsersInRole(x).ToList();
Users = new System.Collections.Generic.List<User>();
usersInRole.ForEach(u =>
{
Users.Add(new User { Name = u });
});
DeleteUsers();
roles.DeleteRole(x, true);
}
else
{
System.Console.WriteLine("Role [{0}] already exists.", x);
}
});
}
public void DeleteUsers()
{
var membership = (WebMatrix.WebData.SimpleMembershipProvider)System.Web.Security.Membership.Provider;
Users.ForEach(x =>
{
if (WebMatrix.WebData.WebSecurity.UserExists(x.Name))
{
membership.DeleteAccount(x.Name);
membership.DeleteUser(x.Name, true);
}
else
{
System.Console.WriteLine("User [{0}] does not exist.", x.Name);
}
});
}
public void ResetPasswordUsers()
{
Users.ForEach(x =>
{
if (WebMatrix.WebData.WebSecurity.UserExists(x.Name))
{
WebMatrix.WebData.WebSecurity.ResetPassword(null, x.Name);
}
else
{
System.Console.WriteLine("User [{0}] does not exist.", x.Name);
}
});
}
}
public interface IWebSecurityWrapper
{
void CreateRoles();
void CreateUsers();
string DatabaseConnectionString { get; set; }
void DeleteRoles();
void DeleteUsers();
void Initialize();
void ResetPasswordUsers();
System.Collections.Generic.List<string> Roles { get; set; }
string UserIdColumnName { get; set; }
string UserNameColumnName { get; set; }
System.Collections.Generic.List<Research.Rli.User> Users { get; set; }
string UserTableName { get; set; }
}
public class User
{
public string Name { get; set; }
public string Password { get; set; }
}
}

What is the state of HTML 5 cross platform apps, just look at Steve Anderson – Touralot

Just go to the Apple store on your iPhone and download the Touralot app.

This app is written in HTML 5 CSS3 and uses in PhoneGap to create a Apple store compatible app package.

 

http://blog.stevensanderson.com/category/touralot/

The Look and Feel and the performance are just amazing.

 

If you are a web oriented company and the business demands an app, your web development team can rapidly, create iOS, Android, Windows Phone and Windows 8 apps to get quick user feedback and when they ran into platform features that are not supported by PhoneGap (at this time) or performance issues, there is still the possibility to write a part of the app in native code or convert the whole app to native by platform specific developers.

 

Kudos for Steve Anderson for creating this awesome app. 

How to convert a JSON string, containing UTC datetime to a local server datetime string in C#

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
namespace Research.Rli.Tests
{
[TestClass]
public class ResearchTester
{

[TestMethod]
public void Test()
{
string json = @"{""date"":""2013-04-10T14:52:43.207Z""}";
Dto dto = JsonConvert.DeserializeObject<Dto>(json);
string localTime = dto.date.ToLocalTime().ToString();
Assert.AreEqual("10-4-2013 16:52:43", localTime); // In the Netherlands this test will succeed.
}
}
public class Dto
{
public DateTime date { get; set; }
}
}

 

 

 

Installing SSIS support in Microsoft Visual Studio 2012

As of 5-mrt-2013, Microsoft Visual Studio 2012 supports SSIS projects by installing

Microsoft SQL Server Data Tools – Business Intelligence for Visual Studio 2012

 

You can download Microsoft SQL Server Data Tools – Business Intelligence for Visual Studio 2012 at:

http://www.microsoft.com/en-us/download/details.aspx?id=36843

 

On installation I got the following error:

SQL Server Setup could not search for updates through the Windows Update Service.

 

image

 

Well I just ignored that en clicked Next.

 

Than I got the error:

 

image

 

Rule "Same architecture installation" failed.

 

The CPU architecture of installing feature(s) is different than the instance specified. To continue, add features to this instance with the same architecture.

 

image

 

This was caused by selecting "Add features to an existing instance of SQL Server 2012" instead of "Perform a new installation of SQL Server 2012", this is the right option.

 

image

 

As mentioned on the installation page:

http://msdn.microsoft.com/en-us/library/jj856966.aspx

On the Installation Type page, verify Perform a new installation of SQL Server 2012 is selected, and then click Next.

Setup will not install a new instance of SQL Server 2012 Server, but will install new SQL Server Features, including SQL Server Data Tools- Business Intelligence for Visual Studio 2012,

which you will select on the next Feature Selection page.

Drop all stored procedures not belonging to the dbo schema from a SQL Server database

if you want to drop all stored procedures not belonging to the dbo schema from a SQL Server database, you van use the following select statement to generate a list that can be executed to drop the sprocs.

PS: It’s your foot.

 

    select        'drop procedure ' + s.name + '.' + o.name
from          sys.objects o with (nolock)
inner join    sys.schemas s with (nolock) on o.schema_id = s.schema_id
where         o.type = 'P'
and           s.name <> 'dbo'

How to left pad a string in T-SQL (SQL Server 2012)

If you want to left pad a string in T-SQL in Microsoft SQL Server 2012, you can use the format function:

To get the current hour padded with, zeros use:

declare @CurrentDateTime datetime = '2013-04-03 05:06:17'
select format(datepart(hh, @CurrentDateTime), '00')
-- Result: 05

For more information, including (SQL 2005, and 2008 options):

http://www.tech-recipes.com/rx/30469/sql-server-how-to-left-pad-a-number-with-zeros/

Fix: Arithmetic overflow error converting IDENTITY to data type int

I was getting the error: "Arithmetic overflow error converting IDENTITY to data type int", when inserting a record in a table with a identity column. The max id of this table was 45448, this is certainly not the max of int in SQL Server, so I expected the next Id to be 45449, but DBCC CHECKIDENT returned 2147483647 (the max of an int). 

DBCC CHECKIDENT ('Reporting.MyTable');

Reseeding the table with DBCC CHECKIDENT fixed the problem:

DBCC CHECKIDENT ('Reporting.MyTable', reseed, 45449)