FAQ Database Discussion Community


Wait for download to complete

c#,download,.net-4.5
I'm trying to create a simple program to download few files. I've tried some ready-made solutions I found on the web but I can't manage to make it work the way I want it to. I'm using this: private void startDownload(string toDownload, string saveLocation) { Thread thread = new Thread(()...

WPF Controls - Should code behind be avoided at all costs?

c#,wpf,.net-4.5
I have a WPF project and need to create a control that is specific to the domain but will be reused in multiple views. The control must display a decimal value in 3 parts, the integral part and the decimal part split into 2 with different font sizes. I have...

Getting a System.AccessViolationException only during debug

c#,.net,visual-studio-2013,.net-4.5
UPDATE I've changed the question with my latest findings and simplified as much as possible. I have the following piece of code public virtual int DefineAction(bool b, string s, Type1 t1, Type2 t2) { return 1; } public ProcessResult Process(bool b, string s, Type1 t1, Type2 t2) { int i...

How to write an extension method to return the type being used?

c#,.net,.net-4.5,extension-methods
I have an extension method that allows a user to turn off lazy loading. public static IBaseEntityService<TEntity, TPrimaryKey> EnableLazyLoading<TEntity, TPrimaryKey>( this IBaseEntityService<TEntity, TPrimaryKey> baseService, bool enabled) where TEntity :Entity<TPrimaryKey> where TPrimaryKey : struct { baseService.UnitOfWork.EnableLazyLoading(enabled); baseService.UnitOfWork.EnableProxyCreation(enabled); var type = baseService.GetType().; return (type)baseService; } Here is a sample of the base...

How do I make non-essential computations run in the background?

c#,concurrency,task-parallel-library,.net-4.5
This question is in follow up to Why is this code running synchronously? . I realize that my real question is at a higher level than the one in that post. The question I now ask, below, is "how do I accomplish this?" I want to use concurrency in C#...

HttpClient: Conditionally set AcceptEncoding compression at runtime

c#,gzip,.net-4.5,dotnet-httpclient,winrt-async
We are trying to implement user-determined (on a settings screen) optional gzip compression in our client which uses HttpClient, so we can log and compare performance across a number of different calls over a period of time. Our first attempt was to simply conditionally add the header as follows: HttpRequestMessage...

Async task raises NotImplementedException

c#,windows-phone-8.1,async-await,.net-4.5
I continue to struggle with Windows Phone programming. :) When invoking the method: public static async Task<string> ConvertToBase64(this BitmapImage bitmapImage) { RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmapImage.UriSource); var streamWithContent = await rasr.OpenReadAsync(); byte[] buffer = new byte[streamWithContent.Size]; var result = await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None); using (MemoryStream ms = new...

Common ways to tweak the .NET 4.5 GC for games and other real time applications?

.net,garbage-collection,.net-4.5
I'm working on a game engine in C# and am running into situations where while doing some memory intensive operations, the garbage collection causes noticeable stutters once every multiple frames. What are common ways to tweak the garbage collector in .NET to avoid problems like this or to otherwise optimize...

Is LogicalOperationStack incompatible with async in .Net 4.5

c#,.net,async-await,.net-4.5
Trace.CorrelationManager.LogicalOperationStack enables having nested logical operation identifiers where the most common case is logging (NDC). Should it still work with async-await? Here's a simple example using LogicalFlow which is my simple wrapper over the LogicalOperationStack: private static void Main() { OuterOperationAsync().Wait(); } private static async Task OuterOperationAsync() { Console.WriteLine(LogicalFlow.CurrentOperationId); using...

Is there an elegant LINQ solution for SomeButNotAll()?

c#,linq,.net-4.5,c#-5.0
Here is what I'm trying to do overall. Just to be clear, this isn't homework or for a contest or anything. Hopefully, I've made the wording clear enough: Problem Given a set of strings in the same format, but where some end in a lowercase letter and some do not,...

Unexpected token while parsing Facebook RSS

c#,facebook,winforms,rss,.net-4.5
I'm trying to parse the facebook RSS but none of them seems to work. Every method I've tried so far result in a different exception. I changed the format to format=atom10. I ended up with below code void loadRSS3() { string url = "https://www.facebook.com/feeds/notifications.php?id=XXXX&viewer=XXXX&key=XXXX&format=atom10"; var req = (HttpWebRequest)WebRequest.Create(url); req.Method =...

HttpClient.PutAsync finish immediately with no response

c#,async-await,.net-4.5,dotnet-httpclient
I try to upload a file with PUT method to the http server (Apache Tika) with the following code private static async Task<string> send(string fileName, string url) { using (var fileStream = File.OpenRead(fileName)) { var client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain")); var content = new StreamContent(fileStream); content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");...

How to edit the Typescript 1.4 “specified task executable location”?

asp.net-mvc-4,visual-studio-2013,typescript,.net-4.5
I'm updating a project to use the latest versions of everything. I just updated the MVC 4 project from .Net 4.0 to .Net 4.5.1. I then updated the nuget packages(uninstalling some, and re-installing because they were based on .Net 4.0). Afterwords, I updated the machine version of Typescript to 1.4,...

Switch-Case on Class.PropertyName (not value)

c#,.net-4.5
I have a class which implements INotifyPropertyChanged like this: public class Person : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; string _color; public string Color { get{ return _color; } set { _color = value; RaisePropertyChanged(); } } ... private void RaisePropertyChanged([CallerMemberName]string prop = "") { if (PropertyChanged != null) PropertyChanged(this,...

Get Properties out of LogicalBinaryExpression ; How?

c#,vb.net,lambda,.net-4.5
I would like to know if there is a way (and which is proper) to retrieves properties from a LogicalBinaryExpression, if it's possible. I would like to have something like : Dim whereClause as Expression(Of Func(Of Foo, Boolean)) = Function(f as Foo) f.ID = 1 Dim strignifiedWhereClause as string =...

wrap anonymous function with another call

c#,visual-studio-2013,.net-4.5
I have this code in which I am trying to wrap an anonymous function by another call so when it is actually the wrapper's value that is returned and not the original function's. In the code below however I get a NullPointerException in the last call. I am sure I...

Will a long running .net process be termintated if the user session is terminated?

c#,session,asp-classic,.net-4.5
I have a ASP C# application that allows users to upload and process text files. after the upload, the parser is called and starts its work. depending on the size and quantity of the files the user uploads, this process can run for up to 20 hours. If my users...

Cannot catch FileNotFoundException

c#,wpf,exception-handling,.net-4.5
I think I am having a similar issue as already asked in this Thread. When I run the following code in my current project, I receive a System.IO.FileNotFoundException, although I actually catch it. XmlDocument xmlDocument = new XmlDocument(); public LoadFile(string xmlFile) { try {xmlDocument.Load(xmlFile);} catch {xmlDocument.LoadXml("<settings></settings>");} // File does not...

Calling Stop Timer in Timer.Tick

c#,timer,.net-4.5
I call myTimer.Stop(); in the middle of the myTimer_Tick method. Before asking this question, I read this question: Stop timer in the middle of the tick; but my question is something quit different: I think if call myTimer.Stop() or myTimer.Enable = false , the Tick method will run to the...

IL Emit struct serializer

c#,.net,.net-4.5,code-generation,reflection.emit
I'm writing a code that marshal any structure to byte array. I have a method: public static byte[] Serialize(MyStruct value) { IntPtr p = new IntPtr(&value); byte[] result = new byte[12]; Marshal.Copy(p, result, 0, result.Length); return result; } Here is IL for this code: .method public hidebysig static uint8[] Serialize(valuetype...

.Net BinaryWriter automatically flushes stream when checking stream Position

c#,.net,stream,.net-4.5,flush
Has anyone else seen this or know how to turn this off? I have code which periodically checks the Position of a stream in a BinaryWriter. Every invocation of the BinaryWriter.BaseStream.Position method results in that stream's Flush method being invoked. I tried using a BinaryWriter and a StreamWriter, and only...

Deserializing Json data to c# for use in GridView - Error Data source is an invalid type

c#,json,gridview,serialization,.net-4.5
I am relatively new to working with C# (v5.0) and Json data (Newtonsoft.Json v6.0) and am seeking assistance in resolving an error when attempting to populate a .Net 4.5 GridView control. My sample Json data as returned by a web service is: { PersonDetails: [ { Book: "10 ", FirstName:...

400 Bad Request when calling wcf from html using XDomainRequest

javascript,wcf,internet-explorer-9,.net-4.5,xdomainrequest
I'm on this problem since more than one week and all I have tried haven't work so well. I started with Jquery to find out that Ie9 was different from the other browsers and requires its own way for calling wcf. It is simple enough and I did all the...

Does System.Linq.Dynamic support .net 4.5?

c#,linq,.net-4.5
In nuget, it says that System.Linq.Dynamic supports .net 3.5 and 4.0 Does System.Linq.Dynamic works well with .Net 4.5. If not, is there alternative?

how to handle multiple developer environment in web.config

asp.net,.net-4.5,asp.net-web-api2
So lets say we have three environment dev, qa and prod. In addition to that, all developers have their own environment. How do you manage connection string or app setting for each env? I believe for dev, qa and prod i can use web.config transformations (lot of resources online on...

How to check if a textbox has a line from a TXT File with C#

c#,textbox,.net-4.5,streamreader
It's simple what I'm trying to do; when I click a button, my app should check if textBox1.Text has a line from a text file. Note: I don't want to check if textbox has all the text file in it, just to see if it has a LINE from it....

Service not accessible when “Enable 32-Bit Applications” set to true

web-services,iis-7.5,.net-4.5,windows-server-2008
On the development server I use IIS Veresion 7.5.7600.16385 And a Service compiled for .Net 4.5.1, Any CPU The service works fine on the development server (Win Server 2008 R2). On the client's production server however I get strange problems: (Same IIS Version, same OS version) As soon as I...

Change Backgroundcolor of TabControl

c#,wpf,.net-4.5,ribbon
I'm using the .NET 4.5 WPF Ribbon and want to change the background color of one particular RibbonTab, in all situations (independent of whether it is selected, hovered over, or not - don't ask why). Usually I'd look at the code of the template in Blend but trying to copy...

Culture-aware string comparison for Umlaute

c#,.net-4.5,string-comparison
I need to compare two strings in German language to check if they are equal and only differ in the use of umlaute. E.g. "Jörg" should be the same as "Joerg". So I tried: var ci = new CultureInfo("de-DE"); int compareResult = ci.CompareInfo.Compare("jörg", "joerg", CompareOptions.IgnoreNonSpace); as well as int compareResult...

ConcurrentBag vs Custom Thread Safe List

c#,multithreading,concurrency,.net-4.5,readerwriterlockslim
I have a .NET 4.5 Single Instance WCF service which maintains a collection of items in a list which will have simultaneous concurrent readers and writers, but with far more readers than writers. I am currently deciding on whether to use the BCL ConcurrentBag<T> or use my own custom generic...

Create expression for a simple math formula

c#,.net,expression,.net-4.5,expression-trees
I have some fun with Expressions and a question appears: it throws an exception that I didn't suppose. I have an input - simple math formula, for example 2*x+3, and I want to create an expression tree for it. So I write this code using System; using System.Linq.Expressions; namespace ConsoleApplication50...

Handling different item templates that share the same content

wpf,wpf-controls,.net-4.5
I have two custom ItemTemplates for the ListBox, one for the regular items, and one for the selected item. An example of how would I handle this is: <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="ContentTemplate" Value="{StaticResource Template1}" /> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="ContentTemplate" Value="{StaticResource Template2}" /> </Trigger> </Style.Triggers> </Style> </ListBox.ItemContainerStyle>...

changing image background in button does not work

c#,windows-phone-8.1,.net-4.5
I want to toggle button's image on each click. My code looks like this: private void k1_Click(object sender, RoutedEventArgs e) { bk1 = !bk1; k1.Content = bk1.ToString(); var uriString = bk1 ? @"Assets/image1.png" : @"Assets/image2.png"; k1.Background = new ImageBrush { ImageSource = new BitmapImage(new Uri(uriString, UriKind.Relative)) }; } When I...

Overridden Extension Method Requires Assembly Reference [duplicate]

c#,.net,generics,.net-4.5,extension-methods
This question already has an answer here: The type is defined in an assembly that is not referenced, how to find the cause? 5 answers This seems strange unless I am missing something... public static string ToDomainSolarSystemCelestial(this TypeMapper<string> m) { // Does not reference any other assemblies - straight...

BeginExecuteReader, EndExecuteReader and multiple results

c#,.net,asynchronous,.net-4.5,sqldatareader
I have method that is asynchronously getting results form my database: internal class CommandAndCallback<TCallback, TError> { public SqlCommand Sql { get; set; } public TCallback Callback { get; set; } public TError Error { get; set; } } public void GetResults(string param, Action<DataTable,DataTable> callback, Action<string> error, Action<string> info) { var...

Use Task or Thread when Coding a Remote Desktop Capture App [closed]

c#,.net,multithreading,.net-4.5
Recently I'm coding a remote desktop app. For the client side, I have a Windows Forms app that have a picturebox control and a button. Internally I have two Listeners, and two TcpClient, one for holding the connection and another for receive the image from the remote computer. For the...

Interface implementation with optional arguments

c#,.net,.net-4.5,c#-5.0
Take this interface: interface ILogger { void Store(string payload); } And this class implementation of ILogger: class Logger : ILogger { void Store(string payload, bool swallowException = true) { ... } } I would anticipate the compiler would recognize swallowException as an optional argument, and thus satisfy the requirements of...

How to set source for Image Control where the image resides in application folder

c#,wpf,.net-4.5
I am using an image control. i am setting the source for Image control like below. But the error shows invalid URI. string strUri = String.Format(@"..\..\Assets\Images\Image001.jpeg"); previewImage.Source = BitmapFromUri(new Uri(strUri)); public static ImageSource BitmapFromUri(Uri source) { var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.UriSource = source; bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); return...

Shortest way to deserialize XmlDocument

c#,xml,.net-4.5,.net-4.6
I am looking for a clean and short way to deserialize a XmlDocument object. The closest thing I found was this but I am really wondering if there is no nicer way to do this (in .NET 4.5 or even 4.6) since I already have the XmlDocument. So currently this...

How can I change my current selected item by either the key or value of my datasource?

c#,winforms,.net-4.5
I have a Dictionary<uint, string> and a ComboBox using the style DropDownList, where I bind this dictionary, like: comboBox1.DataSource = new BindingSource(myDic, null); comboBox1.DisplayMember = "Value"; comboBox1.ValueMember = "Key"; Now I would like to be able to select an arbitrary item of my dictionary with a button click, so given...

Constant value cannot be converted to int

c#,.net-4.5
I can't see why line#5 fails to compile whereas line#4 is ok. static void Main(string[] args) { byte b = 0; int i = (int)(0xffffff00 | b); // ok int j = (int)(0xffffff00 | (byte)0); // error: Constant value cannot be converted to a 'int' (use 'unchecked' syntax to override)...

Why doesn't my Task.ContinueWith execute in .NET 4.5?

c#,.net,asynchronous,.net-4.5
Consider the following code Task<T>.Factory.StartNew(() => { // block #1: load some data from local file cache } ) .ContinueWith(task => { // block #2: handle success or failure of load-from-cache operation and surface to application }, cancellationToken, TaskContinuationOptions.NotOnCanceled, TaskScheduler.FromCurrentSynchronizationContext() ) .ContinueWith(task => { // block #3: load data from...

LINQ Replace Different String Values

c#,linq,.net-4.5
I constructed a variable by parsing a text file with some addresses. FileInfo fi = new FileInfo(@"C:\temp\Addresses.txt") var ZipCodesAndCountryCodes = File.ReadLines(fi.FullName) .Select(l => new { ZipCode = l.Substring(1395, 5), CountryCode = String.IsNullOrWhiteSpace(l.Substring(1405,30)) ? "US" : l.Substring(1405,30) }); In this code, I'm replacing any blank value for country with "US". However...

Delphi COM vs DLL in .NET [closed]

.net,delphi,.net-4.5
Need to create a Delphi DLL that can be called from Delphi and .NET. What does .NET like more, COM or dll? Or does it matter? I just remember hearing that COM can be annoying because of versioning....

Is Parallel.ForEach obsolete. old, out of fashion?

multithreading,design-patterns,parallel-processing,async-await,.net-4.5
Good day, Parallel execution can be achieved through multiple ways. From strictly manual "multithreading" to using various "helpers" created by Microsoft. One of those helpers is the Parallel class. One of my colleagues is insisting that Parallel.ForEach (or Parallel class overall) is "old" and shouldn't be used. Instead, he says,...

C# xml deserialization ignoring List<> properties unexpectedly

c#,xml,serialization,.net-4.5
Because XmlSerializer won't work on dictionaries, I use the XmlIgnore attribute on them, and use a mediating List<> property to render the dictionary as a list, which does work with serialization. However, my List<> property is ignored on deserialization. (There's no error thrown, and no serialization events are raised.) Why?...

UriBuilder not combining two uris correctly

c#,.net,.net-4.5
So Here is my problem: I want to combine a URI and a string. The URI is a path to a (parent) folder, while the string represents the path to a sub folder (don't ask me why I am doing this, both types need to stay that way for the...

Batch File works when run, but fails when run from app

.net,batch-file,command-line,.net-4.5
I have a batch file that looks like this: @echo off REM Create the folder to put the converted files in md PngConverted REM Iterate all bitmap files for /r %%F in (*.bmp) do ( REM Convert the files to PNG. Resize them so they are no bigger than 1300x1300...

Is there no Async implementation of MSMQ send in .net 4.5

.net,c#-4.0,.net-4.5,msmq
I wonder why there is no async implementation of MSMQ send? I am using .net 4.5. Am I missing something?

Need to call method as soon as server starts responding to my HttpWebRequest

c#,winforms,httpwebrequest,.net-4.5,httpwebresponse
I need to call a method in new thread for ex: mymethod() as soon as server starts responding to my HttpWebRequest. I am using below to send http requst and getting response. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(MyUrl); HttpWebResponse response = (HttpWebResponse)request.GetResponse (); Now what i need is for my request when...

How to get distance between two locations in Windows Phone 8.1

c#,windows-phone-8,windows-phone-8.1,.net-4.5
In Windows Phone 8 there seems to be method GeoCoordinate.GetDistanceTo() for calculating distances between two locations. (Even if the reference page for the method is not found.) But where is the equivalent in the whole Windows Phone 8.1 Geolocation namespace? I can't find a method to calculate distance between two...

In pure XAML, is it possible to select a string format on the fly?

c#,wpf,xaml,.net-4.5
I have to display a decimal representing a price. If the price is in British Pence or Yen, it needs to display it to 4 decimal places, otherwise it needs to display it to 6 decimal places. The currency is encoded as a string, and will be GBp or YEN...

Web API Sync Calls Best Practice

c#,iis,.net-4.5,web-api
Probably this question has already been made, but I never found a definitive answer. Let's say that I have a Web API 2.0 Application hosted on IIS. I think I understand that best practice (to prevent deadlocks on client) is always use async methods from the GUI event to the...

How to use wcf ServiceBehavior attribute for InstanceContextMode in Web API?

asp.net,wcf,.net-4.5,web-api,asp.net-web-api2
How can I use ServiceBehaviorAttribute in my Web API 2 project to create & recycle instance context object on every request? I tried to set it traditional way by configuring in web.config but didn't work. I think I may need to set custom attribute so any suggestion/thoughts are appreciated! [ServiceBehaviorAttribute(InstanceContextMode...

SignalR and Websockets on Mono

c#,.net,mono,.net-4.5,owin
I've done hours of scouring, trying to figure out why the websockets transport doesn't work through signalr on my c# 4.5 application running on linux via mono 4.0.1. References in my project: Microsoft.Owin.Host.HttpListener Microsoft.Owin.Host.SystemWeb Right now, I'm trying to figure out where the bottleneck is that is preventing websockets from...

How do I change the value of a query string parameter?

c#,.net-4.5
I have a string representation of a URL like this: http://www.GoodStuff.xxx/services/stu/query?where=1%3D1&text=&objectIds=231699%2C232002%2C231700%2C100646&time= It's a URL but a string object in my code. How do I change the value of objectIds? Do I need to find the string, objectIds, then locate the & before and after, and replace the contents with the...

Warning as Error: Possible unintended reference comparison when upgrading from .Net 3.5 to .Net 4.5

c#,reference,.net-3.5,comparison,.net-4.5
Currently I am in the process of migrating a WPF application from .Net Framework 3.5 to .Net Framework 4.5. Next to the upgrade of the .Net Framework, the application will now be compiled 64-bits instead of 32-bits. I get the following error when compiling the application: Warning as Error: Possible...

Entity framework object not updating after being passed around

c#,entity-framework,dependency-injection,ninject,.net-4.5
I'm working on setting up a new MVC payment site with a dependency-injected database connection in a separate project, and experimenting with some new things as I do. Currently, I'm trying to load an existing transaction from the database, authorize the card payment, and then save the result back to...

80040154 Class Not Registered (Debenu PDF Library)

vb.net,dll,runtime-error,.net-4.5,windows64
I have been using the Debenu PDFLibrary successfully for some time. I decided to update the library to the latest version (DebenuPDFLibrary64Lite1113.dll). That's when everything went sideways. I followed the instructions for installing, including the registering of the DLL. The registration process did not produce an error. The registry contains...

Exception when opening all VS 2013 solutions after installing .net framework 4.5.2

visual-studio-2013,.net-4.5
I currently cannot open any of my Visual Studio 2013 solutions. Here's the scenario that happened: 1- All solutions were working well 2- I tried to open one of the CRM 2015 sample solutions, I received an error message that the .Net Framework 4.5.2 is required by the solution and...

Hashtable insert failed. Load factor too high : .Net 4.5

exception,.net-4.5
I'm getting an exception “System.InvalidOperationException: Hashtable insert failed. Load factor too high.” My application is developed in VS2010 with 4.0 framework and it is working fine in our development environment (4.0 version ) (for 4.0 framework I'm able to find the hotfix and I've installed it in my development environment)....

ListBox inside a ListBoxItem template

wpf,wpf-controls,.net-4.5
I have a ListBox with the following ItemTemplate: <DataTemplate> <StackPanel> <TextBlock .... /> <ListBox .... /> </StackPanel> </DataTemplate> I would like to forbid the user to Select an item in a child ListBox, and that when user clicks on the child ListBox, a parent ListBox SelectedItem should be set respectively....

C# How do I stop code from looping during collection serialization causing a stackoverflow?

c#,serialization,collections,.net-4.5
I have a ContactForm object that contains several nested collection objects. When I attempt to serialize the object, the code gets stuck in a loop within the SectionCollectionObject. Here is the code that executes the serialize() call: public static ContactForm SaveForm(ContactForm cf) { if (cf != null) { XmlSerializer xs...

StackExchange.Redis HGET/HGETASYNC returns null when hash key is GUID

c#,.net,redis,.net-4.5,stackexchange.redis
I'm experiencing some issue and I believe it might be a bug in StackExchange.Redis library. When I create a hash where keys are GUID, both .HashGet or HashGetAsync will return a null value, while when I try to get the same hash key using redis-cli I'm able to retrieve the...

WPF calling asynchronous code with out locking on Task..WhenAny()

c#,.net,wpf,async-await,.net-4.5
I have been trying to setup a very basic method in my view models for temporarily freezing the UI thread while still pumping dispatcher messages, I have read this method will only work for simple cases and is not thread safe as 'waiting' for a task while already 'waiting' for...

HmlAgilityPack fix not open tag

c#,html,.net-4.5,html-agility-pack
I get from url html page. in page I get table with hot opened <tr> tag <table class="transparent"> <tr><td>Sąrašo eil. Nr.:</td><td>B-FA001</td></tr> <td>Įrašymo į Sąrašą data:</td><td>2006-11-13</td></tr> </table> how to fix to <table class="transparent"> <tr><td>Sąrašo eil. Nr.:</td><td>B-FA001</td></tr> <tr><td>Įrašymo į Sąrašą...

Azure Active Directory and Windows Authentication

azure,visual-studio-2013,.net-4.5,azure-active-directory
I'm using Visual Studio 2013, .NET 4.5. and trying to find out if it's possible to authenticate against Azure Active Directory with a web app using windows authentication instead of organizational authentication? I don't need a separate sign on page or registration, so rather than send them to an azure...

How to place cursor in the first position of a Datepicker control in C#?

c#,wpf,datepicker,.net-4.5
I have a datepicker control on a wpf form (masked as 00-00-0000). If the datepicker is empty, then I want the cursor always to be in the first position no matter where I click on the datepicker textbox. I tried using SelectionStart property (set to 0) on MouseDown event but...

TLS_PSK_WITH_AES_128_GCM_SHA256 ciphersuite in C#

c#,ssl,.net-4.5
I want to use this specific cipher suite: TLS_PSK_WITH_AES_128_GCM_SHA256 (or perhaps TLS_PSK_WITH_AES_128_CBC_SHA256 but prefferd would be the first) in C#, unfortunately .net does not support this. I've seen many questions about PSK, or the SslStream class of .net but all are dated, most are at least 3 years old. I...

Lambda not equal on join

c#,.net,lambda,.net-4.5
Table 1 called Category contains 70 records Table 2 called FilterCategorys contains 0 records (currently). my lambda join, I want to pull only records that don't match, so in this case I expect to get 70 records back. Here's my incorrect Lambda: var filteredList = categorys .Join(filterCategorys, x => x.Id,...

What is the best way to determine max amount of threads for C# IO operations based on the system's hard drive?

c#,multithreading,.net-4.5
I've got a tool that will run multiple threads at once that will perform a simple IO operation. The question I have is; What is the best way to determine the max amount of possible threads, based on the system's hard drive capabilities, for IO operations?

ClickOnce deployment requires Framework 4.5 required when 4.5.2 is installed

c#,.net,.net-4.5,clickonce
I know that the similar questions has been asked, and I've read them, however I can't understand why it happens with Framework 4.5.2 I've make ClickOnce publish and it requires .net framework 4.5 when 4.5.2 is installed . I can run it in debug mode or build it without any...

Why does String.Format fail to escape characters when the string is in a resource?

c#,string,.net-4.5,string-formatting
var result1 = String.Format("Hello\n\t{0}\n\n", "Bill"); // MyResource.FormatMe contains the same text: Hello\n\t{0}\n\n var result2 = String.Format(MyResource.FormatMe, "Bill"); result1 is as expected: "Hello Bill " result2 is not: Hello\n\tBill\n\n Why is String.Format not escaping escape characters when the format string comes from a resource?...

.Net project executable can use 32 bit drivers only when NOT “run as administrator”

c#,visual-studio-2013,.net-4.5,wow64
Short desc: Same .exe when ran without administrator rights can use 32bit driver. However, when ran with admin rights it's incapable to use it/find it. My environment : Windows 7 64bit Visual Studio 2013 Professional .Net 4.5 Computer NOT in domain Background story: I have a WCF service hosted in...

Adding footer/EXIF (binary data) to JPG image in C#

c#,.net,jpeg,.net-4.5
Hello all I have an image and I want to add binary data as a footer to that image. RGBImage rgbImage = (RGBImage) RGBImage.LoadImage(@"test.tiff"); byte[] bytes = File.ReadAllBytes(@"C:\TEMP\gili.bin"); int padding =(int) Math.Ceiling((double)bytes.Length/(rgbImage.Width*3)); byte[] newMakerNoteImage = new byte[rgbImage[0].Data.Length + (rgbImage.Width * 3 * padding)]; Buffer.BlockCopy(rgbImage[0].Data, 0, newMakerNoteImage, 0, rgbImage[0].Data.Length); Buffer.BlockCopy(bytes, 0,...

How to setup multiple async methods into a queue?

c#,.net,queue,async-await,.net-4.5
I just picked up async/await, and I wrote a series of async methods that each perform a database SQL task and tied each one to a different button. The GUI doesn't get locked when you click a button, so I figure that's awesome. However, if you click each one the...

HTTPClient getting two 401s before success (sending wrong token)

c#,.net,http,authorization,.net-4.5
I'm trying to communicate with a self-hosted WebAPI client using HttpClient. The client is created with the following code: HttpClientHandler clientHandler = new HttpClientHandler() { UseDefaultCredentials = true, PreAuthenticate = true }; var client = new HttpClient(clientHandler); on the server side we set: HttpListener listener = (HttpListener)app.Properties[typeof(HttpListener).FullName]; listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;...

Not allowed to load assembly from network location

.net,visual-studio-2012,.net-4.5,.net-assembly
I've recently set up a new Windows Server 2012 R2 environment and installed Visual Studio 2012. Now I'm having a problem with some .NET 4.5 project's I migrated from my old server, a Windows Server 2008 machine. This never occurred on the old server. When trying to load an assembly...

Why the async await not working as expected

c#,task-parallel-library,async-await,.net-4.5,c#-5.0
I am learning TPL (async/await) from a tutorial and I tried to test it out myself using a console application. Please don't be offended by my ignorance. I am sure I am doing wrong somewhere- I wrote the following code: static void Main(string[] args_) { Task<int> task = ProcessNumber(25); Console.WriteLine(string.Format("{0}:...

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,...

Rotate gauge needle in C#

c#,wpf,graphics,.net-4.5
I cannot rotate the needle properly around its center without clipping occurring. The code I have found for rotation that doesn't result in clipping rotates the needle the wrong way. I found the code samples somewhere from stackoverflow. Pic1 : correct position pointing south Pic2 : RotateBitmap4(), rotation at wrong...

WEB API call stops working after introducing the “await” keyword

c#,asp.net-mvc,asp.net-web-api,.net-4.5,c#-5.0
I have a simple web api method which retrieves a list of items from a database. When the method looks like this it works and the items are displayed in the UI: [ActionName("GetServices")] public async Task<IHttpActionResult> GetServices() { var services = dbContext.Service.ToListAsync(); return Ok(services); } But as soon as I...

Writing a file using NPOI

c#,.net,.net-4.5,npoi
I'm unable to use NPOI to save changes to an xlsx to disk, when attempting to do it from a DLL. I have a set of data that I'm currently storing in a database, and a home-grown ORM for it. The home-grown ORM is housed in its own DLL. I...

LINQ anonymous object is inaccessible due to its protection level

c#,linq,.net-4.5,anonymous-types
I have LINQ logic that collects regex parsed data into a dynamically-created dictionary. The issue I am facing is accessing the data in the dictionary (Info). Regex .Matches(text, pattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture) .OfType<Match>() .Select(mt => new { Info = mt.Groups["ADKey"].Captures .OfType<Capture>() .Select(cp => cp.Value) .Zip(mt.Groups["ADValue"].Captures.OfType<Capture>().Select(cp => cp.Value), (k, v) =>...