Run a Stored Procedure via a click of a button in .Net web page - sqlconnection

Afternoon All,
I have a stored procedure in an SQL 2005 database named GasNominationsRawData_Insert.
When executed this simply extracts some data from another database and inserts the result into a table. This query works fine.
What i need to do is enable this to be executed on the click on a button on my web page. I have had a good luck around the internet have have managed to create the following code in my .net 2008 web page. But i think im either missing something or i have have completly the wrong code. Im new to programming in .Net but i understand that i need to delclare the stored procedure, create the SQL connection, create the command line, open the conection, execute the query and then close the connection.
I dont need or have any parameters. Essentially this button is just used to push data to a table.
Imports System.Data
Imports System.Data.SqlClient
Partial Class RawData
Inherits System.Web.UI.Page
Protected Sub btnAddRawData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddRawData.Click
'Declare Stored Procedure
Dim GasNominationsRawData_Insert As String = "GasNominationsRawData_Insert"
'Declare SQL Connection (This is the connection string located on the web.config page)
Dim SQLConn As SqlConnection
SQLConn = New SqlConnection("GasNominationsDataConnectionString")
'Declare command
Dim SqlComm As SqlCommand = New SqlCommand("GasNominationsRawData_Insert", SQLConn)
SqlComm.CommandType = CommandType.StoredProcedure
Try
'Open SQL Connection
SQLConn.Open()
'Execute Query
SqlComm.ExecuteNonQuery()
'Close connection
SQLConn.Close()
Catch ex As Exception
Throw (ex)
End Try
End Sub
End Class
Any Help is much appreciated.
Regards Betty

Upps. I overlooked that. You're trying to connect to your database with the connectionstring: "GasNominationsDataConnectionString". That's of course no correct connection string.
Your connection string should look somehow like that:
"Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"
So you have to get your connection string first out of your web.config like
Dim GasNominationsDataConnectionString As String = ConfigurationManager.ConnectionStrings("GasNominationsDataConnectionString").ConnectionString
Regards
Anja

Looks fine at a first glance. So what happens on clicking the button? Have you assured that your btnAddRawData_Click is called when the button is clicked?

Related

Crystal reports - server and database

