text
stringlengths 46
37.3k
| title
stringlengths 12
162
|
|---|---|
C_sharp : I think it was in .net 2.0 , microsoft introduced an accessor that was abbreviated to something likepublic string Name { get ; set ; } But is there any real difference between the above code , and simply : <code> public string Name ;
|
Public accessor .net
|
C_sharp : I need to display a PieChart , I 'm currently using Modern UI ( Metro ) Charts . I did copy the code in the documentation and the problem is that i 'm always having the border and the title in the screen but no chart.XAMLCS <code> < UserControl x : Class= '' Projet.Recources0.Statistique.Ad_Aj '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mui= '' http : //firstfloorsoftware.com/ModernUI '' xmlns : controls= '' http : //metro.mahapps.com/winfx/xaml/controls '' xmlns : chart= '' clr-namespace : De.TorstenMandelkow.MetroChart ; assembly=De.TorstenMandelkow.MetroChart '' mc : Ignorable= '' d '' d : DesignWidth= '' 1000 '' Height= '' 670 '' > < UserControl.Resources > < Style x : Key= '' MinimalChartStyle '' TargetType= '' { x : Type chart : ChartBase } '' > < Setter Property= '' Width '' Value= '' 500 '' / > < Setter Property= '' Height '' Value= '' 500 '' / > < /Style > < /UserControl.Resources > < Grid > < chart : PieChart Style= '' { StaticResource MinimalChartStyle } '' ChartTitle= '' Minimal Pie Chart '' ChartSubTitle= '' Chart with fixed width and height '' SelectedItem= '' { Binding Path=SelectedItem , Mode=TwoWay } '' > < chart : PieChart.Series > < chart : ChartSeries SeriesTitle= '' Errors '' DisplayMember= '' Category '' ValueMember= '' Number '' ItemsSource= '' { Binding Path=Errors } '' / > < /chart : PieChart.Series > < /chart : PieChart > < /Grid > using MySql.Data.MySqlClient ; using System ; using System.Collections.Generic ; using System.Collections.ObjectModel ; using System.Configuration ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Windows ; using System.Windows.Controls ; using System.Windows.Data ; using System.Windows.Documents ; using System.Windows.Input ; using System.Windows.Media ; using System.Windows.Media.Imaging ; using System.Windows.Navigation ; using System.Windows.Shapes ; namespace Projet.Recources0.Statistique { /// < summary > /// Interaction logic for Ad_Aj.xaml /// < /summary > public partial class Ad_Aj : UserControl { public ObservableCollection < TestClass > Errors { get ; private set ; } public Ad_Aj ( ) { Errors = new ObservableCollection < TestClass > ( ) ; Errors.Add ( new TestClass ( ) { Category = `` Globalization '' , Number = 75 } ) ; Errors.Add ( new TestClass ( ) { Category = `` Features '' , Number = 2 } ) ; Errors.Add ( new TestClass ( ) { Category = `` ContentTypes '' , Number = 12 } ) ; Errors.Add ( new TestClass ( ) { Category = `` Correctness '' , Number = 83 } ) ; Errors.Add ( new TestClass ( ) { Category = `` Best Practices '' , Number = 29 } ) ; } private object selectedItem = null ; public object SelectedItem { get { return selectedItem ; } set { // selected item has changed selectedItem = value ; } } } // class which represent a data point in the chart public class TestClass { public string Category { get ; set ; } public int Number { get ; set ; } } }
|
PieChart Does Not Show Up
|
C_sharp : In my ASP.NET MVC 4 / EF 5 web application 's database I have a table with a Comments column that I want to concat new comments to . In traditional T-SQL , I 'd write : I find with method linq for EF ( uow + repository pattern -- which I regret ) , I have to first query the current value of Comments and prepend my new comments to it : Is there any way to write this update without needing to query the DB ? I 'd like to somehow get EF to generate the t-sql above . The comments can be lengthy and I do n't care about what it contains . Performance is a concern.Thanks in advance . <code> UPDATE MyTable SET Comments = 'Hi ' + CHAR ( 13 ) +CHAR ( 10 ) + Comments WHERE ID = 2 StringBuilder displayComment = new StringBuilder ( ) ; var item = uow.MyRepos.Where ( i = > i.ID == 2 ) ; item.Comments = displayComment.Append ( `` Hi '' ) .Append ( Environment.NewLine ) .Append ( item.Comments ) .ToString ( ) ; uow.Save ( ) ;
|
How to cause EF to build update SQL with string concat ?
|
C_sharp : New to Unity and C # This is actually just a small issue that I 'm curious about ... I ran into it while tweaking this code in a ( failed ) attempt to make it work . I have been trying to get this code to work for a few hours now . Anyway , when this code is executed , there is only one error , but it appears 3 times . It says `` Ca n't destroy Transform component of 'Pillar1 ' . If you want to destroy the game object , please call 'Destroy ' on the game object instead . Destroying the transform component is not allowed . `` First time I 've gotten THAT . <code> using System.Collections ; using System.Collections.Generic ; using UnityEngine ; public class PlatformGenerator : MonoBehaviour { public GameObject Single ; private GameObject NewPillar ; private int PillarCount ; private bool run ; private int px ; private int py ; private int pz ; void Start ( ) { px = 0 ; py = 0 ; pz = 0 ; bool run = true ; PlatformCreate ( ) ; } void Update ( ) { if ( run ) { PlatformCreate ( ) ; if ( PillarCount == 3 ) { run = false ; } } } void PlatformCreate ( ) { PillarCount +=1 ; Single.transform.position = new Vector3 ( px , py , pz ) ; NewPillar = Instantiate ( Single , Single.transform ) ; NewPillar.name = `` Pillar '' +PillarCount ; px += 2 ; } }
|
Instantiating a GameObject causes said object to have its Transform destroyed ?
|
C_sharp : According to .NET MemoryStream - Should I set the capacity ? , it 's preferred to set the initial capacity of a MemoryStream if you know it beforehand.In my code , I 'm receiving ( from a third party library ) a Stream object . This Stream is wrapped around a GetObjectResponse class.Since this class will be disposed after the transaction is closed , I need to copy the received stream so I can continue using it afterwards.The Stream class exposes a Length property to determine the length of the stream , so as an initial step to begin the copying process I started writing : But the compiler throws an error , stating that MemoryStream does not take a long parameter , instead it takes an int.Why would they do this ? If MemoryStream extends from Stream , this means that it can have a long Length . If it can have a long size , why ca n't it take a long initial capactiy ? I 'm trying to avoid initializing the stream with no capacity , because I want to take advantage of the fact that I know how big the stream is going to be , but the constructor seems to be constraining this wish.How can I approach this and why does MemoryStream can not take a long capacity ? <code> Stream destination = new MemoryStream ( response.ResponseStream.Length ) ;
|
Why does MemoryStream not offer a constructor taking a `` long '' capacity ?
|
C_sharp : Suppose I have the following class structure : PageThe Page , StaticPage and DynamicPage interfaces are to be implemented by the clients . They provide various data depending on the page type ( static or dynamic ) , which is used to render the page by the Renderer . There might be many implementations of these interfaces.RendererThe Renderers render the pages . Also , there might be multiple implementations of this interface ( for different rendering techniques ) .RenderManagerThis is just a simple facade which is supposed to invoke the appropriate render method on the provided renderer depending on the given page type . And here liesThe problemHow to determine which method to invoke on the Renderer object depending on the provided page type ? Current ( unsatisfactory ) solutionCurrently I am dispatching using a conditional : What 's wrongThe problem with this solution is that whenever I wish to add another page type ( i.e . extending the Page interface ) I need to adjust this method too . Actually , this is what polymorphic ( virtual ) methods in object oriented languages are supposed be used for , but in this case this does n't work ( see below why ) .Other solutions I considered but rejectedAbstract class instead of interface . This would place an unneccessary constraint on the type hierarchy of the implementors : they would no longer be able to extend any class they want and would instead be forced to extend the abstract StaticPage or DynamicPage class , which sucks.Add a dispatch ( Renderer render ) method to the interface and force the implementors to call the appropriate method on the renderer object depending on the page type . This obviously sucks , because the implementors should not care about the rendering : they just need to provide data which is to be rendered.So , maybe there is some pattern or some alternative design which might help in this situation ? Any ideas are welcome . : ) <code> void render ( Page page , Renderer renderer ) { if ( page is StaticPage ) { renderer.renderStaticPage ( page ) ; } else if ( page is DynamicPage ) { renderer.renderDynamicPage ( page ) ; } else { throw new Exception ( `` page type not supported '' ) ; } }
|
How to do multiple dispatch on interface in C # ?
|
C_sharp : Why databinding TwoWay do n't work on the text property of a combobox in .net 4.0 ( it 's working in .net 3.5 ) ? My code : I have an xml file like this : and I have a ListItem control like that : Here is the code behind : I do like that because I can have a ComboBox with auto-completion with the different custom option for each , but I can write what I want , and the result is in the attribute option of the element < combobox > It work fine if I target .net 3.5 , but only textbox bind if I target .net 4.0Why ? What can I do ? <code> < xml > < combobox option= '' '' obs= '' tralala '' > < option value= '' here '' / > < option value= '' there '' / > < /combobox > < combobox option= '' blue '' obs= '' '' > < option value= '' one '' / > < option value= '' two '' / > < option value= '' three '' / > < /combobox > < /xml > < ListBox DataContext= '' { Binding UpdateSourceTrigger=PropertyChanged } '' ItemsSource= '' { Binding UpdateSourceTrigger=PropertyChanged } '' IsSynchronizedWithCurrentItem= '' True '' > < ListBox.ItemTemplate > < DataTemplate > < DockPanel LastChildFill= '' True '' > < ComboBox MinWidth= '' 75 '' IsEditable= '' True '' IsReadOnly= '' False '' DockPanel.Dock= '' Left '' DataContext= '' { Binding Path=Element [ combobox ] } '' IsSynchronizedWithCurrentItem= '' False '' ItemsSource= '' { Binding Path=Elements [ option ] , UpdateSourceTrigger=PropertyChanged } '' DisplayMemberPath= '' Attribute [ value ] .Value '' Text= '' { Binding Path=Attribute [ option ] .Value , UpdateSourceTrigger=PropertyChanged } '' / > < TextBox MinWidth= '' 150 '' AcceptsReturn= '' False '' AcceptsTab= '' False '' TextWrapping= '' NoWrap '' Text= '' { Binding Path=Attribute [ obs ] .Value , UpdateSourceTrigger=PropertyChanged } '' / > < /DockPanel > < /DataTemplate > < /ListBox.ItemTemplate > < /ListBox > XDocument xdXml ; public MyWindow ( ) { xdXml = XDocument.Load ( @ '' C : \file.xml '' ) ; InitializeComponent ( ) ; DataContext = xdXml ; xdXml.Changed += new EventHandler < XObjectChangeEventArgs > ( XdXml_Changed ) ; } private void XdXml_Changed ( object sender , XObjectChangeEventArgs e ) { xdXml.Save ( @ '' C : \fichier.xml '' ) ; }
|
XAML - Why databinding TwoWay do n't work on the text property of a combobox in .net 4.0 ?
|
C_sharp : I 've run into a bit on an Anomaly where for the first time ever , using the var keyword bit me.Take this very simple methodNow we can call this method with a dynamic parameter and everything will work as expected.However , by declaring shouldBeNullableInt32 using implicit typing , the results are far from what I would expect.Instead of being a Nullable < Int32 > the return value get 's treated as a dynamic type . And even then , the underlying Nullable < T > is not preserved . Since System.Int32 has no property named HasValue , a RuntimeBinderException is thrown.I would be VERY curious to hear from someone who can actually explain what is happening ( not just guess ) .Two QuestionsWhy does shouldBeNullableInt32 get implicitly typed as a dynamic when the return type of GetNullableInt32 clearly returns a Nullable < Int32 > ? Why is the underlying Nullable < Int32 > not preserved ? Why a dynamic { int } instead ? ( Answered here : C # 4 : Dynamic and Nullable < > ) UPDATEBoth Rick Sladkey 's answer and Eric Lippert 's answer are equally valid . Please read them both : ) <code> public static Int32 ? GetNullableInt32 ( Int32 num ) { return new Nullable < Int32 > ( num ) ; } public static void WorksAsAdvertised ( ) { dynamic thisIsAnInt32 = 42 ; //Explicitly defined type ( no problems ) Int32 ? shouldBeNullableInt32 = GetNullableInt32 ( thisIsAnInt32 ) ; Console.Write ( shouldBeNullableInt32.HasValue ) ; } public static void BlowsUpAtRuntime ( ) { dynamic thisIsAnInt32 = 42 ; //Now I 'm a dynamic { int } ... WTF ! ! ! var shouldBeNullableInt32 = GetNullableInt32 ( thisIsAnInt32 ) ; //Throws a RuntimeBinderException Console.Write ( shouldBeNullableInt32.HasValue ) ; }
|
Anomaly when using 'var ' and 'dynamic '
|
C_sharp : I have a search application that takes some time ( 10 to 15 seconds ) to return results for some requests . It 's not uncommon to have multiple concurrent requests for the same information . As it stands , I have to process those independently , which makes for quite a bit of unnecessary processing.I 've come up with a design that should allow me to avoid the unnecessary processing , but there 's one lingering problem.Each request has a key that identifies the data being requested . I maintain a dictionary of requests , keyed by the request key . The request object has some state information and a WaitHandle that is used to wait on the results.When a client calls my Search method , the code checks the dictionary to see if a request already exists for that key . If so , the client just waits on the WaitHandle . If no request exists , I create one , add it to the dictionary , and issue an asynchronous call to get the information . Again , the code waits on the event.When the asynchronous process has obtained the results , it updates the request object , removes the request from the dictionary , and then signals the event.This all works great . Except I do n't know when to dispose of the request object . That is , since I do n't know when the last client is using it , I ca n't call Dispose on it . I have to wait for the garbage collector to come along and clean up.Here 's the code : Basically , I do n't know when the last client will be released . No matter how I slice it here , I have a race condition . Consider : Thread A Creates a new request , starts Thread 2 , and waits on the wait handle.Thread B Begins processing the request.Thread C detects that there 's a pending request , and then gets swapped out.Thread B Completes the request , removes the item from the dictionary , and sets the event.Thread A 's wait is satisfied , and it returns the result.Thread C wakes up , calls WaitOne , is released , and returns the result.If I use some kind of reference counting so that the `` last '' client calls Dispose , then the object would be disposed by Thread A in the above scenario . Thread C would then die when it tried to wait on the disposed WaitHandle.The only way I can see to fix this is to use a reference counting scheme and protect access to the dictionary with a lock ( in which case using ConcurrentDictionary is pointless ) so that a lookup is always accompanied by an increment of the reference count . Whereas that would work , it seems like an ugly hack.Another solution would be to ditch the WaitHandle and use an event-like mechanism with callbacks . But that , too , would require me to protect the lookups with a lock , and I have the added complication of dealing with an event or a naked multicast delegate . That seems like a hack , too.This probably is n't a problem currently , because this application does n't yet get enough traffic for those abandoned handles to add up before the next GC pass comes and cleans them up . And maybe it wo n't ever be a problem ? It worries me , though , that I 'm leaving them to be cleaned up by the GC when I should be calling Dispose to get rid of them.Ideas ? Is this a potential problem ? If so , do you have a clean solution ? <code> class SearchRequest : IDisposable { public readonly string RequestKey ; public string Results { get ; set ; } public ManualResetEvent WaitEvent { get ; private set ; } public SearchRequest ( string key ) { RequestKey = key ; WaitEvent = new ManualResetEvent ( false ) ; } public void Dispose ( ) { WaitEvent.Dispose ( ) ; GC.SuppressFinalize ( this ) ; } } ConcurrentDictionary < string , SearchRequest > Requests = new ConcurrentDictionary < string , SearchRequest > ( ) ; string Search ( string key ) { SearchRequest req ; bool addedNew = false ; req = Requests.GetOrAdd ( key , ( s ) = > { // Create a new request . var r = new SearchRequest ( s ) ; Console.WriteLine ( `` Added new request with key { 0 } '' , key ) ; addedNew = true ; return r ; } ) ; if ( addedNew ) { // A new request was created . // Start a search . ThreadPool.QueueUserWorkItem ( ( obj ) = > { // Get the results req.Results = DoSearch ( req.RequestKey ) ; // DoSearch takes several seconds // Remove the request from the pending list SearchRequest trash ; Requests.TryRemove ( req.RequestKey , out trash ) ; // And signal that the request is finished req.WaitEvent.Set ( ) ; } ) ; } Console.WriteLine ( `` Waiting for results from request with key { 0 } '' , key ) ; req.WaitEvent.WaitOne ( ) ; return req.Results ; }
|
How do I know when it 's safe to call Dispose ?
|
C_sharp : This question is about the threshold at which Math.Floor ( double ) and Math.Ceiling ( double ) decide to give you the previous or next integer value . I was disturbed to find that the threshold seems to have nothing to do with Double.Epsilon , which is the smallest value that can be represented with a double . For example : Even multiplying Double.Epsilon by a fair bit did n't do the trick : With some experimentation , I was able to determine that the threshold is somewhere around 2.2E-16 , which is very small , but VASTLY bigger than Double.Epsilon.The reason this question came up is that I was trying to calculate the number of digits in a number with the formula var digits = Math.Floor ( Math.Log ( n , 10 ) ) + 1 . This formula does n't work for n=1000 ( which I stumbled on completely by accident ) because Math.Log ( 1000 , 10 ) returns a number that 's 4.44E-16 off its actual value . ( I later found that the built-in Math.Log10 ( double ) provides much more accurate results . ) Should n't the threshold should be tied to Double.Epsilon or , if not , should n't the threshold be documented ( I could n't find any mention of this in the official MSDN documentation ) ? <code> double x = 3.0 ; Console.WriteLine ( Math.Floor ( x - Double.Epsilon ) ) ; // expected 2 , got 3Console.WriteLine ( Math.Ceiling ( x + Double.Epsilon ) ) ; // expected 4 , got 3 Console.WriteLine ( Math.Floor ( x - Double.Epsilon*1000 ) ) ; // expected 2 , got 3Console.WriteLine ( Math.Ceiling ( x + Double.Epsilon*1000 ) ) ; // expected 4 , got 3
|
Unexpected Behavior of Math.Floor ( double ) and Math.Ceiling ( double )
|
C_sharp : I 'm using Mono.Cecil 0.9.5.3 , and after installing VS2012 RC ( which causes the .NET 4.0 System.XML.DLL to be replaced with its .NET 4.5 counterpart ) , I get an System.ArugmentException in some code that iterates each methods ' custom attributes . It appears the cause is that in certain cases , the AsyncStateMachine attribute 's ctor argument , which should be a Type , is empty . The following piece of code reproduces it : The exception is thrown from My question is - is this a bug in Mono.Cecil , or the System.Xml.DLL ? Does the spec allow for an `` empty '' Type to appear as the ctor argument ? <code> string path = Assembly.Load ( `` System.Xml , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' ) .Location ; AssemblyDefinition systemXmlAssembly = AssemblyDefinition.ReadAssembly ( path ) ; var query = from ModuleDefinition module in systemXmlAssembly.Modules from TypeDefinition td in module.Types from MethodDefinition method in td.Methods from CustomAttribute att in method.CustomAttributes where method.Name == `` System.Xml.IDtdParser.ParseInternalDtdAsync '' & & att.AttributeType.Name == `` AsyncStateMachineAttribute '' select att ; CustomAttribute attribute = query.Single ( ) ; var args = attribute.ConstructorArguments ; // < -- -- this line throws an ArgumentException Mono.Cecil.ModuleDefinition.CheckFullName ( string fullName = `` '' )
|
Mono.Cecil Exception thrown when analyzing .NET 4.5 version of System.Xml DLL , why ?
|
C_sharp : I am trying to deserialize my packages.config file in C # but the Collection i get back is always null . Is there something special that is needed if my xml file consists of a single collection of attributes ? where my packages.config looks like <code> [ Serializable ( ) ] [ System.Xml.Serialization.XmlTypeAttribute ( ) ] public class Package { [ System.Xml.Serialization.XmlAttribute ( `` id '' ) ] public string Id { get ; set ; } [ System.Xml.Serialization.XmlAttribute ( `` version '' ) ] public string Version { get ; set ; } } [ Serializable ( ) ] [ System.Xml.Serialization.XmlRoot ( `` packages '' ) ] public class PackageCollection { [ System.Xml.Serialization.XmlArrayItem ( `` package '' , typeof ( Package ) ) ] public Package [ ] Packages { get ; set ; } } void Main ( ) { var path = `` C : \D\packages.config '' ; var serializer = new System.Xml.Serialization.XmlSerializer ( typeof ( PackageCollection ) , new System.Xml.Serialization.XmlRootAttribute ( `` packages '' ) ) ; StreamReader reader = new StreamReader ( file ) ; var packages2 = ( PackageCollection ) serializer.Deserialize ( reader ) ; reader.Close ( ) ; } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < packages > < package id= '' Autofac '' version= '' 3.3.1 '' targetFramework= '' net45 '' / > < package id= '' Microsoft.AspNet.WebApi.Client '' version= '' 4.0.20710.0 '' targetFramework= '' net45 '' / > < package id= '' Microsoft.AspNet.WebApi.Core '' version= '' 4.0.20710.0 '' targetFramework= '' net45 '' / > < package id= '' Microsoft.AspNet.WebApi.Tracing '' version= '' 4.0.30506 '' targetFramework= '' net45 '' / > < package id= '' Microsoft.Net.Http '' version= '' 2.0.20710.0 '' targetFramework= '' net45 '' / > < package id= '' Microsoft.Web.Infrastructure '' version= '' 1.0.0.0 '' targetFramework= '' net45 '' / > < package id= '' Newtonsoft.Json '' version= '' 4.5.11 '' targetFramework= '' net45 '' / > < /packages >
|
Why does deserializing my packages.config in c # return null values ?
|
C_sharp : I have the following string : I want to split it according to 1 . 2 . 3. and so on : Is there any way I can do it C # ? <code> string text = `` 1 . This is first sentence . 2 . This is the second sentence . 3 . This is the third sentence . 4 . This is the fourth sentence . '' result [ 0 ] == `` This is first sentence . `` result [ 1 ] == `` This is the second sentence . `` result [ 2 ] == `` This is the third sentence . `` result [ 3 ] == `` This is the fourth sentence . ''
|
String split using C #
|
C_sharp : I got hit by a strange `` asymmetry '' in C # that I do not really understand . See the following code : It might be obvious for all you .NET gurus , but the 2nd assert fails.In Java I have learnt that == is a synonym for something called Object.ReferenceEquals here . In C # , I thought that Object.operator== uses Object.Equals , which is virtual , so it is overriden in the System.String class.Can someone explain , why does the 2nd assert fail in C # ? Which of my assumptions are bad ? <code> using System ; using System.Diagnostics ; namespace EqualsExperiment { class Program { static void Main ( string [ ] args ) { object apple = `` apple '' ; object orange = string.Format ( `` { 0 } { 1 } '' , `` ap '' , `` ple '' ) ; Console.WriteLine ( `` 1 '' ) ; Debug.Assert ( apple.Equals ( orange ) ) ; Console.WriteLine ( `` 2 '' ) ; Debug.Assert ( apple == orange ) ; Console.WriteLine ( `` 3 '' ) ; } } }
|
Object.Equals is virtual , but Object.operator== does not use it in C # ?
|
C_sharp : I am a C++ developer and recently started working on WPF . Well I am using Array.Copy ( ) in my app and looks like I am not able to completely get the desired result . I had done in my C++ app as follows : I did the similar operation in my WPF ( C # ) app as follows : But it throws me an error at Array.Copy ( sendBuf + memloc , version , 8 ) ; as Operator '+ ' can not be applied to operands of type 'byte [ ] ' and 'int ' . How can achieve this ? ? ? ? : ) please help : ) <code> static const signed char version [ 40 ] = { ' A ' , ' U ' , 'D ' , ' I ' , ' E ' , ' N ' , ' C ' , ' E ' , // name 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // reserved , firmware size 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // board number 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // variant , version , serial 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 // date code , reserved } ; unsigned char sendBuf [ 256 ] = { } ; int memloc = 0 ; sendBuf [ memloc++ ] = 0 ; sendBuf [ memloc++ ] = 0 ; // fill in the audience headermemcpy ( sendBuf+memloc , version , 8 ) ; // the first 8 bytesmemloc += 16 ; // the 8 copied , plus 8 reserved bytes Byte [ ] sendBuf = new Byte [ 256 ] ; char [ ] version = { ' A ' , ' U ' , 'D ' , ' I ' , ' E ' , ' N ' , ' C ' , ' E ' , // name ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , // reserved , firmware size ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , // board number ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , // variant , version , serial ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' , ' 0 ' // date code , reserved } ; // fill in the address to write to -- 0 sendBuf [ memloc++ ] = 0 ; sendBuf [ memloc++ ] = 0 ; // fill in the audience header Array.Copy ( sendBuf + memloc , version , 8 ) ; // the first 8 bytes memloc += 16 ;
|
Failing to use Array.Copy ( ) in my WPF App
|
C_sharp : I 'm fairly experienced in .NET development but today I was forced to wrap my head around something I 'd never thought about before : How do the installed .NET Framework , the .NET Framework target in Visual Studio and the C # compiler work together ? Concrete example : The System.dll contains the enum System.Net.SecurityProtocolType . On .NET 4.5 this enum contains the members SSl3 , Tls , Tls11 , and Tls12 . With .NET 4.7 , the member SystemDefault was added.So , targeting .NET 4.7.x , this code compiles fine : However , when I target .NET 4.5.x , this code does not compile ( as one would expect ) .What puzzles me here is why this works considering that .NET 4.7 is an in-place update to .NET 4.5 ( i.e . when installing .NET 4.7 , the System.dll of .NET 4.5 is replaced with the one of .NET 4.7 ) .How does the compiler know that I ca n't use SystemDefault on .NET 4.5 but can use it on 4.7 ? Is this done via some kind of API file known to the compiler ? Side fact : When I target .NET 4.5 and have .NET 4.7 installed , a call to Enum.GetValues ( typeof ( SecurityProtocolType ) will give me SecurityProtocolType.SystemDefault . So I 'm fairly certain that my .NET 4.5 application uses the .NET 4.7 System.dll . <code> var p = SecurityProtocolType.SystemDefault ;
|
.NET target framework compatibility and the compiler - on .NET 4.5 or higher
|
C_sharp : My MVC webapp allows users to add and delete images . The UI calls ImageService.SaveImage ( ... ) in my business layer which internally uses a flag that tells the method to save to either Azure or the file system . I might eventually add S3 to I figure an interface here would work great . This is what I would imaging the code would look like in my ImageService class . It does n't care about how the file is saved or where.So I created these implementationsQuestion 1 ) What 's the best way to pass in additional info each provider may need ? I.e . Azure needs to know container name , blob name ( filename ) , and storageAccount name . S3 may need more as well . A good example is the files path . This could be different for each provider or not exist at all . Azure needs a container name , the file system needs a directory name . If they are different for each provider how would I add that to the interface ? Question 2 ) Should I use dependency injection to resolve the interface within the ImageService class in the business layer or should I resolve it in the UI and pass it into the class ? <code> // Service the UI usespublic static class ImageService { public static void SaveImage ( byte [ ] data , IImageProvider imageProvider ) { string fileName = `` some_generated_name.jpg '' imageProvider.Save ( fileName , data ) ; } } public interface IImageProvider { void Save ( string filename , byte [ ] imageData ) ; byte [ ] Get ( string filename ) ; void Delete ( string filename ) ; } // File system implementationpublic class FSImageProvider : IImageProvider { public void Delete ( string filename ) { File.Delete ( filename ) ; } public byte [ ] Get ( filename ) { return File.ReadAllBytes ( filename ) ; } public void Save ( string filename , byte [ ] imageData ) { File.WriteAllBytes ( filename , imageData ) ; } } // Azure implementationpublic class AzureBlobImageProvider : IImageProvider { private string _azureKey = `` '' ; private string _storageAccountName = `` '' ; public AzureBlobImageProvider ( string azureKey , string storageAccount ) { _azureKey = azureKey ; _storageAccountName = storageAccount ; } public void Delete ( string filename ) { throw new NotImplementedException ( ) ; } public byte [ ] Get ( string filename ) { throw new NotImplementedException ( ) ; } public void Save ( string filename , byte [ ] imageData ) { throw new NotImplementedException ( ) ; } }
|
How to implement interface with additional parameters/info per implementation
|
C_sharp : The text `` lblDate.Content '' disappears when I use the sleep timer to close the window . How do I get that text to display ? The rest of the window/text is shown . I 'm open to other ways to autoclose a window . <code> public void DisplayErrorMessage ( string message ) { // Error Message TextBox textBox1.Text = message ; Show ( ) ; // Show date and logged message lblDate.Content = `` This error has been logged and an administrator contacted : `` + DateTime.Now ; // Auto close window System.Threading.Thread.Sleep ( 3000 ) ; this.Close ( ) ; }
|
c # autoclose window with sleep but text disappears
|
C_sharp : This is the c # codeThis is the IL of M1 methodMy question is : Why twice ldarg.0 ? <code> class SimpleIL { private int f = 2 ; public void M1 ( ) { M2 ( f ) ; } public void M2 ( Object p ) { Console.WriteLine ( p ) ; } } IL_0000 : nop IL_0001 : ldarg.0 IL_0002 : ldarg.0 IL_0003 : ldfld int32 ConsoleApplication1.SimpleIL : :f IL_0008 : box [ mscorlib ] System.Int32 IL_000d : call instance void ConsoleApplication1.SimpleIL : :M2 ( object ) IL_0012 : nop IL_0013 : ret
|
IL code , Someone get me explain why ldarg.0 appear twice ?
|
C_sharp : I have a Class that retrieves some data and images does some stuff to them and them uploads them to a third party app using web services.The object needs to perform some specific steps in order.My question is should I be explicitly exposing each method publicly like so . or should all of these methods be private and encapsulated in a single public method like so.which is called like so . <code> myObject obj = new myObject ( ) ; obj.RetrieveImages ( ) ; obj.RetrieveAssociatedData ( ) ; obj.LogIntoThirdPartyWebService ( ) ; obj.UploadStuffToWebService ( ) ; public class myObject ( ) { private void RetrieveImages ( ) { } ; private void RetrieveAssociatedData ( ) { } ; private void LogIntoThirdPartyWebService ( ) { } ; private void UploadStuffToWebService ( ) { } ; public void DoStuff ( ) { this.RetrieveImages ( ) ; this.RetrieveAssociatedData ( ) ; this.LogIntoThirdPartyWebService ( ) ; this.UploadStuffToWebService ( ) ; } } myObject obj = new myObject ( ) ; obj.DoStuff ( ) ;
|
Should methods that are required to be executed in a specific order be private ?
|
C_sharp : I have a WCF service that has a few different responsibilities , but it provides one entry point for anyone interacting with my code . To keep it simple , let 's say there are 2 methodsBecause consumers will only call the service for one reason , MethodA or MethodB , is it a problem that the IOC container will be needlessly spinning up all dependencies ? I want to provide a single entry point , so I do n't want to split up the service , but it seems a little wasteful to spin up all the dependencies when each consumer of the service will only need a subset . Another way I was thinking of doing this would be something like This allows each `` path '' to bring up the dependencies it needs , however , that makes it a lot harder to write unit tests . Does anyone have any suggestions ? How big of an issue is it to spin up all the dependencies ? After this first entry point into the service , it will make sense to inject the dependencies via the constructor , but at this first entry point , what is the recommended approach ? <code> private IMethodAHelper _methodA ; private IMethodBHelper _methodB ; public MyService ( IMethodAHelper methodA , IMethodBHelper methodB ) { _methodA = methodA ; _methodB = methodB ; } public void MethodA ( ) { _methodA.CallThis ( ) ; } public void MethodB ( ) { _methodB.CallThis ( ) ; } public void MethodA ( ) { var methodA = ObjectFactory.GetInstance < IMethodAHelper > ( ) ; methodA.CallThis ( ) ; }
|
IOC Container - WCF Service - Should I instantiate all dependencies via constructor ?
|
C_sharp : To reduce redundant code , I have some throw helper methods : Usage : Problem : Because the operator + must always return a value , I fixed this by making ThrowInvalidOperation return a value and call it with returnThrowInvalidOperation ( `` + '' , a , b ) ; There a many disadvatages - one is because I ca n't call it from a method returning a different type.I wish there is there a way to mark the helper function `` always throws a exception '' , so the compiler stops tracking return values.Q : What possibilities do I have to make this work ? <code> protected static X ThrowInvalidOperation ( string operation , X a , X b ) { throw new InvalidOperationException ( `` Invalid operation : `` + a.type.ToString ( ) + `` `` + operation + `` `` + b.type.ToString ( ) ) ; } public static X operator + ( X a , X b ) { if ( ... ) { return new X ( ... ) ; } return ThrowInvalidOperation ( `` + '' , a , b ) ; }
|
Thoughts on throw helpers
|
C_sharp : I want a function that I can call as an alternative to .ToString ( ) , that will show the contents of collections.I 've tried this : but the second overload never gets called . For example : I 'm expecting this output : What actually happens is this : dict is correctly interpreted as an IEnumerable < KeyValuePair < int , List < string > > > , so the 3rd overload is called.the 3rd overload calls dump on a KeyValuePair > . This should ( ? ) invoke the second overload , but it does n't -- it calls the first overload instead.So we get this output : which is built from KeyValuePair 's .ToString ( ) method.Why is n't the second overload called ? It seems to me that the runtime should have all the information it needs to identify a KeyValuePair with full generic arguments and call that one . <code> public static string dump ( Object o ) { if ( o == null ) return `` null '' ; return o.ToString ( ) ; } public static string dump < K , V > ( KeyValuePair < K , V > kv ) { return dump ( kv.Key ) + `` = > '' + dump ( kv.Value ) ; } public static string dump < T > ( IEnumerable < T > list ) { StringBuilder result = new StringBuilder ( `` { `` ) ; foreach ( T t in list ) { result.Append ( dump ( t ) ) ; result.Append ( `` , `` ) ; } result.Append ( `` } '' ) ; return result.ToString ( ) ; } List < string > list = new List < string > ( ) ; list.Add ( `` polo '' ) ; Dictionary < int , List < string > > dict ; dict.Add ( 1 , list ) ; Console.WriteLine ( dump ( dict ) ) ; { 1= > { `` polo '' , } , } { [ 1= > System.Collections.Generic.List ` 1 [ System.String ] ] , }
|
How do I convert IEnumerable < T > to string , recursively ?
|
C_sharp : 15 years ago , while programming with Pascal , I understood why to use power of two 's for memory allocation . But this still seems to be state-of-the-art.C # Examples : I still see this thousands of times , I use this myself and I 'm still questioning : Do we need this in modern programming languages and modern hardware ? I guess its good practice , but what 's the reason ? EDITFor example a byte [ ] array , as stated by answers here , a power of 2 will make no sense : the array itself will use 16 bytes ( ? ) , so does it make sense to use 240 ( =256-16 ) for the size to fit a total of 256 bytes ? <code> new StringBuilder ( 256 ) ; new byte [ 1024 ] ; int bufferSize = 1 < < 12 ;
|
Why does everyone use 2^n numbers for allocation ? - > new StringBuilder ( 256 )
|
C_sharp : I have created a controller with an Index action . All of my other Actions return the views just fine ... but for some reason I have to specify the full url to have the Index view return . It 's almost like my Routes are n't working correctly.For instance , to go to the properties page , you have to go to /Properties/Index instead of just /Properties/ . My routes are as follows . Any help would be greatly appreciated ! <code> routes.MapRoute ( name : `` Index '' , url : `` { controller } / { action } / { id } '' , defaults : new { controller = `` Home '' , action = `` Index '' , id = UrlParameter.Optional } ) ;
|
MVC4 Index Action Not Working Correctly
|
C_sharp : I have implemented the following benchmark using BenchmarkDotNet : The results are : Originally I guessed the Array.Fill does some optimizations which make it perform better than for-loop , but then I checked the .NET Core source code to see that the Array.Fill implementation is pretty straightforward : The performance is close enough , but it stills seems Fill is consistently a bit faster then for even though under the hood it is exactly the same code . Can you explain why ? Or am I just reading the results incorrectly ? <code> public class ForVsFillVsEnumerable { private bool [ ] data ; [ Params ( 10 , 100 , 1000 ) ] public int N ; [ GlobalSetup ] public void Setup ( ) { data = new bool [ N ] ; } [ Benchmark ] public void Fill ( ) { Array.Fill ( data , true ) ; } [ Benchmark ] public void For ( ) { for ( int i = 0 ; i < data.Length ; i++ ) { data [ i ] = true ; } } [ Benchmark ] public void EnumerableRepeat ( ) { data = Enumerable.Repeat ( true , N ) .ToArray ( ) ; } } BenchmarkDotNet=v0.11.3 , OS=Windows 10.0.17763.195 ( 1809/October2018Update/Redstone5 ) Intel Core i7-8700K CPU 3.70GHz ( Coffee Lake ) , 1 CPU , 12 logical and 6 physical cores.NET Core SDK=2.2.200-preview-009648 [ Host ] : .NET Core 2.2.0 ( CoreCLR 4.6.27110.04 , CoreFX 4.6.27110.04 ) , 64bit RyuJIT Core : .NET Core 2.2.0 ( CoreCLR 4.6.27110.04 , CoreFX 4.6.27110.04 ) , 64bit RyuJITJob=Core Runtime=Core Method | N | Mean | Error | StdDev | Median | Ratio | Rank | -- -- -- -- -- -- -- -- - | -- -- - | -- -- -- -- -- - : | -- -- -- -- -- - : | -- -- -- -- -- -- : | -- -- -- -- -- - : | -- -- -- : | -- -- - : | Fill | 10 | 3.675 ns | 0.2550 ns | 0.7150 ns | 3.331 ns | 1.00 | 1 | | | | | | | | | For | 10 | 6.615 ns | 0.3928 ns | 1.1581 ns | 6.056 ns | 1.00 | 1 | | | | | | | | | EnumerableRepeat | 10 | 25.388 ns | 1.0451 ns | 2.9307 ns | 24.170 ns | 1.00 | 1 | | | | | | | | | Fill | 100 | 50.557 ns | 2.0766 ns | 6.1229 ns | 46.690 ns | 1.00 | 1 | | | | | | | | | For | 100 | 64.330 ns | 4.0058 ns | 11.8111 ns | 59.442 ns | 1.00 | 1 | | | | | | | | | EnumerableRepeat | 100 | 81.784 ns | 4.2407 ns | 12.5039 ns | 75.937 ns | 1.00 | 1 | | | | | | | | | Fill | 1000 | 447.016 ns | 15.4420 ns | 45.5312 ns | 420.239 ns | 1.00 | 1 | | | | | | | | | For | 1000 | 589.243 ns | 51.3450 ns | 151.3917 ns | 495.177 ns | 1.00 | 1 | | | | | | | | | EnumerableRepeat | 1000 | 519.124 ns | 21.3580 ns | 62.9746 ns | 505.573 ns | 1.00 | 1 | public static void Fill < T > ( T [ ] array , T value ) { if ( array == null ) { ThrowHelper.ThrowArgumentNullException ( ExceptionArgument.array ) ; } for ( int i = 0 ; i < array.Length ; i++ ) { array [ i ] = value ; } }
|
Performance difference between C # for-loop and Array.Fill
|
C_sharp : I am working on implementing AutoMapper in our service and am seeing a very confusing issue in our unit tests.First off this issue involves the following objects and their respective maps : It also involves these objects , though I have n't mapped these with AutoMapper at this point : These classes are converted using custom code that includes the following , where source is a DbParty : The test I 'm having an issue with creates a new DbParty , 2 new DbAccounts linked to the new DbParty , and 2 new DbPartyAccountRoles both linked to the new DbParty and 1 each to each of the DbAccounts.It then tests some update functionality via the DbParty repository . I can include some code for this if needed it will just take some time to scrub.When run by itself this test works just fine , but when run in the same session as another test ( that I will detail below ) the Mapper call in the above conversion code throws this exception : The other test also creates a new DbParty but with only one DbAccount and then creates 3 DbPartyAccountRoles . I was able to narrow this test down to the exact line that breaks the other test and it is : Commenting out this line allows the other test to pass . With that information my guess is that the test is breaking because of something to do with the CastleProxy that is behind the DbAccount object when calling AutoMapper but I do n't have the slightest idea of how.I 've now managed to run the relevant functional tests ( making calls against the service itself ) and they seem to work fine , this makes me think the unit test setup may be a factor , most notable is that the tests in question are run against a SqlLite in memory database . <code> public class DbAccount : ActiveRecordBase < DbAccount > { // this is the ORM entity } public class Account { // this is the primary full valued Dto } public class LazyAccount : Account { // this class as it is named does n't load the majority of the properties of account } Mapper.CreateMap < DbAccount , Account > ( ) ; //There are lots of custom mappings , but I do n't believe they are relevantMapper.CreateMap < DbAccount , LazyAccount > ( ) ; //All non matched properties are ignored public class DbParty : ActiveRecordBase < DbParty > { public IList < DbPartyAccountRole > PartyAccountRoles { get ; set ; } public IList < DbAccount > Accounts { get ; set ; } } public class DbPartyAccountRole : ActiveRecordBase < DbPartyAccountRole > { public DbParty Party { get ; set ; } public DbAccount Account { get ; set ; } } var party = new Party ( ) //field to field mapping hereforeach ( var partyAccountRole in source.PartyAccountRoles ) { var account = Mapper.Map < LazyAccount > ( partyAccountRole.Account ) ; account.Party = party ; party.Accounts.Add ( account ) ; } System.InvalidCastException : Unable to cast object of type ' [ Namespace ] .Account ' to type ' [ Namespace ] .LazyAccount ' . Assert.That ( DbPartyAccountRole.FindAll ( ) .Count ( ) , Is.EqualTo ( 3 ) )
|
How to stop Automapper from mapping to parent class when child class was requested
|
C_sharp : So I 've been tinkering with Linq.Expressions ( and if anyone can suggest a more proper or more elegant way to do what I 'm doing please feel free to chime in ) and have hit a wall in trying to do something . Let 's imagine we have a simple math class : I decide I want to convert our AddNumbers method to a simple Func < object , object , object > delegate . To do this I do the following : So if you run that code func should return simple calculations . However , it accepts parameters of Type Object , which obviously leaves it open to problems at runtime , for example : So I want to wrap the method in a Try ... Catch ( obviously this exact problem would be picked up at compile time if we were dealing with a straight call to AddNumbers and passing a string as a parameter ) .So to catch this exception I can do the following : The TryExpression.TryCatch takes an Expression body and then a collection of CatchBlock handlers . returnMethodWithParametersAsObject is the expression we wish to wrap , Expression.Catch defines that the Exception we want to catch is of Type InvalidCastException and its Expression body is a constant , 55.So the exception is handled , but it 's not much use unless I want to always return a static value when the exception is thrown . So returning to the SimpleMath class I add a new method HandleException : And following the same process above I convert the new method to an Expression : Then using it when creating the TryCatch block : So this time when the InvalidCastException is thrown the SimpleMath.HandleException method will be executed . So far so good , I can now execute some code when there is an exception.My problem now is , in a normal inline Try ... Catch block you actually have the exception object at your disposal . E.g.I can execute code when an exception is thrown but I ca n't seem to figure out how to actually get my hands on the exception object like you would in a normal Try ... Catch block.Any help would be appreciated ! p.s . I know that you would n't actually organise anything in the way I 've done above but I thought it was necessary for example purposes to show the mechanics of what I want to do . <code> public class SimpleMath { public int AddNumbers ( int number1 , int number2 ) { return number1 + number2 ; } } // Two collections , one for Type Object paramaters and one for converting to Type int.List < ParameterExpression > parameters = new List < ParameterExpression > ( ) ; List < Expression > convertedParameters = new List < Expression > ( ) ; // Populate collections with Parameter and conversionParameterExpression parameter1 = Expression.Parameter ( typeof ( object ) ) ; parameters.Add ( parameter1 ) ; convertedParameters.Add ( Expression.Convert ( parameter1 , typeof ( int ) ) ) ; ParameterExpression parameter2 = Expression.Parameter ( typeof ( object ) ) ; parameters.Add ( parameter2 ) ; convertedParameters.Add ( Expression.Convert ( parameter2 , typeof ( int ) ) ) ; // Create instance of SimpleMathSimpleMath simpleMath = new SimpleMath ( ) ; // Get the MethodInfo for the AddNumbers methodMethodInfo addNumebrsMethodInfo = simpleMath.GetType ( ) .GetMethods ( ) .Where ( x = > x.Name == `` AddNumbers '' ) .ToArray ( ) [ 0 ] ; // Create MethodCallExpression using the SimpleMath object , the MethodInfo of the method we want and the converted parametersMethodCallExpression returnMethodWithParameters = Expression.Call ( Expression.Constant ( simpleMath ) , addNumebrsMethodInfo , convertedParameters ) ; // Convert the MethodCallExpression to return an Object rather than intUnaryExpression returnMethodWithParametersAsObject = Expression.Convert ( returnMethodWithParameters , typeof ( object ) ) ; // Create the Func < object , object , object > with our converted Expression and Parameters of Type ObjectFunc < object , object , object > func = Expression.Lambda < Func < object , object , object > > ( returnMethodWithParametersAsObject , parameters ) .Compile ( ) ; object result = func ( 20 , 40 ) ; // result = 60 object result1 = func ( 20 , `` f '' ) ; // Throws InvalidCastException TryExpression tryCatchMethod = TryExpression.TryCatch ( returnMethodWithParametersAsObject , Expression.Catch ( typeof ( InvalidCastException ) , Expression.Constant ( 55 , typeof ( object ) ) ) ) ; Func < object , object , object > func = Expression.Lambda < Func < object , object , object > > ( tryCatchMethod , parameters ) .Compile ( ) ; object result = func ( 20 , `` f '' ) ; // result = 55 public class SimpleMath { public int AddNumbers ( int number1 , int number2 ) { return number1 + number2 ; } public int HandleException ( ) { return 100 ; } } MethodInfo handleExceptionMethodInfo = simpleMath.GetType ( ) .GetMethods ( ) .Where ( x = > x.Name == `` HandleException '' ) .ToArray ( ) [ 0 ] ; MethodCallExpression returnMethodWithParameters2 = Expression.Call ( Expression.Constant ( simpleMath ) , handleExceptionMethodInfo ) ; UnaryExpression returnMethodWithParametersAsObject2 = Expression.Convert ( returnMethodWithParameters2 , typeof ( object ) ) ; TryExpression tryCatchMethod2 = TryExpression.TryCatch ( returnMethodWithParametersAsObject , Expression.Catch ( typeof ( InvalidCastException ) , returnMethodWithParametersAsObject2 ) ) ; Func < object , object , object > func = Expression.Lambda < Func < object , object , object > > ( tryCatchMethod2 , parameters ) .Compile ( ) ; object result = func ( 20 , `` f '' ) ; // result = 100 try { // Do stuff that causes an exception } catch ( InvalidCastException ex ) { // Do stuff with InvalidCastException ex }
|
Linq.Expression TryCatch - Pass exception to Catch Block ?
|
C_sharp : I have about 100k Outlook mail items that have about 500-600 chars per Body . I have a list of 580 keywords that must search through each body , then append the words at the bottom.I believe I 've increased the efficiency of the majority of the function , but it still takes a lot of time . Even for 100 emails it takes about 4 seconds.I run two functions for each keyword list ( 290 keywords each list ) .Is there anyway I can increase the efficiency of this function ? The other thing that might be slowing it down is that I use HTML Agility Pack to navigate through some nodes and pull out the body ( nSearch.InnerHtml ) . The _keywordList is a List item , and not an array . <code> public List < string > Keyword_Search ( HtmlNode nSearch ) { var wordFound = new List < string > ( ) ; foreach ( string currWord in _keywordList ) { bool isMatch = Regex.IsMatch ( nSearch.InnerHtml , `` \\b '' + @ currWord + `` \\b '' , RegexOptions.IgnoreCase ) ; if ( isMatch ) { wordFound.Add ( currWord ) ; } } return wordFound ; }
|
Increasing Regex Efficiency
|
C_sharp : Suppose I have a list of strings , like this : Now I 'd like to verify that another List < String > , let 's call it list1 , contains each of those candidates exactly once . How can I do that , succintly ? I think I can use Intersect ( ) . I also want to get the missing candidates . Order does n't matter . <code> var candidates = new List < String > { `` Peter '' , `` Chris '' , `` Maggie '' , `` Virginia '' } ; private bool ContainsAllCandidatesOnce ( List < String > list1 ) { ? ? ? ? } private IEnumerable < String > MissingCandidates ( List < String > list1 ) { ? ? ? ? }
|
how to ensure a List < String > contains each string in a sequence exactly once
|
C_sharp : This is asked more out of curiosity than with regards to any real-world problem . Consider the following code : In the synchronous world , this would ultimately cause a stackoverflow.In the async world , this simply consumes a lot of memory ( which I assume is related to something that I might loosely call the `` asynchronous stack '' ? ) What precisely is this data , and how is it held ? <code> void Main ( ) { FAsync ( ) .Wait ( ) ; } async Task FAsync ( ) { await Task.Yield ( ) ; await FAsync ( ) ; }
|
Async recursion . Where is my memory actually going ?
|
C_sharp : I have a WCF service hosted in a consol application ( that also acts as the Windows Service installer ) , pleas see more here : http : //msdn.microsoft.com/en-us/library/ms733069.aspxThis is how the class in the consol application looks like : This is made for running in a Windows Service , how do I make so I can run this as a regular selfhost in debug mode ( during development ) ? or do I really have to start a special project to be able to debug this servuce during runtime ? Edit : I decided to use the existing windows service project but change the main to something like this : <code> public class MyAppWindowsService : ServiceBase { public ServiceHost _MyAppClientServiceHost = null ; public ServiceHost _MyAppIntegrationServiceHost = null ; public ServiceHost _MyAppserviceHost = null ; public MyAppWindowsService ( ) { // Name the Windows Service ServiceName = `` MyApp Service '' ; } public static void Main ( ) { ServiceBase.Run ( new MyAppWindowsService ( ) ) ; } private void StopService ( ServiceHost serviceHost ) { if ( serviceHost ! = null ) { serviceHost.Close ( ) ; serviceHost = null ; } } private ServiceHost StartService ( Type serviceType ) { ServiceHost serviceHost = null ; // Create a ServiceHost for the CalculatorService type and // provide the base address . serviceHost = new ServiceHost ( serviceType ) ; // Open the ServiceHostBase to create listeners and start // listening for messages . serviceHost.Open ( ) ; return serviceHost ; } private void StartServices ( ) { StopService ( _MyAppClientServiceHost ) ; StopService ( _MyAppIntegrationServiceHost ) ; StopService ( _MyAppServiceHost ) ; _MyAppClientServiceHost = StartService ( typeof ( MyApp.ServiceImplementation.MyAppClientService ) ) ; _MyAppIntegrationServiceHost = StartService ( typeof ( MyApp.ServiceImplementation.MyAppIntegration ) ) ; _MyAppServiceHost = StartService ( typeof ( MyApp.ServiceImplementation.HL7Service ) ) ; } private void StopServices ( ) { StopService ( _MyAppClientServiceHost ) ; StopService ( _MyAppIntegrationServiceHost ) ; StopService ( _MyAppHl7ServiceHost ) ; } // Start the Windows service . protected override void OnStart ( string [ ] args ) { StartServices ( ) ; } protected override void OnStop ( ) { StopServices ( ) ; } } public static void Main ( ) { if ( Debugger.IsAttached ) { Console.WriteLine ( `` -- - MyApp Services -- - '' ) ; Console.WriteLine ( `` Starting services ... '' ) ; Instance.StartServices ( ) ; Console.WriteLine ( `` -- Finished -- '' ) ; Console.WriteLine ( `` Press any key to exit '' ) ; Console.ReadKey ( ) ; Instance.StopServices ( ) ; } else ServiceBase.Run ( new MyAppWindowsService ( ) ) ; }
|
Running consol application in debug mode with WCF selfhosting ?
|
C_sharp : While doing some fancy code generation , I 've encountered a stack overflow that I do n't understand.My code is basically like this : If you use small numbers like here ( 100 ) everything works fine . If the numbers are large , strange things happens . In my case , I tried emitting approximately 10K lines of code like this , which triggered a stack overflow exception.So ... why do I think this is strange : tmp is a local of a reference type , and therefore I expect only the pointer to be allocated on the heap.Tuples are reference types and allocated on the heap.No recursion or other weirdness ; afaik the storage requirements on the heap should be limited.Reproducing the strangeness ... I can not reproduce the stackoverflow in a minimum test case , but I did notice it seems to be triggered on 64-bit .NET 4.5 . What I can give is some evidence that demonstrates what 's going on.Also note that the real code uses Reflection.Emit code that does this code generation ... it 's not like the code itself has all these lines of code ... The emitted IL code is correct BTW.In Visual Studio - put a breakpoint on the last line . Notice the use of the stack pointer in the disassembly ( ASM , not IL ) .Now add a new line to the code -- e.g . tmp [ 100 ] = // the usuals . Put a breakpoint here as well and notice that the used stack space grows . As for an attempt to reproduce using a minimum test-case using Reflection.Emit , this is the code ( which DOES NOT reproduce the problem strangely enough -- but is very close to what I 've done to trigger the stack overflow ... it should give a bit of a picture what I 'm trying to do , and perhaps someone else can produce a viable test case using this ) . Here goes : My questionHow on earth can something like this produce a SOE ? What 's going on here ? Why are things put on the stack in this context anyways ? <code> static Tuple < string , int > [ ] DoWork ( ) { // [ call some methods ] Tuple < string , int > [ ] tmp = new Tuple < string , int > [ 100 ] ; tmp [ 0 ] = new Tuple < string , int > ( `` blah 1 '' , 0 ) ; tmp [ 1 ] = new Tuple < string , int > ( `` blah 2 '' , 1 ) ; tmp [ 2 ] = new Tuple < string , int > ( `` blah 3 '' , 2 ) ; // ... tmp [ 99 ] = new Tuple < string , int > ( `` blah 99 '' , 99 ) ; return tmp ; } public static void Foo ( ) { Console.WriteLine ( `` Foo ! `` ) ; } static void Main ( string [ ] args ) { // all this just to invoke one opcode with no arguments ! var assemblyName = new AssemblyName ( `` MyAssembly '' ) ; var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly ( assemblyName , AssemblyBuilderAccess.RunAndCollect ) ; // Create module var moduleBuilder = assemblyBuilder.DefineDynamicModule ( `` MyModule '' ) ; var type = moduleBuilder.DefineType ( `` MyType '' , TypeAttributes.Public , typeof ( object ) ) ; var method = type.DefineMethod ( `` Test '' , System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Static , System.Reflection.CallingConventions.Standard , typeof ( Tuple < string , int > [ ] ) , new Type [ 0 ] ) ; ILGenerator gen = method.GetILGenerator ( ) ; int count = 0x10000 ; gen.Emit ( OpCodes.Call , typeof ( StackOverflowGenerator ) .GetMethod ( `` Foo '' ) ) ; var loc = gen.DeclareLocal ( typeof ( Tuple < string , int > [ ] ) ) ; gen.Emit ( OpCodes.Ldc_I4 , count ) ; gen.Emit ( OpCodes.Newarr , typeof ( Tuple < string , int > ) ) ; gen.Emit ( OpCodes.Stloc , loc ) ; for ( int i = 0 ; i < count ; ++i ) { // Load array gen.Emit ( OpCodes.Ldloc , loc ) ; gen.Emit ( OpCodes.Ldc_I4 , i ) ; // Construct tuple : gen.Emit ( OpCodes.Ldstr , `` This is the string '' ) ; gen.Emit ( OpCodes.Ldc_I4 , i ) ; gen.Emit ( OpCodes.Newobj , typeof ( Tuple < string , int > ) .GetConstructor ( new [ ] { typeof ( string ) , typeof ( int ) } ) ) ; // Store in the array gen.Emit ( OpCodes.Stelem_Ref ) ; } // Return the result gen.Emit ( OpCodes.Ldloc , loc ) ; gen.Emit ( OpCodes.Ret ) ; var materialized = type.CreateType ( ) ; var tmp = checked ( ( Tuple < string , int > [ ] ) materialized.GetMethod ( `` Test '' ) .Invoke ( null , new object [ 0 ] ) ) ; int total = 0 ; foreach ( var item in tmp ) { total += item.Item1.Length + item.Item2 ; } Console.WriteLine ( `` Total : { 0 } '' , total ) ; Console.ReadLine ( ) ; }
|
Weird stackoverflow in c # when allocating reference types
|
C_sharp : I 'm getting an odd response from a site that I was looking to parse with FiddlerCore . In chrome developer tools if I inspect the response it looks completely normal , in fiddler it does n't . Code snippet as follows ( which used to work fine ) Returns the following , which is n't html , note this is a sample rather than the full huge string.It 's also littered with `` \n '' and html like thisResponse headers are as follows : Fiddler startup code : Initially i 'd assumed it was chunked/gzipped so I added utilDecodeResponse ( ) ; to onBeforeResponse which had no effect ! Just to cover all the bases I 'd also tried manually decoding responseBodyBytes in UTF-8 , Unicode , Bigendian etc just on the off chance the response content type was incorrect AND disabled javascript and loaded the page to prove it was n't some funky templating thingy , which also made no difference.Any ideas ? UPDATE : In line with the information provided by Developer & NineBerry below the solution is as follows : In order to prevent the response being SDCH encoded you can add an handler like so : It should be noted that this is n't suitable for everything as you are manually setting the headers rather than checking to see if SDCH is present and then removing it , for my purposes this works fine , but for using the general proxy features of fiddler you 'd want more logic here . <code> String html = oSession.GetResponseBodyAsString ( ) ; JRHwJNeR\0���\0\0\u0001��D\0�2�\b\0�\u0016�7 ] < ! DOCTYPE html > \n win\ '' > \n\n\n\n\n \n < meta name=\ '' treeID\ '' content=\ '' dwedxE+pgRQAWIHiFSsAAA==\ '' > \n Cache-Control : no-cache , no-storeConnection : keep-aliveContent-Encoding : sdch , gzipContent-Language : en-USContent-Type : text/html ; charset=UTF-8Date : Fri , 28 Oct 2016 10:17:02 GMTExpires : Thu , 01 Jan 1970 00:00:00 GMTPragma : no-cacheServer : Apache-Coyote/1.1Set-Cookie : lidc= '' b=VB87 : g=518 : u=60 : i=1477649823 : t=1477731496 : s=AQG-LTdly5mcIjAtiRHIOrKE1TiRWW-l '' ; Expires=Sat , 29 Oct 2016 08:58:16 GMT ; domain=.thedomain.com ; Path=/Set-Cookie : _lipt=deleteMe ; Expires=Thu , 01-Jan-1970 00:00:10 GMT ; Path=/Strict-Transport-Security : max-age=0Transfer-Encoding : chunkedVary : Accept-Encoding , Avail-DictionaryX-Content-Type-Options : nosniffX-Frame-Options : sameoriginX-FS-UUID:882b3366afaa811400a04937a92b0000X-Li-Fabric : prod-lva1X-Li-Pop : prod-tln1-scalableX-LI-UUID : iCszZq+qgRQAoEk3qSsAAA==X-XSS-Protection:1 ; mode=block Fiddler.FiddlerApplication.AfterSessionComplete += FiddlerApplication_OnAfterSessionComplete ; Fiddler.FiddlerApplication.BeforeResponse += delegate ( Fiddler.Session oS ) { oS.utilDecodeResponse ( ) ; } ; Fiddler.FiddlerApplication.Startup ( 0 , FiddlerCoreStartupFlags.Default ) ; } Fiddler.FiddlerApplication.BeforeRequest += delegate ( Fiddler.Session oS ) { oS.oRequest [ `` Accept-Encoding '' ] = `` gzip , deflate , br '' ; } ;
|
FiddlerCore decoding an sdch response
|
C_sharp : I have a C # method that looks a bit like this : In F # this ends up looking quite a bit uglier because of the mandatory else branches : What would be a cleaner way of writing this in F # ? <code> bool Eval ( ) { // do some work if ( conditionA ) { // do some work if ( conditionB ) { // do some work if ( conditionC ) { // do some work return true ; } } } return false ; } let eval ( ) = // do some work if conditionA then // do some work if conditionB then // do some work if conditionC then // do some work true else false else false else false
|
How can I refactor out the required else clause ?
|
C_sharp : The following example shows Type.GetType failing in a specific scenario.GetType succeeds when I provide it the class name string ( including namespace ) in a lambda expression , but fails when I specify the call to GetType as a method group.Fails : Succeeds : Both methods succeed when the class path includes the assembly name . I suspect it 's something to do with the current context/scope given the IL generated for the above . I can see the differences in the IL but I still ca n't explain the exact cause.The below is a runnable example that demonstrates the problem.I 'd like to know why # 2 fails but # 3 succeeds . <code> collectionOfClassNames.Select ( GetType ) collectionOfClassNames.Select ( s = > GetType ( s ) ) using System ; using System.Linq ; using System.Reflection ; namespace GetTypeTest { public class FindMe { } class Program { static void Main ( string [ ] args ) { var assemblyName = Assembly.GetExecutingAssembly ( ) .FullName ; var className = `` GetTypeTest.FindMe '' ; var classAndAssembly = string.Format ( `` { 0 } , { 1 } '' , className , assemblyName ) ; // 1 ) GetType succeeds when input is `` class , assembly '' , using method group var result = new [ ] { classAndAssembly } .Select ( Type.GetType ) .ToArray ( ) ; Console.WriteLine ( `` 1 ) Method group & class+assembly : { 0 } '' , result.First ( ) ) ; // 2 ) GetType fails when input is just the class name , using method group var result2 = new [ ] { className } .Select ( Type.GetType ) .ToArray ( ) ; Console.WriteLine ( `` 2 ) Method group & class name only : { 0 } '' , result2.First ( ) ) ; // 3 ) Identical to ( 2 ) except using lamba expression - this succeeds ... var result3 = new [ ] { className } .Select ( s = > Type.GetType ( s ) ) .ToArray ( ) ; Console.WriteLine ( `` 3 ) Lambda expression & class name only : { 0 } '' , result3.First ( ) ) ; // 4 ) Method group and core type class name var result4 = new [ ] { `` System.String '' } .Select ( Type.GetType ) .ToArray ( ) ; Console.WriteLine ( `` 4 ) Method group for System.String : { 0 } '' , result4.First ( ) ) ; Console.ReadLine ( ) ; } } }
|
Type.GetType fails when invoked as method group but not in lambda expression
|
C_sharp : I 'm trying to find a way to loop through all the controls of type 'Checkbox ' in a ASP Placeholder , and then do something with the control in the loop.Problem is I ca n't access the controls ... here is what I have so far ... But I 'm getting the error - `` Foreach can not operate on a method group '' .Any help would be greatly appreciated.Thanks . <code> string selections = `` '' ; foreach ( CheckBox ctrl in phProductLines.Controls.OfType < CheckBox > ) { selections += ctrl.Text + `` , `` ; }
|
Loop through Checkboxes in Placholder
|
C_sharp : public class Item { ... } Now , using LINQ I need to get all items that a customer bought . How can I ? I tried something like var items = from o in cust.Orders select o.Items ; but result is IEnuberable < List < Item > > and I wan na just one IEnumerable < Item > .I 'm asking here to try to avoid coding 2 loops . <code> public class Order { public List < Item > Items ... } public class Customer { public List < Order > Orders ... }
|
Get a IEnumerable < T > from a IEnumerable < IEnumerable < T > >
|
C_sharp : I have this C # method which I 'm trying to optimize : The function basically compares two int arrays . For each pair of matching elements , the method compares each individual byte value and takes the larger of the two . The element in the first array is then assigned a new int value constructed from the 4 largest byte values ( irrespective of source ) .I think I have optimized this method as much as possible in C # ( probably I have n't , of course - suggestions on that score are welcome as well ) . My question is , is it worth it for me to move this method to an unmanaged C DLL ? Would the resulting method execute faster ( and how much faster ) , taking into account the overhead of marshalling my managed int arrays so they can be passed to the method ? If doing this would get me , say , a 10 % speed improvement , then it would not be worth my time for sure . If it was 2 or 3 times faster , then I would probably have to do it.Note : please , no `` premature optimization '' comments , thanks in advance . This is simply `` optimization '' .Update : I realized that my code sample did n't capture everything I 'm trying to do in this function , so here is an updated version : Essentially this does the same thing as the first method , except in this one the second array ( src ) is always smaller than the first ( dest ) , and the second array is positioned fractionally relative to the first ( meaning that instead of being position at , say , 10 relative to dest , it can be positioned at 10.682791 ) .To achieve this , I have to interpolate between two bracketing values in the source ( say , 10 and 11 in the above example , for the first element ) and then compare the interpolated bytes with the destination bytes.I suspect here that the multiplication involved in this function is substantially more costly than the byte comparisons , so that part may be a red herring ( sorry ) . Also , even if the comparisons are still somewhat expensive relative to the multiplications , I still have the problem that this system can actually be multi-dimensional , meaning that instead of comparing 1-dimensional arrays , the arrays could be 2- , 5- or whatever-dimensional , so that eventually the time taken to calculate interpolated values would dwarf the time taken by the final bytewise comparison of 4 bytes ( I 'm assuming that 's the case ) .How expensive is the multiplication here relative to the bit-shifting , and is this the kind of operation that could be sped up by being offloaded to a C DLL ( or even an assembly DLL , although I 'd have to hire somebody to create that for me ) ? <code> // assume arrays are same dimensionsprivate void DoSomething ( int [ ] bigArray1 , int [ ] bigArray2 ) { int data1 ; byte A1 , B1 , C1 , D1 ; int data2 ; byte A2 , B2 , C2 , D2 ; for ( int i = 0 ; i < bigArray1.Length ; i++ ) { data1 = bigArray1 [ i ] ; data2 = bigArray2 [ i ] ; A1 = ( byte ) ( data1 > > 0 ) ; B1 = ( byte ) ( data1 > > 8 ) ; C1 = ( byte ) ( data1 > > 16 ) ; D1 = ( byte ) ( data1 > > 24 ) ; A2 = ( byte ) ( data2 > > 0 ) ; B2 = ( byte ) ( data2 > > 8 ) ; C2 = ( byte ) ( data2 > > 16 ) ; D2 = ( byte ) ( data2 > > 24 ) ; A1 = A1 > A2 ? A1 : A2 ; B1 = B1 > B2 ? B1 : B2 ; C1 = C1 > C2 ? C1 : C2 ; D1 = D1 > D2 ? D1 : D2 ; bigArray1 [ i ] = ( A1 < < 0 ) | ( B1 < < 8 ) | ( C1 < < 16 ) | ( D1 < < 24 ) ; } } private void DoSomethingElse ( int [ ] dest , int [ ] src , double pos , double srcMultiplier ) { int rdr ; byte destA , destB , destC , destD ; double rem = pos - Math.Floor ( pos ) ; double recipRem = 1.0 - rem ; byte srcA1 , srcA2 , srcB1 , srcB2 , srcC1 , srcC2 , srcD1 , srcD2 ; for ( int i = 0 ; i < src.Length ; i++ ) { // get destination values rdr = dest [ ( int ) pos + i ] ; destA = ( byte ) ( rdr > > 0 ) ; destB = ( byte ) ( rdr > > 8 ) ; destC = ( byte ) ( rdr > > 16 ) ; destD = ( byte ) ( rdr > > 24 ) ; // get bracketing source values rdr = src [ i ] ; srcA1 = ( byte ) ( rdr > > 0 ) ; srcB1 = ( byte ) ( rdr > > 8 ) ; srcC1 = ( byte ) ( rdr > > 16 ) ; srcD1 = ( byte ) ( rdr > > 24 ) ; rdr = src [ i + 1 ] ; srcA2 = ( byte ) ( rdr > > 0 ) ; srcB2 = ( byte ) ( rdr > > 8 ) ; srcC2 = ( byte ) ( rdr > > 16 ) ; srcD2 = ( byte ) ( rdr > > 24 ) ; // interpolate ( simple linear ) and multiply srcA1 = ( byte ) ( ( ( double ) srcA1 * recipRem ) + ( ( double ) srcA2 * rem ) * srcMultiplier ) ; srcB1 = ( byte ) ( ( ( double ) srcB1 * recipRem ) + ( ( double ) srcB2 * rem ) * srcMultiplier ) ; srcC1 = ( byte ) ( ( ( double ) srcC1 * recipRem ) + ( ( double ) srcC2 * rem ) * srcMultiplier ) ; srcD1 = ( byte ) ( ( ( double ) srcD1 * recipRem ) + ( ( double ) srcD2 * rem ) * srcMultiplier ) ; // bytewise best-of destA = srcA1 > destA ? srcA1 : destA ; destB = srcB1 > destB ? srcB1 : destB ; destC = srcC1 > destC ? srcC1 : destC ; destD = srcD1 > destD ? srcD1 : destD ; // convert bytes back to int dest [ i ] = ( destA < < 0 ) | ( destB < < 8 ) | ( destC < < 16 ) | ( destD < < 24 ) ; } }
|
Help with optimizing C # function via C and/or Assembly
|
C_sharp : So I 'm writing tests for our MVC4 application and I 'm testing Controller actions specifically . As I mention in the title , the test still hits the service ( WCF ) instead of returning test data . I have this controller : And it uses this DAO object : And this is my test using JustMock , the mock on GetForms ( ) returns some test data in a helper class : My problem is that when I run the test , the Service is still being called . I 've verified this using Fiddler as well as debugging the test and inspecting the value of `` result '' which is populated with our service 's test data.EDIT : I 've changed the test constructor to be a [ TestInitialize ] function , so the Test now looks like this : <code> public class FormController : Controller { public SurveyServiceClient Service { get ; set ; } public SurveyDao Dao { get ; set ; } public FormController ( SurveyServiceClient service = null , SurveyDao dao = null ) { this.Service = service ? ? new SurveyServiceClient ( ) ; this.Dao = dao ? ? new SurveyDao ( Service ) ; } // // GET : /Form/ public ActionResult Index ( ) { var formsList = new List < FormDataTransformContainer > ( ) ; Dao.GetForms ( ) .ForEach ( form = > formsList.Add ( form.ToContainer ( ) ) ) ; var model = new IndexViewModel ( ) { forms = formsList } ; return View ( `` Index '' , model ) ; } public class SurveyDao { private readonly SurveyServiceClient _service ; private readonly string _authKey ; public SurveyDao ( SurveyServiceClient serviceClient ) { _service = serviceClient ; } ... . public FormContract [ ] GetForms ( ) { var forms = _service.RetrieveAllForms ( ) ; return forms ; } [ TestClass ] public class FormControllerTest { private SurveyDao mockDao ; private SurveyServiceClient mockClient ; public FormControllerTest ( ) { mockClient = Mock.Create < SurveyServiceClient > ( ) ; mockDao = Mock.Create < SurveyDao > ( mockClient ) ; } [ TestMethod ] public void TestIndexAction ( ) { //Arrange var controller = new FormController ( mockClient , mockDao ) ; Mock.Arrange ( ( ) = > mockDao.GetForms ( ) ) .Returns ( TestHelpers.FormContractArrayHelper ) ; //Act var result = controller.Index ( ) as ViewResult ; //Assert Assert.IsInstanceOfType ( result.Model , typeof ( IndexViewModel ) ) ; } } [ TestClass ] public class FormControllerTest { private SurveyDao mockDao ; private SurveyServiceClient mockClient ; [ TestInitialize ] public void Initialize ( ) { mockClient = Mock.Create < SurveyServiceClient > ( ) ; mockDao = Mock.Create < SurveyDao > ( Behavior.Strict ) ; } [ TestMethod ] public void TestIndexAction ( ) { //Arrange var controller = new FormController ( mockClient , mockDao ) ; Mock.Arrange ( ( ) = > mockDao.GetForms ( ) ) .Returns ( TestHelpers.FormContractArrayHelper ) ; //Act var result = controller.Index ( ) as ViewResult ; //Assert Assert.IsInstanceOfType ( result.Model , typeof ( IndexViewModel ) ) ; } }
|
Mocked Object Still Making Calls to Service
|
C_sharp : I have an interface : I 'd like to configure Ninject ( v3 ) bindings so that I can have a `` dispatcher '' shuffle method calls out to multiple instances of IService , like so : However , my bindings , that look like this , wind up throwing an exception at runtime indicating a cyclic dependency : Is this possible ? If so , what am I doing wrong ? Can the ninja escape this cyclical dependency doom ? <code> public interface IService { void DoStuff ( int parm1 , string parm2 , Guid gimmeABreakItsAnExampleK ) ; } public sealed class DispatcherService : IService { private IEnumerable < IService > _children ; public DispatcherService ( IEnumerable < IService > children ) { this._children = children.ToList ( ) ; } public void DoStuff ( int parm1 , string parm2 , Guid gimmeABreakItsAnExampleK ) { foreach ( var child in this._children ) { child.DoStuff ( parm1 , parm2 , gimmeABreakItsAnExampleK ) ; } } } this.Bind < IService > ( ) .To < DispatcherService > ( ) ; this.Bind < IService > ( ) .To < SomeOtherService > ( ) .WhenInjectedExactlyInto < DispatcherService > ( ) ; this.Bind < IService > ( ) .To < YetAnotherService > ( ) .WhenInjectedExactlyInto < DispatcherService > ( ) ;
|
Ninject bindings for a dispatcher implementation of an interface
|
C_sharp : Could someone explain what this C # code is doing ? I know that CameraCaptureTask is a class and has a public method Show ( ) . What kind of event is this ? what is ( s , e ) ? <code> // launch the camera capture when the user touch the screenthis.MouseLeftButtonUp += ( s , e ) = > new CameraCaptureTask ( ) .Show ( ) ; // this static event is raised when a task completes its jobChooserListener.ChooserCompleted += ( s , e ) = > { //some code here } ;
|
What is this event ?
|
C_sharp : I am going through a LitJSON library . In the code there are lots of segments likeFor a method I know how overriding/overloading works but in the example above the code reads : int ICollection.CountI 'm not familiar with that format for a method signature . Is the coder trying to explicitly state its the ICollection.Count interface ? Could you explain what this is `` called '' ( is it overriding still ? ) . <code> public class JsonData : IJsonWrapper , IEquatable < JsonData > # region ICollection Properties int ICollection.Count { get { return Count ; } } # end region
|
What is it called when you edit an interface ?
|
C_sharp : In VS2012 's C # the following code : results in a printed to console output window . The spaces are separated by 0xFFFD yet it matches two consecutive spaces . Is that an expected result/feature or a ( known ) bug ? <code> string test = `` [ `` + ( char ) 0xFFFD + `` ] '' ; System.Console.WriteLine ( `` { 0 } '' , test.IndexOf ( `` `` ) == 1 ) ; True
|
IndexOf matching when Unicode 0xFFFD is in the string - bug or feature ?
|
C_sharp : I am currently trying to add an order by to a LINQ query that will order by a datetime field in an EF object : When the SortingDirection is set to desc it works fine . But when set to asc I get no records ! Upon looking at SQL Server Profiler , it turns out that DateTime objects are being formatted differently ! For DESC : and for ASC : Days and months have been swapped , causing the sql query to return no results . This to me suggests that the IQueryable.OrderBy ( ) method is not using the correct local format / different format to OrderByDescending ( ) , could this be a bug in EF ? Is there something in my connection string I could add to enforce this or another way I could sort by these dates ? My setup : .NET 4.5Entity Framework 5.0.0SQL Server 2012 Standard Many thanks <code> return this.SortingDirection.Equals ( `` asc '' , StringComparison.InvariantCultureIgnoreCase ) ? entities.OrderBy ( e = > e.ProcessStartTime ) : entities.OrderByDescending ( e = > e.ProcessStartTime ) ; ORDER BY [ Project1 ] . [ StartTime ] DESC ' , N ' ... @ p__linq__22='2015-01-07 09:00:23 ' , @ p__linq__23='2015-01-07 09:00:23 ' , @ p__linq__24='2015-01-07 09:05:30 ' , @ p__linq__25='2015-01-07 09:05:30 ' ORDER BY [ Project1 ] . [ StartTime ] ASC ' , N ' ... @ p__linq__22='2015-07-01 09:00:23 ' , @ p__linq__23='2015-07-01 09:00:23 ' , @ p__linq__24='2015-07-01 09:05:30 ' , @ p__linq__25='2015-07-01 09:05:30 '
|
Order by ( asc|desc ) in linq to SQL Server handles DateTime differently
|
C_sharp : I have an issue with ListBoxItems . I am trying to make all controls in the ListBoxItem select it as well , so clicking on a TextBox , Label , etc will select the ListBoxItem . Pretty simple so far . I am also changing the ListBoxItem Template to change the selection visualization from highlighting the background to just drawing a border . Also pretty simple . The combination of these two , however , seems to cause some really irritating issues with MouseDown and PreviewMouseDown , specifically in my case regarding Labels in a Grid , where one creates a `` void '' occupied by Grid space.Using snoop , I can see the PreviewMouseDown event stopping at the ScrollViewer inside the ListBox , and not going all the way to the ListBoxItem.XAML : Code-behind : However , if I remove the Template setter , all is well . Is there some magic in the template I 'm missing ? I tried renaming the border to `` Bd '' as that was what the default template border was named , but no luck . Any ideas ? <code> < Window x : Class= '' ListBoxClickThroughTest.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Width= '' 525 '' Height= '' 350 '' > < Grid > < ListBox ItemsSource= '' { Binding Items } '' SelectionMode= '' Single '' > < ListBox.ItemTemplate > < DataTemplate > < Grid > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' Auto '' / > < ColumnDefinition Width= '' * '' / > < /Grid.ColumnDefinitions > < Grid.RowDefinitions > < RowDefinition / > < RowDefinition / > < /Grid.RowDefinitions > < Label Name= '' VerySuperLongLabel '' Grid.Row= '' 0 '' Grid.Column= '' 0 '' HorizontalAlignment= '' Left '' Content= '' VerySuperLongLabel '' Padding= '' 0 '' / > < TextBox Name= '' Textbox1 '' Grid.Row= '' 0 '' Grid.Column= '' 1 '' HorizontalAlignment= '' Stretch '' HorizontalContentAlignment= '' Right '' Text= '' Textbox1 Text '' / > < Label Name= '' ShortLabel '' Grid.Row= '' 1 '' Grid.Column= '' 0 '' HorizontalAlignment= '' Left '' Content= '' ShortLabel '' Padding= '' 0 '' / > < TextBox Name= '' Textbox2 '' Grid.Row= '' 1 '' Grid.Column= '' 1 '' HorizontalAlignment= '' Stretch '' HorizontalContentAlignment= '' Right '' Text= '' Textbox2 Text '' / > < /Grid > < /DataTemplate > < /ListBox.ItemTemplate > < ListBox.ItemContainerStyle > < Style TargetType= '' { x : Type ListBoxItem } '' > < EventSetter Event= '' PreviewMouseDown '' Handler= '' ListBoxItem_PreviewMouseDown '' / > < EventSetter Event= '' MouseDown '' Handler= '' ListBoxItem_PreviewMouseDown '' / > < Setter Property= '' HorizontalContentAlignment '' Value= '' Stretch '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type ListBoxItem } '' > < Border x : Name= '' Bd '' BorderThickness= '' 1 '' > < ContentPresenter / > < /Border > < ControlTemplate.Triggers > < Trigger Property= '' IsSelected '' Value= '' true '' > < Setter TargetName= '' Bd '' Property= '' BorderBrush '' Value= '' Gray '' / > < /Trigger > < /ControlTemplate.Triggers > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > < /ListBox.ItemContainerStyle > < /ListBox > < /Grid > < /Window > using System.Collections.Generic ; using System.Windows ; using System.Windows.Controls ; using System.Windows.Input ; namespace ListBoxClickThroughTest { /// < summary > /// Interaction logic for MainWindow.xaml /// < /summary > public partial class MainWindow : Window { public MainWindow ( ) { Items = new List < string > ( ) { `` 1 '' , `` 2 '' } ; InitializeComponent ( ) ; DataContext = this ; } public List < string > Items { get ; set ; } private void ListBoxItem_PreviewMouseDown ( object sender , MouseButtonEventArgs e ) { var listBoxItem = ( ListBoxItem ) sender ; listBoxItem.IsSelected = true ; } } }
|
WPF ListBoxItem ControlTemplate breaks some MouseDown/Selection
|
C_sharp : I have an ASP.Net web page that currently works on the iOS4 but not on the iOS5 . On the parent web page I have a button that opens a child window . And I do a setTimeout refresh thing in the parent window right after the open window call.I noticed on the iPhone iOS5 that when it opens the child window , the setTimeout function in the parent page is not called until I go back to the parent window and then back to the child window to see the update . Here 's a snippet of my code in the parent page and where I think is the problemthis runs on iOS4 but not on iOS5 . Any ideas ? <code> WindowManager.OpenWindow ( ' ... ' ) t = setTimeout ( function ( ) { handles [ 0 ] .testfx ( ) ; } , 1000 ) ;
|
JavaScript setTimeout not firing after Window.Open
|
C_sharp : I am trying run a Datastore query to get a list of names and prices . However , I keep getting this error message : Can not implicitly convert type 'Google.Cloud.Datastore.V1.DatastoreQueryResults ' to 'System.Collections.Generic.List < TestApp.Models.AllSportsStore > 'This is the code I am using : AllSportsStore.cs PageAllSportsStore.cshtml pageThis is the image of the datastoreUpdated code result based on a comment <code> public DatastoreDb _db ; [ BindProperty ] public List < AllSportsStore > SportsStoreList { get ; set ; } public void OnGet ( ) { Environment.SetEnvironmentVariable ( `` GOOGLE_APPLICATION_CREDENTIALS '' , Path.Combine ( AppDomain.CurrentDomain.BaseDirectory , `` xxxxx.json '' ) ) ; _db = DatastoreDb.Create ( `` projectid '' ) ; Query query = new Query ( `` Sports_db '' ) ; IEnumerable < Entity > stores = _db.RunQuery ( query ) .Entities ; SportsStoreList = stores.Select ( _ = > new AllSportsStore { Name = _ [ `` Name '' ] .ToString ( ) , Price = _ [ `` Price '' ] .ToString ( ) , } ) .ToList ( ) ; } @ for ( var i = 0 ; i < Model.SportsStoreList.Count ; i++ ) { < tr > < td > @ Html.DisplayFor ( model = > model.SportsStoreList [ i ] .Name ) < /td > < td > @ Html.DisplayFor ( model = > model.SportsStoreList [ i ] .Price ) < /td > < /tr > }
|
Datastore Query Array
|
C_sharp : I 've got an app that has to do the following type of things , preferably on the GUI thread since that 's where most of the action is taking place and there 's no long-running ops : I realize I could use a timer with a state-machine style OnTick function , but that seems cumbersome : Plus I 'd like to be able to make it generic enough to do something likeIs there an idiomatic way to do this kind of thing ? Given all the TPL stuff , or Rx , or even the computation expressions in F # I 'd assume one exists , but I 'm not finding it . <code> Wait 1000FuncA ( ) Wait 2000FuncB ( ) Wait 1000FuncC ( ) int _state ; void OnTick ( object sender , EventArgs e ) { switch ( _state ) { case 0 : FuncA ( ) ; _timer.Interval = TimeSpan.FromSeconds ( 2 ) ; _state = 1 ; break ; case 1 : FuncB ( ) ; _timer.Interval = TimeSpan.FromSeconds ( 1 ) ; _state = 2 ; break ; case 2 : FuncC ( ) ; _timer.IsEnabled = false ; _state = 0 ; } } RunSequenceOnGuiThread ( new Sequence { { 1000 , FuncA } { 2000 , FuncB } { 1000 , FuncC } } ;
|
How does one kick off a timed sequence of events on the GUI thread in C # ?
|
C_sharp : I am using .Net Core 3.1 Framework in WPF Application . I have a button event in which I am trying to redirect to Instagram url on click . but its giving me the following error . Exception thrown : 'System.ComponentModel.Win32Exception ' in System.Diagnostics.Process.dll . <code> private void Insta_Click ( object sender , RoutedEventArgs e ) { try { string targetURL = `` https : //www.instagram.com/xyz/ '' ; Process.Start ( targetURL ) ; } catch { } }
|
.Net Core 3.1 Process.Start ( `` www.website.com '' ) not working in WPF
|
C_sharp : I 've been playing with RavenDB recently and there is something that is annoying me a little . I have an entity object with a series of value objects , e.g . There are a number of times when I want to pass an object of type Bar into a method/class but at some point want to reference back to the parent entity . In the world of NHibernate that 's really easy if I configure it with a 1..* relationship , e.g . However RavenDb does n't really like that which results in me having to create methods like : rather than Is there any way to achieve this with RavenDb ? I realise that RavenDb ( And document databases in general ) promote a different way of thinking about dealing with entities , if this is just a case of me being spending too long in the relational/normalised world could anyone explain how I should be structuring my code in a more document db way ? <code> class Foo { IList < Bar > Bars { get ; set ; } } class Bar { Foo Foo { get ; set ; } } void DoSomething ( Foo foo , Bar bar ) { Console.WriteLine ( foo ) ; Console.WriteLine ( bar ) ; } void DoSomething ( Bar bar ) { Console.WriteLine ( bar.Foo ) ; Console.WriteLine ( bar ) ; }
|
Reference a value objects parent entity object in RavenDb
|
C_sharp : Is it necessary to protect access to a single variable of a reference type in a multi-threaded application ? I currently lock that variable like this : But I 'm wondering if this is really necessary ? Is n't assignment of a value to a field atomic ? Can anything go wrong if I do n't lock in this case ? P.S . : MyType is an immutable class : all the fields are set in the constructor and do n't change . To change something , a new instance is created and assigned to the variable above . <code> private readonly object _lock = new object ( ) ; private MyType _value ; public MyType Value { get { lock ( _lock ) return _value ; } set { lock ( _lock ) _value = value ; } }
|
Is a lock necessary in this situation ?
|
C_sharp : I ran into a weird issue and I 'm wondering what I should do about it.I have this class that return a IEnumerable < MyClass > and it is a deferred execution . Right now , there are two possible consumers . One of them sorts the result.See the following example : Consumers call the deferred execution only once , but if they were to call it more than that , the result would be wrong as the culmulativeSum would n't be reset . I 've found the issue by inadvertence with unit testing.The easiest way for me to fix the issue would be to just add .ToArray ( ) and get rid of the deferred execution at the cost of a little bit of overhead.I could also add unit test in consumers class to ensure they call it only once , but that would n't prevent any new consumer coded in the future from this potential issue.Another thing that came to my mind was to make subsequent execution throw.Something likeObviously this does n't exist.Would it be a good idea to implement such thing and how would you do it ? Otherwise , if there is a big pink elephant that I do n't see , pointing it out will be appreciated . ( I feel there is one because this question is about a very basic scenario : | ) EDIT : Here is a bad consumer usage example : <code> public class SomeClass { public IEnumerable < MyClass > GetMyStuff ( Param givenParam ) { double culmulativeSum = 0 ; return myStuff.Where ( ... ) .OrderBy ( ... ) .TakeWhile ( o = > { bool returnValue = culmulativeSum < givenParam.Maximum ; culmulativeSum += o.SomeNumericValue ; return returnValue ; } ; } } return myStuff.Where ( ... ) .OrderBy ( ... ) .TakeWhile ( ... ) .ThrowIfExecutedMoreThan ( 1 ) ; public class ConsumerClass { public void WhatEverMethod ( ) { SomeClass some = new SomeClass ( ) ; var stuffs = some.GetMyStuff ( param ) ; var nb = stuffs.Count ( ) ; //first deferred execution var firstOne = stuff.First ( ) ; //second deferred execution with the culmulativeSum not reset } }
|
Ensure deferred execution will be executed only once or else
|
C_sharp : Should I worry about the order of Entity Framework linq query clauses in terms of performance ? In the example below could changing the order of the two where clauses have an performance impact on the DB lookup ? <code> using ( var context = new ModelContext ( ) ) { var fetchedImages = ( from images in context.Images.Include ( `` ImageSource '' ) where images.Type.Equals ( `` jpg '' ) where images.ImageSource.Id == 5 select images ) .ToArray ( ) ; }
|
Does the order of EF linq query clauses influence performance ?
|
C_sharp : Currently in my code I have a method like this : What Im trying to do is selecting the interface method using lambda expression and then get the name of method inside AddMethod . So the result would be : I have tried this : But the problem is some of the interface methods have input parameters which I 'm trying to ignore , as I just need the method name . Would be thankful if you help me with this . Alex <code> .AddMethod ( nameof ( IRoleService.GetRoles ) ) .AddMethod < IRoleService > ( x= > x.GetRoles ) AddMethod < T > ( Expression < Func < T , Action > > expression ) ;
|
Selecting a class method name using Lambda Expression
|
C_sharp : Suppose I have a method like so : Would this still dispose the 'ms ' object ? I 'm having doubts , maybe because something is returned before the statement block is finished.Thanks , AJ . <code> public byte [ ] GetThoseBytes ( ) { using ( System.IO.MemoryStream ms = new System.IO.MemoryStream ( ) ) { ms.WriteByte ( 1 ) ; ms.WriteByte ( 2 ) ; return ms.ToArray ( ) ; } }
|
.NET/C # - Disposing an object with the 'using ' statement
|
C_sharp : Why does conditional if in VB require not handle the direct cast of the conditions . For example in C # this is just fine ... But if I wanted the same thing in VB I would have to cast it I do n't understand why C # will do the transform and why VB does not . Should I be casting on my C # conditionals eg Also , Yes I am aware that IIF returns type object but I would assume that C # does as well as you can return more than just True|False ; it seems to me that C # handles the implicit conversion . <code> bool i = false ; i = ( 1 < 2 ) ? true : false ; int x = i ? 5:6 ; Dim i as Boolean = CBool ( IIF ( 1 < 2 , True , False ) ) Dim x as Integer = CInt ( IIF ( i , 5 , 6 ) ) bool i = Convert.ToBoolean ( ( 1 < 2 ) ? True : False ) ; int x = Convert.ToInt32 ( i ? 5:6 ) ;
|
Condition if differences in C # and VB
|
C_sharp : I have a system that compiles C # code at runtime . I would like the generated assemblies to be linked to the system itself . Here 's some example code that I am using : What I would like to do is also add a reference to the main compiler program as well , so the newly compiled extension can use library routines from the compiler program.So the question is this : How do I add a reference to entryasm in the compiled Assembly result ? <code> CSharpCodeProvider provider = new CSharpCodeProvider ( new Dictionary < String , String > { { `` CompilerVersion '' , `` v3.5 '' } } ) ; CompilerParameters compilerparams = new CompilerParameters ( ) ; compilerparams.GenerateExecutable = false ; compilerparams.GenerateInMemory = true ; foreach ( string name in linkedreferences ) compilerparams.ReferencedAssemblies.Add ( name + `` .dll '' ) ; Assembly result = provider.CompileAssemblyFromFile ( compilerparams , filename ) ; Assembly entryasm = Assembly.GetEntryAssembly ( ) ;
|
Compile C # code extension at runtime
|
C_sharp : What 's the best practice to check if a collection has items ? Here 's an example of what I have : The GetAllTerminals ( ) method will execute a stored procedure and , if we return a result , ( Any ( ) is true ) , SyncTerminals ( ) will loop through the elements ; thus enumerating it again and executing the stored procedure for the second time.What 's the best way to avoid this ? I 'd like a good solution that can be used in other cases too ; possibly without converting it to List.Thanks in advance . <code> var terminalsToSync = TerminalAction.GetAllTerminals ( ) ; if ( terminalsToSync.Any ( ) ) SyncTerminals ( terminalsToSync ) ; else GatewayLogAction.WriteLogInfo ( Messages.NoTerminalsForSync ) ;
|
How to properly check IEnumerable for existing results
|
C_sharp : I work with a codebase where several classes implement an indexer : When I stumble over code like foo [ 1,2 ] = 3 in visual Studio 2008 , I frequently want toright-click / `` go to definition '' , i.e . show the above definition in the visual studio editor window.For normal properties or methods this works without problems : foo.bar = 3 , right-click / `` go to definition '' takes me to the source code for foo.bar.For overloaded + or == this works as well.However with the indexer this does not seem to work . Is there any way to accomplish this ? ( I can not even search for the string `` this [ `` in the appropriate source file , since the same syntax may be used throughout the class to access the indexer . I always have to scroll trough all the methods and properties in the dropdown list for this file ) <code> public double this [ int i , int j ] { get { return ... ; } set { ... ; } }
|
How do I `` go to definition '' for the indexer ` this [ ] ` in Visual Studio
|
C_sharp : I have a piece of code that throws a NullReferenceException : It throws because dataSource is null . GetView returns a DataTable.However , when run on the one computer ( 64 bits ) , the program continues without any problems . The Exception does happen , because when I step , I end up completely somewhere else . The debugger does n't stop though.When run on another ( 32 bits ) it throws the exception and my debugger stops.My program is compiled for 32 bit . When I switch to `` Any CPU '' , the 64 bits computer does crash on the exception.Update I know how to fix my problem ( I in fact already have ) . All I want to know if this is is somehow known behaviour or something which can be caused by a number of reasons.The fix was 1 ) choose `` Any CPU '' ( which made the 64-bit machine crash ) and 2 ) check if dataSource is null before running this piece . <code> dataSource.DataSource = GetView ( ) ;
|
32 bit program on 64 bit computer does n't crash on NullReferenceException
|
C_sharp : I am trying to understand the below code trying to use reactive extensionsIf I enter SEARC in the input box , the output looks OnNext SE OnNext SEA OnNext SEAOnNext SEAROnNext SEAR OnNext SEAROnNext SEARCOnNext SEARC OnNext SEARC OnNext SEARCWhy is `` S '' not triggering an OnNext ? Why is OnCompleted never called ? Why is the OnNext called n-1 time on the nth character ? <code> IObservable < string > textChangedObservable = Observable.FromEventPattern < TextChangedEventArgs > ( searchScrip , `` TextChanged '' ) .Select ( evt = > ( ( TextBox ) sender ) .Text ) ; textChangedObservable.Subscribe ( OnNext , OnCompleted ) ; private void OnNext ( string s ) { System.Diagnostics.Debug.Print ( `` OnNext `` + s + `` \n '' ) ; } private void OnCompleted ( ) { System.Diagnostics.Debug.Print ( `` OnCompleted `` + `` \n '' ) ; }
|
Observable pattern on reactive extension
|
C_sharp : why is it , that in the following code , n does n't end up being 0 , it 's some random number with a magnitude less than 1000000 each time , somtimes even a negative number ? Does n't up.Join ( ) force both for loops to finish before WriteLine is called ? I understand that the local variable is actually part of a class behind the scenes ( think it 's called a closure ) , however because the local variable n is actually heap allocated , would that affect n not being 0 each time ? <code> static void Main ( string [ ] args ) { int n = 0 ; var up = new Thread ( ( ) = > { for ( int i = 0 ; i < 1000000 ; i++ ) { n++ ; } } ) ; up.Start ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { n -- ; } up.Join ( ) ; Console.WriteLine ( n ) ; Console.ReadLine ( ) ; }
|
Conflicting threads on a local variable
|
C_sharp : I have a system that is performing lots of calculations using decimals , occasionally it will add up the same numbers , but return different results , +/- 0.000000000000000000000000001Here is a short example : That outputs : The differences are so small that there is no practical effect , but has anyone seen something like this before ? I expected that when adding up the same numbers you would always get the same results . <code> decimal a = 2.016879990455473621256359079m ; decimal b = 0.8401819425625631128956517177m ; decimal c = 0.4507062854741283043456903406m ; decimal d = 6.7922317815078349615022988627m ; decimal result1 = a + b + c + d ; decimal result2 = a + d + c + b ; Console.WriteLine ( ( result1 == result2 ) ? `` Same '' : `` DIFFERENT '' ) ; Console.WriteLine ( result1 ) ; Console.WriteLine ( result2 ) ; DIFFERENT10.10000000000000000000000000010.100000000000000000000000001
|
Decimal order of addition affects results
|
C_sharp : I 'm trying to learn how to do Unit Testing and Mocking . I understand some of the principles of TDD and basic testing . However , I 'm looking at refactoring the below code that was written without tests and am trying to understand how it needs to change in order to make it testable . These two methods are in a single class . The database-related code in the GetAgentFromDatabase is related to Enterprise Libraries.How would I be able to go about making this testable ? Should I abstract out the GetAgentFromDatabase method into a different class ? Should GetAgentFromDatabase return something other than an IDataReader ? Any suggestions or pointers to external links would be greatly appreciated . <code> public class AgentRepository { public Agent Select ( int agentId ) { Agent tmp = null ; using ( IDataReader agentInformation = GetAgentFromDatabase ( agentId ) ) { if ( agentInformation.Read ( ) ) { tmp = new Agent ( ) ; tmp.AgentId = int.Parse ( agentInformation [ `` AgentId '' ] .ToString ( ) ) ; tmp.FirstName = agentInformation [ `` FirstName '' ] .ToString ( ) ; tmp.LastName = agentInformation [ `` LastName '' ] .ToString ( ) ; tmp.Address1 = agentInformation [ `` Address1 '' ] .ToString ( ) ; tmp.Address2 = agentInformation [ `` Address2 '' ] .ToString ( ) ; tmp.City = agentInformation [ `` City '' ] .ToString ( ) ; tmp.State = agentInformation [ `` State '' ] .ToString ( ) ; tmp.PostalCode = agentInformation [ `` PostalCode '' ] .ToString ( ) ; tmp.PhoneNumber = agentInformation [ `` PhoneNumber '' ] .ToString ( ) ; } } return tmp ; } private IDataReader GetAgentFromDatabase ( int agentId ) { SqlCommand cmd = new SqlCommand ( `` SelectAgentById '' ) ; cmd.CommandType = CommandType.StoredProcedure ; SqlDatabase sqlDb = new SqlDatabase ( `` MyConnectionString '' ) ; sqlDb.AddInParameter ( cmd , `` AgentId '' , DbType.Int32 , agentId ) ; return sqlDb.ExecuteReader ( cmd ) ; } }
|
How could I refactor this factory-type method and database call to be testable ?
|
C_sharp : Consider these two controller methods : Let 's say on the client side we do n't care about the response . We might wait for it to complete , we might abandon it half-way due user refreshing the page -- but it does n't matter that DoWithTaskRunAndReturnEarly returns earlier.Is there an important server-side difference between those two approaches , e.g . in reliability , timeouts , etc ? Does ASP.NET Core ever abort threads on a timeout ? <code> public async Task DoAsync ( ) { await TaskThatRunsFor10MinutesAsync ( ) .ConfigureAwait ( false ) ; } public void DoWithTaskRunAndReturnEarly ( ) { Task.Run ( ( ) = > TaskThatRunsFor10MinutesAsync ( ) ) ; }
|
What are possible issues if we await a long async operation in ASP.NET Core ?
|
C_sharp : I am using windows azure blob storage service . I want to protect my blobs from public access ( except my users ) .For this i used Shared Access Signature ( SAS ) and it works fine . But my issue is that i have a Container which contains blob in a directory structure , like : Now my requirement is that i want to give public access to all blobs in myContainer under directory2 but not to blobs which is under directory1 , i want to keep all the blobs under directory1 as private . How can i achieve this ? <code> https : //xxxxxxx.blob.core.windows.net/myContainer/directory1/blob1 https : //xxxxxxx.blob.core.windows.net/myContainer/directory1/blob2 https : //xxxxxxx.blob.core.windows.net/myContainer/directory1/blob3 https : //xxxxxxx.blob.core.windows.net/myContainer/directory1/blob4 https : //xxxxxxx.blob.core.windows.net/myContainer/directory1/blob5 https : //xxxxxxx.blob.core.windows.net/myContainer/directory2/blob1 https : //xxxxxxx.blob.core.windows.net/myContainer/directory2/blob2 https : //xxxxxxx.blob.core.windows.net/myContainer/directory2/blob3 https : //xxxxxxx.blob.core.windows.net/myContainer/directory2/blob4 https : //xxxxxxx.blob.core.windows.net/myContainer/directory2/blob5 and so on ...
|
How to secure azure blobs
|
C_sharp : Is there any automated way to verify that all commits in a Git repo are in a compilable state ? I need this to verify I have n't broken anything after rewriting history . Since I 'm rewriting history , this excludes a build server - a commit that worked at the time it was committed might be broken after rewriting history.For example I have a Visual Studio 2015 C # project , and I imagine some script like : I want it to run a build on each commit , and stop with an error message if the build process returns nonzero . <code> git filter-branch -- tree-filter msbuild
|
Verify that all Git commits of a C # project compile after rewriting history
|
C_sharp : System.ObjectDisposedException when the button style is set to FlatStyle.System in WinForms applicationI 've a child form which shows up on clicking a button in parent . And the code goes like below.The child form has in turn a button that closes itself.Steps to get exception : In debug mode , put a break point on Me.Close ( ) Then click close button of child . On hit of break point open notepad and Comeback to solution then continueException : Does anyone has any idea , this is explicitly coming when button style set to FlatStyle.System <code> Public Class Parent Private Sub Form1_Load ( sender As Object , e As EventArgs ) Handles MyBase.Load End Sub Private Sub btnOpenChild_Click ( sender As Object , e As EventArgs ) Handles btnOpenChild.Click Child.Show ( ) End SubEnd Class Public Class Child Private Sub btnCloseMe_Click ( sender As Object , e As EventArgs ) Handles btnCloseMe.Click Me.Close ( ) End SubEnd Class System.ObjectDisposedException was unhandled HResult=-2146232798 Message= Can not access a disposed object.Object name : 'Button ' . Source=System.Windows.Forms ObjectName=Button StackTrace : at System.Windows.Forms.Control.CreateHandle ( ) at System.Windows.Forms.Control.get_Handle ( ) at System.Windows.Forms.Control.PointToScreen ( Point p ) at System.Windows.Forms.Button.OnMouseUp ( MouseEventArgs mevent ) at System.Windows.Forms.Control.WmMouseUp ( Message & m , MouseButtons button , Int32 clicks ) at System.Windows.Forms.Control.WndProc ( Message & m ) at System.Windows.Forms.ButtonBase.WndProc ( Message & m ) at System.Windows.Forms.Button.WndProc ( Message & m ) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage ( Message & m ) at System.Windows.Forms.Control.ControlNativeWindow.WndProc ( Message & m ) at System.Windows.Forms.NativeWindow.DebuggableCallback ( IntPtr hWnd , Int32 msg , IntPtr wparam , IntPtr lparam ) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW ( MSG & msg ) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop ( IntPtr dwComponentID , Int32 reason , Int32 pvLoopData ) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner ( Int32 reason , ApplicationContext context ) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop ( Int32 reason , ApplicationContext context ) at System.Windows.Forms.Application.Run ( ApplicationContext context ) at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun ( ) at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel ( ) at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run ( String [ ] commandLine ) at WindowsApplication2.My.MyApplication.Main ( String [ ] Args ) in 17d14f5c-a337-4978-8281-53493378c1071.vb : line 81 at System.AppDomain._nExecuteAssembly ( RuntimeAssembly assembly , String [ ] args ) at System.AppDomain.ExecuteAssembly ( String assemblyFile , Evidence assemblySecurity , String [ ] args ) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ( ) at System.Threading.ThreadHelper.ThreadStart_Context ( Object state ) at System.Threading.ExecutionContext.RunInternal ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( ) InnerException :
|
System.ObjectDisposedException when the button style is set to FlatStyle.System in WinForms application
|
C_sharp : Searching Effort : Google : custom c # syntaxc # floating pointStackoverflow : custom c # syntaxc # floating pointAnd some more I do not remember ... Preconception : Every `` built-in type '' in c # ( such as int , float , charetc . ) is a class , and every class in C # inherits from the Object class . Therefore , every `` built-in type '' inherits from the Object class.With that preconception in mind , I would assume that to set a double variable , for example , I would need to set some properties using the `` normal '' syntax . Here is what I mean : But C # has a special , equivalent syntax for creating a double variable ( in a way that it would do what I tried to do above , not that the code above will actually work ) : The compiler understands that the floating point separates the number into two : 5 and 23.My question is if I can do the same with my own classes . For example , if I have my own Time class ( and it is just an example , so please do not suggest to use built-in time classes ) , I would want to have the option to instantiate it like so : And the compiler would understand that the colon separates the number into hours and minutes ( which are , I assume , properties I need to create in the Time class ) .I have heard about Roslyn CTP but I am looking for a simpler , built-in way , of doing what I have described.Can I do it ? <code> double number = new double ( ) ; number.leftSide= 5 ; number.rightSide = 23 ; Console.Write ( number ) ; // Output : // 5.23 double number = 5.23 ; Time time = 10:25 ;
|
How to create a custom syntax for describing an object in c # ?
|
C_sharp : I have tried to implement Read write operation using File IO operations and encapsulated those operations into TransformBlock so as to make these operation thread safe instead of using locking mechanism . But the problem is that when I try to write even 5 files parallely there is a memory out of exception and on using this implementation it is blocking UI thread . The implementation is done in Windows Phone project . Please suggest what is wrong in this implemantation.File IO OperationMainPage.xaml.cs UsageSave and Load data AsyncEdit : The reason that it is having memory exception is because of one reason that data string which i took is too huge . The string is link : http : //1drv.ms/1QWSAscBut the second problem is that if i add small data also then it is blocking UI thread . Is code doing any task on UI tread ? <code> public static readonly IsolatedStorageFile _isolatedStore = IsolatedStorageFile.GetUserStoreForApplication ( ) ; public static readonly FileIO _file = new FileIO ( ) ; public static readonly ConcurrentExclusiveSchedulerPair taskSchedulerPair = new ConcurrentExclusiveSchedulerPair ( ) ; public static readonly ExecutionDataflowBlockOptions exclusiveExecutionDataFlow = new ExecutionDataflowBlockOptions { TaskScheduler = taskSchedulerPair.ExclusiveScheduler , BoundedCapacity = 1 } ; public static readonly ExecutionDataflowBlockOptions concurrentExecutionDataFlow = new ExecutionDataflowBlockOptions { TaskScheduler = taskSchedulerPair.ConcurrentScheduler , BoundedCapacity = 1 } ; public static async Task < T > LoadAsync < T > ( string fileName ) { T result = default ( T ) ; var transBlock = new TransformBlock < string , T > ( async fName = > { return await LoadData < T > ( fName ) ; } , concurrentExecutionDataFlow ) ; transBlock.Post ( fileName ) ; result = await transBlock.ReceiveAsync ( ) ; return result ; } public static async Task SaveAsync < T > ( T obj , string fileName ) { var transBlock = new TransformBlock < Tuple < T , string > , Task > ( async tupleData = > { await SaveData ( tupleData.Item1 , tupleData.Item2 ) ; } , exclusiveExecutionDataFlow ) ; transBlock.Post ( new Tuple < T , string > ( obj , fileName ) ) ; await transBlock.ReceiveAsync ( ) ; } private static string data = `` vjdsskjfhkjsdhvnvndjfhjvkhdfjkgd '' private static string fileName = string.Empty ; private List < string > DataLstSample = new List < string > ( ) ; private ObservableCollection < string > TestResults = new ObservableCollection < string > ( ) ; private static string data1 = `` hjhkjhkhkjhjkhkhkjhkjhkhjkhjkh '' ; List < Task > allTsk = new List < Task > ( ) ; private Random rand = new Random ( ) ; private string fileNameRand { get { return rand.Next ( 100 ) .ToString ( ) ; } } public MainPage ( ) { InitializeComponent ( ) ; for ( int i = 0 ; i < 5 ; i ++ ) { DataLstSample.Add ( ( i % 2 ) == 0 ? data : data1 ) ; } } private void Button_Click ( object sender , RoutedEventArgs e ) { AppIsolatedStore_TestInMultiThread_LstResultShouldBeEqual ( ) ; } public async void AppIsolatedStore_TestInMultiThread_LstResultShouldBeEqual ( ) { TstRst.Text = `` InProgress.. '' ; allTsk.Clear ( ) ; foreach ( var data in DataLstSample ) { var fName = fileNameRand ; var t = Task.Run ( async ( ) = > { await AppIsolatedStore.SaveAsync < string > ( data , fName ) ; } ) ; TestResults.Add ( string.Format ( `` Writing file name : { 0 } , data : { 1 } '' , fName , data ) ) ; allTsk.Add ( t ) ; } await Task.WhenAll ( allTsk ) ; TstRst.Text = `` Completed.. '' ; } /// < summary > /// Load object from file /// < /summary > private static async Task < T > LoadData < T > ( string fileName ) { T result = default ( T ) ; try { if ( ! string.IsNullOrWhiteSpace ( fileName ) ) { using ( var file = new IsolatedStorageFileStream ( fileName , FileMode.OpenOrCreate , _isolatedStore ) ) { var data = await _file.ReadTextAsync ( file ) ; if ( ! string.IsNullOrWhiteSpace ( data ) ) { result = JsonConvert.DeserializeObject < T > ( data ) ; } } } } catch ( Exception ex ) { //todo : log the megatron exception in a file Debug.WriteLine ( `` AppIsolatedStore : LoadAsync : An error occured while loading data : { 0 } '' , ex.Message ) ; } finally { } return result ; } /// < summary > /// Save object from file /// < /summary > private static async Task SaveData < T > ( T obj , string fileName ) { try { if ( obj ! = null & & ! string.IsNullOrWhiteSpace ( fileName ) ) { //Serialize object with JSON or XML serializer string storageString = JsonConvert.SerializeObject ( obj ) ; if ( ! string.IsNullOrWhiteSpace ( storageString ) ) { //Write content to file await _file.WriteTextAsync ( new IsolatedStorageFileStream ( fileName , FileMode.Create , _isolatedStore ) , storageString ) ; } } } catch ( Exception ex ) { //todo : log the megatron exception in a file Debug.WriteLine ( `` AppIsolatedStore : SaveAsync : An error occured while saving the data : { 0 } '' , ex.Message ) ; } finally { } }
|
Memory issue in TPL Dataflow implementation of IO read write operation
|
C_sharp : I am new to WPF programming and not a professional in C # coding.So I have the following problem : I have a lot of different comboboxes and textboxes.I want to bind them to a variable in the background , because I want to fill the comboboxes with Data from a Database.So I created the following in the fileliste.xaml.cs : When I load liste.xaml it initializes the ctrlFilter Dictionary with the following code : So the filter class ( which is also in liste.xaml.cs ) looks like this : Now i dynamically load other xaml-files into the liste.xaml file . For example the Fahrzeug_Allgemein.xamlThere I have the comboboxes , which looks like this : You see that I tried to get the Items property from the Filter class , but it does n't work . In the Visual Studio 2015 output it says : I already read something about INotifyPropertyChanged but I do not know how to use it in my case.It would be cool , if you could help me.Thank you . <code> private Dictionary < string , Filter > _ctrlFilter ; public Dictionary < string , Filter > ctrlFilter { get { return _ctrlFilter ; } set { _ctrlFilter = value ; } } ctrlFilter = new Dictionary < string , Filter > { //ComboBox { `` hersteller '' , new Filter ( `` Hersteller '' , typeof ( ComboBox ) ) } , { `` fahrzeugart '' , new Filter ( `` Fahrzeugart '' , typeof ( ComboBox ) , false ) } , //TextBox { `` baujahr '' , new Filter ( `` Baujahr '' , typeof ( TextBox ) , true , typeof ( short ) ) } , { `` anschaffungswert '' , new Filter ( `` Anschaffungswert '' , typeof ( TextBox ) , true , typeof ( decimal ) ) } , { `` finanz_restwert '' , new Filter ( `` Restwert '' , typeof ( TextBox ) , true , typeof ( decimal ) ) } , //Others { `` zugelassen '' , new Filter ( `` Zugelassen '' , typeof ( DatePicker ) , true , typeof ( DateTime ) ) } , { `` vstabzug '' , new Filter ( `` Vorsteuerabzug '' , typeof ( CheckBox ) , true , typeof ( bool ) ) } , } ; public class Filter { public string FilterName ; public Type ControlType ; public Type FromToType ; public bool Load ; public ObservableCollection < object > Items ; public object SelectedFilter ; public object From ; public object To ; public Filter ( string name , Type type , bool load = true , Type ftType = null ) { Reset ( ) ; FilterName = name ; ControlType = type ; Load = load ; FromToType = ftType ; } public void Reset ( ) { From = null ; To = null ; SelectedFilter = null ; Items = new ObservableCollection < object > ( ) ; } } < StackPanel > < Label Content= '' Hersteller : '' Target= '' { Binding ElementName=cmb_hersteller , Mode=OneWay } '' / > < ComboBox x : Name= '' cmb_hersteller '' Fahrzeuge : FilterExtension.FilterName= '' hersteller '' Width= '' 120 '' ItemsSource= '' { Binding ctrlFilter [ hersteller ] .Items } '' SelectedIndex= '' 0 '' SelectionChanged= '' cmb_hersteller_SelectionChanged '' / > < /StackPanel > System.Windows.Data Error : 40 : BindingExpression path error : 'Items ' property not found on 'object ' `` Filter ' ( HashCode=44888241 ) ' . BindingExpression : Path=ctrlFilter [ hersteller ] .Items ; DataItem='liste ' ( Name= '' ) ; target element is 'ComboBox ' ( Name='cmb_hersteller ' ) ; target property is 'ItemsSource ' ( type 'IEnumerable ' )
|
WPF Binding to dictionary with classes
|
C_sharp : I have a block of code that attempts to query some simple configuration parameters from a database . However , using the code below , as soon as I enumerate the result I get the first value for each item in the result : If I print the results ( before attempting to add them to a new dictionary ) I get something like : But if I replace the select line with an anonymous type , it works just fine : With this anonymous type , I get the following result : I 've researched this for a few hours now to no avail and while I could just call it good with the anonymous type , this is really bothering me . I have seen plenty of examples that suggest my first block of code should work just fine . I 'm sure I 'm doing something silly , I just ca n't see it ! Any ideas ? The following are the full details of the model I am using starting with the DataContext implementation : The core contents table is represented by my ConfigurationContentsTable entity class : The two associated tables are pretty simple and only exist for normalization purposes . They are represented as follows : And finally : <code> var db = new ConfigurationServiceDataContext ( `` Server=vsdcs022.aridev.lcl ; Database=ConfigurationService ; Trusted_Connection=True ; '' ) ; var parameters = from configContents in db.ConfigurationContents where configContents.ConfigurationContextsTable.ConfigurationContextName == contextName & & configContents.ConfigurationSectionTable.ConfigurationSectionName == sectionName select configContents ; // print stuff for debugging purposes : foreach ( var parameter in parameters ) { Console.WriteLine ( `` key = ' { 0 } ' , value = ' { 1 } ' '' , parameter.ConfigurationKey , parameter.ConfigurationValue ) ; } return parameters.ToDictionary ( parameter = > parameter.ConfigurationKey , parameter = > parameter.ConfigurationValue ) ; key = 'key1 ' , value = 'value1'key = 'key1 ' , value = 'value1'key = 'key1 ' , value = 'value1 ' select new { configContents.ConfigurationKey , configContents.ConfigurationValue } ; key = 'key1 ' , value = 'value1'key = 'key2 ' , value = 'value2'key = 'key3 ' , value = 'value3 ' using System.Data.Linq ; using Ari.Core.ConfigurationService.LinqEntityClasses ; namespace Ari.Core.ConfigurationService { class ConfigurationServiceDataContext : DataContext { public Table < ConfigurationContentsTable > ConfigurationContents ; public Table < ConfigurationContextsTable > ConfigurationContexts ; public Table < ConfigurationSectionsTable > ConfigurationSections ; public ConfigurationServiceDataContext ( string connectionString ) : base ( connectionString ) { } } } using System.Data.Linq ; using System.Data.Linq.Mapping ; namespace Ari.Core.ConfigurationService.LinqEntityClasses { [ Table ( Name = `` ConfigurationContents '' ) ] class ConfigurationContentsTable { private long _configurationContextId ; private string _configurationKey ; private string _configurationValue ; private EntityRef < ConfigurationContextsTable > _configurationContextsTable ; private EntityRef < ConfigurationSectionsTable > _configurationSectionsTable ; public ConfigurationContentsTable ( ) { _configurationContextsTable = new EntityRef < ConfigurationContextsTable > ( ) ; _configurationSectionsTable = new EntityRef < ConfigurationSectionsTable > ( ) ; } [ Column ( Storage = `` _configurationContextId '' , DbType = `` BigInt NOT NULL IDENTITY '' , IsPrimaryKey = true , IsDbGenerated = true ) ] public long ConfigurationContextId { get { return _configurationContextId ; } } [ Column ( Storage = `` _configurationKey '' ) ] public string ConfigurationKey { get { return _configurationKey ; } set { _configurationKey = value ; } } [ Column ( Storage = `` _configurationValue '' ) ] public string ConfigurationValue { get { return _configurationValue ; } set { _configurationValue = value ; } } [ Association ( Storage = `` _configurationContextsTable '' , OtherKey = `` ConfigurationContextId '' ) ] public ConfigurationContextsTable ConfigurationContextsTable { get { return _configurationContextsTable.Entity ; } set { _configurationContextsTable.Entity = value ; } } [ Association ( Storage = `` _configurationSectionsTable '' , OtherKey = `` ConfigurationSectionId '' ) ] public ConfigurationSectionsTable ConfigurationSectionTable { get { return _configurationSectionsTable.Entity ; } set { _configurationSectionsTable.Entity = value ; } } } } using System.Data.Linq ; using System.Data.Linq.Mapping ; namespace Ari.Core.ConfigurationService.LinqEntityClasses { [ Table ( Name = `` ConfigurationContexts '' ) ] class ConfigurationContextsTable { private long _configurationContextId ; private string _configurationContextName ; private EntityRef < ConfigurationContentsTable > _configurationContentsTable ; public ConfigurationContextsTable ( ) { _configurationContentsTable = new EntityRef < ConfigurationContentsTable > ( ) ; } [ Column ( Storage = `` _configurationContextId '' , DbType = `` BigInt NOT NULL IDENTITY '' , IsPrimaryKey = true , IsDbGenerated = true ) ] public long ConfigurationContextId { get { return _configurationContextId ; } } [ Column ( Storage = `` _configurationContextName '' ) ] public string ConfigurationContextName { get { return _configurationContextName ; } set { _configurationContextName = value ; } } [ Association ( Storage = `` _configurationContentsTable '' , ThisKey = `` ConfigurationContextId '' ) ] public ConfigurationContentsTable ConfigurationContentsTable { get { return _configurationContentsTable.Entity ; } set { _configurationContentsTable.Entity = value ; } } } } using System.Data.Linq ; using System.Data.Linq.Mapping ; namespace Ari.Core.ConfigurationService.LinqEntityClasses { [ Table ( Name = `` ConfigurationSections '' ) ] class ConfigurationSectionsTable { private long _configurationSectionId ; private string _configurationSectionName ; private EntityRef < ConfigurationContentsTable > _configurationContentsTable ; public ConfigurationSectionsTable ( ) { _configurationContentsTable = new EntityRef < ConfigurationContentsTable > ( ) ; } [ Column ( Storage = `` _configurationSectionId '' , DbType = `` BigInt NOT NULL IDENTITY '' , IsPrimaryKey = true , IsDbGenerated = true ) ] public long ConfigurationSectionId { get { return _configurationSectionId ; } } [ Column ( Storage = `` _configurationSectionName '' ) ] public string ConfigurationSectionName { get { return _configurationSectionName ; } set { _configurationSectionName = value ; } } [ Association ( Storage = `` _configurationContentsTable '' , ThisKey = `` ConfigurationSectionId '' ) ] public ConfigurationContentsTable ConfigurationContentsTable { get { return _configurationContentsTable.Entity ; } set { _configurationContentsTable.Entity = value ; } } } }
|
Why does iterating over IQueryable give the first value for each item in the result ?
|
C_sharp : What is the default behavior of violating the Authorize attribute in ASP.NET Core ? It seems that it redirects to the /Account/AccessDenied if the user does n't have enough rights and /Account/Login if the user did n't login yet.Am I right ? I do n't see anything about it in the docs . <code> [ Authorize ( Roles = `` Administrator '' ) ] public ActionResult ShutDown ( ) { }
|
What is the default behavior of violating the Authorize attribute in ASP.NET Core
|
C_sharp : Update : This is no longer an issue from C # 6 , which has introduced the nameof operator to address such scenarios ( see MSDN ) . Note : Refer to “ Getting names of local variables ( and parameters ) at run-time through lambda expressions ” for a generalization of this question , as well as some answers.I like the idea of using lambda expressions to create refactor-safe implementations of the INotifyPropertyChanged interface , using code similar to that provided by Eric De Carufel . I ’ m experimenting with implementing something similar for providing the parameter name to an ArgumentException ( or its derived classes ) in a refactor-safe manner.I have defined the following utility method for performing null checks : Argument validation may then be performed in a refactor-safe manner using the following syntax : My concern lies in the following lines : A MemberExpression represents “ accessing a field or property ” . It is guaranteed to work correctly in the INotifyPropertyChanged case , since the lambda expression would be a property access . However , in my code above , the lambda expression is semantically a parameter access , not a field or property access . The only reason the code works is that the C # compiler promotes any local variables ( and parameters ) that are captured in anonymous functions to instance variables within a compiler-generated class behind the scenes . This is corroborated by Jon Skeet.My question is : Is this behaviour ( of promoting captured parameters to instance variables ) documented within the .NET specification , or is it just an implementation detail that may change in alternate implementations or future releases of the framework ? Specifically , may there be environments where parameterAccessExpression.Body is MemberExpression returns false ? <code> public static void CheckNotNull < T > ( Expression < Func < T > > parameterAccessExpression ) { Func < T > parameterAccess = parameterAccessExpression.Compile ( ) ; T parameterValue = parameterAccess ( ) ; CheckNotNull ( parameterValue , parameterAccessExpression ) ; } public static void CheckNotNull < T > ( T parameterValue , Expression < Func < T > > parameterAccessExpression ) { if ( parameterValue == null ) { Expression bodyExpression = parameterAccessExpression.Body ; MemberExpression memberExpression = bodyExpression as MemberExpression ; string parameterName = memberExpression.Member.Name ; throw new ArgumentNullException ( parameterName ) ; } } CheckNotNull ( ( ) = > arg ) ; // most conciseCheckNotNull ( arg , ( ) = > args ) ; // equivalent , but more efficient Expression bodyExpression = parameterAccessExpression.Body ; MemberExpression memberExpression = bodyExpression as MemberExpression ;
|
Lambda expressions for refactor-safe ArgumentException
|
C_sharp : Curious about the reputed performance gains in xobotos , I checked out the binary tree benchmark code.The Java version of the binary tree node is : The C # version is : I 'm wondering what the benefit of using a struct here is , since the Next and Previous pointers are still encapsulated in a class . Well , there is one - leaf nodes are pure value types since they do n't need left and right pointers . In a typical binary tree where half the nodes are leaves , that means a 50 % reduction in the number of objects . Still , the performance gains listed seem far greater.Question : Is there more to this ? Also , since I would n't have thought of defining tree nodes this way in C # ( thanks Xamarin ! ) what other data structures can benefit from using structs in a non-obvious way ? ( Even though that 's a bit off-topic and open ended . ) <code> private static class TreeNode { private TreeNode left , right ; private int item ; } struct TreeNode { class Next { public TreeNode left , right ; } private Next next ; private int item ; }
|
XobotOS : Why does the C # binary tree benchmark use a struct ?
|
C_sharp : First of all sorry for the long question , but I could n't write it any shorter : ) Real world example : we have large roll of paper , which contains small 'stickers ' printed on them . Each sticker has a code . First two letters of the code tells us what kind of a sticker this is ( sticker that represents new roll , sticker that represents end of current roll , sticker which should go to quality control , ... but most of them are normal enumerated stickers ) .For example sticker with the code XX0001 means , that after it there should be only normal enumerated codes ( like NN0001 to NN9999 ) , always the same number . Code QC0001 tells us , that next 10 codes ( from QC0001 to QC0010 ) should go to quality control.I designed the application so , that each type of a sticker is its own class - NormalSticker , BadSticker , ControllSticker , QualitySticker , ... They all inherit from a SticerBase class , which contains some common data for all of them ( quality of the scan , date and time of the scan , content of the code ) . Instances of these classes are created in a static Parser class , which checkes the code and returns appropriate object back to us.This all works OK , but now I got to a halt . I have also a Roll class , which has a set of Stickers , implemented as List < StickerBase > . This class has a public AddSticker ( StickerBase ) method , with which we add stickers to the roll . But this method should contain some logic , for example if we get the code XX001 , then next 9999 stickers should be from NN0001 to NN9999 . Only option I see here , is to make desicions based on the type of the sticker , like : I would be really surprised if this is the right approach . Any ideas ? Edit - possible solution : because for each sticker I know how the next one should look like , I can add new method public Sticker NextStickerShouldLookLike ( ) method to each Sticker class . In the validation logic ( similar to Péter Török 's answer ) I can just check if current sticker is the same as previousSticker.NextStickerShouldLookLike ( ) . The Validate method would have two input parameters - current and previous sticker . <code> public void AddSticker ( StickerBase sticker ) { if ( sticker.GetType ( ) .Equals ( typeof ( StickerNewRoll ) ) ) { // Next 9999 sticker should be in the form of NN0001 to NN9999 } if ( sticker.GetType ( ) .Equals ( typeof ( EnumeratedSticker ) ) ) { // Add 9999 stickers to the list , other business logic ... } if ( sticker.GetType ( ) .Equals ( typeof ( QualitySticker ) ) ) { // Stop the machine and notify the worker } }
|
Polymorphism design question
|
C_sharp : Here 's the deal . Have a functioning web app using ASP.NET WebForms with a C # backend . The thing works fine , but I 'm always looking to improve , as a beginner at this stuff . Right now , to deal with a user 's search coming back with no results , I utilize the following , and was wondering if there was any cleaner way to do it , for future reference : <code> DataClass data = new DataClass ( ) ; var searchresults = data.GetData ( searchBox.Text ) ; int datanumber = searchresults.Count ( ) ; if ( datanumber == 0 ) { ClientScript.RegisterStartupScript ( this.GetType ( ) , `` alert '' , `` javascript : alert ( 'There were no records found to match your search ' ) ; '' , true ) ; } else { DropDownList1.Visible = true ; DropDownList1.Items.Clear ( ) ; DropDownList1.DataSource = searchresults ; DropDownList1.DataBind ( ) ; }
|
Throwing a popup when search yields no results
|
C_sharp : Consider the following scenario.Document - > Section - > Body - > ItemsDocument has sections , a section contains a body . A body has some text and a list of items . The items is what the question is about . Sometimes the items is a basic list of string , but sometimes the items contain a list of a custom datatype . So : I can´t get this to work . The property Items has to be defined by a type in order to compile . I am stuck here . I can fix this easily by creating a Section class for each of the kind of sections I use . But the thing is that all the other code is the same and all the operations on the section will be the same . The only thing different is the type of list used in the Body.What is the best practice for this . I have tried generics , abstraction etc . I can make it work if creating the Items class directly from the calling program , but I can´t get it to work if Items is declared a property on another class.I can provide more details if needed . Thank you guys and girls for your support . <code> public class Document { public Section [ ] Sections { get ; set ; } } public class Section { public SectionType Type { get ; set ; } public Body { get ; set ; } } public class Body { //I want the items to be depending on the section type . //If e.g . the sectiontype is experience , I want the Items to be created with type //Experience . If sectiontype is default I want the Items to be created with type string public Items < T > Items { get ; set ; } } public class Items < T > : IEnumerable , IEnumerator { // Do all the plumbing for creating an enumerable collection } public class Experience { public string Prop1 { get ; set ; } public string Prop2 { get ; set ; } }
|
polymorphism , generics and anonymous types C #
|
C_sharp : I have created a Rectangle inside of a ScrollViewer like thisDuring the use of the app , the size of MusicBg changes , sometimes to something around 3,000 pixels width.However , while scrolling the scrollViewer , it allows me to scroll the rectangle all the way off the screen.For example this line of code gives me the following values when I have moved the rectangle as far as I want to move it.HorizontalOffset has a value of ~1200 and ScrollableWidth has a value of about ~2900.How can I get this to be done properly so that the rectangle is not scrolled completely off the screen ? I would expect a HorizontalOffset of about 1200 to only push the rectangle about halfway through to it 's destination , and not make it start going off screen.ANSWER : After much frustration , I was able to solve this problem by using Canvas instead of Border or Rectangle.I 'll award points if anyone can explain why this problem happened , and if there is a less processor intensive control that would work better than canvas.Edit : Screen shots : Bad Code : Image of bad scroll with bad code : Good working code : Good Scroll : Notice it says 170 seconds on the bottom right instead of the smaller number of 118 seconds in the bad scroll . <code> < ScrollViewer ManipulationMode= '' Control '' x : Name= '' songScrollViewer '' HorizontalScrollBarVisibility= '' Visible '' VerticalScrollBarVisibility= '' Disabled '' Height= '' 270 '' VerticalAlignment= '' Center '' Width= '' 728 '' Canvas.Top= '' 20 '' d : LayoutOverrides= '' HorizontalMargin '' > < Rectangle x : Name= '' musicBG '' Fill= '' # FF0692FD '' / > < /ScrollViewer > musicBG.Width = _songLength*PixelsPerSecond if ( songScrollViewer.HorizontalOffset > songScrollViewer.ScrollableWidth ) < ScrollViewer ManipulationMode= '' Control '' x : Name= '' songScrollViewer '' Width= '' 720 '' HorizontalScrollBarVisibility= '' Visible '' VerticalScrollBarVisibility= '' Disabled '' Height= '' 270 '' VerticalAlignment= '' Top '' Canvas.Top= '' 20 '' HorizontalAlignment= '' Left '' > < Border x : Name= '' musicBG '' Background= '' # FF0692FD '' VerticalAlignment= '' Top '' HorizontalAlignment= '' Left '' Height= '' 270 '' / > < /ScrollViewer > < ScrollViewer ManipulationMode= '' Control '' x : Name= '' songScrollViewer '' Width= '' 720 '' HorizontalScrollBarVisibility= '' Visible '' VerticalScrollBarVisibility= '' Disabled '' Height= '' 270 '' VerticalAlignment= '' Top '' Canvas.Top= '' 20 '' HorizontalAlignment= '' Left '' > < Canvas x : Name= '' musicBG '' Background = '' # FF0692FD '' Height= '' 270 '' > < Border Background= '' # FF0692FD '' VerticalAlignment= '' Top '' HorizontalAlignment= '' Left '' Height= '' 270 '' / > < /Canvas > < /ScrollViewer >
|
How do I get a ScrollViewer with a Rectangle inside to stop scrolling when it reaches the end of the rectangle ?
|
C_sharp : The following code demonstrates my question : The question is , why is there a difference for the compiler between casting the type inline to the extension method call and moving that cast out into a separate method ? <code> public class DynamicExample { public void DoSomething ( ) { var x = new ExpandoObject ( ) ; dynamic d = x ; d.GetString = ( Func < string > ) ( ( ) = > `` Some Value '' ) ; d.GetString ( ) .SomeStringExtension ( ) ; // Does n't work - expected ( ( string ) d.GetString ( ) ) .SomeStringExtension ( ) ; // Works - expected Build ( d ) .SomeStringExtension ( ) ; // Does n't work - unexpected ? } private static string Build ( dynamic d ) { return ( string ) d.GetString ( ) ; } } public static class StringExtensions { public static int SomeStringExtension ( this string s ) { return s.Length ; } }
|
Explicit cast of dynamic method return value within a method does n't allow an extension method to be called
|
C_sharp : So I 'm using a webclient to send some data from my C # application to my PHP script , which is located on a remote server . The problem that I 'm having is that the NameValueCollection I 'm using to store my data in works , But whenever my PHP script hits the object switch then it says that the type is invalid , this basically meanse that the switch goes to the default statement.This is the code from my C # application : ( Sorry for my bad code layout , this got a little messed up when I synced with github ) this is what my jobj parameter would look like : and this is a portion of my PHP script : This PHP script gets an empty POST and that 's why it goes directly to the else statement . The thing is that my application actually sends POST data , I have tested this with Fiddler , but the script says that $ _POST looks like this : `` array ( 0 ) { } '' The goal of my application : The goal of this API is that it will store its data to my database , which does not happen for some reason.What am I doing wrong ? Am I sending the data the wrong way ? can someone please tell me the right way of doing this ? Thanks in advance ! UPDATE : For those who know something about Fiddler . These are the results of my app activity : Send result : [ ! [ enter image description here ] [ 2 ] ] [ 2 ] As requested by CodeCaster , the data from the RAW tab in fiddler : <code> private static void send_it ( string jobj ) { // this is where I encode my JSON object to base_64 var b64bytes = System.Text.Encoding.UTF8.GetBytes ( json ) ; b64encode = System.Convert.ToBase64String ( b64bytes ) ; var data = new NameValueCollection ( ) ; // this is where I add the data data [ `` b64string '' ] = b64encode ; data [ `` filename '' ] = dt.bedrijfsNaam ; using ( WebClient client = new WebClient ( ) ) { var sendB64 = client.UploadValues ( `` http : //theurl/script.php '' , `` POST '' , data ) ; } } json = `` { \ '' type\ '' : \ '' '' + cat + `` \ '' , '' + `` \ '' bedrijfsNaam\ '' : \ '' '' + dt.bedrijfsNaam + `` \ '' , '' + `` \ '' omzet\ '' : \ '' '' + dt.Omzet + `` \ '' , '' + `` \ '' nieuweklanten1\ '' : \ '' '' + dt.NieuweKlanten + `` \ '' , '' + `` \ '' propsects\ '' : \ '' '' + dt.skProspects + `` \ '' , '' + `` \ '' hotprospects\ '' : \ '' '' + dt.skHotProspects + `` \ '' , '' + `` \ '' afsprakenmaken\ '' : \ '' '' + dt.afsMak + `` \ '' , '' + `` \ '' afspraken\ '' : \ '' '' + dt.afs + `` \ '' , '' + `` \ '' offertesmaken\ '' : \ '' '' + dt.offMak + `` \ '' , '' + `` \ '' gescoordeoffertes\ '' : \ '' '' + dt.gescOff + `` \ '' , '' + `` \ '' nieuweklanten2\ '' : \ '' '' + dt.newKlant + `` \ '' } '' ; if ( $ link - > connect_errno ) { echo 'ERROR : no connection ! ' ; } else { if ( isset ( $ _POST ) ) { $ obj = json_decode ( base64_decode ( $ _POST [ 'b64string ' ] ) ) ; $ cat = $ obj- > type ; switch ( $ obj- > type ) { case 'main ' : $ database = 'SalesKicker ' ; $ pre = 'INSERT INTO ' . $ database [ 'main ' ] . ' VALUES ' ; store_main_data ( $ pre ) ; break ; case 'second ' : $ database = 'SalesKicker ' ; $ pre = 'INSERT INTO ' . $ database [ 'second ' ] . ' VALUES ' ; store_sec_data ( $ pre ) ; break ; default : echo 'ERROR : Invalid Category ' break ; } print_r ( $ obj ) ; } else { echo 'ERROR : no data ! < br > The object returns : < br > ' ; vardump ( $ obj ) ; } } function store_sec_data ( $ pre ) { $ query_save = $ pre . `` ( ' '' . $ obj- > bedrijfsNaam . '' ' , ' '' . $ obj- > omzet . '' ' , ' '' . $ obj- > nieuweklanten1 . '' ' , ' '' . $ obj- > prospects . '' ' , ' '' . $ obj- > hotprospects . '' ' , ' '' . $ obj- > afsprakenmaken . '' ' , ' '' . $ obj- > afspraken . '' ' , ' '' . $ obj- > offertesmaken . '' ' , ' '' . $ obj- > gescoordeoffertes . '' ' , ' '' . $ obj- > nieuweklanten2 . `` ' ) '' ; save ( $ query_save ) ; } function save ( $ query ) { mysqli_query ( $ link , $ query ) or die ( mysqli_error ( $ query ) ) ; } The $ _POSTArray ( [ b64string ] = > eyJ0eXBlIjoibWFpbiIsImJlZHJpamZzTmFhbSI6IlRFU1QiLCJDb250UGVycyI6IlRFU1QiLCJUZWxOdW0iOiIxMzM3IiwiZW1haWwiOiJURVNUIiwiTGFuZCI6IlRFU1QiLCJQbGFhdHMiOiJURVNUIiwiUG9zdENvZGUiOiJURVNUIn0= ) The $ _REQUESTArray ( [ b64string ] = > eyJ0eXBlIjoibWFpbiIsImJlZHJpamZzTmFhbSI6IlRFU1QiLCJDb250UGVycyI6IlRFU1QiLCJUZWxOdW0iOiIxMzM3IiwiZW1haWwiOiJURVNUIiwiTGFuZCI6IlRFU1QiLCJQbGFhdHMiOiJURVNUIiwiUG9zdENvZGUiOiJURVNUIn0= ) The $ obj stdClass Object ( [ type ] = > main [ bedrijfsNaam ] = > TEST [ ContPers ] = > TEST [ TelNum ] = > 1337 [ email ] = > TEST [ Land ] = > TEST [ Plaats ] = > TEST [ PostCode ] = > TEST ) string ( 89 ) `` INSERT INTO SalesKicker ( BedrijfsNaam , ContPers , TelNr , Email , Land , Plaats , POC ) VALUES `` string ( 146 ) `` INSERT INTO SalesKicker ( BedrijfsNaam , ContPers , TelNr , Email , Land , Plaats , POC ) VALUES ( 'TEST ' , 'TEST ' , '1337 ' , 'TEST ' , 'TEST ' , 'TEST ' , 'TEST ' ) ''
|
PHP not processing data from C # webclient correctly
|
C_sharp : Consider the TranslateAllCoords static function : Then , later in code , you have : But , by calling TranslateAllCoords you are in effect modifying value types ( i.e. , the integer coords ) and generally values types should be immutable . Are some rules broken here or is this a perfectly valid construct that gets around the `` value types should be immutable '' construct by modifying only built in value types ? <code> static class CoordinateTransformation { public static void TranslateAllCoords ( ref int x , ref int y , ref int z , int amount ) { x+=amount ; y+=amount ; z+=amount ; } } int x=0 , y=0 , z=0 ; ... CoordinateTransformation.TranslateAllCoords ( ref x , ref y , ref z , 5 ) ; ...
|
Mutability of value types
|
C_sharp : So , I 've written a small and , from what I initially thought , easy method in C # .This static method is meant to be used as a simple password suggestion generator , and the code looks like this : I call this function like this : Now , this method almost always return random strings like `` AAAAAA '' , `` BBBBBB '' , `` 888888 '' etc.. , where I thought it should return strings like `` A8JK2A '' , `` 82mOK7 '' etc.However , and here is the wierd part ; If I place a breakpoint , and step through this iteration line by line , I get the correct type of password in return . In 100 % of the other cases , when Im not debugging , it gives me crap like `` AAAAAA '' , `` 666666 '' , etc..How is this possible ? Any suggestion is greatly appreciated ! : - ) BTW , my system : Visual Studio 2010 , C # 4.0 , ASP.NET MVC 3 RTM project w/ ASP.NET Development Server . Have n't tested this code in any other environments . <code> public static string CreateRandomPassword ( int outputLength , string source = `` '' ) { var output = string.Empty ; for ( var i = 0 ; i < outputLength ; i++ ) { var randomObj = new Random ( ) ; output += source.Substring ( randomObj.Next ( source.Length ) , 1 ) ; } return output ; } var randomPassword = StringHelper.CreateRandomPassword ( 5 , `` ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 '' ) ;
|
My static C # function is playing games with me ... totaly weird !
|
C_sharp : I understand that AspNetCore 2.1 is still in release candidate form and that new testing model with Microsoft.AspNetCore.Mvc.Testing is not stabilized.But I 'm trying to follow examples and use WebApplicationTestFixture class for testing . Here is code I have so far : However , I ca n't find WebApplicationTestFixture class in package anywhere . Is it located in additional assembly ? Or I 'm supposed to create this class ? <code> public class UnitTest1 : IClassFixture < WebApplicationTestFixture < Startup > > { public UnitTest1 ( WebApplicationTestFixture < Startup > fixture ) { Client = fixture.CreateClient ( ) ; } public HttpClient Client { get ; } [ Fact ] public async void Test1 ( ) { var response = await Client.GetAsync ( `` api/values '' ) ; response.EnsureSuccessStatusCode ( ) ; } }
|
AspNetCore testing with TestHost , WebApplicationTestFixture class not found
|
C_sharp : I 've noticed that when using Contains in EFThe generated SQL looks like this Since the values are not parameterized , is n't it possible to inject some SQL ? <code> .Where ( i = > myListOfStrings.Contains ( i.Value ) ) IN ( 'Value1 ' , 'Value2 ' )
|
Possible SQL Injection when using contains with EF ?
|
C_sharp : During reflection , is it possible in C # to check whether one constructor calls another ? I would like to determine for each ConstructorInfo whether or not it 's at the end of chain of invocation . <code> class Test { public Test ( ) : this ( false ) { } public Test ( bool inner ) { } }
|
Check whether a constructor calls another constructor
|
C_sharp : I used SHA1 for hashing passwords on my site . I 'm trying to move to ASP.NET Identity . I found how I can verify the old passwords ( ASP.NET Identity default Password Hasher , how does it work and is it secure ? ) : In my custom ApplicationUserManager , I set the PasswordHasher property : Now , I would like delete the old hash ( sha1 ) and save the new hash.How I can do it ? Thanks in advance ! <code> public class CustomPasswordHasher : IPasswordHasher { // ... . public static bool VerifyHashedPassword ( string hashedPassword , string password ) { byte [ ] buffer4 ; if ( hashedPassword == null ) { return false ; } if ( password == null ) { throw new ArgumentNullException ( `` password '' ) ; } // Old hash verification using ( SHA1Managed sha1 = new SHA1Managed ( ) ) { var hash = sha1.ComputeHash ( Encoding.UTF8.GetBytes ( password ) ) ; var sb = new StringBuilder ( hash.Length * 2 ) ; foreach ( byte b in hash ) { sb.Append ( b.ToString ( `` x2 '' ) ) ; } if ( hashedPassword == sb.ToString ( ) ) return true ; else return false ; } // Identity hash verification byte [ ] src = Convert.FromBase64String ( hashedPassword ) ; if ( ( src.Length ! = 0x31 ) || ( src [ 0 ] ! = 0 ) ) { return false ; } byte [ ] dst = new byte [ 0x10 ] ; Buffer.BlockCopy ( src , 1 , dst , 0 , 0x10 ) ; byte [ ] buffer3 = new byte [ 0x20 ] ; Buffer.BlockCopy ( src , 0x11 , buffer3 , 0 , 0x20 ) ; using ( Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes ( password , dst , 0x3e8 ) ) { buffer4 = bytes.GetBytes ( 0x20 ) ; } return ByteArraysEqual ( buffer3 , buffer4 ) ; } // ... . } // ... .manager.PasswordHasher = new CustomPasswordHasher ( ) ; // ... .
|
How can I rewrite password hash made by SHA1 ( in ASP.NET Identity ) ?
|
C_sharp : From a long time i am trying to generate graph like this Codes i tried.Please help which chart type i should use or i am making any mistake . AAfter changing chart type , it works perfectly fine but its not working for last row text . As shown in image below . <code> Excel.Range chartRange1 ; Excel.ChartObjects xlCharts1 = ( Excel.ChartObjects ) worksheet.ChartObjects ( Type.Missing ) ; Excel.ChartObject myChart1 = ( Excel.ChartObject ) xlCharts1.Add ( 350 , 500 , 500 , 350 ) ; Excel.Chart chartPage1 = myChart1.Chart ; chartRange1 = worksheet.get_Range ( `` A33 '' , `` b56 '' ) ; chartPage1.SetSourceData ( chartRange1 , Type.Missing ) ; chartPage1.ChartType = Excel.XlChartType.xlBarStacked ; Excel.Range xValues = worksheet.Range [ `` B33 '' , `` B56 '' ] ; Excel.Range values = worksheet.Range [ `` a33 '' , `` a56 '' ] ; Excel.SeriesCollection seriesCollection = ( Excel.SeriesCollection ) chartPage1.SeriesCollection ( ) ; Excel.Series series1 = seriesCollection.NewSeries ( ) ; series1.XValues = xValues ; series1.Values = values ;
|
Excel Chart Type vertical value
|
C_sharp : I have following program to add the values.When I am comenting Add method call in main method and looking into ILDASM.EXE Maxstack size is 2 . And after uncommenting maxstack size becomes 4.Why in the case of Main method all variables are not going into stack as stack size remains 2 only , While in case of Add method call every variable goes into stack ? Is this the case that inside main method calculation is happening one by one so that it takes only two variable at a time.Please clear my confusion . <code> static void Main ( string [ ] args ) { int x = 2 ; int y = 3 ; int a = 4 ; int b = 5 ; int c = 6 ; Console.WriteLine ( x + y + a + b + c ) ; Console.WriteLine ( Add ( 10 , 20 , 30 , 40 ) ) ; Console.ReadLine ( ) ; } static int Add ( int x , int y , int z , int a ) { return x + y + z + a ; }
|
Calculation of maxstack value in IL code
|
C_sharp : I 'm trying to create a request with IP address SAN . This is the function that is responsible for creating the CAlternativeName : The problem is that I 'm getting the next error : What am I doing wrong ? <code> public static CAlternativeNameClass GetCurrentIpName ( ) { //get current machine IP address IPAddress ip = GetCurrentIp ( ) ; if ( ip == null ) { return null ; } try { CAlternativeNameClass nameClass = new CAlternativeNameClass ( ) ; nameClass.InitializeFromString ( AlternativeNameType.XCN_CERT_ALT_NAME_IP_ADDRESS , ip.ToString ( ) ) ; return nameClass ; } catch ( Exception e ) { Console.WriteLine ( e ) ; return null ; } } System.ArgumentException : Value does not fall within the expected range . at CERTENROLLLib.CAlternativeNameClass.InitializeFromString ( AlternativeNameType Type , String strValue )
|
Create a Computer Request Including IP address Subject Alternative Name
|
C_sharp : https : //msdn.microsoft.com/en-us/magazine/jj883956.aspx Consider the polling loop pattern : In this case , the .NET 4.5 JIT compiler might rewrite the loop like this : In the single-threaded case , this transformation is entirely legal and , in general , hoisting a read out of a loop is an excellent optimization . However , if the _flag is set to false on another thread , the optimization can cause a hang . Note that if the _flag field were volatile , the JIT compiler would not hoist the read out of the loop . ( See the “ Polling Loop ” section in the December article for a more detailed explanation of this pattern . ) Will the JIT compiler still optimize the code as shown above if I lock _flag or will only making it volatile stop the optimization ? Eric Lippert has the following to say about volatile : Frankly , I discourage you from ever making a volatile field . Volatile fields are a sign that you are doing something downright crazy : you 're attempting to read and write the same value on two different threads without putting a lock in place . Locks guarantee that memory read or modified inside the lock is observed to be consistent , locks guarantee that only one thread accesses a given chunk of memory at a time , and so on . The number of situations in which a lock is too slow is very small , and the probability that you are going to get the code wrong because you do n't understand the exact memory model is very large . I do n't attempt to write any low-lock code except for the most trivial usages of Interlocked operations . I leave the usage of `` volatile '' to real experts.To summarize : Who ensures that the optimization mentioned above does n't destroy my code ? Only volatile ? Also the lock statement ? Or something else ? As Eric Lippert discourages you from using volatile there must be something else ? Downvoters : I appreciate every feedback to the question . Especially if you downvoted it I 'd like to hear why you think this is a bad question.A bool variable is not a thread synchronization primitive : The question is meant as a generell question . When will the compiler not do the optimizion ? Dupilcate : This question is explicitly about optimizations . The one you linked does n't mention optimizations . <code> private bool _flag = true ; public void Run ( ) { // Set _flag to false on another thread new Thread ( ( ) = > { _flag = false ; } ) .Start ( ) ; // Poll the _flag field until it is set to false while ( _flag ) ; // The loop might never terminate ! } if ( _flag ) { while ( true ) ; }
|
.NET JIT compiler volatile optimizations
|
C_sharp : Consider the following code : Assuming I 'm calling MyMethod ( `` mystring '' ) from different threads concurrently.Would it be possible for more than one thread ( we 'll just take it as two ) enter the if ( ! list.Contains ( a ) ) statement in the same time ( with a few CPU cycles differences ) , both threads get evaluated as false and one thread enters the critical region while another gets locked outside , so the second thread enters and add `` mystring '' to the list again after the first thread exits , resulting in the dictionary trying to add a duplicate key ? <code> Dictionary < string , string > list = new Dictionary < string , string > ( ) ; object lockObj = new object ( ) ; public void MyMethod ( string a ) { if ( list.Contains ( a ) ) return ; lock ( lockObj ) { list.Add ( a , '' someothervalue '' ) ; } }
|
C # Is this method thread safe ?
|
C_sharp : I am using a pre-built third party class library ( think .NET Framework ... ) that contains a class Foo with the following members : Foo does not contain a public _state setter.In a specific scenario , I want to set the state of a Foo object to the object itself . This will NOT compile : Given the above prerequisites , is there any way that I can set the state of a Foo object to the object itself ? Rationale The Timer class in Windows 8.1 does not contain the Timer ( AsyncCallback ) constructor which assigned the state of the Timer object with the object itself . I am trying to port .NET code that contains this Timer constructor to a Windows 8.1 class library , so my concern is How do I pass the object itself to its state member ? This issue is further outlined here , but I thought it would be more efficient to also pose the principal question above . <code> public sealed class Foo { private object _state ; public Foo ( object state ) { _state = state ; } } Foo f ; f = new Foo ( f ) ; // Compilation error : Use of unassigned local variable ' f '
|
Can I set the state of an object to the object itself in the constructor call ?
|
C_sharp : What are the implications or unperceived consequences of throwing an exception inside of a delegate that is used during an unmanaged callback ? Here is my situation : Unmanaged C : Managed C # : <code> int return_callback_val ( int ( *callback ) ( void ) ) { return callback ( ) ; } [ DllImport ( `` MyDll.dll '' ) ] static extern int return_callback_val ( IntPtr callback ) ; [ UnmanagedFunctionPointer ( CallingConvention.Cdecl ) ] delegate int CallbackDelegate ( ) ; int Callback ( ) { throw new Exception ( ) ; } void Main ( ) { CallbackDelegate delegate = new CallbackDelegate ( Callback ) ; IntPtr callback = Marshal.GetFunctionPointerForDelegate ( delegate ) ; int returnedVal = return_callback_val ( callback ) ; }
|
Implications of throwing exception in delegate of unmanaged callback
|
C_sharp : I have four consumer when error occured message publishing to default EasyNetQ_Default_Error_Queue is it possible to each queue consumer write own error exchangeFor example ; <code> Queue Name : A ErrorExchange : A_ErrorExchangeQueue Name : B ErrorExchange : B_ErrorExchange bus.Advanced.Conventions.ErrorExchangeNamingConvention = new ErrorExchangeNameConvention ( info = > `` A_DeadLetter '' ) ; bus.Advanced.Conventions.ErrorExchangeNamingConvention = new ErrorExchangeNameConvention ( info2 = > `` B_DeadLetter '' ) ;
|
How to declare custom error exchange for each consumer in EasyNetQ ?
|
C_sharp : Today , when I write a piece of code like this : I suddenly realize that thestatement is so much like a function declaration . And I vaguely remembered that the exception handling involves some kind of stack walking/manipulation.So , what exactly is the above exception handling code compiled into ? I have the feeling that the above code is just a special/convenient syntax to ease our coding , but in fact , maybe our code is wrapped into an auto-generated exception handling function ? I hope I made myself clear . <code> try { ... } catch ( Exception e ) { ... } catch ( Exception e ) { ... }
|
The internal implementation of exception handling
|
C_sharp : I am trying to create a .NET Object from a JObject but I am getting all properties of the Object as defaults ( null for string , 0 for int etc . ) I am creating a simple Jobject : The car class is : The deserialization is here : But the result in run time is default values : Run time pictureI would like to know why it is happening and how should I do it properly , Thanks <code> var jsonObject = new JObject ( ) ; jsonObject.Add ( `` type '' , `` Fiat '' ) ; jsonObject.Add ( `` model '' , 500 ) ; jsonObject.Add ( `` color '' , `` white '' ) ; public class Car { string type { get ; set ; } int model { get ; set ; } string color { get ; set ; } } Car myCar = jsonObject.ToObject < Car > ( ) ;
|
Deserialize Json using ToObject method results in default properties values
|
C_sharp : I am trying to export an excel and make it password protected . My code is given below.But i am getting error : Excel completed file level validation and repair . Some parts of this workbook may have been repaired or discarded.I DO N'T KNOW WHAT I AM DOING WRONG .In-case i do it without the save As line for package then this error does n't appear.In my controller : <code> [ HttpGet ] public FileStreamResult ExportToExcel ( ) { _objService = new ServiceBAL ( ) ; List < ReconcilationEntity > Objmodel = new List < ReconcilationEntity > ( ) ; Objmodel = _objService.GetCreditsudharLeads ( ) ; String URL = string.Empty ; if ( ! Directory.Exists ( Server.MapPath ( `` ~/TempExcel '' ) ) ) { System.IO.Directory.CreateDirectory ( Server.MapPath ( `` ~/TempExcel '' ) ) ; } String Filepath = Server.MapPath ( `` ~/TempExcel '' ) ; string date = DateTime.Now.ToShortDateString ( ) .Replace ( `` / '' , `` _ '' ) + `` _ '' + DateTime.Now.ToShortTimeString ( ) .Replace ( `` `` , `` _ '' ) .Replace ( `` : '' , `` _ '' ) .Trim ( ) ; String FileName = `` Creditsudhar_ '' + date + `` .xlsx '' ; Filepath = Filepath + `` \\ '' + FileName ; string [ ] columns = { `` AffName '' , `` AffPhone '' , `` AffEmail '' , `` ProductName '' , `` ContactName '' , `` Status '' , `` CreatedOn '' , `` Commission '' , `` IsCommissionPaid '' , `` Accountname '' , `` AccountNumber '' , `` BankName '' , `` BankBranch '' , `` IFSCCode '' , `` PanNumber '' } ; var file = ExcelExportHelper.ExportExcel ( ExcelExportHelper.ListToDataTable ( Objmodel ) , Filepath , `` Creditsudhar Reconcillation Sheet `` + DateTime.Now.ToShortDateString ( ) , true , columns ) ; var memStream = new MemoryStream ( file ) ; return this.File ( memStream , `` application/vnd.openxmlformats-officedocument.spreadsheetml.sheet '' , FileName ) ; } public static string ExcelContentType { get { return `` application/vnd.openxmlformats-officedocument.spreadsheetml.sheet '' ; } } public static DataTable ListToDataTable < T > ( List < T > data ) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties ( typeof ( T ) ) ; DataTable dataTable = new DataTable ( ) ; for ( int i = 0 ; i < properties.Count ; i++ ) { PropertyDescriptor property = properties [ i ] ; dataTable.Columns.Add ( property.Name , Nullable.GetUnderlyingType ( property.PropertyType ) ? ? property.PropertyType ) ; } object [ ] values = new object [ properties.Count ] ; foreach ( T item in data ) { for ( int i = 0 ; i < values.Length ; i++ ) { values [ i ] = properties [ i ] .GetValue ( item ) ; } dataTable.Rows.Add ( values ) ; } return dataTable ; } public static byte [ ] ExportExcel ( DataTable dataTable , String Filepath , string heading = `` '' , bool showSrNo = false , params string [ ] columnsToTake ) { string fullPath = string.Empty ; byte [ ] ret ; DeleteUploadedFile ( Filepath ) ; String result = String.Empty ; using ( ExcelPackage package = new ExcelPackage ( ) ) { ExcelWorksheet workSheet = package.Workbook.Worksheets.Add ( String.Format ( `` { 0 } Data '' , heading ) ) ; int startRowFrom = String.IsNullOrEmpty ( heading ) ? 1 : 3 ; if ( showSrNo ) { DataColumn dataColumn = dataTable.Columns.Add ( `` # '' , typeof ( int ) ) ; dataColumn.SetOrdinal ( 0 ) ; int index = 1 ; foreach ( DataRow item in dataTable.Rows ) { item [ 0 ] = index ; index++ ; } } // add the content into the Excel file workSheet.Cells [ `` A '' + startRowFrom ] .LoadFromDataTable ( dataTable , true ) ; // autofit width of cells with small content int columnIndex = 1 ; foreach ( DataColumn column in dataTable.Columns ) { try { ExcelRange columnCells = workSheet.Cells [ workSheet.Dimension.Start.Row , columnIndex , workSheet.Dimension.End.Row , columnIndex ] ; int maxLength = columnCells.Max ( cell = > cell.Value.ToString ( ) .Count ( ) ) ; if ( maxLength < 150 ) { workSheet.Column ( columnIndex ) .AutoFit ( ) ; } columnIndex++ ; } catch ( Exception ex ) { if ( ! ( ex is System.Threading.ThreadAbortException ) ) { //Log other errors here } } } // format header - bold , yellow on black using ( ExcelRange r = workSheet.Cells [ startRowFrom , 1 , startRowFrom , dataTable.Columns.Count ] ) { r.Style.Font.Color.SetColor ( System.Drawing.Color.White ) ; r.Style.Font.Bold = true ; r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid ; r.Style.Fill.BackgroundColor.SetColor ( System.Drawing.ColorTranslator.FromHtml ( `` # 1fb5ad '' ) ) ; } // format cells - add borders using ( ExcelRange r = workSheet.Cells [ startRowFrom + 1 , 1 , startRowFrom + dataTable.Rows.Count , dataTable.Columns.Count ] ) { r.Style.Border.Top.Style = ExcelBorderStyle.Thin ; r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin ; r.Style.Border.Left.Style = ExcelBorderStyle.Thin ; r.Style.Border.Right.Style = ExcelBorderStyle.Thin ; r.Style.Border.Top.Color.SetColor ( System.Drawing.Color.Black ) ; r.Style.Border.Bottom.Color.SetColor ( System.Drawing.Color.Black ) ; r.Style.Border.Left.Color.SetColor ( System.Drawing.Color.Black ) ; r.Style.Border.Right.Color.SetColor ( System.Drawing.Color.Black ) ; } // removed ignored columns for ( int i = dataTable.Columns.Count - 1 ; i > = 0 ; i -- ) { if ( i == 0 & & showSrNo ) { continue ; } if ( ! columnsToTake.Contains ( dataTable.Columns [ i ] .ColumnName ) ) { workSheet.DeleteColumn ( i + 1 ) ; } } if ( ! String.IsNullOrEmpty ( heading ) ) { workSheet.Cells [ `` A1 '' ] .Value = heading ; workSheet.Cells [ `` A1 '' ] .Style.Font.Size = 20 ; workSheet.InsertColumn ( 1 , 1 ) ; workSheet.InsertRow ( 1 , 1 ) ; workSheet.Column ( 1 ) .Width = 5 ; } System.IO.FileInfo fileinfo2 = new System.IO.FileInfo ( Filepath ) ; DeleteUploadedFile ( Filepath ) ; workSheet.Protection.SetPassword ( `` myPassword '' ) ; workSheet.Protection.IsProtected = true ; workSheet.Protection.AllowSelectUnlockedCells = false ; workSheet.Protection.AllowSelectLockedCells = false ; package.SaveAs ( fileinfo2 , `` myPassword '' ) ; ret = package.GetAsByteArray ( ) ; return ret ; } } public static void DeleteUploadedFile ( String filePath ) { try { if ( System.IO.File.Exists ( filePath ) ) { System.IO.File.Delete ( filePath ) ; } } catch ( Exception ex ) { } } public static byte [ ] ExportExcel < T > ( List < T > data , String Filepath , string Heading = `` '' , bool showSlno = false , params string [ ] ColumnsToTake ) { return ExportExcel ( ListToDataTable < T > ( data ) , Filepath , Heading , showSlno , ColumnsToTake ) ; }
|
I am trying to export an excel and make it password protected . My code is given below.But i am getting error
|
C_sharp : Can optimizations done by the C # compiler or the JITter have visible side effects ? One example I 've though off.When calling A ( x ) x is guaranteed to be kept alive to the end of A - because B uses the same parameter . But if B is defined asThen the B ( x ) can be eliminated by the optimizer and then a GC.KeepAlive ( x ) call might be necessary instead.Can this optimization actually be done by the JITter ? Are there other optimizations that might have visible side effects , except stack trace changes ? <code> var x = new Something ( ) ; A ( x ) ; B ( x ) ; public void B ( Something x ) { }
|
C # optimizations and side effects
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.