Search Results

Search found 204 results on 9 pages for 'sqldatareader'.

Page 7/9 | < Previous Page | 3 4 5 6 7 8 9  | Next Page >

  • linq: SQL performance on high loaded web applications

    - by Alex
    I started working with linq to SQL several weeks ago. I got really tired of working with SQL server directly through the SQL queries (sqldatareader, sqlcommand and all this good stuff).  After hearing about linq to SQL and mvc I quickly moved all my projects to these technologies. I expected linq to SQL work slower but it suprisongly turned out to be pretty fast, primarily because I always forgot to close my connections when using datareaders. Now I don't have to worry about it. But there's one problem that really bothers me. There's one page that's requested thousands of times a day. The system gets data in the beginning, works with it and updates it. Primarily the updates are ++ @ -- (increase and decrease values). I used to do it like this UPDATE table SET value=value+1 WHERE ID=@I'd It worked with no problems obviously. But with linq to SQL the data is taken in the beginning, moved to the class, changed and then saved. Stats.registeredusers++; Db.submitchanges(); Let's say there were 100 000 users. Linq will say "let it be 100 001" instead of "let it be increased by 1". But if there value of users has already been increased (that happens in my site all the time) then linq will be like oops, this value is already 100 001. Whatever I'll throw an exception" You can change this behavior so that it won't throw an exception but it still will not set the value to 100 002. Like I said, it happened with me all the time. The stas value was increased twice a second on average. I simply had to rewrite this chunk of code with classic ado net. So my question is how can you solve the problem with linq

    Read the article

  • ASP.NET, C#: timeout when trying to Transaction.Commit() to database; potential deadlock?

    - by user1843921
    I have a web page that has coding structured somewhat as follows: SqlConnection conX =new SqlConnection(blablabla); conX.Open(); SqlTransaction tran=conX.BeginTransaction(); try{ SqlCommand cmdInsert =new SqlCommand("INSERT INTO Table1(ColX,ColY) VALUES @x,@y",conX); cmdInsert.Transaction=tran; cmdInsert.ExecuteNonQuery(); SqlCommand cmdSelect=new SqlCOmmand("SELECT * FROM Table1",conX); cmdSelect.Transaction=tran; SqlDataReader dtr=cmdSelect.ExecuteReader(); //read stuff from dtr dtr.Close(); cmdInsert=new SqlCommand("UPDATE Table2 set ColA=@a",conX); cmdInsert.Transaction=tran; cmdInsert.ExecuteNonQuery(); //display MiscMessage tran.Commit(); //display SuccessMessage } catch(Exception x) { tran.Rollback(); //display x.Message } finally { conX.Close(); } So, everything seems to work until MiscMessage. Then, after a while (maybe 15-ish seconds?) x.Message pops up, saying that: "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding." So something wrong with my trans.Commit()? The database is not updated so I assume the trans.Rollback works... I have read that deadlocks can cause timeouts...is this problem cause by my SELECT statement selecting from Table1, which is being used by the first INSERT statement? If so, what should I do? If that ain't the problem, what is?

    Read the article

  • C# ASP.NET Binding Controls via Generic Method

    - by OverTech
    I have a few web applications that I maintain and I find myself very often writing the same block of code over and over again to bind a GridView to a data source. I'm trying to create a Generic method to handle data binding but I'm having trouble getting it to work with Repeaters and DataLists. Here is the Generic method I have so far: public void BindControl<T>(T control, SqlCommand sql) where T : System.Web.UI.WebControls.BaseDataBoundControl { cmd = sql; cn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { control.DataSource = dr; control.DataBind(); } dr.Close(); cn.Close(); } That way I can just define my CommandText then make a call to "BindControls(myGridView, cmd)" instead of retyping this same basic block of code every time I need to bind a grid. The problem is, this doesn't work with Repeaters or DataLists. Each of these controls inherit their respective "DataSource" and "DataBind" methods from different classes. Someone on another forum suggested that I implement an interface, but I'm not sure how to make that work either. The GridView, Datalist and Repeater get their respective "DataBind" methods from BaseDataBoundControl, BaseDataList, and Repeater classes. How would I go about creating a single interface to tie them all together? Or am I better off just using 3 overloads for this method? Dave

    Read the article

  • populate checkboxes with database.

    - by amby
    Hi, I have to poulate checkboxes with data coming from database but no checkbox is showing on my page. please give me correct way to do that. in C# file page_load method i m doing this: public partial class dbTest1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string Server = "al2222"; string Username = "hshshshsh"; string Password = "sjjssjs"; string Database = "database1"; string ConnectionString = "Data Source=" + Server + ";"; ConnectionString += "User ID=" + Username + ";"; ConnectionString += "Password=" + Password + ";"; ConnectionString += "Initial Catalog=" + Database; string query = "Select * from Customer_Order where orderNumber = 17"; using (SqlConnection conn = new SqlConnection(ConnectionString)) { using (SqlCommand cmd = new SqlCommand(query, conn)) { conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { if (!IsPostBack) { Interests.DataSource = dr; Interests.DataTextField = "OptionName"; Interests.DataValueField = "OptionName"; Interests.DataBind(); } } conn.Close(); conn.Dispose(); } } } } and in .aspx using this: <asp:CheckBoxList ID="Interests" runat="server"></asp:CheckBoxList> please tell me correct way to do that.

    Read the article

  • sql statement supposed to have 2 distinct rows, but only 1 is returned

    - by jello
    I have an sql statement that is supposed to return 2 rows. the first with psychological_id = 1, and the second, psychological_id = 2. here is the sql statement select * from psychological where patient_id = 12 and symptom = 'delire'; But with this code, with which I populate an array list with what is supposed to be 2 different rows, two rows exist, but with the same values: the second row. OneSymptomClass oneSymp = new OneSymptomClass(); ArrayList oneSympAll = new ArrayList(); string connStrArrayList = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\PatientMonitoringDatabase.mdf; " + "Initial Catalog=PatientMonitoringDatabase; " + "Integrated Security=True"; string queryStrArrayList = "select * from psychological where patient_id = " + patientID.patient_id + " and symptom = '" + SymptomComboBoxes[tag].SelectedItem + "';"; using (var conn = new SqlConnection(connStrArrayList)) using (var cmd = new SqlCommand(queryStrArrayList, conn)) { conn.Open(); using (SqlDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { oneSymp.psychological_id = Convert.ToInt32(rdr["psychological_id"]); oneSymp.patient_history_date_psy = (DateTime)rdr["patient_history_date_psy"]; oneSymp.strength = Convert.ToInt32(rdr["strength"]); oneSymp.psy_start_date = (DateTime)rdr["psy_start_date"]; oneSymp.psy_end_date = (DateTime)rdr["psy_end_date"]; oneSympAll.Add(oneSymp); } } conn.Close(); } OneSymptomClass testSymp = oneSympAll[0] as OneSymptomClass; MessageBox.Show(testSymp.psychological_id.ToString()); the message box outputs "2", while it's supposed to output "1". anyone got an idea what's going on?

    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

  • What's the most DRY-appropriate way to execute an SQL command?

    - by Sean U
    I'm looking to figure out the best way to execute a database query using the least amount of boilerplate code. The method suggested in the SqlCommand documentation: private static void ReadOrderData(string connectionString) { string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); try { while (reader.Read()) { Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1])); } } finally { reader.Close(); } } } mostly consists of code that would have to be repeated in every method that interacts with the database. I'm already in the habit of factoring out the establishment of a connection, which would yield code more like the following. (I'm also modifying it so that it returns data, in order to make the example a bit less trivial.) private SQLConnection CreateConnection() { var connection = new SqlConnection(_connectionString); connection.Open(); return connection; } private List<int> ReadOrderData() { using(var connection = CreateConnection()) using(var command = connection.CreateCommand()) { command.CommandText = "SELECT OrderID FROM dbo.Orders;"; using(var reader = command.ExecuteReader()) { var results = new List<int>(); while(reader.Read()) results.Add(reader.GetInt32(0)); return results; } } } That's an improvement, but there's still enough boilerplate to nag at me. Can this be reduced further? In particular, I'd like to do something about the first two lines of the procedure. I don't feel like the method should be in charge of creating the SqlCommand. It's a tiny piece of repetition as it is in the example, but it seems to grow if transactions are being managed manually or timeouts are being altered or anything like that.

    Read the article

  • im unable to validate a login of users ,since if im entering the wrong values my datareader is not getting executed y ?

    - by Salman_Khan
    //code private void glassButton1_Click(object sender, EventArgs e) { if (textBox1.Text == "" || textBox1.Text == "" || comboBox1.SelectedIndex == 0) { Message m = new Message(); m.ShowDialog(); } else { try { con.ConnectionString = "Data source=BLACK-PEARL;Initial Catalog=LIFELINE ;User id =sa; password=143"; con.Open(); SqlCommand cmd = new SqlCommand("Select LoginID,Password,Department from Login where LoginID=@loginID and Password=@Password and Department=@Department", con); cmd.Parameters.Add(new SqlParameter("@loginID", textBox1.Text)); cmd.Parameters.Add(new SqlParameter("@Password", textBox2.Text)); cmd.Parameters.Add(new SqlParameter("@Department", comboBox1.Text)); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { string Strname = dr[0].ToString(); string StrPass = dr[1].ToString(); string StrDept = dr[2].ToString(); if(dr[2].ToString().Equals(comboBox1.Text)&&dr[0].ToString().Equals(textBox1.Text)&&dr[1].ToString().Equals(textBox2.Text)) { MessageBox.Show("Welcome"); } else { MessageBox.Show("Please Enter correct details"); } } dr.Close(); } catch (Exception ex) { MessageBox.Show("Exception" + ex); } finally { con.Close(); } } }

    Read the article

  • Providing custom database functionality to custom asp.net membership provider

    - by IrfanRaza
    Hello friends, I am creating custom membership provider for my asp.net application. I have also created a separate class "DBConnect" that provides database functionality such as Executing SQL statement, Executing SPs, Executing SPs or Query and returning SqlDataReader and so on... I have created instance of DBConnect class within Session_Start of Global.asax and stored to a session. Later using a static class I am providing the database functionality throughout the application using the same single session. In short I am providing a single point for all database operations from any asp.net page. I know that i can write my own code to connect/disconnect database and execute SPs within from the methods i need to override. Please look at the code below - public class SGI_MembershipProvider : MembershipProvider { ...... public override bool ChangePassword(string username, string oldPassword, string newPassword) { if (!ValidateUser(username, oldPassword)) return false; ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true); OnValidatingPassword(args); if (args.Cancel) { if (args.FailureInformation != null) { throw args.FailureInformation; } else { throw new Exception("Change password canceled due to new password validation failure."); } } ..... //Database connectivity and code execution to change password. } .... } MY PROBLEM - Now what i need is to execute the database part within all these overriden methods from the same database point as described on the top. That is i have to pass the instance of DBConnect existing in the session to this class, so that i can access the methods. Could anyone provide solution on this. There might be some better techniques i am not aware of that. The approach i am using might be wrong. Your suggessions are always welcome. Thanks for sharing your valuable time.

    Read the article

  • Procedure expects parameter which was not supplied.

    - by Tony Peterson
    I'm getting the error when accessing a Stored Procedure in SQL Server Server Error in '/' Application. Procedure or function 'ColumnSeek' expects parameter '@template', which was not supplied. This is happening when I call a Stored Procedure with a parameter through .net's data connection to sql (System.data.SqlClient), even though I am supplying the parameter. Here is my code. SqlConnection sqlConn = new SqlConnection(connPath); sqlConn.Open(); // METADATA RETRIEVAL string sqlCommString = "QCApp.dbo.ColumnSeek"; SqlCommand metaDataComm = new SqlCommand(sqlCommString, sqlConn); metaDataComm.CommandType = CommandType.StoredProcedure; SqlParameter sp = metaDataComm.Parameters.Add("@template", SqlDbType.VarChar, 50); sp.Value = Template; SqlDataReader metadr = metaDataComm.ExecuteReader(); And my Stored Procedure is: USE [QCApp] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[ColumnSeek] @template varchar(50) AS EXEC('SELECT Column_Name, Data_Type FROM [QCApp].[INFORMATION_SCHEMA].[COLUMNS] WHERE TABLE_NAME = ' + @template); I'm trying to figure out what I'm doing wrong here. Edit: As it turns out, Template was null because I was getting its value from a parameter passed through the URL and I screwed up the url param passing (I was using @ for and instead of &)

    Read the article

  • Store multiple values in a session variable

    - by user458790
    Hi, Before I ask my doubt, please consider this scenario that a user on my website have a profileID. With this profileID are associated some pluginID's. For eg: User1 might have 2, 3 and 5 plugins associated with its profile. When the user logs in, I store the profileID of the user in a session variable cod. At a certain page, the user tries to edit the plugins associated with his profile. So, on that page, I have retrieve those pluginID's from the DB. I have applied this code but this fetches only the maximum pluginID from the DB and not all the pluginID's. SqlCommand cmd1 = new SqlCommand("select plugin_id from profiles_plugins where id=(select id from profiles_plugins where profile_id=" + Convert.ToInt32(Session["cod"]) + ")", con); SqlDataReader dr1 = cmd1.ExecuteReader(); if (dr1.HasRows) { while (dr1.Read()) { Session["edp1"] = Convert.ToInt32(dr1[0]); } } dr1.Close(); cmd1.Dispose(); I was trying to figure out how can I store multiple pluginID's in this session variable? Thanks

    Read the article

  • How do I change or add data to a data repeater and get it to display in ASP.NET

    - by CowKingDeluxe
    Here is my code-behind, this adds the "OakTreeName" to the datarepeater. There's about 200 of them. Dim cmd As New SqlClient.SqlCommand("OakTree_Load", New SqlClient.SqlConnection(ConnStr)) cmd.CommandType = CommandType.StoredProcedure cmd.Connection.Open() Dim datareader As SqlClient.SqlDataReader = cmd.ExecuteReader() OakTree_Thumb_Repeater.DataSource = datareader OakTree_Thumb_Repeater.DataBind() cmd.Connection.Close() Here is essentially what I'd like to do with my markup: <ContentTemplate> <asp:Repeater ID="OakTree_Thumb_Repeater" runat="server"> <ItemTemplate> <asp:ImageButton ImageUrl="<%# Container.DataItem("OakTreeName") %>" AlternateText="" runat="server" /> <!-- Or I'd like to do it this way by adding a custom variable to the data repeater --> <asp:ImageButton ImageUrl="<%# Container.DataItem("OakTreeThumbURL") %>" AlternateText="" runat="server" /> </ItemTemplate> </asp:Repeater> </ContentTemplate> I would like to manipulate the "OakTreeName" variable before it gets placed into the item template. Basically I need to manipulate the "OakTreeName" variable and then input it as the ImageURL for the imagebutton within the item template. How do I do this? Am I approaching this wrong? Is there a way to manipulate the item template from code-behind before it gets displayed for each round of variables in the data repeater?

    Read the article

  • Assigning values to the lable through database depending on listbox values

    - by SurajVitekar
    I want to assign the values of five labels from database regarding to values selected in listbox. The db query returns single column with multiple records. Please help. I'm working with C# 2010 and MS SQL. My current code is: private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { try { String c1, c2; c1 = "NULL"; MessageBox.Show("LB index :"+listBox1.SelectedIndex.ToString()); //p = listBox1.SelectedItem.ToString(); SqlConnection con = new SqlConnection(); con.ConnectionString = "Data Source=localhost;Initial Catalog=eVoting;Integrated Security=True;Pooling=False"; con.Open(); MessageBox.Show("List bOx sect :"+listBox1.SelectedValue.ToString()); SqlCommand cmd = new SqlCommand("select Firstname from candidates where position ='" + listBox1.SelectedValue.ToString() + "'", con); int index = 0; SqlDataReader reader = cmd.ExecuteReader(); while(reader.Read()) { if (index == 0) { c1 = reader[index].ToString(); radioButton1.Text = c1; } if (index == 1) { c1 = reader[index].ToString(); radioButton2.Text = c1; } if (index == 2) { c1 = reader[index].ToString(); radioButton3.Text = c1; } if (index == 3) { c1 = reader[index].ToString(); radioButton4.Text = c1; } if (index == 4) { c1 = reader[index].ToString(); radioButton4.Text = c1; } if (index == 5) { c1 = reader[index].ToString(); radioButton5.Text = c1; } MessageBox.Show("c1 :" + c1); index++; } } catch (Exception E) { } }

    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

  • What is the best way to embed SQL in VB.NET.

    - by Amy P
    I am looking for information on the best practices or project layout for software that uses SQL embedded inside VB.NET or C#. The software will connect to a full SQL DB. The software was written in VB6 and ported to VB.NET, we want to update it to use .NET functionality but I am not sure where to start with my research. We are using Visual Studio 2005. All database manipulations are done from VB. Update: To clarify. We are currently using SqlConnection, SqlDataAdapter, SqlDataReader to connect to the database. What I mean by embed is that the SQL stored procedures are scripted inside our VB code and then run on the db. All of our tables, stored procs, views, etc are all manipulated in the VB code. The layout of our code is quite messy. I am looking for a better architecture or pattern that we can use to organize our code. Can you recommend any books, webpages, topics that I can google, etc to help me better understand the best way for us to do this.

    Read the article

  • Is this method a good aproach to get SQL values from C#?

    - by MadBoy
    I have this little method that i use to get stuff from SQL. I either call it with varSearch = "" or varSearch = "something". I would like to know if having method written this way is best or would it be better to split it into two methods (by overloading), or maybe i could somehow parametrize whole WHERE clausule? private void sqlPobierzKontrahentDaneKlienta(ListView varListView, string varSearch) { varListView.BeginUpdate(); varListView.Items.Clear(); string preparedCommand; if (varSearch == "") { preparedCommand = @" SELECT t1.[KlienciID], CASE WHEN t2.[PodmiotRodzaj] = 'Firma' THEN t2.[PodmiotFirmaNazwa] ELSE t2.[PodmiotOsobaNazwisko] + ' ' + t2.[PodmiotOsobaImie] END AS 'Nazwa' FROM [BazaZarzadzanie].[dbo].[Klienci] t1 INNER JOIN [BazaZarzadzanie].[dbo].[Podmioty] t2 ON t1.[PodmiotID] = t2.[PodmiotID] ORDER BY t1.[KlienciID]"; } else { preparedCommand = @" SELECT t1.[KlienciID], CASE WHEN t2.[PodmiotRodzaj] = 'Firma' THEN t2.[PodmiotFirmaNazwa] ELSE t2.[PodmiotOsobaNazwisko] + ' ' + t2.[PodmiotOsobaImie] END AS 'Nazwa' FROM [BazaZarzadzanie].[dbo].[Klienci] t1 INNER JOIN [BazaZarzadzanie].[dbo].[Podmioty] t2 ON t1.[PodmiotID] = t2.[PodmiotID] WHERE t2.[PodmiotOsobaNazwisko] LIKE @searchValue OR t2.[PodmiotFirmaNazwa] LIKE @searchValue OR t2.[PodmiotOsobaImie] LIKE @searchValue ORDER BY t1.[KlienciID]"; } using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails)) using (SqlCommand sqlQuery = new SqlCommand(preparedCommand, varConnection)) { sqlQuery.Parameters.AddWithValue("@searchValue", "%" + varSearch + "%"); using (SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader()) if (sqlQueryResult != null) { while (sqlQueryResult.Read()) { string varKontrahenciID = sqlQueryResult["KlienciID"].ToString(); string varKontrahent = sqlQueryResult["Nazwa"].ToString(); ListViewItem item = new ListViewItem(varKontrahenciID, 0); item.SubItems.Add(varKontrahent); varListView.Items.AddRange(new[] {item}); } } } varListView.EndUpdate(); }

    Read the article

  • Value is zero after filter SQL in C#

    - by Chuki2
    I`m new in C#.. I have write function to filter department. And this function will return idDepartment. New problem is, department keep value "System.Windows.Forms.Label, Text : ADMIN ", that`s why i got zero. So how can i take "ADMIN" only and keep to department? Update : public partial class frmEditStaff : Form { private string connString; private string userId, department; //Department parameter coming from here private string conString = "Datasource"; public frmEditStaff(string strUserID, string strPosition) { InitializeComponent(); //Pass value from frmListStaff to userID text box tbStaffId.Text = strUserID.ToString(); userId = strUserID.ToString(); department = strPosition.ToString(); } This code below is working, don`t have any problem. public int lookUpDepart() { int idDepart=0; using (SqlConnection openCon = new SqlConnection(conString)) { string lookUpDepartmenId = "SELECT idDepartment FROM tbl_department WHERE department = '" + department + "';"; openCon.Open(); using (SqlCommand querylookUpDepartmenId = new SqlCommand(lookUpDepartmenId, openCon)) { SqlDataReader read = querylookUpDepartmenId.ExecuteReader(); while (read.Read()) { idDepart = int.Parse(read[0].ToString()); break; } } openCon.Close(); return idDepart; } } Thanks for help. Happy nice day!

    Read the article

  • Microsoft CRM Dynamics Install

    - by Pino
    Trying to install CRM4.0 on Windows Small Business Server. We get through the isntall process (Setting up database, website, AD etc) when we clikc install though the following error is dumped to the log file, anyone point us in the right directon? 13:49:07| Info| Win32Exception: 1635 13:49:07| Error| Failed to revoke temporary database access.System.Data.SqlClient.SqlException: Cannot open database "MSCRM_CONFIG" requested by the login. The login failed. Login failed for user 'SCHIP\administrator'. 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.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.SqlClient.SqlConnection.Open() at Microsoft.Crm.CrmDbConnection.Open() at Microsoft.Crm.Setup.Database.SharedDatabaseUtility.DeleteDBUser(String sqlServerName, String databaseName, String user, CrmDBConnectionType connectionType) at Microsoft.Crm.Setup.Server.RevokeConfigDBDatabaseAccessAction.Do(IDictionary parameters) 13:49:07| Error| HResult=80004005 Install exception.System.Exception: Action Microsoft.Crm.Setup.Server.MsiInstallServerAction failed. --- System.ComponentModel.Win32Exception: This update package could not be opened. Verify that the update package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer update package at Microsoft.Crm.Setup.Common.Utility.MsiUtility.InstallProduct(String packagePath, String commandLine) at Microsoft.Crm.Setup.Server.MsiInstallServerAction.Do(IDictionary parameters) at Microsoft.Crm.Setup.Common.Action.ExecuteAction(Action action, IDictionary parameters, Boolean undo) --- End of inner exception stack trace --- at Microsoft.Crm.Setup.Common.Action.ExecuteAction(Action action, IDictionary parameters, Boolean undo) at Microsoft.Crm.Setup.Common.Installer.Install(IDictionary stateSaver) at Microsoft.Crm.Setup.Common.ComposedInstaller.InternalInstall(IDictionary stateSaver) at Microsoft.Crm.Setup.Common.ComposedInstaller.Install(IDictionary stateSaver) at Microsoft.Crm.Setup.Server.ServerSetup.Install(IDictionary data) at Microsoft.Crm.Setup.Server.ServerSetup.Run() 13:49:07| Info| Microsoft Dynamics CRM Server install Failed. 13:49:07| Info| Microsoft Dynamics CRM Server Setup did not complete successfully. Action Microsoft.Crm.Setup.Server.MsiInstallServerAction failed. This update package could not be opened. Verify that the update package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer update package

    Read the article

  • Setup MSSQL replication with peer to peer topology: problem setting up Conflict Detection

    - by Roel
    Hi, I'm setting up a SQL Replication strategy, using MSSQL2008 with peer-to-peer publications (2 servers, each one subscribes to the other). I followed this HOWTO from MSDN, and the setup seems to be working fine: add a record to one table on server A, query on server B shows the new record. So far, so good. So far I only have one table 'Templates': Id PK (calculated field) NodeId int default 1/2 (Server A = 1, Server B = 2) LocalId int autoid Name nvarchar(100) Now, I would like to enable 'Conflict detection', which should be enabled by default. But every time I try to save the 'Conflict Detection' feature in the Publication Properties I get the following error: Cannot save Peer conflict detection properties. An exception occurred while executing a Transact-SQL statement or batch.(Microsoft.SqlServer.ConnectionInfo) Program Location: at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType) at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand) at Microsoft.SqlServer.Replication.ReplicationObject.ExecCommand(String commandIn) at Microsoft.SqlServer.Replication.TransPublication.SetPeerConflictDetection(Boolean enablePeerConflictDetection, Int32 peerOriginatorID) at Microsoft.SqlServer.Management.UI.PubPropSubscriptionOptions.SaveP2PConflictDetection() at Microsoft.SqlServer.Management.UI.PubPropSubscriptionOptions.SaveProperties(ExecutionMode& executionResult) Column name 'Id' does not exist in the target table or view. Changed database context to 'TestDB'. (.Net SqlClient Data Provider) For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.00.2531&EvtSrc=MSSQLServer&EvtID=1911&LinkId=20476 Server Name: SERVER_A Error Number: 1911 Severity: 16 State: 1 Line Number: 2 Program Location: 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.RunExecuteNonQueryTds(String methodName, Boolean async) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType) Now, I googled the hell out of this error, and nothing shows up. I also can't seem to find out what the exact target table of the error "Column name 'Id' does not exist..." is. Has anyone every done this successfully? Am I missing something? Having this setup without conflict detection feels pretty useless... EDIT OK, so after some more research and setting up with different databases etc, I found out that the calculated 'Id' column of the Templates table is the culprit. I don't know why, but the replication doesn't seem to allow calculated columns (which are also primary key). It works now too, without the 'Id' column, and using the NodeId and LocalId as a combined PK. So now the question is, why isn't it allowed to have a calculated column as PK for replication with conflict detection?

    Read the article

  • Could not load type 'Default.DataMatch' in DataMatch.aspx file

    - by salvationishere
    I am developing a C# VS 2008 / SQL Server 2008 website, but now I am getting the above error when I build it. I included the Default.aspx, Default.aspx.cs, DataMatch.aspx, and DataMatch.aspx.cs files below. What do I need to do to fix this? Default.aspx: <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %> ... DataMatch.aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataMatch.aspx.cs" Inherits="_Default.DataMatch" %> ... Default.aspx.cs: using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Collections.Generic; using System.IO; using System.Drawing; using System.ComponentModel; using System.Data.SqlClient; using ADONET_namespace; using System.Security.Principal; //using System.Windows; public partial class _Default : System.Web.UI.Page //namespace AddFileToSQL { //protected System.Web.UI.HtmlControls.HtmlInputFile uploadFile; //protected System.Web.UI.HtmlControls.HtmlInputButton btnOWrite; //protected System.Web.UI.HtmlControls.HtmlInputButton btnAppend; protected System.Web.UI.WebControls.Label Label1; protected static string inputfile = ""; public static string targettable; public static string selection; // Number of controls added to view state protected int default_NumberOfControls { get { if (ViewState["default_NumberOfControls"] != null) { return (int)ViewState["default_NumberOfControls"]; } else { return 0; } } set { ViewState["default_NumberOfControls"] = value; } } protected void uploadFile_onclick(object sender, EventArgs e) { } protected void Load_GridData() { //GridView1.DataSource = ADONET_methods.DisplaySchemaTables(); //GridView1.DataBind(); } protected void btnOWrite_Click(object sender, EventArgs e) { if (uploadFile.PostedFile.ContentLength > 0) { feedbackLabel.Text = "You do not have sufficient access to overwrite table records."; } else { feedbackLabel.Text = "This file does not contain any data."; } } protected void btnAppend_Click(object sender, EventArgs e) { string fullpath = Page.Request.PhysicalApplicationPath; string path = uploadFile.PostedFile.FileName; if (File.Exists(path)) { // Create a file to write to. try { StreamReader sr = new StreamReader(path); string s = ""; while (sr.Peek() > 0) s = sr.ReadLine(); sr.Close(); } catch (IOException exc) { Console.WriteLine(exc.Message + "Cannot open file."); return; } } if (uploadFile.PostedFile.ContentLength > 0) { inputfile = System.IO.File.ReadAllText(path); Session["Message"] = inputfile; Response.Redirect("DataMatch.aspx"); } else { feedbackLabel.Text = "This file does not contain any data."; } } protected void Page_Load(object sender, EventArgs e) { if (Request.IsAuthenticated) { WelcomeBackMessage.Text = "Welcome back, " + User.Identity.Name + "!"; // Reference the CustomPrincipal / CustomIdentity CustomIdentity ident = User.Identity as CustomIdentity; if (ident != null) WelcomeBackMessage.Text += string.Format(" You are the {0} of {1}.", ident.Title, ident.CompanyName); AuthenticatedMessagePanel.Visible = true; AnonymousMessagePanel.Visible = false; if (!Page.IsPostBack) { Load_GridData(); } } else { AuthenticatedMessagePanel.Visible = false; AnonymousMessagePanel.Visible = true; } } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { GridViewRow row = GridView1.SelectedRow; targettable = row.Cells[2].Text; } } DataMatch.aspx.cs: using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ADONET_namespace; //using MatrixApp; //namespace AddFileToSQL //{ public partial class DataMatch : AddFileToSQL._Default { protected System.Web.UI.WebControls.PlaceHolder phTextBoxes; protected System.Web.UI.WebControls.PlaceHolder phDropDownLists; protected System.Web.UI.WebControls.Button btnAnotherRequest; protected System.Web.UI.WebControls.Panel pnlCreateData; protected System.Web.UI.WebControls.Literal lTextData; protected System.Web.UI.WebControls.Panel pnlDisplayData; protected static string inputfile2; static string[] headers = null; static string[] data = null; static string[] data2 = null; static DataTable myInputFile = new DataTable("MyInputFile"); static string[] myUserSelections; static bool restart = false; private DropDownList[] newcol; int @temp = 0; string @tempS = ""; string @tempT = ""; // a Property that manages a counter stored in ViewState protected int NumberOfControls { get { return (int)ViewState["NumControls"]; } set { ViewState["NumControls"] = value; } } private Hashtable ddl_ht { get { return (Hashtable)ViewState["ddl_ht"]; } set { ViewState["ddl_ht"] = value; } } // Page Load private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { ddl_ht = new Hashtable(); this.NumberOfControls = 0; } } // This data comes from input file private void PopulateFileInputTable() { myInputFile.Columns.Clear(); string strInput, newrow; string[] oneRow; DataColumn myDataColumn; DataRow myDataRow; int result, numRows; //Read the input file strInput = Session["Message"].ToString(); data = strInput.Split('\r'); //Headers headers = data[0].Split('|'); //Data for (int i = 0; i < data.Length; i++) { newrow = data[i].TrimStart('\n'); data[i] = newrow; } result = String.Compare(data[data.Length - 1], ""); numRows = data.Length; if (result == 0) { numRows = numRows - 1; } data2 = new string[numRows]; for (int a = 0, b = 0; a < numRows; a++, b++) { data2[b] = data[a]; } // Create columns for (int col = 0; col < headers.Length; col++) { @temp = (col + 1); @tempS = @temp.ToString(); @tempT = "@col"+ @temp.ToString(); myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = headers[col]; myInputFile.Columns.Add(myDataColumn); ddl_ht.Add(@tempT, headers[col]); } // Create new DataRow objects and add to DataTable. for (int r = 0; r < numRows - 1; r++) { oneRow = data2[r + 1].Split('|'); myDataRow = myInputFile.NewRow(); for (int c = 0; c < headers.Length; c++) { myDataRow[c] = oneRow[c]; } myInputFile.Rows.Add(myDataRow); } NumberOfControls = headers.Length; myUserSelections = new string[NumberOfControls]; } //Create display panel private void CreateDisplayPanel() { btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); btnSubmit.Style.Add("top", "200px"); btnSubmit.Style.Add("left", "400px"); newcol = CreateDropDownLists(); for (int counter = 0; counter < NumberOfControls; counter++) { pnlDisplayData.Controls.Add(newcol[counter]); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); pnlDisplayData.Visible = true; pnlDisplayData.FindControl(newcol[counter].ID); } } //Recreate display panel private void RecreateDisplayPanel() { btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); btnSubmit.Style.Add("top", "200px"); btnSubmit.Style.Add("left", "400px"); newcol = RecreateDropDownLists(); for (int counter = 0; counter < NumberOfControls; counter++) { pnlDisplayData.Controls.Add(newcol[counter]); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); pnlDisplayData.Visible = true; pnlDisplayData.FindControl(newcol[counter].ID); } } // Add DropDownList Control to Placeholder private DropDownList[] CreateDropDownLists() { DropDownList[] dropDowns = new DropDownList[NumberOfControls]; for (int counter = 0; counter < NumberOfControls; counter++) { DropDownList ddl = new DropDownList(); SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable); ddl.ID = "DropDownListID" + counter.ToString(); int NumControls = targettable.Length; DataTable dt = new DataTable(); dt.Load(dr2); ddl.DataValueField = "COLUMN_NAME"; ddl.DataTextField = "COLUMN_NAME"; ddl.DataSource = dt; ddl.SelectedIndexChanged += new EventHandler(ddlList_SelectedIndexChanged); ddl.DataBind(); ddl.AutoPostBack = true; ddl.EnableViewState = true; //Preserves View State info on Postbacks dr2.Close(); ddl.Items.Add("IGNORE"); dropDowns[counter] = ddl; } return dropDowns; } protected void ddlList_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; string ID = ddl.ID; } // Add TextBoxes Control to Placeholder private DropDownList[] RecreateDropDownLists() { DropDownList[] dropDowns = new DropDownList[NumberOfControls]; for (int counter = 0; counter < NumberOfControls; counter++) { DropDownList ddl = new DropDownList(); SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable); ddl.ID = "DropDownListID" + counter.ToString(); int NumControls = targettable.Length; DataTable dt = new DataTable(); dt.Load(dr2); ddl.DataValueField = "COLUMN_NAME"; ddl.DataTextField = "COLUMN_NAME"; ddl.DataSource = dt; ddl.SelectedIndexChanged += new EventHandler(ddlList_SelectedIndexChanged); ddl.DataBind(); ddl.AutoPostBack = true; ddl.EnableViewState = false; //Preserves View State info on Postbacks dr2.Close(); ddl.Items.Add("IGNORE"); dropDowns[counter] = ddl; } return dropDowns; } private void CreateLabels() { for (int counter = 0; counter < NumberOfControls; counter++) { Label lbl = new Label(); lbl.ID = "Label" + counter.ToString(); lbl.Text = headers[counter]; lbl.Style["position"] = "absolute"; lbl.Style["top"] = 60 * counter + 10 + "px"; lbl.Style["left"] = 250 + "px"; pnlDisplayData.Controls.Add(lbl); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); } } // Add TextBoxes Control to Placeholder private void RecreateLabels() { for (int counter = 0; counter < NumberOfControls; counter++) { Label lbl = new Label(); lbl.ID = "Label" + counter.ToString(); lbl.Text = headers[counter]; lbl.Style["position"] = "absolute"; lbl.Style["top"] = 60 * counter + 10 + "px"; lbl.Style["left"] = 250 + "px"; pnlDisplayData.Controls.Add(lbl); pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>")); } } // Create TextBoxes and DropDownList data here on postback. protected override void CreateChildControls() { // create the child controls if the server control does not contains child controls this.EnsureChildControls(); // Creates a new ControlCollection. this.CreateControlCollection(); // Here we are recreating controls to persist the ViewState on every post back if (Page.IsPostBack) { RecreateDisplayPanel(); RecreateLabels(); } // Create these conrols when asp.net page is created else { PopulateFileInputTable(); CreateDisplayPanel(); CreateLabels(); } // Prevent dropdownlists and labels from being created again. if (restart == false) { this.ChildControlsCreated = true; } else if (restart == true) { this.ChildControlsCreated = false; } } private void AppendRecords() { switch (targettable) { case "ContactType": for (int r = 0; r < myInputFile.Rows.Count; r++) { resultLabel.Text = ADONET_methods.AppendDataCT(myInputFile.Rows[r], ddl_ht); } break; case "Contact": for (int r = 0; r < myInputFile.Rows.Count; r++) { resultLabel.Text = ADONET_methods.AppendDataC(myInputFile.Rows[r], ddl_ht); } break; case "AddressType": for (int r = 0; r < myInputFile.Rows.Count; r++) { resultLabel.Text = ADONET_methods.AppendDataAT(myInputFile.Rows[r], ddl_ht); } break; default: resultLabel.Text = "You do not have access to modify this table. Please select a different target table and try again."; restart = true; break; //throw new ArgumentOutOfRangeException("targettable type", targettable); } } // Read all the data from TextBoxes and DropDownLists protected void btnSubmit_Click(object sender, System.EventArgs e) { //int cnt = FindOccurence("DropDownListID"); AppendRecords(); pnlDisplayData.Visible = false; btnSubmit.Visible = false; resultLabel.Attributes.Add("style", "align:center"); btnSubmit.Style.Add("top", "auto"); btnSubmit.Style.Add("left", "auto"); btnSubmit.Style.Add("position", "absolute"); int bSubmitPosition = NumberOfControls; btnSubmit.Style.Add("top", System.Convert.ToString(bSubmitPosition)+"px"); resultLabel.Visible = true; Instructions.Visible = false; if (restart == true) { CreateChildControls(); } } private int FindOccurence(string substr) { string reqstr = Request.Form.ToString(); return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion } //}

    Read the article

  • Stored Procedure call with parameters in ASP.NET MVC

    - by cc0
    I have a working controller for another stored procedure in the database, but I am trying to test another. When I request the URL; http://host.com/Map?minLat=0&maxLat=50&minLng=0&maxLng=50 I get the following error message, which is understandable but I can't seem to find out why it occurs; Procedure or function 'esp_GetPlacesWithinGeoSpan' expects parameter '@MinLat', which was not supplied. This is the code I am using. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Data; using System.Text; using System.Data.SqlClient; namespace prototype.Controllers { public class MapController : Controller { //Initial variable definitions //Array with chars to be used with the Trim() methods char[] lastComma = { ',' }; //Minimum and maximum lat/longs for queries float _minLat; float _maxLat; float _minLng; float _maxLng; //Creates stringbuilder object to store SQL results StringBuilder json = new StringBuilder(); //Defines which SQL-server to connect to, which database, and which user SqlConnection con = new SqlConnection(...connection string here...); // // HTTP-GET: /Map/ public string CallProcedure_getPlaces(float minLat, float maxLat, float minLng, float maxLng) { con.Open(); using (SqlCommand cmd = new SqlCommand("esp_GetPlacesWithinGeoSpan", con)) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@MinLat", _minLat); cmd.Parameters.AddWithValue("@MaxLat", _maxLat); cmd.Parameters.AddWithValue("@MinLng", _minLng); cmd.Parameters.AddWithValue("@MaxLng", _maxLng); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { json.AppendFormat("\"{0}\":{{\"c\":{1},\"f\":{2}}},", reader["PlaceID"], reader["PlaceName"], reader["SquareID"]); } } con.Close(); } return "{" + json.ToString().TrimEnd(lastComma) + "}"; } //http://host.com/Map?minLat=0&maxLat=50&minLng=0&maxLng=50 public ActionResult Index(float minLat, float maxLat, float minLng, float maxLng) { _minLat = minLat; _maxLat = maxLat; _minLng = minLng; _maxLng = maxLng; return Content(CallProcedure_getPlaces(_minLat, _maxLat, _minLng, _maxLng)); } } } Any help on resolving this problem would be greatly appreciated.

    Read the article

  • SQL Server 2008: FileStream Insertion Failure w/ .NET 3.5SP1

    - by James Alexander
    I've configured a db w/ a FileStream group and have a table w/ File type on it. When attempting to insert a streamed file and after I create the table row, my query to read the filepath out and the buffer returns a null file path. I can't seem to figure out why though. Here is the table creation script: /****** Object: Table [dbo].[JobInstanceFile] Script Date: 03/22/2010 18:05:36 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[JobInstanceFile]( [JobInstanceFileId] [int] IDENTITY(1,1) NOT NULL, [JobInstanceId] [int] NOT NULL, [File] [varbinary](max) FILESTREAM NULL, [FileId] [uniqueidentifier] ROWGUIDCOL NOT NULL, [Created] [datetime] NOT NULL, CONSTRAINT [PK_JobInstanceFile] PRIMARY KEY CLUSTERED ( [JobInstanceFileId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] FILESTREAM_ON [JobInstanceFilesGroup], UNIQUE NONCLUSTERED ( [FileId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] FILESTREAM_ON [JobInstanceFilesGroup] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[JobInstanceFile] ADD DEFAULT (newid()) FOR [FileId] GO Here's my proc I call to create the row before streaming the file: /****** Object: StoredProcedure [dbo].[JobInstanceFileCreate] Script Date: 03/22/2010 18:06:23 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO create proc [dbo].[JobInstanceFileCreate] @JobInstanceId int, @Created datetime as insert into JobInstanceFile (JobInstanceId, FileId, Created) values (@JobInstanceId, newid(), @Created) select scope_identity() GO And lastly, here's the code I'm using: public int CreateJobInstanceFile(int jobInstanceId, string filePath) { using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConsumerMarketingStoreFiles"].ConnectionString)) using (var fileStream = new FileStream(filePath, FileMode.Open)) { connection.Open(); var tran = connection.BeginTransaction(IsolationLevel.ReadCommitted); try { //create the JobInstanceFile instance var command = new SqlCommand("JobInstanceFileCreate", connection) { Transaction = tran }; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@JobInstanceId", jobInstanceId); command.Parameters.AddWithValue("@Created", DateTime.Now); int jobInstanceFileId = Convert.ToInt32(command.ExecuteScalar()); //read out the filestream transaction context to stream the file for storage command.CommandText = "select [File].PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() from JobInstanceFile where JobInstanceFileId = @JobInstanceFileId"; command.CommandType = CommandType.Text; command.Parameters.AddWithValue("@JobInstanceFileId", jobInstanceFileId); using (SqlDataReader dr = command.ExecuteReader()) { dr.Read(); //get the file path we're writing out to string writePath = dr.GetString(0); using (var writeStream = new SqlFileStream(writePath, (byte[])dr.GetValue(1), FileAccess.ReadWrite)) { //copy from one stream to another byte[] bytes = new byte[65536]; int numBytes; while ((numBytes = fileStream.Read(bytes, 0, 65536)) 0) writeStream.Write(bytes, 0, numBytes); } } tran.Commit(); return jobInstanceFileId; } catch (Exception e) { tran.Rollback(); throw e; } } } Can someone please let me know what I'm doing wrong. In the code, the following expression is returning null for the file path and shouldn't be: //get the file path we're writing out to string writePath = dr.GetString(0); The server is different then the computer the code is running on but the necessary shares appear to be in order and I have also run the following: EXEC sp_configure filestream_access_level, 2 Any help would be greatly appreciated. Thanks!

    Read the article

  • ASP.NET web forms as ASP.NET MVC

    - by lopkiju
    I am sorry for possible misleading about the title, but I have no idea for a proper title. Feel free to edit. Anyway, I am using ASP.NET Web Forms, and maybe this isn't how web forms is intended to be used, but I like to construct and populate HTML elements manually. It gives me more control. I don't use DataBinding and that kind of stuff. I use SqlConnection, SqlCommand and SqlDataReader, set SQL string etc. and read the data from the DataReader. Old school if you like. :) I do create WebControls so that I don't have to copy-paste every time I need some control, but mostly, I need WebControls to render as HTML so I can append that HTML into some other function that renders the final output with the control inside. I know I can render a control with control.RenderControl(writer), but this can only be done in (pre)Render or RenderContents overrides. For example. I have a dal.cs file where is stored all static functions and voids that communicate with the database. Functions mostly return string so that it can be appended into some other function to render the final result. The reason I am doing like this is that I want to separate the coding from the HTML as much as I can so that I don't do <% while (dataReader.Read()) % in HTML and display the data. I moved this into a CodeBehind. I also use this functions to render in the HttpHandler for AJAX response. That works perfectly, but when I want to add a control (ASP.NET Server control (.cs extension, not .ascx)) I don't know how to do that, so I see my self writing the same control as function that returns string or another function inside that control that returns string and replaces a job that would RenderContents do, so that I can call that function when I need control to be appended into a another string. I know this may not be a very good practice. As I see all the tutorials/videos about the ASP.NET MVC, I think it suite my needs as with the MVC you have to construct everything (or most of it) by your self, which I am already doing right now with web forms. After this long intro, I want to ask how can I build my controls so I can use them as I mentioned (return string) or I have to forget about server controls and build the controls as functions and used them that way? Is that even possible with ASP.NET Server Controls (.cs extension) or am I right when I said that I am not using it right. To be clear, I am talking about how to properly use a web forms, but to avoid data binders because I want to construct everything by my self (render HTML in Code Behind). Someone might think that I am appending strings like "some " + "string", which I am not. I am using StringBuilder for that so there's no slowness. Every opinion is welcome.

    Read the article

  • Forms Authentication logs out very quickly , locally works fine !!!

    - by user319075
    Hello to all, There's a problem that i am facing with my hosting company, I use a project that uses FormsAuthentication and the problem is that though it successfully logs in, it logs out VERY QUICKLY, and i don't know what could be the cause of that, so in my web.config file i added those lines: <authentication mode="Forms" > <forms name="Nadim" loginUrl="Login.aspx" defaultUrl="Default.aspx" protection="All" path="/" requireSSL="false"/> </authentication> <authorization> <deny users ="?" /> </authorization> <sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" cookieless="false" timeout="1440"> </sessionState> and this is the code i use in my custom login page : protected void PasswordCustomValidator_ServerValidate(object source, ServerValidateEventArgs args) { try { UsersSqlDataSource.SelectParameters.Clear(); UsersSqlDataSource.SelectCommand = "Select * From Admins Where AdminID='" + IDTextBox.Text + "' and Password='" + PassTextBox.Text + "'"; UsersSqlDataSource.SelectCommandType = SqlDataSourceCommandType.Text; UsersSqlDataSource.DataSourceMode = SqlDataSourceMode.DataReader; reader = (SqlDataReader)UsersSqlDataSource.Select(DataSourceSelectArguments.Empty); if (reader.HasRows) { reader.Read(); if (RememberCheckBox.Checked == true) Page.Response.Cookies["Admin"].Expires = DateTime.Now.AddDays(5); args.IsValid = true; string userData = "ApplicationSpecific data for this user."; FormsAuthenticationTicket ticket1 = new FormsAuthenticationTicket(1, IDTextBox.Text, System.DateTime.Now, System.DateTime.Now.AddMinutes(30), true, userData, FormsAuthentication.FormsCookiePath); string encTicket = FormsAuthentication.Encrypt(ticket1); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); Response.Redirect(FormsAuthentication.GetRedirectUrl(IDTextBox.Text, RememberCheckBox.Checked)); //FormsAuthentication.RedirectFromLoginPage(IDTextBox.Text, RememberCheckBox.Checked); } else args.IsValid = false; } catch (SqlException ex) { ErrorLabel.Text = ex.Message; } catch (InvalidOperationException) { args.IsValid = false; } catch (Exception ex) { ErrorLabel.Text = ex.Message; } Also you will find that line of code: FormsAuthentication.RedirectFromLoginPage(IDTextBox.Text, RememberCheckBox.Checked); is commented because i thought there might be something wrong with the ticket when i log in , so i created it manually , every thing i know i tried but nothing worked, so does anyone have any idea what is the problem ? Thanks in advance, Baher.

    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

< Previous Page | 3 4 5 6 7 8 9  | Next Page >