Im using visual studio 2010 + Sql Server 2008.
Im trying to show my reports using CR.. well when i try to use the system in my local machine, everything is ok.
I use store procedures to create reports.
The issue appears when i deploy the system in another PC.. A message appears asking for:
Server: // RETRIEVES ORIGINAL Server(Local)// Its not Correct i need to get Client Server
Database: // RETRIEVES ORIGINAL DB(Local)// Its not Correct i need to get Client DB
Username: I don't use any user , what user ?
Password: I don't use any password, what password?
i saw another solutions, but i can't find what's the data that i must use in Username or password. i use Windows autenthication to login to sql..
Thanks.
Regards.
Edit.. that's my code.. i can't use parameters, i don't receive any error. but system dont recognize the parameter that i send...
Dim NuevoReporte As New CReportNotaPorUsuario
Dim contenido As String
Dim ReportPath As String = My.Application.Info.DirectoryPath & "\CReportNotaPorUsuario.rpt"
Dim ConexionCR As New CrystalDecisions.Shared.ConnectionInfo()
contenido = Servicios.Funciones_Auxiliares.LeerArchivo(My.Application.Info.DirectoryPath & "\configuracion.txt")
ConexionCR.ServerName = Servicios.Funciones_Auxiliares.TextoEntreMarcas(contenido, "<server>", "</server>")
ConexionCR.DatabaseName = Servicios.Funciones_Auxiliares.TextoEntreMarcas(contenido, "<catalog>", "</catalog>")
ConexionCR.IntegratedSecurity = True
CrystalReportViewer1.ReportSource = ReportPath
'NuevoReporte.SetParameterValue("#cod_usuario", cbousuario.SelectedValue)
Dim field1 As ParameterField = Me.CrystalReportViewer1.ParameterFieldInfo(0)
Dim val1 As New ParameterDiscreteValue()
val1.Value = cbousuario.SelectedValue
field1.CurrentValues.Add(val1)
SetDBLogonForReport(ConexionCR)
It appears that you have separate servers and databases between the development and production environment. You need to make sure when you deploy your VS solution that the production server and database get referenced, not the development server and database.
There are some tutorials out there that can help you find a way to achieve this. Check out:
http://msdn.microsoft.com/en-us/library/dd193254(v=vs.100).aspx
Visual Studio 2010 Database Project Deploy to Different Environments
http://www.asp.net/web-forms/tutorials/deployment/advanced-enterprise-web-deployment/customizing-database-deployments-for-multiple-environments
EDIT: This seems to have evolved into a different issue than originally stated in the question. To dynamically get the connection string for CR from the text file, you will have to read teh text file first and put server name and database name into variables. Reading a text file, you can use something like string text = File.ReadAllText(#"C:\Folder\File.txt"); but you will need to extract server name and database name into variables. Then in order to use the variables in your connection string you use ConnectionInfo.Servername = variable1; and ConnectionInfo.DatabaseName = variable2.

insert into sql query in wpf

Hello everyone i am new in wpf. so i have got problems with it. if you help me, i will be so pleased. thanks everyone in advance.
My problem is, can not insert into name inside database in wpf. how can i fix it? my codes as follows;
private void button1_Click(object sender, RoutedEventArgs e)
{
try
{
string SqlString = "Insert Into UserInformation(name) Values (?)";
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Cell.mdb;Persist Security Info=True"))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("name", textBox1.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{ }
}
Try to use cmd.Parameters.AddWithValue("#name", textBox1.Text);
Is it opening the right database file? As people have suggested in the comments, set Visual Studio to break on first-chance exceptions, or remove the exception handling. The database file needs to exist, and you need the appropriate JET drivers.
I've tried your code and it works without any problems here (in a WPF application or otherwise). Using named parameters instead of a question mark was a good suggestion, but it doesn't appear to be the problem. (I have Office 2007 and .NET 3.5 SP1 installed, but I doubt that matters).
Are you using a WPF browser application (cbap)? Because you won't be able to access the local file system (and thus the database) if you are. WPF browser applications run with isolated permissions, much like a Silverlight browser application.
The problem here seams to be the parameter. In the command text you don't specify its name, but when you add it, it has a name. Change command text to :
Insert Into UserInformation(name) Values (#name)
In line:
cmd.Parameters.AddWithValue("name", textBox1.Text);
the parameter name should stay without # .

Can not find out the function for stored procedure in Entity Framework

Based on a database myDB, I generate edmx for all table and compile the project. Then I create stored procedure myProc in myDB. Then I update the model by "Update Model from database" in the node Stored Procedure and add myProc. It is fine. Then "Create a function import" on myProc. It is fine. Then I compiled the project, it is fine.
The return type for this import function is scalars(string) because myProc return a string.
Then I want to use this function for this stored procedure, but I can find out the function.
How to find out the matching function and call it in code?
In EF 3.5 only functions that return Entities show up in ObjectServices.
I.e. importing pulls the Function into the Conceptual Model, but NOT into the code-generation.
We have addressed this problem in 4.0.
In the meantime you can call the function using eSQL.
i.e. something like this (pseudo code):
EntityConnection connection = ctx.Connection as EntityConnection;
//Open the connection if necessary
connection.Open()
//Create the command
EntityCommand command = new EntityCommand();
command.CommandText = "Function(#p1,#p2");
command.Parameters.Add(...);
command.Parameters.Add(...);
command.Connection = connection;
string s = command.ExecuteScalar().ToString();
Hope this helps
Alex

cannot open user default database. login failed error

I am getting this "cannot open user default database. login failed" error. What I did was using ORM to create DataContext, in the code first call TableExists function to check if the version_tbl existed, if not, then call scripts to exec sql commands to create version_tbl. Then create a new dataContext, but problem is after the call I am getting this error on dataContext entity. If I remove the TableExists call, then dataContext creation is fine or move the dataContext creation before the TableExists call, but then the problem occurs in the TableExists call when it tries to connect. Seems like I can only connect once. Anyway I can call TableExists then able to create dataContext?
Below is my code sample
static bool TableExists(string tableName)
{
using (SqlConnection connection = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=planning;Integrated Security=True"))
{
string checkTable =
String.Format(
"IF OBJECT_ID('{0}', 'U') IS NOT NULL SELECT 'true' ELSE SELECT 'false'",
tableName);
SqlCommand command = new SqlCommand(checkTable, connection);
command.CommandType = CommandType.Text;
connection.Open();
bool retVal = Convert.ToBoolean(command.ExecuteScalar());
return retVal;
}
}
myFunc ()
{
if (!TableExists ("version_tbl"))
{
// call scripts to create version_tbl
}
DataContext ctx = new DataContext ();
Before everything else did you check if your domain user has the appropriate DB rgihts?
Try to validate the DB connection first.
You should be able to open two connections to the database at the same time: 1 through ADO.NET and 1 through LinqToSql.
The format of your code as displayed by StackOverflow is difficult to read, but it appears that you are returning from your TableExists method before the using statement is able to close the connection. Does it make any difference if you change that?
Are you getting different errors depending on which order you open the connections or is it always the same error?
Don't stop with the Exception. Go to the database and check the message in the log. The exceptions for LOGIN's are not clear on purpose for security reasons, but the log should have a better explanation of what happened.

Setup App.Config As Custom Action in Setup Project

I have a custom application with a simple app.config specifying SQL Server name and Database, I want to prompt the user on application install for application configuration items and then update the app.config file.
I admit I'm totally new to setup projects and am looking for some guidance.
Thank You
Mark Koops
I had problems with the code Gulzar linked to on a 64 bit machine. I found the link below to be a simple solution to getting values from the config ui into the app.config.
http://raquila.com/software/configure-app-config-application-settings-during-msi-install/
check this out - Installer with a custom action for changing settings
App.Config CAN be changed...however it exists in a location akin to HKEY___LOCAL_MACHINE i.e. the average user has read-only access.
So you will need to change it as an administrator - best time would be during installation, where you're (supposed to be) installing with enhanced permissions.
So create an Installer class, use a Custom Action in the setup project to pass in the user's choices (e.g. "/svr=[SERVER] /db=[DB] /uilevel=[UILEVEL]") and, in the AfterInstall event, change the App.Config file using something like:
Public Shared Property AppConfigSetting(ByVal SettingName As String) As Object
Get
Return My.Settings.PropertyValues(SettingName)
End Get
Set(ByVal value As Object)
Dim AppConfigFilename As String = String.Concat(System.Reflection.Assembly.GetExecutingAssembly.Location, ".config")
If (My.Computer.FileSystem.FileExists(AppConfigFilename)) Then
Dim AppSettingXPath As String = String.Concat("/configuration/applicationSettings/", My.Application.Info.AssemblyName, ".My.MySettings/setting[#name='", SettingName, "']/value")
Dim AppConfigXML As New System.Xml.XmlDataDocument
With AppConfigXML
.Load(AppConfigFilename)
Dim DataNode As System.Xml.XmlNode = .SelectSingleNode(AppSettingXPath)
If (DataNode Is Nothing) Then
Throw New Xml.XmlException(String.Format("Application setting not found ({0})!", AppSettingXPath))
Else
DataNode.InnerText = value.ToString
End If
.Save(AppConfigFilename)
End With
Else
Throw New IO.FileNotFoundException("App.Config file not found!", AppConfigFilename)
End If
End Set
End Property
Create custom dialogs for use in your Visual Studio Setup projects:
http://www.codeproject.com/Articles/18834/Create-custom-dialogs-for-use-in-your-Visual-Studi