How to connect SQL Server by ConnectionString stored in Web.config? - sql-server

I am trying to use a windows server with IIS and SQL Server to host a website. However, with simple SQL Server ODBC-connection I unfortunately found that there is no chance to work in IIS. After looking for a solution I found that I somehow need to connect SQL Server to IIS. Everybody is taking about a connection string which should be put into "the web.config" file.
String:
<connectionStrings>
<add name="MyProjectContext" connectionString="Server=.\SQLEXPRESS;Database=MyProject;User Id=John;Password=duck;" providerName="System.Data.SqlClient" />
</connectionStrings>
But where exactly do I need to put this, where is this web.config file, how can I get there?

thanks for your help. After researching and trying a lot of things I found a great solution on how to connect my database SQL Server in IIS with PHP.
You need to create a Web.config file in your website path.
Inside this Web.config file paste the connection string e.g.
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="sqlDB" connectionString="Server=xxx.xxx.xxx.xxx; Database=db_name; User Id=sqlserver_user_name; password=sqlserver_password;Max Pool Size=2000;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Then create file e.g. sql.php in same path for instance (the example below doesn't need to be changed)
<?php
// start get connection string from web.config
$xml = simplexml_load_file("Web.config") or die("Error: Cannot create object");
//in my case web.config is in previous directory
$array = json_decode(json_encode((array) $xml), 1);
$server = "";
$database = "";
$user = "";
$password = "";
$fullString = ($xml->connectionStrings->add[0]["connectionString"]);
$strArr = explode(";", $fullString);
$arrCount = count($strArr);
$connArr[]="";
for($x=0;$x<$arrCount-1;$x++){
$aS = explode("=",$strArr[$x]);
$connArr+=array(strtolower(trim($aS[0])) => trim($aS[1]));
}
$server = $connArr["server"];
$database = $connArr["database"];
$user = $connArr["user id"];
$password = $connArr["password"];
// end get connection string from web.config
$connectionInfo = array( "UID"=>$user,
"PWD"=>$password,
"Database"=>$database,
"CharacterSet" => "UTF-8");
/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $server, $connectionInfo);
?>
$conn to perform sql_query()

Related

Deploy SSIS-Package with PowerShell

