text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : I was experimenting with the const modifier while exploring a plethora of C # tutorials , and placed a bunch of const modifiers in a class like this without actually using them anywhere : With this class , I get the following warning ( using csc ) : ConstTesting.cs ( 3,19 ) : warning CS0414 : The field ‘ ConstTesting.somedecimal ’ is assigned but its value is never usedWhat I do n't understand is that I only get the warning for the const decimal . The const int does n't give me any warning , regardless of the order or anything like that . My question is , why does this happen ? Why would my csc compiler be warning me about a const in the first place , and if it is then more importantly why would it only be warning me about const decimal when I 'm writing const int in exactly the same way ? What on earth would the difference between int and decimal have to do with it ? Please note : - I do not have ReSharper - I am using VS 2010 - I am 100 % certain neither ` const ` is being used anywhere in my code . <code> class ConstTesting { const decimal somedecimal = 1 ; const int someint = 2 ; ... } | Confusing warning about a constant decimal field in C # |
C_sharp : Could Someone help me to clarify the difference between : I get the same results in both cases without knowing the difference .Does the Eager Loading require using Include ? <code> var query = awlt.People.Include ( p = > p.EmailAddresses ) .Where ( p = > p.LastName.Equals ( lastName ) ) .SelectMany ( a = > a.EmailAddresses ) .Select ( a = > a.EmailAddress1 ) ; var query = awlt.People .Where ( p = > p.LastName.Equals ( lastName ) ) .SelectMany ( a = > a.EmailAddresses ) .Select ( a = > a.EmailAddress1 ) ; | Using include does n't change the behavior |
C_sharp : I 've been doing some code refactoring in my C # projects.I got a Resharper code analysis warning : `` Redundant string interpolation '' This happens in following scenario : I 've read string interpolation is rewritten to string.Format at compile time . Then I tried following : This time I get : Redundant string.Format call.My question is : Except the code cleanness , is the run-time performance affected by these redundant calls or the performance is the same for : <code> void someFunction ( string param ) { ... } someFunction ( $ '' some string '' ) ; someFunction ( string.Format ( `` some string '' ) ) ; someFunction ( $ '' some string '' ) someFunction ( `` some string '' ) someFunction ( string.Format ( `` some string '' ) ) | Redundant string interpolation and performance |
C_sharp : I wrote a test program wherein a single Button is defined in XAML as the content of a Window . Upon the window 's loading , the Button is programmatically replaced as the window 's content , and the field referring to it is also replaced , both by another Button which I created programmatically . I thereafter track both Button objects using weak references , and poll at 1/10th second intervals the IsAlive property of each . Before the first check of IsAlive in the first call to the polling method , I wipe out rooting references to the programmatically-defined Button as well.The expectation in running this code would be that , despite nondeterminism in the timing of C # garbage collection , both Button objects would eventually be reported as garbage collected . Although the programmatically-defined Button shows this behavior , typically within a 1/2 minute , the XAML Button is never collected . I 've left the program running for more than ten minutes seeing this behavior.Can anyone tell me why the XAML Button object is n't collected ? In particular , I 'd like to know where the garbage collection-blocking reference is , whether it is in my code or it is in the WPF implementation . Perhaps it 's in a XAML loading object . Am I looking at some sort of memory leak ? The program described above is included below for reference.MainWindow.xaml : MainWindow.xaml.cs : App.xaml : <code> < Window x : Class= '' Test.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Width= '' 300 '' Height= '' 150 '' Loaded= '' Window_Loaded '' > < Button Name= '' btn '' / > < /Window > namespace Test { public partial class MainWindow : System.Windows.Window { private System.WeakReference wr_xamlBtn , wr_programmaticBtn ; public MainWindow ( ) { InitializeComponent ( ) ; } private void Window_Loaded ( object sender , System.Windows.RoutedEventArgs e ) { // Immediately upon the window 's loading , create a weak reference to the // button % btn defined in XAML . wr_xamlBtn = new System.WeakReference ( btn ) ; // Replace references in % btn and this.Content to the XAML button with // references to a programmatically-defined button . This would be // expected to free the XAML button for garbage collection . btn = new System.Windows.Controls.Button ( ) ; Content = btn ; // Create a weak reference to the programmatically-defined button , so that // when ( strong ) references to it are removed , it will be eligible for // garbage collection . wr_programmaticBtn = new System.WeakReference ( btn ) ; // Provides a polling mechanism to see whether either the XAML button or // the programmatically-defined button has been collected . var dt = new System.Windows.Threading.DispatcherTimer ( ) ; dt.Tick += Poll ; dt.Interval = System.TimeSpan.FromMilliseconds ( 100 ) ; dt.Start ( ) ; } void Poll ( object sender , System.EventArgs e ) { // If the programmatically-defined button has n't had its references // removed yet , this does so . This makes it eligible for garbage // collection . if ( btn ! = null ) Content = btn = null ; // Uses the console to show a timestamp and the state of collection of the // XAML button and the programmatically-defined button . System.Console.WriteLine ( string.Format ( `` XAML button { 0 } , Programmatically-defined button { 1 } @ { 2 } '' , wr_xamlBtn.IsAlive ? `` Alive '' : `` Collected '' , wr_programmaticBtn.IsAlive ? `` Alive '' : `` Collected '' , System.DateTimeOffset.Now ) ) ; } } } < Application x : Class= '' Test.App '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' StartupUri= '' MainWindow.xaml '' / > | XAML Button not garbage collected after eliminating references |
C_sharp : If you have a Form that displays data , one thing you can do is reference this.DesignMode in the constructor to avoid populating it in the designer : However , if you decide to re-write that form as a UserControl , keeping the same constructor logic , something unexpected happens - this.DesignMode is always false no matter what . This leads to the designer invoking your logic that 's meant to happen at runtime.I just found a comment on a blog post that seem to give a fix to this but it references functionality of the LicenseManager class as a replacement that works as expected in a UserControl.So for a UserControl I can do : Does using the LicenseManager instead of DesignMode have any caveats or implications that might dissuade me from putting in my production code ? <code> public partial class SetupForm : Form { private SetupItemContainer container = new SetupItemContainer ( ) ; public SetupForm ( ) { InitializeComponent ( ) ; if ( ! this.DesignMode ) { this.bindingSource1.DataSource = this.container ; this.Fill ( ) ; } } } public partial class AffiliateSetup : UserControl { private AffiliateItemContainer container = new AffiliateItemContainer ( ) ; public AffiliateSetup ( ) { InitializeComponent ( ) ; if ( LicenseManager.UsageMode == LicenseUsageMode.Runtime ) { this.bindingSource1.DataSource = this.container ; this.Fill ( ) ; } } } | Are there any caveats to swapping out DesignMode for LicenseManager.UsageMode in a WinForms UserControl constructor ? |
C_sharp : Here is what I would like to do : Is such a construction possible in .NET ? Edit : The question was not clear enough . Here is what I want to do , expanded : Meaning , I want the constrained type to : - accept a single generic parameter - implement a given single generic parameter interface.Is that possible ? In fact , I will be happy with only the first thing . <code> public interface IRepository < TSet < TElement > > where TSet < TElement > : IEnumerable < TElement > { TSet < TEntity > GetSet < TEntity > ( ) ; } public class DbRepository : IRepository < DbSet < TElement > > { DbSet < TEntity > GetSet < TEntity > ( ) ; } public class ObjectRepository : IRepository < ObjectSet < TElement > > { ObjectSet < TEntity > GetSet < TEntity > ( ) ; } public interface IRepository < TGeneric < TElement > > { TGeneric < TArgument > GetThing < TArgument > ( ) ; } | Can one specify on a generic type constraint that it must implement a generic type ? |
C_sharp : I may not have it correct , but I saw something like this above a WebMethod : I saw a vb version first and I used a converter to convert it to c # . I have never seen it before . It 's in a vb 6 asmx file . <code> [ return : ( XmlElement ( `` Class2 '' ) , IsNullable = false ) ] public Class2 MEthod1 ( ) { } | What does this syntax mean in c # ? |
C_sharp : I 'm using the Winforms WebBrowser control to collect the links of video clips from the site linked below.LINKBut , when I scroll element by element , I can not find the < video > tag.Soon after using theI already return 0Do I need to call any ajax ? <code> void webBrowser_DocumentCompleted_2 ( object sender , WebBrowserDocumentCompletedEventArgs e ) { try { HtmlElementCollection pTags = browser.Document.GetElementsByTagName ( `` video '' ) ; int i = 1 ; foreach ( HtmlElement link in links ) { if ( link.Children [ 0 ] .GetAttribute ( `` className '' ) == `` vjs-poster '' ) { try { i++ ; } catch ( Exception ex ) { MessageBox.Show ( ex.Message ) ; } } } } // Added by edit } HtmlElementCollection pTags = browser.Document.GetElementsByTagName ( `` video '' ) ; | How to get an HtmlElement value inside Frames/IFrames ? |
C_sharp : I 've just rebuilt my machine with a fresh install of Visual Studio 2015 . I 've also installed the extensions for Web Essentials and Web Compiler but these seem to have caused a problemSay for example , prior to installing Web Essentials and Web Compiler , if I was editing a Razor view , if the current element was formatted a couple of tabs in , and I pressed enter , the cursor would automatically tab to the correct place.Working Example : Non Working Example : This as I 'm sure you can understand is quite annoying ! I 'm pretty sure it 's something to do with Web Essentials or Web Compiler because this was n't a problem before-hand . In addition to this , I am getting the following error on startup : And this appears to be the culprit in ActivityLog.xmlERROREditor or Editor Extension System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation . -- - > System.ArgumentException : Item has already been added . Key in dictionary : 'RazorSupportedRuntimeVersion ' Key being added : 'RazorSupportedRuntimeVersion ' at System.Collections.Hashtable.Insert ( Object key , Object nvalue , Boolean add ) at System.Collections.Hashtable.Add ( Object key , Object value ) at System.Collections.Specialized.HybridDictionary.Add ( Object key , Object value ) at Microsoft.VisualStudio.Utilities.PropertyCollection.AddProperty ( Object key , Object property ) at Microsoft.VisualStudio.Html.Package.Razor.RazorVersionDetector.Microsoft.Html.Editor.ContainedLanguage.Razor.Def.IRazorVersionDetector.GetVersion ( ITextBuffer textBuffer ) at Microsoft.Html.Editor.ContainedLanguage.Razor.RazorUtility.TryGetRazorVersion ( ITextBuffer textBuffer , Version & razorVersion ) at Microsoft.Html.Editor.ContainedLanguage.Razor.RazorErrorTagger..ctor ( ITextBuffer textBuffer ) -- - End of inner exception stack trace -- - at System.RuntimeMethodHandle.InvokeMethod ( Object target , Object [ ] arguments , Signature sig , Boolean constructor ) at System.Reflection.RuntimeConstructorInfo.Invoke ( BindingFlags invokeAttr , Binder binder , Object [ ] parameters , CultureInfo culture ) at System.RuntimeType.CreateInstanceImpl ( BindingFlags bindingAttr , Binder binder , Object [ ] args , CultureInfo culture , Object [ ] activationAttributes , StackCrawlMark & stackMark ) at System.Activator.CreateInstance ( Type type , BindingFlags bindingAttr , Binder binder , Object [ ] args , CultureInfo culture , Object [ ] activationAttributes ) at System.Activator.CreateInstance ( Type type , Object [ ] args ) at Microsoft.Html.Editor.ContainedLanguage.Common.ContainedCodeErrorTaggerProvider1.CreateTagger [ T ] ( ITextBuffer textBuffer ) at Microsoft.VisualStudio.Text.Tagging.Implementation.TagAggregator1.GatherTaggers ( ITextBuffer textBuffer ) <code> < ul > < li > < ! -- press enter here -- > | < ! -- would put cursor here -- > < /li > < /ul > < ul > < li > < ! -- press enter here -- > | < ! -- put 's cursor here -- > < /li > < /ul > | Razor editor formatting not working after installing Web Essentials and Web Compiler |
C_sharp : I have a List < Fruit > , and the list above contains 30 Fruit objects of two types : Apple and Orange . 20 apples and 10 oranges.How can I get a list of 10 random fruits ( from the basket of 30 fruits ) , but there should be 3 oranges and 7 apples ? <code> public class Fruit { public string Name { get ; set ; } public string Type { get ; set ; } } List < Fruit > fruits = new List < Fruit > ( ) ; fruits.Add ( new Fruit ( ) { Name = `` Red Delicious '' , Type = `` Apple '' } ) ; fruits.Add ( new Fruit ( ) { Name = `` Granny Smith '' , Type = `` Apple '' } ) ; fruits.Add ( new Fruit ( ) { Name = `` Sour Granny '' , Type = `` Orange '' } ) ; fruits.Add ( new Fruit ( ) { Name = `` Delicious Yummy '' , Type = `` Orange '' } ) ; ... .. | Get random items with fixed length of different types |
C_sharp : Here is a simple C # .NET Core 3.1 program that calls System.Numerics.Vector2.Normalize ( ) in a loop ( with identical input every call ) and prints out the resulting normalized vector : And here is the output of running that program on my computer ( truncated for brevity ) : So my question is , why does the result of calling Vector2.Normalize ( v ) change from < 0.9750545 , -0.22196561 > to < 0.97505456 , -0.22196563 > after calling it 34 times ? Is this expected , or is this a bug in the language/runtime ? <code> using System ; using System.Numerics ; using System.Threading ; namespace NormalizeTest { class Program { static void Main ( ) { Vector2 v = new Vector2 ( 9.856331f , -2.2437377f ) ; for ( int i = 0 ; ; i++ ) { Test ( v , i ) ; Thread.Sleep ( 100 ) ; } } static void Test ( Vector2 v , int i ) { v = Vector2.Normalize ( v ) ; Console.WriteLine ( $ '' { i:0000 } : { v } '' ) ; } } } 0000 : < 0.9750545 , -0.22196561 > 0001 : < 0.9750545 , -0.22196561 > 0002 : < 0.9750545 , -0.22196561 > ... 0031 : < 0.9750545 , -0.22196561 > 0032 : < 0.9750545 , -0.22196561 > 0033 : < 0.9750545 , -0.22196561 > 0034 : < 0.97505456 , -0.22196563 > 0035 : < 0.97505456 , -0.22196563 > 0036 : < 0.97505456 , -0.22196563 > ... | Why does the result of Vector2.Normalize ( ) change after calling it 34 times with identical inputs ? |
C_sharp : I 'm looking into solutions to convert a string into executeable code . My code is extremely slow and executes at 4.7 seconds . Is there any faster way of doing this ? String : `` 5 * 5 '' Output : 25The code : <code> class Program { static void Main ( string [ ] args ) { var value = `` 5 * 5 '' ; Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; var test = Execute ( value ) ; sw.Stop ( ) ; Debug.WriteLine ( $ '' Execute string at : { sw.Elapsed } '' ) ; } private static object Execute ( string content ) { var codeProvider = new CSharpCodeProvider ( ) ; var compilerParameters = new CompilerParameters { GenerateExecutable = false , GenerateInMemory = true } ; compilerParameters.ReferencedAssemblies.Add ( `` system.dll '' ) ; string sourceCode = CreateExecuteMethodTemplate ( content ) ; CompilerResults compilerResults = codeProvider.CompileAssemblyFromSource ( compilerParameters , sourceCode ) ; Assembly assembly = compilerResults.CompiledAssembly ; Type type = assembly.GetType ( `` Lab.Cal '' ) ; MethodInfo methodInfo = type.GetMethod ( `` Execute '' ) ; return methodInfo.Invoke ( null , null ) ; } private static string CreateExecuteMethodTemplate ( string content ) { var builder = new StringBuilder ( ) ; builder.Append ( `` using System ; '' ) ; builder.Append ( `` \r\nnamespace Lab '' ) ; builder.Append ( `` \r\n { `` ) ; builder.Append ( `` \r\npublic sealed class Cal '' ) ; builder.Append ( `` \r\n { `` ) ; builder.Append ( `` \r\npublic static object Execute ( ) '' ) ; builder.Append ( `` \r\n { `` ) ; builder.AppendFormat ( `` \r\nreturn { 0 } ; '' , content ) ; builder.Append ( `` \r\n } '' ) ; builder.Append ( `` \r\n } '' ) ; builder.Append ( `` \r\n } '' ) ; return builder.ToString ( ) ; } } | Convert string to executable code performance |
C_sharp : One of my fellow developer has a code similar to the following snippetHere the Data class properties fetch the information from DB dynamically . When there is a need to save the Data to a file the developer creates an instance and fills the property using self assignment . Then finally calls a save . I tried arguing that the usage of property is not correct . But he is not convinced . This are his pointsThere are nearly 20 such properties.Fetching all the information is not required except for saving.Instead of self assignment writing an utility method to fetch all will have same duplicate code in the properties.Is this usage correct ? <code> class Data { public string Prop1 { get { // return the value stored in the database via a query } set { // Save the data to local variable } } public void SaveData ( ) { // Write all the properties to a file } } class Program { public void SaveData ( ) { Data d = new Data ( ) ; // Fetch the information from database and fill the local variable d.Prop1 = d.Prop1 ; d.SaveData ( ) ; } } | Is it ok to use C # Property like this |
C_sharp : I saw this kind of code at work : Any idea what does a static modifier on a constructor mean and why in this case it is required ? <code> class FooPlugin : IPlugin // IPlugin is a Microsoft CRM component , it has something special about it 's execution { static FooPlugin ( ) { SomeObject.StaticFunction ( ) ; // The guy who wrote it said it 's meaningful to this question but he ca n't remember why . } } | What does a static modifier on a constructor means ? |
C_sharp : I 'm using .NET 4.5 in a VSTO addin for outlook 2013 . I 'm having some trouble fully grasping properties and accessors . Auto-implemented accessors which I assume are when you just write get ; set ; rather than get { //code } , etc . are also giving me trouble . I have a dictionary I use internally in my class . Here is my code : then later on : I am using the same names as the properties in the code later on , within the same class.I never actually write : to create the variables I just was using the property directly.I tried changing my code to do this , and I had some issues and realized my understanding of properties is a bit mixed up.Here are a few questions I need clarified that I ca n't seem to find the correct answer to.First , is there any reason to use a private property ? My dictionaries are never accessed outside of the class or in any derived classes so is there a reason to even use properties ? I do n't use any special validation or anything in the setter or anything like that . Second , when I tried to change my code to use variables and then access them via the properties like your typical property example would , I ran into problems . I found an example where the getter was set to return _clientDict , but the setter was just set ; It gave me the error : that I must give set a body because it 's not abstract or partial . Why would it not auto-implement the setter for me in this instance ? Last , when I call new on the properties in the same class that it is declared in , what is the difference between doing that with a property and a normal variable of the same type ? Do properties differ at all from variables in that case ? Is it bad practice to use properties this way when it should be accomplished with private variables ? These may be some misguided questions but I ca n't find any other place that has the information to help me understand these distinctions . I 've been playing around with properties to try and figure all of this out but I could use so me assistance . <code> private Dictionary < string , string > clientDict { get ; set ; } private Dictionary < string , string > clientHistoryDict { get ; set ; } clientDict = new Dictionary < string , string > ( ) ; clientHistoryDict = new Dictionary < string , string > ( ) ; private Dictionary < string , string > _clientDict ; // etc . | Properties and auto-implementations |
C_sharp : I 'm trying to resolve CA2225 , which WARNs on ContrainedValue < T > below , with the following message : Provide a method named 'ToXXX ' or 'FromXXX ' as an alternate for operator 'ConstrainedValue < T > .implicit operator T ( ConstrainedValue < T > ) '.I 've also pasted PositiveInteger to illustrate a use-case for ConstrainedValue < T > . ConstrainedValue < T > enables derivatives to simply specify the constraint being applied to a value type , in the constructor . It seems like a pretty clean way to code this up . Is there any way to resolve the CA2225 warning , given that I 'm dealing with a generic type ? How can I provide an alternate operator ? Perhaps I could implement ToInt , ToDouble , etc . for all value types and have them throw if the from is not of the same type ? But I think it 's a bad practice to have the ToXXX method throw ? I could create a layer in-between ConstrainedValue < T > and PositiveInteger < T > , a ConstrainedInteger class . I could put ToInt ( ) in that class . But it seems wrong to create a layer simply to satisfy CA2225 and I do n't think the warning would go away on ConstrainedValue < T > and I would have to suppress that warning.Code : <code> namespace OBeautifulCode.AutoFakeItEasy { using System.Diagnostics ; using Conditions ; /// < summary > /// Represents a constrained value . /// < /summary > /// < typeparam name= '' T '' > The type of the constrained value. < /typeparam > [ DebuggerDisplay ( `` { Value } '' ) ] public abstract class ConstrainedValue < T > where T : struct { /// < summary > /// Initializes a new instance of the < see cref= '' ConstrainedValue { T } '' / > class . /// < /summary > /// < param name= '' value '' > The value of the < see cref= '' ConstrainedValue { T } '' / > instance. < /param > protected ConstrainedValue ( T value ) { this.Value = value ; } /// < summary > /// Gets the underlying value of the instance . /// < /summary > public T Value { get ; } /// < summary > /// Performs an implicit conversion from < see cref= '' ConstrainedValue { T } '' / > to the underlying value type . /// < /summary > /// < param name= '' from '' > The < see cref= '' ConstrainedValue { T } '' / > to convert from. < /param > /// < returns > /// The result of the conversion . /// < /returns > public static implicit operator T ( ConstrainedValue < T > from ) { return from.Value ; } } /// < summary > /// Represents a positive integer . /// < /summary > [ DebuggerDisplay ( `` { Value } '' ) ] public sealed class PositiveInteger : ConstrainedValue < int > { /// < summary > /// Initializes a new instance of the < see cref= '' PositiveInteger '' / > class . /// < /summary > /// < param name= '' value '' > The value held by the < see cref= '' PositiveInteger '' / > instance. < /param > public PositiveInteger ( int value ) : base ( value ) { Condition.Requires ( value , nameof ( value ) ) .IsGreaterThan ( 0 ) ; } } } | How to fix CA2225 ( OperatorOverloadsHaveNamedAlternates ) when using generic class |
C_sharp : BackgroundEven though it 's possible to compile C # code at runtime , it 's impossible to include and run the generated code in the current scope . Instead all variables have to be passed as explicit parameters.Compared with dynamic programming languages like Python , one could never truly replicate the complete behaviour of eval ( as in this example ) .The questionSo my question is ( regardless if it 's actually useful ; ) ) whether it 's possible to mimic dynamic scope in .NET through the use of reflection.Since .NET provides us with the Diagnostics.StackTrace class which allows us to inspect the calling methods , this question boils down to the following : ( How ) is it possible to reliably access the locals of calling methods ? Does the stack trace provide us with enough information to compute the memory offsets or are such things forbidden in managed code anyway ? Is such code somehow possible ? <code> x = 42print ( eval ( `` x + 1 '' ) ) # Prints 43 void Foo ( ) { int x = 42 ; Console.WriteLine ( Bar ( ) ) ; } int Bar ( ) { return ( int ) ( DynamicScope.Resolve ( `` x '' ) ) ; // Will access Foo 's x = 42 } | How to access locals through stack trace ? ( Mimicking dynamic scope ) |
C_sharp : I 'd like to know if it is possible to use an expression as a variable/parameter in C # . I would like to do something like this : Here 's what I do n't want to do : Really what I 'm getting at is a way to get around using a switch or series of if statements for each of : < > < = > = == ! = . Is there a way to do it ? Edit : Suppose that the expression is a string , like `` x < 2 '' . Is there a way to go from the string to a predicate without using a series of if statements on the condition ? <code> int x = 0 ; public void g ( ) { bool greaterThan = f ( `` x > 2 '' ) ; bool lessThan = f ( `` x < 2 '' ) ; } public bool f ( Expression expression ) { if ( expression ) return true ; else return false ; } int x = 0 ; public void g ( ) { bool greaterThan = f ( x , ' < ' , 2 ) ; } public bool f ( int x , char c , int y ) { if ( c == ' < ' ) return x < y ; if ( c == ' > ' ) return x > y ; } | C # : Is there a way to use expressions as a variable/parameter ? |
C_sharp : I am using Microsoft Interactivity and Microsoft Interactions to rotate an object based on a Property in my code-behind . To make the rotation more smooth I added in an easing function . It does the animation perfectly fine but when it reaches the end of the animation for 1 split frame the rotation resets to the value it was before the animation and then switches back to the value after the rotation , causing it to 'twitch ' back and forth . This only happens on EaseOut . <code> < i : Interaction.Triggers > < ie : PropertyChangedTrigger Binding= '' { Binding Rotation } '' > < ie : ChangePropertyAction TargetName= '' RotateTransformer '' PropertyName= '' Angle '' Value= '' { Binding Rotation } '' Duration= '' 0:0:2 '' > < ie : ChangePropertyAction.Ease > < BackEase EasingMode= '' EaseOut '' Amplitude= '' 1.2 '' / > < /ie : ChangePropertyAction.Ease > < /ie : ChangePropertyAction > < /ie : PropertyChangedTrigger > < /i : Interaction.Triggers > < Path Stroke= '' Black '' Fill= '' Gray '' > < Path.RenderTransform > < RotateTransform x : Name= '' RotateTransformer '' CenterX= '' 64 '' CenterY= '' 105 '' / > < /Path.RenderTransform > < Path.Data > < PathGeometry > < PathFigureCollection > < PathFigure StartPoint= '' 64,0 '' > < LineSegment Point= '' 39,110 '' / > < LineSegment Point= '' 64 , 70 '' / > < LineSegment Point= '' 39,180 '' / > < LineSegment Point= '' 89 , 180 '' / > < LineSegment Point= '' 64,70 '' / > < LineSegment Point= '' 89,110 '' / > < LineSegment Point= '' 64,0 '' / > < /PathFigure > < /PathFigureCollection > < /PathGeometry > < /Path.Data > < /Path > | Easing animation 'twitches ' when it finishes |
C_sharp : I would like to know the way to make a list of drop down lists in C # class . I have been trying like this : Then I add _ddlCollection to the Asp.NET site like this : But it breaks on line : Can you tell me how to add a few DDL 's to a List ? <code> List < DropDownList > _ddlCollection ; for ( int i = 0 ; i < 5 ; i++ ) { _ddlCollection.Add ( new DropDownList ( ) ) ; } foreach ( DropDownList ddl in _ddlCollection ) { this.Controls.Add ( ddl ) ; } _ddlCollection.Add ( new DropDownList ( ) ) ; | How to make a list of DDL in C # programatically |
C_sharp : In the MSDN Events Tutorial hooking up to events is demonstrated with the example : Where as I have been keeping a reference to the delegate . Example : When I look at the MSDN example code , `` -= new '' just looks wrong to me . Why would this List have a reference to an event handler I just created ? Obviously I must be thinking about things the wrong way ? Can I get a pointer to a technical explanation of how -= works , seeing how -= appears to not be using one . <code> // Add `` ListChanged '' to the Changed event on `` List '' : List.Changed += new ChangedEventHandler ( ListChanged ) ; ... // Detach the event and delete the list : List.Changed -= new ChangedEventHandler ( ListChanged ) ; ChangedEventHandler myChangedEvent = new ChangedEventHandler ( ListChanged ) ; List.Changed += myChangedEvent ; ... List.Changed -= myChangedEvent ; | How does the removing an event handler with -= work when a `` new '' event is specified |
C_sharp : I 'm using Entity Framework 6.1 , code-first . I 'm trying to store/retrieve a decimal from SQL Server , but the correct precision is n't retrieved . I read from a .csv file , process the data , then insert into the DB.Value in the .csv file : 1.1390Value when saved as decimal from the import : 1.1390Value inserted into DB : 1.139Value actually stored/shown in SSMS : 1.1390Value when manually running the query SQL Profiler captures for the retrieval : 1.1390Value retrieved by EF : 1.1300Everything is working except for retrieving the value . I 've tried the solution given in every single other SO post ( below ) , but it has no effect . What 's going wrong here ? How can I retrieve the correct value with the proper precision ? Supposed solution : Retrieval method , returns type ClassA with incorrect precision : Comparison between the two decimal values : ClassA : <code> modelBuilder.Entity < ClassA > ( ) .Property ( p = > p.MyDecimal ) .HasPrecision ( 19 , 4 ) ; _poRepository.Table.FirstOrDefault ( p = > p.CompNumberA == compNum & & p.LineNumber == lineNumber ) ; import.MyDecimal ! = dbValue.MyDecimal public class ClassA { // properties public virtual decimal MyDecimal { get ; set ; } } | EF retrieves incorrect decimal precision |
C_sharp : I usually find myself doing something like : and I find all this mixup of types/interface a bit confusing and it tickles my potential performance problem antennae ( which I ignore until proven right , of course ) . Is this idiomatic and proper C # or is there a better alternative to avoid casting back and forth to access the proper methods to work with the data ? EDIT : The question is actually twofold : When is it proper to use either the IEnumerable interface or an array or a list ( or any other IEnumerable implementing type ) directly ( when accepting parameters ) ? Should you freely move between IEnumerables ( implementation unknown ) and lists and IEnumerables and arrays and arrays and Lists or is that non idiomatic ( there are better ways to do it ) / non performant ( not typically relevant , but might be in some cases ) / just plain ugly ( unmaintable , unreadable ) ? <code> string [ ] things = arrayReturningMethod ( ) ; int index = things.ToList < string > .FindIndex ( ( s ) = > s.Equals ( `` FOO '' ) ) ; //do something with indexreturn things.Distinct ( ) ; //which returns an IEnumerable < string > | When to use each of T [ ] , List < T > , IEnumerable < T > ? |
C_sharp : Recently it seems like Microsoft changed something in the behaviour when people are trying to sign-in with their Microsoft Account through our services.We have a setup where we use IdentityServer4 and Azure AD for the Microsoft Accounts . When people try to sign-in now , they just click sign-in button on our webpage and is taken to the Microsoft sign-in . Here it seems that Microsoft is automatically selecting the already logged in user and just proceeds to log the user in . This leads to two issues . It is a hard for the user to understand that their account is just automatically selected . If the user is fast enough , they can click their user and that sends two callbacks to our server and a race-condition happens , which results in an OperationCancelledException half of the time.Our setup is pretty close to the one given as example on IdentityServer4s Quick start guide : We setup the authentication schemes as above . And then we do a normal challenge against the provider : Does anybody have any knowledge of why this is happening . I would really like to disable this auto-selection of the users account when they are using Microsoft login . Because it is mostly confusing our customers instead of helping them.Any resources are welcome . Thanks in advance . <code> serviceCollection .AddAuthentication ( o = > { o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme ; o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme ; } ) .AddCookie ( CookieAuthenticationDefaults.AuthenticationScheme ) .AddMicrosoftAccount ( `` Microsoft '' , `` Microsoft '' , o = > { o.SignInScheme = IdentityConstants.ExternalScheme ; o.ClientId = _externalKeysOptions.MicrosoftClientId ; o.ClientSecret = _externalKeysOptions.MicrosoftClientSecret ; o.CallbackPath = new PathString ( `` /signin-microsoft '' ) ; new [ ] { `` offline_access '' , `` Calendars.Read.Shared '' , `` Calendars.ReadWrite '' , `` Tasks.Readwrite '' } .ForEach ( scope = > o.Scope.Add ( scope ) ) ; o.SaveTokens = true ; } ) [ HttpPost ] [ AllowAnonymous ] [ ValidateAntiForgeryToken ] [ Route ( `` externallogin '' ) ] public IActionResult ExternalLogin ( ExternalLoginModel model ) { var redirectUrl = Url.Action ( `` ExternalLoginCallback '' , `` Account '' , new { model.ReturnUrl , termsOfServiceAccepted = model.AgreeToTerms , platform = model.Platform } ) ; var properties = _signInManager.ConfigureExternalAuthenticationProperties ( model.Provider , redirectUrl ) ; return Challenge ( properties , model.Provider ) ; } | IdentityServer4 and Azure AD auto selects users on sign-in page |
C_sharp : For some reason , with the Razor view engine , VS is crashing on me . I copied the CSHTML content over to a VBHTML file and begin reformatting it , and VS has crashed on me twice now as I change a helper or function method syntax from : toIs anyone else getting this ? The whole machine must be rebooted to get intellisense/markup highlighing to work.Thanks . <code> @ helper SomeHelper ( string text ) @ Helper SomeHelper ( text As String ) | VS Crashes with RAZOR VBHTML |
C_sharp : Consider the following two alternatives of getting the higher number between currentPrice and 100 ... I raised this question because I was thinking about a context where the currentPrice variable could be edited by other threads.In the first case ... could price obtain a value lower than 100 ? I 'm thinking about the following : <code> int price = currentPrice > 100 ? currentPrice : 100int price = Math.Max ( currentPrice , 100 ) if ( currentPrice > 100 ) { //currentPrice is edited here . price = currentPrice ; } | Is the ternary operator ( ? : ) thread safe in C # ? |
C_sharp : Being new to programming I have only just found out that you can specifically catch certain types of errors and tie code to only that type of error . I 've been researching into the subject and I do n't quite understand the syntax e.g.I understand the InvalidCastException is the type of error being handled , however I am unsure of what e is.Could somebody please explain this ? <code> catch ( InvalidCastException e ) { } | Being specific with Try / Catch |
C_sharp : What happens when a synchronous method is called within an asynchronous callback ? Example : A connection is accepted and the async receive callback is started . When the tcp connection receives data , it calls the receive callback . If the sync Send method is called , does that stop other async callbacks from happening ? Or are all async callbacks independent of each other ? <code> private void AcceptCallback ( IAsyncResult AR ) { tcp.BeginReceive ( ReceiveCallback ) ; } private void ReceiveCallback ( IAsyncResult AR ) { tcp.Send ( data ) ; } | Call Sync method call from Async Callback ? |
C_sharp : I want lines as many as the width of the console to simultaneously write downwards one char to the height of the console . I 've done most of it , but it goes from top to bottom to right etc ... If you need help picturing what I mean , think of the matrix code rain . <code> int w = Console.WindowWidth ; int h = Console.WindowHeight ; int i = 0 ; while ( i < w ) { int j = 0 ; while ( j < h ) { Thread.Sleep ( 1 ) ; Console.SetCursorPosition ( i , j ) ; Console.Write ( `` . `` ) ; j++ ; } i++ ; } | How to write in multiple positions in a console application at the same time ? C # |
C_sharp : While working on a upgrade i happened to come across a code like this.My question is : Is there any need/use of 'explicit ' implementation of interface in this piece of code ? Will it create any problem if i remove the method ( explicit implementation of interface ) that i have marked `` redundant '' above ? PS : I understand that explicit implementation of interface is very important , and it can be used when we need to give access to a method at interface level only , and to use two interface with same signature of method . <code> interface ICustomization { IMMColumnsDefinition GetColumnsDefinition ( ) ; } class Customization : ICustomization { private readonly ColumnDefinition _columnDefinition ; //More code here . public ColumnsDefinition GetColumnsDefinition ( ) { return _columnDefinition ; } ColumnsDefinition ICustomization.GetColumnsDefinition ( ) //redundant { return GetColumnsDefinition ( ) ; } } | Implicit and Explicit implementation of interface |
C_sharp : I 'm trying to post FormData including both a File and a Collection.This is my Model : This is my action : My FormData in JavaScript is : And here is the header : The `` File '' is working fine , but the `` Content '' is always null.Where am I going wrong ? Thank you ! <code> public class Content { public string Name { get ; set ; } public string Link { get ; set ; } } public class Model { public IEnumerable < Content > Contents { get ; set ; } public IFormFile File { get ; set ; } } [ HttpPost ] public async Task InsertAsync ( [ FromForm ] Model dataPost ) { await _services.Create ( dataPost ) ; } const formData = new FormData ( ) ; formData.append ( `` File '' , myFile , `` image.jpg '' ) formData.append ( `` Contents '' , arrayOfContent ) 'Content-Type ' : ` multipart/form-data ` | Collection always null when using [ FromForm ] attribute |
C_sharp : I have a huge list of Items and need to Group them by one property . Then the oldest of each group should be selected.Simplified Example : Select the oldest User of each FirstName.Class User : I was wondering why this statement took so long until I set a breakpoint at Result and looked into the SQL statement generated : Question : Is there a way to solve his more efficient ? Sub-selects are expensive and EF generates one per column . I use mySQL .NET Connector version 6.9.5.0 <code> using ( ED.NWEntities ctx = new ED.NWEntities ( ) ) { IQueryable < ED.User > Result = ctx.User.GroupBy ( x = > x.FirstName ) .Select ( y = > y.OrderBy ( z = > z.BirthDate ) .FirstOrDefault ( ) ) .AsQueryable ( ) ; } public partial class User { public int UserID { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } public Nullable < System.DateTime > BirthDate { get ; set ; } } { SELECT ` Apply1 ` . ` UserID ` , ` Apply1 ` . ` FIRSTNAME1 ` AS ` FirstName ` , ` Apply1 ` . ` LastName ` , ` Apply1 ` . ` BirthDate ` FROM ( SELECT ` Distinct1 ` . ` FirstName ` , ( SELECT ` Project2 ` . ` UserID ` FROM ` User ` AS ` Project2 ` WHERE ( ` Distinct1 ` . ` FirstName ` = ` Project2 ` . ` FirstName ` ) OR ( ( ` Distinct1 ` . ` FirstName ` IS NULL ) AND ( ` Project2 ` . ` FirstName ` IS NULL ) ) ORDER BY ` Project2 ` . ` BirthDate ` ASC LIMIT 1 ) AS ` UserID ` , ( SELECT ` Project2 ` . ` FirstName ` FROM ` User ` AS ` Project2 ` WHERE ( ` Distinct1 ` . ` FirstName ` = ` Project2 ` . ` FirstName ` ) OR ( ( ` Distinct1 ` . ` FirstName ` IS NULL ) AND ( ` Project2 ` . ` FirstName ` IS NULL ) ) ORDER BY ` Project2 ` . ` BirthDate ` ASC LIMIT 1 ) AS ` FIRSTNAME1 ` , ( SELECT ` Project2 ` . ` LastName ` FROM ` User ` AS ` Project2 ` WHERE ( ` Distinct1 ` . ` FirstName ` = ` Project2 ` . ` FirstName ` ) OR ( ( ` Distinct1 ` . ` FirstName ` IS NULL ) AND ( ` Project2 ` . ` FirstName ` IS NULL ) ) ORDER BY ` Project2 ` . ` BirthDate ` ASC LIMIT 1 ) AS ` LastName ` , ( SELECT ` Project2 ` . ` BirthDate ` FROM ` User ` AS ` Project2 ` WHERE ( ` Distinct1 ` . ` FirstName ` = ` Project2 ` . ` FirstName ` ) OR ( ( ` Distinct1 ` . ` FirstName ` IS NULL ) AND ( ` Project2 ` . ` FirstName ` IS NULL ) ) ORDER BY ` Project2 ` . ` BirthDate ` ASC LIMIT 1 ) AS ` BirthDate ` FROM ( SELECT DISTINCT ` Extent1 ` . ` FirstName ` FROM ` User ` AS ` Extent1 ` ) AS ` Distinct1 ` ) AS ` Apply1 ` } | Entity Framework GroupBy take the oldest with mySQL |
C_sharp : I created new Azure account and trying to automatically deploy app inside it with following code : It works , if identifierUrl is hardcoded as Azure Active Directory name.How can I read identifierUrl ( Azure Active Directory domain name ) from Azure ? I can see this value in portal , but I can not find an API to read it . <code> var app = azure.AccessManagement.ActiveDirectoryApplications.Define ( appName ) .WithSignOnUrl ( appSignOnUrl ) .WithAvailableToOtherTenants ( true ) .WithIdentifierUrl ( identifierUrl ) .DefinePasswordCredential ( username ) .WithPasswordValue ( password ) .WithDuration ( ) .Attach ( ) ; .CreateAsync ( ) ; | How to read domain of Azure Active Directory |
C_sharp : Given this code : I would have expected ReflectedType to be SomeDerivedClass given that it is the type of the parameter for the expression . But it is SomeClass , which is - if i understand correctly - the declaring type . Why is that ? <code> static void Main ( string [ ] args ) { Expression < Func < SomeDerivedClass , object > > test = i = > i.Prop ; var body = ( UnaryExpression ) test.Body ; Console.WriteLine ( ( ( MemberExpression ) body.Operand ) .Member.ReflectedType ) ; } public class SomeClass { public int Prop { get ; private set ; } } public class SomeDerivedClass : SomeClass { } | ReflectedType from MemberExpression |
C_sharp : I 'm developing a Windows Phone 8.1 app . I have a screen with a list of news ' titles with thumbnails . First I 'm making asynchronous http request to get news collection in JSON ( satisfying the NotifyTaskCompletion pattern ) NewsCategory : News : So far it works perfectly , but as soon as I get the ImagePath property , I would like to download and display the given image . I 've found a solution to do it asynchronously here : WP 8.1 Binding image from a http request - so that when xaml gets the image path , it calls a converter class ( BinaryToImageSourceConverter ) , also using the NotifyTaskCompletion pattern.The problem occurs in the following method : When the first await is called , the debugger never reach the next line and the method never returns . The string path variable has proper content.So far I have tried to use ConfigureAwait ( false ) , but it does n't work in my case.I have also found out in the topic : Deadlock while using async await , that : When you 're using ConfigureAwait ( false ) , you tell your program you dont mind about the context . It can solve some deadlocking problems , but is n't usually the right solution . The right solution is most likely never to wait for tasks in a blocking way , and being asynchronous all the way.I do n't know where I could have that stuff in a blocking way . What can be the reason for that deadlock ? And if it 's all about wrong approach , do you know any pattern that would be more appropriate for downloading thumbnails to a collection of items ? Thank you for your help.update : how is GetImage invoked : It 's like in topic : WP 8.1 Binding image from a http request and in xaml : <code> NewsCategories = new NotifyTaskCompletion < ObservableCollection < NewsCategory > > ( _newsService.GetNewsCategoriesAsync ( ) ) ; public class NewsCategory : ObservableObject { ... public string Title { get ; set ; } public ObservableCollection < News > Items { get ; set ; } } public class News : ObservableObject { ... public string Title { get ; set ; } public string ImagePath { get ; set ; } } private async Task < BitmapImage > GetImage ( string path ) { HttpClient webCLient = new HttpClient ( ) ; var responseStream = await webCLient.GetStreamAsync ( path ) ; var memoryStream = new MemoryStream ( ) ; await responseStream.CopyToAsync ( memoryStream ) ; memoryStream.Position = 0 ; var bitmap = new BitmapImage ( ) ; await bitmap.SetSourceAsync ( memoryStream.AsRandomAccessStream ( ) ) ; return bitmap ; } public class WebPathToImage : IValueConverter { public object Convert ( object value , Type targetType , object parameter , string language ) { if ( value == null ) return null ; return new NotifyTaskCompletion < BitmapImage > ( GetImage ( ( String ) value ) ) ; } public object ConvertBack ( object value , Type targetType , object parameter , string language ) { throw new NotImplementedException ( ) ; } private async Task < BitmapImage > GetImage ( string path ) { using ( var webCLient = new HttpClient ( ) ) { webCLient.DefaultRequestHeaders.Add ( `` User-Agent '' , `` bot '' ) ; var responseStream = await webCLient.GetStreamAsync ( path ) .ConfigureAwait ( false ) ; var memoryStream = new MemoryStream ( ) ; await responseStream.CopyToAsync ( memoryStream ) ; memoryStream.Position = 0 ; var bitmap = new BitmapImage ( ) ; await bitmap.SetSourceAsync ( memoryStream.AsRandomAccessStream ( ) ) ; return bitmap ; } } } < Image DataContext= '' { Binding ImagePath , Converter= { StaticResource WebPathToImage } } '' Source= '' { Binding Result } '' Stretch= '' UniformToFill '' Height= '' 79 '' Width= '' 79 '' / > | Async/await deadlock while downloading images |
C_sharp : I 'm having some problems setting up a command handling architecture . I want to be able to create a number of different commands derived from ICommand ; then , create a number of different command handlers derived from ICommandHandler ; Here 's the interface and classes I have begun to define : I have a helper class that can create the appropriate type of command : And , a helper class that creates the appropriate handler ; this is where I 'm having trouble : Here 's the main running methodI can think of a few different ways to refactor the code that I 'm sure would avoid the issue , but I found myself a bit perplexed by the problem and wanted to understand more of what was going on.This design looks like it should work . <code> interface ICommand { } class CreateItemCommand : ICommand { } interface ICommandHandler < TCommand > where TCommand : ICommand { void Handle ( TCommand command ) ; } class CreateItemCommandHandler : ICommandHandler < CreateItemCommand > { public void Handle ( CreateItemCommand command ) { // Handle the command here } } class CommandResolver { ICommand GetCommand ( Message message ) { return new CreateItemCommand ( ) ; // Handle other commands here } } class CommandHandlerResolver { public ICommandHandler < TCommand > GetHandler < TCommand > ( TCommand command ) { // I 'm using Ninject and have an instance of an IKernel // The following code throws an exception despite having a proper binding // _kernel.GetService ( typeof ( ICommandHandler < TCommand > ) ) var bindingType = typeof ( ICommandHandler < > ) .MakeGenericType ( command.GetType ( ) ) ; var handler = _kernel.GetService ( bindingType ) ; return handler as ICommandHandler < TCommand > ; // handler will be null after the cast } } CommandResolver _commandResolver ; HandlerResolver _handlerResolver ; void Run ( ) { // message is taken from a queue of messages var command = _commandResolver.GetCommand ( message ) ; var handler = _handlerResolver.GetHandler ( command ) ; // handler will always be null handler.Handle ( command ) ; } | Contravariance ? Covariance ? What 's wrong with this generic architecture ... ? |
C_sharp : I am reviewing another developer 's code and he has written a lot of code for class level variables that is similar to the following : Does n't coding this way add unnecessary overhead since the variable is private ? Am I not considering a situation where this pattern of coding is required for private variables ? <code> /// < summary > /// how often to check for messages /// < /summary > private int CheckForMessagesMilliSeconds { get ; set ; } /// < summary > /// application path /// < /summary > private string AppPath { get ; set ; } | Is there any benefit to declaring a private property with a getter and setter ? |
C_sharp : I have two pages say Page1 and page2.In Page-1 I have a listview and an Image button ( tap gesture ) .Here if I click listview item , it navigates to Page2 whereit plays a song.Song continues to play . Then I go back to page1 by clicking back button . Then as mentioned I have an imagebutton in page1 , if I click this image button , I want to go the same page which was shown earlier ( page2 ) with same status song continues to play ( it should not play from the beginning ) .I understand , if I click the back button , it destroys the model page . For some reason , I ca n't use pushasync ( ) .Is this possible ? <code> Navigation.PushModalAsync ( new page2 ( parameter1 ) ) ; | Navigation in Xamarin.Forms |
C_sharp : I 've just found strange for me code in Jeffrey Richter book ( CLR via C # 4.0 , page 257 ) and have misunderstanding why it works so.Result : As you can see , we have an accessor property named 'Students ' , which has only getter ( not setter ! ) , but in 'Main ' function , when we 'd like to initialize 'classroom ' variable , we initializing 'Students ' field of 'Classroom ' type : I always thought , that when a variable in 'left-side ' of expression ( int i = 1 ) , then compiler should access to setter function , and when in 'right-side ' ( int x = i + 2 ) to getter function.Why in Jeffrey 's code so interesting behavior ( may be it 's just for me ? sorry if it 's so ) . <code> public sealed class Classroom { private List < String > m_students = new List < String > ( ) ; public List < String > Students { get { return m_students ; } } public Classroom ( ) { } } class Program { static void Main ( string [ ] args ) { Classroom classroom = new Classroom { Students = { `` Jeff '' , `` Kristin '' } } ; foreach ( var student in classroom.Students ) Console.WriteLine ( student ) ; } } JeffKristin Classroom classroom = new Classroom { Students = { `` Jeff '' , `` Kristin '' } } ; | get and set misunderstanding in initialisation : Jeffrey Richter , CLR via C # |
C_sharp : I am saving xml from .NET 's XElement . I 've been using the method ToString , but the formatting does n't look how I 'd like ( examples below ) . I 'd like at most two tags per line . How can I achieve that ? Saving XElement.Parse ( `` < a > < b > < c > one < /c > < c > two < /c > < /b > < b > three < c > four < /c > < c > five < /c > < /b > < /a > '' ) .ToString ( ) gives meBut for readability I would rather 'three ' , 'four ' and 'five ' were on separate lines : Edit : Yes I understand this is syntactically different and `` not in the spirit of xml '' , but I 'm being pragmatic . Recently I 've seen megabyte-size xml files with as few as 3 lines—these are challenging to text editors , source control , and diff tools . Something needs to be done ! I 've tested that changing the formatting above is compatible with our application . <code> < a > < b > < c > one < /c > < c > two < /c > < /b > < b > three < c > four < /c > < c > five < /c > < /b > < /a > < a > < b > < c > one < /c > < c > two < /c > < /b > < b > three < c > four < /c > < c > five < /c > < /b > < /a > | Writing xml with at most two tags per line |
C_sharp : I connect to a 3rd party webservice that returns a complex JSON object that only contains a few bits of information I actually need.Basically , I just need the array in `` value '' . From that array , I just need the `` Id '' , `` Title '' and `` Status '' properties.I want to put those attributes into a c # class called Project . This is my class : I 'm trying to use this code to read the JSON and do the transform : Example JSON : I just get a null object back . But in the debugger , I can see that it 's pulling all the JSON data from the webservice . How can I get what I need from the JSON , build my c # objects , and ignore all the rest ? <code> public class Project { public String Id { get ; set ; } public String Title { get ; set ; } public String Status { get ; set ; } } using ( WebResponse response = request.GetResponse ( ) ) { using ( StreamReader reader = new StreamReader ( response.GetResponseStream ( ) ) ) { var serializer = new JsonSerializer ( ) ; var jsonTextReader = new JsonTextReader ( reader ) ; returnValue = serializer.Deserialize < Project > ( jsonTextReader ) ; } } { `` odata.metadata '' : '' http : //school.edu/Api/1/ $ metadata # Projects '' , `` odata.count '' : '' 3 '' , `` value '' : [ { `` odata.id '' : '' http : //school.edu/Api/1/Projects ( '123 ' ) '' , `` RelatedProjects @ odata.navigationLinkUrl '' : '' http : //school.edu/Api/1/Projects ( '123 ' ) /RelatedProjects '' , `` Tags @ odata.navigationLinkUrl '' : '' http : //school.edu/Api/1/Projects ( '123 ' ) /Tags '' , `` TimedEvents @ odata.navigationLinkUrl '' : '' http : //school.edu/Api/1/Projects ( '123 ' ) /Categories '' , `` ep @ odata.navigationLinkUrl '' : '' http : //school.edu/Api/1/Projects ( '123 ' ) /ep '' , `` # CreateLike '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '123 ' ) /CreateLike '' } , `` # CreateShortcut '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '123 ' ) /CreateShortcut '' } , `` # Play '' : { `` target '' : '' http : //school.edu/Play/123 '' } , `` # SendInvitation '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '123 ' ) /SendInvitation '' } , `` # CopyProject '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '123 ' ) /CopyProject '' } , `` # AddVideoPodcast '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '123 ' ) /AddVideoPodcast '' } , `` # AddEP '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '123 ' ) /AddEP '' } , `` Id '' : '' 123 '' , `` Title '' : '' Test Title 1 '' , `` Status '' : '' Viewable '' } , { `` odata.id '' : '' http : //school.edu/Api/1/Projects ( '456 ' ) '' , `` RelatedProjects @ odata.navigationLinkUrl '' : '' http : //school.edu/Api/1/Projects ( '456 ' ) /RelatedProjects '' , `` Tags @ odata.navigationLinkUrl '' : '' http : //school.edu/Api/1/Projects ( '456 ' ) /Tags '' , `` TimedEvents @ odata.navigationLinkUrl '' : '' http : //school.edu/Api/1/Projects ( '456 ' ) /Categories '' , `` ep @ odata.navigationLinkUrl '' : '' http : //school.edu/Api/1/Projects ( '456 ' ) /ep '' , `` # CreateLike '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '456 ' ) /CreateLike '' } , `` # CreateShortcut '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '456 ' ) /CreateShortcut '' } , `` # Play '' : { `` target '' : '' http : //school.edu/Play/456 '' } , `` # SendInvitation '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '456 ' ) /SendInvitation '' } , `` # CopyProject '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '456 ' ) /CopyProject '' } , `` # AddVideoPodcast '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '456 ' ) /AddVideoPodcast '' } , `` # AddEP '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '456 ' ) /AddEP '' } , `` Id '' : '' 456 '' , `` Title '' : '' Test Title 2 '' , `` Status '' : '' Viewable '' } , { `` odata.id '' : '' http : //school.edu/Api/1/Projects ( '789 ' ) '' , `` RelatedProjects @ odata.navigationLinkUrl '' : '' http : //school.edu/Api/1/Projects ( '789 ' ) /RelatedProjects '' , `` Tags @ odata.navigationLinkUrl '' : '' http : //school.edu/Api/1/Projects ( '789 ' ) /Tags '' , `` TimedEvents @ odata.navigationLinkUrl '' : '' http : //school.edu/Api/1/Projects ( '789 ' ) /Categories '' , `` ep @ odata.navigationLinkUrl '' : '' http : //school.edu/Api/1/Projects ( '789 ' ) /ep '' , `` # CreateLike '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '789 ' ) /CreateLike '' } , `` # CreateShortcut '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '789 ' ) /CreateShortcut '' } , `` # Play '' : { `` target '' : '' http : //school.edu/Play/789 '' } , `` # SendInvitation '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '789 ' ) /SendInvitation '' } , `` # CopyProject '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '789 ' ) /CopyProject '' } , `` # AddVideoPodcast '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '789 ' ) /AddVideoPodcast '' } , `` # AddEP '' : { `` target '' : '' http : //school.edu/Api/1/Projects ( '789 ' ) /AddEP '' } , `` Id '' : '' 789 '' , `` Title '' : '' Test Title 3 '' , `` Status '' : '' Viewable '' } ] , `` odata.nextLink '' : '' http : //school.edu/Api/1/Folders ( 'xyz ' ) /Projects ? $ skip=10 & $ top=10 '' } | Selectively read part of JSON data using JsonSerializer and populate a c # object |
C_sharp : In C # , I can attach documentation for properties , methods , events , and so on , directly in the code using XML Documentation Comments . I know how to insert a reference to a particular method : Is there a way to insert a reference to a method group ? Where I 've got multiple overloads of the same method name ... I tried ..but that did not work . EDIT : BUMP <code> < see cref= '' MethodName ( TypeForArg1 , TypeForArg2.. ) '' / > < see cref= '' M : MethodName '' / > | In xml doc , can I insert a reference to a method group ? How ? |
C_sharp : I 'm trying to learn MVVM , but there is something I do n't understand yet.Currently , I have this event handler : Very easy . However , I would like to apply the MVVM pattern in this application.I 'm wondering , am I supposed to put this logic in a ViewModel instead of directly in the view code ? If so , how am I supposed to do that ? Thanks <code> private void Window_Closing ( object sender , System.ComponentModel.CancelEventArgs e ) { if ( MessageBox.Show ( `` Are you sure you want to close this application ? `` , `` Close ? ? `` , MessageBoxButton.YesNo , MessageBoxImage.Question ) == MessageBoxResult.No ) { e.Cancel = true ; } } | MVVM - Exit confirmation |
C_sharp : We have our integration tests set up using xUnit and Microsoft.AspNetCore.TestHost.TestServer to run tests against Web API running on ASP.NET Core 2.2.Our Web API is a single code base that would be deployed separately multiple times based on some configuration or application setting differences like country , currency , etc.Below diagram tries to explain our deployment set up : We want to ensure that our integration tests run against all the deployments.For both deployments , X and X ` the API endpoint , request , and response are absolutely same . Hence , We would like to avoid repeating ourselves when it comes to integration tests for each deployment.Here is the sample code explaining our current test set up : TestStartup.csTestServerFixture.csMyTest.csNow , I 'm looking to run ItShouldExecuteTwice_AgainstTwoSeparateConfigurations test in class MyTest more than once against two different configurations/ app settings or in other words against two different test deployments within Visual Studio.I know , I should be able to achieve this using a combination of build configurations ( like DEBUG_SETTING1 , DEBUG_SETTING2 ) and preprocessor directive ( # if DEBUG_SETTING1 ) .The other option could be to have a base test helper project with common methods and a separate integration project for each deployment.Is there a better and more elegant way to achieve this ? <code> public class TestStartup : IStartup { public IServiceProvider ConfigureServices ( IServiceCollection services ) { var configuration = new ConfigurationBuilder ( ) .SetBasePath ( Directory.GetCurrentDirectory ( ) ) .AddJsonFile ( `` appsettings.json '' , false ) .AddEnvironmentVariables ( ) .Build ( ) ; services.AddMvc ( ) .SetCompatibilityVersion ( version : CompatibilityVersion.Version_2_2 ) ; // Code to add required services based on configuration return services.BuildServiceProvider ( ) ; } public void Configure ( IApplicationBuilder app ) { app.UseMvc ( ) ; // Code to configure test Startup } } public class TestServerFixture { public TestServerFixture ( ) { var builder = new WebHostBuilder ( ) .ConfigureServices ( services = > { services.AddSingleton < IStartup > ( new TestStartup ( ) ) ; } ) ; var server = new TestServer ( builder ) ; Client = server.CreateClient ( ) ; } public HttpClient Client { get ; private set ; } } public class MyTest : IClassFixture < TestServerFixture > { private readonly TestServerFixture _fixture ; public MyTest ( TestServerFixture fixture ) { _fixture = fixture ; } [ Fact ] public void ItShouldExecuteTwice_AgainstTwoSeparateConfigurations ( ) { // ... } } | Run single test against multiple configurations in Visual Studio |
C_sharp : If a type has no static constructor , field initializers will execute just prior to the type being used— or anytime earlier at the whim of the runtimeWhy this code : yields : while this code : yields The order of a and b is understood . but why dealing with static method is different than static field.I mean why the start and end lines are in different locations with static methods vs static fields ? I mean - in both situation he 's got to initialize those fields ... so why ? ( I know I can add static ctor which make it to be the same - but Im asking about this particular situation . ) ( p.s . Dump ( ) is just like console.write ) <code> void Main ( ) { `` -- -- -- -start -- -- -- - '' .Dump ( ) ; Test.EchoAndReturn ( `` Hello '' ) ; `` -- -- -- -end -- -- -- - '' .Dump ( ) ; } class Test { public static string x = EchoAndReturn ( `` a '' ) ; public static string y = EchoAndReturn ( `` b '' ) ; public static string EchoAndReturn ( string s ) { Console.WriteLine ( s ) ; return s ; } } -- -- -- -start -- -- -- -abHello -- -- -- -end -- -- -- - void Main ( ) { `` -- -- -- -start -- -- -- - '' .Dump ( ) ; var test=Test.x ; `` -- -- -- -end -- -- -- - '' .Dump ( ) ; } ab -- -- -- -start -- -- -- -- -- -- -- end -- -- -- - | static constructors and BeforeFieldInit ? |
C_sharp : It is quite a while that I have been trying to understand the idea behind IEnumerable and IEnumerator . I read all the questions and answers I could find over the net , and on StackOverflow in particular , but I am not satisfied . I got to the point where I understand how those interfaces should be used , but not why they are used this way.I think that the essence of my misunderstanding is that we need two interfaces for one operation . I realized that if both are needed , one was probably not enough . So I took the `` hard coded '' equivalent of foreach ( as I found here ) : and tried to get it to work with one interface , thinking something would go wrong which would make me understand why another interface is needed.So I created a collection class , and implemented IForeachable : and used the foreach equivalent to nominate the collection : And it works ! So what is missing here that make another interface required ? Thanks.Edit : My question is not a duplicate of the questions listed in the comments : This question is why interfaces are needed for enumerating in the first place.This question and this question are about what are those interfaces and how should they be used.My question is why they are designed the way they are , not what are they , how they work , and why do we need them in the first place . <code> while ( enumerator.MoveNext ( ) ) { object item = enumerator.Current ; // logic } class Collection : IForeachable { private int [ ] array = { 1 , 2 , 3 , 4 , 5 } ; private int index = -1 ; public int Current = > array [ index ] ; public bool MoveNext ( ) { if ( index < array.Length - 1 ) { index++ ; return true ; } index = -1 ; return false ; } } var collection = new Collection ( ) ; while ( collection.MoveNext ( ) ) { object item = collection.Current ; Console.WriteLine ( item ) ; } | Why do we need two interfaces to enumerate a collection ? |
C_sharp : I have an array of { 0,1,2,3 } and want to shuffle it . This is working pretty wellsome of the time . However , I 'm finding that it often produces a stack of { 1,2,3,0 } where 0 is just placed on the back of the stack . In fact , often enough that this does n't appear random at all . An `` original sequence of 3 in the new randomized array '' is not desired.Is there anyway to improve this so that : An item is never in its original positionA stack of 3 sequential items ( from the original sequence is neverallowed ) ( or any number of sequential original items ) It could be 6 items or 10 items in the array , but what I 'm working with currently is just 4 items . C # or VB.net are fine . <code> Public Function ShuffleArray ( ByVal items ( ) As Integer ) As Integer ( ) Dim ptr As Integer Dim alt As Integer Dim tmp As Integer Dim rnd As New Random ( ) ptr = items.Length Do While ptr > 1 ptr -= 1 alt = rnd.Next ( ptr - 1 ) tmp = items ( alt ) items ( alt ) = items ( ptr ) items ( ptr ) = tmp Loop Return itemsEnd Function | ensuring a sequential stack of 3 does n't appear in a shuffled array of 4 ? |
C_sharp : I am new to GraphQL , when I try to upgrade .net core version from 2.2 to 3.0I got problem about UI display on /graphql page when using UseGraphiQlAPI is working normally but the UI is display incorrect.I googled for find out solutions , but nothing really helpful.Here is my config for graphql : Any help is greatly appreciated , thanks . <code> services.AddRazorPages ( ) .SetCompatibilityVersion ( CompatibilityVersion.Version_3_0 ) ; app.UseGraphiQLServer ( new GraphiQLOptions ( ) ) ; app.UseGraphiQl ( `` /graphiql '' , `` /graphql '' ) ; app.UseEndpoints ( x = > { x.MapControllers ( ) ; } ) ; | Upgrade GraphQL from .NET core 2.2 to 3.0 |
C_sharp : Been coding .net for years now yet I feel like a n00b . Why is the following code failing ? UpdateApproved the answer from CodeInChaos . Reason for the 16 bytes becomming 32 bytes can be read in his answer . Also stated in the answer : the default constructor of UTF8Encoding has error checking disabledIMHO the UTF8 encoder should throw exception when trying to encode a byte array to string that contains invalid bytes . To make the .net framework behave properly the code should have been written as follows <code> byte [ ] a = Guid.NewGuid ( ) .ToByteArray ( ) ; // 16 bytes in arraystring b = new UTF8Encoding ( ) .GetString ( a ) ; byte [ ] c = new UTF8Encoding ( ) .GetBytes ( b ) ; Guid d = new Guid ( c ) ; // Throws exception ( 32 bytes recived from c ) byte [ ] a = Guid.NewGuid ( ) .ToByteArray ( ) ; string b = new UTF8Encoding ( false , true ) .GetString ( a ) ; // Throws exception as expected byte [ ] c = new UTF8Encoding ( false , true ) .GetBytes ( b ) ; Guid d = new Guid ( c ) ; | It sould be so obvious , but why does this fail ? |
C_sharp : I 'm navigating the ins and outs of ref returns , and am having trouble emitting a dynamic method which returns by ref.Handcrafted lambdas and existing methods work as expected : But emitting a dynamic method fails . Note : I 'm using Sigil here . Apologies , I 'm less familiar with System.Reflection.Emit.This fails at NewDynamicMethod , throwing 'The return Type contains some invalid type ( i.e . null , ByRef ) ' . Which makes sense , since I understand that under the hood WidgetMeasurer returns an Int32 & .The question is , is there some first- or third-party technique I can employ to emit code mimicking the first two examples ( which I empirically know work correctly ) ? If not , is this restriction a logical one ? EDIT : I 've tried the equivalent System.Reflection.Emit code and got the same exception ( as expected ) : <code> class Widget { public int Length ; } delegate ref int WidgetMeasurer ( Widget w ) ; WidgetMeasurer GetMeasurerA ( ) { return w = > ref w.Length ; } static ref int MeasureWidget ( Widget w ) = > ref w.Length ; WidgetMeasurer GetMeasurerB ( ) { return MeasureWidget ; } WidgetMeasurer GetMeasurerC ( ) { FieldInfo lengthField = typeof ( Widget ) .GetField ( nameof ( Widget.Length ) ) ; var emitter = Emit < WidgetMeasurer > .NewDynamicMethod ( ) .LoadArgument ( 0 ) .LoadFieldAddress ( lengthField ) .Return ( ) ; return emitter.CreateDelegate ( ) ; } WidgetMeasurer GetMeasurerD ( ) { FieldInfo lengthField = typeof ( Widget ) .GetField ( nameof ( Widget.Length ) ) ; Type returnType = typeof ( int ) .MakeByRefType ( ) ; Type [ ] paramTypes = { typeof ( Widget ) } ; DynamicMethod method = new DynamicMethod ( `` '' , returnType , paramTypes ) ; ILGenerator il = method.GetILGenerator ( ) ; il.Emit ( OpCodes.Ldarg_0 ) ; il.Emit ( OpCodes.Ldflda , lengthField ) ; il.Emit ( OpCodes.Ret ) ; return ( WidgetMeasurer ) method.CreateDelegate ( typeof ( WidgetMeasurer ) ) ; } | How can I emit a dynamic method returning a ref ? |
C_sharp : I try to Delete a Row from the Database on the phpAdmin the Query is workingfine , but when I execute it with the Code : I get theError : Destination array is not long enough to copy all the items in the collection . Check array index and length.I Insert the to deleting user before without any trouble.The Database has an UserID with properties Unique , Int ( Length 9 ) and Auto-Increment and a UserName from type Char.My Question is : Why I ca n't receive the userID and how can I receive it ? EditI ca n't receive any integer or date data only varchar.Here is the Database creation query : Creation Query <code> MySqlCommand getUserID = new MySqlCommand ( `` SELECT UserID FROM User '' , connection ) ; MySqlDataReader reader = getUserID.ExecuteReader ( ) ; | MySqlException on ExecuteReader by Selecting UserID ( PK ) |
C_sharp : I have a DLL written in C # .NET which exposes a COM interface , so a vb6 application can call my DLL . This interface looks like : This works fine . But each time I build this DLL without changing the interface ( because I had to fix something somewhere in the logic ) the reference with the vb6 application is broken and we need to recompile the vb6 application.Does anyone know what I am doing wrong ? 'Cause we had vb.net DLL 's which did n't break the reference after recompile due to fixed GUIDs . Any help would be much appreciated.UpdateBoth vb6 app and DLL are operational . But when I recompile the DLL and test it on our testserver via the vb6 application I get an automation error ( which usually means the reference is broken and you need to recompile the vb6 app aswell ) <code> [ System.Runtime.InteropServices.Guid ( `` 3D2C106C-097F-4ED7-9E4F-CDBC6A43BDC4 '' ) ] public interface IZDPharmaManager { [ System.Runtime.InteropServices.DispId ( 2 ) ] SearchPatientEventArgs FoundPatient { get ; set ; } [ System.Runtime.InteropServices.DispId ( 3 ) ] IntPtr Start ( string server , string database , string user , string password , bool integrated , int praktijkID , string userGUID , int userID , string userName , bool hasRightToSearchPatient ) ; [ System.Runtime.InteropServices.DispId ( 4 ) ] void Stop ( ) ; [ System.Runtime.InteropServices.DispId ( 5 ) ] void InitializeSkinner ( System.Object skinnerFramework ) ; } [ System.Runtime.InteropServices.Guid ( `` 4438852E-CF2D-4DB0-8E6E-428F65A6B16C '' ) ] [ InterfaceType ( ComInterfaceType.InterfaceIsIDispatch ) ] public interface IZDPharmaManagerEvents { [ DispId ( 1 ) ] void SearchPatient ( ZDPharmaManager sender , SearchPatientEventArgs e ) ; } [ System.Runtime.InteropServices.Guid ( `` 9297D43F-C581-3F0F-AA60-9506C6B77B5F '' ) ] [ ClassInterface ( ClassInterfaceType.None ) ] public class SearchPatientEventArgs : WebHIS.ZDPharmaceutisch.ISearchPatientEventArgs { public SearchPatientEventArgs ( ) { //Nodig voor COM . } public int ID { get ; set ; } public string FullName { get ; set ; } public string OwnName { get ; set ; } public string PartnerName { get ; set ; } public string DateOfBirth { get ; set ; } public string ZipCode { get ; set ; } public string HouseNumber { get ; set ; } public string BSN { get ; set ; } } public delegate void SearchPatientEventHandler ( ZDPharmaManager sender , SearchPatientEventArgs e ) ; [ System.Runtime.InteropServices.Guid ( `` 465AC7EC-27EF-3D95-AAA6-29D01FCF15A1 '' ) ] [ ClassInterface ( ClassInterfaceType.None ) ] [ ComSourceInterfaces ( typeof ( IZDPharmaManagerEvents ) ) ] public class ZDPharmaManager : WebHIS.ZDPharmaceutisch.IZDPharmaManager { public event SearchPatientEventHandler SearchPatient = null ; public SearchPatientEventArgs FoundPatient { get ; set ; } //private MainForm GraphicalInterface { get ; set ; } private ChoosePatient GraphicalInterface { get ; set ; } public ZDPharmaManager ( ) { //Nodig voor COM . } # region IZDPharmaManager Members public IntPtr Start ( string server , string database , string user , string password , bool integrated , int praktijkID , string userGUID , int userID , string userName , bool hasRightToSearchPatient ) { //Zet connectiestring . DAL.DAC.CnnInfo = new System.Data.SqlClient.SqlConnectionStringBuilder ( ) { DataSource = server , InitialCatalog = database , UserID = user , Password = password , IntegratedSecurity = integrated } ; DAL.DAC.PracticeID = praktijkID ; DAL.DAC.UserGUID = userGUID ; DAL.DAC.UserID = userID ; DAL.DAC.UserName = userName ; DAL.DAC.HasRightToSearchPatient = hasRightToSearchPatient ; //Apotheek IDs ophalen en bewaren . DAL.DAC.PharmacyIDs = DAL.PracticeDAO.GetPharmacyByPracticeID ( praktijkID ) ; //Initialiseer grafische interface . //this.GraphicalInterface = new MainForm ( ) ; this.GraphicalInterface = new ChoosePatient ( ) ; //Haal ongekoppelde afhaalberichten op . this.GraphicalInterface.Patients = new VML.PatientsVM ( this ) ; //Toon grafische interface . this.GraphicalInterface.Show ( ) ; return this.GraphicalInterface.Handle ; } public void Stop ( ) { foreach ( var item in this.SearchPatient.GetInvocationList ( ) ) { this.SearchPatient -= ( SearchPatientEventHandler ) item ; } this.GraphicalInterface.Close ( ) ; this.GraphicalInterface = null ; this.FoundPatient = null ; } public void InitializeSkinner ( System.Object skinnerFramework ) { WebHIS.ZDPharmaceutisch.SkinnerModule.SkinFramework = ( XtremeSkinFramework.SkinFramework ) skinnerFramework ; } # endregion internal virtual void OnSearchPatient ( SearchPatientEventArgs e ) { if ( this.SearchPatient ! = null ) { this.SearchPatient ( this , e ) ; } } } | c # .net COM dll breaks reference with vb6 application |
C_sharp : I am using FxCopCmd tool for static code analysis . Since we already had a huge codebase , we baselined existing issues using baseline.exe tool that comes with FxCop.I am observing that if I add a new method to my C # class , then some of the suppression messages in GlobalSuppression.cs file stop working and I get issues for the code I have n't touched.Example : This throws following error : CA1031 : Microsoft.Design : Modify 'Program.d__0.MoveNext ( ) ' to catch a more specific exception than 'Exception ' or rethrow the exceptionTo suppress the 'CA1309 UseOrdinalStringComparison ' issue , I added following suppression message in GlobalSuppression.cs file [ module : SuppressMessage ( `` Microsoft.Globalization '' , `` CA1309 : UseOrdinalStringComparison '' , Scope= '' member '' , Target= '' ConsoleApplication1.Program.d__0.MoveNext ( ) '' , MessageId= '' System.String.Equals ( System.String , System.StringComparison ) '' , Justification= '' '' ) ] But if I add one more method in the class , then this suppression message stops working . This is because method1 is async and so a new class is created ( refer this ) in compiled code ( which was < method1 > d__0 in the first case ) . But when I add another method before method1 , then the new class created in compiled code is named < method1 > d__1 . Consequently , the suppression message is not applied and FxCop again starts showing errors in the code.Is there any way to suppress FxCop errors for async methods permanently ? <code> namespace ConsoleApplication1 { class Program { public async Task < string > method1 ( ) { string a = `` '' ; a.Equals ( `` abc '' , StringComparison.InvariantCultureIgnoreCase ) ; return a ; } static void Main ( string [ ] args ) { } } } | FxCop : Suppression message for async method |
C_sharp : I am writing a live-video imaging application and need to speed up this method . It 's currently taking about 10ms to execute and I 'd like to get it down to 2-3ms.I 've tried both Array.Copy and Buffer.BlockCopy and they both take ~30ms which is 3x longer than the manual copy.One thought was to somehow copy 4 bytes as an integer and then paste them as an integer , thereby reducing 4 lines of code to one line of code . However , I 'm not sure how to do that.Another thought was to somehow use pointers and unsafe code to do this , but I 'm not sure how to do that either.All help is much appreciated . Thank you ! EDIT : Array sizes are : inputBuffer [ 327680 ] , lookupTable [ 16384 ] , outputBuffer [ 1310720 ] EDIT : I 've updated the method keeping the same variable names so others can see how the code would translate based on HABJAN 's solution below . <code> public byte [ ] ApplyLookupTableToBuffer ( byte [ ] lookupTable , ushort [ ] inputBuffer ) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch ( ) ; sw.Start ( ) ; // Precalculate and initialize the variables int lookupTableLength = lookupTable.Length ; int bufferLength = inputBuffer.Length ; byte [ ] outputBuffer = new byte [ bufferLength * 4 ] ; int outIndex = 0 ; int curPixelValue = 0 ; // For each pixel in the input buffer ... for ( int curPixel = 0 ; curPixel < bufferLength ; curPixel++ ) { outIndex = curPixel * 4 ; // Calculate the corresponding index in the output buffer curPixelValue = inputBuffer [ curPixel ] * 4 ; // Retrieve the pixel value and multiply by 4 since the lookup table has 4 values ( blue/green/red/alpha ) for each pixel value // If the multiplied pixel value falls within the lookup table ... if ( ( curPixelValue + 3 ) < lookupTableLength ) { // Copy the lookup table value associated with the value of the current input buffer location to the output buffer outputBuffer [ outIndex + 0 ] = lookupTable [ curPixelValue + 0 ] ; outputBuffer [ outIndex + 1 ] = lookupTable [ curPixelValue + 1 ] ; outputBuffer [ outIndex + 2 ] = lookupTable [ curPixelValue + 2 ] ; outputBuffer [ outIndex + 3 ] = lookupTable [ curPixelValue + 3 ] ; //System.Buffer.BlockCopy ( lookupTable , curPixelValue , outputBuffer , outIndex , 4 ) ; // Takes 2-10x longer than just copying the values manually //Array.Copy ( lookupTable , curPixelValue , outputBuffer , outIndex , 4 ) ; // Takes 2-10x longer than just copying the values manually } } Debug.WriteLine ( `` ApplyLookupTableToBuffer ( ms ) : `` + sw.Elapsed.TotalMilliseconds.ToString ( `` N2 '' ) ) ; return outputBuffer ; } public byte [ ] ApplyLookupTableToBufferV2 ( byte [ ] lookupTable , ushort [ ] inputBuffer ) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch ( ) ; sw.Start ( ) ; // Precalculate and initialize the variables int lookupTableLength = lookupTable.Length ; int bufferLength = inputBuffer.Length ; byte [ ] outputBuffer = new byte [ bufferLength * 4 ] ; //int outIndex = 0 ; int curPixelValue = 0 ; unsafe { fixed ( byte* pointerToOutputBuffer = & outputBuffer [ 0 ] ) fixed ( byte* pointerToLookupTable = & lookupTable [ 0 ] ) { // Cast to integer pointers since groups of 4 bytes get copied at once uint* lookupTablePointer = ( uint* ) pointerToLookupTable ; uint* outputBufferPointer = ( uint* ) pointerToOutputBuffer ; // For each pixel in the input buffer ... for ( int curPixel = 0 ; curPixel < bufferLength ; curPixel++ ) { // No need to multiply by 4 on the following 2 lines since the pointers are for integers , not bytes // outIndex = curPixel ; // This line is commented since we can use curPixel instead of outIndex curPixelValue = inputBuffer [ curPixel ] ; // Retrieve the pixel value if ( ( curPixelValue + 3 ) < lookupTableLength ) { outputBufferPointer [ curPixel ] = lookupTablePointer [ curPixelValue ] ; } } } } Debug.WriteLine ( `` 2 ApplyLookupTableToBuffer ( ms ) : `` + sw.Elapsed.TotalMilliseconds.ToString ( `` N2 '' ) ) ; return outputBuffer ; } | How to optimize copying chunks of an array in C # ? |
C_sharp : I have the following objects structureIs there any way to make some kind of binding between these parent and child interfaces in DryIOC ? EDIT : I did some research and found that RegisterMany did the trick but I am a bit confused becauseIf I uncomment back individual registrations lines above , Resolve works for IAction and ICommand but not for IParser.It seems that RegisterMany is not registering parent types properly ... Edit2 : I changed my registration to following , using RegisterMappingThe item in the IParsers list is of type of the first registered mapping , in this case ICommandI am using DryIOC v2.6.2 <code> public interface IParser { } public interface IAction : IParser { } public interface ICommand : IParser { } //implpublic class Action1 : IAction { } public class Command1 : ICommand { } //registrationcontainer.Register < IAction , Action1 > ( ) ; container.Register < ICommand , Command1 > ( ) ; //resolvevar parsersList = container.Resolve < IList < IParser > > ( ) //expected : parsersList.Count=2 actual count=0 //registration//container.Register < IAction , Action1 > ( ) ; //if I drop these two lines \_____//container.Register < ICommand , Command1 > ( ) ; / |container.RegisterMany < Action1 > ( ) ; // and use these lines |container.RegisterMany < Command1 > ( ) ; |//resolve |var parsersList = container.Resolve < IList < IParser > > ( ) //WORKS Count = 2 |container.Resolve < IAction > ( ) //not working Unable to resolve IAction < -- -|container.Resolve < ICommand > ( ) //Same here for ICommand < -- -|container.Resolve < IParser > ( ) //not working either container.Register < IAction , Action1 > ( ) ; container.Register < ICommand , Command1 > ( ) ; container.RegisterMapping < IParsable , ICommand > ( ) ; //1st registered mappingcontainer.RegisterMapping < IParsable , IAction > ( ) ; container.Resolve < IList < IParser > > ( ) .Count = 1 //instead of 2 . | How to resolve using parent hierarchy interfaces using DryIOC |
C_sharp : Note 1 : Here CPS stands for `` continuation passing style '' I would be very interested in understanding how to hook into C # async machinery.Basically as I understand C # async/await feature , the compiler is performing a CPS transform and then passes the transformed code to a contextual object that manages the scheduling of tasks on various threads.Do you think it is possible to leverage that compiler feature to createpowerful combinators while leaving aside the default threading aspect ? An example would be something that can derecursify and memoize a method like I managed to do it with something like : ( no use of async , very kludgy ... ) or using a monad ( While < X > = Either < X , While < X > > ) a bit better but not as cute looking as the async syntax : ) I have asked this question on the blog of E. Lippert and he was kind enough to let me know it is indeed possible.The need for me arose when implementing a ZBDD library : ( a special kind of DAG ) lots of complex mutually recursive operationsstack overflows constantly on real examplesonly practical if fully memoized Manual CPS and derecursification was very tedious and error prone.The acid test for what I am after ( stack safety ) would be something like : which produces a stack overflow on Fib ( 10000 , 1 , 0 ) with the default behavior . Or even better , using the code at the beginning with memoization to compute Fib ( 10000 ) . <code> async MyTask < BigInteger > Fib ( int n ) // hypothetical example { if ( n < = 1 ) return n ; return await Fib ( n-1 ) + await Fib ( n-2 ) ; } void Fib ( int n , Action < BigInteger > Ret , Action < int , Action < BigInteger > > Rec ) { if ( n < = 1 ) Ret ( n ) ; else Rec ( n-1 , x = > Rec ( n-2 , y = > Ret ( x + y ) ) ) ; } While < X > Fib ( int n ) = > n < = 1 ? While.Return ( ( BigInteger ) n ) : from x in Fib ( n-1 ) from y in Fib ( n-2 ) select x + y ; async MyTask < BigInteger > Fib ( int n , BigInteger a , BigInteger b ) { if ( n == 0 ) return b ; if ( n == 1 ) return a ; return await Fib ( n - 1 , a + b , a ) ; } | How to use C # async/await as a stand-alone CPS transform |
C_sharp : Is there a cost in passing an object to a function that implements a particular interface where the function only accepts that interface ? Like : and I pass : which all of them implements IEnumerable . But when you pass any of those to the Change method , are they cast to IEnumerable , thus there is a cast cost but also the issue of losing their unique methods , etc ? <code> Change ( IEnumerable < T > collection ) List < T > LinkedList < T > CustomCollection < T > | C # interface question |
C_sharp : I 'm implementing an automatic `` evaluator '' for a course I 'm currently teaching . The overall idea is that every student delivers a DLL with some algorithms implemented . My evaluator loads all these DLLs using Reflection , finds the student implementations and evaluates them in a tournament . All these algorithms are black-box optimizers , which implement the following interfaceThe class definition for Function ( at least the relevant part ) is : As you can see , I need to pass a Function instance to these metaheuristics . These functions are implemented by myself . Most of them are in some sense random , that is , I choose a random optimum point in the function constructor . That is why you can see an xopt field in the class . The problem is , I do n't want my students to be able to access the xopt or fopt fields by Reflection or any other technique , since that would be cheating , or at least , find out if they do it so I can punish them accordingly ; ) .So , the general question is : Is there any way to disallow the use of Reflection in a piece of code I have dynamically loaded , or in any other sense disallow this code from accessing private fields ( cheating ) .Thanks in advance . <code> public interface IContinuousMetaheuristic { // ... Some unimportant properties Vector Evaluate ( Function function , int maxEvaluations , ... ) ; } public class Function : { private Vector xopt ; // The optimum point private double fopt ; // The optimum value public double Evaluate ( Vector x ) ; } | Avoiding user code calling to Reflection in C # |
C_sharp : Today I was debugging some code of mine that builds a few ExpressionTrees , compiles them to callable Delegates and calls them afterwards if required . While doing this I encountered a FatalExecutionEngineError stepping through the code : At first I was a little bit shocked since I had no idea what could have been possibly wrong with my Expressions , they looked all fine . Then I found out that this only happens in the following situation : Method A is a static method that is called and generates the ExpressionTree , which can possibly contain an Expression.Call ( ) to Method A again . So after I compile the Lambda for the ExpressionTree , the generated Delegate ( let 's call it Method B ) may possible cause recursion if I call it from within this method ... ( Method A - > [ Generated ] Method B - > Method A ) ... .which is totally possible in my scenario . As described above I was debugging this piece of code , so I set a breakpoint in Method A.The first time Method A is called by the regular code , the breakpoint hits as usual . When Method B is called , the breakpoint hits a second time , still everything is ok.But as soon as I leave the second call with the debugger by stepping over the last line , the FatalExecutionEngineError occurs.If I run the code without debugging , or do NOT step into the recursive call to Method A , OR if I do NOT step over the last line of the method , the problem does not occur and my Expression code is executed as expected.I ca n't determine if this is an error in the VS-Debugger or the .NET Framework , or if I do something horribly , horribly wrong that only comes up when debugging the relevant lines.Here is a very bare example code you can run out of the box . I am using Visual Studio 2013 Prof Update 4 and .NET 4.5.1 . Just set a breakpoint in DoSomething ( ) and try to step through to the end - if you can ; ) Can anyone confirm a bug , or is my Expression ill-formed ? <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Linq.Expressions ; using System.Reflection ; using System.Text ; using System.Threading.Tasks ; namespace ExpressionProblem { public class MainClass { public static void DoSomething ( bool stop ) { var method = typeof ( MainClass ) .GetMethod ( `` DoSomething '' , BindingFlags.Public | BindingFlags.Static , Type.DefaultBinder , new Type [ ] { typeof ( bool ) } , null ) ; var expParam = Expression.Parameter ( typeof ( bool ) , `` stop '' ) ; var expCall = Expression.Call ( null , method , expParam ) ; var lambda = Expression.Lambda ( expCall , expParam ) ; var @ delegate = lambda.Compile ( ) ; if ( ! stop ) { @ delegate.DynamicInvoke ( true ) ; } } public static void Main ( string [ ] args ) { DoSomething ( false ) ; } } } | C # Expressions - FatalExecutionEngineError |
C_sharp : IEnumerable is a query that is lazily evaluated . But apparently my understanding is a bit flawed . I 'd expect the following to work : What am I misunderstanding here ? How can I alter the results of what this query returns ? <code> // e.Result is JSON from a server JObject data = JObject.Parse ( e.Result ) ; JsonSerializer serializer = new JsonSerializer ( ) ; // LINQ query to transform the JSON into Story objects var stories = data [ `` nodes '' ] .Select ( obj = > obj [ `` node '' ] ) .Select ( storyData = > storyOfJson ( serializer , storyData ) ) ; // set a value on each story returned by the query foreach ( Story story in stories ) { story.Vid = vid ; } // run through the query again , making sure the value was actually set foreach ( Story story in stories ) { // FAILS - story.VID is 0 Debug.Assert ( story.Vid == vid ) ; } | Changes to an IEnumerable are not being kept between queries |
C_sharp : first time posting , please be kind ! : - ) New to VB/C # , Trying to fix up a CLR function that calls a web service . I 've cobbled together the following : This will only return 4000 characters even though it is coded for sqlChars . The API call could potentially return upwards of 14MB during a full inventory pull . If I understand correctly sqlChars goes to varchar ( max ) ( or nvarchar ( max ) ) ... What am I missing here ? compiled for .Net 3.0 on sql server 2005 if that helps ... Andy <code> using System ; using System.Data ; using System.Data.SqlClient ; using System.Data.SqlTypes ; using System.Collections ; using System.Globalization ; // For the SQL Server integrationusing Microsoft.SqlServer.Server ; // Other things we need for WebRequestusing System.Net ; using System.Text ; using System.IO ; public partial class UserDefinedFunctions { // Function to return a web URL as a string value . [ Microsoft.SqlServer.Server.SqlFunction ( DataAccess = DataAccessKind.Read ) ] public static SqlChars GET ( SqlString uri , SqlString username , SqlString passwd ) { // The SqlPipe is how we send data back to the caller SqlPipe pipe = SqlContext.Pipe ; SqlChars document ; // Set up the request , including authentication WebRequest req = WebRequest.Create ( Convert.ToString ( uri ) ) ; if ( Convert.ToString ( username ) ! = null & Convert.ToString ( username ) ! = `` '' ) { req.Credentials = new NetworkCredential ( Convert.ToString ( username ) , Convert.ToString ( passwd ) ) ; } ( ( HttpWebRequest ) req ) .UserAgent = `` CLR web client on SQL Server '' ; // Fire off the request and retrieve the response . // We 'll put the response in the string variable `` document '' . WebResponse resp = req.GetResponse ( ) ; Stream dataStream = resp.GetResponseStream ( ) ; StreamReader rdr = new StreamReader ( dataStream ) ; document = new SqlChars ( rdr.ReadToEnd ( ) ) ; if ( document.IsNull ) { return SqlChars.Null ; } // Close up everything ... rdr.Close ( ) ; dataStream.Close ( ) ; resp.Close ( ) ; // .. and return the output to the caller . return ( document ) ; } | CLR function will not return more than 4000 chars |
C_sharp : I think there are people who may be able to answer this , this is a question out of curiosity : The generic CreateInstance method from System.Activator , introduced in .NET v2 has no type constraints on the generic argument but does require a default constructor on the activated type , otherwise a MissingMethodException is thrown . To me it seems obvious that this method should have a type constraint likeJust an omission or some anecdote lurking here ? UpdateAs pointed out , the compiler does not allow you to writeHowever , see comments a struct can be used as type argument to a generic method specifying a new ( ) constraint . Under this circumstance the given answer seems the only valid reason to not constrain the method ... Thanks for looking over this ! <code> Activator.CreateInstance < T > ( ) where T : new ( ) { ... } private T Create < T > ( ) where T : struct , new ( ) error CS0451 : The 'new ( ) ' constraint can not be used with the 'struct ' constraint | More trivia than really important : Why no new ( ) constraint on Activator.CreateInstance < T > ( ) ? |
C_sharp : I would like to build a facebook application similar to nametest or Meaww and almost succeeded to have my API calls to Facebook Graph API and return data from facebook.What makes me confused is the UI of aforementioned web applications . When you complete a test on Meaww or Nametests the result is represented to the user is in Image ( Jpeg ) format . I just do n't know how they manage to convert HTML to an Image on the fly with all CSS styling and etc and how they return it back to the user as an Image ? Is it possible to put this scenario into practice in ASP.NET MVC Too ? If yes , So I need a hint to do it.Below is an Image generated by Meaww as a result of playing a test.Edit : To be more specific ... I have a public async Task < ActionResult > FB_Analyse ( ) action in my controller which takes data from facebook via a Graph API call to facebook and then pass the data values to a model and at then end of Action returns a view as below : Then In my view I have this simple < div > tag with images as below : As you can see I have three different < img > tags . One is the background for two other images and two others is one Facebook user picture and second one is for facebook user friend 's picture which both placed on the top of Background Image.What I want to achieve is clear as blue sky . I want to combine these three pictures in one and then show it to the user as one image.Please help I am lost . <code> public async Task < ActionResult > FB_Analyse ( ) { var access_token = HttpContext.Items [ `` access_token '' ] .ToString ( ) ; if ( ! string.IsNullOrEmpty ( access_token ) ) { var appsecret_proof = access_token.GenerateAppSecretProof ( ) ; var fb = new FacebookClient ( access_token ) ; # region FacebookUser Name and Picture plus other Info //Get current user 's profile dynamic myInfo = await fb.GetTaskAsync ( `` me ? fields=first_name , last_name , link , locale , email , name , birthday , gender , location , age_range , about '' .GraphAPICall ( appsecret_proof ) ) ; dynamic myinfojson = JsonConvert.DeserializeObject ( myInfo.ToString ( ) ) ; ViewBag.UserName = myinfojson.name ; ViewBag.UserGender = myinfojson.gender ; //get current picture dynamic profileImgResult = await fb.GetTaskAsync ( `` { 0 } /picture ? width=200 & height=200 & redirect=false '' .GraphAPICall ( ( string ) myInfo.id , appsecret_proof ) ) ; ViewBag.ProfilePictureURL = profileImgResult.data.url ; # endregion dynamic myFeed = await fb.GetTaskAsync ( ( `` me/feed ? fields=likes { { name , pic_large } } '' ) .GraphAPICall ( appsecret_proof ) ) ; string result = myFeed.ToString ( ) ; var jsonResult = JsonConvert.DeserializeObject < RootObject > ( result ) ; var likes = new List < Datum2 > ( ) ; foreach ( var likeitem in jsonResult.data ) { if ( likeitem.likes ! = null ) { foreach ( var feedlikeitem in likeitem.likes.data ) { likes.Add ( feedlikeitem ) ; } } } return view ( likes ) ; } < div class= '' imageWrapper '' style= '' position : relative '' > < img class= '' girl img-responsive '' src= '' ~/images/TestPictures/mHiDMsL.jpg '' style= '' position : relative ; z-index : 1 ; '' / > < img src= '' @ ViewBag.Picture '' alt=.. width= '' 100 '' height= '' 100 '' style= '' position : absolute ; left:80px ; top : 80px ; z-index : 10 ; '' / > < img src= '' @ ViewBag.ProfilePictureURL '' alt=.. width= '' 200 '' height= '' 200 '' style= '' position : absolute ; left:300px ; top : 160px ; z-index : 11 ; '' / > < /div > | Is there anyway to make one image out of 3 image URLs using asp.net mvc ? |
C_sharp : Assume that I have a class that exposes the following event : How should methods that are registered to this event be named ? Do you prefer to follow the convention that Visual Studio uses when it assigns names to the methods it generates ( aka . += , Tab , Tab ) ? For example : Or do you use your own style to name these methods ? I 've tried different ways to name these methods ( like TheClassClosing , HandleClosing , etc. ) . But I have n't found a good style to indicate that the intent of a method is to handle a registered event . I personally do n't like the style ( underscore ) that Visual Studio uses to generate method names.I know that registered event-handling methods are always private and that there is no naming convention like the one for methods that raise events ( e.g. , OnClosing ) . <code> public event EventHandler Closing private void TheClass_Closing ( object sender , EventArgs e ) | Naming methods that are registered to events |
C_sharp : F # provides a feature , where a function can return another function . An example of function generating a function in F # is : The best way I could come up with to achieve the same in C # was this : Is there some other way ( /better way ) of doing this ? <code> let powerFunctionGenarator baseNumber = ( fun exponent - > baseNumber ** exponent ) ; let powerOfTwo = powerFunctionGenarator 2.0 ; let powerOfThree = powerFunctionGenarator 3.0 ; let power2 = powerOfTwo 10.0 ; let power3 = powerOfThree 10.0 ; printfn `` % f '' power2 ; printfn `` % f '' power3 ; class Program { delegate double PowerOf2 ( double exponent ) ; delegate double PowerOf3 ( double exponent ) ; delegate double PowerOfN ( double n , double exponent ) ; static void Main ( string [ ] args ) { PowerOfN powerOfN = ( a , b ) = > { return Math.Pow ( a , b ) ; } ; PowerOf2 powerOf2 = ( a ) = > { return powerOfN ( 2 , a ) ; } ; PowerOf3 powerOf3 = ( a ) = > { return powerOfN ( 3 , a ) ; } ; double result = powerOf2 ( 10 ) ; Console.WriteLine ( result ) ; result = powerOf3 ( 10 ) ; Console.WriteLine ( result ) ; } } | Best way to generate a function that generates a function in C # |
C_sharp : I 'm loading in a solution in the MSBuildWorkspace : Projects without ProjectReferences show all MetadataReferences , including mscorlib . Projects with ProjectReferences have an empty collection of MetadataReferences . As compilation works , I guess the compiler platform for some reason is not populating this collection , and I 'm wondering why ? If I remove the ProjectReferences , the MetadataReferences collection gets populated correctly.EDIT : Diagnostics contains errors for missing mscorlib-types like Object and DateTime , so the project seems to not compile because of these missing references . <code> var msWorkspace = MSBuildWorkspace.Create ( ) ; var solution = msWorkspace.OpenSolutionAsync ( solutionPath ) .Result ; | Project MetadataReferences is not populated when ProjectReferences are present |
C_sharp : I have a User entity which has a HasCompletedSecurity property which indicates whether that particular User has answered the number of security questions required by the system . The number of security questions the system requires is configurable and retrieved from a config file . How should the User class access the configured information ? I currently have an IConfigurationService interface behind which I have implementations which use the ConfigurationManager or the Azure equivalent if it is available . I 've encapsulated access to my DI container through a static InjectionService class , and am currently resolving the configured value like so : This is of course an example of the ServiceLocator anti-pattern , and I do n't like it one bit . The static dependency makes unit testing anything which uses this class awkward.I 'm using the Entity Framework and taking a cue from here I do n't want to pass my entities through a DI container to give them their dependencies , so ... how should I be accessing the configured value instead ? Edit : With this exact example to one side ( and I do appreciate the suggestions as to the correct architecture for it ) , the larger question I 'm interested in is how do you manage non-static references to services from entities ? Is the answer to just architect the entities in such a way that you never need to ? <code> public class User { private static readonly IConfigurationService _configurationService = InjectionService.Resolve < IConfigurationService > ( ) ; public bool HasCompletedSecurity { get { // Uses the static _configurationService to get the // configured value : int numberOfRequiredResponses = GetConfiguredNumberOfRequiredResponses ( ) ; return this.SecurityQuestionResponses.Count ( ) > = GetConfiguredNumberOfRequiredResponses ( ) ; } } } | Domain Driven Design : access a configured value from an Entity without using a Service Locator |
C_sharp : My code calls a WCF service that is current not running . So we should expect the EndPointNotFoundException . The using statement tries to Close ( ) the faulted connection which causes a CommunicationObjectFaultedException which is excepted . This exception is caught in a try catch block surrounding the using block : Note the service EndPoint uses a fresh Guid so it will never have a service listening.IDummyService is : This causes the Visual Studio debugger ( Visual Studio Professional 2017 15.4.1 ) to break with an `` Exception Unhandled '' popup : The exception on which Visual Studio breaks is System.ServiceModel.CommunicationObjectFaultedException which is caught in the code.Stepping to continue execution shows that catch ( CommunicationObjectFaultedException ex ) is reached . Using LinqPad to run the demo also shows that the exception is caught as expected.I also tried explicitly ( double ) closing the channel instead of using the using-block : This still causes the debugger to break on the Close statement.My Exception Settings has System.ServiceModel.CommunicationObjectFaultedException unchecked . ( When it is checked Visual studio breaks as expected and with the `` Exception Thrown '' dialog instead of the `` Exception Unhandled '' dialog ) .When I enable `` Options '' \ '' Debugging '' \ '' General '' \ '' Enable Just My Code '' the debugger does not break . However , I have async methods where the exception should leave my code and I later catch the exception when awaiting the Task . For these methods I need `` Enable Just My Code '' unchecked ; see Stop visual studio from breaking on exception in Tasks.With `` Using the New Exception Helper '' disabled ( as suggested by Jack Zhai-MSFT ) Visual Studio still breaks and it showsThe dialog provides some additional information : The exception is not caught before it crosses a managed/native boundary.I suspect that the using block probably introduces this managed/native boundary.What causes the debugger to break by mistake and how to make the debugger not break neither or handled CommunicationObjectFaultedExceptions nor on later handler async exceptions ? <code> class Program { static void Main ( ) { try { using ( ChannelFactory < IDummyService > unexistingSvc = new ChannelFactory < IDummyService > ( new NetNamedPipeBinding ( ) , `` net.pipe : //localhost/UnexistingService- '' + Guid.NewGuid ( ) .ToString ( ) ) ) { using ( IClientChannel chan = ( unexistingSvc.CreateChannel ( ) as IClientChannel ) ) { ( chan as IDummyService ) ? .Echo ( `` Hello '' ) ; } } } catch ( EndpointNotFoundException ex ) { Console.WriteLine ( `` Expected '' ) ; } catch ( CommunicationObjectFaultedException ex ) { Console.WriteLine ( `` Expected : caused by closing channel that has thrown EndPointNotFoundException '' ) ; } } } [ ServiceContract ] interface IDummyService { [ OperationContract ] string Echo ( string e ) ; } class Program { static void Main ( ) { try { using ( ChannelFactory < IDummyService > unexistingSvc = new ChannelFactory < IDummyService > ( new NetNamedPipeBinding ( ) , `` net.pipe : //localhost/UnexistingService- '' + Guid.NewGuid ( ) .ToString ( ) ) ) { IDummyService chan = null ; try { chan = unexistingSvc.CreateChannel ( ) ; chan.Echo ( `` Hello '' ) ; } catch ( EndpointNotFoundException ex ) { Console.WriteLine ( $ '' Expected : { ex.Message } '' ) ; } finally { try { ( chan as IClientChannel ) ? .Close ( ) ; } catch ( CommunicationObjectFaultedException ex ) { Console.WriteLine ( $ '' Caused by Close : { ex.Message } '' ) ; } } } } catch ( EndpointNotFoundException ex ) { Console.WriteLine ( `` Expected '' ) ; } catch ( CommunicationObjectFaultedException ex ) { Console.WriteLine ( `` Expected : caused by closing channel that has thrown EndPointNotFoundException '' ) ; } } } | Visual studio breaks on exception that IS handled with unhandled exception dialog |
C_sharp : I managed to consume a java based web service ( third party ) with WS-Security 1.1 protocol . The web service needs only to be signed over a x509 certificate , not encrypted.But I 'm getting this error : The signature confirmation elements can not occur after the primary signature.The captured server response package looks like this : The server is responding what it should but my app seems not to be interpreting it correctly . It seems that the < wsse11 : SignatureConfirmation ... / > tag must be before < ds : Signature > < /ds : Signature > tag . I could n't find any reference to a order standard of this.EDIT : Adding my code . <code> < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < soapenv : Envelope xmlns : soapenv= '' http : //www.w3.org/2003/05/soap-envelope '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' > < soapenv : Header > < wsse : Security xmlns : wsse= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd '' soapenv : mustUnderstand= '' true '' > < ds : Signature xmlns : ds= '' http : //www.w3.org/2000/09/xmldsig # '' Id= '' Signature-501 '' > < ds : SignedInfo > < ds : CanonicalizationMethod Algorithm= '' http : //www.w3.org/2001/10/xml-exc-c14n # '' / > < ds : SignatureMethod Algorithm= '' http : //www.w3.org/2000/09/xmldsig # rsa-sha1 '' / > < ds : Reference URI= '' # id-502 '' > < ds : Transforms > < ds : Transform Algorithm= '' http : //www.w3.org/2001/10/xml-exc-c14n # '' / > < /ds : Transforms > < ds : DigestMethod Algorithm= '' http : //www.w3.org/2000/09/xmldsig # sha1 '' / > < ds : DigestValue > ... < /ds : DigestValue > < /ds : Reference > < ds : Reference URI= '' # SigConf-500 '' > < ds : Transforms > < ds : Transform Algorithm= '' http : //www.w3.org/2001/10/xml-exc-c14n # '' / > < /ds : Transforms > < ds : DigestMethod Algorithm= '' http : //www.w3.org/2000/09/xmldsig # sha1 '' / > < ds : DigestValue > ... < /ds : DigestValue > < /ds : Reference > < /ds : SignedInfo > < ds : SignatureValue > ... < /ds : SignatureValue > < ds : KeyInfo Id= '' KeyId- ... '' > < wsse : SecurityTokenReference xmlns : wsu= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd '' wsu : Id= '' STRId- ... '' > < ds : X509Data > < ds : X509IssuerSerial > < ds : X509IssuerName > CN=COMODO RSA Organization Validation Secure Server CA , O=COMODO CA Limited , L=Salford , ST=Greater Manchester , C=GB < /ds : X509IssuerName > < ds : X509SerialNumber > ... < /ds : X509SerialNumber > < /ds : X509IssuerSerial > < /ds : X509Data > < /wsse : SecurityTokenReference > < /ds : KeyInfo > < /ds : Signature > < wsse11 : SignatureConfirmation xmlns : wsse11= '' http : //docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd '' xmlns : wsu= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd '' Value= '' ... '' wsu : Id= '' SigConf-500 '' / > < /wsse : Security > < /soapenv : Header > < soapenv : Body xmlns : wsu= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd '' wsu : Id= '' id-502 '' > < altaClienteResponse xmlns= '' ... '' > < altaClienteReturn > < codigoError > 7 < /codigoError > < descripcionError > El código de banco no es válido. < /descripcionError > < idTransaccion xsi : nil= '' true '' / > < /altaClienteReturn > < /altaClienteResponse > < /soapenv : Body > < /soapenv : Envelope > try { var certificate = new X509Certificate2 ( @ '' C : \Users\ ... \cert.pfx '' , PassKeyStore ) ; var binding = new CustomBinding ( ) ; var security = ( AsymmetricSecurityBindingElement ) SecurityBindingElement.CreateMutualCertificateDuplexBindingElement ( MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10 ) ; security.EndpointSupportingTokenParameters.Signed.Add ( new X509SecurityTokenParameters { InclusionMode = SecurityTokenInclusionMode.Never , ReferenceStyle = SecurityTokenReferenceStyle.Internal , } ) ; security.RecipientTokenParameters.InclusionMode = SecurityTokenInclusionMode.Never ; security.RecipientTokenParameters.ReferenceStyle = SecurityTokenReferenceStyle.Internal ; security.MessageSecurityVersion = MessageSecurityVersion . WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10 ; security.IncludeTimestamp = false ; security.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.EncryptBeforeSign ; security.RequireSignatureConfirmation = true ; security.AllowSerializedSigningTokenOnReply = true ; binding.Elements.Add ( security ) ; binding.Elements.Add ( new TextMessageEncodingBindingElement ( MessageVersion.Soap11 , Encoding.UTF8 ) ) ; binding.Elements.Add ( new HttpsTransportBindingElement ( ) ) ; var client = new SistarbancService.WsMediosPagoClient ( binding , new EndpointAddress ( new Uri ( UrlSistarbanc ) , new DnsEndpointIdentity ( `` ... '' ) , new AddressHeaderCollection ( ) ) ) ; client.ClientCredentials.ServiceCertificate.DefaultCertificate = new X509Certificate2 ( `` C : \\Users\\ ... \\servidor.cer '' ) ; client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None ; client.ClientCredentials.ClientCertificate.Certificate = certificate ; client.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign ; var response = await client.altaClienteAsync ( `` XXX '' , `` 0 '' , `` 0 '' , `` 0 '' , `` 0 '' , `` 0 '' ) ; } catch ( Exception ex ) { } | WCF Client consuming WS-Security webservice |
C_sharp : Here is a part of my code : I expect testBranches will be https : //127.0.0.1:8443/svn/CXB1/Validation/branches/test , but it is https : //127.0.0.1:8443/svn/CXB1/Validation/test . I can not understand why Uri ( Uri , string ) constructor eats the last part of the path . <code> Uri branches = new Uri ( @ '' https : //127.0.0.1:8443/svn/CXB1/Validation/branches '' ) ; Uri testBranch = new Uri ( branches , `` test '' ) ; | Uri ( Uri , String ) constructor does not works properly ? |
C_sharp : On the current project we are working on we have n't upgraded to MVC 2.0 yet so I 'm working on implementing some simple validation with the tools available in 1.0.I 'm looking for feedback on the way I 'm doing this.I have a model that represents a user profile . Inside that model I have a method that will validate all the fields and such . What I want to do is pass a controller to the validation method so that the model can set the model validation property in the controller . The goal is to get the validation from the controller into the model.Here is a quick exampleAnd my model validation signature is likeWhat issues can you see with this ? Am I way out to lunch on how I want to do this ? <code> public FooController : Controller { public ActionResult Edit ( User user ) { user.ValidateModel ( this ) ; if ( ModelState.IsValid ) ... ... . ... ... . } } public void ValidateModel ( Controller currentState ) | Simple ASP.Net MVC 1.0 Validation |
C_sharp : I tried to use firewallAPI.dll to add a rule . It works fine for calc.exe ( or some other files ) as described bellow but fails for msdtc.exe with the following exception : System.IO.FileNotFoundException : 'The system can not find the file specified . ( Exception from HRESULT : 0x80070002 ) 'Example : Note : I checked the folder and see the file is located properly ... Could anybody help to add firewall rule for Distributed Transaction Coordinator ? Maybe I should try to add another file to firewall ( not msdtc.exe ) ? <code> static void Main ( string [ ] args ) { var manager = GetFirewallManager ( ) ; if ( manager.LocalPolicy.CurrentProfile.FirewallEnabled ) { var path = @ '' C : \Windows\System32\calc.exe '' ; //var path = @ '' C : \Windows\System32\msdtc.exe '' ; // System.IO.FileNotFoundException : 'The system can not find the file specified . AuthorizeApplication ( `` Test '' , path , NET_FW_SCOPE_.NET_FW_SCOPE_ALL , NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY ) ; } } private const string CLSID_FIREWALL_MANAGER = `` { 304CE942-6E39-40D8-943A-B913C40C9CD4 } '' ; private static NetFwTypeLib.INetFwMgr GetFirewallManager ( ) { Type objectType = Type.GetTypeFromCLSID ( new Guid ( CLSID_FIREWALL_MANAGER ) ) ; return Activator.CreateInstance ( objectType ) as NetFwTypeLib.INetFwMgr ; } private const string PROGID_AUTHORIZED_APPLICATION = `` HNetCfg.FwAuthorizedApplication '' ; public static bool AuthorizeApplication ( string title , string applicationPath , NET_FW_SCOPE_ scope , NET_FW_IP_VERSION_ ipVersion ) { // Create the type from prog id Type type = Type.GetTypeFromProgID ( PROGID_AUTHORIZED_APPLICATION ) ; INetFwAuthorizedApplication auth = Activator.CreateInstance ( type ) as INetFwAuthorizedApplication ; auth.Name = title ; auth.ProcessImageFileName = applicationPath ; auth.Scope = scope ; auth.IpVersion = ipVersion ; auth.Enabled = true ; INetFwMgr manager = GetFirewallManager ( ) ; manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add ( auth ) ; return true ; } | Add a firewall rule for Distributed Transaction Coordinator ( msdtc.exe ) |
C_sharp : I have the following code : What 's the difference between passing a pointer and a ref keyword as a parameter in the method ? <code> class Program { private unsafe static void SquarePtrParam ( int* input ) { *input *= *input ; } private static void SquareRefParam ( ref int input ) { input *= input ; } private unsafe static void Main ( ) { int value = 10 ; SquarePtrParam ( & value ) ; Console.WriteLine ( value ) ; int value2 = 10 ; SquareRefParam ( ref value2 ) ; Console.WriteLine ( value2 ) ; //output 100 , 100 Console.ReadKey ( ) ; } } | What is the difference between referencing a value using a pointer and a ref keyword |
C_sharp : When generating GetHashCode ( ) implementation for anonymous class , Roslyn computes the initial hash value based on the property names . For example , the class generated foris going to have the following GetHashCode ( ) method : But if we change the property names , the initial value changes : What 's the reason behind this behaviour ? Is there some problem with just picking a big [ prime ? ] number and using it for all the anonymous classes ? <code> var x = new { Int = 42 , Text = `` 42 '' } ; public override in GetHashCode ( ) { int hash = 339055328 ; hash = hash * -1521134295 + EqualityComparer < int > .Default.GetHashCode ( Int ) ; hash = hash * -1521134295 + EqualityComparer < string > .Default.GetHashCode ( Text ) ; return hash ; } var x = new { Int2 = 42 , Text2 = `` 42 '' } ; public override in GetHashCode ( ) { int hash = 605502342 ; hash = hash * -1521134295 + EqualityComparer < int > .Default.GetHashCode ( Int2 ) ; hash = hash * -1521134295 + EqualityComparer < string > .Default.GetHashCode ( Text2 ) ; return hash ; } | Why does initial hash value in GetHashCode ( ) implementation generated for anonymous class depend on property names ? |
C_sharp : I need to find out what the current Row index from within a foreach loop.An exception can occur at any point within the try/catch block , but if I use an incremental counter within the foreach loop , and the exception occurs outside of the loop , I 'll get an invalid row because I 've moved the pointer along by one.I know that I can declare a DataRow outside of the foreach scope , but the foreach is within a try/catch block . I need to pass the Row index so I can use it in the catch statement . I should say that my DataTable is at class level scope . Is this really the only way to get the current Row index ? Or is there a cleaner implementation ? EDITSo , giving more thought to this , I could use an int to store the current row value , and increment this value like so : However , if the foreach does n't throw the exception , then the value of i will be greater than the actual number of rows in the table . Obviously , I could do i -- ; after the foreach loop , but this seems like a really dirty hack . <code> foreach ( DataRow row in DataTable [ 0 ] .Rows ) { // I do stuff in here with the row , and if it throws an exception // I need to pass out the row Index value to the catch statement } int i = 0 ; try { // Some code here - which could throw an exception foreach ( DataRow row in DataTables [ 0 ] .Rows ) { // My stuff i++ ; } // Some code here - which could throw an exception } catch { // Use the counter DataRow row = DataTables [ 0 ] .Rows [ i ] ; } | Clean implementation of storing current row index |
C_sharp : I use EntityFramework 4 + generated POCOs with Lazy loading disabled.Let 's say there are SQL tables named Table1 , Table2 , Table3 and Table4 and assume they contain some data.Let 's assume the simplified POCO representation of these tables looks like this : If the following code would be executed : EF would generate the following SQL statement : and the query would return the expected data.However , if the following code would be executed : EF would generate the following SQL statement : and the query would return nothing.Why could this be happening ? EDITFollowing are SQL statements to create the above tables : EDIT 2This query will also return no records and can serve as a minimal example : Generated SQL : Additionally , here is an excerpt from the .edmx : <code> public class Table1 { public int ID ; public DateTime TableDate ; public int Table2ID ; public Table2 Table2 ; public ICollection < Table3 > Table3s ; } public class Table2 { public int ID ; public string SomeString ; public int Table4ID ; public Table4 Table4 ; } public class Table3 { public int ID ; public int Table1ID ; public Table1 Table1 ; public decimal SomeDecimal ; } public decimal Table4 { public int ID ; public string SomeName ; } Database DB = new Database ( ) ; // object contextvar result = DB.Table1 .Where ( x = > x.TableDate > = DateTime.MinValue ) ; exec sp_executesql N'SELECT [ Extent1 ] . [ ID ] AS [ ID ] , [ Extent1 ] . [ TableDate ] AS [ TableDate ] , [ Extent1 ] . [ Table2ID ] As [ Table2ID ] FROM [ dbo ] . [ Table1 ] AS [ Extent1 ] WHERE ( [ Extent1 ] . [ TableDate ] > = @ p__linq__0 ) ' , N ' @ p__linq__0 datetime2 ( 7 ) ' , @ p__linq__0='0001-01-01 00:00:00 ' Database DB = new Database ( ) ; // object contextvar result = DB.Table1 .Include ( `` Table2 '' ) .Include ( `` Table2.Table4 '' ) .Include ( `` Table3 '' ) .Where ( x = > x.TableDate > = DateTime.MinValue ) ; exec sp_executesql N'SELECT [ Project1 ] . [ ID2 ] AS [ ID ] , [ Project1 ] . [ ID ] AS [ ID1 ] , [ Project1 ] . [ TableDate ] AS [ TableDate ] , [ Project1 ] . [ ID1 ] AS [ ID2 ] , [ Project1 ] . [ SomeString ] AS [ SomeString ] , [ Project1 ] . [ Table4ID ] AS [ Table4ID ] , [ Project1 ] . [ ID3 ] AS [ ID3 ] , [ Project1 ] . [ SomeName ] AS [ SomeName ] , [ Project1 ] . [ ID4 ] AS [ ID4 ] , [ Project1 ] . [ SomeDecimal ] AS [ SomeDecimal ] , [ Project1 ] . [ Table1ID ] AS [ Table1ID ] FROM ( SELECT [ Extent1 ] . [ ID ] AS [ ID ] , [ Extent1 ] . [ TableDate ] AS [ TableDate ] , [ Extent2 ] . [ ID ] AS [ ID1 ] , [ Extent2 ] . [ SomeString ] AS [ SomeString ] , [ Extent2 ] . [ Table4ID ] AS [ Table4ID ] , [ Extent3 ] . [ ID ] AS [ ID2 ] , [ Extent4 ] . [ ID ] AS [ ID3 ] , [ Extent4 ] . [ SomeName ] AS [ SomeName ] , [ Extent5 ] . [ ID ] AS [ ID4 ] , [ Extent5 ] . [ SomeDecimal ] AS [ SomeDecimal ] , [ Extent5 ] . [ Table1ID ] AS [ Table1ID ] , CASE WHEN ( [ Extent5 ] . [ ID ] IS NULL ) THEN CAST ( NULL AS int ) ELSE 1 END AS [ C1 ] FROM [ dbo ] . [ Table1 ] AS [ Extent1 ] INNER JOIN [ dbo ] . [ Table2 ] AS [ Extent2 ] ON [ Extent1 ] . [ Table2ID ] = [ Extent2 ] . [ ID ] LEFT OUTER JOIN [ dbo ] . [ Table2 ] AS [ Extent3 ] ON [ Extent1 ] . [ Table2ID ] = [ Extent3 ] . [ ID ] LEFT OUTER JOIN [ dbo ] . [ Table4 ] AS [ Extent4 ] ON [ Extent3 ] . [ Table4ID ] = [ Extent4 ] . [ ID ] LEFT OUTER JOIN [ dbo ] . [ Table3 ] AS [ Extent5 ] ON [ Extent1 ] . [ ID ] = [ Extent5 ] . [ Table1ID ] WHERE ( [ Extent1 ] . [ TableDate ] > = @ p__linq__0 ) ) AS [ Project1 ] ORDER BY [ Project1 ] . [ ID2 ] ASC , [ Project1 ] . [ ID ] ASC , [ Project1 ] . [ ID1 ] ASC , [ Project1 ] . [ ID3 ] ASC , [ Project1 ] . [ C1 ] ASC ' , N ' @ p__linq__0 datetime2 ( 7 ) ' , @ p__linq__0='0001-01-01 00:00:00 ' CREATE TABLE [ dbo ] . [ Table1 ] ( [ ID ] [ int ] IDENTITY ( 1,1 ) NOT NULL , [ Table2ID ] [ int ] NOT NULL , [ TableDate ] [ date ] NOT NULL , CONSTRAINT [ PK_Table1 ] PRIMARY KEY CLUSTERED ( [ ID ] ASC ) WITH ( PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [ PRIMARY ] ) ON [ PRIMARY ] ALTER TABLE [ dbo ] . [ Table1 ] WITH NOCHECK ADD CONSTRAINT [ FK_Table1_Table2 ] FOREIGN KEY ( [ Table2ID ] ) REFERENCES [ dbo ] . [ Table2 ] ( [ ID ] ) ALTER TABLE [ dbo ] . [ Table1 ] CHECK CONSTRAINT [ FK_Table1_Table2 ] CREATE TABLE [ dbo ] . [ Table2 ] ( [ ID ] [ int ] NOT NULL , [ SomeString ] [ nvarchar ] ( 50 ) NOT NULL , [ Table4ID ] [ int ] NULL , CONSTRAINT [ PK_Table2 ] PRIMARY KEY CLUSTERED ( [ ID ] ASC ) WITH ( PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [ PRIMARY ] ) ON [ PRIMARY ] ALTER TABLE [ dbo ] . [ Table2 ] WITH NOCHECK ADD CONSTRAINT [ FK_Table2_Table4 ] FOREIGN KEY ( [ Table4ID ] ) REFERENCES [ dbo ] . [ Table4 ] ( [ ID ] ) ON UPDATE CASCADEALTER TABLE [ dbo ] . [ Table2 ] CHECK CONSTRAINT [ FK_Table2_Table4 ] CREATE TABLE [ dbo ] . [ Table3 ] ( [ ID ] [ int ] IDENTITY ( 1,1 ) NOT NULL , [ SomeDecimal ] [ decimal ] ( 18 , 4 ) NOT NULL , [ Table1ID ] [ int ] NOT NULL , CONSTRAINT [ PK_Table3 ] PRIMARY KEY CLUSTERED ( [ ID ] ASC ) WITH ( PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [ PRIMARY ] ) ON [ PRIMARY ] ALTER TABLE [ dbo ] . [ Table3 ] WITH NOCHECK ADD CONSTRAINT [ FK_Table3_Table1 ] FOREIGN KEY ( [ Table1ID ] ) REFERENCES [ dbo ] . [ Table1 ] ( [ ID ] ) ON DELETE CASCADEALTER TABLE [ dbo ] . [ Table3 ] CHECK CONSTRAINT [ FK_Table3_Table1 ] CREATE TABLE [ dbo ] . [ Table4 ] ( [ ID ] [ int ] NOT NULL , [ SomeName ] [ nvarchar ] ( 50 ) NOT NULL , CONSTRAINT [ PK_Table4 ] PRIMARY KEY CLUSTERED ( [ ID ] ASC ) WITH ( PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [ PRIMARY ] ) ON [ PRIMARY ] Database DB = new Database ( ) ; var result = DB.Table1 .Include ( `` Table2 '' ) .Where ( x = > x.TableDate > = DateTime.MinValue ) ; exec sp_executesql N'SELECT [ Extent1 ] . [ ID ] AS [ ID ] , [ Extent1 ] . [ Table2ID ] AS [ Table2ID ] , [ Extent1 ] . [ TableDate ] AS [ TableDate ] , [ Extent2 ] . [ ID ] AS [ ID1 ] , [ Extent2 ] . [ SomeString ] AS [ SomeString ] , [ Extent2 ] . [ Table4ID ] AS [ Table4ID ] , FROM [ dbo ] . [ Table1 ] AS [ Extent1 ] INNER JOIN [ dbo ] . [ Table2 ] AS [ Extent2 ] ON [ Extent1 ] . [ Table2ID ] = [ Extent2 ] . [ ID ] WHERE ( [ Extent1 ] . [ TableDate ] > = @ p__linq__0 ) ' , N ' @ p__linq__0 datetime2 ( 7 ) ' , @ p__linq__0='0001-01-01 00:00:00 ' < EntityContainer > < AssociationSet Name= '' FK_Table1_Table2 '' Association= '' MyModel.Store.FK_Table1_Table2 '' > < End Role= '' Table2 '' EntitySet= '' Table2 '' / > < End Role= '' Table1 '' EntitySet= '' Table1 '' / > < /AssociationSet > < /EntityContainer > < ! -- ... -- > < EntityType Name= '' Table2 '' > < Key > < PropertyRef Name= '' ID '' / > < /Key > < Property Name= '' ID '' Type= '' int '' Nullable= '' false '' / > < Property Name= '' SomeString '' Type= '' nvarchar '' Nullable= '' false '' MaxLength= '' 50 '' / > < Property Name= '' Table4ID '' Type= '' int '' / > < /EntityType > < ! -- ... -- > < EntityType Name= '' Table1 '' > < Key > < PropertyRef Name= '' ID '' / > < /Key > < Property Name= '' ID '' Type= '' int '' Nullable= '' false '' StoreGeneratedPattern= '' Identity '' / > < Property Name= '' TableDate '' Type= '' date '' Nullable= '' false '' / > < Property Name= '' Table2ID '' Type= '' int '' Nullable= '' false '' / > < /EntityType > < ! -- ... -- > < Association Name= '' FK_Table1_Table2 '' > < End Role= '' Table2 '' Type= '' MyModel.Store.Table2 '' Multiplicity= '' 1 '' / > < End Role= '' Table1 '' Type= '' MyModel.Store.Table1 '' Multiplicity= '' * '' / > < ReferentialConstraint > < Principal Role= '' Table2 '' > < PropertyRef Name= '' ID '' / > < /Principal > < Dependent Role= '' Table1 '' > < PropertyRef Name= '' Table2ID '' / > < /Dependent > < /ReferentialConstraint > < /Association > | Query returning nothing when there is data in the database |
C_sharp : Update ! See my dissection of a portion of the C # spec below ; I think I must be missing something , because to me it looks like the behavior I 'm describing in this question actually violates the spec.Update 2 ! OK , upon further reflection , and based on some comments , I think I now understand what 's going on . The words `` source type '' in the spec refer to the type being converted from -- i.e. , Type2 in my example below -- which simply means that the compiler is able to narrow the candidates down to the two operators defined ( since Type2 is the source type for both ) . However , it can not narrow the choices any further . So the key words in the spec ( as it applies to this question ) are `` source type '' , which I previously misinterpreted ( I think ) to mean `` declaring type . `` Original QuestionSay I have these types defined : Then say I do this : Obviously this is ambiguous , as it is not clear which implicit operator should be used . My question is -- since I can not see any way to resolve this ambiguity ( it is n't like I can perform some explicit cast to clarify which version I want ) , and yet the class definitions above do compile -- why would the compiler allow those matching implicit operators at all ? DissectionOK , I 'm going to step through the excerpt of the C # spec quoted by Hans Passant in an attempt to make sense of this . Find the set of types , D , from which user-defined conversion operators will be considered . This set consists of S ( if S is a class or struct ) , the base classes of S ( if S is a class ) , and T ( if T is a class or struct ) .We 're converting from Type2 ( S ) to Type1 ( T ) . So it seems that here D would include all three types in the example : Type0 ( because it is a base class of S ) , Type1 ( T ) and Type2 ( S ) . Find the set of applicable user-defined conversion operators , U . This set consists of the user-defined implicit conversion operators declared by the classes or structs in D that convert from a type encompassing S to a type encompassed by T. If U is empty , the conversion is undefined and a compile-time error occurs.All right , we 've got two operators satisfying these conditions . The version declared in Type1 meets the requirements because Type1 is in D and it converts from Type2 ( which obviously encompasses S ) to Type1 ( which is obviously encompassed by T ) . The version in Type2 also meets the requirements for exactly the same reasons . So U includes both of these operators.Lastly , with respect to finding the most specific `` source type '' SX of the operators in U : If any of the operators in U convert from S , then SX is S.Now , both operators in U convert from S -- so this tells me that SX is S.Does n't this mean that the Type2 version should be used ? But wait ! I 'm confused ! Could n't I have only defined Type1 's version of the operator , in which case , the only remaining candidate would be Type1 's version , and yet according to the spec SX would be Type2 ? This seems like a possible scenario in which the spec mandates something impossible ( namely , that the conversion declared in Type2 should be used when in fact it does not exist ) . <code> class Type0 { public string Value { get ; private set ; } public Type0 ( string value ) { Value = value ; } } class Type1 : Type0 { public Type1 ( string value ) : base ( value ) { } public static implicit operator Type1 ( Type2 other ) { return new Type1 ( `` Converted using Type1 's operator . `` ) ; } } class Type2 : Type0 { public Type2 ( string value ) : base ( value ) { } public static implicit operator Type1 ( Type2 other ) { return new Type1 ( `` Converted using Type2 's operator . `` ) ; } } Type2 t2 = new Type2 ( `` B '' ) ; Type1 t1 = t2 ; | Equivalent implicit operators : why are they legal ? |
C_sharp : I came accross the following code today and I did n't like it . It 's fairly obvious what it 's doing but I 'll add a little explanation here anyway : Basically it reads all the settings for an app from the DB and the iterates through all of them looking for the DB Version and the APP Version then sets some variables to the values in the DB ( to be used later ) .I looked at it and thought it was a bit ugly - I do n't like switch statements and I hate things that carry on iterating through a list once they 're finished . So I decided to refactor it.My question to all of you is how would you refactor it ? Or do you think it even needs refactoring at all ? Here 's the code : <code> using ( var sqlConnection = new SqlConnection ( Lfepa.Itrs.Framework.Configuration.ConnectionString ) ) { sqlConnection.Open ( ) ; var dataTable = new DataTable ( `` Settings '' ) ; var selectCommand = new SqlCommand ( Lfepa.Itrs.Data.Database.Commands.dbo.SettingsSelAll , sqlConnection ) ; var reader = selectCommand.ExecuteReader ( ) ; while ( reader.Read ( ) ) { switch ( reader [ SettingKeyColumnName ] .ToString ( ) .ToUpper ( ) ) { case DatabaseVersionKey : DatabaseVersion = new Version ( reader [ SettingValueColumneName ] .ToString ( ) ) ; break ; case ApplicationVersionKey : ApplicationVersion = new Version ( reader [ SettingValueColumneName ] .ToString ( ) ) ; break ; default : break ; } } if ( DatabaseVersion == null ) throw new ApplicationException ( `` Colud not load Database Version Setting from the database . `` ) ; if ( ApplicationVersion == null ) throw new ApplicationException ( `` Colud not load Application Version Setting from the database . `` ) ; } | A C # Refactoring Question |
C_sharp : Suppose I have following program : I can not understand compiled il code ( it uses too extra code ) . Here is simplified version : Why does compiler create not static equal methods b/b1 ? Equal means that they have the same code <code> static void SomeMethod ( Func < int , int > otherMethod ) { otherMethod ( 1 ) ; } static int OtherMethod ( int x ) { return x ; } static void Main ( string [ ] args ) { SomeMethod ( OtherMethod ) ; SomeMethod ( x = > OtherMethod ( x ) ) ; SomeMethod ( x = > OtherMethod ( x ) ) ; } class C { public static C c ; public static Func < int , int > foo ; public static Func < int , int > foo1 ; static C ( ) { c = new C ( ) ; } C ( ) { } public int b ( int x ) { return OtherMethod ( x ) ; } public int b1 ( int x ) { return OtherMethod ( x ) ; } } static void Main ( ) { SomeMethod ( new Func < int , int > ( OtherMethod ) ) ; if ( C.foo ! = null ) SomeMethod ( C.foo ) else { C.foo = new Func < int , int > ( c , C.b ) SomeMethod ( C.foo ) ; } if ( C.foo1 ! = null ) SomeMethod ( C.foo1 ) else { C.foo1 = new Func < int , int > ( c , C.b1 ) SomeMethod ( C.foo1 ) ; } } | Weird behaviour of c # compiler due caching delegate |
C_sharp : Any suggestion how to make the below query more `` readable '' ? Its difficult to read with the long code of condition and value . <code> var result = result .OrderBy ( a = > ( conditionA ) ? valueA : ( conditionB ? valueB : ( conditionC ? ( conditionD ? valueC : valueD ) : valueE ) ) ) ; | Ternary operator difficult to read |
C_sharp : I hear that Nullable < T > is a C # generic class and it does not work with COM - like any other generic class.Well , in my C # class library I have : Surprisingly that compiles and I am able to attach references to my COMClass library in VBE.I know that : VBA does not list .GetNullable ( ) in the list of members on Object Browser ( even with show hidden members ticked ) VBA does not list .GetNullable ( ) in the intelli-sense drop downbut why : does not throw a rather expected Object does n't support this property or method ? as opposed to : Can anyone explain why ? I am suspicious that it has something to do with ComInterfaceType Enumeration because both : InterfaceIsDual & InterfaceIsIDispatch act just like I described above but : InterfaceIsIUnknown actually does n't seem to marshal/touch the GetNullable ( ) and the expected error is thrown ... Can anyone explain this behaviour ? <code> [ InterfaceType ( ComInterfaceType.InterfaceIsDual ) , Guid ( `` 2FCEF713-CD2E-4ACB-A9CE-E57E7F51E72E '' ) ] public interface ICOMClass { int ? GetNullable ( ) ; } [ ClassInterface ( ClassInterfaceType.None ) ] [ Guid ( `` 57BBEC44-C6E6-4E14-989A-B6DB7CF6FBEB '' ) ] public class COMClass : ICOMClass { public int ? GetNullable ( ) { int ? hello = null ; return hello ; } } Dim c as new COMClassc.GetNullable c.NonExistingMethod | How does a COM server marshal nullable in C # class library with different ComInterfaceType Enumerations ? |
C_sharp : Does using the braced initializer on a collection type set it 's capacity or do you still need to specify it ? That is , does : result in the same as this : <code> var list = new List < string > ( ) { `` One '' , `` Two '' } ; var list = new List < string > ( 2 ) { `` One '' , `` Two '' } ; | Does using the braced initializer on collection types set the initial capacity ? |
C_sharp : Had to pick up a bit of work from another developer so just trying to wrap my head round it all ! But I 'm having issues building an Azure Functions project and continuously getting a error coming form Microsoft.NET.Sdk.Functions.Build.targets , specifically unable to resolve a reference to Microsoft.Azure.WebJobs.Extensions.So far I have attempted re-installing the Nuget Package , Re-Starting Visual Studio , my machine yada-yada.I would welcome any suggestions and appreciate your time ! Full Error Below <code> Severity Code Description Project File Line Suppression StateError Mono.Cecil.AssemblyResolutionException : Failed to resolve assembly : 'Microsoft.Azure.WebJobs.Extensions , Version=3.0.6.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 ' at Mono.Cecil.BaseAssemblyResolver.Resolve ( AssemblyNameReference name , ReaderParameters parameters ) at Mono.Cecil.BaseAssemblyResolver.Resolve ( AssemblyNameReference name ) at Mono.Cecil.DefaultAssemblyResolver.Resolve ( AssemblyNameReference name ) at Mono.Cecil.MetadataResolver.Resolve ( TypeReference type ) at Mono.Cecil.ModuleDefinition.Resolve ( TypeReference type ) at Mono.Cecil.TypeReference.Resolve ( ) at MakeFunctionJson.AttributeExtensions.IsWebJobsAttribute ( CustomAttribute attribute ) at MakeFunctionJson.ParameterInfoExtensions. < > c. < IsWebJobSdkTriggerParameter > b__0_0 ( CustomAttribute a ) at System.Linq.Enumerable.Any [ TSource ] ( IEnumerable ` 1 source , Func ` 2 predicate ) at MakeFunctionJson.ParameterInfoExtensions.IsWebJobSdkTriggerParameter ( ParameterDefinition parameterInfo ) at MakeFunctionJson.MethodInfoExtensions. < > c. < HasTriggerAttribute > b__4_0 ( ParameterDefinition p ) at System.Linq.Enumerable.Any [ TSource ] ( IEnumerable ` 1 source , Func ` 2 predicate ) at MakeFunctionJson.MethodInfoExtensions.HasTriggerAttribute ( MethodDefinition method ) at MakeFunctionJson.MethodInfoExtensions.HasValidWebJobSdkTriggerAttribute ( MethodDefinition method ) at MakeFunctionJson.FunctionJsonConverter.GenerateFunctions ( IEnumerable ` 1 types ) +MoveNext ( ) at System.Collections.Generic.List ` 1..ctor ( IEnumerable ` 1 collection ) at System.Linq.Enumerable.ToList [ TSource ] ( IEnumerable ` 1 source ) at MakeFunctionJson.FunctionJsonConverter.TryGenerateFunctionJsons ( ) at MakeFunctionJson.FunctionJsonConverter.TryRun ( ) Error generating functions metadata Panmure.RiskMI.DataCollector.Functions | Failed to resolve for reference Microsoft.Azure.WebJobs.Extensions - Metadata generation failed |
C_sharp : Apps downloaded from the Windows Store are installed in this location : If you look inside this folder you can access each application 's .exe and use reflector to decompile them.Currently , my Windows RT application sends a password over SSL to a WCF service to ensure that only people using my app can access my database ( via the service ) .If my code can be read by anybody , how can I ensure that only people using my Windows 8 app are accessing the service ? Thanks ! <code> C : \Program Files\WindowsApps | What can I do to stop other people running my Windows RT code ? |
C_sharp : I 'm attempting to find a minimized window and Show it.The program can be downloaded from Samsung and it is titled `` SideSync '' . To fully replicate my question you would need to install this and also have a Samsung phone to plug in to your computer . Here is a screen shot of it fully configured and running : Observe that there are two windows , A and B. I used a tool titled Microsoft Inspect to determine that the two program windows are normal windows . They do not have a child parent relationship . However , when I start SideSync , only Window A appears . I must then click `` Phone Screen '' and then Window B appears ( in addition to Window A ) . This might a clue to solve this issue ? We shall see.Here are both windows as they appear in Microsoft Inspect : Both windows have Window Titles . Using the code below I can retrieve the Process of the window ( which is my objective ) . Server code : However , some strange behavior is going on . GetProcessByWindowTitle ( ) will return ONE but not BOTH of the processes . I 'm assuming that because there are two windows that there must be two processes . Which Process it returns is dependent on which was the last window that I clicked with my mouse . For example , if I last clicked Window A ; then GetProcessByWindowTitle ( `` SideSync '' ) will return a Process , but then GetProcessByWindowTitle ( `` SAMSUNG '' ) will return void ... .and vice versa if I last clicked Window B , GetProcessByWindowTitle ( `` SideSync '' ) will return a void , but then GetProcessByWindowTitle ( `` SAMSUNG '' ) will return Process.Client code : My goal is to show Window B . My issue is that this is only possible if I clicked on it last , which creates an unwanted dependency.I want to be able to show window B independent of any click order . <code> public static Process GetProcessByWindowTitle ( string windowTitleContains ) { foreach ( var windowProcess in GetWindowProcesses ( ) ) if ( windowProcess.MainWindowTitle.Contains ( windowTitleContains ) ) return windowProcess ; return null ; } [ Ignore ( `` Requires starting SideSync and clicking one of the windows . Only the last clicked will return a Process . `` ) ] [ Test ] public void NonMinimizedWindowProcessIsDetected ( ) { Process p1 = Windows.GetProcessByWindowTitle ( `` SAMSUNG '' ) ; if ( p1==null ) { Console.WriteLine ( `` SAMSUNG process is null . `` ) ; } else { Console.WriteLine ( `` SAMSUNG process detected . `` ) ; } Process p2 = Windows.GetProcessByWindowTitle ( `` SideSync '' ) ; if ( p2 == null ) { Console.WriteLine ( `` SideSync process is null . `` ) ; } else { Console.WriteLine ( `` SideSync process detected . `` ) ; } } | C # minimized windows not being returned by call to System.Diagnostics.Process.GetProcesses ( ) |
C_sharp : I have a form which I 'm bringing up using ShowDialog which contains a couple of text boxes , labels and a button . The problem I 'm having is that the text boxes are being drawn before the form itself and the other controls are drawn.I am overriding the OnPaint method I 'm not sure if this could be causing the problem : It 's only a slight delay but it 's visible and annoying . Thank you.The form is double buffered by the way.EDIT : I have pinpointed the issue to be the fact that the form does not have a FormBorderStyle . With the FormBorderStyle set to Sizable , this issue does not occur . However please note that having FormBorderStyle.None as my border style is necessary , so I have not found a solution yet . <code> protected override void OnPaint ( PaintEventArgs e ) { ControlPaint.DrawBorder ( e.Graphics , e.ClipRectangle , Color.Black , ButtonBorderStyle.Solid ) ; base.OnPaint ( e ) ; } | Controls not being drawn at the same time |
C_sharp : I have a form in HTML which contains multiple same name fields . For example : Now on the server side ( C # ) , I have an action method and a model class Product : Now my question is : I am submitting the form using jquery $ .ajax method . On the server side the action method accepts a Product class array . Now how can I convert the form fields into a Json array ( similar to product array ) . I tried : The first generates the name-value pair of all the form fields and the second generates the name-value array of all the form fields . And my requirement is : Can anyone tell me how can I can achieve this through JavaScript or JQuery ? <code> < form action= '' '' method= '' post '' id= '' form '' > < div class= '' itemsection '' id= '' item1 '' > < input type= '' text '' name= '' Price '' / > < input type= '' text '' name= '' Name '' / > < input type= '' text '' name= '' Catagory '' / > < /div > < div class= '' itemsection '' id= '' item2 '' > < input type= '' text '' name= '' Price '' / > < input type= '' text '' name= '' Product '' / > < input type= '' text '' name= '' Catagory '' / > < /div > < div class= '' itemsection '' id= '' item3 '' > < input type= '' text '' name= '' Price '' / > < input type= '' text '' name= '' Product '' / > < input type= '' text '' name= '' Catagory '' / > < /div > < /form > //Action method accepts the form on server //It require the Product array public ActionResult SaveItem ( Product [ ] products ) { ... .. ... } //Model class product public Class Product { public int Id { get ; set ; } public double Price { get ; set ; } public string Name { get ; set ; } public string Catagory { get ; set ; } } $ ( `` # form '' ) .serialize ( ) ; & $ ( `` # form '' ) .serializeArray ( ) ; //currently my form contains 3 item section so : [ { `` Price '' : `` value '' , `` Name '' : `` value '' , `` Catagory '' : `` value '' } , { `` Price '' : `` value '' , `` Name '' : `` value '' , `` Catagory '' : `` value '' } { `` Price '' : `` value '' , `` Name '' : `` value '' , `` Catagory '' : `` value '' } ] | How to serialize the form fields and send it to server , jquery ? |
C_sharp : I 've an array of objects DataTestplans from which I try to retrieve records for a particular DataID and ProductID using the LINQ query shown , my current query has Distinct ( ) which distiguishes on all 5 mentioned properties , how do I retrieve distinct records based on properties DataID , TestPlanName , TCIndexList and ProductID ? DataTestplans : -LINQ <code> [ { `` DataTestPlanID '' : 0 , `` DataID '' : 19148 , `` TestPlanName '' : `` string '' , `` TCIndexList '' : `` string '' , `` ProductID '' : 2033915 } , { `` DataTestPlanID '' : 0 , `` DataID '' : 19148 , `` TestPlanName '' : `` string '' , `` TCIndexList '' : `` string '' , `` ProductID '' : 2033915 } , { `` DataTestPlanID '' : 0 , `` DataID '' : 19149 , `` TestPlanName '' : `` string '' , `` TCIndexList '' : `` string '' , `` ProductID '' : -2642 } ] DataTestPlans_DataID_ProductID = DataTestPlans.Where ( c = > c.DataID == DataID_ProductID_Record.DataID & & c.ProductID == DataID_ProductID_Record.ProductID ) .Distinct ( ) ; | how do I write LINQ query to retrieve distinct records based on only specific properties ? |
C_sharp : I am trying to achieve something like this : So I can do something like this : Is this possible ? <code> interface IAbstract { string A { get ; } object B { get ; } } interface IAbstract < T > : IAbstract { T B { get ; } } class RealThing < T > : IAbstract < T > { public string A { get ; private set ; } public T B { get ; private set ; } } RealThing < string > rt = new RealThing < string > ( ) ; IAbstract ia = rt ; IAbstract < string > ias = rt ; object o = ia.B ; string s = ias.B ; | Generics IAbstract < T > inherits from IAbstract |
C_sharp : Yes , I am using a profiler ( ANTS ) . But at the micro-level it can not tell you how to fix your problem . And I 'm at a microoptimization stage right now . For example , I was profiling this : ANTS showed that the y-loop-line was taking a lot of time . I thought it was because it has to constantly call the Height getter . So I created a local int height = Height ; before the loops , and made the inner loop check for y < height . That actually made the performance worse ! ANTS now told me the x-loop-line was a problem . Huh ? That 's supposed to be insignificant , it 's the outer loop ! Eventually I had a revelation - maybe using a property for the outer-loop-bound and a local for the inner-loop-bound made CLR jump often between a `` locals '' cache and a `` this-pointer '' cache ( I 'm used to thinking in terms of CPU cache ) . So I made a local for Width as well , and that fixed it.From there , it was clear that I should make a local for Data as well - even though Data was not even a property ( it was a field ) . And indeed that bought me some more performance.Bafflingly , though , reordering the x and y loops ( to improve cache usage ) made zero difference , even though the array is huge ( 3000x3000 ) .Now , I want to learn why the stuff I did improved the performance . What book do you suggest I read ? <code> for ( int x = 0 ; x < Width ; x++ ) { for ( int y = 0 ; y < Height ; y++ ) { packedCells.Add ( Data [ x , y ] .HasCar ) ; packedCells.Add ( Data [ x , y ] .RoadState ) ; packedCells.Add ( Data [ x , y ] .Population ) ; } } | How do I learn enough about CLR to make educated guesses about performance problems ? |
C_sharp : Consider this example code : Here B.TheT is null . However , changing the Main method like this : B.TheT is `` Test '' , as expected . I can understand that this forces the static constructor to run , but why does this not happen for the first case ? I tried reading the spec , and this caught my attention ( §10.12 ) : [ ... ] The execution of a static constructor is triggered by the first of the following events to occur within an application domain : • [ ... ] • Any of the static members of the class type are referenced.My interpretation of this is that since TheT is not a member of B , the static constructor of B is not forced to be run . Is this correct ? If that is correct , how would I best let B specify how to initialize TheT ? <code> public class A < T > { public static T TheT { get ; set ; } } public class B : A < string > { static B ( ) { TheT = `` Test '' ; } } public class Program { public static void Main ( String [ ] args ) { Console.WriteLine ( B.TheT ) ; } } public static void Main ( ) { new B ( ) ; Console.WriteLine ( B.TheT ) ; } | Static initialization of inherited static member |
C_sharp : Using C # for ASP.NET and MOSS development , we often have to embed JavaScript into our C # code . To accomplish this , there seems to be two prevalent schools of thought : The other school of thought is something like this : Is there a better way than either of these two methods ? I like the second personally , as you can see the entire section of JavaScript ( or other language block , whether SQL or what have you ) , and it also aids in copying the code between another editor for that specific language.Edit : I should mention that the end goal is having formatted JavaScript in the final web page.I also changed the example to show interaction with the generated code . <code> string blah = `` asdf '' ; StringBuilder someJavaScript = new StringBuilder ( ) ; someJavaScript.Append ( `` < script language='JavaScript ' > '' ) ; someJavaScript.Append ( `` function foo ( ) \n '' ) ; someJavaScript.Append ( `` { \n '' ) ; someJavaScript.Append ( `` var bar = ' { 0 } ' ; \n '' , blah ) ; someJavaScript.Append ( `` } \n '' ) ; someJavaScript.Append ( `` < /script > '' ) ; string blah = `` asdf '' ; string someJavaScript = @ '' < script language='JavaScript ' > function foo ( ) { var bar = ' '' + blah + @ '' ' ; } < /script > '' ; | How do you embed other programming languages into your code ? |
C_sharp : In C # you can refer to values in a class using the 'this ' keyword.While I presume the answer will likley be user preference , is it best practice to use the this keyword within a class for local values ? <code> class MyClass { private string foo ; public string MyMethod ( ) { return this.foo ; } } | Should you always refer to local class variables with `` this '' |
C_sharp : I have a piece of software written with fluent syntax . The method chain has a definitive `` ending '' , before which nothing useful is actually done in the code ( think NBuilder , or Linq-to-SQL 's query generation not actually hitting the database until we iterate over our objects with , say , ToList ( ) ) .The problem I am having is there is confusion among other developers about proper usage of the code . They are neglecting to call the `` ending '' method ( thus never actually `` doing anything '' ) ! I am interested in enforcing the usage of the return value of some of my methods so that we can never `` end the chain '' without calling that `` Finalize ( ) '' or `` Save ( ) '' method that actually does the work.Consider the following code : As you can see , proper usage of this code would be something like : The problem is that people are using it this way ( thinking it achieves the same as the above ) : So pervasive is this problem that , with entirely good intentions , another developer once actually changed the name of the `` Init '' method to indicate that THAT method was doing the `` real work '' of the software.Logic errors like these are very difficult to spot , and , of course , it compiles , because it is perfectly acceptable to call a method with a return value and just `` pretend '' it returns void . Visual Studio does n't care if you do this ; your software will still compile and run ( although in some cases I believe it throws a warning ) . This is a great feature to have , of course . Imagine a simple `` InsertToDatabase '' method that returns the ID of the new row as an integer - it is easy to see that there are some cases where we need that ID , and some cases where we could do without it.In the case of this piece of software , there is definitively never any reason to eschew that `` Save '' function at the end of the method chain . It is a very specialized utility , and the only gain comes from the final step.I want somebody 's software to fail at the compiler level if they call `` With ( ) '' and not `` Save ( ) '' .It seems like an impossible task by traditional means - but that 's why I come to you guys . Is there an Attribute I can use to prevent a method from being `` cast to void '' or some such ? Note : The alternate way of achieving this goal that has already been suggested to me is writing a suite of unit tests to enforce this rule , and using something like http : //www.testdriven.net to bind them to the compiler . This is an acceptable solution , but I am hoping for something more elegant . <code> //The `` factory '' class the user will be dealing withpublic class FluentClass { //The entry point for this software public IntermediateClass < T > Init < T > ( ) { return new IntermediateClass < T > ( ) ; } } //The class that actually does the workpublic class IntermediateClass < T > { private List < T > _values ; //The user can not call this constructor internal IntermediateClass < T > ( ) { _values = new List < T > ( ) ; } //Once generated , they can call `` setup '' methods such as this public IntermediateClass < T > With ( T value ) { var instance = new IntermediateClass < T > ( ) { _values = _values } ; instance._values.Add ( value ) ; return instance ; } //Picture `` lazy loading '' - you have to call this method to //actually do anything worthwhile public void Save ( ) { var itemCount = _values.Count ( ) ; . . . //save to database , write a log , do some real work } } new FluentClass ( ) .Init < int > ( ) .With ( -1 ) .With ( 300 ) .With ( 42 ) .Save ( ) ; new FluentClass ( ) .Init < int > ( ) .With ( -1 ) .With ( 300 ) .With ( 42 ) ; | How to enforce the use of a method 's return value in C # ? |
C_sharp : I 'm using Newtonsoft JSON library and I 'm trying to deserialize a JSON . The problem is that when I use [ JsonConverter ( typeof ( StringEnumConverter ) ) ] I get this error : Can not apply attribute class 'JsonConverter ' because it is abstract.Here are my classes : I get the squiggly line under the JsonConverter.EDIT : The JsonConverter class is indeed abstract if I navigate to the class ( ctrl+click in VS ) . I 'm using .NET for Windows Universal . <code> public class ActionRepository { [ JsonConverter ( typeof ( StringEnumConverter ) ) ] public enum AllowedActions { FINDWINDOW , } public enum AllowedParameters { WINDOWNAME , } } public class Action { public AllowedActions Name { get ; set ; } public List < Parameter > Parameters { get ; set ; } } | Can not apply attribute class 'JsonConverter ' because it is abstract |
C_sharp : I have a code which updates an array based on values in another , small array.Where c is a struct that is a pair of bytes representing cards from a deck.one is an array size of 52 ( with entries for each of 52 cards from a deck ) I wrote a benchmark to profile this code : Setting testRepetitions = 25 million , and using array of 256 elements ( result.Length = 256 ) , it runs in about 8.5 seconds on my machine.Here is the Cards struct : When I modify that struct to hold 5 cards ( 5 bytes ) , the same benchmark now takes ~13s.Why would that happen ? The computation is the same , remaining 3 cards are unused , and all arrays are small enough to fit in L1 cache.What is even stranger , is that if I further change Cards to now hold 8 bytes , benchmark is now faster , taking ~10 seconds.My Setup : Here are exact timings I got : What is going on here ? Benchmark Code : EditI 've rerun the benchmark again , with 100 million iterations . Here are the results : And in reverse order : Running it on Surface Pro 4 ( Skylake i7-6650U Turbo-boosted to ~3.4ghz ) : So the difference persists and does n't depend on the order.I also ran profiling using Intel VTune , and it shows CPI of 0.3 for `` 5 cards '' version , and 0.27 for `` 8 cards '' .Edit2 Added ArrayUtils class for creating initial random arrays . <code> for ( var i = 0 ; i < result.Length ; i++ ) { var c = cards [ i ] ; result [ i ] -= one [ c.C0 ] + one [ c.C1 ] ; } private void TestCards2 ( int testRepetitions , float [ ] result , float [ ] one , Cards [ ] cards ) { for ( var r = 0 ; r < testRepetitions ; r++ ) for ( var i = 0 ; i < result.Length ; i++ ) { var c = cards [ i ] ; result [ i ] -= one [ c.C0 ] + one [ c.C1 ] ; } } struct Cards { public byte C0 ; public byte C1 ; public Cards ( byte c0 , byte c1 ) { C0 = c0 ; C1 = c1 ; } } VS 2015 Update 3..NET 4.6.2Release Build x64CPU : Haswell i7-5820K CPU @ 3.30GHz Test With 2 Cards . Time = 8582 msTest With 5 Cards . Time = 12910 msTest With 8 Cards . Time = 10180 ms class TestAdjustment { public void Test ( ) { using ( Process p = Process.GetCurrentProcess ( ) ) p.PriorityClass = ProcessPriorityClass.High ; var size = 256 ; float [ ] one = ArrayUtils.CreateRandomFloatArray ( size:52 ) ; int [ ] card0 = ArrayUtils.RandomIntArray ( size , minValue:0 , maxValueInclusive:51 ) ; int [ ] card1 = ArrayUtils.RandomIntArray ( size , minValue : 0 , maxValueInclusive : 51 ) ; Cards [ ] cards = CreateCardsArray ( card0 , card1 ) ; Cards5 [ ] cards5 = CreateCards5Array ( card0 , card1 ) ; Cards8 [ ] cards8 = CreateCards8Array ( card0 , card1 ) ; float [ ] result = ArrayUtils.CreateRandomFloatArray ( size ) ; float [ ] resultClone = result.ToArray ( ) ; var testRepetitions = 25*1000*1000 ; var sw = Stopwatch.StartNew ( ) ; TestCards2 ( testRepetitions , result , one , cards ) ; WriteLine ( $ '' Test With 2 Cards . Time = { sw.ElapsedMilliseconds } ms '' ) ; result = resultClone.ToArray ( ) ; //restore original array from the clone , so that next method works on the same data sw.Restart ( ) ; TestCards5 ( testRepetitions , result , one , cards5 ) ; WriteLine ( $ '' Test With 5 Cards . Time = { sw.ElapsedMilliseconds } ms '' ) ; result = resultClone.ToArray ( ) ; sw.Restart ( ) ; TestCards8 ( testRepetitions , result , one , cards8 ) ; WriteLine ( $ '' Test With 8 Cards . Time = { sw.ElapsedMilliseconds } ms '' ) ; } private void TestCards2 ( int testRepetitions , float [ ] result , float [ ] one , Cards [ ] cards ) { for ( var r = 0 ; r < testRepetitions ; r++ ) for ( var i = 0 ; i < result.Length ; i++ ) { var c = cards [ i ] ; result [ i ] -= one [ c.C0 ] + one [ c.C1 ] ; } } private void TestCards5 ( int testRepetitions , float [ ] result , float [ ] one , Cards5 [ ] cards ) { for ( var r = 0 ; r < testRepetitions ; r++ ) for ( var i = 0 ; i < result.Length ; i++ ) { var c = cards [ i ] ; result [ i ] -= one [ c.C0 ] + one [ c.C1 ] ; } } private void TestCards8 ( int testRepetitions , float [ ] result , float [ ] one , Cards8 [ ] cards ) { for ( var r = 0 ; r < testRepetitions ; r++ ) for ( var i = 0 ; i < result.Length ; i++ ) { var c = cards [ i ] ; result [ i ] -= one [ c.C0 ] + one [ c.C1 ] ; } } private Cards [ ] CreateCardsArray ( int [ ] c0 , int [ ] c1 ) { var result = new Cards [ c0.Length ] ; for ( var i = 0 ; i < result.Length ; i++ ) result [ i ] = new Cards ( ( byte ) c0 [ i ] , ( byte ) c1 [ i ] ) ; return result ; } private Cards5 [ ] CreateCards5Array ( int [ ] c0 , int [ ] c1 ) { var result = new Cards5 [ c0.Length ] ; for ( var i = 0 ; i < result.Length ; i++ ) result [ i ] = new Cards5 ( ( byte ) c0 [ i ] , ( byte ) c1 [ i ] ) ; return result ; } private Cards8 [ ] CreateCards8Array ( int [ ] c0 , int [ ] c1 ) { var result = new Cards8 [ c0.Length ] ; for ( var i = 0 ; i < result.Length ; i++ ) result [ i ] = new Cards8 ( ( byte ) c0 [ i ] , ( byte ) c1 [ i ] ) ; return result ; } } struct Cards { public byte C0 ; public byte C1 ; public Cards ( byte c0 , byte c1 ) { C0 = c0 ; C1 = c1 ; } } struct Cards5 { public byte C0 , C1 , C2 , C3 , C4 ; public Cards5 ( byte c0 , byte c1 ) { C0 = c0 ; C1 = c1 ; C2 = C3 = C4 = 0 ; } } struct Cards8 { public byte C0 , C1 , C2 , C3 , C4 , C5 , C6 , C7 ; public Cards8 ( byte c0 , byte c1 ) { C0 = c0 ; C1 = c1 ; C2 = C3 = C4 = C5 = C6 = C7 = 0 ; } } Test With 5 Cards . Time = 52245 msTest With 8 Cards . Time = 40531 ms Test With 8 Cards . Time = 41041 msTest With 5 Cards . Time = 52034 ms Test With 8 Cards . Time = 47913 msTest With 5 Cards . Time = 55182 ms public static class ArrayUtils { static Random rand = new Random ( 137 ) ; public static float [ ] CreateRandomFloatArray ( int size ) { var result = new float [ size ] ; for ( int i = 0 ; i < size ; i++ ) result [ i ] = ( float ) rand.NextDouble ( ) ; return result ; } public static int [ ] RandomIntArray ( int size , int minValue , int maxValueInclusive ) { var result = new int [ size ] ; for ( int i = 0 ; i < size ; i++ ) result [ i ] = rand.Next ( minValue , maxValueInclusive + 1 ) ; return result ; } } | Accessing 5-byte struct is much slower than 8-byte |
C_sharp : return confControl ; throws an exception : Can not implicitly convert type ConfigControlBase < ProviderX > to ConfigControlBase < ProviderBase > <code> public class ConfigControlBase < T > : UserControl where T : ProviderBase { public T Provider { get ; set ; } public void Init ( T provider ) { this.Provider = provider ; } } public abstract class ProviderBase { public abstract ConfigControlBase < ProviderBase > GetControl ( ) ; } public class ProviderXConfigControl : ConfigControlBase < ProviderX > { } public class ProviderX : ProviderBase { public override ConfigControlBase < ProviderBase > GetControl ( ) { var confControl = new ProviderXConfigControl ( ) as ConfigControlBase < ProviderX > ; return confControl ; } } | Casting a generic element type downwards |
C_sharp : What 's the simple way to add the dollar sign ( ' $ ' ) or currency to a decimal data type on the following query : Thanks for the help ! <code> SELECT TOP 100000 SUM ( [ dbo ] . [ Entry ] . [ Amount ] ) AS 'Total Charges ' | How to convert , cast , or add ' $ ' to a decimal SQL SUM ( ) |
C_sharp : In Perl I can sayWhat is the equivalent of this in C # ASP.NET ? Specifically what I 'm looking for is something so that other members of my team can know when they 're still using a deprecated routine . It should show up at run time when the code path is actually hit , not at compile time ( otherwise they 'd get warnings about code sitting at a compatibility layer which ought to never run anyway . ) My best option so far is to use Trace , which feels like a bad hack . <code> use warnings ; warn `` Non-fatal error condition , printed to stderr . `` ; | What 's the C # equivalent of perl warn ? |
C_sharp : This question is not so much about finding a solution as about getting an explanation for the bizarrest behavior I have ever seen from SQL Server.I had a stored procedure with the following signature : Given a certain set of parameters , this proc was taking a very long time to run from C # ( using SqlCommand.ExecuteReader ( ) ) - about 2 minutes . Using the same parameters in a direct query session , the SP ran in under 2 seconds.It took a long time , and I wo n't even try to explain how we stumbled upon this solution , but this is what we did : At the beginning of the SP , we declared 3 local variables and assigned them to the values of the parameters , like so : And then , in the rest of the SP we substituted all references to the input parameters with the local copies.Voila . SP executed in under 2 seconds . And the team here is gobsmacked.Now , ladies and gentlemen , can anyone explain this behavior ? <code> alter procedure MySP @ param1 uniqueidentifier , @ param2 uniqueidentifier , @ param3 uniqueidentifier declare @ param1_copy uniqueidentifier , @ param2_copy uniqueidentifier , @ param3_copy uniqueidentifierselect @ param1_copy = @ param1 , @ param2_copy = @ param2 , @ param3_copy = @ param3 | Stored procedure performance - this is WILD ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.