I am getting th efollowing error Please help.
C# code
string s2 = System.Configuration.ConfigurationManager.ConnectionStrings["conec"].ToString();
SqlConnection con = new SqlConnection(s2);
App.Config
<add name="conec" connectionString ="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=PACS_ENG_NEW;Data Source=HCL-68\SQLEXPRESS"/>
Error
Error 1 A field initializer cannot reference the non-static field, method, or property 'PDS1.frm_sales.s2' C:\Documents and Settings\admin\My Documents\Visual Studio 2008\Projects\PDS1\PDS1\Sales.cs 28 47 PDS1
This is generally happen because you can not access con in the field initializer,its non static.
SqlConnection conec = null;
string s2 = System.Configuration.ConfigurationManager.ConnectionStrings["conec"].ToString();
public constructor()
{
conec = new SqlConnection(s2);
}
Try as like above. It will work.
Related
I want to authenticate my vb.net Winform application to access my Google drive account. It works fine if I use a json file. But I want to avoid having a plain json file lying around the file system with my private keys in it. Especially when I am going to install the application on another machine.
So I tried to hardcode the credential parameters, with no luck so far. This is what I have tried:
Public Function Authenticate() As DriveService
Dim scope As String = DriveService.Scope.Drive
Dim credential As GoogleCredential
Dim params As New JsonCredentialParameters
With params
.Type = JsonCredentialParameters.ServiceAccountCredentialType
.ProjectId = "myprojid"
.PrivateKeyId = "mykeyid"
.PrivateKey = "-----BEGIN PRIVATE KEY-----\n myprivatekey =\n-----END PRIVATE KEY-----\n"
.ClientEmail = "myappname#myprojid.iam.gserviceaccount.com"
.ClientId = "12345"
End With
credential = GoogleCredential.FromJsonParameters(params).CreateScoped(scope)
Return New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = credential, .ApplicationName = "GoogleDriveDownloader"})
End Function
and also this similar approach:
Public Function CreateServiceCredentials() As GoogleCredential
Dim parameters = New JsonCredentialParameters With {
.Type = JsonCredentialParameters.ServiceAccountCredentialType,
.ProjectId = "myprojid",
.PrivateKeyId = "mykeyid",
.PrivateKey = "-----BEGIN PRIVATE KEY-----\n myprivatekey =\n-----END PRIVATE KEY-----\n",
.ClientEmail = "myappname#myprojid.iam.gserviceaccount.com",
.ClientId = "12345"
}
Dim json As String = JsonConvert.SerializeObject(parameters)
Dim stream = New MemoryStream(System.Text.Encoding.UTF8.GetBytes(json))
Return GoogleCredential.FromStream(stream)
End Function
In both cases I get the error: ArgumentException: PKCS8 data must be contained within '-----BEGIN PRIVATE KEY-----' and '-----END PRIVATE KEY-----'. Arg_ParamName_Name
If I remove the trailing \n I get the error: FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
What am I doing wrong?
I found it out myself, or let's call it a workaround for it:
I just took the whole text of the json file, put it into a winforms textbox and called:
credential = GoogleCredential.FromJson(txt_Credentials.Text).CreateScoped(scope)
Meh, it works ;-)
I use something like this for my application
MySqlConnection cnn = new MySqlConnection("Server=myServerAddress;" +
"Database=myDataBase;" +
"Uid=myUsername;" +
"Pwd=myPassword;");
And this changes everytime because we deploy databases with our application.
It works fine. I type in using(new connection(cnn)){ query... } and go.
And I've got it working with a dataset using a connection defined in the windows ODBC datasouce administrator.
But I'm curious, is there a way to use visual studio's dataset items using the my local test db and then change the connection of the dataset at runtime? Even better, can I use c# to programmatically add the ODBC data source at runtime?
Usually a connection string is loaded from the application exe.config file present in the same folder of the application. This connection string could be defined using the Settings tab in the project properties.
Right click on Properties of your project
Select the Settings tab (confirm the creation if you have no
settings)
Click on the ComboBox in the column type and select Connection String
Give a symbolic name to your connection
Type the connection string in the Value column (Examples at
connectionstrings.com)
Now in your project files you should have the file app.config (that becomes yourapp.exe.config) where there is a section like this
<configuration>
<connectionStrings>
<add name="MyAppConnection"
connectionString="Server=myServerAddress;Database=myDB;Uid=user;Pwd=pass;" />
</connectionStrings>
</configuration
At this point you read it in the program using
string conString = ConfigurationManager
.ConnectionStrings["MyAppConnection"]
.ConnectionString;
Instead in a dynamic situation where you want to build yourself the connection string during runtime (from user inputs, your own configuration files and so on) then you could leverage the functionality of the class MySqlConnectionStringBuilder
MySqlConnectionStringBuilder msb = new MySqlConnectionStringBuilder();
msb.Server = "localhost";
msb.Port = 3306;
msb.UserID = "root";
msb.Password = "xxx";
msb.Database = "test";
MySqlConnection cnn = new MySqlConnection(msb.ConnectionString);
cnn.Open();
Of course, these literal values could be substituted by your own variables.
The documentation of this class is surprising difficult to find. The best docs are the one of the Sql Server equivalent. It is interesting that you could read a static connection string from your config file and then change only the property needed.
string conString = ConfigurationManager
.ConnectionStrings["MyAppConnection"]
.ConnectionString;
MySqlConnectionStringBuilder msb = new MySqlConnectionStringBuilder(conString);
msb.Database = "AnotherDB";
MySqlConnection cnn = new MySqlConnection(msb.ConnectionString);
Application connection string cannot be changed at runtime.
User settings can be changed.
Assuming you are using an application setting-property named "MyConnectionString" which holds the connection string for the entire application.
On your main Program class create a global string:
internal static string Prconnstring;
Create and save this settings.cs file:
namespace MYSOLUTIONORPROJECTNAME.Properties
{
// (Not sure where I found this solution some time ago)
// This class allows you to handle specific events on the settings class:
// The SettingChanging event is raised before a setting's value is changed.
// The PropertyChanged event is raised after a setting's value is changed.
// The SettingsLoaded event is raised after the setting values are loaded.
// The SettingsSaving event is raised before the setting values are saved.
internal sealed partial class Settings
{
public Settings()
{
// // To add event handlers for saving and changing settings, uncomment the lines below:
//
// this.SettingChanging += this.SettingChangingEventHandler;
//
// this.SettingsSaving += this.SettingsSavingEventHandler;
//
}
private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e)
{
// Add code to handle the SettingChangingEvent event here.
}
private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e)
{
// Add code to handle the SettingsSaving event here.
}
public override object this[string propertyName]
{
get
{
if (propertyName == "MyConnectionString")
{
return Program.Prconnstring;
}
else
{
return base[propertyName];
}
}
set
{
base[propertyName] = value;
}
}
}
}
Before calling-opening any object that uses the connection string (examples include Forms that use datasets or other classes that use datasets created on the development enviroment) create your new connection string by any means you think. (Example: You might want to use as user name in the connection string the current user. Create the connection string using the info provided form the environment.)
Program.Prconnstring = thenewruntimeconnectionstring.
Now whenever the application tries to get MyConnectionString (which is hardcoded in the myapplicationname.config and cannot be changed) instead gets the new thenewruntimeconnectionstring you provided to Program.Prconnstring.
Be aware that the development connection string will be available-visible to final user, since it is just a text file. If you do not want this, you can change that file (will be a file named NAMEOFMYAPPLICATION.exe.config) during deployment, since the connection string hardcoded there, will be of no use for the running app. Do not delete it, just change.
Your connection string will be stored in your App.config (or c# equivalent). Say it's called MyConnectionString. Just add My.Settings("MyConnectionString")="[your new connection string]" to your entry point to change to database binding at runtime. E.g:
Public Sub New()
' This call is required by the designer.
InitializeComponent()
My.Settings("MyConnectionString") = "server=remotedb.uk;user id=MainUser;password=2jdi38edhnche73g;database=mainDb;persistsecurityinfo=True;allowuservariables=True;defaultcommandtimeout=480;characterset=utf8mb4"
End Sub
I've developed web applications in PHP for a few years and would like to learn about ASP.Net. I've installed VS2013 and have created an ASP.Net Web Application. I tried playing around with something that I found on wait for it W3Schools just because I knew it would be as simple as simple could be but it caused me some errors. I was trying to "connect" to an Access file in the wwwroot directory by using System.Data.OleDb but I had some problems.
My question is: Is there a simplistic way like in PHP where you have PHPMyAdmin to manage the database and then connect via something simple like $conn = new mysqli('localhost', 'user', 'password', 'db'); but for ASP.Net?
I'm struggling to find beginner level support for this on the web and would like to figure it out asap!
David, isnt's going to be "simple" as PHP, remember that VS2013 it's a server side language, more strong and complex.
I recommend to you the next:
Work with objects.
Here is some code may help you.
C#:
public System.Data.DataSet GetQuery(string _QueryComm){
System.Data.DataSet objResult = new System.Data.DataSet();
OleDbDataAdapter objAdapter;
strProvider = "Provider=SQLOLEDB.1;Data Source=YourServer;Initial Catalog=Database;User Id=databaseuser;Password=pass;";
objCon = new OleDbConnection(strProvider);
objCon.Open();
try
{
objAdapter = new OleDbDataAdapter(_QueryComm, objCon);
objAdapter.Fill(objResult);
objAdapter.Dispose();
objCon.Close();
}
catch (Exception e)
{
// Some exception handler
}
return objResult;}
Usage:
DataSet datainfo = GetQuery("select * from table");
VB:
Public Function GetQuery(strCommandQuery as String) As System.Data.DataSet
Dim objResult As System.Data.DataSet = New System.Data.DataSet
Dim objAdapter As OleDbDataAdapter
strProvider = "Provider=SQLOLEDB.1;Data Source=YourServer;Initial Catalog=Database;User Id=databaseuser;Password=pass;"
objCon = New OleDbConnection(strProvider)
objCon.Open()
Try
objAdapter = New OleDbDataAdapter(strCommandQuery, objCon)
objAdapter.Fill(objResult)
objAdapter.Dispose()
objCon.Close()
Catch ex As System.Exception
' Some exception handler
End Try
Return objResult End Function
Usage:
Dim datainfo as DataSet = GetQuery("select * From table")
Let me know if it's work for you.
Again my question related with the same project which i am doing for the report tracking system getting the below error in the tomcat logs after accessing the login page which is redirect towards "userloginmid.jsp".The code as shown below in the same window.
Please provide the solution for the same if possible.
<%# page import="java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
<%
String userName = request.getParameter("userName");
String password = request.getParameter("password");
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "report_tracking";
String driver = "com.mysql.jdbc.Driver";
String username = "root";
String userPassword = "root";
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
String strDateNew = sdf.format(now) ;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,username,userPassword);
Statement st = conn.createStatement();
String strQuery = "select * from userregister where username='"+userName+"' and password='"+password+"'";
out.println(strQuery);
ResultSet rs = st.executeQuery(strQuery);
if(rs.next())
{
int userid=rs.getInt(1);
String user=rs.getString(2);
session.setAttribute("userid",userid);
session.setAttribute("username",user);
session.setAttribute("intime",strDateNew);
String queryString = "INSERT INTO admin set userid="+userid+",intime='"+strDateNew+"'";
int i = st.executeUpdate(queryString);
if(i>0)
{
response.sendRedirect("welcome.jsp");
}
}
response.sendRedirect("login.jsp");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
As all said there are lot of loopholes in your code.
But the answer to your quesion is
sendRedirect requires a return statement
So change your lines of code to
response.sendRedirect( "welcome.jsp"); return; and
response.sendRedirect("login.jsp"); return;
Also read this .
There are a lot of problems with your code.
First, the explanation of your stated problem, redirecting after committing a response:
When the HTTP headers are already sent to the client (read about the HTTP protocol if you don't know it yet), they are out and cannot be pulled back. You're coding your sample in a jsp, which is the VIEW part of your architecture - and at least between the "page import" and the code part there's a newline which might trigger the server to flush its buffers to the client. Once that's done, the HTTP headers are gone and you cannot redirect any more.
Workaround: Don't implement this routine in a jsp, but in a servlet (or use a decent framework that handles this problem for you. Any of the current will suffice).
Now about some of the problems that your code has:
Please read about SQL injection. Think of someone posting
usernames like someone'; someone' OR '0' = '0 or similar (just
making them up as I go)
Once you get your connection and run in to any error, you won't clean
up the connection (e.g. you will leak connections on any exception)
You seem to be storing clear text passwords. Definitely a no-go as
soon as someone else than you will have an account
I've been searching for a solution for days now and I still cant seem to find one. I have a problem acquiring a connection in my Script component. I need to query my database to retrieve an Id to be used before I insert it in the
public override void AcquireConnections(object Transaction)
{
connMgr = base.Connections.Connection;
conn = (SqlConnection)connMgr.AcquireConnection(null);
}
I get an exception here.
System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
Any solutions?
For those that want to be able to do this in a Script Component:
Double Click the Script component to open the "Script Transformation Editor"
Click the "Connection Managers" list item.
Add a new Connection Manager. Select an existing ADO.NET connection manager.
Click on the "Script" list item and then the "Edit Script..." button.
You can do something like this inside your script:
using (SqlConnection connection = this.Connections.Connection.AcquireConnection(null) as SqlConnection)
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT [Value] FROM dbo.MyTable";
command.CommandType = CommandType.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
ProfanityWords.Add(reader.GetValue(0).ToString());
}
}
}
this.Connections.Connection.ReleaseConnection(connection);
}
ADO.NET connection manger should be created and refer into the code to type cast to the SqlConnection. If you dont have the ADO.NET connection in your SSIS pakcage you will get the TypeCast exception. Following steps should be used if you want to use the SqlConnection.
Create the ADO.NET connection.
Use the following line in your code.
var connObj = Dts.Connections["ADO.NETConnectionName"].AcquireConnection(null);
var sqlConn = (SqlConnection)connObj;
Once you done with your SQL connection. Use the following code to Close/ Release your connection.
Dts.Connections["ADO.NETConnectionName"].ReleaseConnection(connObj);
Hope this helps.