.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

SQlCeResultSet.Update throws a duplicate value exception

Posted By:      Posted Date: October 27, 2010    Points: 0   Category :Sql Server


I am using VS2008, C#, SQL Server Compact Ed 3.5, and SQLCeResultSet.SetValues then SQLCeResultSet.Update to update a record in the database where a GUID is the primary key.  When I debug my program everything looks good and all inserts and updates work perfectly fine except when I try to update this one record in one of the tables I get the following exception:

System.Data.SqlServerCe.SqlCeException was caught
  Message="A duplicate value cannot be inserted into a unique index. [ Table name = TableA ,Constraint name = KeyConstraint ]"
  Source="SQL Server Compact ADO.NET Data Provider"
       at System.Data.SqlServerCe.SqlCeResultSet.InternalUpdate(Object sender)
       at System.Data.SqlServerCe.SqlCeResultSet.Update()
       at MyProgram.UpdateRecords(SqlCeConnection sqlceconnection, SqlCeCommand command, DataTable modified, Properties properties)

The deal is that I am not inserting the record again!! This is an update. I have stepped through the code and it is clearly finding the record in the database, updating the values in the SQLCEResultSet (

View Complete Post

More Related Resource Links

userprincipal.changepassword throws exception


Hi all,

      userprincipal.changepassword(oldpassword, newpassword);

gives error: that is Configuration information could not be read from the domain controller, either because the machine is unavailable, or access has been denied. (Exception from HRESULT: 0x80070547)

but userDirectoryEntry.invoke("ChangePassword", new object[] { oldpassword, newpassword });

      userDirectoryEntry.CommitChanges works fine.

Any one please tell me the reason behind this.

WebControls.TableRow throws exception on Add()


I have the following method to strip hidden and user-specified columns from a gridviewrow and return a tablerow. 

    Private Shared Function StripHiddenColumns(ByVal gvRow As GridViewRow, ByVal ColumnsToExclude() As Integer) As TableRow

        Dim row As New TableRow
        Dim i As Integer = 0
            For Each cell As TableCell In gvRow.Cells
                If cell.Visible Then
                    If Not ColumnsToExclude.Contains(i) Then
                    End If
                End If
                i += 1

            Return row
        Catch ex As Exception
            Throw ex
        End Try
    End Function

However, when I run this code and hit the Add method for the TableRow,  I get an InvalidOperationException stating the Collection was modified; enumeration operation may not execute.  I've gotten this exception before, but usually it's because I'm attempting to modify a table that is databound.  This particular one is not, i am creating it.  Can anyone offer any insight? 

Thanks in advance.


SPWorkflowManager.CancelWorkflow throws an exception


Sorry, I had posted that same question in the "Dev and Programming" forum, but I'm reposting here because it's more of a workflow related question.

We are trying to cancel workflow programmatically.

It used to work fine until we migrated our environment to a new server and now it fails.

Our code goes something like this: 


foreach (SPWorkflow wf in form.Workflows)


//code omitted for brievety



But an ArgumentException is thrown.

Msdn docs say that an ArgumentNullException exception can be thrown (ArgumentNullException: The workflow to cancel belongs to an SPWeb object that has been deleted) but it is actually an ArgumentException that is thrown. Plus I know for sure that the SPWeb does not get deleted.

I tried to reflector what piec

EvaluateOldNewStates() throws exception when updating TreeViewItem.IsSelected

I apply a WPF theme in my application. At some point in my code, I need to change the selected tree view item. so I update the property MyViewModel.IsSelected and raise PropertyChanged event. Then I get this: Object reference not set to an instance of an object. System.Windows.StyleHelper.EvaluateOldNewStates(MultiTrigger multiTrigger, DependencyObject triggerContainer, DependencyProperty changedProperty, DependencyPropertyChangedEventArgs changedArgs, Int32 sourceChildIndex, Style style, FrameworkTemplate frameworkTemplate, Boolean& oldState, Boolean& newState) System.Windows.StyleHelper.InvokePropertyTriggerActions(TriggerBase triggerBase, DependencyObject triggerContainer, DependencyProperty changedProperty, DependencyPropertyChangedEventArgs changedArgs, Int32 sourceChildIndex, Style style, FrameworkTemplate frameworkTemplate) System.Windows.StyleHelper.OnTriggerSourcePropertyInvalidated(Style ownerStyle, FrameworkTemplate frameworkTemplate, DependencyObject container, DependencyProperty dp, DependencyPropertyChangedEventArgs changedArgs, Boolean invalidateOnlyContainer, FrugalStructList`1& triggerSourceRecordFromChildIndex, FrugalMap& propertyTriggersWithActions, Int32 sourceChildIndex) System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEve

Page navigation in a frame throws an exception

I created a very simple WPF project that exhibits the following error. I have no idea how to get of this error. System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.Menu', AncestorLevel='1''. BindingExpression:Path=TemplatedParent; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'CommandTarget' (type 'IInputElement') Steps to reproduce:1. Create a WPF Application project in Visual Studio 2008 (Windows 7)2. Create Page1.xaml <Page x:Class="WpfApplication1.Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page1"> <TextBlock> <Hyperlink NavigateUri="Page2.xaml">Page 2</Hyperlink> </TextBlock> </Page> 3. Create Page2.xaml <Page x:Class="WpfApplication1.Page2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page2"> <TextBlock> <Hyperlink NavigateUri="Page1.xaml">Page 1</Hyperlink> </TextBlock> </Page> 4. Add a frame in Window1.xaml <Window x:Class="WpfAppli

CLR Profiler for the .NET Framework 2.0 : A bug (with possible fix!) - It throws exception - null ob

CLR Profiler for the .NET Framework 2.0   I tied to profile a service on my machine. But when I try to see the heap data (during reading of the log file) it throws exception that the object reference is not set (null object).   I debugged the CLR profiler and found that in class ReadNewLog, there is method "ReadFile" internal void ReadFile(long startFileOffset, long endFileOffset, ReadLogResult readLogResult, int requestedIndex) ...     if (matched > 0 && c != -1)     {         /* use some other stack trace as a reference */         int otherStackTraceId = ReadInt();         otherStackTraceId = stacktraceTable.MapTypeSizeStacktraceId(otherStackTraceId);         int[] stacktrace = stacktraceTable.IndexToStacktrace(otherStackTraceId);         if (matched > stacktrace.Length - hadTypeId)             matched = stacktrace.Length - hadTypeId;         for(int i = 0; i < matched; i++)         {             int funcId = stacktrace[i + hadTypeId];             Debug.Assert

Update duplicate field in same table

  hi I have a table with some other duplicate field as below   IssueID Title A1 Test1 A1 Test2 A2 Test3 A2 Test4 A3 Test5 A4 Test6   i want update all duplicate field based on IssueID and the final result will show as below   IssueID Title A1 Test1 A1 Test1 A2 Test3 A2 Test3 A3 Test5 A4 Test6 may someone help me?  

SharePoint 2010 : Creating SPSite object throws exception FileNotFoundException

We are in a process of upgrading from SharePoint 2007 to SharePoint 2010. I had written a Service which runs under default web site on the SharePoint web server. This service's app pool account uses the farm admin account. The service was working with no issue on SharePoint 2007 x64bit server. When I installed and run the same service on SharePoint 2010 x64bit box. I get the FileNotFoundException on SPSite site = new SPSite(http://myserver/sites/projects/project01); I have given the pool account running this server following rights: The Farm Admin The Site Collection Admin The Database Sys Admin The Local Admin No Luck. Thank you in advance for your help.

RESTful WCF with session required throws exception

Interface code:   [ServiceContract(Namespace="", SessionMode=SessionMode.Required)]   public interface ITestService   {     [WebInvoke(UriTemplate = "",         Method = "POST",         BodyStyle = WebMessageBodyStyle.WrappedRequest)]     [OperationContract]     string ModInit(String arg); ... Service code: [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] public class TestService : ITestService public string ModInit(String arg) ... Startup code: WebServiceHost host = new WebServiceHost(typeof(TestService),    new Uri("http://localhost:10000/test)); ... Client code: Uri address =  new Uri("http://localhost:10000/test"); var factory = new WebChannelFactory<ITestService>(new   WebHttpBinding { AllowCookies = true }, address); ITestService svc = factory.CreateChannel(); string resp = svc.ModInit("test"); ... This code throws a InvalidOperationException: Contract requires Session, but Binding 'WebHttpBinding' doesn't support it ... Does anyone know to get PerSession and SessionMode=SessionMode.Required working in the self hosted code above? Thanks, Mike

ActivityXamlServices.Load throws exception

Hi guys, I have very strange problem and I don't know what to do. I have written application in workflow 4. This application contains a few parts. One of the part is responsible for testing workflow in rehosted workflow designer and another for running workflow periodically. In both parts I use the same code, which is responsible for create Activity from xaml. And here is my problem. In one part this code works fine but in the second part of my application it throws exception. This is the code of which I speak. public static Activity XamlToActivity(Workflow Workflow) { byte[] workflowFilestream = Workflow.FileStream; MemoryStream workflowStream = new MemoryStream(); workflowStream.Write(workflowFilestream, 0, workflowFilestream.Length); return ActivityXamlServices.Load(workflowStream); } Exception Message: "Cannot set unknown member '{http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation}VirtualizedContainerService.HintSize'.' Line number '1' and line position '11'. I'm sure, that xaml is correct (I saved it from workflow designer). It seems to me important thing, that ActivityXamlServices.Load throws exception, when I use it in another Thread (I create new threat, which runs workflows). Someone have any idea or doing something similar? I would be very grateful for help.

Release mode application throws Break instruction exception - code 80000003 when running in WinDbg


Here is the initial output of my program after running it from WinDbg:

CommandLine: "C:\Documents and Settings\Administrator\My Documents\Work\QMI_Test_Tool\QMI_UT_Source\Release\QMI Validation Tool.exe"
Symbol search path is: SRV*c:\symbols*http://msdl.microsoft.com/download/symbols
Executable search path is: 
ModLoad: 00400000 0048f000  QMI Validation Tool.exe
ModLoad: 7c900000 7c9b2000  ntdll.dll
ModLoad: 79000000 7904a000  C:\WINDOWS\system32\mscoree.dll
ModLoad: 7c800000 7c8f6000  C:\WINDOWS\system32\KERNEL32.dll
ModLoad: 77dd0000 77e6b000  C:\WINDOWS\system32\advapi32.dll
ModLoad: 77e70000 77f03000  C:\WINDOWS\system32\RPCRT4.dll
ModLoad: 77fe0000 77ff1000  C:\WINDOWS\system32\Secur32.dll
ModLoad: 7c420000 7c4a7000  C:\WINDOWS\WinSxS\x86_Microsoft.VC80.CRT_1fc8b3b9a1e18e3b_8.0.50727.4053_x-ww_e6967989\MSVCP80.dll
ModLoad: 78130000 781cb000  C:\WINDOWS\WinSxS\x86_Microsoft.VC80.CRT_1fc8b3b9a1e18e3b_8.0.50727.4053_x-ww_e6967989\MSVCR80.dll
ModLoad: 77c10000 77c68000  C:\WINDOWS\system32\msvcrt.dll
ModLoad: 7c9c0000 7d1d7000  C:\WINDOWS\system32\SHELL32.dll
ModLoad: 77f10000 77f59000  C:\WINDOWS\system32\GDI32.dll
ModLoad: 7e410000 7e4a1000  C:\WINDOWS\system32\USER32.dll
ModLoad: 77f60000 77fd6000  C:\WINDOWS\system32\SHLWAPI.dll
ModLoad: 7c4c0000 7c53d000  C:\WINDOWS\WinSxS\x86_Microsoft.VC80.CRT_1fc8b3b9a1e18e3b_8.0.50727.4053_x-ww_e6967989\m

TryConnect, TcpClient.Connect that doesn't throws exception, it returns bool

using System;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;

namespace TryConnect
  class Program
    [DllImport("ws2_32.dll", SetLastError = true)]
    internal static extern int WSAConnect(
                     [In] IntPtr socketHandle,
                     [In] byte[] socketAddress,
                     [In] int socketAddressSize,
                     [In] IntPtr inBuffer,
                     [In] IntPtr outBuffer,
                     [In] IntPtr sQOS,
                     [In] IntPtr gQOS

    [DllImport("ws2_32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    internal static extern IntPtr WSASocket(
                        [In] AddressFamily addressFamily,
                        [In] SocketType socketType,
                        [In] ProtocolType protocolType,
                        [In] IntPtr protocolInfo,
                        [In] uint group,
                        [In] int flags

    [DllImport("ws2_32.dll", ExactSpelling = true, SetLastError = true)]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    internal static extern int closesocket(
                       [In] IntPtr socketHandle


Using "Transaction activty" in Workflow to update 2 tables - throws "communication with the underlyi


I created a transactionscope over 2 code activities,
Code activity1 opens a connection, fires an insert into a table and closes the connection.
Code actibity2 also opens connection, does a simple insert into same table and closes the connection

I get the following exception:
The 1st code activity runs fine, then the second code activity fails when it tries to open a connection and I get this message "Communication with the underlying transaction manager has failed. "

I have persistence services working properly, I'm able to persist the workflows..which means my MSDTC is configured right, also able to insert data into the tables..but when I use the transactionscope I just get that error whever I open the connection in the second code activity

Am I missing something or this is one of those inbuilt bugs of the "workflowfoundation" bugs like the timer etc?

IHostAssemblyStore::ProvideAssembly: CLR throws exception "The located assembly's manifest definiti


PostSharp 2.0 includes a CLR host and implements IHostAssemblyStore::ProvideAssembly.

From managed code, I invoke:
Assembly.Load("logicnp.cryptolicensing, Version=, Culture=neutral, PublicKeyToken=4a3c0a4c668b48b4")
My implementation of IHostAssemblyStore::ProvideAssembly receives the following input for the first parameter pBindInfo:
0x002cd578 {


lpReferencedIdentity=0x03c123f8 "logicnp.cryptolicensing, version=, culture=neutral, publickeytoken=4a3c0a4c668b48b4" 

lpPostPolicyIdentity=0x03c14620 "logicnp.cryptolicensing, version=, culture=neutral, publickeytoken=4a3c0a4c668b48b4, processorarchitecture=x86" ...


My implementation then returns the right stream. Note that the binding identity of that file is "logicnp.cryptolicensing, version=, culture=neutral, publickeytoken=4a3c0a4c668b48b4".

When I return this file from ProvideAssembly, the CLR throws the following exception:

Could not load file or assembly 'logicnp.cryptolicensing, Version=, Culture=neutral, PublicKeyToken=4a3c0a4c668b48b4' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

So the

MembershipUser.UnlockUser() throws exception: A constraint violation occurred. (Exception from HRESU



I'm having some problems getting code to work that'll re-enable a locked out account. Below is my code:

public bool ChangeAccountStatus(string username, bool enable)

                if (AzMan.CheckAccess(Operations["ChangeAccountStatus"], null) == false)
                    throw new SecurityException();

                MembershipUser user = Membership.GetUser(username);
                if (enable)
                    user.IsApproved = true;
                    if (user.IsLockedOut)
                    user.IsApproved = false;

                return enable;
            catch (Exception e)
                return !enable;

Enabling a disabled account works fine but when the account is locked out, I hit the user.UnlockUser() line and get the following exception:

Message "A constraint violation occurred. (Exception from HRESULT: 0x8007202F)"

StackTrace " at System.DirectoryServices.DirectoryEntry.CommitChanges()\r\n


HTTP Module :Item.Update() gives exception 'Operation is not valid due to the current state of the


Hi, I have created a http module to update the list item but when i use the Update function of SPListItem object it gives the error: "Operation is not valid due to the current state of the object". Below is the HTTP Module i have written to update the List Item. Please suggest






public class SiteUsage : IHttpModule



WCF NetDispatcherFaultException - Throws exception only when I include file (List)


Hi All,

My service would return a file (List<byte> - use WSSF so dont know why it is a list rather than a byte array. When I consume the service it throws the following exception:

"The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://www.tempuri.org. The InnerException message was 'Error in line 1 position 1124. Expecting state 'Element'.. Encountered 'Text'  with name '', namespace ''. '.  Please see InnerException for more details."

Any ideas on how to fix it would be much appreciated.



ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend