I found this code on the web
Imports System
Imports System.Collections.Specialized
Namespace Williablog.Net.Examples.Providers
Public Class SqlMembershipProvider
Inherits System.Web.Security.SqlMembershipProvider
Public Overrides Sub Initialize(ByVal name As String, ByVal config As System.Collections.Specialized.NameValueCollection)
' intercept the setting of the connection string so that we can set it ourselves...
Dim specifiedConnectionString As String = config.Item("connectionStringName")
config.Item("connectionStringName") = GetYourRunTimeConnectionStringNAme(specifiedConnectionString)
' Pass doctored config to base classes
MyBase.Initialize(name, config)
End Sub
End Class
End Namespace
I think it will solve my problem.
I need to encrypt my connection string in the web.config
I am using MS default Membership provider
The login mechanism "Membership.ValidateUser(UsernameTextbox.Text,
passwordtext)) doesn't allow me to change the connection string and
it uses the one in the web.config.
Can i use the code above to change the connection string so that I
can decrypt it first before Validate User runs?
if yes, how do I use the code above in my code?
Related
I need to open the connection for Entity Framework without a connection string.
Due to a security layer that we are using I'm, we don't allow to connect to SQL Server using connection string, So we have a DLL that returns an opened SqlConnection.
EF version: 6.2.0
Error:
MetadataWorkspace must have EdmItemCollection pre-registered.
I tried to give the entityConnection as SqlConnection but I get an error.
Sample code:
Public Shared Function getEntityConnection() As EntityConnection
Dim workspace As New MetadataWorkspace()
Return New EntityClient.EntityConnection(workspace, AppCommon.AppFunctions.AppGetSQLCon(True))
End Function
AppCommon.AppFunctions.AppGetSQLCon(True) is the function which returns the SqlConnection instance.
But it's not working, does anyone have a solution for this issue?
Finally I found the solution for connecting the entityframework without a connection string, So what you need to is the following:
change the constructor of the entity `DbContext' to recive the connection from a function like this:
Public Sub New()
MyBase.New(getEntityConnection(), False)
End Sub
Then inside that function return an entity-connection object from an open sqlconnection obbject as the following:
Public Shared Function getEntityConnection() As EntityConnection
Dim workspace As New MetadataWorkspace(New String() {"res://*/"}, New Assembly() {Assembly.GetExecutingAssembly()})
Return New EntityClient.EntityConnection(workspace, getSqlConnectionObject())
End Function
Now your entityframework is connected to the database without a connection string
I'm busy testing SSRS to see if it's a viable alternative to our current reporting solution. I've set up SSRS on my local machine and have developed a working report using SQL Server Report Builder. Now what I'm trying to do is to call the report from within a WinForms application and display it in a ReportViewer control. The problem is that I've set up SQL Server to use SQL Server Authentication and I'm struggling to figure out how to connect to it programmatically.
The code I've pieced together so far looks like this:
Imports Microsoft.Reporting.WinForms
Public Class frmMain
Public v_report_name As String = "TestReport"
Public v_report_server As String = "http://elnah-ict-dt006:80"
Public v_report_path As String = "/reports_SSRS/"
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'create parameter array
Dim paramlist As New List(Of Microsoft.Reporting.WinForms.ReportParameter)
'create a specific parameter required by the report
Dim param1 As New Microsoft.Reporting.WinForms.ReportParameter("ClientID")
'add values to the parameter here we use a variable that holds the parameter value
param1.Values.Add("0279")
'add parameter to array
paramlist.Add(param1)
'Set the processing mode for the ReportViewer to Remote
ReportViewer1.ProcessingMode = ProcessingMode.Remote
'use the serverreport property of the report viewer to select a report from a remote SSRS server
ReportViewer1.ServerReport.ReportServerUrl = New System.Uri(v_report_server)
ReportViewer1.ServerReport.ReportPath = v_report_path & v_report_name
'select where the report should be generated with the report viewer control or on the report server using the SSRS service.
'Me.ReportViewer1.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Remote
'add the parameterlist to the viewer
ReportViewer1.ServerReport.SetParameters(paramlist)
Me.ReportViewer1.RefreshReport()
End Sub
End Class
When it hits the SetParameters line towards the bottom, it gets the following error message:
Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.MissingEndpointException
HResult=0x80131500
Message=The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version.
Source=Microsoft.ReportViewer.WinForms
I've tried to find examples of how to set the username and password but from what I can tell, most examples are focused on using Windows Authentication. I've tried the following line but it doesn't work:
ReportViewer1.ServerReport.ReportServerCredentials = New ReportServerCredentials("SA", "mypassword")
I haven't worked in VB.NET for ages so please excuse any obvious errors.
Here's some code from a Web Forms project I was part of the team for recently:
private void SetCredentials()
{
var userName = ConfigurationManager.AppSettings["SSRSUserName"];
var passwordEncrypted = ConfigurationManager.AppSettings["SSRSUserPasswordEncrypted"];
var passwordPlainText = SI.Crypto3.Crypto.Decrypt(passwordEncrypted, PASSPHRASE);
var domain = ConfigurationManager.AppSettings["SSRSUserDomain"];
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(passwordPlainText) && !string.IsNullOrEmpty(domain))
{
this.EventsHubReportViewer.ServerReport.ReportServerCredentials = new ReportServerCredentials(userName, passwordPlainText, domain);
}
}
That's C# but hopefully you can see that the important part is that last line. I think that the equivalent in your case should be:
ReportViewer1.ServerReport.ReportServerCredentials = New ReportServerCredentials(userName, password, domain)
The domain value can be an empty String if your on the same domain as the server.
EDIT:
I looked more closely and the ReportServerCredentials class that code is using is one of our own. In your case, you can use the Microsoft.ReportViewer.WinForms.ReportServerCredentials class, which I don't think has a constructor like that. Looking at the documentation for the NetworkCredentials property of that type indicates that you need to do this:
Dim credentials As New NetworkCredential(userName, password, domain)
ReportViewer1.ServerReport.ReportServerCredentials.NetworkCredentials = credentials
I'm trying to connect to a SQL Server database that is not local. I have the Data Source and Initial Catalog - no issues. But need to change Integrated Security to False and insert SQL Server credentials.
Does anyone have any idea how put that in the connection string?
Also, does anyone know how to handle SecureStrings?
Here is my code so far:
Dim pwd As New SecureString("Password")
Dim cred As New SqlCredential("Username", pwd)
Dim sql As New SqlConnection("Data Source=OnlineServer;Initial Catalog=DatabaseName;Integrated Security=False")
Have a look at here: SQL Connection Strings to hopefully find which one you need. This will give you the basics.
To make the SQL account credentials confidential, you should encrypt the <connection strings> section in the web.config. to do so:
aspnet_regiis -pe "connectionStrings" -app "OnlineServer" -prov "DataProtectionConfigurationProvider"
Retrieving your connection string using ConfigurationManager will automatically decrypt the string
Dim connectionString = ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
Here is a Microsoft Link that explains it further.
I worked out what I needed to do and how to handle secure strings.
Here is a code snippet for anyone who struggles in the future:
Imports System.Data.SqlClient
Imports System.Net.Mail
Imports System.Security
Public Module secure
Public Function sql()
Dim pass As String = "Password"
Dim pwd As SecureString = New SecureString()
For Each ch As Char In pass
pwd.AppendChar(ch)
Next
pwd.MakeReadOnly()
Dim cred As New SqlCredential("SQL_Login", pwd)
Dim conn As New SqlConnection("Server=Database_Name;Initial Catalog=Database_Address;Integrated Security=False", cred)
Return conn
End Function
End Module
Public Class sqlCommunications
Dim sql As New SqlConnection
Dim sqlcom As New SqlCommand
Public Sub start()
sql = secure.sql
sqlcom.Connection = sql
sql.Open()
sql.Close()
End Sub
End Class
In .NET I simply use Application Name = MyApp inside the connection string, but when using ADO connection through VBA the Activity Monitor of the SQL Server Management Studio always shows Microsoft Office 2010 in Processes on the Application column no matter what name I set on the VBA code.
conn.ConnectionString = "UID=" & UID & ";PWD=" & PWD & ";DSN=" & DSN & _
";Application Name = MyApp"
How can I set the application name for monitoring purposes?
Ahh I see VBA connection string doesn't support the Application Name attribute. It simply isn't being recognized when used within VBA. The only way I can think of solving this at the moment it's to return an ADODB.Connection object from a COM C# library.
Your own COM library would return an ADODB.Connection object with a predefined connection string which seem to work in .NET. You will be connecting to the database using a VBA ADODB.Connection object but with a substituted object reference. Instead of
Set cn = new ADODB.Connection you will use a GetConection() method exposed by your own library.
Dim cn as ADODB.Connection
Set cn = yourCOMlibrary.GetConnection
here are the steps
Download and install Visual Studio Express for Windows (FREE)
Open it as Administrator and create a New Project. Select Visual C# then Class Library and rename it to MyConnection
In the Solution Explorer, rename Class1.cs to ServerConnection.cs
Right click your MyConnection project in the Solution Explorer and select Add Reference
Type activeX in the search box and tick the Microsoft ActiveX Data Objects 6.1 Library
Copy and paste the below code into the ServerConnection.cs completely replacing whatever is in the file.
using System;
using System.Runtime.InteropServices;
using System.IO;
using ADODB;
namespace MyConnection
{
[InterfaceType(ComInterfaceType.InterfaceIsDual),
Guid("32A5A235-DA9F-47F0-B02C-9243315F55FD")]
public interface INetConnection
{
Connection GetConnection();
void Dispose();
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("4E7C6DA2-2606-4100-97BB-AB11D85E54A3")]
public class ServerConnection : INetConnection, IDisposable
{
private Connection cn;
private string cnStr = "Provider=SQLOLEDB; Data Source=SERVER\\DB; Initial Catalog=default_catalog; User ID=username; Password=password;Application Name=MyNetConnection";
public Connection GetConnection()
{
cn = new Connection();
cn.ConnectionString = cnStr;
return cn;
}
public void Dispose()
{
cn = null;
GC.Collect();
}
}
}
Locate the cnStr variable in the code and UPDATE your connection string details.
Note: if you are unsure about the connection string you should use see ALL CONNECTION STRINGS
Click on TOOLs in Visual Studio and CREATE GUID
Replace the GUIDs with your own and remove the curly braces so they are in the same format as the ones you see now from the copied code
Right click MyConnection in the Solution Explorer and select Properties.
Click the Application tab on the left side, then Assembly Info and tick Make Assembly COM-Visible
Click the *Build* from the menu on the left and tick Register For COM Interop
Note: If you are developing for 64-bit Office then make sure you change the Platform Target on the Build menu to x64! This is mandatory for 64-bit Office COM libraries to avoid any ActiveX related errors.
Right click MyConnection in the Solution Explorer and select Build from the menu.
If everything went OK then your MyConnection.dll and MyConnection.tlb should be successfully generated. Go to this path now
C:\Users\username\desktop\
or wherever you saved them
and you should see your files.
Now open Excel and go to VBE. Click Tools and select References.
Click the Browse button and navigate to the MyConnection.tlb.
Also, add references to Microsoft ActiveX Object 6.1 Library - this is so you can use ADODB library.
Now right click anywhere in the Project Explorer window and Insert a new Module
copy and paste the below code to it
Option Explicit
Sub Main()
Dim myNetConnection As ServerConnection
Set myNetConnection = New ServerConnection
Dim cn As ADODB.Connection
Set cn = myNetConnection.GetConnection
cn.Open
Application.Wait (Now + TimeValue("0:00:10"))
cn.Close
Set cn = Nothing
myNetConnection.Dispose
End Sub
Open SQL Server Management Studio, right click the server and select Activity Monitor
dont close this window
Go back to Excel and hit F5 or hit the green play button on the ribbon.
now switch back to SSMS ( SQL Server Management Studio )
and wait for your custom connection name to appear! :)
Here we go! That was easy, wasn't it? :)
This is what is happening.
You are returning an ADODB Connection object from you C# COM library by using myNetConnection.GetConnection function
Dim myNetConnection As ServerConnection
Set myNetConnection = New ServerConnection
Dim cn As ADODB.Connection
Set cn = myNetConnection.GetConnection
It's almost like saying Set cn = new ADODB.Connection but with predefined connection string which you did in your C# code.
You can use the cn object like a normal ADODB.Connection object within VBA now.
Remember to always .Close() the ADODB.Connection. A good programmers practice is to always close anything you open - streams, connections, etc.
You can rely on the Garbage Collector to free references/ memory but I also wrote a Dispose() method for you so you can force the GC to run. You can do that to immediately get rid of the Connection so it does not hang in the SSMS as opened.
Remember to use myNetConnection.Dispose along with the cn.Close and you'll be fine.
Note:
This is how I would do it if any one thinks this is wrong or needs to be updates (as being unstable or unsafe) please leave a comment.
Well, I hope this will be helpful to anyone in the future :)
The correct keyword to set the application name in an ADODB connection string in VBA is APP, not Application Name.
Example connection string, copied from an MS Access app I'm working on:
DRIVER={SQL Server};SERVER=xxxx;DATABASE=xxxx;Trusted_Connection=Yes;APP=xxxx
I am working on an MVC application using Entity Framework.
After creating an EDMX, I noticed the DB connection string is located in TWO places - an app.config file in my Data class library, and a web.config file in my web application.
We want to:
remove these two plain text connection strings
encrypt a single connection string
and use our pre-existing class library to decrypt the connection string when needed
I tried removing one or the other connection string from the config files, and DB access fails. Why are TWO required? And is there any way to do what we want in an MVC - EF project, and how would I tell EF that is what we are doing?
Thanks!
You can ignore the connection string in your EF project, I think, and just set the connection programmatically from your controller.
public class SomeController : Controller
{
public SomeController()
{
/* Substitute whatever method you want to fetch your data source string here */
/* example assumes plain text from web.config */
string dataSource = ConfigurationManager
.ConnectionStrings["ApplicationServices"]
.ConnectionString;
this.Entities = new SomeEntities(dataSource);
}
private SomeEntities Entities { get; set; }
}