FAQ Database Discussion Community


XSD: choice based on the condition of an element

xml,xsd,.net-4.0
I'm trying to come up with an XSD for this kind of XML: <root> <valid> <a>1</a> <b>foo</b> <c>bar</c> </valid> <valid> <a>2</a> <c>bar</c> <d1>baz</d1> </valid> <valid> <a>3</a> <c>bar</c> <d2>baz-restricted</d2> <e>qux</e> </valid> </root> In all elements named valid, each child-element is mandatory. I know I need to make the xs:choice conditional on...

Define Next Start Point When Number of Items Unknown

c#,.net,multithreading,.net-4.0,parallel-processing
I have a web service I need to query and it takes a value that supports pagination for its data. Due to the amount of data I need to fetch and how that service is implemented I intended to do a series of concurrent http web requests to accumulate this...

VB.net application too fast for SQL query loop

sql-server,vb.net,.net-4.0
I am designing software using Visual Basic with .Net 4.0 with MS SQL server backend for storing data. I have designed a class for the "Employee Wages" section of the database. The purpose of this Class's sub routine is to reset the payroll tables that have been prepared. Each time...

Adding string to embedded resources file stops project from compiling

c#,.net,c#-4.0,.net-4.0,embedded-resource
A resources file is compiled as an embedded resource in Project1. Strings are accessed code by: Resources.ResourcesFileName.ResourceManager.GetString("Resource1"); Project1 compiles and works fine. I cleaned before building to confirm. When I add another string to the resource, (TFS checks out the file) Project1 no longer compiles. 'ResourcesFileName' is not a member...

SerialPort object does not receive any data under Windows XP

c#,.net-4.0,serial-port,windows-xp
I have a SerialPort object to control a gsm modem connected to a virtual com port. My problem is that i do not receive any data under Windows XP. The DataReceived Event is not triggered nor outputs port.ReadExisting() any data if called periodically. But when i shut down my program...

Acess Denied. Reading and writing the file. Grant reading permission