I'm trying to deploy an .ispac-file via PowerShell to SQL Server (2017). So far I have already downloaded the SQL Server PowerShell Module and of course SSIS is installed as well (Version 15.0.2000.93).
The PowerShell script I'm trying to run is pretty much the same as the one from the documentation:
# Variables
$SSISNamespace = "Microsoft.SqlServer.Management.IntegrationServices"
$TargetServerName = "name"
$TargetFolderName = "name"
$ProjectFilePath = "path"
$ProjectName = "name"
# Load the IntegrationServices assembly
$loadStatus = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SQLServer.Management.IntegrationServices, "+
"Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL")
# Create a connection to the server
$sqlConnectionString = `
"Data Source=" + $TargetServerName + ";Initial Catalog=master;Integrated Security=SSPI;"
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection $sqlConnectionString
# Create the Integration Services object
$integrationServices = New-Object $SSISNamespace".IntegrationServices" $sqlConnection
# Get the Integration Services catalog
$catalog = $integrationServices.Catalogs["SSISDB"]
# Create the target folder
$folder = New-Object $SSISNamespace".CatalogFolder" ($catalog, $TargetFolderName,
"Folder description")
$folder.Create()
Write-Host "Deploying " $ProjectName " project ..."
# Read the project file and deploy it
[byte[]] $projectFile = [System.IO.File]::ReadAllBytes($ProjectFilePath)
$folder.DeployProject($ProjectName, $projectFile)
The error occurs on line 18:
$integrationServices = New-Object $SSISNamespace".IntegrationServices" $sqlConnection
and says that the assembly or a dependency of it can't be found (see below):
"Microsoft.SqlServer.Dmf.Common,Version=13.0.0.0, Culture=neutral,
PublicKeyToken=89845dcd8080cc91"
Also, when I try 'Start PowerShell' by rightclicking on the Integration Services Catalog in SSMS(18.5), I get the error:
Value cannot be null. Parameter name: value(mscorlib)
I don't know if the errors are connected in some way, but I hope it helps finding the problem.
I ran the PowerShell as administrator and there are no restrictions to reading or executing DLLs.
Thanks alot in advance and I'm happy with any hints you can give me!

How to use MSSQL DSN as URL in DataSource.groovy

I have been trying this code in DataSource.groovy but its showing an error of "No suitable driver"
dataSource
{
pooled = true
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
String url="jdbc:microsoft:sqlserver:DSNname";
}
I have already included two jdbc SQLserver drivers sqljdbc, sqljdbc4 (*.jar files).
I also tried this code but went futile.
DataSource
{
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
//url="jdbc:sqlserver://localhost:1433;database=DBNAME" its working
url="jdbc:odbc:myDSN"
username="sa"
password=""
}
Thanks a ton in advance.

What's the difference between app.config's connection string and c# connection string

Is there any difference between the following two lines of code in c# and app.config file.
C# connectionString declaration.
string conn = "/server = test/ DB = test_dev/ env = dev"
and
app.config declartion
<connectionStrings>
<add name="Test" connectionString="Data Source=.;Initial Catalog=test_dev;" providerName="System.Data.SqlClient" />
</connectionStrings>
How can I declare c# connection string to the format in the app.config file so that I can read from the app.config file.
There's no real difference between hard coding a connection string and pulling one out of the app.config file.
The advantage of using app.config is that you can use that same connection string in multiple places in your application, and then if you need to change it (for testing purposes or anything else really), you only have to change it in one spot that is nicely contained in a configuration file.
As mentioned in the comments, to read a connection string directly from your app.config, you can use this:
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Test"];
although there are many different ways to access the connection string (DataSet, etc.)
To read connectionString values in your C# code, you can access System.Configuration.ConnectionStringSettingsCollection
System.Configuration.ConfigurationManager.ConnectionStrings
will return collection of all connection strings defined in <connectionStrings></connectionStrings> section
You can access connection strings by name using
string conn =
System.Configuration.ConfigurationManager.ConnectionStrings["Test"];

Set PasswordQuestion in DotnetNuke(DNN)

i have a requirement to store Security Question and Answer, Their are columns in aspnet_Membership Table passwordQuestion and PasswordAnswer.i am using the following code
UserInfo User = new UserInfo();
User.AffiliateID = Null.NullInteger;
User.DisplayName =txtDisplayName.Text;
User.FirstName = txtFirstName.Text;
User.LastName = TxtLastName.Text;
User.Membership.Username = txtUserName.Text;
User.Membership.Password = txtPassword.Text;
User.Membership.CreatedDate = DateTime.Now;
User.Membership.Email = txtEmail.Text;
User.PortalID = this.PortalId;
User.Username = txtUserName.Text;
User.Email = txtEmail.Text;
User.Membership.PasswordQuestion =TxtSecurityQuestion.Text;
User.Membership.PasswordAnswer = TxtSecurityAnswer.Text;
UserCreateStatus ucStatus = UserController.CreateUser(ref User);
I am not able to store Password Question and answer in aspnet_Membership Table
If you set the requiresQuestionAndAnswer attribute to true in the SQL membership provider, DNN will automatically provide UI for and fill in those fields.
<membership defaultProvider="AspNetSqlMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<!-- Configuration for AspNetSqlMembershipProvider:
connectionStringName="string" Name corresponding to the entry in <connectionStrings> section where the connection string for the provider is specified
maxInvalidPasswordAttempts="int" The number of failed password attempts, or failed password answer attempts that are allowed before locking out a user?s account
passwordAttemptWindow="int" The time window, in minutes, during which failed password attempts and failed password answer attempts are tracked
enablePasswordRetrieval="[true|false]" Should the provider support password retrievals
enablePasswordReset="[true|false]" Should the provider support password resets
requiresQuestionAndAnswer="[true|false]" Should the provider require Q & A
minRequiredPasswordLength="int" The minimum password length
minRequiredNonalphanumericCharacters="int" The minimum number of non-alphanumeric characters
applicationName="string" Optional string to identity the application: defaults to Application Metabase path
requiresUniqueEmail="[true|false]" Should the provider require a unique email to be specified
passwordFormat="[Clear|Hashed|Encrypted]" Storage format for the password: Hashed (SHA1), Clear or Encrypted (Triple-DES)
description="string" Description of what the provider does
-->
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="SiteSqlServer" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="true" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="0" requiresUniqueEmail="false" passwordFormat="Encrypted" applicationName="DotNetNuke" description="Stores and retrieves membership data from the local Microsoft SQL Server database" />
</providers>
</membership>
You need to create a Membership object and attach it to your new user
Dim newMemebership As New UserMembership(User)
With newMemebership
.CreatedDate = Date.Now()
.Password = txtPassword.Text
.PasswordAnswer = Answer
.PasswordQuestion = Question
.etc....
End With
user.membership = newmembership
Sorry its VB but Im sure you can switch it over

Using ASP.NET ActiveDirectoryMembershipProvider with a Forest

I'm trying to setup an ActiveDirectoryMembershipProvider to go against a Forest and I can't seem to get it working. One of our AD Admins suggested I refer to the global catalog but it seems that is not supported. Anyone know if you can and if so how do you configure the AD Membership Provider to go against a Forest?
Here are some of the permutations I've tried and the resultant errors.
<add name="ADConnectionString1"
connectionString="LDAP://domain.org/DC=domain,DC=org:3268" />
"A referral was returned from the
server"
<add name="ADConnectionString2"
connectionString="LDAP://domain.org/DC=domain,DC=org:" />
A null reference exception.
<add name="ADConnectionString3"
connectionString="LDAP://domain.org" />
A null reference exception
<add name="ADConnectionString4"
connectionString="LDAP://domain.org:3268" />
"LDAP connections on the GC port are
not supported against Active
Directory."
<add name="ADConnectionString5"
connectionString="LDAP://domain.org:3268/DC=domain,DC=org:3268" />
"LDAP connections on the GC port are
not supported against Active
Directory."
<add name="ADConnectionString6"
connectionString="LDAP://domain.org:3268/DC=domain,DC=org" />
"LDAP connections on the GC port are
not supported against Active
Directory."
I don't have access to test an ActiveDirectoryMembershipProvider at the moment but global catalog searches are usually performed using the GC:// moniker. E.g.
using (DirectoryEntry searchRoot = new DirectoryEntry("GC://DC=yourdomain,DC=com"))
using (DirectorySearcher ds = new DirectorySearcher(searchRoot))
{
ds.Filter = "(sAMAccountName=userID1)";
ds.SearchScope = SearchScope.Subtree;
using (SearchResultCollection src = ds.FindAll())
{
foreach (SearchResult sr in src)
{
uxFred.Content = sr.Path;
}
}
}
My suggestion when working in ASP.NET is always to get your search filters, etc. working using LDP or just a plain console/winform/wpf app.

Resources