Search Results

Search found 55 results on 3 pages for 'parameterdirection'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • Return nullable datetime from scalar, stored procedure

    - by molgan
    Hello I have a function that returns a date from a stored procedure, and it all works great til the value is NULL, how can I fix this so it works with null aswell? public DateTime? GetSomteDate(int SomeID) { DateTime? LimitDate= null; if (_entities.Connection.State == System.Data.ConnectionState.Closed) _entities.Connection.Open(); using (EntityCommand c = new EntityCommand("MyEntities.GetSomeDate", (EntityConnection)this._entities.Connection)) { c.CommandType = System.Data.CommandType.StoredProcedure; EntityParameter paramSomeID = new EntityParameter("SomeID", System.Data.DbType.Int32); paramSomeID.Direction = System.Data.ParameterDirection.Input; paramSomeID.Value = SomeID; c.Parameters.Add(paramSomeID); var x = c.ExecuteScalar(); if (x != null) LimitDate = (DateTime)x; return LimitDate.Value; }; }

    Read the article

  • Return rows from stored procedure

    - by molgan
    Hello I have this code: public IEnumerable<SomeClass> GetAvalibleThingies(DateTime startDate, DateTime endDate, int categoryID) { if (_entities.Connection.State == System.Data.ConnectionState.Closed) _entities.Connection.Open(); using (EntityCommand c = new EntityCommand("SomeEntities.GetAvalibleThingies", (EntityConnection)this._entities.Connection)) { c.CommandType = System.Data.CommandType.StoredProcedure; EntityParameter paramstartDate = new EntityParameter("startDate", System.Data.DbType.DateTime); paramstartDate.Direction = System.Data.ParameterDirection.Input; paramstartDate.Value = startDate; c.Parameters.Add(paramstartDate); ........ var x = c.ExecuteReader(); return x as IEnumerable<SomeClass>; }; But I can't get it to return a list of SomeClass. What's needed to do here? I use the entity framework 3.5sp1 one /M

    Read the article

  • Update query in ado.net

    - by nikhil
    I wanted to update a column in my table, i have written the code it runs fine without any error also it displays the confirmation dialog box but the table is not updated whats wrong with the code. Dim sqlConn As New SqlClient.SqlConnection sqlConn.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\housingsociety.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True" Try sqlConn.Open() Catch sqlError As Exception MsgBox(sqlError.Message, 0, "Connection Error!") End Try Dim sqlComm As New SqlClient.SqlCommand sqlComm.Connection = sqlConn sqlComm.CommandText = "update committe_member set name = '@name' where name = 'member1'" Dim paramString As New SqlClient.SqlParameter("@name", SqlDbType.VarChar, 50) paramString.Direction = ParameterDirection.Input sqlComm.Parameters.Add(paramString) paramString.Value = TextBox1.Text sqlComm.ExecuteNonQuery() MsgBox("Record Sucessfully Altered", 0, "Confirmation!") sqlConn.Close()

    Read the article

  • Supplying output parameter to sqlparametercollection resulting in error (Varbinary)

    - by dotnetdev
    Hi, I want to supply an output parameter to my stored proc. This output proc is returning byte[]. How do I do this? If I do the following: command.Parameters.Add(new SqlParameter("@Bytes", SqlDbType.VarBinary)); command.Parameters[1].Direction = ParameterDirection.Output; I get: System.InvalidOperationException: Byte[][1]: the Size property has an invalid size of 0. This stored proc works fine in SQL Server when I execute it via the SSMS option "Execute Stored Procedure). Any ideas? Thanks

    Read the article

  • can we assign object value to the label?

    - by user334294
    I have a label for that i have to assign object value which is returned by stored procedure.my code as following object returnvalue; SqlConnection con = new SqlConnection("Data Source=vela21; Initial Catalog=MilkDb;Integrated Security=True"); con.Open(); string sa; sa = textBox1.Text; SqlCommand cmd = new SqlCommand("custname", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("Cid", SqlDbType.Int).Value = sa; cmd.Parameters.Add("cname", SqlDbType.NVarChar, 20); cmd.Parameters["cname"].Direction = ParameterDirection.Output; returnvalue = cmd.ExecuteNonQuery(); label3.Text = Convert.ToString(returnvalue); con.Close(); can anyone help me? plz........

    Read the article

  • Problem with date parameter - Oracle

    - by Nicole
    Hi everyone! I have this stored procedure: CREATE OR REPLACE PROCEDURE "LIQUIDACION_OBTENER" ( p_Cuenta IN NUMBER, p_Fecha IN DATE, p_Detalle OUT LIQUIDACION.FILADETALLE%TYPE ) IS BEGIN SELECT FILADETALLE INTO p_Detalle FROM Liquidacion WHERE (FILACUENTA = p_Cuenta) AND (FILAFECHA = p_Fecha); END; and my c# code: string liquidacion = string.Empty; OracleCommand command = new OracleCommand("Liquidacion_Obtener"); command.BindByName = true; command.Parameters.Add(new OracleParameter("p_Cuenta", OracleDbType.Int64)); command.Parameters["p_Cuenta"].Value = cuenta; command.Parameters.Add(new OracleParameter("p_Fecha", OracleDbType.Date)); command.Parameters["p_Fecha"].Value = fecha; command.Parameters.Add("p_Detalle", OracleDbType.Varchar2, ParameterDirection.Output); OracleConnectionHolder connection = null; connection = this.GetConnection(); command.Connection = connection.Connection; command.CommandTimeout = 30; command.CommandType = CommandType.StoredProcedure; OracleDataReader lector = command.ExecuteReader(); while (lector.Read()) { liquidacion += ((OracleString)command.Parameters["p_Detalle"].Value).Value; } the thing is that when I try to put a value into the parameter "Fecha" (that is a date) the code gives me this error (when the line command.ExecuteReader(); is executed) Oracle.DataAccess.Client.OracleException : ORA-06502: PL/SQL: numeric or value error ORA-06512: at "SYSTEM.LIQUIDACION_OBTENER", line 9 ORA-06512: at line 1 the thing is that te date in the data base is saved like a date but it's format is "2010-APR-14" and the value I send is a datetime that has this format: "14/04/2010 00:00:00" could it be that??? I hope my post is understandable.. thanks!!!!!!!!!!

    Read the article

  • Problem with oracle stored procedure - parameters

    - by Nicole
    I have this stored procedure: CREATE OR REPLACE PROCEDURE "LIQUIDACION_OBTENER" ( p_Cuenta IN NUMBER, p_Fecha IN DATE, p_Detalle OUT LIQUIDACION.FILADETALLE%TYPE ) IS BEGIN SELECT FILADETALLE INTO p_Detalle FROM Liquidacion WHERE (FILACUENTA = p_Cuenta) AND (FILAFECHA = p_Fecha); END; / ...and my c# code: string liquidacion = string.Empty; OracleCommand command = new OracleCommand("Liquidacion_Obtener"); command.BindByName = true; command.Parameters.Add(new OracleParameter("p_Cuenta", OracleDbType.Int64)); command.Parameters["p_Cuenta"].Value = cuenta; command.Parameters.Add(new OracleParameter("p_Fecha", OracleDbType.Date)); command.Parameters["p_Fecha"].Value = fecha; command.Parameters.Add("p_Detalle", OracleDbType.Varchar2, ParameterDirection.Output); OracleConnectionHolder connection = null; connection = this.GetConnection(); command.Connection = connection.Connection; command.CommandTimeout = 30; command.CommandType = CommandType.StoredProcedure; OracleDataReader lector = command.ExecuteReader(); while (lector.Read()) { liquidacion += ((OracleString)command.Parameters["p_Detalle"].Value).Value; } the thing is that when I try to put a value into the parameter "Fecha" (that is a date) the code gives me this error (when the line command.ExecuteReader(); is executed) Oracle.DataAccess.Client.OracleException : ORA-06502: PL/SQL: numeric or value error ORA-06512: at "SYSTEM.LIQUIDACION_OBTENER", line 9 ORA-06512: at line 1 I tried with the datetime and was not the problem, I eve tried with no input parameters and just the output and still got the same error. Aparently the problem is with the output parameter. I already tried putting p_Detalle OUT VARCHAR2 instead of p_Detalle OUT LIQUIDACION.FILADETALLE%TYPE but it didn't work either I hope my post is understandable.. thanks!!!!!!!!!!

    Read the article

  • C# and SQL - sub select from a table parameter

    - by Dr.HappyPants
    Below is a code snippet for passing a table as a parameter to a query that can be used in Sql Server 2008. I'm confused though about the "SELECT id.custid FROM @custids id". Why does it use id.custid and @custids id...? private static void datatable_example() { string [] custids = {"ALFKI", "BONAP", "CACTU", "FRANK"}; DataTable custid_list = new DataTable(); custid_list.Columns.Add("custid", typeof(String)); foreach (string custid in custids) { DataRow dr = custid_list.NewRow(); dr["custid"] = custid; custid_list.Rows.Add(dr); } using(SqlConnection cn = setup_connection()) { using(SqlCommand cmd = cn.CreateCommand()) { cmd.CommandText = @"SELECT C.CustomerID, C.CompanyName FROM Northwind.dbo.Customers C WHERE C.CustomerID IN (SELECT id.custid FROM @custids id)"; cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@custids", SqlDbType.Structured); cmd.Parameters["@custids"].Direction = ParameterDirection.Input; cmd.Parameters["@custids"].TypeName = "custid_list_tbltype"; cmd.Parameters["@custids"].Value = custid_list; using (SqlDataAdapter da = new SqlDataAdapter(cmd)) using (DataSet ds = new DataSet()) { da.Fill(ds); PrintDataSet(ds); } } }

    Read the article

  • OdbcCommand on Stored Procedure - "Parameter not supplied" error on Output parameter

    - by Aaron
    I'm trying to execute a stored procedure (against SQL Server 2005 through the ODBC driver) and I recieve the following error: Procedure or Function 'GetNodeID' expects parameter '@ID', which was not supplied. @ID is the OUTPUT parameter for my procedure, there is an input @machine which is specified and is set to null in the stored procedure: ALTER PROCEDURE [dbo].[GetNodeID] @machine nvarchar(32) = null, @ID int OUTPUT AS BEGIN SET NOCOUNT ON; IF EXISTS(SELECT * FROM Nodes WHERE NodeName=@machine) BEGIN SELECT @ID = (SELECT NodeID FROM Nodes WHERE NodeName=@machine) END ELSE BEGIN INSERT INTO Nodes (NodeName) VALUES (@machine) SELECT @ID = (SELECT NodeID FROM Nodes WHERE NodeName=@machine) END END The following is the code I'm using to set the parameters and call the procedure: OdbcCommand Cmd = new OdbcCommand("GetNodeID", _Connection); Cmd.CommandType = CommandType.StoredProcedure; Cmd.Parameters.Add("@machine", OdbcType.NVarChar); Cmd.Parameters["@machine"].Value = Environment.MachineName.ToLower(); Cmd.Parameters.Add("@ID", OdbcType.Int); Cmd.Parameters["@ID"].Direction = ParameterDirection.Output; Cmd.ExecuteNonQuery(); _NodeID = (int)Cmd.Parameters["@Count"].Value; I've also tried using Cmd.ExecuteScalar with no success. If I break before I execute the command, I can see that @machine has a value. If I execute the procedure directly from Management Studio, it works correctly. Any thoughts? Thanks

    Read the article

  • How do I get LongVarchar out param from SPROC in ADO.NET 2.0 with SQLAnywhere 10?

    - by todthomson
    Hi All, I have sproc 'up_selfassessform_view' which has the following parameters: in ai_eqidentkey SYSKEY in ai_acidentkey SYSKEY out as_eqcomments TEXT_STRING out as_acexplanation TEXT_STRING  -  which are domain objects - SYSKEY is 'integer' and TEXT_STRING is 'long varchar'. I can call the sproc fine from iSQL using the following code: create variable @eqcomments TEXT_STRING; create variable @acexamples TEXT_STRING; call up_selfassessform_view (75000146, 3, @eqcomments, @acexamples); select @eqcomments, @acexamples;  - which returns the correct values from the DB (so I know the SPROC is good). I have configured the out param in ADO.NET like so (which has worked up until now for 'integer', 'timestamp', 'varchar(255)', etc): SAParameter as_acexplanation = cmd.CreateParameter(); as_acexplanation.Direction = ParameterDirection.Output; as_acexplanation.ParameterName = "as_acexplanation"; as_acexplanation.SADbType = SADbType.LongVarchar; cmd.Parameters.Add(as_acexplanation); When I run the following code: SADataReader reader = cmd.ExecuteReader(); I receive the following error: Parameter[2]: the Size property has an invalid size of 0. Which (I suppose) makes sense... But the thing is, I don't know the size of the field (it's just "long varchar" it doesn't have a predetermined length - unlike varchar(XXX)). Anyhow, just for fun, I add the following: as_acexplanation.Size = 1000; and the above error goes away, but now when I call: as_acexplanation.Value i get back a string of length = 1000 which is just '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0...' (\0 repeated 1000 times). So I'm really really stuck... Any help one this one would be much appreciated. Cheers! ;) Tod T.

    Read the article

  • Getting identity from Ado.Net Update command

    - by rboarman
    My scenario is simple. I am trying to persist a DataSet and have the identity column filled in so I can add child records. Here's what I've got so far: using (SqlConnection connection = new SqlConnection(connStr)) { SqlDataAdapter adapter = new SqlDataAdapter("select * from assets where 0 = 1", connection); adapter.MissingMappingAction = MissingMappingAction.Passthrough; adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; SqlCommandBuilder cb = new SqlCommandBuilder(adapter); var insertCmd = cb.GetInsertCommand(true); insertCmd.Connection = connection; connection.Open(); adapter.InsertCommand = insertCmd; adapter.InsertCommand.CommandText += "; set ? = SCOPE_IDENTITY()"; adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.OutputParameters; var param = new SqlParameter("RowId", SqlDbType.Int); param.SourceColumn = "RowId"; param.Direction = ParameterDirection.Output; adapter.InsertCommand.Parameters.Add(param); SqlTransaction transaction = connection.BeginTransaction(); insertCmd.Transaction = transaction; try { assetsImported = adapter.Update(dataSet.Tables["Assets"]); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); // Log an error } connection.Close(); } The first thing that I noticed, besides the fact that the identity value is not making its way back into the DataSet, is that my change to add the scope_identity select statement to the insert command is not being executed. Looking at the query using Profiler, I do not see my addition to the insert command. Questions: 1) Why is my addition to the insert command not making its way to the sql being executed on the database? 2) Is there a simpler way to have my DataSet refreshed with the identity values of the inserted rows? 3) Should I use the OnRowUpdated callback to add my child records? My plan was to loop through the rows after the Update() call and add children as needed. Thank you in advance. Rick

    Read the article

  • Please take a stab at this VB.Net Oracle-related sample and help me with String.Format.

    - by Hamish Grubijan
    If the database is not Oracle, it is MS SQl 2008. My task: if Oracle, add two more parameters when calling a stored proc. Oracle and MSFT stored procs are generated; Oracle ones have 3 extra parameters: Vret_val out number, Vparam2 in out number, Vparam3 in out number, ... the rest (The are not actually named Vparam2 and Vparam3, but this should not matter). So, the code for a helper VB.Net class that calls a stored proc: Imports System.Data.Odbc Imports System.Configuration Dim objCon As OdbcConnection = Nothing Dim objAdapter As OdbcDataAdapter Dim cmdCommand As New OdbcCommand Dim objDataTable As DataTable Dim sconnection As String Try sconnection = mConnectionString objAdapter = New OdbcDataAdapter objCon = New OdbcConnection(sconnection) objCon.Open() objAdapter.SelectCommand = cmdCommand objAdapter.SelectCommand.Connection = objCon objAdapter.SelectCommand.CommandType = CommandType.StoredProcedure objAdapter.SelectCommand.CommandTimeout = Globals.mReportTimeOut If Not mIsOracle Then objAdapter.SelectCommand.CommandText = String.Format("{{call {0}}}", spName) Else Dim returnValue As New OdbcParameter returnValue.Direction = ParameterDirection.Output returnValue.ParameterName = "@Vret_val" returnValue.OdbcType = OdbcType.Numeric objAdapter.SelectCommand.Parameters.Add(returnValue) objAdapter.SelectCommand.CommandText = String.Format("{{call {0}(?)}}", spName) End If Try objDataTable = New DataTable(spName) objAdapter.Fill(objDataTable) Catch ex As Exception ... Question: I am puzzled as to what String.Format("{{call {0}(?)}}", spName) does, in particular the (?) part. My understanding of the String.Format is that it will simply replace {0} with spName. The {{, }}, and (?) do throw me off because { reminds me of formatting, (?) hints at some advanced regex use. Unfortunately I am getting little help from a key person who is on vacation without a leash [smart]phone. I am guessing that I simply add 5 more lines for each additional parameter, and change String.Format("{{call {0}(?)}}", spName) to String.Format("{{call {0}(?,?,?)}}", spName). I forgot to mention that I am coding this "blindly" - I have a compiler to help me, but no environment set up to test this. This will be over in a few days, but I need to do my best to try finishing it on time :) Thanks.

    Read the article

  • How to send check boxes ID in gridview in one string for mass update.

    - by SmartDev
    hi , I have a grid which has check boxes and when selecting the top chek box select all will select all the check box in gridview and would update .for this im using for loop where it exceutes every time and this is taking lot of time cuase there are more thn 100 records in grid . try { string StrOutputMessageDisplayDocReqCsu = string.Empty; string strid = string.Empty; string strflag = string.Empty; string strSelected = string.Empty; for (int j = 0; j < GdvDocReqMU.Rows.Count; j++) { CheckBox Chkupdate = (CheckBox)GdvDocReqMU.Rows[j].Cells[1].FindControl("chkDR"); if (Chkupdate != null) { if (Chkupdate.Checked) { strid = ((Label)GdvDocReqMU.Rows[j].FindControl("lblIDDocReqCsu")).Text; strflag = ((Label)GdvDocReqMU.Rows[j].FindControl("lblStatusDocReqCsu")).Text; cmd = new SqlCommand("sp_Update_v1", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@id", strSelected); cmd.Parameters.AddWithValue("@flag", DdlStatusDocReqMU.SelectedValue); cmd.Parameters.AddWithValue("@notes", txtnotesDocReqMU.Text); cmd.Parameters.AddWithValue("@user", strUseridDRAhk); cmd.Parameters.Add(new SqlParameter("@message", SqlDbType.VarChar, 100, ParameterDirection.Output, false, 0, 50, "message", DataRowVersion.Default, null)); cmd.UpdatedRowSource = UpdateRowSource.OutputParameters; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } } //} //StrOutputMessageDisplayDocReqCsu += (string)cmd.Parameters["@message"].Value + "<br/>"; //lbldbmessDocReqAhk.Text += StrOutputMessageDisplayDocReqCsu + "<br>"; GetgridDocReq(); } catch (Exception ex) { lbldbmessDocReqAhk.Text = ex.Message.ToString(); }

    Read the article

  • using a stored procedure for login in c#

    - by Jin Yim
    Hi all, If I run a store procedure with two parameter values (admin, admin) (parameters : admin, admin) I get the following message : Session_UID User_Group_Name Sys_User_Name NULLAdministratorsNTMSAdmin No rows affected. (1 row(s) returned) @RETURN_VALUE = 0 Finished running [dbo].[p_SYS_Login]. -- To get the same message in c# I used the code following : string strConnection = Settings.Default.ConnectionString; using (SqlConnection conn = new SqlConnection(strConnection)) { using (SqlCommand cmd = new SqlCommand()) { SqlDataReader rdr = null; cmd.Connection = conn; cmd.CommandText = "p_SYS_Login"; cmd.CommandType = CommandType.StoredProcedure; SqlParameter paramReturnValue = new SqlParameter(); paramReturnValue.ParameterName = "@RETURN_VALUE"; paramReturnValue.SqlDbType = SqlDbType.Int; paramReturnValue.SourceColumn = null; paramReturnValue.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(paramReturnValue); cmd.Parameters.Add(paramGroupName); cmd.Parameters.Add(paramUserName); cmd.Parameters.AddWithValue("@Sys_Login", "admin"); cmd.Parameters.AddWithValue("@Sys_Password", "admin"); try { conn.Open(); rdr = cmd.ExecuteReader(); string test = (string)cmd.Parameters["@RETURN_VALUE"].Value; while (rdr.Read()) { Console.WriteLine("test : " + rdr[0]); } } catch (Exception ex) { string message = ex.Message; string caption = "MAVIS Exception"; MessageBoxButtons buttons = MessageBoxButtons.OK; MessageBox.Show( message, caption, buttons, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); } finally { cmd.Dispose(); conn.Close(); } } } but I get nothing in SqlDataReader rdr ; is there something I am missing ? Thanks

    Read the article

  • asp.net stored procedure problem

    - by kenom
    Why this code don't work,when i want run this code vwd 2008 express show me this error message:Invalid object name 'answers'. this is my ascx.cs code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Security; using System.Data.SqlClient; using System.Configuration; public partial class odgl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { string connectionString = @"SANATIZEDSTRING!!!!"; using (SqlConnection cn = new SqlConnection(connectionString)) { using (SqlCommand dohvati = new SqlCommand("dbo.get_answers",cn)) { dohvati.CommandType = CommandType.StoredProcedure; SqlParameter izracun = new SqlParameter("@count", SqlDbType.Int); izracun.Direction = ParameterDirection.Output; dohvati.Parameters.Add(izracun); cn.Open(); dohvati.ExecuteNonQuery(); int count = Int32.Parse(dohvati.Parameters["@count"].Value.ToString()); Response.Write(count.ToString()); cn.Close(); } } } } and this is my stored procedure : set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER procedure [dbo].[get_answers] @ukupno int output as select @count= (SELECT COUNT(*) FROM answers) go

    Read the article

  • How to convert "0" and "1" to false and true

    - by Chris
    I have a method which is connecting to a database via Odbc. The stored procedure which I'm calling has a return value which from the database side is a 'Char'. Right now I'm grabbing that return value as a string and using it in a simple if statement. I really don't like the idea of comparing a string like this when only two values can come back from the database, 0 and 1. OdbcCommand fetchCommand = new OdbcCommand(storedProc, conn); fetchCommand.CommandType = CommandType.StoredProcedure; fetchCommand.Parameters.AddWithValue("@column ", myCustomParameter); fetchCommand.Parameters.Add("@myReturnValue", OdbcType.Char, 1). Direction = ParameterDirection.Output; fetchCommand.ExecuteNonQuery(); string returnValue = fetchCommand.Parameters["@myReturnValue"].Value.ToString(); if (returnValue == "1") { return true; } What would be the proper way to handle this situation. I've tried 'Convert.ToBoolean()' which seemed like the obvious answer but I ran into the 'String was not recognized as a valid Boolean. ' exception being thrown. Am I missing something here, or is there another way to make '1' and '0' act like true and false? Thanks!

    Read the article

  • How to create festival calendar in ASP.net

    - by Atul
    I want to make a festival calendar using asp.net from that I used two ajax calendar and one textbox it is a festival textbox where we enter festival which FromDate and ToDate respectively. I want to do this as following point If I enter in textbox Christmas and Choose Fromdate=25/12/2011 and ToDate=31/12/2011 then it will be valid If I choose fromDate=25/12/2011 and ToDate=24/12/2011 then it will invalid If I choose Fromdate=25/12/2011 and Todate=28/12/2011 then also it is invalid because it coming in between 25/12/2011 and 31/12/2011 If I Choose fromdate=1/1/2011 and ToDate=1/1/2011 then it is valid If I choose fromdate=21/12/2011 and 25/12/2011 then it is invalid because of already Christmas done in 1/1/2011 And all date should show in gridview like 25-dec-2011 format Here is my code: DateTime dt1 = Convert.ToDateTime(txt_fromdate.Text); DateTime dt2 = Convert.ToDateTime(txt_todate.Text); if (dt1 > dt2) { con.Open(); com = new SqlCommand("BTNN_MovieDB_Festival_Details_Insert", con); com.Parameters.Add("@fromdate", SqlDbType.VarChar).Value = dateformat_mmdd(txt_fromdate.Text.ToString().Trim()); com.Parameters.Add("@todate", SqlDbType.VarChar).Value = dateformat_mmdd(txt_todate.Text.ToString().Trim()); com.Parameters.Add("@return", SqlDbType.VarChar).Direction = ParameterDirection.ReturnValue; com.ExecuteNonQuery(); con.Close(); showdata(); } else if (dt1 < dt2) { lblerror.Text = "ToDate should be greater than FromDate"; }

    Read the article

  • Creating packages in code – Execute SQL Task

    The Execute SQL Task is for obvious reasons very well used, so I thought if you are building packages in code the chances are you will be using it. Using the task basic features of the task are quite straightforward, add the task and set some properties, just like any other. When you start interacting with variables though it can be a little harder to grasp so these samples should see you through. Some of these more advanced features are explained in much more detail in our ever popular post The Execute SQL Task, here I’ll just be showing you how to implement them in code. The abbreviated code blocks below demonstrate the different features of the task. The complete code has been encapsulated into a sample class which you can download (ExecSqlPackage.cs). Each feature described has its own method in the sample class which is mentioned after the code block. This first sample just shows adding the task, setting the basic properties for a connection and of course an SQL statement. Package package = new Package(); // Add the SQL OLE-DB connection ConnectionManager sqlConnection = AddSqlConnection(package, "localhost", "master"); // Add the SQL Task package.Executables.Add("STOCK:SQLTask"); // Get the task host wrapper TaskHost taskHost = package.Executables[0] as TaskHost; // Set required properties taskHost.Properties["Connection"].SetValue(taskHost, sqlConnection.ID); taskHost.Properties["SqlStatementSource"].SetValue(taskHost, "SELECT * FROM sysobjects"); For the full version of this code, see the CreatePackage method in the sample class. The AddSqlConnection method is a helper method that adds an OLE-DB connection to the package, it is of course in the sample class file too. Returning a single value with a Result Set The following sample takes a different approach, getting a reference to the ExecuteSQLTask object task itself, rather than just using the non-specific TaskHost as above. Whilst it means we need to add an extra reference to our project (Microsoft.SqlServer.SQLTask) it makes coding much easier as we have compile time validation of any property and types we use. For the more complex properties that is very valuable and saves a lot of time during development. The query has also been changed to return a single value, one row and one column. The sample shows how we can return that value into a variable, which we also add to our package in the code. To do this manually you would set the Result Set property on the General page to Single Row and map the variable on the Result Set page in the editor. Package package = new Package(); // Add the SQL OLE-DB connection ConnectionManager sqlConnection = AddSqlConnection(package, "localhost", "master"); // Add the SQL Task package.Executables.Add("STOCK:SQLTask"); // Get the task host wrapper TaskHost taskHost = package.Executables[0] as TaskHost; // Add variable to hold result value package.Variables.Add("Variable", false, "User", 0); // Get the task object ExecuteSQLTask task = taskHost.InnerObject as ExecuteSQLTask; // Set core properties task.Connection = sqlConnection.Name; task.SqlStatementSource = "SELECT id FROM sysobjects WHERE name = 'sysrowsets'"; // Set single row result set task.ResultSetType = ResultSetType.ResultSetType_SingleRow; // Add result set binding, map the id column to variable task.ResultSetBindings.Add(); IDTSResultBinding resultBinding = task.ResultSetBindings.GetBinding(0); resultBinding.ResultName = "id"; resultBinding.DtsVariableName = "User::Variable"; For the full version of this code, see the CreatePackageResultVariable method in the sample class. The other types of Result Set behaviour are just a variation on this theme, set the property and map the result binding as required. Parameter Mapping for SQL Statements This final example uses a parameterised SQL statement, with the coming from a variable. The syntax varies slightly between connection types, as explained in the Working with Parameters and Return Codes in the Execute SQL Taskhelp topic, but OLE-DB is the most commonly used, for which a question mark is the parameter value placeholder. Package package = new Package(); // Add the SQL OLE-DB connection ConnectionManager sqlConnection = AddSqlConnection(package, ".", "master"); // Add the SQL Task package.Executables.Add("STOCK:SQLTask"); // Get the task host wrapper TaskHost taskHost = package.Executables[0] as TaskHost; // Get the task object ExecuteSQLTask task = taskHost.InnerObject as ExecuteSQLTask; // Set core properties task.Connection = sqlConnection.Name; task.SqlStatementSource = "SELECT id FROM sysobjects WHERE name = ?"; // Add variable to hold parameter value package.Variables.Add("Variable", false, "User", "sysrowsets"); // Add input parameter binding task.ParameterBindings.Add(); IDTSParameterBinding parameterBinding = task.ParameterBindings.GetBinding(0); parameterBinding.DtsVariableName = "User::Variable"; parameterBinding.ParameterDirection = ParameterDirections.Input; parameterBinding.DataType = (int)OleDBDataTypes.VARCHAR; parameterBinding.ParameterName = "0"; parameterBinding.ParameterSize = 255; For the full version of this code, see the CreatePackageParameterVariable method in the sample class. You’ll notice the data type has to be specified for the parameter IDTSParameterBinding .DataType Property, and these type codes are connection specific too. My enumeration I wrote several years ago is shown below was probably done by reverse engineering a package and also the API header file, but I recently found a very handy post that covers more connections as well for exactly this, Setting the DataType of IDTSParameterBinding objects (Execute SQL Task). /// <summary> /// Enumeration of OLE-DB types, used when mapping OLE-DB parameters. /// </summary> private enum OleDBDataTypes { BYTE = 0x11, CURRENCY = 6, DATE = 7, DB_VARNUMERIC = 0x8b, DBDATE = 0x85, DBTIME = 0x86, DBTIMESTAMP = 0x87, DECIMAL = 14, DOUBLE = 5, FILETIME = 0x40, FLOAT = 4, GUID = 0x48, LARGE_INTEGER = 20, LONG = 3, NULL = 1, NUMERIC = 0x83, NVARCHAR = 130, SHORT = 2, SIGNEDCHAR = 0x10, ULARGE_INTEGER = 0x15, ULONG = 0x13, USHORT = 0x12, VARCHAR = 0x81, VARIANT_BOOL = 11 } Download Sample code ExecSqlPackage.cs (10KB)

    Read the article

  • Creating packages in code – Execute SQL Task

    The Execute SQL Task is for obvious reasons very well used, so I thought if you are building packages in code the chances are you will be using it. Using the task basic features of the task are quite straightforward, add the task and set some properties, just like any other. When you start interacting with variables though it can be a little harder to grasp so these samples should see you through. Some of these more advanced features are explained in much more detail in our ever popular post The Execute SQL Task, here I’ll just be showing you how to implement them in code. The abbreviated code blocks below demonstrate the different features of the task. The complete code has been encapsulated into a sample class which you can download (ExecSqlPackage.cs). Each feature described has its own method in the sample class which is mentioned after the code block. This first sample just shows adding the task, setting the basic properties for a connection and of course an SQL statement. Package package = new Package(); // Add the SQL OLE-DB connection ConnectionManager sqlConnection = AddSqlConnection(package, "localhost", "master"); // Add the SQL Task package.Executables.Add("STOCK:SQLTask"); // Get the task host wrapper TaskHost taskHost = package.Executables[0] as TaskHost; // Set required properties taskHost.Properties["Connection"].SetValue(taskHost, sqlConnection.ID); taskHost.Properties["SqlStatementSource"].SetValue(taskHost, "SELECT * FROM sysobjects"); For the full version of this code, see the CreatePackage method in the sample class. The AddSqlConnection method is a helper method that adds an OLE-DB connection to the package, it is of course in the sample class file too. Returning a single value with a Result Set The following sample takes a different approach, getting a reference to the ExecuteSQLTask object task itself, rather than just using the non-specific TaskHost as above. Whilst it means we need to add an extra reference to our project (Microsoft.SqlServer.SQLTask) it makes coding much easier as we have compile time validation of any property and types we use. For the more complex properties that is very valuable and saves a lot of time during development. The query has also been changed to return a single value, one row and one column. The sample shows how we can return that value into a variable, which we also add to our package in the code. To do this manually you would set the Result Set property on the General page to Single Row and map the variable on the Result Set page in the editor. Package package = new Package(); // Add the SQL OLE-DB connection ConnectionManager sqlConnection = AddSqlConnection(package, "localhost", "master"); // Add the SQL Task package.Executables.Add("STOCK:SQLTask"); // Get the task host wrapper TaskHost taskHost = package.Executables[0] as TaskHost; // Add variable to hold result value package.Variables.Add("Variable", false, "User", 0); // Get the task object ExecuteSQLTask task = taskHost.InnerObject as ExecuteSQLTask; // Set core properties task.Connection = sqlConnection.Name; task.SqlStatementSource = "SELECT id FROM sysobjects WHERE name = 'sysrowsets'"; // Set single row result set task.ResultSetType = ResultSetType.ResultSetType_SingleRow; // Add result set binding, map the id column to variable task.ResultSetBindings.Add(); IDTSResultBinding resultBinding = task.ResultSetBindings.GetBinding(0); resultBinding.ResultName = "id"; resultBinding.DtsVariableName = "User::Variable"; For the full version of this code, see the CreatePackageResultVariable method in the sample class. The other types of Result Set behaviour are just a variation on this theme, set the property and map the result binding as required. Parameter Mapping for SQL Statements This final example uses a parameterised SQL statement, with the coming from a variable. The syntax varies slightly between connection types, as explained in the Working with Parameters and Return Codes in the Execute SQL Taskhelp topic, but OLE-DB is the most commonly used, for which a question mark is the parameter value placeholder. Package package = new Package(); // Add the SQL OLE-DB connection ConnectionManager sqlConnection = AddSqlConnection(package, ".", "master"); // Add the SQL Task package.Executables.Add("STOCK:SQLTask"); // Get the task host wrapper TaskHost taskHost = package.Executables[0] as TaskHost; // Get the task object ExecuteSQLTask task = taskHost.InnerObject as ExecuteSQLTask; // Set core properties task.Connection = sqlConnection.Name; task.SqlStatementSource = "SELECT id FROM sysobjects WHERE name = ?"; // Add variable to hold parameter value package.Variables.Add("Variable", false, "User", "sysrowsets"); // Add input parameter binding task.ParameterBindings.Add(); IDTSParameterBinding parameterBinding = task.ParameterBindings.GetBinding(0); parameterBinding.DtsVariableName = "User::Variable"; parameterBinding.ParameterDirection = ParameterDirections.Input; parameterBinding.DataType = (int)OleDBDataTypes.VARCHAR; parameterBinding.ParameterName = "0"; parameterBinding.ParameterSize = 255; For the full version of this code, see the CreatePackageParameterVariable method in the sample class. You’ll notice the data type has to be specified for the parameter IDTSParameterBinding .DataType Property, and these type codes are connection specific too. My enumeration I wrote several years ago is shown below was probably done by reverse engineering a package and also the API header file, but I recently found a very handy post that covers more connections as well for exactly this, Setting the DataType of IDTSParameterBinding objects (Execute SQL Task). /// <summary> /// Enumeration of OLE-DB types, used when mapping OLE-DB parameters. /// </summary> private enum OleDBDataTypes { BYTE = 0x11, CURRENCY = 6, DATE = 7, DB_VARNUMERIC = 0x8b, DBDATE = 0x85, DBTIME = 0x86, DBTIMESTAMP = 0x87, DECIMAL = 14, DOUBLE = 5, FILETIME = 0x40, FLOAT = 4, GUID = 0x48, LARGE_INTEGER = 20, LONG = 3, NULL = 1, NUMERIC = 0x83, NVARCHAR = 130, SHORT = 2, SIGNEDCHAR = 0x10, ULARGE_INTEGER = 0x15, ULONG = 0x13, USHORT = 0x12, VARCHAR = 0x81, VARIANT_BOOL = 11 } Download Sample code ExecSqlPackage.cs (10KB)

    Read the article

  • How do you Send More that 20 Parameters to a Stored Procedure Using ODP.Net?

    - by discwiz
    Switching from Microsofts Oracle Driver to ODP.NET version 10.2.0.100. After changing the data types to OracleDBTypes in a procedure, that worked perficetly using System.Data.OracleClient, the procedure fails if we try and pass in more that 20 parameters. The error returned is: ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'ADD_TARP_EVENT' ORA-06550: line 1, column 7: PL/SQL: Statement ignorede If we reduce the number of parameters to less than 20 it works. Is this a known issue? Thanks, Dave Here the code for creating the parameters: Shared Function CreateTarpEventCommand(ByVal aTarpEvent As TARPEventType) As OracleCommand Dim cmd As New OracleCommand With aTarpEvent cmd.Parameters.Add(New OracleParameter("I_facID_C", OracleDbType.Char)).Value = .FacilityShortName cmd.Parameters.Add(New OracleParameter("I_facName_VC", OracleDbType.Varchar2)).Value = .FacilityLongName cmd.Parameters.Add(New OracleParameter("I_client_VC", OracleDbType.Varchar2)).Value = .ComputerNameTarpIsRunningOn cmd.Parameters.Add(New OracleParameter("I_TARP_Version_VC", OracleDbType.Varchar2)).Value = .TarpVersionNumber cmd.Parameters.Add(New OracleParameter("I_NAS_Type_VC", OracleDbType.Varchar2)).Value = .FacilityNASSystemType cmd.Parameters.Add(New OracleParameter("I_Aircraft1_Callsign_VC", OracleDbType.Varchar2)).Value = .Aircraft1Callsign If .Aircraft1Type Is Nothing Then cmd.Parameters.Add(New OracleParameter("I_Aircraft1_Type_VC", OracleDbType.Varchar2)).Value = .Aircraft1Type End If If .Aircraft1Category Is Nothing Then cmd.Parameters.Add(New OracleParameter("I_Aircraft1_Cat_VC", OracleDbType.Varchar2)).Value = .Aircraft1Category End If cmd.Parameters.Add(New OracleParameter("I_Aircraft2_Callsign_VC", OracleDbType.Varchar2)).Value = .Aircraft2Callsign If .Aircraft2Type Is Nothing Then cmd.Parameters.Add(New OracleParameter("I_Aircraft2_Type_VC", OracleDbType.Varchar2)).Value = .Aircraft2Type End If If .Aircraft2Category Is Nothing Then cmd.Parameters.Add(New OracleParameter("I_Aircraft2_Cat_VC", OracleDbType.Varchar2)).Value = .Aircraft2Category End If If .SensorShortName Is Nothing Then cmd.Parameters.Add(New OracleParameter("I_Sensor_Name_VC", OracleDbType.Varchar2)).Value = .SensorShortName End If If .TarpConfigurationName Is Nothing Then cmd.Parameters.Add(New OracleParameter("I_TARP_Config_Name_VC", OracleDbType.Varchar2)).Value = .TarpConfigurationName End If If .EntryCreatorID Is Nothing Then cmd.Parameters.Add(New OracleParameter("I_Create_VC", OracleDbType.Varchar2)).Value = .EntryCreatorID End If If .LogAction Is Nothing Then cmd.Parameters.Add(New OracleParameter("I_Log_Action_VC", OracleDbType.Varchar2)).Value = .LogAction End If cmd.Parameters.Add(New OracleParameter("I_TARP_Mode_VC", OracleDbType.Varchar2)).Value = .TarpOperatingMode cmd.Parameters.Add(New OracleParameter("I_Min_Loss_N", OracleDbType.Decimal)).Value = .ClosestMeasureOfLoSS If .MapName Is Nothing Then cmd.Parameters.Add(New OracleParameter("I_MAP_NAME_VC", OracleDbType.Varchar2)).Value = .MapName End If If .TarpConfigurationFileHash Is Nothing Then cmd.Parameters.Add(New OracleParameter("I_CONFIG_HASH_VC", OracleDbType.Varchar2)).Value = .TarpConfigurationFileHash End If Dim aDate As OracleDate = CType(.LossEventsMessages(0).LossEventTime, System.DateTime) cmd.Parameters.Add(New OracleParameter("I_FIRST_LOSS_EVENT_DATE", OracleDbType.Date)).Value = aDate cmd.Parameters.Add(New OracleParameter("I_FIRST_LOSS_EVENT_MS_N", OracleDbType.Int32)).Value = .LossEventsMessages(0).LossEventMilliSeconds If .ZippedMapFiles Is Nothing Then cmd.Parameters.Add(New OracleParameter("I_Map_File_BL", OracleDbType.Blob)).Value = .ZippedMapFiles End If cmd.Parameters.Add(New OracleParameter("I_TARP_Package_BL", OracleDbType.Blob)).Value = .ZippedTarpPackageWithoutMaps cmd.Parameters.Add(New OracleParameter("rs_RESULTS", OracleDbType.RefCursor)).Direction = ParameterDirection.Output End With Return cmd End Function And here is the code for executing the procedure: Dim workingDataSet As New DataSet Dim oracleConnection As New OracleConnection Dim cmd As New OracleCommand Dim oracleDataAdapter As New OracleDataAdapter Try Using oracleConnection oracleConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("MasterConnectionODT") cmd = HelperDB.CreateTarpEventCommand(TarpEvent) cmd.Connection = oracleConnection cmd.CommandText = "LOADER.ADD_TARP_EVENT" cmd.CommandType = CommandType.StoredProcedure Using oracleConnection oracleConnection.Open() Dim aTransation As OracleTransaction = oracleConnection.BeginTransaction(IsolationLevel.ReadCommitted) Try Using oracleDataAdapter oracleDataAdapter = New OracleDataAdapter(cmd) oracleDataAdapter.TableMappings.Add("Results", "rs_Max") oracleDataAdapter.Fill(workingDataSet) ....

    Read the article

  • Dropdownlist and Datareader

    - by salvationishere
    After trying many solutions listed on the internet I am very confused now. I have a C#/SQL web application for which I am simply trying to bind an ExecuteReader command to a Dropdownlist so the user can select a value. This is a VS2008 project on an XP OS. How it works is after the user selects a table, I use this selection as an input parameter to a method from my Datamatch.aspx.cs file. Then this Datamatch.aspx.cs file calls a method from my ADONET.cs class file. Finally this method executes a SQL procedure to return the list of columns from that table. (These are all tables in Adventureworks DB). I know that this method returns successfully the list of columns if I execute this SP in SSMS. However, I'm not sure how to tell if it works in VS or not. This should be simple. How can I do this? Here is some of my code. The T-sQL stored proc: CREATE PROCEDURE [dbo].[getColumnNames] @TableName VarChar(50) AS BEGIN SET NOCOUNT ON; SELECT col.name 'COLUMN_NAME' FROM sysobjects obj INNER JOIN syscolumns col ON obj.id = col.id WHERE obj.name = @TableName END It gives me desired output when I execute following from SSMS: exec getColumnNames 'AddressType' And the code from Datamatch.aspx.cs file currently is: // Add DropDownList Control to Placeholder private void CreateDropDownLists() { SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable); int NumControls = targettable.Length; DropDownList ddl = new DropDownList(); } Where ADONET_methods.DisplayTableColumns(targettable) is: public static SqlDataReader DisplayTableColumns(string tt) { SqlDataReader dr = null; string TableName = tt; string connString = "Server=(local);Database=AdventureWorks;Integrated Security = SSPI"; string errorMsg; SqlConnection conn2 = new SqlConnection(connString); SqlCommand cmd = new SqlCommand("getColumnNames"); //conn2.CreateCommand(); try { cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn2; SqlParameter parm = new SqlParameter("@TableName", SqlDbType.VarChar); parm.Value = "Person." + TableName.Trim(); parm.Direction = ParameterDirection.Input; cmd.Parameters.Add(parm); conn2.Open(); dr = cmd.ExecuteReader(); } catch (Exception ex) { errorMsg = ex.Message; } return dr; }

    Read the article

  • ExecuteNonQuery on a stored proc causes it to be deleted

    - by FinancialRadDeveloper
    This is a strange one. I have a Dev SQL Server which has the stored proc on it, and the same stored proc when used with the same code on the UAT DB causes it to delete itself! Has anyone heard of this behaviour? SQL Code: -- Check if user is registered with the system IF OBJECT_ID('dbo.sp_is_valid_user') IS NOT NULL BEGIN DROP PROCEDURE dbo.sp_is_valid_user IF OBJECT_ID('dbo.sp_is_valid_user') IS NOT NULL PRINT '<<< FAILED DROPPING PROCEDURE dbo.sp_is_valid_user >>>' ELSE PRINT '<<< DROPPED PROCEDURE dbo.sp_is_valid_user >>>' END go create procedure dbo.sp_is_valid_user @username as varchar(20), @isvalid as int OUTPUT AS BEGIN declare @tmpuser as varchar(20) select @tmpuser = username from CPUserData where username = @username if @tmpuser = @username BEGIN select @isvalid = 1 END else BEGIN select @isvalid = 0 END END GO Usage example DECLARE @isvalid int exec dbo.sp_is_valid_user 'username', @isvalid OUTPUT SELECT valid = @isvalid The usage example work all day... when I access it via C# it deletes itself in the UAT SQL DB but not the Dev one!! C# Code: public bool IsValidUser(string sUsername, ref string sErrMsg) { string sDBConn = ConfigurationSettings.AppSettings["StoredProcDBConnection"]; SqlCommand sqlcmd = new SqlCommand(); SqlDataAdapter sqlAdapter = new SqlDataAdapter(); try { SqlConnection conn = new SqlConnection(sDBConn); sqlcmd.Connection = conn; conn.Open(); sqlcmd.CommandType = CommandType.StoredProcedure; sqlcmd.CommandText = "sp_is_valid_user"; // params to pass in sqlcmd.Parameters.AddWithValue("@username", sUsername); // param for checking success passed back out sqlcmd.Parameters.Add("@isvalid", SqlDbType.Int); sqlcmd.Parameters["@isvalid"].Direction = ParameterDirection.Output; sqlcmd.ExecuteNonQuery(); int nIsValid = (int)sqlcmd.Parameters["@isvalid"].Value; if (nIsValid == 1) { conn.Close(); sErrMsg = "User Valid"; return true; } else { conn.Close(); sErrMsg = "Username : " + sUsername + " not found."; return false; } } catch (Exception e) { sErrMsg = "Error :" + e.Source + " msg: " + e.Message; return false; } }

    Read the article

  • SQL Server 2008 Filestream Impersonation Access Denied error

    - by Adi
    I've been trying to upload a file to the database using SQL SERVER 2008 Filestream and Impersonation technique to save the file in the file system, but i keep getting Access Denied error; even though i've set the permissions for the impersonating user to the Filestream folder(C:\SQLFILESTREAM\Dev_DB). when i debugged the code, i found the server return a unc path(\Server_Name\MSSQLSERVER\v1\Dev_LMDB\dbo\FileData\File_Data\13C39AB1-8B91-4F5A-81A1-940B58504C17), which was not accessible through windows explorer. I've my web application hosted on local maching(Windows 7). SQL Server is located on a remote server(Windows Server 2008 R2). Sql authentication was used to call the stored procedure. Following is the code i've used to do the above operations. SqlCommand sqlCmd = new SqlCommand("AddFile"); sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Parameters.Add("@File_Name", SqlDbType.VarChar, 512).Value = filename; sqlCmd.Parameters.Add("@File_Type", SqlDbType.VarChar, 5).Value = Path.GetExtension(filename); sqlCmd.Parameters.Add("@Username", SqlDbType.VarChar, 20).Value = username; sqlCmd.Parameters.Add("@Output_File_Path", SqlDbType.VarChar, -1).Direction = ParameterDirection.Output; DAManager PDAM = new DAManager(DAManager.getConnectionString()); using (SqlConnection connection = (SqlConnection)PDAM.CreateConnection()) { connection.Open(); SqlTransaction transaction = connection.BeginTransaction(); WindowsImpersonationContext wImpersonationCtx; NetworkSecurity ns = null; try { PDAM.ExecuteNonQuery(sqlCmd, transaction); string filepath = sqlCmd.Parameters["@Output_File_Path"].Value.ToString(); sqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()"); sqlCmd.CommandType = CommandType.Text; byte[] Context = (byte[])PDAM.ExecuteScalar(sqlCmd, transaction); byte[] buffer = new byte[4096]; int bytedRead; ns = new NetworkSecurity(); wImpersonationCtx = ns.ImpersonateUser(IMP_Domain, IMP_Username, IMP_Password, LogonType.LOGON32_LOGON_INTERACTIVE, LogonProvider.LOGON32_PROVIDER_DEFAULT); SqlFileStream sfs = new SqlFileStream(filepath, Context, System.IO.FileAccess.Write); while ((bytedRead = inFS.Read(buffer, 0, buffer.Length)) != 0) { sfs.Write(buffer, 0, bytedRead); } sfs.Close(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); } finally { sqlCmd.Dispose(); connection.Close(); connection.Dispose(); ns.undoImpersonation(); wImpersonationCtx = null; ns = null; } } Can someone help me with this issue. Reference Exception: Type : System.ComponentModel.Win32Exception, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Message : Access is denied Source : System.Data Help link : NativeErrorCode : 5 ErrorCode : -2147467259 Data : System.Collections.ListDictionaryInternal TargetSite : Void OpenSqlFileStream(System.String, Byte[], System.IO.FileAccess, System.IO.FileOptions, Int64) Stack Trace : at System.Data.SqlTypes.SqlFileStream.OpenSqlFileStream(String path, Byte[] transactionContext, FileAccess access, FileOptions options, Int64 allocationSize) at System.Data.SqlTypes.SqlFileStream..ctor(String path, Byte[] transactionContext, FileAccess access, FileOptions options, Int64 allocationSize) at System.Data.SqlTypes.SqlFileStream..ctor(String path, Byte[] transactionContext, FileAccess access) Thanks

    Read the article

  • Stored procedure error when use computed column for ID

    - by Hari
    I got the error: Procedure or function usp_User_Info3 has too many arguments specified When I run the program. I don't know the error in SP or in C# code. I have to display the Vendor_ID after the user clicks the submit button. Where the thing going wrong here ? Table structure : CREATE TABLE User_Info3 ( SNo int Identity (2000,1) , Vendor_ID AS 'VEN' + CAST(SNo as varchar(16)) PERSISTED PRIMARY KEY, UserName VARCHAR(16) NOT NULL, User_Password VARCHAR(12) NOT NULL, User_ConPassword VARCHAR(12) NOT NULL, User_FirstName VARCHAR(25) NOT NULL, User_LastName VARCHAR(25) SPARSE NULL, User_Title VARCHAR(35) NOT NULL, User_EMail VARCHAR(35) NOT NULL, User_PhoneNo VARCHAR(14) NOT NULL, User_MobileNo VARCHAR(14)NOT NULL, User_FaxNo VARCHAR(14)NOT NULL, UserReg_Date DATE DEFAULT GETDATE() ) Stored Procedure : ALTER PROCEDURE [dbo].[usp_User_Info3] @SNo INT OUTPUT, @Vendor_ID VARCHAR(10) OUTPUT, @UserName VARCHAR(30), @User_Password VARCHAR(12), @User_ConPassword VARCHAR(12), @User_FirstName VARCHAR(25), @User_LastName VARCHAR(25), @User_Title VARCHAR(35), @User_OtherEmail VARCHAR(30), @User_PhoneNo VARCHAR(14), @User_MobileNo VARCHAR(14), @User_FaxNo VARCHAR(14) AS BEGIN SET NOCOUNT ON; INSERT INTO User_Info3 (UserName,User_Password,User_ConPassword,User_FirstName, User_LastName,User_Title,User_OtherEmail,User_PhoneNo,User_MobileNo,User_FaxNo) VALUES (@UserName,@User_Password,@User_ConPassword,@User_FirstName,@User_LastName, @User_Title,@User_OtherEmail,@User_PhoneNo,@User_MobileNo,@User_FaxNo) SET @SNo = Scope_Identity() SELECT Vendor_ID From User_Info3 WHERE SNo = @SNo END C# Code : protected void BtnUserNext_Click(object sender, EventArgs e) { cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "usp_User_Info3"; System.Data.SqlClient.SqlParameter SNo=cmd.Parameters.Add("@SNo",System.Data.SqlDbType.Int); System.Data.SqlClient.SqlParameter Vendor_ID=cmd.Parameters.Add("@Vendor_ID", System.Data.SqlDbType.VarChar,10); cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = txtUserName.Text; cmd.Parameters.Add("@User_Password", SqlDbType.VarChar).Value = txtRegPassword.Text; cmd.Parameters.Add("@User_ConPassword", SqlDbType.VarChar).Value = txtRegConPassword.Text; cmd.Parameters.Add("@User_FirstName", SqlDbType.VarChar).Value = txtRegFName.Text; cmd.Parameters.Add("@User_LastName", SqlDbType.VarChar).Value = txtRegLName.Text; cmd.Parameters.Add("@User_Title", SqlDbType.VarChar).Value = txtRegTitle.Text; cmd.Parameters.Add("@User_OtherEmail", SqlDbType.VarChar).Value = txtOtherEmail.Text; cmd.Parameters.Add("@User_PhoneNo", SqlDbType.VarChar).Value =txtRegTelephone.Text; cmd.Parameters.Add("@User_MobileNo", SqlDbType.VarChar).Value =txtRegMobile.Text; cmd.Parameters.Add("@User_FaxNo", SqlDbType.VarChar).Value =txtRegFax.Text; cmd.Connection = SqlCon; try { Vendor_ID.Direction = System.Data.ParameterDirection.Output; SqlCon.Open(); cmd.ExecuteNonQuery(); string VendorID = cmd.ExecuteScalar() as string; } catch (Exception ex) { throw new Exception(ex.Message); } finally { string url = "../CompanyBasicInfo.aspx?Parameter=" + Server.UrlEncode(" + VendorID + "); SqlCon.Close(); } }

    Read the article

  • SQL Invalid Object Name 'AddressType'

    - by salvationishere
    I am getting the above error in my VS 2008 C# method when I try to invoke the SQL getColumnNames stored procedure from VS. This SP accepts one input parameter, the table name, and works successfully from SSMS. Currently I am selecting the AdventureWorks AddressType table for it to pull the column names from this table. I can see teh AdventureWorks table available in VS from my Server Explorer / Data Connection. And I see both the AddressType table and getColumnNames SP showing in Server Explorer. But I am still getting this error listed above. Here is the C# code snippet I use to execute this: public static DataTable DisplayTableColumns(string tt) { SqlDataReader dr = null; string TableName = tt; string connString = "Data Source=.;AttachDbFilename=\"C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\AdventureWorks_Data.mdf\";Initial Catalog=AdventureWorks;Integrated Security=True;Connect Timeout=30;User Instance=False"; string errorMsg; SqlConnection conn2 = new SqlConnection(connString); SqlCommand cmd = conn2.CreateCommand(); try { cmd.CommandText = "dbo.getColumnNames"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn2; SqlParameter parm = new SqlParameter("@TableName", SqlDbType.VarChar); parm.Value = TableName; parm.Direction = ParameterDirection.Input; cmd.Parameters.Add(parm); conn2.Open(); dr = cmd.ExecuteReader(); } catch (Exception ex) { errorMsg = ex.Message; } And when I examine the errorMsg it says the following: " at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)\r\n at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)\r\n at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)\r\n at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)\r\n at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()\r\n at System.Data.SqlClient.SqlDataReader.get_MetaData()\r\n at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)\r\n at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)\r\n at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)\r\n at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)\r\n at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)\r\n at System.Data.SqlClient.SqlCommand.ExecuteReader()\r\n at ADONET_namespace.ADONET_methods.DisplayTableColumns(String tt) in C:\Documents and Settings\Admin\My Documents\Visual Studio 2008\Projects\AddFileToSQL\AddFileToSQL\ADONET methods.cs:line 35" Where line 35 is dr = cmd.ExecuteReader();

    Read the article

< Previous Page | 1 2 3  | Next Page >