c#,.net,visual-studio-2012,.net-4.0
After installation the application gives error access denied to the file PathName\\BLsms.ocx Here PatheName is complete path. Advance installer is used to create the installer. Then application is installed in C Drive. How can I make these files read and writable? I am using this code. try { this.brlmfc =...

Implement IDownloadManger for my application only

c#,winforms,.net-4.0,webbrowser-control
I'm using the WebBrowsercontrol in a WinForms application and have implemented my own download manager by following the instructions here. My custom download manager works, but also overrides the download manager for Internet Explorer, too*. Is there a way to only have the custom download manager appear when my application...

Restrict Dependencies to specific .NET version using NuGet

c#,.net,visual-studio-2013,.net-4.0,nuget
I have a C# solution targeted for framework 4.5.1 but the server I need to install this on uses 4.0 so I need to roll this back. The developer has used NuGet (which I'm not really familiar with) for dependency management. I've seen there is a way to request specific...

Deserialize array Object using Newtonsoft Json.Net

c#,json,.net-4.0,json.net,deserialization
I have following json string [ { "itemtype": "note", "body": "some text" }, { "itemtype": "list", "items": [ { "item": "some text" }, { "item": "some text" } ] }, { "itemtype": "link", "url": "some link" } ] Which I need to parse in C#. My string might return error...

Different behaviour when collection modified between Dictionary and ConcurrentDictionary

c#,dictionary,.net-4.0,enumeration,concurrentdictionary
With a normal Dictionary code as list below, I get exception that Collection was modified; enumeration operation may not execute. Dictionary<int, int> dict2 = new Dictionary<int, int>(); dict2.Add(1, 10); dict2.Add(2, 20); dict2.Add(3, 30); dict2.Add(4, 40); foreach (var d in dict2) { if (dict2.ContainsKey(2)) dict2.Remove(2); if (dict2.ContainsKey(3)) dict2.Remove(3); } However with...

wpf c# DispatcherUnhandledException not firing

c#,wpf,error-handling,.net-4.0
I am in the process of creating a new WPF application and wanted to implement the DispatcherUnhandledException handler. My application is using a custom [STAThread] to handle the application startup rather than the App.XAML As you can see I register the handler in the Main() method: [STAThread] public static void...

Installing Asp.Net SignalR error while installing

asp.net,.net,.net-4.0,signalr,nuget
I am trying to install SignalR in Visual Studio 2010 professional project. But I am getting this error: Could not install package 'Microsoft.Owin.Security 2.1.0'. You are trying to install this package into a project that targets ' .NETFramework,Version=v4.0', but the package does not contain any assembly references or content files...

External Function Call Blocks UI thread

c#,multithreading,.net-4.0,task
I am working on an application that talks to a motion controller over ethernet. To connect to the controller I use a library provided by the supplier, to connect you create an instance of the controller than then tell it to connect, this has the chance to block for a...

Binding two queries in the same chart

c#,sql-server,.net-4.0
I have this query: public static string shitjeJavore = "with java as " +" (select subscription.username as username, " +"convert(varchar,max(subscription.saledate),101)as saledate, " +" convert(varchar,convert(datetime,max(startdate),100)) as startdate, " +" convert(varchar,convert(datetime,max(enddate),100)) as enddate from subscription " +" inner join SaleReport on SaleReport.username=subscription.username " +" inner join login on login.username=subscription.username " +" inner...

What is the C#/.NET 4.0+ way to implement a cancellable background thread?

c#,.net,multithreading,.net-4.0
Before .NET 4.0, my understanding is that if one wanted to start a thread to do some work which could be cancelled, one would start a BackgroundWorker. .NET 4 brought about the TAP model, and a whole bunch of new async and threading stuff. Is the BackgroundWorker still the way...

Wiring a wrapper for a third party API and wanted some advice

c#,.net-4.0,third-party
Background - I'm writing a wrapper for a third party API. The third part API controls a program called Sherlock. This is a machine vision application that takes an image and runs inspection tools on it. The tools that are doing the inspections will place the result into variables with...

Simulate async/await with task.continuewith in .net 4.0

c#,asynchronous,.net-4.0,async-await
Is it possible to simulate the behaviour of async/await in .NET 4.0 without using the Microsoft.Bcl.Async Package? I tried running Task myTask = Task.Factory.Startnew(MyMethod,...) myTask.ContinueWith((x)=>{ //do stuff when myTask is completed },...); //code that i hoped would run without waiting for myTask but this blocks my UI while myTask is...

Can I run scriptcs with useLegacyV2RuntimeActivationPolicy?

.net-4.0,scriptcs
I have a DLL (Microsoft.SqlServer.BatchParser) which I need to reference in a scriptcs file. The following DLL can only be referenced if useLegacyV2RuntimeActivationPolicy is included in the app.config file. For example, this console application: namespace ConsoleApplication { class Program { static void Main(string[] args) { var batchParser = new ManagedBatchParser.Parser();...

When to use ReaderWriterLockSlim and When to use ConcurrentBag? [closed]

c#,.net-4.0
Is it the same if I used ConcurrentBag (to handle scenario of one writer & multiple readers) instead of using ReaderWriterLockSlim on a List<> ?? UPDATE 1: The scenario is that there are multiple threads that can reach a static list and some may need to read others may need...

MissingManifestException in mscorlib.dll on IMessageService.ShowXXXX

c#,wpf,.net-4.0,resources,catel
In my view model, I have a IMessageService, which is initialized in the constructor: private IMessageService messageService; public MyViewModel() { messageService = ServiceLocator.Default.ResolveType<IMessageService>(); } Its Show method works, but ShowError, ShowInformation and ShowWarning (anything in need of a resource, here the icons) crash with a MissingManifestException pointing towards Catel.Properties.Resources.resources manifest....

Detect if webclient's DownloadComplete event handler execution finished?

c#,multithreading,asynchronous,.net-4.0,async-await
I am new to the whole Async and Threading world of the programming. And I am stuck at one problem. Following code is simplified version for the better understanding. What I am trying to do the three things, 1) Hit api in loop using WebClient and it's Async method and...

Threading: Application Freezes after using Thread.Join()

c#,.net,multithreading,.net-4.0
I understand that the .Join() causes the threads to pause and wait till a thread finishes its work but how can I avoid the UI from getting frozen? This is what my codes look like" Thread dataThread = new Thread(()=> data = getData(id)); dataThread.Start(); dataThread.Join(); Thread storingThread = new Thread(()=>...

The target “TransformAll” does not exist in the project T4 transformation MSBuild

visual-studio-2013,.net-4.0,msbuild
I want to transform my T4 templates using MSBuild, so I found this link. But when running: msbuild solution.sln /t:TransformAll I get the following error "The target "TransformAll" does not exist in the project". The same happens if I try to compile a single project. No matter if I open...

HTTP Post Request to web service . ERROR : Index was outside the bounds of the array

c#,multithreading,.net-4.0,xmlhttprequest
I have the following code for posting multiple HTTP Post requests to a web service from XML files. The problem here is if I put thread.Join() in the place where it is commented , I am able to put all the requests successfully . But if i use the second...

Windows Forms WebBrowser control error on .net 4.0 framework

c#,.net,com,.net-4.0,winforms-interop
I have a fatal error thrown from my c# code where I have customized forms web browser to support browser autocomplete functionality. The exception gets thrown only on .net 4.0 framework, when we try to obtain the WebBrowserSite COM interfaces. error thrown at _baseIDocHostUiHandler = (WebBrowserNativeMethods.IDocHostUIHandler) Marshal.GetTypedObjectForIUnknown(_unkInnerAggregated, typeof (WebBrowserNativeMethods.IDocHostUIHandler)); Code:...

Using a custom dictionary for spellcheck with an http url

c#,wpf,.net-4.0
I have a WPF control that contains a TextBox that I would like to enable SpellCheck on, as well as use a custom dictionary. <TextBox Name="SpellBoxControl" SpellCheck.IsEnabled="True" > <SpellCheck.CustomDictionaries> <system:Uri>\\network-share\customWords.lex</system:Uri> </SpellCheck.CustomDictionaries> </TextBox> I've managed to get this to work just fine by using a custom dictionary that is located on...

Can't use WebBrowser Scrollbar on winforms

winforms,.net-4.0,webbrowser-control
I have a Winforms VB.NET application that uses a WebBrowser control to render HTML. The WebBrowser is embedded into a Panel, which is on another Panel. So the embedding is Form --> Panel --> Panel --> WebBrowser Whenever the DocumentText surpasses the visible borders of the WebBrowser the scrollbar is...

If and only if in vb.net 4?

vb.net,if-statement,.net-4.0
IIF seems to be unavailable in .net 4, do we have a replacement? IIf(condition = 0, True, False) Would be a simple if statement a good replacement?...

Updating the key object in AddOrUpdate method

c#,.net-4.0,concurrentdictionary
I have a Test class. class Test { public int Id { get; set; } public int Val { get; set; } } I would like to setup a ConcurrentDictionary with an int as Key and Test as the value. bool External = true; ConcurrentDictionary<int, Test> data = new ConcurrentDictionary<int,...

Issue raising a simple event

c#,events,.net-4.0,raiseevent
My interface has an event that don't has an arguments public interface IMyInterface { event EventHandler OnSomethingHappened; } Here is how I am implementing it. public class MyBaseClass : IMyInterface { private event EventHandler onSomethingHappened; public event EventHandler OnSomethingHappened { add { onSomethingHappened-= value; onSomethingHappened+= value; } remove { onSomethingHappened-=...

Serial Port Asynchronous Read Using Base Stream

c#,asynchronous,.net-4.0,serial-port
I have found that the C# serial port implementation can be pretty flaky when it comes to the datarecieved event, so I decided to implement my own asynchronous read using the underlying stream. I implemented a continuous read loop that I would expect to get a stack overflow due to...

Validating texbox control within gridview

c#,winforms,datagrid,.net-4.0
I am developing an application where teacher are allowed to enter marks for students, based on selecting a subject they teach. Now I am using a 4 columed datagrid to which I am populating all the student rollnum(1st col) and name (2nd col) and textbox control to enter Test marks(3rd...

Use async/await with Microsoft.Bcl.Async: the type or namespace name 'async' could not be found

c#,asp.net,asynchronous,.net-4.0
I need to use async/await on the .net framework 4, VS2013 (web forms application). I installed Microsoft.Bcl.Async via nuget, but I get always: The type or namespace name 'async' could not be found And if I try to define a namespace like: using Microsoft.Threading.Tasks; I get The type or namespace...

AutoCompleteStringCollection with TextChanged Event

c#,winforms,.net-4.0
I'm currently using a text box to filter some entries. I have the display updating on the text box TextChanged event, so the user isn't hitting enter or pressing a button to begin filtering. I want to use an AutoCompleteStringCollection to remember entries typed into the text box; however, if...

Updating DataGrid causes GUI to hang?

c#,wpf,datagrid,.net-4.0
So I bind a DataGrid to an ICollectionView. I set the virtualization to True. <DataGrid EnableColumnVirtualization="True" EnableRowVirtualization="True" IsReadOnly="True" ItemsSource="{Binding ImportRecords, IsAsync=True}" Name="ImportRecordsView"> I create a task via TPL to populate an ObservableCollection (presumably not on the GUI thread). Task<ObservableCollection<myClass>> task = Task.Factory.StartNew( () => { var records = new ObservableCollection<myClass>();...

Serialize/Deserialize class containing byte array property into XML

c#,.net,xml,serialization,.net-4.0
My data class that will be serialized into XML look like this: [XmlType(TypeName = "SPCFileInfo")] [Serializable] public class SPCFileInfoProtocol { [XmlElement("CompanyCode")] public string CompanyCode { get; set; } [XmlElement("FileName")] public string FileName { get; set; } [XmlElement("FileVer")] public int FileVer { get; set; } [XmlElement("FileSize")] public long FileSize { get;...

Sybase SQL Anywhere driver throws NullReferenceException

c#,multithreading,.net-4.0,nullreferenceexception,sqlanywhere
I have the problem, that in my multithreading application, the SQL Anywhere 12 driver throws NullReferenceExceptions. The Exception is always thrown at different points, but always during opening a connection. There are a maximum of 5 open connections. The stack trace is the following: I have no idea why this...

Wait for an event to fire using tasks in .net 4

c#,winforms,.net-4.0,task
I have function A that calls function B from an external class that I cannot modify. Function B fires an event when completed on which I subscribed the doSomeStuff function. I only want to finish Function A when doSomeStuff is finished. I can only use .Net 4, so no use...

how to retrieve keys only when filter by value

c#,.net-4.0,concurrentdictionary
ConcurrentDictionary<int, int> dic = new ConcurrentDictionary<int, int>(); dic.AddOrUpdate(1, 2, (s, i) => 0); dic.AddOrUpdate(2, 3, (s, i) => 0); dic.AddOrUpdate(3, 1, (s, i) => 0); dic.AddOrUpdate(4, 7, (s, i) => 0); I want to only select keys where the value is greater than 5. How can I do this?...

Sitecore: InvalidOperationException: The asynchronous action method 'Search' cannot be executed synchronously

asp.net-mvc-4,asynchronous,.net-4.0,sitecore,sitecore6
We are using Sitecore 6.6 under .NET 4.0 and using MVC 4 with it. we are trying to implement an asyncontroller and async action within it. We call this action using an ajax request. we have set up a route to the action and also added that route to the...

ASP.NET instantiating regex within a static method and thread safety

c#,asp.net,regex,.net-4.0,thread-safety
Taken the following class that is part of a ASP.NET HttpModule (and taken that I know about regex and html, I don't have a choice in this one though): sealed internal class RegexUtility { public static Regex RadioButton { get; private set; } static RegexUtility() { RadioButton = new Regex(@"<input.*type=.?radio.*?>",...

Error loading aspx page: Only part of webpage displays correctly after loading the page for the 2nd time in an active session

c#,asp.net,vb.net,visual-studio-2010,.net-4.0
I have an aspx page, which has a main display view and a form view. The main view is supposed to display a set of records and have a button (which redirects to the form) to add a new record. If I add a new record for the first time,...

How to separate a ViewModel in multiple?

c#,wpf,mvvm,.net-4.0,catel
Following on this question's comments, I feel obliged to ask this one. It's an application I'm currently working on, and to avoid further issues and to keep on working with Catel (which, whatever troubles I may have with it, is really pleasant to use), I will need explanations on a...

How to catch an OperationCanceledException when using ContinueWith

c#,asynchronous,.net-4.0,async-await
I have some code I'm downgrading from .NET 4.5's lovely async and await keywords to .NET 4.0. I'm using ContinueWith to create a continuation similar to the way await works. Basically, my old code was: var tokenSource = newCancellationTokenSource(); var myTask = Task.Run(() => { return MyStaticClass.DoStuff(tokenSource.Token); }, tokenSource.Token); try...

What does the Flush method do on a DeflateStream?

.net,.net-4.0,stream,deflatestream
What does the Flush method do on a DeflateStream? The description for the DeflateStream.Flush method is: Flushes the contents of the internal buffer of the current stream object to the underlying stream. Is this an accurate description? And if so, what does it mean? To elaborate on the points of...

Regex string with “$” symbol

c#,regex,.net-4.0
I was using StringBuilder.Replace() to change some "keywords" to my own methods, but since it doesn't match the whole word I need to find a way to replace it correctly. string example = "Hey $name! Welcome to $namewebsite!"; StringBuilder sb = new StringBuilder(example); sb.Replace("$name", "getName()"); sb.Replace("$namewebsite", "getWebSiteName()"); return sb; Above...

How to implement a Timeout on WebClient.DownloadFileAsync

c#,.net-4.0,timeout,webclient
So I thought Webclient.DownloadFileAysnc would have a default timeout but looking around the documentation I cannot find anything about it anywhere so I'm guessing it doesn't. I am trying to download a file from the internet like so: using (WebClient wc = new WebClient()) { wc.DownloadProgressChanged += ((sender, args) =>...

Using Task with Parallel.Foreach in .NET 4.0

c#,multithreading,.net-4.0,parallel-processing
I started off trying to add a progress bar to the windows form that updates the progress of code running within a Parallel.Foreach loop. In order to do this the UI thread has to be available to update the progress bar. I used a Task to run the Parallel.Foreach loop...

ManualResetEvent Skipped by thread

c#,.net-4.0,thread-safety,manualresetevent
Here I have a block of code that executes: public override void Execute(XObjectList itemList, ProcessInfo processInfo) { ManualResetEvent syncEvent = new ManualResetEvent(false); execute(itemList, processInfo); //openScreen(); Thread STAThread = new Thread(() => { var window = new Window(); window.Content = new MailViewerView(); window.Show(); syncEvent.Set(); }); STAThread.SetApartmentState(ApartmentState.STA); STAThread.Start(); syncEvent.WaitOne(); } I expect...

How to avoid WPF Application not Responding when logging off

c#,wpf,windows-7,.net-4.0
When trying to press the standard Windows 7 logoff button while my WPF app is running, I get "This program is preventing Windows from logging off". I would like to force it to close without having to press "Force log off". Similarly, pressing "End Task" in the (applications) Task Manager...

Do I need a lock in AddOrUpdate of a concurrent dictionary?

c#,.net,.net-4.0,locking,concurrentdictionary
in my class I have public static ConcurrentDictionary<string, HashSet<string>> ConnectedUserConnections = new ConcurrentDictionary<string, HashSet<string>>(); When adding or updating, should I update via: ConnectedUserConnections.AddOrUpdate(userId, new HashSet<string>(), (key, existingVal) => { existingVal.Add(connectionId); return existingVal; }); or ConnectedUserConnections.AddOrUpdate(userId, new HashSet<string>(), (key, existingVal) => { lock(ConnectedUserConnections) {...

What way to change Hash back to it string in c#

c#,.net,.net-4.0,.net-3.5
I am writing a part of code to change string into hash String hash = GetHashString("A"); //return 7FC56270E7A70FA81A5935B72EACBE29 My question is how can I get back "A" when I pass in the hash code ? 7FC56270E7A70FA81A5935B72EACBE29 ...

IsFirstRun Problems

c#,wpf,.net-4.0,clickonce
So I'm trying to detect if the application is first run or not, but for some reason I'm getting a name space error. I'm using the following code: private void Window_Loaded(object sender, RoutedEventArgs e) { lblUsername.Content = "CIS User: " + username; lblbuildVersion.Content = staticinfo.buildVersion; if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed && System.Deployment.Application.ApplicationDeployment.IsFirstRun) {...

Timeout.InfiniteTimespan in .Net 4.0?

c#,.net,timer,.net-4.0,.net-4.5
I actually do know that Timeout.InfiniteTimespan does not exist in .NET 4.0. Noticed, there's also Timeout.Infinite which does exist in .NET 4.0 I am calling those two methods: // the Change-Method public bool Change( TimeSpan dueTime, TimeSpan period ) // the Constructor of Timer public Timer( TimerCallback callback, Object state,...

Inspect element from my WPF WebBrowser, using “inspect element(s)”(IE,Chrome,Firefox) to get the css path(“copy css-path”)

c#,wpf,.net-4.0,webbrowser-control
I need the correct css path from a webpage, which will be displayed in my WPF application(to use it later with HTMLAgilityPack and/or Fizzler). Something like this, to "copy css-path" or xpath(FireBug), should be the final goal. I also found some interesting post like: stackoverflow stackoverflow stackoverflow codeproject They all...

Most efficient way to fix an invalid JSON

javascript,c#,json,.net-4.0,fastjson
I am stuck in an impossible situation. I have a JSON from outer space (there is no way they are going to change it). Here is the JSON { user:'180111', title:'I\'m sure "E pluribus unum" means \'Out of Many, One.\' \n\nhttp://en.wikipedia.org/wiki/E_pluribus_unum.\n\n\'', date:'2007/01/10 19:48:38', "id":"3322121", "previd":112211, "body":"\'You\' can \"read\" more here...

Multiple Async Operations with Delegates

c#,asynchronous,.net-4.0,delegates
Code: private delegate void NotificationDelegate(sis_company company, int days, string type, string param); private NotificationDelegate _notDel; private void Notifications(sys_company company, int days, string type, string param) { if (*something*) { _notDel = SendEmails; _notDel.BeginInvoke(company, days, type, param, CallBackNotification, null); } } private void SendEmails(sys_company company, int days, string type, string param)...

Calculate Value Types (int, float, string) Sizes In C# With Generic Method

c#,generics,types,.net-4.0,value-type
I want to write method which calculate value types size. But i can't give value types (int, double, float) as method parameter. /* *When i call this method with SizeOf<int>() and *then it returns 4 bytes as result. */ public static int SizeOf<T>() where T : struct { return Marshal.SizeOf(default(T));...

Display scrollbars with reportviewer and asp.net webform?

c#,asp.net,visual-studio-2010,.net-4.0,reportviewer
I will be displaying 4 reports in one webform, so I would like to create a section of about 500x500px for each report and use the horizontal/vertical scrollbars to navigate each report. I've tried wrapping the reportviewer in a div, iframe, panel, tablecell, but none of them can contain the...

Console Application doesn't display output, but renaming it does

c#,visual-studio-2013,.net-4.0,console-application
I have a simple Console Application, which uses Enterprise Framework 5 to call a Stored Procedure and create a text file. The very first line in this Console application's main() is Console.WriteLine("Starting..."); Built this in Release mode; tested it in a test machine and it executes fine. I copied this...