Search Results

Search found 484 results on 20 pages for 'sqlcommand'.

Page 12/20 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • MSSQL: How to copy a file (pdf, doc, txt...) stored in a varbinary(max) field to a file in a CLR sto

    - by user193655
    I ask this question as a followup of this question. A solution that uses bcp and xp_cmdshell, that is not my desired solution, has been posted here: stackoverflow.com/questions/828749/ms-sql-server-2005-write-varbinary-to-file-system (sorry i cannot post a second hyperlink since my reputation is les than 10). I am new to c# (since I am a Delphi developer) anyway I was able to create a simple CLR stored procedures by following a tutorial. My task is to move a file from the client file system to the server file system (the server can be accessed using remote IP, so I cannot use a shared folder as destination, this is why I need a CLR stored procedure). So I plan to: 1) store from Delphi the file in a varbinary(max) column of a temporary table 2) call the CLR stored procedure to create a file at the desired path using the data contained in the varbinary(max) field Imagine I need to move C:\MyFile.pdf to Z:\MyFile.pdf, where C: is a harddrive on local system and Z: is an harddrive on the server. I provide the code below (not working) that someone can modify to make it work? Here I suppose to have a table called MyTable with two fields: ID (int) and DATA (varbinary(max)). Please note it doesn't make a difference if the table is a real temporary table or just a table where I temporarly store the data. I would appreciate if some exception handling code is there (so that I can manage an "impossible to save file" exception). I would like to be able to write a new file or overwrite the file if already existing. [Microsoft.SqlServer.Server.SqlProcedure] public static void VarbinaryToFile(int TableId) { using (SqlConnection connection = new SqlConnection("context connection=true")) { connection.Open(); SqlCommand command = new SqlCommand("select data from mytable where ID = @TableId", connection); command.Parameters.AddWithValue("@TableId", TableId); // This was the sample code I found to run a query //SqlContext.Pipe.ExecuteAndSend(command); // instead I need something like this (THIS IS META_SYNTAX!!!): SqlContext.Pipe.ResultAsStream.SaveToFile('z:\MyFile.pdf'); } } (one subquestion is: is this approach coorect or there is a way to directly pass the data to the CLR stored procedure so I don't need to use a temp table?) If the subquestion's answer is No, could you describe the approach of avoiding a temp table? So is there a better way then the one I describe above (=temp table + Stored procedure)? A way to directly pass the dataastream from the client application to the CLR stored procedure? (my files can be any size but also very big)

    Read the article

  • export to excel from vb.net from sql datareader

    - by reffer
    I have an sql query with sql datareader. i put a for loop for the data reader. now when the data starts coming in from the query i want it to export to excel in the for loop. here's my code Try Dim SqlStr As String = "", dr As SqlDataReader = Nothing ConnectDB(Cnn) Str = "query" SqlCmd = New SqlCommand(Str, Cnn) dr = SqlCmd.ExecuteReader while dr.read ..EXPORT TO EXCEL do end while does anyone know how to do this?

    Read the article

  • i don't solve "must declare a body because it is not marked abstract, extern, or partial" problem?

    - by programmerist
    How can i solve "must declare a body because it is not marked abstract, extern, or partial". This problem. Can you show me some advices? Full Error message is about Save, Update, Delete, Select events... Full message sample : GenoTip.DAL._AccessorForSQL.Save(string, System.Collections.Specialized.ListDictionary, System.Data.CommandType)' must declare a body because it is not marked abstract, extern, or partial This error also return in Update, Delete, Select... public abstract class _AccessorForSQL { public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType); public virtual bool Update(); public virtual bool Delete(); public virtual DataSet Select(); } class GenAccessor : _AccessorForSQL { DataSet ds; DataTable dt; public override bool Save(string sp, ListDictionary ld, CommandType cmdType) { SqlConnection con = null; SqlCommand cmd = null; SqlDataReader dr = null; try { con = GetConnection(); cmd = new SqlCommand(sp, con); con.Open(); cmd.CommandType = cmdType; foreach (string ky in ld.Keys) { cmd.Parameters.AddWithValue(ky, ld[ky]); } dr = cmd.ExecuteReader(); ds = new DataSet(); dt = new DataTable(); ds.Tables.Add(dt); ds.Load(dr, LoadOption.OverwriteChanges, dt); } catch (Exception exp) { HttpContext.Current.Trace.Warn("Error in GetCustomerByID()", exp.Message, exp); } finally { if (dr != null) dr.Close(); if (con != null) con.Close(); } return (ds.Tables[0].Rows.Count 0) ? true : false; } public override bool Update() { return true; } public override bool Delete() { return true; } public override DataSet Select() { DataSet dst = new DataSet(); return dst; } private static SqlConnection GetConnection() { string connStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); return conn; }

    Read the article

  • SQL Command Result to Dictionary C# .NET 2.0

    - by Joel
    I have a simple SQL query (using SqlCommand, SqlTransaction) in .NET 2.0 that returns a table of integer-string pairs (ID, Name). I want to get this data into a dictionary like Dictionary. I can get the result into a DataTable, but even iterating over it, I'm not sure how to do the typing and all that stuff. I feel like this must be a common problem but I haven't found any good solutions. Thanks in advance.

    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

  • Why are there connections open to my databases?

    - by Everett
    I have a program that stores user projects as databases. Naturally, the program should allow the user to create and delete the databases as they need to. When the program boots up, it looks for all the databases in a specific SQLServer instance that have the structure the program is expecting. These database are then loaded into a listbox so the user can pick one to open as a project to work on. When I try to delete a database from the program, I always get an SQL error saying that the database is currently open and the operation fails. I've determined that the code that checks for the databases to load is causing the problem. I'm not sure why though, because I'm quite sure that all the connections are being properly closed. Here are all the relevant functions. After calling BuildProjectList, running "DROP DATABASE database_name" from ExecuteSQL fails with the message: "Cannot drop database because it is currently in use". I'm using SQLServer 2005. private SqlConnection databaseConnection; private string connectionString; private ArrayList databases; public ArrayList BuildProjectList() { //databases is an ArrayList of all the databases in an instance if (databases.Count <= 0) { return null; } ArrayList databaseNames = new ArrayList(); for (int i = 0; i < databases.Count; i++) { string db = databases[i].ToString(); connectionString = "Server=localhost\\SQLExpress;Trusted_Connection=True;Database=" + db + ";"; //Check if the database has the table required for the project string sql = "select * from TableExpectedToExist"; if (ExecuteSQL(sql)) { databaseNames.Add(db); } } return databaseNames; } private bool ExecuteSQL(string sql) { bool success = false; openConnection(); SqlCommand cmd = new SqlCommand(sql, databaseConnection); try { cmd.ExecuteNonQuery(); success = true; } catch (SqlException ae) { MessageBox.Show(ae.Message.ToString()); } closeConnection(); return success; } public void openConnection() { databaseConnection = new SqlConnection(connectionString); try { databaseConnection.Open(); } catch(Exception e) { MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void closeConnection() { if (databaseConnection != null) { try { databaseConnection.Close(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }

    Read the article

  • VBNet2008 Transfer DATAREADER rows to CrystalReport DataSet1.xsd

    - by lennie
    Hi Good Guys, I need your help. Please help me as I am a newbie using VB.NET. I have been asked to transfer DATAREADER rows into Crystal Report DATASET1.XSD Here are the coding Private Sub BtnTransfer() dim strsql as string = "Select OrderID, OrderDate from ORDERS" dim DS as new dataset1 '<---crysal report dataset1.xsd dim DR as SqlDataReader dim RW as DataRow = DS.Tables(0).NewRow sqlconn = new sqlconnection(ConnString) sqlcmd = new sqlCommand(strSql, sqlconn) sqlcmd.Connection.open() DR = sqlcmd.ExecuteReader(CommandBehaviour.CloseConnection) Do while DR.READ RW("OrderID") = DR("OrderID") RW("OrderDate") = DR(OrderDate") DS.Tables(0).Rows.ADD(RW) Loop End sub

    Read the article

  • Transfer DataReader rows to a CrystalReport DataSet

    - by lennie
    Please help me as I am a newbie using VB.NET. I have been asked to transfer rows from a DataReader into a Crystal Report dataset. Here are the coding: Private Sub BtnTransfer() dim strsql as string = "Select OrderID, OrderDate from ORDERS" dim DS as new dataset1 '<---crysal report dataset1.xsd dim DR as SqlDataReader dim RW as DataRow = DS.Tables(0).NewRow sqlconn = new sqlconnection(ConnString) sqlcmd = new sqlCommand(strSql, sqlconn) sqlcmd.Connection.open() DR = sqlcmd.ExecuteReader(CommandBehaviour.CloseConnection) Do while DR.Read RW("OrderID") = DR("OrderID") RW("OrderDate") = DR(OrderDate") DS.Tables(0).Rows.ADD(RW) Loop End sub

    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

  • Error: No mapping exists from object type....

    - by jakesankey
    Here is the code for my simple parsing application. I am getting an error that states 'No mapping exists from type System.Text.RegularExpressions.Match to a known managed provider native type'. This started to occur when I switched from using Split('_') to RegEx.Match for defining RNumberE, RNumberD, etc. Any guidance is appreciated. using System; using System.Data; using System.Data.SQLite; using System.IO; using System.Text.RegularExpressions; using System.Threading; using System.Collections.Generic; using System.Linq; using System.Data.SqlClient; namespace JohnDeereCMMDataParser { internal class Program { public static List<string> GetImportedFileList() { List<string> ImportedFiles = new List<string>(); using (SqlConnection connect = new SqlConnection(@"Server=FRXSQLDEV;Database=RX_CMMData;Integrated Security=YES")) { connect.Open(); using (SqlCommand fmd = connect.CreateCommand()) { fmd.CommandText = @"SELECT FileName FROM CMMData;"; fmd.CommandType = CommandType.Text; SqlDataReader r = fmd.ExecuteReader(); while (r.Read()) { ImportedFiles.Add(Convert.ToString(r["FileName"])); } } } return ImportedFiles; } private static void Main(string[] args) { Console.Title = "John Deere CMM Data Parser"; Console.WriteLine("Preparing CMM Data Parser... done"); Console.WriteLine("Scanning for new CMM data..."); Console.ForegroundColor = ConsoleColor.Gray; using (SqlConnection con = new SqlConnection(@"Server=FRXSQLDEV;Database=RX_CMMData;Integrated Security=YES")) { con.Open(); using (SqlCommand insertCommand = con.CreateCommand()) { Console.WriteLine("Connecting to SQL server..."); SqlCommand cmdd = con.CreateCommand(); string[] files = Directory.GetFiles(@"C:\Documents and Settings\js91162\Desktop\CMM WENZEL\", "*_*_*.txt", SearchOption.AllDirectories); List<string> ImportedFiles = GetImportedFileList(); insertCommand.Parameters.Add(new SqlParameter("@FeatType", DbType.String)); insertCommand.Parameters.Add(new SqlParameter("@FeatName", DbType.String)); insertCommand.Parameters.Add(new SqlParameter("@Axis", DbType.String)); insertCommand.Parameters.Add(new SqlParameter("@Actual", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@Nominal", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@Dev", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@TolMin", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@TolPlus", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@OutOfTol", DbType.Decimal)); foreach (string file in files.Except(ImportedFiles)) { var FileNameExt1 = Path.GetFileName(file); cmdd.Parameters.Clear(); cmdd.Parameters.Add(new SqlParameter("@FileExt", FileNameExt1)); cmdd.CommandText = @" IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RX_CMMData' AND TABLE_NAME = 'CMMData')) BEGIN SELECT COUNT(*) FROM CMMData WHERE FileName = @FileExt; END"; int count = Convert.ToInt32(cmdd.ExecuteScalar()); con.Close(); con.Open(); if (count == 0) { Console.WriteLine("Preparing to parse CMM data for SQL import..."); if (file.Count(c => c == '_') > 5) continue; insertCommand.CommandText = @" INSERT INTO CMMData (FeatType, FeatName, Axis, Actual, Nominal, Dev, TolMin, TolPlus, OutOfTol, PartNumber, CMMNumber, Date, FileName) VALUES (@FeatType, @FeatName, @Axis, @Actual, @Nominal, @Dev, @TolMin, @TolPlus, @OutOfTol, @PartNumber, @CMMNumber, @Date, @FileName);"; string FileNameExt = Path.GetFullPath(file); string RNumber = Path.GetFileNameWithoutExtension(file); int index2 = RNumber.IndexOf("~"); Match RNumberE = Regex.Match(RNumber, @"^(R|L)\d{6}(COMP|CRIT|TEST|SU[1-9])(?=_)", RegexOptions.IgnoreCase); Match RNumberD = Regex.Match(RNumber, @"(?<=_)\d{3}[A-Z]\d{4}|\d{3}[A-Z]\d\w\w\d(?=_)", RegexOptions.IgnoreCase); Match RNumberDate = Regex.Match(RNumber, @"(?<=_)\d{8}(?=_)", RegexOptions.IgnoreCase); if (RNumberD.Value == @"") continue; if (RNumberE.Value == @"") continue; if (RNumberDate.Value == @"") continue; if (index2 != -1) continue; /* string RNumberE = RNumber.Split('_')[0]; string RNumberD = RNumber.Split('_')[1]; string RNumberDate = RNumber.Split('_')[2]; */ DateTime dateTime = DateTime.ParseExact(RNumberDate.Value, "yyyyMMdd", Thread.CurrentThread.CurrentCulture); string cmmDate = dateTime.ToString("dd-MMM-yyyy"); string[] lines = File.ReadAllLines(file); bool parse = false; foreach (string tmpLine in lines) { string line = tmpLine.Trim(); if (!parse && line.StartsWith("Feat. Type,")) { parse = true; continue; } if (!parse || string.IsNullOrEmpty(line)) { continue; } Console.WriteLine(tmpLine); foreach (SqlParameter parameter in insertCommand.Parameters) { parameter.Value = null; } string[] values = line.Split(new[] { ',' }); for (int i = 0; i < values.Length - 1; i++) { SqlParameter param = insertCommand.Parameters[i]; if (param.DbType == DbType.Decimal) { decimal value; param.Value = decimal.TryParse(values[i], out value) ? value : 0; } else { param.Value = values[i]; } } insertCommand.Parameters.Add(new SqlParameter("@PartNumber", RNumberE)); insertCommand.Parameters.Add(new SqlParameter("@CMMNumber", RNumberD)); insertCommand.Parameters.Add(new SqlParameter("@Date", cmmDate)); insertCommand.Parameters.Add(new SqlParameter("@FileName", FileNameExt)); insertCommand.ExecuteNonQuery(); insertCommand.Parameters.RemoveAt("@PartNumber"); insertCommand.Parameters.RemoveAt("@CMMNumber"); insertCommand.Parameters.RemoveAt("@Date"); insertCommand.Parameters.RemoveAt("@FileName"); } } } Console.WriteLine("CMM data successfully imported to SQL database..."); } con.Close(); } } } }

    Read the article

  • Possible uncommitted transactions causing "System.Data.SqlClient.SqlException: Timeout expired" erro

    - by Michael
    My application requires a user to log in and allows them to edit a list of things. However, it seems that if the same user always logs in and out and edits the list, this user will run into a "System.Data.SqlClient.SqlException: Timeout expired." error. I've read comments about increasing the timeout period but I've also read a comment about it possibly caused by uncommitted transactions. And I do have one going in the application. I'll provide the code I'm working with and there is an IF statement in there that I was a little iffy about but it seemed like a reasonable thing to do. I'll just go over what's going on here, there is a list of objects to update or add into the database. New objects created in the application are given an ID of 0 while existing objects have their own ID's generated from the DB. If the user chooses to delete some objects, their IDs are stored in a separate list of Integers. Once the user is ready to save their changes, the two lists are passed into this method. By use of the IF statement, objects with ID of 0 are added (using the Add stored procedure) and those objects with non-zero IDs are updated (using the Update stored procedure). After all this, a FOR loop goes through all the integers in the "removal" list and uses the Delete stored procedure to remove them. A transaction is used for all this. Public Shared Sub UpdateSomethings(ByVal SomethingList As List(Of Something), ByVal RemovalList As List(Of Integer)) Using DBConnection As New SqlConnection(conn) DBConnection.Open() Dim MyTransaction As SqlTransaction MyTransaction = DBConnection.BeginTransaction() Try For Each SomethingItem As Something In SomethingList Using MyCommand As New SqlCommand() MyCommand.Connection = DBConnection If SomethingItem.ID > 0 Then MyCommand.CommandText = "UpdateSomething" Else MyCommand.CommandText = "AddSomething" End If MyCommand.Transaction = MyTransaction MyCommand.CommandType = CommandType.StoredProcedure With MyCommand.Parameters If MyCommand.CommandText = "UpdateSomething" Then .Add("@id", SqlDbType.Int).Value = SomethingItem.ID End If .Add("@stuff", SqlDbType.Varchar).Value = SomethingItem.Stuff End With MyCommand.ExecuteNonQuery() End Using Next For Each ID As Integer In RemovalList Using MyCommand As New SqlCommand("DeleteSomething", DBConnection) MyCommand.Transaction = MyTransaction MyCommand.CommandType = CommandType.StoredProcedure With MyCommand.Parameters .Add("@id", SqlDbType.Int).Value = ID End With MyCommand.ExecuteNonQuery() End Using Next MyTransaction.Commit() Catch ex As Exception MyTransaction.Rollback() 'Exception handling goes here End Try End Using End Sub There are three stored procedures used here as well as some looping so I can see how something can be holding everything up if the list is large enough. Other users can log in to the system at the same time just fine though. I'm using Visual Studio 2008 to debug and am using SQL Server 2000 for the DB.

    Read the article

  • Am I Leaking ADO.NET Connections?

    - by HardCode
    Here is an example of my code in a DAL. All calls to the database's Stored Procedures are structured this way, and there is no in-line SQL. Friend Shared Function Save(ByVal s As MyClass) As Boolean Dim cn As SqlClient.SqlConnection = Dal.Connections.MyAppConnection Dim cmd As New SqlClient.SqlCommand Try cmd.Connection = cn cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = "proc_save_my_class" cmd.Parameters.AddWithValue("@param1", s.Foo) cmd.Parameters.AddWithValue("@param2", s.Bar) Return True Finally Dal.Utility.CleanupAdoObjects(cmd, cn) End Try End Function Here is the Connection factory (if I am using the correct term): Friend Shared Function MyAppConnection() As SqlClient.SqlConnection Dim cn As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ToString) cn.Open() If cn.State <> ConnectionState.Open Then ' CriticalException is a custom object inheriting from Exception. Throw New CriticalException("Could not connect to the database.") Else Return cn End If End Function Here is the Dal.Utility.CleaupAdoObjects() function: Friend Shared Sub CleanupAdoObjects(ByVal cmd As SqlCommand, ByVal cn As SqlConnection) If cmd IsNot Nothing Then cmd.Dispose() If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then cn.Close() End Sub I am getting a lot of "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding." error messages reported by the users. The application's DAL opens a connection, reads or saves data, and closes it. No connections are ever left open - intentionally! There is nothing obvious on the Windows 2000 Server hosting the SQL Server 2000 that would indicate a problem. Nothing in the Event Logs and nothing in the SQL Server logs. The timeouts happen randomly - I cannot reproduce. It happens early in the day with only 1 to 5 users in the system. It also happens with around 50 users in the system. The most connections to SQL Server via Performance Monitor, for all databases, has been about 74. The timeouts happen in code that both saves to, and reads from, the database in different parts of the application. The stack trace does not point to one or two offending DAL functions. It's happened in many different places. Does my ADO.NET code appear to be able to leak connections? I've goolged around a bit, and I've read that if the connection pool fills up, this can happen. However, I'm not explicitly setting any connection pooling. I've even tried to increase the Connection Timeout in the connection string, but timeouts happen long before the 300 second (5 minute) value: <add name="MyConnectionString" connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=SSPI;Connection Timeout=300;"/> I'm at a total loss already as to what is causing these Timeout issues. Any ideas are appreciated.

    Read the article

  • How to call base abstract or interface from DAL into BLL?

    - by programmerist
    How can i access abstract class in BLL ? i shouldn't see GenAccessor in BLL it must be private class GenAccessor . i should access Save method over _AccessorForSQL. ok? MY BLL cs: public class AccessorForSQL: GenoTip.DAL._AccessorForSQL { public bool Save(string Name, string SurName, string Adress) { ListDictionary ld = new ListDictionary(); ld.Add("@Name", Name); ld.Add("@SurName", SurName); ld.Add("@Adress", Adress); return **base.Save("sp_InsertCustomers", ld, CommandType.StoredProcedure);** } } i can not access base.Save....???????? it is my DAL Layer: namespace GenoTip.DAL { public abstract class _AccessorForSQL { public abstract bool Save(string sp, ListDictionary ld, CommandType cmdType); public abstract bool Update(); public abstract bool Delete(); public abstract DataSet Select(); } private class GenAccessor : _AccessorForSQL { DataSet ds; DataTable dt; public override bool Save(string sp, ListDictionary ld, CommandType cmdType) { SqlConnection con = null; SqlCommand cmd = null; SqlDataReader dr = null; try { con = GetConnection(); cmd = new SqlCommand(sp, con); con.Open(); cmd.CommandType = cmdType; foreach (string ky in ld.Keys) { cmd.Parameters.AddWithValue(ky, ld[ky]); } dr = cmd.ExecuteReader(); ds = new DataSet(); dt = new DataTable(); ds.Tables.Add(dt); ds.Load(dr, LoadOption.OverwriteChanges, dt); } catch (Exception exp) { HttpContext.Current.Trace.Warn("Error in GetCustomerByID()", exp.Message, exp); } finally { if (dr != null) dr.Close(); if (con != null) con.Close(); } return (ds.Tables[0].Rows.Count 0) ? true : false; } public override bool Update() { return true; } public override bool Delete() { return true; } public override DataSet Select() { DataSet dst = new DataSet(); return dst; } private static SqlConnection GetConnection() { string connStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); return conn; }

    Read the article

  • Executing Stored Procedure for each InputRow + SSIS Script Component.

    - by Nev_Rahd
    Hello, In my Script Component, am trying to execute Stored Procedure = which return multiple rows = of which need to generate output rows. Code as below: /* Microsoft SQL Server Integration Services Script Component * Write scripts using Microsoft Visual C# 2008. * ScriptMain is the entry point class of the script.*/ using System; using System.Data; using System.Data.SqlClient; using Microsoft.SqlServer.Dts.Pipeline.Wrapper; using Microsoft.SqlServer.Dts.Runtime.Wrapper; [Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute] public class ScriptMain : UserComponent { SqlConnection cnn = new SqlConnection(); IDTSConnectionManager100 cnManager; //string cmd; SqlCommand cmd = new SqlCommand(); public override void AcquireConnections(object Transaction) { cnManager = base.Connections.myConnection; cnn = (SqlConnection)cnManager.AcquireConnection(null); } public override void PreExecute() { base.PreExecute(); } public override void PostExecute() { base.PostExecute(); } public override void InputRows_ProcessInputRow(InputRowsBuffer Row) { while(Row.NextRow()) { DataTable dt = new DataTable(); cmd.Connection = cnn; cmd.CommandText = "OSPATTRIBUTE_GetOPNforOP"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@NK", SqlDbType.VarChar).Value = Row.OPNK.ToString(); cmd.Parameters.Add("@EDWSTARTDATE", SqlDbType.DateTime).Value = Row.EDWEFFECTIVESTARTDATETIME; SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(dt); foreach (DataRow dtrow in dt.Rows) { OutputValidBuffer.AddRow(); OutputValidBuffer.OPNK = Row.OPNK; OutputValidBuffer.OSPTYPECODE = Row.OSPTYPECODE; OutputValidBuffer.ORGPROVTYPEDESC = Row.ORGPROVTYPEDESC; OutputValidBuffer.HEALTHSECTORCODE = Row.HEALTHSECTORCODE; OutputValidBuffer.HEALTHSECTORDESCRIPTION = Row.HEALTHSECTORDESCRIPTION; OutputValidBuffer.EDWEFFECTIVESTARTDATETIME = Row.EDWEFFECTIVESTARTDATETIME; OutputValidBuffer.EDWEFFECTIVEENDDATETIME = Row.EDWEFFECTIVEENDDATETIME; OutputValidBuffer.OPQI = Row.OPQI; OutputValidBuffer.OPNNK = dtrow[0].ToString(); OutputValidBuffer.OSPNAMETYPECODE = dtrow[1].ToString(); OutputValidBuffer.NAMETYPEDESC = dtrow[2].ToString(); OutputValidBuffer.OSPNAME = dtrow[3].ToString(); OutputValidBuffer.EDWEFFECTIVESTARTDATETIME1 = Row.EDWEFFECTIVESTARTDATETIME; OutputValidBuffer.EDWEFFECTIVEENDDATETIME1 = Row.EDWEFFECTIVEENDDATETIME; OutputValidBuffer.OPNQI = dtrow[6].ToString(); } } } public override void ReleaseConnections() { cnManager.ReleaseConnection(cnn); } } This is always skipping the first row. while(Row.NextRow()) is always bringing the second row of the input buffer. What am I doing wrong. Thanks

    Read the article

  • ASP.net Repeater Control Problem (nothing outputted)

    - by Phil
    I have the following db code in my usercontrol (content.ascx.vb): If did = 0 Then s = "select etc (statement works on server)" x = New SqlCommand(s, c) x.Parameters.Add("@contentid", Data.SqlDbType.Int) x.Parameters("@contentid").Value = contentid c.Open() r = x.ExecuteReader If r.HasRows Then Contactinforepeater.DataSource = r End If c.Close() r.Close() Else s = "select etc (statement works on server)" x = New SqlCommand(s, c) x.Parameters.Add("@contentid", SqlDbType.Int) x.Parameters("@contentid").Value = contentid x.Parameters.Add("@did", SqlDbType.Int) x.Parameters("@did").Value = did c.Open() r = x.ExecuteReader If r.HasRows Then Contactinforepeater.DataSource = r c.Close() r.Close() End If End If Then I have the following repeater control markup in my usercontrol (content.ascx): <asp:Repeater ID="Contactinforepeater" runat="server"> <HeaderTemplate> <h1>Contact Information</h1> </HeaderTemplate> <ItemTemplate> <table width="50%"> <tr> <td colspan="2"><%#Container.DataItem("position")%></td> </tr> <tr> <td>Name:</td> <td><%#Container.DataItem("surname")%></td> </tr> <tr> <td>Telephone:</td> <td><%#Container.DataItem("telephone")%></td> </tr> <tr> <td>Fax:</td> <td><%#Container.DataItem("fax")%></td> </tr> <tr> <td>Email:</td> <td><%#Container.DataItem("email")%></td> </tr> </table> </ItemTemplate> <SeparatorTemplate><br /><hr /><br /></SeparatorTemplate> </asp:Repeater> When I insert this usercontrol into default.aspx with this code: <%@ Register src="Modules/Content.ascx" tagname="Content" tagprefix="uc1" %> and <form id="form1" runat="server"> <div> <uc1:Content ID="Content" runat="server" /> </div> </form> I do not get any error messages but the expected content from the database is not displayed. Can someone please show me the syntax to get this working or point out where I am going wrong? Thanks in advance!

    Read the article

  • ASP.net Repeater Control Problem (nothing outputted from datasource(sqldatareader))

    - by Phil
    I have the following code to get the repeaters' data in my usercontrol (content.ascx.vb): If did = 0 Then s = "select etc (statement works on server)" x = New SqlCommand(s, c) x.Parameters.Add("@contentid", Data.SqlDbType.Int) x.Parameters("@contentid").Value = contentid c.Open() r = x.ExecuteReader If r.HasRows Then Contactinforepeater.DataSource = r End If c.Close() r.Close() Else s = "select etc (statement works on server)" x = New SqlCommand(s, c) x.Parameters.Add("@contentid", SqlDbType.Int) x.Parameters("@contentid").Value = contentid x.Parameters.Add("@did", SqlDbType.Int) x.Parameters("@did").Value = did c.Open() r = x.ExecuteReader If r.HasRows Then Contactinforepeater.DataSource = r c.Close() r.Close() End If End If Then I have the following repeater control markup in my usercontrol (content.ascx): <asp:Repeater ID="Contactinforepeater" runat="server"> <HeaderTemplate> <h1>Contact Information</h1> </HeaderTemplate> <ItemTemplate> <table width="50%"> <tr> <td colspan="2"><%#Container.DataItem("position")%></td> </tr> <tr> <td>Name:</td> <td><%#Container.DataItem("surname")%></td> </tr> <tr> <td>Telephone:</td> <td><%#Container.DataItem("telephone")%></td> </tr> <tr> <td>Fax:</td> <td><%#Container.DataItem("fax")%></td> </tr> <tr> <td>Email:</td> <td><%#Container.DataItem("email")%></td> </tr> </table> </ItemTemplate> <SeparatorTemplate><br /><hr /><br /></SeparatorTemplate> </asp:Repeater> When I insert this usercontrol into default.aspx with this code: <%@ Register src="Modules/Content.ascx" tagname="Content" tagprefix="uc1" %> and <form id="form1" runat="server"> <div> <uc1:Content ID="Content" runat="server" /> </div> </form> I do not get any error messages but the expected content from the database is not displayed. Can someone please show me the syntax to get this working or point out where I am going wrong? Thanks in advance!

    Read the article

  • can we use both custom button and inbuilt button in datagridview

    - by Srikanth Mattihalli
    HI all, I am using Datagridview in asp.net. I have used custom buttons of up and down in the datagridview along with edit,delete and paging options. I am handling the up down buttons by raising events in rowcommand and the code is as below string command = e.CommandName; Response.Write(e.CommandArgument.ToString()); int index = Convert.ToInt32(e.CommandArgument.ToString()); int count = GridView1.Rows.Count; int keyValue = Convert.ToInt32(GridView1.Rows[index].Cells1.Text); string value = GridView1.Rows[index].Cells[4].Text; SqlConnection conn = new SqlConnection(SqlDataSource1.ConnectionString); SqlCommand cmd = new SqlCommand(); if (command == "up") { if (index > 0) { index = index - 1; int keyValue1 = Convert.ToInt32(GridView1.Rows[index].Cells[1].Text); string value1 = GridView1.Rows[index].Cells[4].Text; cmd.Connection = conn; cmd.CommandText = "UPDATE [category] SET [order_id] = '" + value + "' WHERE [category_id]=" + keyValue1 + ";UPDATE [category] SET [order_id] = '" + value1 + "' WHERE [category_id]=" + keyValue + ";"; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } } else if (command == "down") { if (index < count - 1) { index = index + 1; int keyValue1 = Convert.ToInt32(GridView1.Rows[index].Cells[1].Text); string value1 = GridView1.Rows[index].Cells[4].Text; cmd.Connection = conn; cmd.CommandText = "UPDATE [category] SET [order_id] = '" + value + "' WHERE [category_id]=" + keyValue1 + ";UPDATE [category] SET [order_id] = '" + value1 + "' WHERE [category_id]=" + keyValue + ";"; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } } Response.Redirect("Default.aspx"); Designer file " DeleteCommand="DELETE FROM [category] WHERE [category_id] = @category_id" InsertCommand="INSERT INTO [category] ([categoryname], [navigation_url], [order_id]) VALUES (@categoryname, @navigation_url, @order_id)" SelectCommand="SELECT * FROM [category] order by order_id" UpdateCommand="UPDATE [category] SET [categoryname] = @categoryname, [navigation_url] = @navigation_url, [order_id] = @order_id WHERE [category_id] = @category_id" After this my edit,delete and paging is not working bcoz of event conflicts. Can anyone plz help me on this, so that i will be able to use both custom buttons(up and down) and edit,delete and paging features.

    Read the article

  • SQL error - Cannot convert nvarchar to decimal

    - by jakesankey
    I have a C# application that simply parses all of the txt documents within a given network directory and imports the data to a SQL server db. Everything was cruising along just fine until about the 1800th file when it happend to have a few blanks in columns that are called out as DBType.Decimal (and the value is usually zero in the files, not blank). So I got this error, "cannot convert nvarchar to decimal". I am wondering how I could tell the app to simply skip the lines that have this issue?? Perhaps I could even just change the column type to varchar even tho values are numbers (what problems could this create?) Thanks for any help! using System; using System.Data; using System.Data.SQLite; using System.IO; using System.Text.RegularExpressions; using System.Threading; using System.Collections.Generic; using System.Linq; using System.Data.SqlClient; namespace JohnDeereCMMDataParser { internal class Program { public static List<string> GetImportedFileList() { List<string> ImportedFiles = new List<string>(); using (SqlConnection connect = new SqlConnection(@"Server=FRXSQLDEV;Database=RX_CMMData;Integrated Security=YES")) { connect.Open(); using (SqlCommand fmd = connect.CreateCommand()) { fmd.CommandText = @"SELECT FileName FROM CMMData;"; fmd.CommandType = CommandType.Text; SqlDataReader r = fmd.ExecuteReader(); while (r.Read()) { ImportedFiles.Add(Convert.ToString(r["FileName"])); } } } return ImportedFiles; } private static void Main(string[] args) { Console.Title = "John Deere CMM Data Parser"; Console.WriteLine("Preparing CMM Data Parser... done"); Console.WriteLine("Scanning for new CMM data..."); Console.ForegroundColor = ConsoleColor.Gray; using (SqlConnection con = new SqlConnection(@"Server=FRXSQLDEV;Database=RX_CMMData;Integrated Security=YES")) { con.Open(); using (SqlCommand insertCommand = con.CreateCommand()) { Console.WriteLine("Connecting to SQL server..."); SqlCommand cmdd = con.CreateCommand(); string[] files = Directory.GetFiles(@"C:\Documents and Settings\js91162\Desktop\CMM WENZEL\", "*_*_*.txt", SearchOption.AllDirectories); List<string> ImportedFiles = GetImportedFileList(); insertCommand.Parameters.Add(new SqlParameter("@FeatType", DbType.String)); insertCommand.Parameters.Add(new SqlParameter("@FeatName", DbType.String)); insertCommand.Parameters.Add(new SqlParameter("@Axis", DbType.String)); insertCommand.Parameters.Add(new SqlParameter("@Actual", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@Nominal", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@Dev", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@TolMin", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@TolPlus", DbType.Decimal)); insertCommand.Parameters.Add(new SqlParameter("@OutOfTol", DbType.Decimal)); foreach (string file in files.Except(ImportedFiles)) { var FileNameExt1 = Path.GetFileName(file); cmdd.Parameters.Clear(); cmdd.Parameters.Add(new SqlParameter("@FileExt", FileNameExt1)); cmdd.CommandText = @" IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RX_CMMData' AND TABLE_NAME = 'CMMData')) BEGIN SELECT COUNT(*) FROM CMMData WHERE FileName = @FileExt; END"; int count = Convert.ToInt32(cmdd.ExecuteScalar()); con.Close(); con.Open(); if (count == 0) { Console.WriteLine("Preparing to parse CMM data for SQL import..."); if (file.Count(c => c == '_') > 5) continue; insertCommand.CommandText = @" INSERT INTO CMMData (FeatType, FeatName, Axis, Actual, Nominal, Dev, TolMin, TolPlus, OutOfTol, PartNumber, CMMNumber, Date, FileName) VALUES (@FeatType, @FeatName, @Axis, @Actual, @Nominal, @Dev, @TolMin, @TolPlus, @OutOfTol, @PartNumber, @CMMNumber, @Date, @FileName);"; string FileNameExt = Path.GetFullPath(file); string RNumber = Path.GetFileNameWithoutExtension(file); int index2 = RNumber.IndexOf("~"); Match RNumberE = Regex.Match(RNumber, @"^(R|L)\d{6}(COMP|CRIT|TEST|SU[1-9])(?=_)", RegexOptions.IgnoreCase); Match RNumberD = Regex.Match(RNumber, @"(?<=_)\d{3}[A-Z]\d{4}|\d{3}[A-Z]\d\w\w\d(?=_)", RegexOptions.IgnoreCase); Match RNumberDate = Regex.Match(RNumber, @"(?<=_)\d{8}(?=_)", RegexOptions.IgnoreCase); string RNumE = Convert.ToString(RNumberE); string RNumD = Convert.ToString(RNumberD); if (RNumberD.Value == @"") continue; if (RNumberE.Value == @"") continue; if (RNumberDate.Value == @"") continue; if (index2 != -1) continue; DateTime dateTime = DateTime.ParseExact(RNumberDate.Value, "yyyyMMdd", Thread.CurrentThread.CurrentCulture); string cmmDate = dateTime.ToString("dd-MMM-yyyy"); string[] lines = File.ReadAllLines(file); bool parse = false; foreach (string tmpLine in lines) { string line = tmpLine.Trim(); if (!parse && line.StartsWith("Feat. Type,")) { parse = true; continue; } if (!parse || string.IsNullOrEmpty(line)) { continue; } Console.WriteLine(tmpLine); foreach (SqlParameter parameter in insertCommand.Parameters) { parameter.Value = null; } string[] values = line.Split(new[] { ',' }); for (int i = 0; i < values.Length - 1; i++) { if (i = "" || i = null) continue; SqlParameter param = insertCommand.Parameters[i]; if (param.DbType == DbType.Decimal) { decimal value; param.Value = decimal.TryParse(values[i], out value) ? value : 0; } else { param.Value = values[i]; } } insertCommand.Parameters.Add(new SqlParameter("@PartNumber", RNumE)); insertCommand.Parameters.Add(new SqlParameter("@CMMNumber", RNumD)); insertCommand.Parameters.Add(new SqlParameter("@Date", cmmDate)); insertCommand.Parameters.Add(new SqlParameter("@FileName", FileNameExt)); insertCommand.ExecuteNonQuery(); insertCommand.Parameters.RemoveAt("@PartNumber"); insertCommand.Parameters.RemoveAt("@CMMNumber"); insertCommand.Parameters.RemoveAt("@Date"); insertCommand.Parameters.RemoveAt("@FileName"); } } } Console.WriteLine("CMM data successfully imported to SQL database..."); } con.Close(); } } } }

    Read the article

  • Login function runs different between local and server

    - by quangnd
    Here is my check login function: protected bool checkLoginStatus(String email, String password) { bool loginStatus = false; bool status = false; try { Connector.openConn(); String str = "SELECT * FROM [User]"; SqlCommand cmd = new SqlCommand(str, Connector.conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "tblUser"); //check valid foreach (DataRow dr in ds.Tables[0].Rows) { if (email == dr["Email"].ToString() && password == Connector.base64Decode(dr["Password"].ToString())) { Session["login_status"] = true; Session["username"] = dr["Name"].ToString(); Session["userId"] = dr["UserId"].ToString(); status = true; break; } } } catch (Exception ex) { } finally { Connector.closeConn(); } return status; } And call it at my aspx page: String email = Login1.UserName.Trim(); String password = Login1.Password.Trim(); if (checkLoginStatus(email, password)) Response.Redirect(homeSite); else lblFailure.Text = "Invalid!"; I ran this page at localhost successful! When I published it to server, this function only can run if email and password correct! Other, error occured: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) I tried open SQL Server 2008 Configuration Manager and enable SQL Server Browser service (Logon as:NT Authority/Local Service) but it stills error. (note: here is connection string of openConn() at Localhost (run on SQLEXpress 2005) connectionString="Data Source=MYLAPTOP\SQLEXPRESS;Initial Catalog=Spider_Vcms;Integrated Security=True" /> ) At server (run on SQL Server Enterprise 2008) connectionString="Data Source=SVR;Initial Catalog=Spider_Vcms;User Id=abc;password=123456;" /> anyone have an answer for my problem :( thanks a lot!

    Read the article

  • Selecting one row when working with typed datasets.

    - by Wodzu
    I have a typed dataset in my project. I would like to populate a datatable with only one row instead of all rows. The selected row must be based on the primary key column. I know I could modify the designer code to achive this functionality however if I change the code in the designer I risk that this code will be deleted when I update my datased via designer in the future. So I wanted to alter the SelectCommand not in the designer but just before firing up MyTypedTableAdapter.Fill method. The strange thing is that the designer does not create a SelectCommand! It creates all other commands but not this one. If it would create SelectCommand I could alter it in this way: this.operatorzyTableAdapter.Adapter.SelectCommand.CommandText += " WHERE MyColumn = 1"; It is far from perfection but atleast I would not have to modify the designer's work. unfortunately as I said earlier the SelectCommand is not created. Instead designer creates something like this: [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] private void InitCommandCollection() { this._commandCollection = new global::System.Data.SqlClient.SqlCommand[1]; this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand(); this._commandCollection[0].Connection = this.Connection; this._commandCollection[0].CommandText = "SELECT Ope_OpeID, Ope_Kod, Ope_Haslo, Ope_Imie, Ope_Nazwisko FROM dbo.Operatorzy"; this._commandCollection[0].CommandType = global::System.Data.CommandType.Text; } It doesn't make sense in my opinion. Why to create UpdateCommand, InsertCommand and DeleteCommand but do not create SelectCommand? I could bear with this but this._commandCollection is private so I cannot acces it outside of the class code. I don't know how to get into this collection without changing the designer's code. The idea which I have is to expose the collection via partial class definition. However I want to introduce many typed datasets and I really don't want to create partial class definition for each of them. Please note that I am using .NET 3.5. I've found this article about accessing private properties but it concerns .NET 4.0 Thanks for your time.

    Read the article

  • delete row from selected gridview and database

    - by user175084
    i am trying to delete a row from the gridview and database... It should be deleted if a delte linkbutton is clicked in the gridview.. I am gettin the row index as follows: protected void LinkButton1_Click(object sender, EventArgs e) { LinkButton btn = (LinkButton)sender; GridViewRow row = (GridViewRow)btn.NamingContainer; if (row != null) { LinkButton LinkButton1 = (LinkButton)sender; // Get reference to the row that hold the button GridViewRow gvr = (GridViewRow)LinkButton1.NamingContainer; // Get row index from the row int rowIndex = gvr.RowIndex; string str = rowIndex.ToString(); //string str = GridView1.DataKeys[row.RowIndex].Value.ToString(); RemoveData(str); //call the delete method } } now i want to delete it... so i am having problems with this code.. i get an error Must declare the scalar variable "@original_MachineGroupName"... any suggestions private void RemoveData(string item) { SqlConnection conn = new SqlConnection(@"Data Source=JAGMIT-PC\SQLEXPRESS; Initial Catalog=SumooHAgentDB;Integrated Security=True"); string sql = "DELETE FROM [MachineGroups] WHERE [MachineGroupID] = @original_MachineGroupID; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@original_MachineGroupID", item); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } Blockquote <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SumooHAgentDBConnectionString %>" SelectCommand="SELECT MachineGroups.MachineGroupID, MachineGroups.MachineGroupName, MachineGroups.MachineGroupDesc, MachineGroups.TimeAdded, MachineGroups.CanBeDeleted, COUNT(Machines.MachineName) AS Expr1, DATENAME(month, (MachineGroups.TimeAdded - 599266080000000000) / 864000000000) + SPACE(1) + DATENAME(d, (MachineGroups.TimeAdded - 599266080000000000) / 864000000000) + ', ' + DATENAME(year, (MachineGroups.TimeAdded - 599266080000000000) / 864000000000) AS Expr2 FROM MachineGroups FULL OUTER JOIN Machines ON Machines.MachineGroupID = MachineGroups.MachineGroupID GROUP BY MachineGroups.MachineGroupID, MachineGroups.MachineGroupName, MachineGroups.MachineGroupDesc, MachineGroups.TimeAdded, MachineGroups.CanBeDeleted" DeleteCommand="DELETE FROM [MachineGroups] WHERE [MachineGroupID] =@original_MachineGroupID" > <DeleteParameters> <asp:Parameter Name="@original_MachineGroupID" Type="Int16" /> <asp:Parameter Name="@original_MachineGroupName" Type="String" /> <asp:Parameter Name="@original_MachineGroupDesc" Type="String" /> <asp:Parameter Name="@original_CanBeDeleted" Type="Boolean" /> <asp:Parameter Name="@original_TimeAdded" Type="Int64" /> </DeleteParameters> </asp:SqlDataSource> I still get an error : Must declare the scalar variable "@original_MachineGroupID"

    Read the article

  • How to bind grid in ASP.NET?

    - by Abid Ali
    I cant bind my Grid. I dont know what I am doing wrong, the grid appears empty when I run the program. here is my code :: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) this.BindGrid(this.GridView1); } private void BindGrid(GridView grid) { SqlCommand cmd = new SqlCommand("Select * from Person", cn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); grid.DataSource = dt; grid.DataBind(); } <body> <form id="form1" runat="server"> <div style="margin-left: 240px"> <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" Width="856px" AutoGenerateColumns = "false" ShowFooter = "true" ShowHeader="true" BorderStyle="Groove" CaptionAlign="Top" HorizontalAlign="Center" onrowdatabound="GridView1_RowDataBound" > <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <Columns> <asp:BoundField HeaderText="ID" /> <asp:BoundField HeaderText="First Name" /> <asp:BoundField HeaderText="Last Name" /> <asp:BoundField HeaderText="Home Phone #" /> <asp:BoundField HeaderText="Cell #" /> <asp:BoundField HeaderText="Email Address" /> <asp:BoundField HeaderText="NIC #" /> <asp:TemplateField HeaderText="Action"> <ItemTemplate> <asp:Button ID="Button1" runat="server" Text="Button" /> <asp:Button ID="Button2" runat="server" Text="Button" /> </ItemTemplate> </asp:TemplateField> </Columns> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <EditRowStyle BackColor="#999999" /> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> </asp:GridView> </div> </form> </body>

    Read the article

  • How can I programmatically drop a SQL Server database from .NET code

    - by Craig Shearer
    I'm trying to drop a SQL Server database from .NET code. I've tried using the SMO classes but get an exception saying the database is in use. Then I tried executing a query (opening a SqlConnection, executing a SqlCommand), along the lines of: ALTER DATABASE foo SET SINGLE_USER WITH ROLLBACK IMMEDIATE (pause) DROP DATABASE foo But still I get an exception saying the database is in use. How do I do this? (Or, how does SQL Server Management Studio implement the Drop database and close existing connections?)

    Read the article

  • List<> of objects, different types, sort and pull out types individually?

    - by Brazos
    I've got a handful of products, any, all, or none of which may be associated with a specific submission. All 7 products are subclasses of the class Product. I need to store all the products associated with a submission, and then retrieve them and their field data on my presentation layer. I've been using a List, and List, but when I use the OfType, I throw an error saying that I can't implicitly convert systems.generic.IEnumerable to type 'Product'. I've tried to cast, but to no avail. When I use prodlist.OfType<EPL>(); there are no errors, but when I try and store that in an instance of EPL "tempEpl", I get the aforementioned cast-related error. What gives? Code below. ProductService pserv = new ProductService(); IList<object> prodlist = pserv.getProductById(x); EPL tempEpl = new EPL(); if ((prodlist.OfType<EPL>()) != null) { tempEpl = prodlist.OfType<EPL>(); // this throws a conversion error. } the Data layer List<object> TempProdList = new List<object>(); conn.Open(); SqlCommand EplCmd = new SqlCommand(EPLQuery, conn); SqlDataReader EplRead = null; EplRead = EplCmd.ExecuteReader(); EPL TempEpl = new EPL(); if (EplRead.Read()) { TempEpl.Entity1 = EplRead.GetString(0); TempEpl.Employees1 = EplRead.GetInt32(1); TempEpl.CA1 = EplRead.GetInt32(2); TempEpl.MI1 = EplRead.GetInt32(3); TempEpl.NY1 = EplRead.GetInt32(4); TempEpl.NJ1 = EplRead.GetInt32(5); TempEpl.PrimEx1 = EplRead.GetInt32(6); TempEpl.EplLim1 = EplRead.GetInt32(7); TempEpl.EplSir1 = EplRead.GetInt32(8); TempEpl.Premium1 = EplRead.GetInt32(9); TempEpl.Wage1 = EplRead.GetInt32(10); TempEpl.Sublim1 = EplRead.GetInt32(11); TempProdList.Add(TempEpl); }

    Read the article

  • Uploading files to varbinary(max) in SQL Server -- works on one server, not the other

    - by pjabbott
    I have some code that allows users to upload file attachments into a varbinary(max) column in SQL Server from their web browser. It has been working perfectly fine for almost two years, but all of a sudden it stopped working. And it stopped working on only the production database server -- it still works fine on the development server. I can only conclude that the code is fine and there is something up with the instance of SQL Server itself. But I have no idea how to isolate the problem. I insert a record into the ATTACHMENT table, only inserting non-binary data like the title and the content type, and then chunk-upload the uploaded file using the following code: // get the file stream System.IO.Stream fileStream = postedFile.InputStream; // make an upload buffer byte[] fileBuffer; fileBuffer = new byte[1024]; // make an update command SqlCommand fileUpdateCommand = new SqlCommand("update ATTACHMENT set ATTACHMENT_DATA.WRITE(@Data, NULL, NULL) where ATTACHMENT_ID = @ATTACHMENT_ID", sqlConnection, sqlTransaction); fileUpdateCommand.Parameters.Add("@Data", SqlDbType.Binary); fileUpdateCommand.Parameters.AddWithValue("@ATTACHMENT_ID", newId); while (fileStream.Read(fileBuffer, 0, fileBuffer.Length) > 0) { fileUpdateCommand.Parameters["@Data"].Value = fileBuffer; fileUpdateCommand.ExecuteNonQuery(); <------ FAILS HERE } fileUpdateCommand.Dispose(); fileStream.Close(); Where it says "FAILS HERE", it sits for a while and then I get a SQL Server timeout error on the very first iteration through the loop. If I connect to the development database instead, everything works fine (it runs through the loop many, many times and the commit is successful). Both servers are identical (SQL Server 9.0.3042) and the schemas are identical as well. When I open Activity Monitor right after the timeout to see what's going it, it says the last command is (@Data binary(1024),@ATTACHMENT_ID decimal(4,0))update ATTACHMENT set ATTACHMENT_DATA.WRITE(@Data, NULL, NULL) where ATTACHMENT_ID = @ATTACHMENT_ID which I would expect but it also says it has a status of "Suspended" and a wait type of "PAGEIOLATCH_SH". I looked this up and it seems to be a bad thing but I can't find anything specific to my stuation. Ideas?

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >