Search Results

Search found 332 results on 14 pages for 'connectionstrings'.

Page 11/14 | < Previous Page | 7 8 9 10 11 12 13 14  | Next Page >

  • ODP.NET Procedure Compilation

    - by Bobcat1506
    When I try to execute a create procedure using ODP.NET I get back ORA-24344: success with compilation error. However, when I run the same statement in SQL Developer it compiles successfully. Does anyone know what I need to change to get my procedure to compile? Is it a character set issue? I am using Oracle 10g Express, .NET 3.5 SP 1, and ODP.NET 2.111.7.20 (version from Oracle.DataAccess.dll) [TestMethod] public void OdpNet_CreateProcedure() { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["ODP.NET"]; using (var con = new OracleConnection(settings.ConnectionString)) { con.InfoMessage += new OracleInfoMessageEventHandler(con_InfoMessage); con.Open(); var cmd = new OracleCommand(); cmd.Connection = con; cmd.CommandText = @" CREATE OR REPLACE PROCEDURE TABLE1_GET ( P_CURSOR OUT SYS_REFCURSOR ) IS BEGIN OPEN P_CURSOR FOR SELECT * FROM TABLE1; END;"; cmd.ExecuteNonQuery(); // ORA-24344: success with compilation error cmd.CommandText = @"ALTER PROCEDURE TABLE1_GET COMPILE"; cmd.ExecuteNonQuery(); // ORA-24344: success with compilation error } } void con_InfoMessage(object sender, OracleInfoMessageEventArgs eventArgs) { System.Diagnostics.Debug.WriteLine(eventArgs.Message); }

    Read the article

  • how to retrieve informatin from deleted row

    - by JM
    How can I retrie infromation from delete rows. I delete some rows from table in dataset, then I use method GetChanges(DataRowState.Deleted) to get deleted rows. I try delete rows in original table on server side, but it finished with this errors. System.Data.DeletedRowInaccessibleException: Deleted row information cannot be accessed through the row. What is correct way? Here is my code, any advice? Thank you everybody Dataset ds = //get dataset from client side //get changes DataTable delRows = ds.Tables[0].GetChanges(DataRowState.Deleted); //try delete rows in table in DB if (delRows != null) { string connStr = WebConfigurationManager.ConnectionStrings["Employees"].ConnectionString; conn = new SqlConnection(connStr); conn.Open(); for (int i = 0; i < delRows.Rows.Count; i++) { string cmdText = string.Format("DELETE Tab1 WHERE Surname=@Surname"); cmd = new SqlCommand() { Connection = conn, CommandText = cmdText }; //here is problem, I need get surnames from rows which was deleted var sqlParam = new SqlParameter(@"Surname", SqlDbType.VarChar) { Value = delRows.Rows[i][1].ToString() }; cmd.Parameters.Add(sqlParam); cmd.CommandText = cmdText; cmd.Connection = conn; cmd.ExecuteNonQuery(); } }

    Read the article

  • ASP.Net MVC, JS injection and System.ArgumentException - Illegal Characters in path

    - by Mose
    Hi, In my ASP.Net MVC application, I use custom error handling. I want to perform custom actions for each error case I meet in my application. So I override Application_Error, get the Server.GetLastError(); and do my business depending on the exception, the current user, the current URL (the application runs on many domains), the user IP, and many others. Obviousely, the application is often the target of hackers. In almost all the case it's not a problem to detect and manage it, but for some JS URL attacks, my error handling does not perform what I want it to do. Ex (from logs) : http://localhost:1809/Scripts/]||!o.support.htmlSerialize&&[1 When I got such an URL, an exception is raised when accessing the ConnectionStrings section in the web.config, and I can't even redirect to another URL. It leads to a "System.ArgumentException - Illegal Characters in path, etc." The screenshot below shows the problem : http://screencast.com/t/Y2I1YWU4 An obvious solution is to write a HTTP module to filter the urls before they reach my application, but I'd like to avoid it because : I like having the whole security being managed in one place (in the Application_Error() method) In the module I cannot access the whole data I have in the application itself (application specific data I don't want to debate here) Questions : Did you meet this problem ? How did you manage it ? Thanks for you suggestions, Mose

    Read the article

  • Add dynamic charts using ASP.NET CHART CONTROL, c#

    - by dhareni
    I wanted to add dynamic charts in the webpage. It goes like this... I get the start and end date from user and draw separate charts for each date bewteen the start and end date. I get the data from sql database and bind it with the chart like this: SqlConnection UsageLogConn = new SqlConnection(ConfigurationManager.ConnectionStrings["UsageConn"].ConnectionString); UsageLogConn.Open();//open connection string sql = "SELECT v.interval,dateadd(mi,(v.interval-1)*2,'" + startdate + " 00:00:00') as 'intervaltime',COUNT(Datediff(minute,'" + startdate + " 00:00:00',d.DateTime)/2) AS Total FROM usage_internet_intervals v left outer join (select * from Usage_Internet where " + name + " LIKE ('%" + value + "%') and DateTime BETWEEN '" + startdate + " 00:00:00' AND '" + enddate + " 23:59:59') d on v.interval = Datediff(minute,'" + startdate + " 00:00:00',d.DateTime)/2 GROUP BY v.interval,Datediff(minute,'" + startdate + " 00:00:00',d.DateTime)/2 ORDER BY Interval"; SqlCommand cmd = new SqlCommand(sql, UsageLogConn); SqlDataAdapter mySQLadapter = new SqlDataAdapter(cmd); Chart1.DataSource = cmd; // set series members names for the X and Y values Chart1.Series["Series 1"].XValueMember = "intervaltime"; Chart1.Series["Series 1"].YValueMembers = "Total"; UsageLogConn.Close(); // data bind to the selected data source Chart1.DataBind(); cmd.Dispose(); The above code adds only one chart for one date and I have added 'chart1' to design view and its not created dynamic. But I wanted to add more charts dynamic at runtime to the webpage. Can anyone help me with this? I am using VS 2008, ASP.NET 3.5 and the charting lib is: using System.Web.UI.DataVisualization.Charting;

    Read the article

  • VB dataset issue

    - by Gabriel
    Hi. The idea was to create a message box that stores my user name, message, and post datetime into the database as messages are sent. Soon came to realise, what if the user changed his name? So I decided to use the user id (icn) to identify the message poster instead. However, my chunk of codes keep giving me the same error. Says that there are no rows in the dataset ds2. I've tried my Query on my SQL and it works perfectly so I really really need help to spot the error in my chunk of codes here. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim name As String Dim icn As String Dim message As String Dim time As String Dim tags As String = "" Dim strConn As System.Configuration.ConnectionStringSettings strConn = ConfigurationManager.ConnectionStrings("ufadb") Dim conn As SqlConnection = New SqlConnection(strConn.ToString()) Dim cmd As New SqlCommand("Select * From Message", conn) Dim daMessages As SqlDataAdapter = New SqlDataAdapter(cmd) Dim ds As New DataSet cmd.Connection.Open() daMessages.Fill(ds, "Messages") cmd.Connection.Close() If ds.Tables("Messages").Rows.Count > 0 Then Dim n As Integer = ds.Tables("Messages").Rows.Count Dim i As Integer For i = 0 To n - 1 icn = ds.Tables("Messages").Rows(i).Item("icn") Dim cmd2 As New SqlCommand("SELECT name FROM Member inner join Message ON Member.icn = Message.icn WHERE message.icn = @icn", conn) cmd2.Parameters.AddWithValue("@icn", icn) Dim daName As SqlDataAdapter = New SqlDataAdapter(cmd2) Dim ds2 As New DataSet cmd2.Connection.Open() daName.Fill(ds2, "PosterName") cmd2.Connection.Close() name = ds2.Tables("PosterName").Rows(0).Item("name") message = ds.Tables("Messages").Rows(i).Item("message") time = ds.Tables("Messages").Rows(i).Item("timePosted") tags = time + vbCrLf + name + ": " + vbCrLf + message + vbCrLf + tags Next txtBoard.Text = tags Else txtBoard.Text = "nothing to display" End If End Sub Help will be very much appreciated as I have been on this simple problem for 2 days.

    Read the article

  • "The data types text and nvarchar are incompatible in the equal to operator" in SQL Query

    - by kenom
    Why i get this error: The data types text and nvarchar are incompatible in the equal to operator. The field of "username" in database is text type... This is my soruce: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="my_answers.ascx.cs" Inherits="kontrole_login_my_answers" %> <div style=" margin-top:-1280px; float:left;"> <p></p> <div id="question"> Add question </div> </div> <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" > </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:estudent_piooConnectionString %>" SelectCommand="SELECT * FROM [question] WHERE ([username] = @fafa)"> <SelectParameters> <asp:QueryStringParameter Name="fafa" QueryStringField="user" Type="String"/> </SelectParameters> </asp:SqlDataSource>

    Read the article

  • Problem using SQLDataReader with Sybase ASE

    - by John K.
    We're developing a reporting application that uses asp.net-mvc (.net 4). We connect through DDTEK.Sybase middleware to a Sybase ASE 12.5 database. We're having a problem pulling data into a datareader (from a stored procedure). The stored procedure computes values (approximately 50 columns) by doing sums, counts, and calling other stored procedures. The problem we're experiencing is... certain (maybe 5% of the columns) come back with NULL or 0. If we debug and copy the SQL statement being used for the datareader and run it inside another SQL tool we get all valid values for all columns. conn = new SybaseConnection { ConnectionString = ConfigurationManager.ConnectionStrings[ConnectStringName].ToString() }; conn.Open(); cmd = new SybaseCommand { CommandTimeout = cmdTimeout, Connection = conn, CommandText = mainSql }; reader = cmd.ExecuteReader(); // AT THIS POINT IMMEDIATELY AFTER THE EXECUTEREADER COMMAND // THE READER CONTAINS THE BAD (NULL OR 0) DATA FOR THESE COLUMNS. DataTable schemaTable = reader.GetSchemaTable(); // AT THIS POINT WE CAN VIEW THE DATATABLE FOR THE SCHEMA AND IT APPEARS CORRECT // THE COLUMNS THAT DON'T WORK HAVE SPECIFICATIONS IDENTICAL TO THE COLUMNS THAT DO WORK Has anyone had problems like this using Sybase and ADO? Thanks, John K.

    Read the article

  • [C#]Update Datatable and DatagridView with database Changes by Timer

    - by aleroot
    Scenario : i have a database table that is being apdated frequently bey some services. I have a c# Winform Application that load this table in a datagridview by binding a datatable as Datasource, then i whant to add a Timer that every 10 seconds update a the content of a datatable with the last changes in the database table ... I don't need to update a database with the datatable changes, but i need to update datatable with the last changes in the database table, that is the inverse of the usually.... Is there a way to do that ? What is the best way ? i've tried with this code : private void ServiceTimer_Tick(object state) { OdbcConnection oCon = new OdbcConnection(); oCon.ConnectionString = ConnectionStrings; OdbcDataAdapter dp = new OdbcDataAdapter("SELECT * FROM table", oCon); dsProva.Tables.Clear(); dp.Fill(dsProva,"table"); dataGridViewMessaggi.DataSource = dsProva.Tables["table"]; dataGridViewMessaggi.Refresh(); } But every Timer Tick i lost the selection in DatagridView and Current Row .... Is There a better solution ?

    Read the article

  • Using jquery Autocomplete on textbox control in c#

    - by Abid Ali
    When I run this code I get alert saying Error. My Code: <script type="text/javascript"> debugger; $(document).ready(function () { SearchText(); }); function SearchText() { $(".auto").autocomplete({ source: function (request, response) { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "Default.aspx/GetAutoCompleteData", data: "{'fname':'" + document.getElementById('txtCategory').value + "'}", dataType: "json", success: function (data) { response(data.d); }, error: function (result) { alert("Error"); } }); } }); } </script> [WebMethod] public static List<string> GetAutoCompleteData(string CategoryName) { List<string> result = new List<string>(); using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString)) { using (SqlCommand cmd = new SqlCommand("select fname from tblreg where fname LIKE '%'+@CategoryText+'%'", con)) { con.Open(); cmd.Parameters.AddWithValue("@CategoryText", CategoryName); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { result.Add(dr["fname"].ToString()); } return result; } } } I want to debug my function GetAutoCompleteData but breakpoint is not fired at all. What's wrong in this code? Please guide. I have attached screen shot above.

    Read the article

  • Could DataGridView be this dumb? or its me?lol

    - by Selase
    Am trying to bind data to a dropdown list on pageload based on a condition. Code explains further below. public partial class AddExhibit : System.Web.UI.Page { string adminID, caseIDRetrieved; DataSet caseDataSet = new DataSet(); SqlDataAdapter caseSqlDataAdapter = new SqlDataAdapter(); string strConn = WebConfigurationManager.ConnectionStrings["CMSSQL3ConnectionString1"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { adminID = Request.QueryString["adminID"]; caseIDRetrieved = Request.QueryString["caseID"]; if (caseIDRetrieved != null) { CaseIDDropDownList.Text = caseIDRetrieved; //CaseIDDropDownList.Enabled = false; } else { try { CreateDataSet(); DataView caseDataView = new DataView(caseDataSet.Tables[0]); CaseIDDropDownList.DataSource = caseDataView; CaseIDDropDownList.DataBind(); } catch (Exception ex) { string script = "<script>alert('" + ex.Message + "');</script>"; } } } The CreateDataset method that is called in the if..else statement is contains the following code. private void CreateDataSet() { SqlConnection caseConnection = new SqlConnection(strConn); caseSqlDataAdapter.SelectCommand = new SqlCommand("Select CaseID FROM Cases", caseConnection); caseSqlDataAdapter.Fill(caseDataSet); } However when i load the page and as usual the condition that is supposed to bid the data is met, the gridview decides to displays as follows... IS IT ME OR ITS THE DATAGRID?...??

    Read the article

  • Help with SQL Server query

    - by Travis
    Sorry* this is what I should have put My query is creating duplicate entries for any record that has more than 1 instance (regardless of date) <asp:SqlDataSource ID="EastMonthlyHealthDS" runat="server" ConnectionString="<%$ ConnectionStrings:SNA_TRTTestConnectionString %>" SelectCommand="SELECT [SNA_Parent_Accounts].[Company], (SELECT [Monthly_HIP_Reports].[AccountHealth] from [Monthly_HIP_Reports] where ([Monthly_HIP_Reports].[YearMonth] = @ToDtRFC) AND ([SNA_Parent_Accounts].[CompID] = [Monthly_HIP_Reports].[CompID])) as [AccountHealth], [SNA_Parent_Accounts].[CompID] FROM [SNA_Parent_Accounts] LEFT OUTER JOIN [Monthly_HIP_Reports] ON [Monthly_HIP_Reports].[CompID] = [SNA_Parent_Accounts].[CompID] WHERE (([SNA_Parent_Accounts].[Classification] = 'Business') OR ([SNA_Parent_Accounts].[Classification] = 'Business Ihn')) AND ([SNA_Parent_Accounts].[Status] = 'active') AND ([SNA_Parent_Accounts].[Region] = 'east') ORDER BY [SNA_Parent_Accounts].[Company]"> <SelectParameters> <asp:ControlParameter ControlID="ddMonths" Name="ToDtRFC" PropertyName="Text" Type="String" /> </SelectParameters> </asp:SqlDataSource> Using SELECT DISTINCT appears to correct the problem, but I don't consider that a solution. There are no duplicate entries in the database. So it appears my query is superfically creating duplicates. The query should grab a list of companies that meet the criteria in the where clause, but also grab the Health status for each company in that particular [YearMonth] if present which is what the subquery is for. If an entry for that YearMonth is not present, then leave the Health status blank. but as stated earlier.. if you have an entry say for 2009-03 for CompID 2 and an entry for 2009-04 for CompID 2.. Doesn't matter what month you select it will list that company 2-3 times.

    Read the article

  • Update data table on ASMX Service side

    - by Paul
    Hi, I need advice. On Web Service side a I hav this method : public DataSet GetDs(string id) { SqlConnection conn = null; SqlDataAdapter da = null; DataSet ds; try { string sql = "SELECT * FROM Tab1"; string connStr = WebConfigurationManager.ConnectionStrings["Employees"].ConnectionString; conn = new SqlConnection(connStr); conn.Open(); da = new SqlDataAdapter(sql, conn); ds = new DataSet(); da.Fill(ds, "Tab1"); return ds; } catch (Exception ex) { throw ex; } finally { if (conn != null) conn.Close(); if (da != null) da.Dispose(); } } It return dataset to client app. I client application is dataset binding in datagridview. Client can insert,update,delete row from table. If client finish his work, I want accept change in data table on web service side. I can sent clients all dataset na update table on web service side, but I want sent only changed data. Any advice? Thank u.

    Read the article

  • Update Datatable and DatagridView with database Changes by Timer

    - by aleroot
    Scenario : i have a database table that is being updated frequently by some services. I have a c# Winforms Application that load this table in a datagridview by binding a datatable as Datasource, then i whant to add a Timer that every 10 seconds update a the content of a datatable with the last changes in the database table ... I don't need to update a database with the datatable changes, but i need to update datatable with the last changes in the database table, that is the inverse of the usually.... Is there a way to do that ? What is the best way ? i've tried with this code : private void ServiceTimer_Tick(object state) { OdbcConnection oCon = new OdbcConnection(); oCon.ConnectionString = ConnectionStrings; OdbcDataAdapter dp = new OdbcDataAdapter("SELECT * FROM table", oCon); dsProva.Tables.Clear(); dp.Fill(dsProva,"table"); dataGridViewMessaggi.DataSource = dsProva.Tables["table"]; dataGridViewMessaggi.Refresh(); } But every Timer Tick i lost the selection in DatagridView and Current Row .... Is There a better solution ?

    Read the article

  • Populate asp.net MVC Index page with data from the database

    - by Sunil Ramu
    I have a web application in which I need to fetch data from the database and display in the index page. As you know, asp.net mvc has given options to edit delete etc... I need to populate the page using the conventional DB way and it uses a stored procedure to retrieve results. I dont want to use LINQ. This is my model entity class using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LogMVCApp.Models { public class Property { public int Id { get; set; } public string LogInId { get; set; } public string Username { get; set; } public string Action { get; set; } public string Information { get; set; } public bool Passed{get; set; } public string LogType { get; set; } } } and I need to retrieve data using something like this... var conString = ConfigurationManager.ConnectionStrings["connection"].ToString(); var conn = new SqlConnection(conString); var command = new SqlCommand("LogInsert", conn){CommandType=CommandType.StoredProcedure};

    Read the article

  • Database.ExecuteNonQuery does not return

    - by dan-waterbly
    I have a very odd issue. When I execute a specific database stored procedure from C# using SqlCommand.ExecuteNonQuery, my stored procedure is never executed. Furthermore, SQL Profiler does not register the command at all. I do not receive a command timeout, and no exeception is thrown. The weirdest thing is that this code has worked fine over 1,200,000 times, but for this one particular file I am inserting into the database, it just hangs forever. When I kill the application, I receive this error in the event log of the database server: "A fatal error occurued while reading the input stream from the network. The session will be terminated (input error: 64, output error: 0). Which makes me think that the database server is receiving the command, though SQL Profiler says otherwise. I know that the appropiate permissions are set, and that the connection string is right as this piece of code and stored procedure works fine with other files. Below is the code that calls the stored procedure, it may be important to note that the file I am trying to insert is 33.5MB, but I have added more than 10,000 files larger than 500MB, so I do not think the size is the issue: using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["TheDatabase"].ConnectionString)) using (SqlCommand command = sqlconn.CreateCommand()) { command.CommandText = "Add_File"; command.CommandType = CommandType.StoredProcedure; command.CommandTimeout = 30 //should timeout in 30 seconds, but doesn't... command.Parameters.AddWithValue("@ID", ID).SqlDbType = SqlDbType.BigInt; command.Parameters.AddWithValue("@BinaryData", byteArr).SqlDbType = SqlDbType.VarBinary; command.Parameters.AddWithValue("@FileName", fileName).SqlDbType = SqlDbType.VarChar; sqlconn.Open(); command.ExecuteNonQuery(); } There is no firewall between the server making the call and the database server, and the windows firewalls have been disabled to troubleshoot this issue.

    Read the article

  • error while updating a database in ASP.NET

    - by Viredae
    I am having trouble updating an SQL database, the problem is not that it doesn't update at all, but that particular parameters are being updated while the others are not. here is the code for updating the parameters: string EditRequest = "UPDATE Requests SET Description = @Desc, BJustif = @Justif, Priority = @Priority, Requested_System = @Requested, Request_Status = @Stat WHERE"; EditRequest += " Req_ID=@ID"; SqlConnection Submit_conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DBConn"].ConnectionString); SqlCommand Submit_comm = new SqlCommand(EditRequest, Submit_conn); Submit_comm.Parameters.AddWithValue("@ID", Request.QueryString["reqid"]); Submit_comm.Parameters.AddWithValue("@Desc", DescBox.Text); Submit_comm.Parameters.AddWithValue("@Justif", JustifBox.Text); Submit_comm.Parameters.AddWithValue("@Priority", PriorityList.SelectedValue); Submit_comm.Parameters.AddWithValue("@Requested", RelatedBox.Text); Submit_comm.Parameters.AddWithValue("@Stat", 1); Submit_conn.Open(); Submit_comm.ExecuteNonQuery(); Submit_comm.Dispose(); Submit_comm = null; Submit_conn.Close(); get_Description(); Page.ClientScript.RegisterStartupScript(this.GetType(), "Refresh", "ReloadPage();", true); this function is called by a button on a pop-up form which shows the parameters content that is being changed in a text box which is also used to submit the changes back to the database, but when I press submit, the parameters which are displayed on the form don't change, I can't find any problem wit the code, even though I've compared it to similar code which is working fine. In case you need to, here is one of the text boxes I'm using to display and edit the content: <asp:TextBox ID="JustifBox" TextMode="MultiLine" runat="server" Width="250" Height="50"></asp:TextBox> What exactly is wrong with the code?

    Read the article

  • Access DB Transaction on insert or updating

    - by Raju Gujarati
    I am going to implement the database access layer of the Window application using C#. The database (.accdb) is located to the project files. When it comes to two notebooks (clients) connecting to one access database through switches, it throws DBConcurrency Exception Error. My target is to check the timestamp of the sql executed first and then run the sql . Would you please provide me some guidelines to achieve this ? The below is my code protected void btnTransaction_Click(object sender, EventArgs e) { string custID = txtID.Text; string CompName = txtCompany.Text; string contact = txtContact.Text; string city = txtCity.Text; string connString = ConfigurationManager.ConnectionStrings["CustomersDatabase"].ConnectionString; OleDbConnection connection = new OleDbConnection(connString); connection.Open(); OleDbCommand command = new OleDbCommand(); command.Connection = connection; OleDbTransaction transaction = connection.BeginTransaction(); command.Transaction = transaction; try { command.CommandText = "INSERT INTO Customers(CustomerID, CompanyName, ContactName, City, Country) VALUES(@CustomerID, @CompanyName, @ContactName, @City, @Country)"; command.CommandType = CommandType.Text; command.Parameters.AddWithValue("@CustomerID", custID); command.Parameters.AddWithValue("@CompanyName", CompName); command.Parameters.AddWithValue("@ContactName", contact); command.Parameters.AddWithValue("@City", city); command.ExecuteNonQuery(); command.CommandText = "UPDATE Customers SET ContactName = @ContactName2 WHERE CustomerID = @CustomerID2"; command.CommandType = CommandType.Text; command.Parameters.AddWithValue("@CustomerID2", custIDUpdate); command.Parameters.AddWithValue("@ContactName2", contactUpdate); command.ExecuteNonQuery(); adapter.Fill(table); GridView1.DataSource = table; GridView1.DataBind(); transaction.Commit(); lblMessage.Text = "Transaction successfully completed"; } catch (Exception ex) { transaction.Rollback(); lblMessage.Text = "Transaction is not completed"; } finally { connection.Close(); } }

    Read the article

  • public class ImageHandler : IHttpHandler

    - by Ken
    cmd.Parameters.AddWithValue("@id", new system.Guid (imageid)); What using System reference would this require? Here is the handler: using System; using System.Collections.Specialized; using System.Web; using System.Web.Configuration; using System.Web.Security; using System.Globalization; using System.Configuration; using System.Data.SqlClient; using System.Data; using System.IO; using System.Web.Profile; using System.Drawing; public class ImageHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string imageid; if (context.Request.QueryString["id"] != null) imageid = (context.Request.QueryString["id"]); else throw new ArgumentException("No parameter specified"); context.Response.ContentType = "image/jpeg"; Stream strm = ShowProfileImage(imageid.ToString()); byte[] buffer = new byte[8192]; int byteSeq = strm.Read(buffer, 0, 8192); while (byteSeq > 0) { context.Response.OutputStream.Write(buffer, 0, byteSeq); byteSeq = strm.Read(buffer, 0, 8192); } //context.Response.BinaryWrite(buffer); } public Stream ShowProfileImage(String imageid) { string conn = ConfigurationManager.ConnectionStrings["MyConnectionString1"].ConnectionString; SqlConnection connection = new SqlConnection(conn); string sql = "SELECT image FROM Profile WHERE UserId = @id"; SqlCommand cmd = new SqlCommand(sql, connection); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@id", new system.Guid (imageid));//Failing Here!!!! connection.Open(); object img = cmd.ExecuteScalar(); try { return new MemoryStream((byte[])img); } catch { return null; } finally { connection.Close(); } } public bool IsReusable { get { return false; } } }

    Read the article

  • Conversion failed when converting datetime from character string

    - by salvationishere
    I am developing a C# VS 2008 / SQL Server 2005 Express website application. I have tried some of the fixes for this problem but my call stack differs from others. And these fixes did not fix my problem. What steps can I take to troubleshoot this? Here is my error: System.Data.SqlClient.SqlException was caught Message="Conversion failed when converting datetime from character string." Source=".Net SqlClient Data Provider" ErrorCode=-2146232060 LineNumber=10 Number=241 Procedure="AppendDataCT" Server="\\\\.\\pipe\\772EF469-84F1-43\\tsql\\query" State=1 StackTrace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at ADONET_namespace.ADONET_methods.AppendDataCT(DataTable dt, Dictionary`2 dic) in c:\Documents and Settings\Admin\My Documents\Visual Studio 2008\WebSites\Jerry\App_Code\ADONET methods.cs:line 102 And here is the related code. When I debugged this code, "dic" only looped through the 3 column names, but did not look into row values which are stored in "dt", the Data Table. public static string AppendDataCT(DataTable dt, Dictionary<string, string> dic) { if (dic.Count != 3) throw new ArgumentOutOfRangeException("dic can only have 3 parameters"); string connString = ConfigurationManager.ConnectionStrings["AW3_string"].ConnectionString; string errorMsg; try { using (SqlConnection conn2 = new SqlConnection(connString)) { using (SqlCommand cmd = conn2.CreateCommand()) { cmd.CommandText = "dbo.AppendDataCT"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn2; foreach (string s in dic.Keys) { SqlParameter p = cmd.Parameters.AddWithValue(s, dic[s]); p.SqlDbType = SqlDbType.VarChar; } conn2.Open(); cmd.ExecuteNonQuery(); conn2.Close(); errorMsg = "The Person.ContactType table was successfully updated!"; } } }

    Read the article

  • build SQL query string using user input

    - by user175084
    i have to make a string by using the values which the user selects on the webpage suppose i need to display files for multiple machines with differnt search criteria.. i currently use this code: DataTable dt = new DataTable(); SqlConnection connection = new SqlConnection(); connection.ConnectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString; connection.Open(); SqlCommand sqlCmd = new SqlCommand("SELECT FileID FROM Files WHERE MachineID=@machineID and date= @date", connection); SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd); sqlCmd.Parameters.AddWithValue("@machineID", machineID); sqlCmd.Parameters.AddWithValue("@date", date); sqlDa.Fill(dt); now this is fixed query where the user just has one machine and just selects one date... i want to make a query in which the user has multiple search options like type or size if he wants depending on what he selects also if he can select multiple machines.. SELECT FileID FROM Files WHERE (MachineID=@machineID1 or MachineID = @machineID2...) and (date= @date and size=@size and type=@type... ) all of this happens in runtime... other wise i have to create a for loop to put multiple machines one by one... and have multiple queries depending on the case the user selected... this is quiet interesting and i could use some help... thanks

    Read the article

  • Using block around a static/singleton resource reference

    - by byte
    This is interesting (to me anyway), and I'd like to see if anyone has a good answer and explanation for this behavior. Say you have a singleton database object (or static database object), and you have it stored in a class Foo. public class Foo { public static SqlConnection DBConn = new SqlConnection(ConfigurationManager.ConnectionStrings["BAR"].ConnectionString); } Then, lets say that you are cognizant of the usefulness of calling and disposing your connection (pretend for this example that its a one-time use for purposes of illustration). So you decide to use a 'using' block to take care of the Dispose() call. using (SqlConnection conn = Foo.DBConn) { conn.Open(); using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "SP_YOUR_PROC"; cmd.ExecuteNonQuery(); } conn.Close(); } This fails, with an error stating that the "ConnectionString property is not initialized". It's not an issue with pulling the connection string from the app.config/web.config. When you investigate in a debug session you see that Foo.DBConn is not null, but contains empty properties. Why is this?

    Read the article

  • ASP ListView - Eval() as formatted number, Bind() as unformatted?

    - by chucknelson
    I have an ASP ListView, and have a very simple requirement to display numbers as formatted w/ a comma (12,123), while they need to bind to the database without formatting (12123). I am using a standard setup - ListView with a datasource attached, using Bind(). I converted from some older code, so I'm not using ASP.NET controls, just form inputs...but I don't think it matters for this: <asp:SqlDataSource ID="MySqlDataSource" runat="server" ConnectionString='<%$ ConnectionStrings:ConnectionString1 %>' SelectCommand="SELECT NUMSTR FROM MY_TABLE WHERE ID = @ID" UpdateCommand= "UPDATE MY_TABLE SET NUMSTR = @NUMSTR WHERE ID = @ID"> </asp:SqlDataSource> <asp:ListView ID="MyListView" runat="server" DataSourceID="MySqlDataSource"> <LayoutTemplate> <div id="itemplaceholder" runat="server"></div> </LayoutTemplate> <ItemTemplate> <input type="text" name="NUMSTR" ID="NUMSTR" runat="server" value='<%#Bind("NUMSTR")%>' /> <asp:Button ID="UpdateButton" runat="server" Text="Update" Commandname="Update" /> </ItemTemplate> </asp:ListView> In the example above, NUMSTR is a number, but stored as a string in a SqlServer 2008 database. I'm also using the ItemTemplate as read and edit templates, to save on duplicate HTML. In the example, I only get the unformatted number. If I convert the field to an integer (via the SELECT) and use a format string like Bind("NUMSTR", "{0:###,###}"), it writes the formatted number to the database, and then fails when it tries to read it again (can't convert with the comma in there). Is there any elegant/simple solution to this? It's so easy to get the two-way binding going, and I would think there has to be a way to easily format things as well... Oh, and I'm trying to avoid the standard ItemTemplate and EditItemTemplate approach, just for sheer amount of markup required for that. Thanks!

    Read the article

  • Make datalist into 3 x 3

    - by unknown
    This is my code behind for products page. The prodblem is that my datalist will fill in new items whenever I add a new object in the website. So may I know how to add the codes in so that I can make the datalist into 3x3. Thanks. Code behind Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim Product As New Product Dim DataSet As New DataSet Dim pds As New PagedDataSource DataSet = Product.GetProduct Session("Dataset") = DataSet pds.PageSize = 4 pds.AllowPaging = True pds.CurrentPageIndex = 1 Session("Page") = pds If Not Page.IsPostBack Then UpdateDatabind() End If End Sub Sub UpdateDatabind() Dim DataSet As DataSet = Session("DataSet") If DataSet.Tables(0).Rows.Count > 0 Then pds.DataSource = DataSet.Tables(0).DefaultView Session("Page") = pds dlProducts.DataSource = DataSet.Tables(0).DefaultView dlProducts.DataBind() lblCount.Text = DataSet.Tables(0).Rows.Count End If End Sub Private Sub dlProducts_UpdateCommand(source As Object, e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles dlProducts.UpdateCommand dlProducts.DataBind() End Sub Public Sub PrevNext_Command(source As Object, e As CommandEventArgs) Dim pds As PagedDataSource = Session("Page") Dim CurrentPage = pds.CurrentPageIndex If e.CommandName = "Previous" Then If CurrentPage < 1 Or CurrentPage = pds.IsFirstPage Then CurrentPage = 1 Else CurrentPage -= 1 End If UpdateDatabind() ElseIf e.CommandName = "Next" Then If CurrentPage > pds.PageCount Or CurrentPage = pds.IsLastPage Then CurrentPage = CurrentPage Else CurrentPage += 1 End If UpdateDatabind() End If Response.Redirect("Products.aspx?PageIndex=" & CurrentPage) End Sub this is my code for product.vb Public Function GetProduct() As DataSet Dim strConn As String strConn = ConfigurationManager.ConnectionStrings("HomeFurnitureConnectionString").ToString Dim conn As New SqlConnection(strConn) Dim strSql As String 'strSql = "SELECT * FROM Product p INNER JOIN ProductDetail pd ON p.ProdID = pd.ProdID " & _ ' "WHERE pd.PdColor = (SELECT min(PdColor) FROM ProductDetail as pd1 WHERE pd1.ProdID = p.ProdID)" Dim cmd As New SqlCommand(strSql, conn) Dim ds As New DataSet Dim da As New SqlDataAdapter(cmd) conn.Open() da.Fill(ds) conn.Close() Return ds End Function

    Read the article

  • Compare system date with a date field in SQL

    - by JeT_BluE
    I am trying to compare a date record in SQL Server with the system date. In my example the user first register with his name and date of birth which are then stored in the database. The user than logs into the web application using his name only. After logging in, his name is shown on the side where it says "Welcome "player name" using Sessions. What I am trying to show in addition to his name is a message saying "happy birthday" if his date of birth matches the system date. I have tried working with System.DateTime.Now, but what I think is that it is also comparing the year, and what I really want is the day and the month only. I would really appreciate any suggestion or help. CODE In Login page: protected void Button1_Click(object sender, EventArgs e) { String name = TextBox1.Text; String date = System.DateTime.Today.ToShortDateString(); SqlConnection myconn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["User"].ToString()); SqlCommand cmd2 = new SqlCommand(); SqlDataReader reader; myconn2.Open(); cmd2 = new SqlCommand("Select D_O_B from User WHERE Username = @username", myconn2); cmd2.Parameters.Add("@username", SqlDbType.NVarChar).Value = name; cmd2.Connection = myconn2 cmd2.ExecuteNonQuery(); reader = cmd2.ExecuteReader(); while (reader.Read().ToString() == date) { Session["Birthday"] = "Happy Birthday"; } } Note: I using the same reader in the code above this one, but the reader here is with a different connection. Also, reader.Read() is different than reader.HasRows? Code in Web app Page: string date = (string)(Session["Birthday"]); // Retrieving the session Label6.Text = date;

    Read the article

  • How can i pull an image and data from a Database?

    - by user1851377
    I am trying to pull data from a Database using C#.net and use a Foreach loop to make it visible on a page. Every time i run the code i only get one item that shows up when i know that there is at least 7 items in the DB. i have placed the code below for the C#. SqlConnection oConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["HomeGrownEnergyConnectionString"].ToString()); string sqlEnergy = "Select * from Product p where p.ProductTypeId=3"; SqlCommand oCmd = new SqlCommand(sqlEnergy, oConnection); DataTable dtenergy = new DataTable(); SqlDataAdapter oDa = new SqlDataAdapter(oCmd); try { oConnection.Open(); ; oDa.Fill(dtenergy); } catch (Exception ex) { lblnodata.Text = ex.Message; return; } finally { oConnection.Close(); } DataTableReader results = dtenergy.CreateDataReader(); if (results.HasRows) { results.Read(); foreach(DataRow result in dtenergy.Rows) { byte[] imgProd = result["ThumnailLocation"] as byte[]; ID.Text = result["ProductID"].ToString(); Name.Text = result["Name"].ToString(); price.Text = FormatPriceColumn(result["Price"].ToString()); } } Here is the code for the asp.net. <div> <asp:Image ID="imgProd" CssClass="ProdImg" runat="server" /> <asp:Label runat="server" ID="ID" /> <asp:Label runat="server" ID="Name" /> <asp:Label runat="server" ID="price" /> <asp:TextBox ID="txtQty" MaxLength="3" runat="server" Width="30px" /> <asp:Button runat="server" ID="Addtocart" Text="Add To Cart" CommandName="AddToCart" ItemStyle-CssClass="btnCol" /> If someone could please help me that would be great thanks.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14  | Next Page >