Search Results

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

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

  • Using the ASP.NET Cache to cache data in a Model or Business Object layer, without a dependency on System.Web in the layer - Part One.

    - by Rhames
    ASP.NET applications can make use of the System.Web.Caching.Cache object to cache data and prevent repeated expensive calls to a database or other store. However, ideally an application should make use of caching at the point where data is retrieved from the database, which typically is inside a Business Objects or Model layer. One of the key features of using a UI pattern such as Model-View-Presenter (MVP) or Model-View-Controller (MVC) is that the Model and Presenter (or Controller) layers are developed without any knowledge of the UI layer. Introducing a dependency on System.Web into the Model layer would break this independence of the Model from the View. This article gives a solution to this problem, using dependency injection to inject the caching implementation into the Model layer at runtime. This allows caching to be used within the Model layer, without any knowledge of the actual caching mechanism that will be used. Create a sample application to use the caching solution Create a test SQL Server database This solution uses a SQL Server database with the same Sales data used in my previous post on calculating running totals. The advantage of using this data is that it gives nice slow queries that will exaggerate the effect of using caching! To create the data, first create a new SQL database called CacheSample. Next run the following script to create the Sale table and populate it: USE CacheSample GO   CREATE TABLE Sale(DayCount smallint, Sales money) CREATE CLUSTERED INDEX ndx_DayCount ON Sale(DayCount) go INSERT Sale VALUES (1,120) INSERT Sale VALUES (2,60) INSERT Sale VALUES (3,125) INSERT Sale VALUES (4,40)   DECLARE @DayCount smallint, @Sales money SET @DayCount = 5 SET @Sales = 10   WHILE @DayCount < 5000  BEGIN  INSERT Sale VALUES (@DayCount,@Sales)  SET @DayCount = @DayCount + 1  SET @Sales = @Sales + 15  END Next create a stored procedure to calculate the running total, and return a specified number of rows from the Sale table, using the following script: USE [CacheSample] GO   SET ANSI_NULLS ON GO   SET QUOTED_IDENTIFIER ON GO   -- ============================================= -- Author:        Robin -- Create date: -- Description:   -- ============================================= CREATE PROCEDURE [dbo].[spGetRunningTotals]       -- Add the parameters for the stored procedure here       @HighestDayCount smallint = null AS BEGIN       -- SET NOCOUNT ON added to prevent extra result sets from       -- interfering with SELECT statements.       SET NOCOUNT ON;         IF @HighestDayCount IS NULL             SELECT @HighestDayCount = MAX(DayCount) FROM dbo.Sale                   DECLARE @SaleTbl TABLE (DayCount smallint, Sales money, RunningTotal money)         DECLARE @DayCount smallint,                   @Sales money,                   @RunningTotal money         SET @RunningTotal = 0       SET @DayCount = 0         DECLARE rt_cursor CURSOR       FOR       SELECT DayCount, Sales       FROM Sale       ORDER BY DayCount         OPEN rt_cursor         FETCH NEXT FROM rt_cursor INTO @DayCount,@Sales         WHILE @@FETCH_STATUS = 0 AND @DayCount <= @HighestDayCount        BEGIN        SET @RunningTotal = @RunningTotal + @Sales        INSERT @SaleTbl VALUES (@DayCount,@Sales,@RunningTotal)        FETCH NEXT FROM rt_cursor INTO @DayCount,@Sales        END         CLOSE rt_cursor       DEALLOCATE rt_cursor         SELECT DayCount, Sales, RunningTotal       FROM @SaleTbl   END   GO   Create the Sample ASP.NET application In Visual Studio create a new solution and add a class library project called CacheSample.BusinessObjects and an ASP.NET web application called CacheSample.UI. The CacheSample.BusinessObjects project will contain a single class to represent a Sale data item, with all the code to retrieve the sales from the database included in it for simplicity (normally I would at least have a separate Repository or other object that is responsible for retrieving data, and probably a data access layer as well, but for this sample I want to keep it simple). The C# code for the Sale class is shown below: using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient;   namespace CacheSample.BusinessObjects {     public class Sale     {         public Int16 DayCount { get; set; }         public decimal Sales { get; set; }         public decimal RunningTotal { get; set; }           public static IEnumerable<Sale> GetSales(int? highestDayCount)         {             List<Sale> sales = new List<Sale>();               SqlParameter highestDayCountParameter = new SqlParameter("@HighestDayCount", SqlDbType.SmallInt);             if (highestDayCount.HasValue)                 highestDayCountParameter.Value = highestDayCount;             else                 highestDayCountParameter.Value = DBNull.Value;               string connectionStr = System.Configuration.ConfigurationManager .ConnectionStrings["CacheSample"].ConnectionString;               using(SqlConnection sqlConn = new SqlConnection(connectionStr))             using (SqlCommand sqlCmd = sqlConn.CreateCommand())             {                 sqlCmd.CommandText = "spGetRunningTotals";                 sqlCmd.CommandType = CommandType.StoredProcedure;                 sqlCmd.Parameters.Add(highestDayCountParameter);                   sqlConn.Open();                   using (SqlDataReader dr = sqlCmd.ExecuteReader())                 {                     while (dr.Read())                     {                         Sale newSale = new Sale();                         newSale.DayCount = dr.GetInt16(0);                         newSale.Sales = dr.GetDecimal(1);                         newSale.RunningTotal = dr.GetDecimal(2);                           sales.Add(newSale);                     }                 }             }               return sales;         }     } }   The static GetSale() method makes a call to the spGetRunningTotals stored procedure and then reads each row from the returned SqlDataReader into an instance of the Sale class, it then returns a List of the Sale objects, as IEnnumerable<Sale>. A reference to System.Configuration needs to be added to the CacheSample.BusinessObjects project so that the connection string can be read from the web.config file. In the CacheSample.UI ASP.NET project, create a single web page called ShowSales.aspx, and make this the default start up page. This page will contain a single button to call the GetSales() method and a label to display the results. The html mark up and the C# code behind are shown below: ShowSales.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShowSales.aspx.cs" Inherits="CacheSample.UI.ShowSales" %>   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title>Cache Sample - Show All Sales</title> </head> <body>     <form id="form1" runat="server">     <div>         <asp:Button ID="btnTest1" runat="server" onclick="btnTest1_Click"             Text="Get All Sales" />         &nbsp;&nbsp;&nbsp;         <asp:Label ID="lblResults" runat="server"></asp:Label>         </div>     </form> </body> </html>   ShowSales.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;   using CacheSample.BusinessObjects;   namespace CacheSample.UI {     public partial class ShowSales : System.Web.UI.Page     {         protected void Page_Load(object sender, EventArgs e)         {         }           protected void btnTest1_Click(object sender, EventArgs e)         {             System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();             stopWatch.Start();               var sales = Sale.GetSales(null);               var lastSales = sales.Last();               stopWatch.Stop();               lblResults.Text = string.Format( "Count of Sales: {0}, Last DayCount: {1}, Total Sales: {2}. Query took {3} ms", sales.Count(), lastSales.DayCount, lastSales.RunningTotal, stopWatch.ElapsedMilliseconds);         }       } }   Finally we need to add a connection string to the CacheSample SQL Server database, called CacheSample, to the web.config file: <?xmlversion="1.0"?>   <configuration>    <connectionStrings>     <addname="CacheSample"          connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=CacheSample"          providerName="System.Data.SqlClient" />  </connectionStrings>    <system.web>     <compilationdebug="true"targetFramework="4.0" />  </system.web>   </configuration>   Run the application and click the button a few times to see how long each call to the database takes. On my system, each query takes about 450ms. Next I shall look at a solution to use the ASP.NET caching to cache the data returned by the query, so that subsequent requests to the GetSales() method are much faster. Adding Data Caching Support I am going to create my caching support in a separate project called CacheSample.Caching, so the next step is to add a class library to the solution. We shall be using the application configuration to define the implementation of our caching system, so we need a reference to System.Configuration adding to the project. ICacheProvider<T> Interface The first step in adding caching to our application is to define an interface, called ICacheProvider, in the CacheSample.Caching project, with methods to retrieve any data from the cache or to retrieve the data from the data source if it is not present in the cache. Dependency Injection will then be used to inject an implementation of this interface at runtime, allowing the users of the interface (i.e. the CacheSample.BusinessObjects project) to be completely unaware of how the caching is actually implemented. As data of any type maybe retrieved from the data source, it makes sense to use generics in the interface, with a generic type parameter defining the data type associated with a particular instance of the cache interface implementation. The C# code for the ICacheProvider interface is shown below: using System; using System.Collections.Generic;   namespace CacheSample.Caching {     public interface ICacheProvider     {     }       public interface ICacheProvider<T> : ICacheProvider     {         T Fetch(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry);           IEnumerable<T> Fetch(string key, Func<IEnumerable<T>> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry);     } }   The empty non-generic interface will be used as a type in a Dictionary generic collection later to store instances of the ICacheProvider<T> implementation for reuse, I prefer to use a base interface when doing this, as I think the alternative of using object makes for less clear code. The ICacheProvider<T> interface defines two overloaded Fetch methods, the difference between these is that one will return a single instance of the type T and the other will return an IEnumerable<T>, providing support for easy caching of collections of data items. Both methods will take a key parameter, which will uniquely identify the cached data, a delegate of type Func<T> or Func<IEnumerable<T>> which will provide the code to retrieve the data from the store if it is not present in the cache, and absolute or relative expiry policies to define when a cached item should expire. Note that at present there is no support for cache dependencies, but I shall be showing a method of adding this in part two of this article. CacheProviderFactory Class We need a mechanism of creating instances of our ICacheProvider<T> interface, using Dependency Injection to get the implementation of the interface. To do this we shall create a CacheProviderFactory static class in the CacheSample.Caching project. This factory will provide a generic static method called GetCacheProvider<T>(), which shall return instances of ICacheProvider<T>. We can then call this factory method with the relevant data type (for example the Sale class in the CacheSample.BusinessObject project) to get a instance of ICacheProvider for that type (e.g. call CacheProviderFactory.GetCacheProvider<Sale>() to get the ICacheProvider<Sale> implementation). The C# code for the CacheProviderFactory is shown below: using System; using System.Collections.Generic;   using CacheSample.Caching.Configuration;   namespace CacheSample.Caching {     public static class CacheProviderFactory     {         private static Dictionary<Type, ICacheProvider> cacheProviders = new Dictionary<Type, ICacheProvider>();         private static object syncRoot = new object();           ///<summary>         /// Factory method to create or retrieve an implementation of the  /// ICacheProvider interface for type <typeparamref name="T"/>.         ///</summary>         ///<typeparam name="T">  /// The type that this cache provider instance will work with  ///</typeparam>         ///<returns>An instance of the implementation of ICacheProvider for type  ///<typeparamref name="T"/>, as specified by the application  /// configuration</returns>         public static ICacheProvider<T> GetCacheProvider<T>()         {             ICacheProvider<T> cacheProvider = null;             // Get the Type reference for the type parameter T             Type typeOfT = typeof(T);               // Lock the access to the cacheProviders dictionary             // so multiple threads can work with it             lock (syncRoot)             {                 // First check if an instance of the ICacheProvider implementation  // already exists in the cacheProviders dictionary for the type T                 if (cacheProviders.ContainsKey(typeOfT))                     cacheProvider = (ICacheProvider<T>)cacheProviders[typeOfT];                 else                 {                     // There is not already an instance of the ICacheProvider in       // cacheProviders for the type T                     // so we need to create one                       // Get the Type reference for the application's implementation of       // ICacheProvider from the configuration                     Type cacheProviderType = Type.GetType(CacheProviderConfigurationSection.Current. CacheProviderType);                     if (cacheProviderType != null)                     {                         // Now get a Type reference for the Cache Provider with the                         // type T generic parameter                         Type typeOfCacheProviderTypeForT = cacheProviderType.MakeGenericType(new Type[] { typeOfT });                         if (typeOfCacheProviderTypeForT != null)                         {                             // Create the instance of the Cache Provider and add it to // the cacheProviders dictionary for future use                             cacheProvider = (ICacheProvider<T>)Activator. CreateInstance(typeOfCacheProviderTypeForT);                             cacheProviders.Add(typeOfT, cacheProvider);                         }                     }                 }             }               return cacheProvider;                 }     } }   As this code uses Activator.CreateInstance() to create instances of the ICacheProvider<T> implementation, which is a slow process, the factory class maintains a Dictionary of the previously created instances so that a cache provider needs to be created only once for each type. The type of the implementation of ICacheProvider<T> is read from a custom configuration section in the application configuration file, via the CacheProviderConfigurationSection class, which is described below. CacheProviderConfigurationSection Class The implementation of ICacheProvider<T> will be specified in a custom configuration section in the application’s configuration. To handle this create a folder in the CacheSample.Caching project called Configuration, and add a class called CacheProviderConfigurationSection to this folder. This class will extend the System.Configuration.ConfigurationSection class, and will contain a single string property called CacheProviderType. The C# code for this class is shown below: using System; using System.Configuration;   namespace CacheSample.Caching.Configuration {     internal class CacheProviderConfigurationSection : ConfigurationSection     {         public static CacheProviderConfigurationSection Current         {             get             {                 return (CacheProviderConfigurationSection) ConfigurationManager.GetSection("cacheProvider");             }         }           [ConfigurationProperty("type", IsRequired=true)]         public string CacheProviderType         {             get             {                 return (string)this["type"];             }         }     } }   Adding Data Caching to the Sales Class We now have enough code in place to add caching to the GetSales() method in the CacheSample.BusinessObjects.Sale class, even though we do not yet have an implementation of the ICacheProvider<T> interface. We need to add a reference to the CacheSample.Caching project to CacheSample.BusinessObjects so that we can use the ICacheProvider<T> interface within the GetSales() method. Once the reference is added, we can first create a unique string key based on the method name and the parameter value, so that the same cache key is used for repeated calls to the method with the same parameter values. Then we get an instance of the cache provider for the Sales type, using the CacheProviderFactory, and pass the existing code to retrieve the data from the database as the retrievalMethod delegate in a call to the Cache Provider Fetch() method. The C# code for the modified GetSales() method is shown below: public static IEnumerable<Sale> GetSales(int? highestDayCount) {     string cacheKey = string.Format("CacheSample.BusinessObjects.GetSalesWithCache({0})", highestDayCount);       return CacheSample.Caching.CacheProviderFactory. GetCacheProvider<Sale>().Fetch(cacheKey,         delegate()         {             List<Sale> sales = new List<Sale>();               SqlParameter highestDayCountParameter = new SqlParameter("@HighestDayCount", SqlDbType.SmallInt);             if (highestDayCount.HasValue)                 highestDayCountParameter.Value = highestDayCount;             else                 highestDayCountParameter.Value = DBNull.Value;               string connectionStr = System.Configuration.ConfigurationManager. ConnectionStrings["CacheSample"].ConnectionString;               using (SqlConnection sqlConn = new SqlConnection(connectionStr))             using (SqlCommand sqlCmd = sqlConn.CreateCommand())             {                 sqlCmd.CommandText = "spGetRunningTotals";                 sqlCmd.CommandType = CommandType.StoredProcedure;                 sqlCmd.Parameters.Add(highestDayCountParameter);                   sqlConn.Open();                   using (SqlDataReader dr = sqlCmd.ExecuteReader())                 {                     while (dr.Read())                     {                         Sale newSale = new Sale();                         newSale.DayCount = dr.GetInt16(0);                         newSale.Sales = dr.GetDecimal(1);                         newSale.RunningTotal = dr.GetDecimal(2);                           sales.Add(newSale);                     }                 }             }               return sales;         },         null,         new TimeSpan(0, 10, 0)); }     This example passes the code to retrieve the Sales data from the database to the Cache Provider as an anonymous method, however it could also be written as a lambda. The main advantage of using an anonymous function (method or lambda) is that the code inside the anonymous function can access the parameters passed to the GetSales() method. Finally the absolute expiry is set to null, and the relative expiry set to 10 minutes, to indicate that the cache entry should be removed 10 minutes after the last request for the data. As the ICacheProvider<T> has a Fetch() method that returns IEnumerable<T>, we can simply return the results of the Fetch() method to the caller of the GetSales() method. This should be all that is needed for the GetSales() method to now retrieve data from a cache after the first time the data has be retrieved from the database. Implementing a ASP.NET Cache Provider The final step is to actually implement the ICacheProvider<T> interface, and add the implementation details to the web.config file for the dependency injection. The cache provider implementation needs to have access to System.Web. Therefore it could be placed in the CacheSample.UI project, or in its own project that has a reference to System.Web. Implementing the Cache Provider in a separate project is my favoured approach. Create a new project inside the solution called CacheSample.CacheProvider, and add references to System.Web and CacheSample.Caching to this project. Add a class to the project called AspNetCacheProvider. Make the class a generic class by adding the generic parameter <T> and indicate that the class implements ICacheProvider<T>. The C# code for the AspNetCacheProvider class is shown below: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Caching;   using CacheSample.Caching;   namespace CacheSample.CacheProvider {     public class AspNetCacheProvider<T> : ICacheProvider<T>     {         #region ICacheProvider<T> Members           public T Fetch(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry)         {             return FetchAndCache<T>(key, retrieveData, absoluteExpiry, relativeExpiry);         }           public IEnumerable<T> Fetch(string key, Func<IEnumerable<T>> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry)         {             return FetchAndCache<IEnumerable<T>>(key, retrieveData, absoluteExpiry, relativeExpiry);         }           #endregion           #region Helper Methods           private U FetchAndCache<U>(string key, Func<U> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry)         {             U value;             if (!TryGetValue<U>(key, out value))             {                 value = retrieveData();                 if (!absoluteExpiry.HasValue)                     absoluteExpiry = Cache.NoAbsoluteExpiration;                   if (!relativeExpiry.HasValue)                     relativeExpiry = Cache.NoSlidingExpiration;                   HttpContext.Current.Cache.Insert(key, value, null, absoluteExpiry.Value, relativeExpiry.Value);             }             return value;         }           private bool TryGetValue<U>(string key, out U value)         {             object cachedValue = HttpContext.Current.Cache.Get(key);             if (cachedValue == null)             {                 value = default(U);                 return false;             }             else             {                 try                 {                     value = (U)cachedValue;                     return true;                 }                 catch                 {                     value = default(U);                     return false;                 }             }         }           #endregion       } }   The two interface Fetch() methods call a private method called FetchAndCache(). This method first checks for a element in the HttpContext.Current.Cache with the specified cache key, and if so tries to cast this to the specified type (either T or IEnumerable<T>). If the cached element is found, the FetchAndCache() method simply returns it. If it is not found in the cache, the method calls the retrievalMethod delegate to get the data from the data source, and then adds this to the HttpContext.Current.Cache. The final step is to add the AspNetCacheProvider class to the relevant custom configuration section in the CacheSample.UI.Web.Config file. To do this there needs to be a <configSections> element added as the first element in <configuration>. This will match a custom section called <cacheProvider> with the CacheProviderConfigurationSection. Then we add a <cacheProvider> element, with a type property set to the fully qualified assembly name of the AspNetCacheProvider class, as shown below: <?xmlversion="1.0"?>   <configuration>  <configSections>     <sectionname="cacheProvider" type="CacheSample.Base.Configuration.CacheProviderConfigurationSection, CacheSample.Base" />  </configSections>    <connectionStrings>     <addname="CacheSample"          connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=CacheSample"          providerName="System.Data.SqlClient" />  </connectionStrings>    <cacheProvidertype="CacheSample.CacheProvider.AspNetCacheProvider`1, CacheSample.CacheProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">  </cacheProvider>    <system.web>     <compilationdebug="true"targetFramework="4.0" />  </system.web>   </configuration>   One point to note is that the fully qualified assembly name of the AspNetCacheProvider class includes the notation `1 after the class name, which indicates that it is a generic class with a single generic type parameter. The CacheSample.UI project needs to have references added to CacheSample.Caching and CacheSample.CacheProvider so that the actual application is aware of the relevant cache provider implementation. Conclusion After implementing this solution, you should have a working cache provider mechanism, that will allow the middle and data access layers to implement caching support when retrieving data, without any knowledge of the actually caching implementation. If the UI is not ASP.NET based, if for example it is Winforms or WPF, the implementation of ICacheProvider<T> would be written around whatever technology is available. It could even be a standalone caching system that takes full responsibility for adding and removing items from a global store. The next part of this article will show how this caching mechanism may be extended to provide support for cache dependencies, such as the System.Web.Caching.SqlCacheDependency. Another possible extension would be to cache the cache provider implementations instead of storing them in a static Dictionary in the CacheProviderFactory. This would prevent a build up of seldom used cache providers in the application memory, as they could be removed from the cache if not used often enough, although in reality there are probably unlikely to be vast numbers of cache provider implementation instances, as most applications do not have a massive number of business object or model types.

    Read the article

  • Is executing SQL through a WebService a really bad idea?

    - by Kyle
    Typically when creating a simple tool or something that has to use a database, I go through the fairly long process of first creating a webservice that connects to a database then creating methods on this webservice that do all the type of queries I need.. methods like List<Users> GetUsers() { ... } User GetUserByID(int id) { ... } //More Get/Update/Add/Delete methods Is it terrible design to simply make the webservice as secure as I can (not quite sure the way to do something like this yet) and just make a couple methods like this SqlDataReader RunQuery(string sql) { ... } void RunNonQuery(string sql) { ... } I would sorta be like exposing my database to the internet I suppose, which sounds bad but I'm not sure. I just feel like I waste so much time running everything through this webservice, there has to be a quicker yet safe way that doesn't involve my application connecting directly to the database (the application can't connect directly to database because the database isn't open to any connections but localhost, and where the appliction resides the standard sql ports are blocked anyway) Especially when I just need to run a few simple queries

    Read the article

  • C# and SQL data layer code generator

    I've created a simple yet efficient tool to help generate stored procedures and a C# data access layer from a table.  Instead of using an ORM, this uses standard ADO .NET (SqlConnection, SqlDataReader, etc).  Check it out at www.asteio.com.  It's saved me a ton of time and I'm hoping it does the same for you....Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Failed Castle ActiveRecord TransactionScope causes future queries to be invalid

    - by mbp
    I am trying to solve an issue when using a Castle ActiveRecord TransactionScope which is rolled back. After the rollback, I am unable to query the Dog table. The "Dog.FindFirst()" line fails with "Could not perform SlicedFindAll for Dog", because it cannot insert dogMissingName. using (new SessionScope()) { try { var trans = new TransactionScope(TransactionMode.New, OnDispose.Commit); try { var dog = new Dog { Name = "Snowy" }; dog.Save(); var dogMissingName = new Dog(); dogMissingName.Save(); } catch (Exception) { trans.VoteRollBack(); throw; } finally { trans.Dispose(); } } catch (Exception ex) { var randomDog = Dog.FindFirst() Console.WriteLine("Random dog : " + randomDog.Name); } } Stacktrace is as follows: Castle.ActiveRecord.Framework.ActiveRecordException: Could not perform SlicedFindAll for Dog ---> NHibernate.Exceptions.GenericADOException: could not insert: [Mvno.Dal.Dog#219e86fa-1081-490a-92d1-9d480171fcfd][SQL: INSERT INTO Dog (Name, Id) VALUES (?, ?)] ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Name', table 'Dog'; column does not allow nulls. INSERT fails. The statement has been terminated. ved System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) ved System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) ved System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) ved System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) ved System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) ved System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) ved System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) ved System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) ved System.Data.SqlClient.SqlCommand.ExecuteNonQuery() ved NHibernate.AdoNet.AbstractBatcher.ExecuteNonQuery(IDbCommand cmd) ved NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation) ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session) --- End of inner exception stack trace --- ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session) ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Object obj, ISessionImplementor session) ved NHibernate.Action.EntityInsertAction.Execute() ved NHibernate.Engine.ActionQueue.Execute(IExecutable executable) ved NHibernate.Engine.ActionQueue.ExecuteActions(IList list) ved NHibernate.Engine.ActionQueue.ExecuteActions() ved NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) ved NHibernate.Event.Default.DefaultAutoFlushEventListener.OnAutoFlush(AutoFlushEvent event) ved NHibernate.Impl.SessionImpl.AutoFlushIfRequired(ISet`1 querySpaces) ved NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) ved NHibernate.Impl.CriteriaImpl.List(IList results) ved NHibernate.Impl.CriteriaImpl.List() ved Castle.ActiveRecord.ActiveRecordBase.SlicedFindAll(Type targetType, Int32 firstResult, Int32 maxResults, Order[] orders, ICriterion[] criteria) --- End of inner exception stack trace --- ved Castle.ActiveRecord.ActiveRecordBase.SlicedFindAll(Type targetType, Int32 firstResult, Int32 maxResults, Order[] orders, ICriterion[] criteria) ved Castle.ActiveRecord.ActiveRecordBase.FindFirst(Type targetType, Order[] orders, ICriterion[] criteria) ved Castle.ActiveRecord.ActiveRecordBase.FindFirst(Type targetType, ICriterion[] criteria) ved Castle.ActiveRecord.ActiveRecordBase`1.FindFirst(ICriterion[] criteria)

    Read the article

  • How to fix Index out of range exception on idatareader

    - by Phil
    Good morning stack overflow, I have been forced into using the idatareader as opposed to the sqldatareader which has .hasrows available. In my code I am attempting to handle nulls like this: reader = GetContent(pageid) While reader.Read If reader("content") IsNot DBNull.Value Then content = Replace(reader("content"), Chr(38) + Chr(97) + Chr(109) + Chr(112) + Chr(59) + Chr(98) + Chr(104) + Chr(99) + Chr(112) + Chr(61) + Chr(49), "") If reader("id") IsNot DBNull.Value Then contentid = reader("id") End If Else contentid = -1 content = String.Empty End If End While Outputcontent.Text = content I am getting an 'Index Out of Range Exception' here: If reader("content") IsNot DBNull.Value Then The database does 100% contain 'content'

    Read the article

  • export to excel from vb.net from sql datareader

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

    Read the article

  • VBNet2008 Transfer DATAREADER rows to CrystalReport DataSet1.xsd

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

    Read the article

  • Transfer DataReader rows to a CrystalReport DataSet

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

    Read the article

  • How to check if a field is an Image field

    - by AJ
    Hello, This might seem an easy question for some, but I am struggling with it. I am trying to use SQLDataReader.GetFieldType to check if a certain field is an Image field. Lets assume the first field of the result set is an Image field, if I do: reader.GetFieldType(0).ToString; I get System.Byte[] But is this the correct way to check for it? I really don't like: if (reader.GetFieldType(0).ToString="System.Byte[]") Is there a better way? Thanks, AJ

    Read the article

  • How to add an XML parameter to a stored procedure in C#?

    - by salvationishere
    I am developing a C# web application in VS 2008 which interacts with my Adventureworks database in my SQL Server 2008. Now I am trying to add new records to one of the tables which has an XML column in it. How do I do this? This is the error I'm getting: System.Data.SqlClient.SqlException was caught Message="XML Validation: Text node is not allowed at this location, the type was defined with element only content or with simple content. Location: /" Source=".Net SqlClient Data Provider" ErrorCode=-2146232060 Class=16 LineNumber=22 Number=6909 Procedure="AppendDataC" Server="." State=1 StackTrace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at ADONET_namespace.ADONET_methods.AppendDataC(DataRow d, Hashtable ht) in C:\Documents and Settings\Admin\My Documents\Visual Studio 2008\Projects\AddFileToSQL\AddFileToSQL\ADONET methods.cs:line 212 InnerException: And this is a portion of my code in C#: try { SqlConnection conn2 = new SqlConnection(connString); SqlCommand cmd = conn2.CreateCommand(); cmd.CommandText = "dbo.AppendDataC"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn2; ... sqlParam10.SqlDbType = SqlDbType.VarChar; SqlParameter sqlParam11 = cmd.Parameters.AddWithValue("@" + ht["@col11"], d[10]); sqlParam11.SqlDbType = SqlDbType.VarChar; SqlParameter sqlParam12 = cmd.Parameters.AddWithValue("@" + ht["@col12"], d[11]); sqlParam12.SqlDbType = SqlDbType.Xml; ... conn2.Open(); cmd.ExecuteNonQuery(); //This is the line it fails on and then jumps //to the Catch statement conn2.Close(); errorMsg = "The Person.Contact table was successfully updated!"; } catch (Exception ex) { Right now in my text input MDF file I have the XML parameter as: '<Products><id>3</id><id>6</id><id>15</id></Products>' Is this valid format for XML?

    Read the article

  • Equivalent of NextResult() method in Dataset/DataAdapter?

    - by flopdix
    Hi All, I have a stored procedure that contains 3 select statements hence i get 3 resultsets. I am aware that using SqlDataReader, i can use NextResult() method to jump to the 2nd or 3rd resultsets by calling it twice or thrice. But i want to use the dataset/dataadapter, is there any ways that i can achieve this by not changing my stored procedure? tia!

    Read the article

  • output parameter into label

    - by MyHeadHurts
    instead of returning my output paremeter value in my stored procedure to my label it returns the default value i set my output parameter to. why cant i put my output parameter into my text label Dim reader As SqlDataReader cmd.Parameters.AddWithValue("@tour", "2365") cmd.Parameters.Add("@tourname", SqlDbType.VarChar) cmd.Parameters("@tourname").Direction = ParameterDirection.Output cmd.CommandText = "test" cmd.CommandType = CommandType.StoredProcedure cmd.Connection = conn conn.Open() reader = cmd.ExecuteReader() Dim myTable As DataTable = New DataTable() myTable.Load(reader) DropDownList1.DataSource = myTable DropDownList1.DataTextField = "ddate7" DropDownList1.DataBind() Label1.Text = cmd.Parameters("@tourname").ToString conn.Close()

    Read the article

  • Difference in declaring IDisposable member in using block or at using block declaration?

    - by dotnetdev
    Hi, I have the code below: using (SqlCommand command = new SqlCommand()) { command.CommandType = System.Data.CommandType.StoredProcedure; command.Connection = new SqlConnection(); command.CommandText = ""; command.Parameters.Add(new SqlParameter("@ExperienceLevel", 3).Direction = System.Data.ParameterDirection.Input); SqlDataReader dataReader = command.ExecuteReader(); } Is there any functional impact in declaring the SqlConnection where I currently am declaring it as opposed to like so?: using (SqlCommand command = new SqlCommand()) using (SqlConnection connection = new SqlConnection()) Thanks

    Read the article

  • Passing values between pages in JavaScript

    - by buni
    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; using System.Text; using System.Web.Services; using System.IO; namespace T_Smade { public partial class ConferenceManagement : System.Web.UI.Page { volatile int i = 0; protected void Page_Load(object sender, EventArgs e) { GetSessionList(); } public void GetSessionList() { string secondResult = ""; string userName = ""; try { if (HttpContext.Current.User.Identity.IsAuthenticated) { userName = HttpContext.Current.User.Identity.Name; } SqlConnection thisConnection = new SqlConnection(@"data Source=ZOLA-PC;AttachDbFilename=D:\2\5.Devp\my DB\ASPNETDB.MDF;Integrated Security=True"); thisConnection.Open(); SqlCommand secondCommand = thisConnection.CreateCommand(); secondCommand.CommandText = "SELECT myApp_Session.session_id FROM myApp_Session, myApp_Role_in_Session where myApp_Role_in_Session.user_name='" + userName + "' and myApp_Role_in_Session.session_id=myApp_Session.session_id"; SqlDataReader secondReader = secondCommand.ExecuteReader(); while (secondReader.Read()) { secondResult = secondResult + secondReader["session_id"].ToString() + ";"; } secondReader.Close(); SqlCommand thisCommand = thisConnection.CreateCommand(); thisCommand.CommandText = "SELECT * FROM myApp_Session;"; SqlDataReader thisReader = thisCommand.ExecuteReader(); while (thisReader.Read()) { test.Controls.Add(GetLabel(thisReader["session_id"].ToString(), thisReader["session_name"].ToString())); string[] compare = secondResult.Split(';'); foreach (string word in compare) { if (word == thisReader["session_id"].ToString()) { test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session")); } } } thisReader.Close(); thisConnection.Close(); } catch (SqlException ex) { } } private Button GetButton(string id, string name) { Button b = new Button(); b.Text = name; b.ID = "Button_" + id + i; b.Command += new CommandEventHandler(Button_Click); b.CommandArgument = id; i++; return b; } private Label GetLabel(string id, string name) { Label tb = new Label(); tb.Text = name; tb.ID = id; return tb; } protected void Button_Click(object sender, CommandEventArgs e) { Response.Redirect("EnterSession.aspx?session=" + e.CommandArgument.ToString()); } } I have this code when a user clicks a button www.mypage/EnterSession.aspx?session=session_name in the EnterSession.aspx i have used the code below to track the current URL _gaq.push(['pageTrackerTime._trackEvent', 'Category', 'Action', document.location.href, roundleaveSiteEnd]); Now I would also like to track in the Action parameter the session_name from the previous page.see the code below from the previous page test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session")); Some idea how to do it? Thanx

    Read the article

  • Where do I find scripts generated by SharePoint MCMS Migration Profiles

    - by HipCzeck
    I am attempting to migrate data from an Microsoft Content Management Server (MCMS) 2002 instance into a new Microsoft Office Sharepoint Server (MOSS) 2007 installation using the Manage Microsoft Content Management Server Migration Profiles tool in the Operations space of MOSS Central Administration. When analyzing the profile, I receive 4 warnings, all of which may be safely ignored, but when I actually execute the migration profile, I get the same warnings and an additional error with a description of: Line 6: Incorrect syntax near ';'. I have seen this error numerous times when mucking about in SQL Server and recognize it as a Transact SQL error message, but can't find the actual SQL statement that is being executed so that I may determine the source of the error. EDIT: After enabling verbose logging on the MCMS 2002 Migration category, and poring through the Unified Logging Service (ULS) logs, I received a more complete stack trace at the point of the error, and a couple more anomalies listed below. Anomalies: The following is an abbreviated listing from the ULS logs around the time of the pre-migration analysis. 01 MCMS 2002 Migration Verbose Start ConnectionCheck 02 MCMS 2002 Migration Verbose End ConnectionCheck 03 MCMS 2002 Migration Verbose Start DatabaseCheck 04 MCMS 2002 Migration High Extra table SiteDeployLock will not be migrated 05 MCMS 2002 Migration High Analysis: Extra index PK__SiteDeployLock__05D8E0BE 06 MCMS 2002 Migration Verbose End DatabaseCheck 07 MCMS 2002 Migration Medium Pre-migration analysis: RootCheckTask is skipped because database check is blocked. 08 MCMS 2002 Migration Medium Pre-migration analysis: RightsGroupNameCheckTask is skipped because database check is blocked. 09 MCMS 2002 Migration Medium Pre-migration analysis: InvalidNameCheckTask is skipped because database check is blocked. 10 MCMS 2002 Migration Medium Pre-migration analysis: LeafNameCheckTask is skipped because database check is blocked. 11 MCMS 2002 Migration Medium Pre-migration analysis: LeafLengthCheckTask is skipped because database check is blocked. 12 MCMS 2002 Migration Medium Pre-migration analysis: TemplateNameCheckTask is skipped because database check is blocked. 13 MCMS 2002 Migration Medium Pre-migration analysis: TemplateCollisionCheckTask is skipped because database check is blocked. 14 MCMS 2002 Migration Medium Pre-migration analysis: PlaceholderCheckTask is skipped because database check is blocked. 15 MCMS 2002 Migration Medium Pre-migration analysis: CheckedOutItemsCheckTask is skipped because database check is blocked. 16 MCMS 2002 Migration Medium Pre-migration analysis: SubmittedItemsCheckTask is skipped because database check is blocked. 17 MCMS 2002 Migration Medium Pre-migration analysis: DeletedItemsCheckTask is skipped because database check is blocked. 18 MCMS 2002 Migration Medium Pre-migration analysis: UserCheckTask is skipped because database check is blocked. 19 MCMS 2002 Migration Medium Pre-migration analysis: FileSizeCheckTask is skipped because database check is blocked. 20 MCMS 2002 Migration Medium Pre-migration analysis: HostHeaderMapCheckTask is skipped because database check is blocked. 21 MCMS 2002 Migration Verbose Start Server check 22 MCMS 2002 Migration Verbose End Server check 23 MCMS 2002 Migration Verbose Start Server emptyness check 24 MCMS 2002 Migration Verbose End Server emptyness check 25 MCMS 2002 Migration Medium PreMigrationAnalyzer: Dry run starts 26 MCMS 2002 Migration Verbose CleanLockProcedure: start. 27 MCMS 2002 Migration High CleanLockProcedure: connection system lock is null 28 MCMS 2002 Migration Verbose Finished all tasks 29 MCMS 2002 Migration High PreMigrationAnalyzer ends with True 30 MCMS 2002 Migration Verbose Migration profile status is changed to AnalysisPassed Specifically, the two High level alerts on lines 4 and 5 are reflected in the migration report as warnings when running Pre-migration Analysis or running the migration profile. In addition, two other warnings appear in the migration report indicating two tables containing data (LayoutProperty and NodeLayout) that should be empty. According to the documentation, warnings are not sufficient cause to stop migration from occurring. Other anomalies are on lines 7-20 indicating a series of tests that are skipped because database check is blocked. The ULS doesn't give any additional warnings to indicate that the database check was blocked or exited in exceptional circumstances. After switching the profile from pre-migration analysis to exporting, there is one medium level warning that LastChangeTime is not set or incorrect. (null). As with all the skipped test names and SQL table names from the warnings, the major search engines are unable (with the exception of LayoutProperty) to find any reference to these objects or tests. Finally, the section of the log indicating the actual live migration attempt is appended below: 01 MCMS 2002 Migration Medium LastChangeTime is not set or incorrect. (null) 02 MCMS 2002 Migration Verbose Set export lock 03 MCMS 2002 Migration Verbose CleanLockProcedure: start. 04 MCMS 2002 Migration Verbose CleanLockProcedure: end. 05 MCMS 2002 Migration Verbose Prepare for export 06 MCMS 2002 Migration Verbose Open connection... 07 MCMS 2002 Migration Verbose Create temporary stored procedures 08 MCMS 2002 Migration Verbose Create temporary tables... 09 MCMS 2002 Migration Verbose Initialize temporary tables... 10 MCMS 2002 Migration Verbose InitializeTemporaryTables: start 11 MCMS 2002 Migration Verbose Initialize export table... 12 MCMS 2002 Migration Verbose InitializeExportTable: start 13 MCMS 2002 Migration Verbose CleanLockProcedure: start. 14 MCMS 2002 Migration Verbose CleanLockProcedure: end. 15 MCMS 2002 Migration High Migration throws exception: Line 6: Incorrect syntax near ';'.. Stacktrace: at System.Data.SqlClient.SqlConnection.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.SharePoint.Publishing.Internal.Administration... 16 MCMS 2002 Migration High ....MigrationBatchCommand.ExecuteImmediate(String command) at Microsoft.SharePoint.Publishing.Internal.Administration.MigrationBatchCommand.ExecuteWaitingCommands() at Microsoft.SharePoint.Publishing.Internal.Administration.MigrationDBSerializer.SerializeSelectedExportObject(StringCollection objectAttribs) at Microsoft.SharePoint.Publishing.Internal.Administration.MigrationDataAccess.InitializeExportTable(ScopeType scopeType) at Microsoft.SharePoint.Publishing.Internal.Administration.MigrationDataAccess.InitializeTemporaryTables(DateTime lastChangeTime) at Microsoft.SharePoint.Publishing.Internal.Administration.MigrationDataAccess.InitializeDatabase(DateTime lastChangeTime, Boolean isAnalysis, SqlConnection connection) at Microsoft.SharePoint.Publishing.Internal.Admin... 17 MCMS 2002 Migration High ...stration.MigrationDataAccess.InitializeDatabase(DateTime lastChangeTime, Boolean isAnalysis) at Microsoft.SharePoint.Publishing.Administration.ContentMigration.Export(MigrationDataAccess dataAccess) at Microsoft.SharePoint.Publishing.Administration.ContentMigration.MigrateInternal(). 18 MCMS 2002 Migration Verbose MigrationProfile: GetInstance. Start. 19 MCMS 2002 Migration Verbose MigrationProfile: GetInstance. End. 20 MCMS 2002 Migration Verbose Migration profile status is changed to Failed The stack trace of the failed parsing of the SQL command appear on lines 15-17. A cleaner version of the stack trace is appended below. Full Stack Trace: Migration throws exception: Line 6: Incorrect syntax near ';'.. at System.Data.SqlClient.SqlConnection.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.SharePoint.Publishing.Internal.Administration.MigrationBatchCommand .ExecuteImmediate(String command) at Microsoft.SharePoint.Publishing.Internal.Administration.MigrationBatchCommand .ExecuteWaitingCommands() at Microsoft.SharePoint.Publishing.Internal.Administration.MigrationDBSerializer .SerializeSelectedExportObject(StringCollection objectAttribs) at Microsoft.SharePoint.Publishing.Internal.Administration.MigrationDataAccess .InitializeExportTable(ScopeType scopeType) at Microsoft.SharePoint.Publishing.Internal.Administration.MigrationDataAccess .InitializeTemporaryTables(DateTime lastChangeTime) at Microsoft.SharePoint.Publishing.Internal.Administration.MigrationDataAccess .InitializeDatabase(DateTime lastChangeTime, Boolean isAnalysis, SqlConnection connection) at Microsoft.SharePoint.Publishing.Internal.Administration.MigrationDataAccess .InitializeDatabase(DateTime lastChangeTime, Boolean isAnalysis) at Microsoft.SharePoint.Publishing.Administration.ContentMigration.Export (MigrationDataAccess dataAccess) at Microsoft.SharePoint.Publishing.Administration.ContentMigration .MigrateInternal(). None of this log information indicates the SQL command that is failing a parser check. I've checked the SQL servers hosting the source and destination databases for a trace of the query, but neither seems to have triggered the parse failure condition. That appears to have happened on the SharePoint server. Are there any other locations I should investigate that might tell me where to find the source of the error?

    Read the article

  • Why does GetSqlDecimal throw when GetDecimal doesn't?

    - by I. J. Kennedy
    I have a database table that has a column of type money, allowing nulls. Using a SqlDataReader named reader, I can do decimal d = reader.GetDecimal(1); which works, unless of course we're reading a null. If I try using SqlDecimal instead--and I thought the whole point of the SqlTypes was to deal with nulls--then I get an invalid cast, whether or not the value is null. SqlDecimal s = reader.GetSqlDecimal(1); // throws an invalid cast exception What am I doing wrong? Do I really have to write a conditional statement to shepherd the value from the database to a SqlDecimal variable?

    Read the article

  • .NET and Closing SQL Server connections

    - by user307076
    I am having a hard time figuring out why the following constructor will not close connnections. When I view the active connections. Here is the code that I have. Public Sub New(ByVal UserID As Integer) Dim oConn As New SqlConnection(ConfigurationManager.ConnectionStrings("connStr").ToString()) Dim cmd As New SqlCommand("stored proc", oConn) Dim sdr As SqlDataReader cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@userID", UserID) oConn.Open() sdr = cmd.ExecuteReader() Try If Not sdr.HasRows Then sdr.Close() If Not oConn Is Nothing Then If oConn.State <> ConnectionState.Closed Then oConn.Close() End If End If cmd.Dispose() Exit Sub End If 'User has account in WATS, proceed to load account information While sdr.Read _firstname = Convert.ToString(sdr("First Name")) _lastname = Convert.ToString(sdr("Last Name")) End While Catch ex As Exception 'Throw New Exception("User Error: " + ex.Message) Finally sdr.Close() If Not oConn Is Nothing Then If oConn.State <> ConnectionState.Closed Then oConn.Close() End If End If cmd.Dispose() End Try End Sub

    Read the article

  • .NET and Closing MSSQL connections

    - by user307076
    I am having a hard time figuring out why the following constructor will not close connnections. When I view the active connections. Here is the code that I have. Public Sub New(ByVal UserID As Integer) Dim oConn As New SqlConnection(ConfigurationManager.ConnectionStrings("connStr").ToString()) Dim cmd As New SqlCommand("stored proc", oConn) Dim sdr As SqlDataReader cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@userID", UserID) oConn.Open() sdr = cmd.ExecuteReader() Try If Not sdr.HasRows Then sdr.Close() If Not oConn Is Nothing Then If oConn.State <> ConnectionState.Closed Then oConn.Close() End If End If cmd.Dispose() Exit Sub End If 'User has account in WATS, proceed to load account information While sdr.Read _firstname = Convert.ToString(sdr("First Name")) _lastname = Convert.ToString(sdr("Last Name")) End While Catch ex As Exception 'Throw New Exception("User Error: " + ex.Message) Finally sdr.Close() If Not oConn Is Nothing Then If oConn.State <> ConnectionState.Closed Then oConn.Close() End If End If cmd.Dispose() End Try End Sub

    Read the article

  • Service Broker message_body error when casting binary data to xml in C#

    - by TimBuckTwo
    I am using Message Broker with Sql server 2008, and designing an External Activator service to consume messages from my target queue. My Problem: Cant cast the returned message body from the SqlDataReader object: "WAITFOR (RECEIVE TOP(1) conversation_handle, message_type_name, message_body FROM [{1}]), TIMEOUT {2}" operation, I cant cast the binary data to XML in C# SqlBinary MessageBody = reader.GetSqlBinary(2); MemoryStream memstream = new MemoryStream(); XmlDocument xmlDoc = new XmlDocument(); memstream.Write(MessageBody.Value, 0, MessageBody.Length); memstream.Position= 0; //below line Fails With Error:{"Data at the root level is invalid. Line 1, position 1."} xmlDoc.LoadXml(Encoding.ASCII.GetString(memstream.ToArray())); memstream.Close(); To prevent poison message I do not use CAST(message_body as XML), Any suggestions would be greatly appreciated.

    Read the article

  • Compiled Linq Queries with Built-in SQL functions

    - by Brandi
    I have a query that I am executing in C# that is taking way too much time: string Query = "SELECT COUNT(HISTORYID) FROM HISTORY WHERE YEAR(CREATEDATE) = YEAR(GETDATE()) "; Query += "AND MONTH(CREATEDATE) = MONTH(GETDATE()) AND DAY(CREATEDATE) = DAY(GETDATE()) AND USERID = '" + EmployeeID + "' "; Query += "AND TYPE = '5'"; I then use SqlCommand Command = new SqlCommand(Query, Connection) and SqlDataReader Reader = Command.ExecuteReader() to read in the data. This is taking over a minute to execute from C#, but is much quicker in SSMS. I see from google searching you can do something with CompiledQuery, but I'm confused whether I can still use the built in SQL functions YEAR, MONTH, DAY, and GETDATE. If anyone can show me an example of how to create and call a compiled query using the built in functions, I will be very grateful! Thanks in advance.

    Read the article

  • automatic id generation which is a primary key

    - by abhi
    in vb.net while entering a new entry i want to assign a record a unique id like in case of numeric i do this way Dim ItemID As Integer KAYAReqConn.Open() SQLCmd = New SqlCommand("SELECT ISNULL(MAX(ItemID),0) AS ItemID from MstItem", ReqConn) Dim dr As SqlDataReader dr = SQLCmd.ExecuteReader If dr.HasRows Then dr.Read() ItemID = dr("ItemID") + 1 End If dr.Close() in this case m using itemid as a unique id and the format is 1,2,3... and m finding out the max and assigning to a new record but how to assign if the previous id is of the a00001,a00002,a00003,a00004...so on. how i do i produce a unique id in this case

    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

  • SqlCommand.Paramaters.AddWithValue issue

    - by Petrus
    Hi I have a problem with the folowwing piece of code. I am passing a parameter (List) to a methods executing the following code. When it executes sql throws an error saying that the proc expects a parameter that was not provided. I know this error and understand it, and when stepping through the code I can see that the cmdExecuteReader object has a collection of parameters, with the correct naame and value. What cou be the problem? public SqlDataReader ExecuteReader(string storedProcedure, List<SqlParameter> parameters = null) { SqlCommand cmdExecuteReader = new SqlCommand() { CommandType = System.Data.CommandType.Text, Connection = conn, CommandText = storedProcedure }; if (parameters != null) { foreach (SqlParameter param in parameters) { cmdExecuteReader.Parameters.AddWithValue(param.ParameterName, param.Value); } } if (conn.State == System.Data.ConnectionState.Closed) conn.Open(); return cmdExecuteReader.ExecuteReader(); }

    Read the article

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