Search Results

Search found 711 results on 29 pages for 'connectionstring'.

Page 6/29 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Am I the only one this anal / obsessive about code? [closed]

    - by Chris
    While writing a shared lock class for sql server for a web app tonight, I found myself writing in the code style below as I always do: private bool acquired; private bool disposed; private TimeSpan timeout; private string connectionString; private Guid instance = Guid.NewGuid(); private Thread autoRenewThread; Basically, whenever I'm declaring a group of variables or writing a sql statement or any coding activity involving multiple related lines, I always try to arrange them where possible so that they form a bell curve (imagine rotating the text 90deg CCW). As an example of something that peeves the hell out of me, consider the following alternative: private bool acquired; private bool disposed; private string connectionString; private Thread autoRenewThread; private Guid instance = Guid.NewGuid(); private TimeSpan timeout; In the above example, declarations are grouped (arbitrarily) so that the primitive types appear at the top. When viewing the code in Visual Studio, primitive types are a different color than non-primitives, so the grouping makes sense visually, if for no other reason. But I don't like it because the right margin is less of an aesthetic curve. I've always chalked this up to being OCD or something, but at least in my mind, the code is "prettier". Am I the only one?

    Read the article

  • Issue with Autofac 2 and MVC2 using HttpRequestScoped

    - by Page Brooks
    I'm running into an issue with Autofac2 and MVC2. The problem is that I am trying to resolve a series of dependencies where the root dependency is HttpRequestScoped. When I try to resolve my UnitOfWork (which is Disposable), Autofac fails because the internal disposer is trying to add the UnitOfWork object to an internal disposal list which is null. Maybe I'm registering my dependencies with the wrong lifetimes, but I've tried many different combinations with no luck. The only requirement I have is that MyDataContext lasts for the entire HttpRequest. I've posted a demo version of the code for download here. Autofac modules are set up in web.config Global.asax.cs protected void Application_Start() { string connectionString = "something"; var builder = new ContainerBuilder(); builder.Register(c => new MyDataContext(connectionString)).As<IDatabase>().HttpRequestScoped(); builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerDependency(); builder.RegisterType<MyService>().As<IMyService>().InstancePerDependency(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); _containerProvider = new ContainerProvider(builder.Build()); IoCHelper.InitializeWith(new AutofacDependencyResolver(_containerProvider.RequestLifetime)); ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(ContainerProvider)); AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } AutofacDependencyResolver.cs public class AutofacDependencyResolver { private readonly ILifetimeScope _scope; public AutofacDependencyResolver(ILifetimeScope scope) { _scope = scope; } public T Resolve<T>() { return _scope.Resolve<T>(); } } IoCHelper.cs public static class IoCHelper { private static AutofacDependencyResolver _resolver; public static void InitializeWith(AutofacDependencyResolver resolver) { _resolver = resolver; } public static T Resolve<T>() { return _resolver.Resolve<T>(); } } UnitOfWork.cs public interface IUnitOfWork : IDisposable { void Commit(); } public class UnitOfWork : IUnitOfWork { private readonly IDatabase _database; public UnitOfWork(IDatabase database) { _database = database; } public static IUnitOfWork Begin() { return IoCHelper.Resolve<IUnitOfWork>(); } public void Commit() { System.Diagnostics.Debug.WriteLine("Commiting"); _database.SubmitChanges(); } public void Dispose() { System.Diagnostics.Debug.WriteLine("Disposing"); } } MyDataContext.cs public interface IDatabase { void SubmitChanges(); } public class MyDataContext : IDatabase { private readonly string _connectionString; public MyDataContext(string connectionString) { _connectionString = connectionString; } public void SubmitChanges() { System.Diagnostics.Debug.WriteLine("Submiting Changes"); } } MyService.cs public interface IMyService { void Add(); } public class MyService : IMyService { private readonly IDatabase _database; public MyService(IDatabase database) { _database = database; } public void Add() { // Use _database. } } HomeController.cs public class HomeController : Controller { private readonly IMyService _myService; public HomeController(IMyService myService) { _myService = myService; } public ActionResult Index() { // NullReferenceException is thrown when trying to // resolve UnitOfWork here. // Doesn't always happen on the first attempt. using(var unitOfWork = UnitOfWork.Begin()) { _myService.Add(); unitOfWork.Commit(); } return View(); } public ActionResult About() { return View(); } }

    Read the article

  • What is the reason of "Transaction context in use by another session"

    - by Shrike
    Hi, I'm looking for a description of the root of this error: "Transaction context in use by another session". I get it sometimes in one of my unittests so I can't provider repro code. But I wonder what is "by design" reason for the error. I've found this post: http://blogs.msdn.com/asiatech/archive/2009/08/10/system-transaction-may-fail-in-multiple-thread-environment.aspx and also that: http://msdn.microsoft.com/en-us/library/ff649002.aspx But I can't understand what "Multiple threads sharing the same transaction in a transaction scope will cause the following exception: 'Transaction context in use by another session.' " means. All words are understandable but not the point. I actually can share a system transaction between threads. And there is even special mechanism for this - DependentTransaction class and Transaction.DependentClone method. I'm trying to reproduce a usecase from the first post: 1. Main thread creates DTC transaction, receives DependentTransaction (created using Transaction.Current.DependentClone on the main thread 2. Child thread 1 enlists in this DTC transaction by creating a transaction scope based on the dependent transaction (passed via constructor) 3. Child thread 1 opens a connection 4. Child thread 2 enlists in DTC transaction by creating a transaction scope based on the dependent transaction (passed via constructor) 5. Child thread 2 opens a connection with such code: using System; using System.Threading; using System.Transactions; using System.Data; using System.Data.SqlClient; public class Program { private static string ConnectionString = "Initial Catalog=DB;Data Source=.;User ID=user;PWD=pwd;"; public static void Main() { int MAX = 100; for(int i =0; i< MAX;i++) { using(var ctx = new TransactionScope()) { var tx = Transaction.Current; // make the transaction distributed using (SqlConnection con1 = new SqlConnection(ConnectionString)) using (SqlConnection con2 = new SqlConnection(ConnectionString)) { con1.Open(); con2.Open(); } showSysTranStatus(); DependentTransaction dtx = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete); Thread t1 = new Thread(o => workCallback(dtx)); Thread t2 = new Thread(o => workCallback(dtx)); t1.Start(); t2.Start(); t1.Join(); t2.Join(); ctx.Complete(); } trace("root transaction completes"); } } private static void workCallback(DependentTransaction dtx) { using(var txScope1 = new TransactionScope(dtx)) { using (SqlConnection con2 = new SqlConnection(ConnectionString)) { con2.Open(); trace("connection opened"); showDbTranStatus(con2); } txScope1.Complete(); } trace("dependant tran completes"); } private static void trace(string msg) { Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " : " + msg); } private static void showSysTranStatus() { string msg; if (Transaction.Current != null) msg = Transaction.Current.TransactionInformation.DistributedIdentifier.ToString(); else msg = "no sys tran"; trace( msg ); } private static void showDbTranStatus(SqlConnection con) { var cmd = con.CreateCommand(); cmd.CommandText = "SELECT 1"; var c = cmd.ExecuteScalar(); trace("@@TRANCOUNT = " + c); } } It fails on Complete's call of root TransactionScope. But error is different: Unhandled Exception: System.Transactions.TransactionInDoubtException: The transaction is in doubt. --- pired. The timeout period elapsed prior to completion of the operation or the server is not responding. To sum up: I want to understand what "Transaction context in use by another session" means and how to reproduce it.

    Read the article

  • About global.asax and the events there

    - by eski
    So what i'm trying to understand is the whole global.asax events. I doing a simple counter that records website visits. I am using MSSQL. Basicly i have two ints. totalNumberOfUsers - The total visist from begining. currentNumberOfUsers - Total of users viewing the site at the moment. So the way i understand global.asax events is that every time someone comes to the site "Session_Start" is fired once. So once per user. "Application_Start" is fired only once the first time someone comes to the site. Going with this i have my global.asax file here. <script runat="server"> string connectionstring = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString; void Application_Start(object sender, EventArgs e) { // Code that runs on application startup Application.Lock(); Application["currentNumberOfUsers"] = 0; Application.UnLock(); string sql = "Select c_hit from v_counter where (id=1)"; SqlConnection connect = new SqlConnection(connectionstring); SqlCommand cmd = new SqlCommand(sql, connect); cmd.Connection.Open(); cmd.ExecuteNonQuery(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Application.Lock(); Application["totalNumberOfUsers"] = reader.GetInt32(0); Application.UnLock(); } reader.Close(); cmd.Connection.Close(); } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started Application.Lock(); Application["totalNumberOfUsers"] = (int)Application["totalNumberOfUsers"] + 1; Application["currentNumberOfUsers"] = (int)Application["currentNumberOfUsers"] + 1; Application.UnLock(); string sql = "UPDATE v_counter SET c_hit = @hit WHERE c_type = 'totalNumberOfUsers'"; SqlConnection connect = new SqlConnection(connectionstring); SqlCommand cmd = new SqlCommand(sql, connect); SqlParameter hit = new SqlParameter("@hit", SqlDbType.Int); hit.Value = Application["totalNumberOfUsers"]; cmd.Parameters.Add(hit); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. Application.Lock(); Application["currentNumberOfUsers"] = (int)Application["currentNumberOfUsers"] - 1; Application.UnLock(); } </script> In the page_load i have this protected void Page_Load(object sender, EventArgs e) { l_current.Text = Application["currentNumberOfUsers"].ToString(); l_total.Text = Application["totalNumberOfUsers"].ToString(); } So if i understand this right, every time someone comes to the site both the currentNumberOfUsers and totalNumberOfUsers are incremented with 1. But when the session is over the currentNumberOfUsers is decremented with 1. If i go to the site with 3 types of browsers with the same computer i should have 3 in hits on both counters. Doing this again after hours i should have 3 in current and 6 in total, right ? The way its working right now is the current goes up to 2 and the total is incremented on every postback on IE and Chrome but not on firefox. And one last thing, is this the same thing ? Application["value"] = 0; value = Application["value"] //OR Application.Set("Value", 0); Value = Application.Get("Value");

    Read the article

  • ASP.NET MVC3 checkbox dropdownlist create [migrated]

    - by user95381
    i'm new in asp.net MVC and I/m use view model to poppulate the dropdown list and group of checkboxes. I use SQL Server 2012, where have many to many relationships between Students - Books; Student - Cities. I need collect StudentName, one city and many books for one student. I have next questions: 1. How can I get the values from database to my StudentBookCityViewModel? 2. How can I save the values to my database in [HttpPost] Create method? Here is the code: MODEL public class Student { public int StudentId { get; set; } public string StudentName { get; set; } public ICollection<Book> Books { get; set; } public ICollection<City> Cities { get; set; } } public class Book { public int BookId { get; set; } public string BookName { get; set; } public bool IsSelected { get; set; } public ICollection<Student> Students { get; set; } } public class City { public int CityId { get; set; } public string CityName { get; set; } public bool IsSelected { get; set; } public ICollection<Student> Students { get; set; } } VIEW MODEL public class StudentBookCityViewModel { public string StudentName { get; set; } public IList<Book> Books { get; set; } public StudentBookCityViewModel() { Books = new[] { new Book {BookName = "Title1", IsSelected = false}, new Book {BookName = "Title2", IsSelected = false}, new Book {BookName = "Title3", IsSelected = false} }.ToList(); } public string City { get; set; } public IEnumerable<SelectListItem> CityValues { get { return new[] { new SelectListItem {Value = "Value1", Text = "Text1"}, new SelectListItem {Value = "Value2", Text = "Text2"}, new SelectListItem {Value = "Value3", Text = "Text3"} }; } } } Context public class EFDbContext : DbContext{ public EFDbContext(string connectionString) { Database.Connection.ConnectionString = connectionString; } public DbSet<Book> Books { get; set; } public DbSet<Student> Students { get; set; } public DbSet<City> Cities { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Book>() .HasMany(x => x.Students).WithMany(x => x.Books) .Map(x => x.MapLeftKey("BookId").MapRightKey("StudentId").ToTable("StudentBooks")); modelBuilder.Entity<City>() .HasMany(x => x.Students).WithMany(x => x.Cities) .Map(x => x.MapLeftKey("CityId").MapRightKey("StudentId").ToTable("StudentCities")); } } Controller public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create() { //I don't understand how I can save values to db context.SaveChanges(); return RedirectToAction("Index"); } View @model UsingEFNew.ViewModels.StudentBookCityViewModel @using (Html.BeginForm()) { Your Name: @Html.TextBoxFor(model = model.StudentName) <div>Genre:</div> <div> @Html.DropDownListFor(model => model.City, Model.CityValues) </div> <div>Books:</div> <div> @for (int i = 0; i < Model.Books.Count; i++) { <div> @Html.HiddenFor(x => x.Books[i].BookId) @Html.CheckBoxFor(x => x.Books[i].IsSelected) @Html.LabelFor(x => x.Books[i].IsSelected, Model.Books[i].BookName) </div> } </div> <div> <input id="btnSubmit" type="submit" value="Submit" /> </div> </div> }

    Read the article

  • Local LINQtoSQL Database For Your Windows Phone 7 Application

    - by Tim Murphy
    There aren’t many applications that are of value without having some for of data store.  In Windows Phone development we have a few options.  You can store text directly to isolated storage.  You can also use a number of third party libraries to create or mimic databases in isolated storage.  With Mango we gained the ability to have a native .NET database approach which uses LINQ to SQL.  In this article I will try to bring together the components needed to implement this last type of data store and fill in some of the blanks that I think other articles have left out. Defining A Database The first things you are going to need to do is define classes that represent your tables and a data context class that is used as the overall database definition.  The table class consists of column definitions as you would expect.  They can have relationships and constraints as with any relational DBMS.  Below is an example of a table definition. First you will need to add some assembly references to the code file. using System.ComponentModel;using System.Data.Linq;using System.Data.Linq.Mapping; You can then add the table class and its associated columns.  It needs to implement INotifyPropertyChanged and INotifyPropertyChanging.  Each level of the class needs to be decorated with the attribute appropriate for that part of the definition.  Where the class represents the table the properties represent the columns.  In this example you will see that the column is marked as a primary key and not nullable with a an auto generated value. You will also notice that the in the column property’s set method It uses the NotifyPropertyChanging and NotifyPropertyChanged methods in order to make sure that the proper events are fired. [Table]public class MyTable: INotifyPropertyChanged, INotifyPropertyChanging{ public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { if(PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public event PropertyChangingEventHandler PropertyChanging; private void NotifyPropertyChanging(string propertyName) { if(PropertyChanging != null) { PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } } private int _TableKey; [Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)] public int TableKey { get { return _TableKey; } set { NotifyPropertyChanging("TableKey"); _TableKey = value; NotifyPropertyChanged("TableKey"); } } The last part of the database definition that needs to be created is the data context.  This is a simple class that takes an isolated storage location connection string its constructor and then instantiates tables as public properties. public class MyDataContext: DataContext{ public MyDataContext(string connectionString): base(connectionString) { MyRecords = this.GetTable<MyTable>(); } public Table<MyTable> MyRecords;} Creating A New Database Instance Now that we have a database definition it is time to create an instance of the data context within our Windows Phone app.  When your app fires up it should check if the database already exists and create an instance if it does not.  I would suggest that this be part of the constructor of your ViewModel. db = new MyDataContext(connectionString);if(!db.DatabaseExists()){ db.CreateDatabase();} The next thing you have to know is how the connection string for isolated storage should be constructed.  The main sticking point I have found is that the database cannot be created unless the file mode is read/write.  You may have different connection strings but the initial one needs to be similar to the following. string connString = "Data Source = 'isostore:/MyApp.sdf'; File Mode = read write"; Using you database Now that you have done all the up front work it is time to put the database to use.  To make your life a little easier and keep proper separation between your view and your viewmodel you should add a couple of methods to the viewmodel.  These will do the CRUD work of your application.  What you will notice is that the SubmitChanges method is the secret sauce in all of the methods that change data. private myDataContext myDb;private ObservableCollection<MyTable> _viewRecords;public ObservableCollection<MyTable> ViewRecords{ get { return _viewRecords; } set { _viewRecords = value; NotifyPropertyChanged("ViewRecords"); }}public void LoadMedstarDbData(){ var tempItems = from MyTable myRecord in myDb.LocalScans select myRecord; ViewRecords = new ObservableCollection<MyTable>(tempItems);}public void SaveChangesToDb(){ myDb.SubmitChanges();}public void AddMyTableItem(MyTable newScan){ myDb.LocalScans.InsertOnSubmit(newScan); myDb.SubmitChanges();}public void DeleteMyTableItem(MyTable newScan){ myDb.LocalScans.DeleteOnSubmit(newScan); myDb.SubmitChanges();} Updating existing database What happens when you need to change the structure of your database?  Unfortunately you have to add code to your application that checks the version of the database which over time will create some pollution in your codes base.  On the other hand it does give you control of the update.  In this example you will see the DatabaseSchemaUpdater in action.  Assuming we added a “Notes” field to the MyTable structure, the following code will check if the database is the latest version and add the field if it isn’t. if(!myDb.DatabaseExists()){ myDb.CreateDatabase();}else{ DatabaseSchemaUpdater dbUdater = myDb.CreateDatabaseSchemaUpdater(); if(dbUdater.DatabaseSchemaVersion < 2) { dbUdater.AddColumn<MyTable>("Notes"); dbUdater.DatabaseSchemaVersion = 2; dbUdater.Execute(); }} Summary This approach does take a fairly large amount of work, but I think the end product is robust and very native for .NET developers.  It turns out to be worth the investment. del.icio.us Tags: Windows Phone,Windows Phone 7,LINQ to SQL,LINQ,Database,Isolated Storage

    Read the article

  • The underlying provider failed on Open

    - by senzacionale
    I was using .mdf for connect to DB and entityClient. Now i want to change connection string that trehe will be no .mdf Is this conectionstring correct <connectionStrings> <!--<add name="conString" connectionString="metadata=res://*/conString.csdl|res://*/conString.ssdl|res://*/conString.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQL2008;AttachDbFilename=|DataDirectory|\NData.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />--> <add name="conString" connectionString="metadata=res://*/conString.csdl|res://*/conString.ssdl|res://*/conString.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQL2008;Initial Catalog=NData;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" /> becouse i always get error !The underlying provider failed on Open!

    Read the article

  • how to serialize a DataTable to json or xml

    - by loviji
    Hello, i'm trying to serialize DataTable to Json or XML. is it possibly and how? any tutorials and ideas, please. For example a have a sql table: CREATE TABLE [dbo].[dictTable]( [keyValue] [int] IDENTITY(1,1) NOT NULL, [valueValue] [int] NULL, CONSTRAINT [Psd2Id] PRIMARY KEY CLUSTERED ( [keyValue] ASC )WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] C# code: string connectionString = "server=localhost;database=dbd;uid=**;pwd=**"; SqlConnection mySqlConnection = new SqlConnection(connectionString); string selectString = "SELECT keyValue, valueValue FROM dicTable"; SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = selectString; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); string dataTableName = "dictionary"; mySqlDataAdapter.Fill(myDataSet, dataTableName); DataTable myDataTable = myDataSet.Tables[dataTableName]; //now how to serialize it?

    Read the article

  • subsonic in visual studio design host

    - by csizo
    Hi, I'm facing currently a problem regarding Subsonic configuration. What I want to achieve is using subsonic data access in a System.Web.UI.Design.ControlDesigner class. This class is hosted in Visual Studio Environment and enables design time operations on the attached System.Web.UI.WebControls.Control. The only problem is SubSonic seems always looking for SubSonicSection in the application configuration regardless passing connection string to it. The relevant code snippet: using (SharedDbConnectionScope dbScope = new SharedDbConnectionScope(new SqlDataProvider(), ConnectionString)) { Table1 _table1 = new Select().From<..().Where(...).IsEqualTo(...).ExecuteSingle<...>(); Throws exception on ExecuteSingle() method (configuration section was not found) while using (SharedDbConnectionScope dbScope = new SharedDbConnectionScope(ConnectionString)) { Throws exception on new SharedDbConnectionScope() (configuration section was not found) So the question is: Is there any way to pass the settings runtime to bypass the configuration section lookup as I don't want to add any subsonic specific configuration to devenv.configuration Thanks

    Read the article

  • Crazy VS Designer Errors

    - by BlueRaja
    Here's a strange one. After renaming a class, one of my forms began giving me errors in the designer, refusing to open. Funny thing is, the form worked just fine when I ran the program. I began reverting my changes to deduce the problem. I have now reverted completely back to the last commit - in which I know the form was working in the designer - cleaned the solution, and deleted the bin/ and obj/ folders, as well as the *.suo file for good measure. The form still does not display in designer. Here are the errors it gives: Could not find 'MyNamespace.MyControl'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built. The variable 'myControl1' is either undeclared or was never assigned. The variable is both declared and assigned, and MyControl builds fine (again, the form works fine when the program is actually run). Stranger still, if I try to create a new form and drag a MyControl onto it, I get this Entity-Framework error: Failed to create component 'MyControl'. The error message follows: 'System.ArgumentException: The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid. at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString) at System.Data.EntityClient.EntityConnection..ctor(String connectionString) at System.Data.Objects.ObjectContect.CreateEntityConnection(String connectionString) etc. etc. There is nothing wrong with my connection string: it worked before, and, again, it works when I actually run the program (the control already exists on the old form from the previous commit). Any ideas whatsoever? I am completely at a loss. [Edit] The only significant code: MyControl.cs public MyControl() { _entities = new MyEFEntities(); //Entity-framework generated class } MyForm.Designer.cs private void InitializeComponent() { this.myControl1 = new MyNamespace.MyControl(); ... this.Controls.Add(this.myControl1); } MyEFDatabase.Designer.cs public MyEFEntities() : base("name=MyEFEntities", "MyEFEntities") { ... } App.Config <connectionStrings> <add name="MyEFEntities" connectionString="metadata=res://*/MyEFDatabase.csdl|res://*/MyEFDatabase.ssdl|res://*/MyEFDatabase.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=MyDatabaseServer;Initial Catalog=MyDatabase;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" /> </connectionStrings> I've tried the "replace &quot; with '" trick - didn't help. [Edit2] It is happening to new projects also, but not immediately. Only after fiddling around a bit (it has something to do with adding a many-to-one relationship that EF did not figure out on its own), but I can't figure out the exact steps to reproduce.

    Read the article

  • Why are there connections open to my databases?

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

    Read the article

  • How to bind a List of a DataObject to a Grid with BindingSources?

    - by citronas
    In an assembly I created a class like the following: [DataObject(true)] public class A { public int Foo{get;set;} [DataObjectMethod[DataObjectMethodType.Select)] public static List<A> GetAllA(string ConnectionString) { // return filled List<A> } } Now I want to display this List with a Gridcontrol under Winforms. I though of a DataGrid. Though I'm coming from ASP.net I'd first think of this.dataGridView1.DataSource = A.GetAllA(ConnectionString) Works, but I'd prefer a better databinding with BindingSources. (Because I've always heard that thats the way to go) I managed to drop a BindingSource onto the form and set the DataSource property to class A. But where can I set the SelectMethod and its parameters? If I set DataSource property of the dataGridView to the BindingSource, it will only display an empty line. Is this the right way to go? Will it only require some additional clicks in the wizard, or do I need to read tons of documentation to get this working?

    Read the article

  • Need help in gridview displaying data

    - by sumit
    Hi all, I want to display all the data in gridview which i am inserting in runtime. For that i have written code but getting this error. "Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition." protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindData(); } } public void BindData() { string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString(); SqlConnection con = new SqlConnection(str); SqlDataAdapter da = new SqlDataAdapter("select * from Items where ItemId='" + TxtItemId.Text + "'", con); DataSet ds = new DataSet(); da.Fill(ds,"Items"); GridView1.DataSource = ds; GridView1.DataBind(); } Pls modify my code where is my mistake. Thanks, Sumit

    Read the article

  • Microsoft Unity, parameters in constructor

    - by raffaeu
    I am using Unity with MVC and NHibernate. Unfortunately, our UnitOfWork resides in a different .dll and it doesn't have a default empty .ctor. This is what I do to register NHibernate: var connectionString = ConfigurationManager.ConnectionStrings["jobManagerConnection"].ConnectionString; var assemblyMap = ConfigurationManager.AppSettings["assemblyMap"]; container .RegisterType<IUnitOfWork, UnitOfWork>(new ContainerControlledLifetimeManager()); In my WebController I have this: /// <summary>Gets or sets UnitOfWork.</summary> [Dependency] public IUnitOfWork UnitOfWork { get; set; } The problem is that the constructor of UnitOfWork expects 2 mandatory strings. How I can setup the RegisterType for this Interface in order to pass the two parameters retreived from the web.config? Is it possible?

    Read the article

  • ASP.NET EnqityDataSource WhereParameters, creates new property.

    - by Alex
    I am trying to populate GridView, using EntityDataSource(code behind), I need to able to sort GridView. However when I sort i get error: A property with name 'aspnet_Users.UserId1' does not exist in metadata for entity type So I beleive it is because I generate where parameter in code behind: ActiveEnqDataSource.WhereParameters.Add(new SessionParameter("aspnet_Users.UserId", TypeCode.Object, "UserName")); Full code is : ActiveEnqDataSource.ConnectionString = db.Connection.ConnectionString; ActiveEnqDataSource.DefaultContainerName = "Entities"; ActiveEnqDataSource.EntitySetName = "Enquiries"; ActiveEnqDataSource.Include = "UserCars.CarModel.CarMake, Category, aspnet_Users"; ActiveEnqDataSource.EnableUpdate = true; ActiveEnqDataSource.EnableInsert = true; ActiveEnqDataSource.EnableDelete = true; ActiveEnqDataSource.AutoGenerateWhereClause = true; ActiveEnqDataSource.WhereParameters.Add(new SessionParameter("aspnet_Users.UserId", TypeCode.Object, "UserName")); Any suggestions? Thank you very much! The gridview itself renders perfectly, only thing I cannot sort it, any "whereParameters" I add, Add 1 to the property e.g UserId1,EnquiryStatus1, ProdauctName1. etc...

    Read the article

  • How to setup fluent nhibernate to work with Fitnesse

    - by Toran Billups
    I'm currently using fluent nhibernate and can't seem to get the configuration to work when using Fitnesse. For starters I have a FitServer.exe.config that looks like the below <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings file='C:\projectpath\web.config' /> </configuration> Then inside my web.config I have a connection string defined But will Fitnesse work when I use the following config? (using the ConnectionString config) private static ISessionFactory CreateSessionFactory() { var cfg = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c.FromConnectionStringWithKey("Local"))) .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())) .ExposeConfiguration(x => x.SetProperty("current_session_context_class", "thread")); return cfg.BuildSessionFactory(); }

    Read the article

  • Castle Windsor config pointing to connectionStrings section in web.config

    - by Georgia Brown
    I want to inject a connection string into my repository but ideally, I want this connection string to be in my web.config connectionStrings section rather than in my windsor config. Is this possible? I know I can use the fluent interface and achieve this easily but my bosses want an xml config file. I also know that I can define a property and use that in my windsor config to pass the parameter in, but I have other code that reads the connectionstring from the web.config directly and do not really want two places with the same connectionString.

    Read the article

  • VS2010 Clean Web.configs - not updating

    - by cw
    Hello, I'm messing around with MVC 2.0 on VS2010 and am having an issue getting the clean web config feature working. Basically in my Web.debug.config I have <connectionStrings xdt:Transform="Replace"> <add name="ApplicationServices" connectionString="Server=localhost;Database=SITE_DB;User ID=dbuser;Password=P@ssw0rd;Trusted_Connection=False;" /> </connectionStrings> and in my Web.config I have <connectionStrings> <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" /> </connectionStrings> When I run the site in debug mode, I'd expect that xdt:Transform="Replace" would replace the entire connectionStrings section with what is in the Web.debug.config. Am I assuming wrong? Or am I doing something else incorrect. Not much info posted around this and I'd figure I'd ask you guys.

    Read the article

  • Connection Timeout exception for a query using ADO.Net

    - by dragon
    Update: Looks like the query does not throw any timeout. The connection is timing out. This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception. I cannot use any of these techniques: 1) Increase timeout. 2) Run it asynchronously with a callback. This needs to run in a synchronous manner. please suggest any other techinques to keep the connection alive while executing a time consuming query? private static void CreateCommand(string queryString, string connectionString) { using (SqlConnection connection = new SqlConnection( connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); command.Connection.Open(); command.ExecuteNonQuery(); } }

    Read the article

  • MS Dynamics CRM trapping .NET error before I can handle it

    - by clifgriffin
    This is a fun one. I have written a custom search page that provides faster, more user friendly searches than the default Contacts view and also allows searching of Leads and Contacts simultaneously. It uses GridViews bound to SqlDataSources that query filtered views. I'm sure someone will complain that I'm not using the web services for this, but this is just the design decision we made. These GridViews live in UpdatePanels to enable very slick AJAX updates upon search. It's all working great. Nearly ready to be deployed, except for one thing: Some long running searches are triggering an uncatchable SQL timeout exception. [SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.] 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.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() 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.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable) at System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) at System.Web.UI.WebControls.DataBoundControl.PerformSelect() at System.Web.UI.WebControls.BaseDataBoundControl.DataBind() at System.Web.UI.WebControls.GridView.DataBind() at System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() at System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() at System.Web.UI.Control.EnsureChildControls() at System.Web.UI.Control.PreRenderRecursiveInternal() at System.Web.UI.Control.PreRenderRecursiveInternal() at System.Web.UI.Control.PreRenderRecursiveInternal() at System.Web.UI.Control.PreRenderRecursiveInternal() at System.Web.UI.Control.PreRenderRecursiveInternal() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) I found that CRM is doing a server.transfer to capture this error because my UpdatePanels started throwing JavaSript errors when this error would occur. I was only able to get the full error message by using the JavaScript debugger in IE. Having found this error, I thought the solution would be simple. I just needed to wrap my databind calls in try/catch blocks to capture any errors. Unfortunately it seems CRM's IIS configuration has the magic ability to capture this error before it ever gets back to my code. Using the debugger I never see it. It never gets to my catch blocks, but it's clearly happening in the SQL Data Source which is clearly (by the stack trace) being triggered by my GridView bind. Any ideas on this? It's driving me crazy. Code Behind (with some irrelevant functions omitted): protected void Page_Load(object sender, EventArgs e) { //Initialize some stuff this.bannerOracle = new OdbcConnection(ConfigurationManager.ConnectionStrings["OracleConnectionString"].ConnectionString); //Prospect default HideProspects(); HideProspectAddressColumn(); //Contacts default HideContactAddressColumn(); //Default error messages gvContacts.EmptyDataText = "Sad day. Your search returned no contacts."; gvProspects.EmptyDataText = "Sad day. Your search returned no prospects."; //New search try { SearchContact(null, -1); } catch { gvContacts.EmptyDataText = "Oops! An error occured. This may have been a timeout. Please try your search again."; gvContacts.DataSource = null; gvContacts.DataBind(); } } protected void txtSearchString_TextChanged(object sender, EventArgs e) { if(!String.IsNullOrEmpty(txtSearchString.Text)) { try { SearchContact(txtSearchString.Text, Convert.ToInt16(lstSearchType.SelectedValue)); } catch { gvContacts.EmptyDataText = "Oops! An error occured. This may have been a timeout. Please try your search again."; gvContacts.DataSource = null; gvContacts.DataBind(); } if (chkProspects.Checked == true) { try { SearchProspect(txtSearchString.Text, Convert.ToInt16(lstSearchType.SelectedValue)); } catch { gvProspects.EmptyDataText = "Oops! An error occured. This may have been a timeout. Please try your search again."; gvProspects.DataSource = null; gvProspects.DataBind(); } finally { ShowProspects(); } } else { HideProspects(); } } } protected void SearchContact(string search, int type) { SqlCRM_Contact.ConnectionString = ConfigurationManager.ConnectionStrings["MSSQLConnectionString"].ConnectionString; gvContacts.DataSourceID = "SqlCRM_Contact"; string strQuery = ""; string baseQuery = @"SELECT filteredcontact.contactid, filteredcontact.new_libertyid, filteredcontact.fullname, 'none' AS line1, filteredcontact.emailaddress1, filteredcontact.telephone1, filteredcontact.birthdateutc AS birthdate, filteredcontact.gendercodename FROM filteredcontact "; switch(type) { case LASTFIRST: strQuery = baseQuery + "WHERE fullname LIKE @value AND filteredcontact.statecode = 0"; SqlCRM_Contact.SelectCommand = strQuery; SqlCRM_Contact.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); break; case LAST: strQuery = baseQuery + "WHERE lastname LIKE @value AND filteredcontact.statecode = 0"; SqlCRM_Contact.SelectCommand = strQuery; SqlCRM_Contact.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); break; case FIRST: strQuery = baseQuery + "WHERE firstname LIKE @value AND filteredcontact.statecode = 0"; SqlCRM_Contact.SelectCommand = strQuery; SqlCRM_Contact.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); break; case LIBERTYID: strQuery = baseQuery + "WHERE new_libertyid LIKE @value AND filteredcontact.statecode = 0"; SqlCRM_Contact.SelectCommand = strQuery; SqlCRM_Contact.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); break; case EMAIL: strQuery = baseQuery + "WHERE emailaddress1 LIKE @value AND filteredcontact.statecode = 0"; SqlCRM_Contact.SelectCommand = strQuery; SqlCRM_Contact.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); break; case TELEPHONE: strQuery = baseQuery + "WHERE telephone1 LIKE @value AND filteredcontact.statecode = 0"; SqlCRM_Contact.SelectCommand = strQuery; SqlCRM_Contact.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); break; case BIRTHDAY: strQuery = baseQuery + "WHERE filteredcontact.birthdateutc BETWEEN @dateStart AND @dateEnd AND filteredcontact.statecode = 0"; try { DateTime temp = DateTime.Parse(search); if (temp.Year < 1753 || temp.Year > 9999) { search = string.Empty; } else { search = temp.ToString("yyyy-MM-dd"); } } catch { search = string.Empty; } SqlCRM_Contact.SelectCommand = strQuery; SqlCRM_Contact.SelectParameters.Add("dateStart", DbType.String, search.Trim() + " 00:00:00.000"); SqlCRM_Contact.SelectParameters.Add("dateEnd", DbType.String, search.Trim() + " 23:59:59.999"); break; case SSN: //Do something break; case ADDRESS: strQuery = @"SELECT contactid, new_libertyid, fullname, line1, emailaddress1, telephone1, birthdate, gendercodename FROM (SELECT FC.contactid, FC.new_libertyid, FC.fullname, FA.line1, FC.emailaddress1, FC.telephone1, FC.birthdateutc AS birthdate, FC.gendercodename, ROW_NUMBER() OVER(PARTITION BY FC.contactid ORDER BY FC.contactid DESC) AS rn FROM filteredcontact FC INNER JOIN FilteredCustomerAddress FA ON FC.contactid = FA.parentid WHERE FA.line1 LIKE @value AND FA.addressnumber <> 1 AND FC.statecode = 0 ) AS RESULTS WHERE rn = 1"; SqlCRM_Contact.SelectCommand = strQuery; SqlCRM_Contact.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); ShowContactAddressColumn(); break; default: strQuery = @"SELECT TOP 500 filteredcontact.contactid, filteredcontact.new_libertyid, filteredcontact.fullname, 'none' AS line1, filteredcontact.emailaddress1, filteredcontact.telephone1, filteredcontact.birthdateutc AS birthdate, filteredcontact.gendercodename FROM filteredcontact WHERE filteredcontact.statecode = 0"; SqlCRM_Contact.SelectCommand = strQuery; break; } if (type != ADDRESS) { HideContactAddressColumn(); } gvContacts.PageIndex = 0; //try //{ // SqlCRM_Contact.DataBind(); //} //catch //{ // SqlCRM_Contact.DataBind(); //} gvContacts.DataBind(); } protected void SearchProspect(string search, int type) { SqlCRM_Prospect.ConnectionString = ConfigurationManager.ConnectionStrings["MSSQLConnectionString"].ConnectionString; gvProspects.DataSourceID = "SqlCRM_Prospect"; string strQuery = ""; string baseQuery = @"SELECT filteredlead.leadid, filteredlead.fullname, 'none' AS address1_line1, filteredlead.emailaddress1, filteredlead.telephone1, filteredlead.lu_dateofbirthutc AS lu_dateofbirth, filteredlead.lu_gendername FROM filteredlead "; switch (type) { case LASTFIRST: strQuery = baseQuery + "WHERE fullname LIKE @value AND filteredlead.statecode = 0"; SqlCRM_Prospect.SelectCommand = strQuery; SqlCRM_Prospect.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); break; case LAST: strQuery = baseQuery + "WHERE lastname LIKE @value AND filteredlead.statecode = 0"; SqlCRM_Prospect.SelectCommand = strQuery; SqlCRM_Prospect.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); break; case FIRST: strQuery = baseQuery + "WHERE firstname LIKE @value AND filteredlead.statecode = 0"; SqlCRM_Prospect.SelectCommand = strQuery; SqlCRM_Prospect.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); break; case LIBERTYID: strQuery = baseQuery + "WHERE new_libertyid LIKE @value AND filteredlead.statecode = 0"; SqlCRM_Prospect.SelectCommand = strQuery; SqlCRM_Prospect.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); break; case EMAIL: strQuery = baseQuery + "WHERE emailaddress1 LIKE @value AND filteredlead.statecode = 0"; SqlCRM_Prospect.SelectCommand = strQuery; SqlCRM_Prospect.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); break; case TELEPHONE: strQuery = baseQuery + "WHERE telephone1 LIKE @value AND filteredlead.statecode = 0"; SqlCRM_Prospect.SelectCommand = strQuery; SqlCRM_Prospect.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); break; case BIRTHDAY: strQuery = baseQuery + "WHERE filteredlead.lu_dateofbirth BETWEEN @dateStart AND @dateEnd AND filteredlead.statecode = 0"; try { DateTime temp = DateTime.Parse(search); if (temp.Year < 1753 || temp.Year > 9999) { search = string.Empty; } else { search = temp.ToString("yyyy-MM-dd"); } } catch { search = string.Empty; } SqlCRM_Prospect.SelectCommand = strQuery; SqlCRM_Prospect.SelectParameters.Add("dateStart", DbType.String, search.Trim() + " 00:00:00.000"); SqlCRM_Prospect.SelectParameters.Add("dateEnd", DbType.String, search.Trim() + " 23:59:59.999"); break; case SSN: //Do nothing break; case ADDRESS: strQuery = @"SELECT filteredlead.leadid, filteredlead.fullname, filteredlead.address1_line1, filteredlead.emailaddress1, filteredlead.telephone1, filteredlead.lu_dateofbirthutc AS lu_dateofbirth, filteredlead.lu_gendername FROM filteredlead WHERE address1_line1 LIKE @value AND filteredlead.statecode = 0"; SqlCRM_Prospect.SelectCommand = strQuery; SqlCRM_Prospect.SelectParameters.Add("value", DbType.String, search.Trim() + "%"); ShowProspectAddressColumn(); break; default: strQuery = @"SELECT TOP 500 filteredlead.leadid, filteredlead.fullname, 'none' AS address1_line1 filteredlead.emailaddress1, filteredlead.telephone1, filteredlead.lu_dateofbirthutc AS lu_dateofbirth, filteredlead.lu_gendername FROM filteredlead WHERE filteredlead.statecode = 0"; SqlCRM_Prospect.SelectCommand = strQuery; break; } if (type != ADDRESS) { HideProspectAddressColumn(); } gvProspects.PageIndex = 0; //try //{ // SqlCRM_Prospect.DataBind(); //} //catch (Exception ex) //{ // SqlCRM_Prospect.DataBind(); //} gvProspects.DataBind(); }

    Read the article

  • [StructureMap] Xml configuration or Configuration through code?

    - by Amith George
    I personally like the option to configure StructureMap from C# code. From what I understand, one of the advantages of DI, is that we can easily swap in a new concrete instance. But, if the configuration is defined in code, then the concrete instances are hardcoded in the dll. So, practically, its as good as having hard coded the dependencies, right? I know, during testing it makes life easier... My point is, wouldnt it be better to use xml configuration instead? you want to plugin a new concrete instance? simply have your installer overwrite the structuremap.config file with the new one. So, what is the preferred way to configure StructureMap? Extra: Am forced to use C# configuration for the time being because I dont know how to pass the connection string to instance. I can write the connectionstring in the config file, but i would like to reuse the connectionstring defined in app.config.

    Read the article

  • VisualBasic.net Database Boiler Plate

    - by Shiftbit
    Is there any built in .net Classes to assist in the reduction of boiler plate code? I have numerous database operations going on and I find that I am reproducing the connection, command, transaction and occassianlly data set. I am aware of the Java Related Question, however, the solutions pertain to Java. I was wondering if anyone was aware of a .net solution? http://stackoverflow.com/questions/1072925/remove-boilerplate-from-db-code Public Sub ReadData(ByVal connectionString As String) Dim queryString As String = "SELECT EmpNo, EName FROM Emp" Using connection As New OracleConnection(connectionString) Dim command As New OracleCommand(queryString, connection) connection.Open() Using reader As OracleDataReader = command.ExecuteReader() ' Always call Read before accessing data. While reader.Read() Console.WriteLine(reader.GetInt32(0).ToString() + ", " _ + reader.GetString(1)) End While End Using End Using End Sub MSDN

    Read the article

  • connecting c# to sql-server

    - by every_answer_gets_a_point
    i am using this example to connect c# to sql server. can you please tell me what i have to include in order to be able to use sqlconnection? it must be something like: using Sqlconnection; ??? string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=""C:\SQL Server 2000 Sample Databases\NORTHWND.MDF"";Integrated Security=True;Connect Timeout=30;User Instance=True"; SqlConnection sqlCon = new SqlConnection(connectionString); sqlCon.Open(); string commandString = "SELECT * FROM Customers"; SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon); SqlDataReader dataReader = sqlCmd.ExecuteReader(); while (dataReader.Read()) { Console.WriteLine(String.Format("{0} {1}", dataReader["CompanyName"], dataReader["ContactName"])); } dataReader.Close(); sqlCon.Close();

    Read the article

  • SqlCommand asp.net C#

    - by emilios
    i you please help me out with my problem i am trying to create a function that output the data on a dropdownlist an setting my parameters my code goes as follow : public static List<string> GetTracks(out List<string> trackIds, string conferenceId) { var res = new List<string>(); trackIds = new List<string>(); var sqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); SqlCommand cmd = new SqlCommand("select Track_name,Track_ID from TrackCommittee where Conference_id= @conferenceId", sqlCon); DataSet ds = new DataSet(); cmd.Connection.Open(); cmd.Parameters.Add(new SqlParameter("@conferenceId", conferenceId)); using (SqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { res.Add(sdr.GetString(sdr.GetOrdinal("Track_name"))); trackIds.Add(sdr.GetInt32(sdr.GetOrdinal("Track_ID")).ToString()); } } cmd.Connection.Close(); cmd.Dispose(); return res; } thanking you in advance

    Read the article

  • How to capture SQL with parameters substituted in? (.NET, SqlCommand)

    - by Bryan
    Hello, If there an easy way to get a completed SQL statement back after parameter substitution? I.e., I want to keep a logfile of all the SQL this program runs. Or if I want to do this, will I just want to get rid of Parameters, and do the whole query the old school way, in one big string? Simple Example: I want to capture the output: SELECT subcatId FROM EnrollmentSubCategory WHERE catid = 1 .. from this code: Dim subCatSQL As String = "SELECT subcatId FROM EnrollmentSubCategory WHERE catid = @catId" Dim connectionString As String = "X" Dim conn As New SqlConnection(connectionString) If conn.State = ConnectionState.Closed Then conn.Open() End If Dim cmd As New SqlCommand(subCatSQL, conn) With cmd .Parameters.Add(New SqlParameter("@catId", SqlDbType.Int, 1)) End With Console.WriteLine("Before: " + cmd.CommandText) cmd.Prepare() Console.WriteLine("After: " + cmd.CommandText) I had assumed Prepare() would do the substitutions, but apparently not. Thoughts? Advice? Thanks in advance.

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >