text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : Could someone please help enlighten me ? I went to check-in some changes to TFS and my check-in was rejected . It prompted me to take a look at a switch statement I had edited . What I 've found is that Visual Studio 2017 claims there is no compile time issue and allows me to build and deploy the application successfully . On top of that , even the unit test for the method appears to be passing as intended.So , please note that the line `` case PaymentStatus Unknown '' is missing the ' . ' dot operator . As mentioned , the project builds and runs ; but failed to check-in with the gated build server.Also , note that the following test is passing : Here are some images showing no squigglies and it does indeed build fine : And , the passing test method : Lastly , note that I ran the test with just a static string rather than using the resource file and it passes . I just left out the resource file stuff for simplicity 's sake in the code above.Any thoughts on this are most appreciated ! Thanks in Advance ! <code> public enum PaymentStatus { Issued , Cleared , Voided , Paid , Requested , Stopped , Unknown } public class PaymentViewModel { public PaymentStatus Status { get ; set ; } ... public String StatusString { get { switch ( this.Status ) { case PaymentStatus.Cleared : return `` Cleared '' ; case PaymentStatus.Issued : return `` Issued '' ; case PaymentStatus.Voided : return `` Voided '' ; case PaymentStatus.Paid : return `` Paid '' ; case PaymentStatus.Requested : return `` Requested '' ; case PaymentStatus.Stopped : return `` Stopped '' ; case PaymentStatus Unknown : return `` Unknown '' ; default : throw new InavlidEnumerationException ( this.Status ) ; } } } } [ TestMethod ] public void StatusStringTest_Unknown ( ) { var model = new PaymentViewModel ( ) { Status = PaymentStatus.Unknown } Assert.AreEqual ( `` Unknown '' , model.StatusString ) ; } | Invalid Switch syntax builds successfully ? |
C_sharp : What I 'm doing is looking up a value for a particular field in the hashtable . The object can be a handful of primitive types who 's value is destined to be put inside XML but it comes out of the hashtable as an object . So I have the problem of needing to decide what the type is , cast it up and then use that types ToString . It would be nice if I did n't need to cast it but then it will call the ToString on the object type and not the counterpart method on the actual type.The following code is functionally correct , but I 'm not comfortable with it . Perhaps following this comfort path will lead to me being a purist . Either way I would very much appreciate a nicer way to write this if such exists . <code> public string GetColumnValue ( string columnName ) { object value = item [ columnName ] ; if ( value == null ) return string.Empty ; if ( value.GetType ( ) == typeof ( string ) ) { return ( string ) value ; } else if ( value.GetType ( ) == typeof ( double ) ) { return ( ( double ) value ) .ToString ( ) ; } ... } | A clean way to cast to an objects actual type |
C_sharp : In the following code : ... what is the meaning of ( i & 1 ) == 1 ? <code> Expression < Func < int , bool > > isOdd = i = > ( i & 1 ) == 1 ; | What is the meaning of the & operator ? |
C_sharp : I have been reading a book called Clean Code A Handbook of Agile Software Craftsmanship . The author in the book motivates that a switch statement should be avoided and if it can not be avoided it should be relegated to factory methods . I have a connection object which is receiving various PDUs ( protocol data units ) . The PDUs vary and they can be received in any order . So if I have a method for example : because I can not tell what the packet type is until it has been fully received . In the header of the PDU is an identifier as to which type it should be . This means that the calling method is going to have figure out what the type of the PDU is and based on that call the relevant method to handle it . This sounds like a perfect example for a switch statement . The object that contains the connection I would ideally like to have two threads . One for receiving PDUs and another for servicing a queue of PDUs to be sent.Now I know that you can not follow every bit of good advice and that there are just some circumstances which are the exception to the rule . Is this one of them ? Or is there a way around this that I just have not yet thought of.UPDATE : I hear what a lot of people are saying by creating subclasses of response handlers . The issue is that the containing object has a lot of context and additional information that the handlers would need for example lookups and throttling etc etc . To inject all of this information into subclasses of handlers would be quite a chore to maintain and would also split a lot of logic up when it feels better to be encapsulated in the object that it is in now . <code> public BasePdu ReceiveNext ( ) ; | How can a switch statement be avoided if the return type is unknown by the calling method ? |
C_sharp : I have viewed similar SO questions but can not figure out why mine wo n't work.I need to convert my Func < string , bool > value to an Expression to be used in the Moq framework but I can not get passed an error when trying to convert the Func to an Expression.This is the error : Static method requires null instance , non-static method requires non-null instance.This is my sample code : Not sure if my function is a static or non-static , but I would have thought it was static . I inspected the Func object using the debugger and there is a field called `` IsStatic '' set to false ( value.Method.IsStatic ) . A bit confused what else to try.Thank you . Stack Trace : <code> using System ; using System.Linq.Expressions ; namespace ConsoleApp1 { class Program { public class MyObject { public void Add < T > ( Func < T , bool > value ) { // Line below causes error : Static method requires null instance , // non-static method requires non-null instance . Expression < Func < T , bool > > expression = Expression.Lambda < Func < T , bool > > ( Expression.Call ( value.Method ) ) ; // I need to use the expression for the line below that is commented out // ( for context reasons I have included this ) //_myMock.Setup ( m = > m.MyMethod ( key , It.Is ( expression ) ) ) .Returns ( `` test '' ) ; } } public static void Main ( string [ ] args ) { // Call it using : var myObject = new MyObject ( ) ; myObject.Add ( new Func < string , bool > ( x = > x.StartsWith ( `` test '' ) ) ) ; } } } System.ArgumentException HResult=0x80070057 Message=Static method requires null instance , non-static method requires non-null instance.Parameter name : method Source=System.Core StackTrace : at System.Linq.Expressions.Expression.ValidateStaticOrInstanceMethod ( Expression instance , MethodInfo method ) at System.Linq.Expressions.Expression.Call ( Expression instance , MethodInfo method , IEnumerable ` 1 arguments ) at System.Linq.Expressions.Expression.Call ( MethodInfo method , Expression [ ] arguments ) at ConsoleApp1.Program.MyObject.Add [ T ] ( Func ` 2 value ) in C : \Users\userName\source\repos\ConsoleApp1\ConsoleApp1\Program.cs : line 14 at ConsoleApp1.Program.Main ( String [ ] args ) in C : \Users\userName\source\repos\ConsoleApp1\ConsoleApp1\Program.cs : line 28 | Expression.Call causes `` Static method requires null instance , non-static method requires non-null instance '' |
C_sharp : I was trying to find information about transforming an index that has been converted from a 2 dimensional index , to a single one . Then turn the single index back to a 2 dimensional one . I do n't even know what this method is called.formula to single indexSo my question is how do I turn it back into two dimensions ? Ca n't wrap my head around it for some reason.Thanks <code> int index = x + y * width ; MyArray [ index ] ; int x = index ? ? ? width ; int y = index ? ? ? width ; | Two dimension array to single dimension and back again |
C_sharp : Let cls be of type XmlNodeFollowing statement allows me to access child nodes : Now when I try to use var : then the type of child is not XmlNode , only object . I can not use child.NodeType , compiler says : object ' does not contain a definition for 'NodeTypeWhy is this ? <code> foreach ( XmlNode child in cls.ChildNodes ) foreach ( var child in cls.ChildNodes ) | Why var used in foreach for XmlNode does not deduce real type , only object ? |
C_sharp : If I save this string to a text file ; Hello this \n is a test messageThe \n character is saved as HEX [ 5C 6E ] I would like to have it saved as [ 0A ] .I believe this is an encoding issue ? I am using ; All this is inside a FileStream scope and uses fs.Write to write the encodedBytes into the file.I have tried to use \r\n but had the same result.Any suggestions ? Thanks ! EDITThe string is being read from a tsv file and placed into an string array . The string being read has the `` \n '' in it.To read the string I use a StreamReader reader and split at \t <code> // 1252 is a variable in the applicationEncoding codePage = Encoding.GetEncoding ( `` 1252 '' ) ; Byte [ ] bytes = new UTF8Encoding ( true ) .GetBytes ( `` Hello this \\n is a test message '' ) ; Byte [ ] encodedBytes = Encoding.Convert ( Encoding.UTF8 , codePage , bytes ) ; | C # '\n ' saved in different bytes than expected |
C_sharp : Suppose I want to implement a functional composition , like this : Now in practice , I can use this Compose ( ) fn like this : And the result is FREDFRED . Is there a way to use a simpler syntax to invoke Compose ? I tried like this : ... but I get a compile error : error CS0411 : The type arguments for method 'FunctionalTest.Compose ( System.Func , System.Func ) ' can not be inferred from the usage . Try specifying the type arguments explicitly.Quite understandable . I am wondering if it is possible to declare it differently and get the inference to actually work . EDITThe origin of the problem : I was watching an online lecture of an undergrad Functional Programming course , UC Berkley 's CS61A . ( find it on youtube ) . I do n't have any formal training on FP , and I thought I might learn something . The prof uses scheme and he talks about how scheme + lisp are purely functional languages , and other languages are less so . He specifically identified Pascal , C , C++ , and Java ( but not C # ) as lacking functional capabilities , and said it would be difficult to do functional composition with these languages ( `` Without standing on your head '' ) . He asserted that a pointer-to-function ( as available in C , C++ ) is not the same as a function `` entity '' , a lambda . I get that . Funny - he did n't mention Javascript or C # , which I consider to be mainstream languages that both have pretty good functional capabilities . ( I do n't know F # . ) I find it curious that this is a lecture from last year - 14 months ago - and yet he seems to be unaware of the functional aspects of mainstream , modern languages . So I 'm following along and doing exercises , but instead of using scheme or lisp , I 'm using C # . And also doing some of them in Javascript.Anyway thanks to everyone for the quality responses . <code> public Func < T , T > Compose < T > ( Func < T , T > f , Func < T , T > g ) { return new Func < T , T > ( x = > f ( g ( x ) ) ) ; } public String ToUpper ( String s ) { return s.ToUpper ( ) ; } public String Replicate ( String s ) { return s+s ; } public void Run ( ) { var h = Compose < String > ( ToUpper , Replicate ) ; System.Console.WriteLine ( `` { 0 } '' , h ( `` fred '' ) ) ; } var h = Compose ( ToUpper , Replicate ) ; | Inferring generic types with functional composition |
C_sharp : How can I take advantage of the content negotiation pipeline when assigning to NancyContext.Response ? Currently my IStatusCodeHandler.Handle method returns JSON regardless of any content negotiation . I want this method to use JSON or XML according on any content negotiation ( preferably using the content negotiation pipeline . ) <code> public void Handle ( HttpStatusCode statusCode , NancyContext context ) { var error = new { StatusCode = statusCode , Message = `` Not Found '' } ; context.Response = new JsonResponse ( error , new JsonNetSerializer ( ) ) .WithStatusCode ( statusCode ) ; } | Automatic Content Negotation When Assigning To Response |
C_sharp : I am encountering what seems to be a very weird bug in ImmutableArray < > ( with BCL Immutable collections v1.0.12.0 , runtime .NET 4.5 ) : I have the following two identical structs exactly in the same source file under the same namespace : The following will throw an exception : If I project elements1 into ToArray ( ) on the first line instead of ToImmutableArray ( ) , everything works fine.The only difference between the two structs is that WeightedComponent is used extensively by the code before , while WeightedComponent2 is never used before ( this is why it may not be obvious to reproduce the bug ) .Iterating on elements1 twice in the same expression seem to be related to the issue , as if I remove it the Select works fine , but there is no such problem with elements2 . It really seems to be related to the way the code behind ImmutableArray < > is considering both structs ( maybe there is a caching mechanism ? ) Do you have any idea what could be causing this ? <code> public struct WeightedComponent { public readonly IComponent Component ; public readonly decimal Weight ; public WeightedComponent ( IComponent component , decimal weight ) { this.Component = component ; this.Weight = weight ; } } public struct WeightedComponent2 { public readonly IComponent Component ; public readonly decimal Weight ; public WeightedComponent2 ( IComponent component , decimal weight ) { this.Component = component ; this.Weight = weight ; } } var elements1 = new [ ] { 1 , 2 , 3 } .Select ( wc = > new WeightedComponent ( null , 0 ) ) .ToImmutableArray ( ) ; var foo = elements1.Select ( ( e1 , i1 ) = > elements1.Select ( ( e2 , i2 ) = > 0 ) .ToArray ( ) ) .ToArray ( ) ; if ( foo.Length ! = 3 ) throw new Exception ( `` Error : `` + foo.Length ) ; //Error : 1var elements2 = new [ ] { 1 , 2 , 3 } .Select ( wc = > new WeightedComponent2 ( null , 0 ) ) .ToImmutableArray ( ) ; var foo2 = elements2.Select ( ( e1 , i1 ) = > elements2.Select ( ( e2 , i2 ) = > 0 ) .ToArray ( ) ) .ToArray ( ) ; if ( foo2.Length ! = 3 ) throw new Exception ( `` Error : `` + foo.Length ) ; | ImmutableArray < > behaves differently than Array < > for nested Select with index |
C_sharp : Given a type , a name and a signature , how can I do a member lookup of the member with name name and signature signature using the C # rules of 7.4 ( the 7.4 is the chapter number from the C # Language Specification ) ( or at least part of them ... Let 's say I can live with an exact match , without conversions/casts ) at runtime ? I need to get a MethodInfo/PropertyInfo/ ... because then I have to use it with reflection ( to be more exact I 'm trying to build an Expression.ForEach builder ( a factory able to create an Expression Tree that represent a foreach statement ) , and to be pixel-perfect with the C # foreach I have to be able to do duck-typing and search for a GetEnumerator method ( in the collection ) , a Current property and a MoveNext method ( in the enumerator ) , as written in 8.8.4 ) The problem ( an example of the problem ) Clearly if I try typeof ( C3 ) .GetProperty ( `` Current '' ) I get an AmbiguousMatchException exception.A similar but different problem is present with interfaces : Here if I try to do a typeof ( I3 ) .GetProperties ( ) I do n't get the Current property ( and this is something known , see for example GetProperties ( ) to return all properties for an interface inheritance hierarchy ) , but I ca n't simply flatten the interfaces , because then I would n't know who is hiding who.I know that probably this problem is solved somewhere in the Microsoft.CSharp.RuntimeBinder namespace ( declared in the Microsoft.CSharp assembly ) . This because I 'm trying to use C # rules and member lookup is necessary when you have dynamic method invocation , but I have n't been able to find anything ( and then what I would get would be an Expression or perhaps a direct invocation ) .After some thought it 's clear that there is something similar in the Microsoft.VisualBasic assembly . VB.NET supports late binding . It 's in Microsoft.VisualBasic.CompilerServices.NewLateBinding , but it does n't expose the late bounded methods . <code> class C1 { public int Current { get ; set ; } public object MoveNext ( ) { return null ; } } class C2 : C1 { public new long Current { get ; set ; } public new bool MoveNext ( ) { return true ; } } class C3 : C2 { } var m = typeof ( C3 ) .GetMethods ( ) ; // I get both versions of MoveNext ( ) var p = typeof ( C3 ) .GetProperties ( ) ; // I get both versions of Current interface I0 { int Current { get ; set ; } } interface I1 : I0 { new long Current { get ; set ; } } interface I2 : I1 , I0 { new object Current { get ; set ; } } interface I3 : I2 { } | Resolving a member name at runtime |
C_sharp : Looking to the implementation of the method in the List < > class ( .NET Framework 4.5.2 ) , I can see an iteration over a collection like thisI am wondering what could be the reason to prefer that syntax over this oneI have created an assembly with two methods each one using a different approach . Then , looking into the generated IL code , I can see both methods calling the Dispose method enforced by the implementation of the IEnumerator < T > and hence IDisposable . So IDisposable is not the reason and here is my question . Is there any reason to prefer one syntax vs the other , other than simple style ( ish ) preferences ? <code> void InsertRange ( int index , IEnumerable < T > collection ) using ( IEnumerator < T > en = collection.GetEnumerator ( ) ) { while ( en.MoveNext ( ) ) { Insert ( index++ , en.Current ) ; } } foreach ( var item in collection ) { Insert ( index++ , item ) } | Iterating an IEnumerable < T > . Best way ? |
C_sharp : in all ( Agile ) articles i read about this : keep your code and functions small and easy to test.How should i do this with the 'controller ' or 'coordinator ' class ? In my situation , i have to import data . In the end i have one object who coordinates this , and i was wondering if there is a way of keeping the coordinator lean ( er ) and mean ( er ) .My coordinator now does the followling ( pseudocode ) Imho , this is one of those 'know all ' classes or at least one being 'not lean and mean ' ? Or , am i taking this lean and mean thing to far and is it impossible to program an import without some kind of 'fat ' importer/coordinator ? MichelEDITthis is actually a two-in-one question : one is how to test it , second is if it 's ok to have a 'know all/glue all together ' coordinator <code> //Write to the log that the import has startedLog.StartImport ( ) //Get the data in Excel sheet formatresult = new Downloader ( ) .GetExcelFile ( ) //Log this stepLog.LogStep ( result ) //convert the data to intern objectsresult = new Converter ( ) .Convertdata ( result ) ; //Log this stepLog.LogStep ( result ) //write the dataresult = Repository.SaveData ( result ) ; //Log this stepLog.LogStep ( result ) | How to keep my functions ( objects/methods ) 'lean and mean ' |
C_sharp : My motivation for chaining my class constructors here is so that I have a default constructor for mainstream use by my application and a second that allows me to inject a mock and a stub . It just seems a bit ugly 'new'-ing things in the `` : this ( ... ) '' call and counter-intuitive calling a parametrized constructor from a default constructor , I wondered what other people would do here ? ( FYI - > SystemWrapper ) <code> using SystemWrapper ; public class MyDirectoryWorker { // SystemWrapper interface allows for stub of sealed .Net class . private IDirectoryInfoWrap dirInf ; private FileSystemWatcher watcher ; public MyDirectoryWorker ( ) : this ( new DirectoryInfoWrap ( new DirectoryInfo ( MyDirPath ) ) , new FileSystemWatcher ( ) ) { } public MyDirectoryWorker ( IDirectoryInfoWrap dirInf , FileSystemWatcher watcher ) { this.dirInf = dirInf ; if ( ! dirInf.Exists ) { dirInf.Create ( ) ; } this.watcher = watcher ; watcher.Path = dirInf.FullName ; watcher.NotifyFilter = NotifyFilters.FileName ; watcher.Created += new FileSystemEventHandler ( watcher_Created ) ; watcher.Deleted += new FileSystemEventHandler ( watcher_Deleted ) ; watcher.Renamed += new RenamedEventHandler ( watcher_Renamed ) ; watcher.EnableRaisingEvents = true ; } public static string MyDirPath { get { return Settings.Default.MyDefaultDirPath ; } } // etc ... } | Is this a good or bad way to use constructor chaining ? ( ... to allow for testing ) |
C_sharp : I am trying to put a mocked Range ( which contains cells with values ) inside the rows of a new Range . But when I try to access a specific element from the Range , a exception is thrown.I 've tried everything , does anyone have a idea what I am doing wrong here ? Exception Message : Test method xxx.MockUtilsTest.MockRowsTest threw exception : Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : Can not apply indexing with [ ] to an expression of type 'Castle.Proxies.RangeProxy'TestMockUtils <code> [ TestMethod ] public void MockRowsTest ( ) { var row1 = MockUtils.MockCells ( `` test_row_1 '' , `` test_row_1 '' ) ; var row2 = MockUtils.MockCells ( `` test_row_2 '' , `` test_row_2 '' ) ; var range = MockUtils.MockRows ( row1 , row2 ) ; Assert.IsNotNull ( range ) ; Assert.AreEqual ( 2 , range.Count ) ; Assert.IsNotNull ( range.Rows ) ; Assert.AreEqual ( 2 , range.Rows.Count ) ; Assert.AreSame ( row1 , range.Rows [ 1 ] .Cells [ 1 ] ) ; // exception is thrown here Assert.AreSame ( row2 , range.Rows [ 2 ] .Cells [ 1 ] ) ; Assert.AreEqual ( `` test_row_1 '' , range.Rows [ 1 ] .Cells [ 1 ] .Value2 ) ; Assert.AreEqual ( `` test_row_2 '' , range.Rows [ 2 ] .Cells [ 1 ] .Value2 ) ; } public static Range MockCellValue2 ( Object value ) { var cell = new Moq.Mock < Range > ( ) ; cell.Setup ( c = > c.Value2 ) .Returns ( value ) ; return cell.Object ; } public static Range MockCells ( params Object [ ] values ) { var cells = new Moq.Mock < Range > ( ) ; for ( int i = 0 ; i < values.Length ; i++ ) { var cell = MockCellValue2 ( values [ i ] ) ; cells.SetupGet ( c = > c [ i + 1 , Moq.It.IsAny < Object > ( ) ] ) .Returns ( cell ) ; } var row = new Moq.Mock < Range > ( ) ; row.SetupGet ( r = > r.Cells ) .Returns ( cells.Object ) ; row.SetupGet ( r = > r.Count ) .Returns ( values.Length ) ; return row.Object ; } public static Range MockRows ( params Range [ ] rows ) { var mergedRows = MergeRanges ( rows ) ; var range = new Moq.Mock < Range > ( ) ; range.SetupGet ( r = > r.Count ) .Returns ( rows.Length ) ; range.SetupGet ( r = > r.Rows ) .Returns ( ( ) = > mergedRows ) ; range.Setup ( r = > r.GetEnumerator ( ) ) .Returns ( rows.GetEnumerator ( ) ) ; return range.Object ; } public static Range MergeRanges ( params Range [ ] ranges ) { var range = new Moq.Mock < Range > ( ) ; for ( int i = 0 ; i < ranges.Length ; i++ ) { range.SetupGet ( r = > r [ i + 1 , Moq.It.IsAny < Object > ( ) ] ) .Returns ( ranges [ i ] ) ; } range.SetupGet ( r = > r.Count ) .Returns ( ranges.Length ) ; range.Setup ( r = > r.GetEnumerator ( ) ) .Returns ( ranges.GetEnumerator ( ) ) ; return range.Object ; } | How to mock rows in a Excel VSTO plugin ? |
C_sharp : Is there a way to Define a default constructor for all classes in a given assembly . For example I have classes like this in an assembly -These classes all require a default constructor but I do n't want to have to riddle all of these classes with a default constructor so how do I do this using reflection or something similar ? ? ( Perhaps TypeBuilder.DefineDefaultConstructor ? ) <code> public class SomeClass { public SomeClass ( int x , int y ) { } } | Define Default Constructor for existing classes in assembly |
C_sharp : Does anybody see any drawbacks ? It should be noted that you ca n't remove anonymous methods from an event delegate list , I 'm aware of that ( actually that was the conceptual motivation for this ) .The goal here is an alternative to : And the code : } <code> if ( onFoo ! = null ) onFoo.Invoke ( this , null ) ; public delegate void FooDelegate ( object sender , EventArgs e ) ; public class EventTest { public EventTest ( ) { onFoo += ( p , q ) = > { } ; } public FireFoo ( ) { onFoo.Invoke ( this , null ) ; } public event FooDelegate onFoo ; | C # Events and Lambdas , alternative to null check ? |
C_sharp : I have two libraries written in C # that I 'd like to use in an F # application . Both libraries use the same type , however , I am unable to convince F # 's type checker of this fact.Here 's a simple example using the Office interop types . F # seems particularly sensitive to these type issues . Casting on the F # side does not seem to help the situation . All three projects have a reference to the same assembly ( `` Microsoft.Office.Interop.Excel '' version 14.0.0.0 ) .In project `` Project1 '' ( a C # project ) : In project `` Project2 '' ( a C # project ) : In project `` TestApp '' ( an F # project ) : Any hints ? Edit : Changing the call to Class2 's constructor with the following dynamic cast solves the problem : However , this is unsatisfying , since it is 1 ) dynamic , and 2 ) I still do n't understand why the original type check failed . <code> namespace Project1 { public class Class1 { public static Microsoft.Office.Interop.Excel.Application GetApp ( ) { return new Microsoft.Office.Interop.Excel.Application ( ) ; } } } namespace Project2 { public class Class2 { Microsoft.Office.Interop.Excel.Application _app ; public Class2 ( Microsoft.Office.Interop.Excel.Application app ) { _app = app ; } } } [ < EntryPoint > ] let main argv = let c2 = Project2.Class2 ( Project1.Class1.GetApp ( ) ) 0 let c2 = Project2.Class2 ( Project1.Class1.GetApp ( ) : ? > Microsoft.Office.Interop.Excel.Application ) | The type 'T ' is not compatible with the type 'T ' |
C_sharp : I 'm using NuGetVersion from the NuGet.Versioning package in LinqPad . I 'm trying to Dump ( ) it to inspect it 's properties , but instead of the usual dump I just get the string representation.For example , this : Shows the following in the output window : Does anyone know why LinqPad runs ToString ( ) when some types are dumped , and how to change this behaviour ? <code> var v = new NuGetVersion ( `` 1.0.0 '' ) ; v.Dump ( ) ; 1.0.0 | Why does LinqPad run ToString ( ) on some types when they are dumped ? |
C_sharp : This question is particularly pointed at other C # devs coming over to TypeScript in VS Code.I fell in love with the code completion in VS C # . To illustrate , say I 'm trying to write : Using C # , I would have : type `` con '' a list of suggestions would appear , probably starting with `` console '' since that 's highlighted and it 's what I want , hitting `` . '' will write out `` sole . '' so now I have : console.type `` l '' , `` log '' is the first suggestiontype `` ( `` , now I have : console.log ( `` ) cursor is now in the `` type `` hello '' Currently with my VS Code setup , the same thing can be achieved in JS/TS hitting tab each time I want to accept a suggestion . But just hitting the next punctuation to proceed was really nice and , if you forgive me for caring about it , `` fun . '' I miss it . And there 's no technical limitation of the languages that I know of that would prohibit this behavior.Anyone know if there 's any extension or setting available to enable this ? Or else , where else this conversation may be occurring ? <code> console.log ( 'hello ' ) | Can VS Code code completion be configured to accept a suggestion on punctuation ? |
C_sharp : I am querying built-in TimeoutData entity in RavenDB using Raven.Client.Lightweight 2.5 library to get specific timeout document . It is possible that TimeoutData does not exist in the database because no document is stored there yet . In that case NotSupportedException is thrown when you try to query it.Currently I have created workaround for this situation : Is it possible to verify if TimeoutData exist without using try-catch ? I have also tried the following code but it returns false when documents exist in TimeoutData entity : <code> try { timeoutData = _session.Query < TimeoutData > ( ) .FirstOrDefault ( t = > t.Headers.ContainsValue ( someValue ) ) ; } catch ( NotSupportedException ) { return null ; } if ( ! _session.Query < TimeoutData > ( ) .Any ( ) ) { } | How to check if table ( entity ) exists in RavenDB |
C_sharp : Can I unit test my multi-threaded code using CHESS & MSTest in VS 2010 . I tried this but I get the following error <code> [ TestMethod ] [ HostType ( `` Chess '' ) ] [ TestProperty ( `` ChessExpectedResult '' , `` deadlock '' ) ] public void TestMyMethod ( ) { ... } The host type 'Chess ' can not be loaded for the following reason : The key 'Chess ' can not be found | MSTest + CHESS in VS 2010 |
C_sharp : As I understand it , each language can have it 's own dynamic handler , so that the appropriate rules are applied . I 'm unsure if the following is correct/incorrect ; thoughts ? Scenario : two interfaces ( one implements the other ) with some methods : and a basic implementation : Now , with normal C # ( no dynamic ) , we can access methods of IA from a target of type IB : Now let 's deliberately add some dynamic to the arguments , which makes the entire invoke use dynamic processing ( as in the general case this could impact overload resolution , although it wo n't here ) : Which fails with the RuntimeBinderException : 'IB ' does not contain a definition for 'Bar'Now , what it says is entirely correct in as much as IB does not have a Bar method . However , as illustrated in the first example : under normal C # rules would expect that since the declaration type of the target is an interface ( IB ) , the other interfaces known to be implemented ( i.e . IA ) are checked as part of overload resolution.So : is this a bug ? Or am I misreading it ? <code> public interface IA { void Bar ( object o ) ; } public interface IB : IA { void Foo ( object o ) ; } public class B : IB { public void Foo ( object o ) { Console.WriteLine ( `` Foo '' ) ; } public void Bar ( object o ) { Console.WriteLine ( `` Bar '' ) ; } } IB b = new B ( ) ; var o = new { y = `` z '' } ; b.Foo ( o.y ) ; // fineb.Bar ( o.y ) ; // fine IB b = new B ( ) ; dynamic x = new { y = `` z '' } ; b.Foo ( x.y ) ; // fineb.Bar ( x.y ) ; // BOOM ! | Should an interface-based method invoke that uses `` dynamic '' still obey C # method resolution rules ? |
C_sharp : If I create a simple class like the following : and examine it within NDepend , it shows that the TestMethod taking a bool and being async Task has a struct generated for it with an enumerator , the enumerator state machine and some additional stuff.Why does the compiler generate a struct called TestClass+ < TestMethod > d__0 with an enumerator for the async method ? It seems to generate more IL than what the actual method produces . In this example , the compiler generates 35 lines of IL for my class , while it generates 81 lines of IL for the struct . It 's also increasing the complexity of the compiled code and causing NDepend to flag it for several rule violations . <code> public class TestClass { public Task TestMethod ( int someParameter ) { return Task.FromResult ( someParameter ) ; } public async Task TestMethod ( bool someParameter ) { await Task.FromResult ( someParameter ) ; } } | Why does the async keyword generate an enumerator & additional struct when compiled ? |
C_sharp : Using the silverlight Windows Phone 8.1 ProjectI 'm trying to load data from a website . I have to authenticate at that site first however.So I do a post to the Website , using a lightly modified version of the CookieAwareWebClient from here.Now I make a WebClient send a POST with Username and Password and continue getting my sites async and processing the site data in my DownloadStringCompleted-EventHandler.So far so good.Now I want to expand on that and get multiple websites.I do n't have to get them all at once , in fact it would be better to get them one after another.But I do n't know how to go at this.My code so far : What I tryed / What I expected / What did block that : My first thought was to let everything happen async and use await on all the requests.So I did my research and found that WebClient has an new async/await implementation.WebClient.DownloadStringTaskAsync however I ca n't find this method in my WebClient , so I assume there is n't an impementation for WP8.1 atm.2nd idea was to use the HttpClient.GetStringAsync ( URI ) methode which I use already and which supports async/await.As I said , I need a Cookie to go with the request , so I did my research and found this.However I ca n't find a HttpClientHandler and also no HttpClient.CookieContainer or equal attributes.I also tried waiting for one site to complete and then going to the next , but tbo I blocked my GUI thread and did n't want to struggle with writing the whole eventhandlers in separate threads and I do n't know how to do so efficiently <code> class CookieAwareWebClient : WebClient { public CookieContainer Cookies = new CookieContainer ( ) ; protected override WebRequest GetWebRequest ( Uri address ) { var request = base.GetWebRequest ( address ) ; if ( request is HttpWebRequest ) ( request as HttpWebRequest ) .CookieContainer = Cookies ; return request ; } } using System ; using System.Net ; using System.Text.RegularExpressions ; using System.Threading.Tasks ; using System.Windows ; using System.Windows.Controls ; using Windows.Web.Http ; using Microsoft.Phone.Shell ; using StackOverflowApp.Resources ; namespace StackOverflowApp { public partial class MainPage { private const string URL_DATES = @ '' /subsite/dates '' ; private const string URL_RESULTS = @ '' /subsite/results '' ; private readonly ApplicationBarIconButton btn ; private int runningOps = 0 ; //Regex 's to parse websites private readonly Regex regexDates = new Regex ( AppResources.regexDates ) ; private readonly Regex regexResults = new Regex ( AppResources.regexResults ) ; private readonly CookieAwareWebClient client = new CookieAwareWebClient ( ) ; private int status ; // Konstruktor public MainPage ( ) { InitializeComponent ( ) ; btn = ( ( ApplicationBarIconButton ) ApplicationBar.Buttons [ 0 ] ) ; // = application/x-www-form-urlencoded client.Headers [ HttpRequestHeader.ContentType ] = AppResources.ContentType ; client.UploadStringCompleted += UploadStringCompleted ; client.DownloadStringCompleted += DownloadStringCompleted ; } private void GetSite ( ) { const string POST_STRING = `` name= { 0 } & password= { 1 } '' ; var settings = new AppSettings ( ) ; if ( settings.UsernameSetting.Length < 3 || settings.PasswordSetting.Length < 3 ) { MessageBox.Show ( ( settings.UsernameSetting.Length < 3 ? `` Bitte geben Sie in den Einstellungen einen Benutzernamen ein\r\n '' : string.Empty ) + ( settings.PasswordSetting.Length < 3 ? `` Bitte geben Sie in den Einstellungen ein Kennwort ein\r\n '' : string.Empty ) ) ; return ; } LoadingBar.IsEnabled = true ; LoadingBar.Visibility = Visibility.Visible ; client.UploadStringAsync ( new Uri ( AppResources.BaseAddress + `` subsite/login '' ) , `` POST '' , string.Format ( POST_STRING , settings.UsernameSetting , settings.PasswordSetting ) ) ; } private void LoadDates ( ) { status = 0 ; //Termine runningOps++ ; client.DownloadStringAsync ( new Uri ( AppResources.BaseAddress + URL_DATES ) ) ; } private void LoadResults ( ) { status = 1 ; //Ergebnisse runningOps++ ; client.DownloadStringAsync ( new Uri ( AppResources.BaseAddress + URL_RESULTS ) ) ; } private void DownloadStringCompleted ( object sender , DownloadStringCompletedEventArgs e ) { runningOps -- ; if ( runningOps == 0 ) { //alle Operationen sind fertig LoadingBar.IsEnabled = false ; LoadingBar.Visibility = Visibility.Collapsed ; btn.IsEnabled = true ; } if ( e.Cancelled || e.Error ! = null ) return ; //Antwort erhalten var source = e.Result.Replace ( `` \r '' , `` '' ) .Replace ( `` \n '' , `` '' ) ; switch ( status ) { case 0 : //Termine geladen foreach ( Match match in regexDates.Matches ( source ) ) { var tb = new TextBlock ( ) ; var g = match.Groups ; tb.Text = string.Format ( `` { 1 } { 2 } { 3 } { 0 } { 4 } { 5 } { 0 } { 6 } '' , Environment.NewLine , g [ 1 ] .Value , g [ 2 ] .Captures.Count > 0 ? g [ 2 ] .Value : string.Empty , g [ 3 ] .Captures.Count > 0 ? `` - `` + g [ 3 ] .Value : string.Empty , g [ 5 ] .Value , g [ 6 ] .Captures.Count > 0 ? `` bei `` + g [ 6 ] .Value : string.Empty , ( g [ 7 ] .Captures.Count > 0 ? g [ 7 ] .Value : string.Empty ) + ( g [ 8 ] .Captures.Count > 0 ? g [ 8 ] .Value ! = g [ 4 ] .Value ? g [ 8 ] .Value + `` ! = `` + g [ 4 ] .Value : g [ 8 ] .Value : g [ 4 ] .Captures.Count > 0 ? g [ 4 ] .Value : string.Empty ) ) ; DatesPanel.Children.Add ( tb ) ; } break ; case 1 : //Ergebnisse geladen foreach ( Match match in regexResults.Matches ( source ) ) { var tb = new TextBlock ( ) ; var g = match.Groups ; tb.Text = string.Format ( `` { 1 } { 2 } { 3 } { 0 } { 4 } { 5 } { 0 } { 6 } '' , Environment.NewLine , g [ 1 ] .Value , g [ 2 ] .Captures.Count > 0 ? g [ 2 ] .Value : string.Empty , g [ 3 ] .Captures.Count > 0 ? `` - `` + g [ 3 ] .Value : string.Empty , g [ 5 ] .Value , g [ 6 ] .Captures.Count > 0 ? `` bei `` + g [ 6 ] .Value : string.Empty , ( g [ 7 ] .Captures.Count > 0 ? g [ 7 ] .Value : string.Empty ) + ( g [ 8 ] .Captures.Count > 0 ? g [ 8 ] .Value ! = g [ 4 ] .Value ? g [ 8 ] .Value + `` ! = `` + g [ 4 ] .Value : g [ 8 ] .Value : g [ 4 ] .Captures.Count > 0 ? g [ 4 ] .Value : string.Empty ) ) ; ResultsPanel.Children.Add ( tb ) ; } break ; default : return ; } } void UploadStringCompleted ( object sender , UploadStringCompletedEventArgs e ) { //Login completed LoadDates ( ) ; //THIS WOULD YIELD AN ERROR FROM THE WEBCLIENT SAYING IT ISNT SUPPORTING MULTIPLE ASYNC ACTIONS //LoadResults ( ) ; } private async void ClickOnRefresh ( object sender , EventArgs e ) { var isUp = await IsUp ( ) ; if ( isUp ) GetSite ( ) ; else MessageBox.Show ( `` Die Seite ist down ! : ( `` ) ; } private void ClickOnSettings ( object sender , EventArgs e ) { NavigationService.Navigate ( new Uri ( `` /Settings.xaml '' , UriKind.Relative ) ) ; } private async Task < bool > IsUp ( ) { btn.IsEnabled = false ; const string ISUPMELINK = `` http : //www.isup.me/ { 0 } '' ; var data = await RequestData ( string.Format ( ISUPMELINK , AppResources.BaseAddress.Replace ( `` https : // '' , string.Empty ) ) ) ; var isUp = ! data.Contains ( `` It 's not just you ! `` ) ; btn.IsEnabled = true ; return isUp ; } private async void ClickOnTestConnection ( object sender , EventArgs e ) { var isUp = await IsUp ( ) ; MessageBox.Show ( string.Format ( `` Die Seite ist { 0 } ! : { 1 } '' , isUp ? `` up '' : `` down '' , isUp ? `` ) '' : `` ( `` ) ) ; } private static async Task < string > RequestData ( string url ) { using ( var httpClient = new HttpClient ( ) ) return await httpClient.GetStringAsync ( new Uri ( url ) ) ; } } } | How can I retrieve multiple websites asynchronously ? |
C_sharp : I 'm using events as part of a game model , and for extensibility and code `` locality 's '' sake I need to be able to veto most actions.More clearly , nearly every method that has a side effect takes this form : What I 'd like is for TryingToDoSomething ( ... ) to be able to indicate that a registered event handler objects ( via returning false , modifying an out parameter , or something ) . So that the code is morally equivalent to : Is there an accepted or standard way to do this in C # /.NET ? <code> public event TryingToDoSomethingHandler TryingToDoSomething ; public event SomethingHappenedHandler SomethingHappened ; /* * Returning true indicates Something happened successfully . */public bool DoSomething ( ... ) { //Need a way to indicate `` veto '' here TryingToDoSomething ( ... ) ; //Actual do it SomethingHappened ( ... ) ; return true ; } /* * Returning true indicates Something happened successfully . */public bool DoSomethingImproved ( ... ) { //Pretty sure multicast delegates do n't work this way , but you get the idea if ( ! TryingToDoSomething ( ... ) ) return false ; //Actual do it SomethingHappened ( ... ) ; return true ; } | Is there a standard way to implement `` Vetoable '' events ? |
C_sharp : A little background : I 'm a WPF to WinForms convertee and for some time I 've been migrating my application.I was reported by a friend that my code does n't work on Windows XP ( it generates a stack overflow at startup ) even though it works fine on Windows 7 ( which I develop in ) .After a little research , what caused the problem was something along these lines : Now that I noticed the obviously poor decision , I was n't wondering why it does n't work on Windows XP . I was wondering why does it work on Windows 7.Obviously at some point the compiler figures out what I 'm trying to do and prevents the same event to be fired over and over again , but I 'd much rather have it do nothing , so I can see and squish the bug on sight on the platform I 'm developing in , rather than have to test it under two platforms simultaneously . Back in WPF I could handle such behaviour manually by setting e.Handled to 'true ' , in WinForms apparently there 's no such thing.Is there some sort of a compiler flag for this ? <code> private void listView1_SelectedIndexChanged ( object sender , EventArgs e ) { listView1.SelectedIndices.Clear ( ) ; listView1.Items [ 0 ] .Selected = true ; } | Why does this code work on Windows 7 , but does n't on Windows XP ? |
C_sharp : Imagine someone coding the following : We all know that in the example above , the call to the “ ToUpper ( ) ” method is meaningless because the returned string is not handled at all . But yet , many people make that mistake and spend time trying to troubleshoot what the problem is by asking themselves “ Why aren ’ t the characters on my ‘ s ’ variable capitalized ” ? ? ? ? So wouldn ’ t it be great if there was an attribute that could be applied to the “ ToUpper ( ) ” method that would yield a compiler error if the return object is not handled ? Something like the following : If order for this code to compile correctly the user would have to handle the return value like this : I think this would make it crystal clear that you must handle the return value otherwise there is no point on calling that function.In the case of the string example this may not be a big deal but I can think of other more valid reasons why this would come in handy.What do you guys think ? Thanks . <code> string s = `` SomeString '' ; s.ToUpper ( ) ; [ MustHandleReturnValueAttribute ] public string ToUpper ( ) { … } string s = `` SomeString '' ; string uppers = s.ToUpper ( ) ; | C # Compiler Enhancement Suggestion |
C_sharp : When I write a value into a field , what guarantees do I get regarding when the new value will be saved in the main memory ? For example , how do I know that the processor do n't keep the new value in it 's private cache , but updated the main memory ? Another example : Is there a possibility that after Write ( ) was finished executing , some other thread executes Read ( ) but actually will see `` 0 '' as the current value ? ( since perhaps the previous write to m_foo was n't flushed yet ? ) .What kind of primitives ( beside locks ) are available to ensure the the writes were flushed ? EDITIn the code sample I 've used , the write and read are placed at different method . Does n't Thread.MemoryBarrier only affect instruction reording that exist in the same scope ? Also , let 's assume that they wo n't be inlined by the JIT , how can I make sure that the value written to m_foo wo n't be stored in a register , but to the main memory ? ( or when m_foo is read , it wo n't get an old value from the CPU cache ) . Is it possible to achieve this without using locks or the 'volatile ' keyword ? ( also , let 's say I 'm not using primitive types , but a WORD sized structs [ so volatile can not be applied ] . ) <code> int m_foo ; void Read ( ) // executed by thread X ( on processor # 0 ) { Console.Write ( m_foo ) ; } void Write ( ) // executed by thread Y ( on processor # 1 ) { m_foo = 1 ; } | When do writes/reads affect main memory ? |
C_sharp : I have to rotate JPG images lossless in .net ( 90°|180°|270° ) . The following articles show how to do it : https : //docs.microsoft.com/en-us/dotnet/api/system.drawing.imaging.encoder.transformation ? view=netframework-4.7.2https : //www.codeproject.com/tips/64116/Using-GDIplus-code-in-a-WPF-application-for-lossle.aspxThe examples seem quite straightforward ; however , I had no luck getting this to work . My source data comes as an array ( various JPG files , from camera from internet etc . ) and so I want to return the rotated images also as a byte array . Here the ( simplified ) code : I always get an ArgumentException from GDI+ without any useful information : The operation failed with the final exception [ ArgumentException ] . Source : System.DrawingI tried an awful lot of things , however never got it working . The main code seems right , since if I change the EncoderParameter to Encoder.Quality , the code works fine : I found some interesting posts about this problem in the internet , however no real solution . One particularly contains a statement from Hans Passant , that this seems to be really a bug , with a response from an MS employee , which I do n't understand or which may be also simply weird : https : //social.msdn.microsoft.com/Forums/vstudio/en-US/de74ec2e-643d-41c7-9d04-254642a9775c/imagesave-quotparameter-is-not-validquot-in-windows-7 ? forum=netfxbclHowever this post is 10 years old and I can not believe , that this is not fixed , especially since the transformation has an explicit example in the MSDN docs . Does anyone have a hint , what I 'm doing wrong , or , if this is really a bug , how can I circumvent it ? Please note that I have to make the transformation lossless ( as far as the pixel-size allows it ) . Therefore , Image.RotateFlip is not an option.Windows version is 10.0.17763 , .Net is 4.7.2 <code> Image image ; using ( var ms = new MemoryStream ( originalImageData ) ) { image = System.Drawing.Image.FromStream ( ms ) ; } // If I do n't copy the image into a new bitmap , every try to save the image fails with a general GDI+ exception . This seems to be another bug of GDI+.var bmp = new Bitmap ( image ) ; // Creating the parameters for savingvar encParameters = new EncoderParameters ( 1 ) ; encParameters.Param [ 0 ] = new EncoderParameter ( Encoder.Transformation , ( long ) EncoderValue.TransformRotate90 ) ; using ( var ms = new MemoryStream ( ) ) { // Now saving the image , what fails always with an ArgumentException from GDI+ // There is no difference , if I try to save to a file or to a stream . bmp.Save ( ms , GetJpgEncoderInfo ( ) , encParameters ) ; return ms.ToArray ( ) ; } encParameters.Param [ 0 ] = new EncoderParameter ( Encoder.Quality , 50L ) ; | Lossless rotation of a JPG image with Image.Save and EncoderParameters fails |
C_sharp : I have a program on .NET 4 for Windows . I 'm trying to port it for Mac computers with mono and Xamarin studio.I have third-part library EmguCV ( it 's a wrapper for OpenCV library ) . I 'm using official manual to install it . It installs both OpenCV and EmguCV to Library/Python/2.7/site-packages/emgucv/libWhen I start program in Debug mode from Xamarin - all works fine . It founds all libraries and use it . But when I make program as `` pak '' and run on computer without installed EmguCV - I got `` DLL not found '' exception.I make my program with this command : My second and third params should attached EmguCV libraries to my pak : -r : /Library/Python/2.7/site-packages/emgucv/lib-r : /Library/Python/2.7/site-packages/emgucv/binAnd when I 'm looking inside pak - I find this libraries . However the program still not found it..I guess trouble in openCV native libraries , but I ca n't realize what is wrong : ( <code> macpack -m:1 -o : . -r : /Library/Frameworks/Mono.framework/Versions/Current/lib/ -r : /Library/Python/2.7/site-packages/emgucv/lib -r : /Library/Python/2.7/site-packages/emgucv/bin -r : Assimp32.dll -r : Assimp64.dll -r : cvextern.dll -r : Emgu.CV.dll -r : Emgu.Util.dll -r : libegl.dll -r : libglesv2.dll -r : OpenTK.dll -r : OpenTK.GLControl.dll -r : RH.AssimpNet.dll -r : RH.HeadEditor.dll -r : RH.ImageListView.dll -r : RH.HeadShop.exe -r : blending.fs -r : blending.vs -r : blendingPl.vs -r : idle.fs -r : idle.vs -r : skelet.vs -r : sprite.png -r : ./Libraries -r : ./Models -r : ./Plugin -r : ./Resources -r : ./Stages -r : ./ '' Haar Cascades '' -n : HeadShop -a : RH.HeadShop.exe | How to attach third-part libraries in release version |
C_sharp : I ca n't get this to work for font names that are 16 characters or longer , but the console itself obviously does n't have this limitation . Does anyone know a programmatic way to set the font that will work with the built-in `` Lucida Sans Typewriter '' or the open source `` Fira Code Retina '' ? This following code works : I have copied PInvoke code from various places , particularly the PowerShell console host , and the Microsoft DocsNote that the relevant docs for CONSOLE_FONT_INFOEX and SetCurrentConsoleFontEx do not talk about this , and the struct defines the font face as a WCHAR field of size 32 ... Also note what 's not a limitation , but is a restriction from the console dialog , is that the font has to have True Type outlines , and must be genuinely fixed width . Using this API you can chose variable width fonts like `` Times New Roman '' ... However , in the API , it has to have less than 16 characters in the name -- which is a restriction the console itself does n't have , and may be a bug in the API and not my code below You can play with it in a PowerShell window by using Add-Type with that code , and then doing something like this : Then , use your console `` Properties '' dialog and manually switch to Lucida Sans Typewriter ... and try just changing the font size , specifying the same font name : And you 'll get output like this ( showing the three settings : before , what we tried , and what we got ) : You see that weird character on the end of the `` before '' value ? That 's happens whenever the font is longer than 16 characters ( I 'm getting garbage data because of a problem in the API or the marshalling ) . The actual console font name is obviously not length limited , but perhaps it 's not possible to use a font with a name that 's 16 characters or longer ? For what it 's worth , I discovered this problem with Fira Code Retina , a font that has exactly 16 characters in the name -- and I have a little bit more code than what 's above in a gist here if you care to experiment ... <code> using System ; using System.Runtime.InteropServices ; public static class ConsoleHelper { private const int FixedWidthTrueType = 54 ; private const int StandardOutputHandle = -11 ; [ DllImport ( `` kernel32.dll '' , SetLastError = true ) ] internal static extern IntPtr GetStdHandle ( int nStdHandle ) ; [ return : MarshalAs ( UnmanagedType.Bool ) ] [ DllImport ( `` kernel32.dll '' , SetLastError = true , CharSet = CharSet.Unicode ) ] internal static extern bool SetCurrentConsoleFontEx ( IntPtr hConsoleOutput , bool MaximumWindow , ref FontInfo ConsoleCurrentFontEx ) ; [ return : MarshalAs ( UnmanagedType.Bool ) ] [ DllImport ( `` kernel32.dll '' , SetLastError = true , CharSet = CharSet.Unicode ) ] internal static extern bool GetCurrentConsoleFontEx ( IntPtr hConsoleOutput , bool MaximumWindow , ref FontInfo ConsoleCurrentFontEx ) ; private static readonly IntPtr ConsoleOutputHandle = GetStdHandle ( StandardOutputHandle ) ; [ StructLayout ( LayoutKind.Sequential , CharSet = CharSet.Unicode ) ] public struct FontInfo { internal int cbSize ; internal int FontIndex ; internal short FontWidth ; public short FontSize ; public int FontFamily ; public int FontWeight ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 32 ) ] // [ MarshalAs ( UnmanagedType.ByValArray , ArraySubType = UnmanagedType.wc , SizeConst = 32 ) ] public string FontName ; } public static FontInfo [ ] SetCurrentFont ( string font , short fontSize = 0 ) { Console.WriteLine ( `` Set Current Font : `` + font ) ; FontInfo before = new FontInfo { cbSize = Marshal.SizeOf < FontInfo > ( ) } ; if ( GetCurrentConsoleFontEx ( ConsoleOutputHandle , false , ref before ) ) { FontInfo set = new FontInfo { cbSize = Marshal.SizeOf < FontInfo > ( ) , FontIndex = 0 , FontFamily = FixedWidthTrueType , FontName = font , FontWeight = 400 , FontSize = fontSize > 0 ? fontSize : before.FontSize } ; // Get some settings from current font . if ( ! SetCurrentConsoleFontEx ( ConsoleOutputHandle , false , ref set ) ) { var ex = Marshal.GetLastWin32Error ( ) ; Console.WriteLine ( `` Set error `` + ex ) ; throw new System.ComponentModel.Win32Exception ( ex ) ; } FontInfo after = new FontInfo { cbSize = Marshal.SizeOf < FontInfo > ( ) } ; GetCurrentConsoleFontEx ( ConsoleOutputHandle , false , ref after ) ; return new [ ] { before , set , after } ; } else { var er = Marshal.GetLastWin32Error ( ) ; Console.WriteLine ( `` Get error `` + er ) ; throw new System.ComponentModel.Win32Exception ( er ) ; } } } [ ConsoleHelper ] : :SetCurrentFont ( `` Consolas '' , 16 ) [ ConsoleHelper ] : :SetCurrentFont ( `` Lucida Console '' , 12 ) [ ConsoleHelper ] : :SetCurrentFont ( `` Lucida Sans Typewriter '' , 12 ) Set Current Font : Lucida Sans TypewriterFontSize FontFamily FontWeight FontName -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 14 54 400 Lucida Sans Typeʈ 12 54 400 Lucida Sans Typewriter 12 54 400 Courier New | SetCurrentConsoleFontEx is n't working for long font names |
C_sharp : I have a case where I have the name of an object , and a bunch of file names . I need to match the correct file name with the object . The file name can contain numbers and words , separated by either hyphen ( - ) or underscore ( _ ) . I have no control of either file name or object name . For example : The object name in this case is just a string , representing an numberI need to return true or false if the file name is a match for the object name . The different segments of the file name can match on their own , or any combination of two segments . In the example above , it should be true for the following cases ( not every true case , just examples ) : And , we should return false for this case ( among others ) : What I 've come up with so far is this : One or two segments combined can make a match , and that is enought . Three or more segments combined should not be considered.This does work so far , but is there a better way to do it , perhaps without nesting foreach loops ? <code> 10-11-12_001_002_003_13001_13002_this_is_an_example.svg 10001 1000110002100031100111002110031200112002120031300113002 13003 public bool IsMatch ( string filename , string objectname ) { var namesegments = GetNameSegments ( filename ) ; var match = namesegments.Contains ( objectname ) ; return match ; } public static List < string > GetNameSegments ( string filename ) { var segments = filename.Split ( ' _ ' , '- ' ) .ToList ( ) ; var newSegments = new List < string > ( ) ; foreach ( var segment in segments ) { foreach ( var segment2 in segments ) { if ( segment == segment2 ) continue ; var newToken = segment + segment2 ; newSegments.Add ( newToken ) ; } } return segments.Concat ( newSegments ) .ToList ( ) ; } | How to combine items in List < string > to make new items efficiently |
C_sharp : With a setup like this , I can show a singular list containing books , authors , and bookmarks . I can drill down into a book , and see that specific books authors and bookmarks.Problem # 1 : I 'd like to drill down into an author , and see all of the authors books . On top of that , I 'd like to see all the bookmarks for all the books by that author.An easy solution is to add the appropriate lists to each other class . eg.public List < Book > Books to the Author class . However , this gets out of hand when you start adding more categories ( eg . Genre , Publisher , Language , etc ) Problem 2 : I 'd also like to be able to sort my list by the number of any selected tag , including any relevant tag type : MyItemsView.SortDescriptions.Add ( new SortDescription ( `` Bookmarks.Count '' , Descending ) ; The number of bookmarks an author has should be the sum of all the bookmarks for all their books . What is a good way to architect this kind of data so as to not have to maintain multiple lookup collections for every type ? Is using Book as a source of truth not a good approach ? Ideally I 'd be able to sort by any tag type.In my real application , I have solved problem # 1 : when drilling down into eg . an Author , I find all the Book in MyItems with a matching author , and then pull all the Genre , Publisher , etc from the list of books pulled . In this way I can display all the tags an author has based on the tags their books provided . ( I do this in the scope of my list view model , as I know which item I am drilling down into and have access to the main MyItems collection ) However , using this approach I ca n't seem to solve problem # 2 . To be able to sort on Bookmarks.Count , I need to move it into Base and somehow populate it for each relevant tag type . How can I expose this kind of information to each non-Book tag type without giving each Author or Bookmark access to the global item collection ( which feels like a big no-no ) , or maintaining lists of all relevant tags for each tag type ( which just feels really painfully inefficient ) ? Edit 1 : Can you define `` tag '' and `` tag type '' and give a few more examples ? I 'm using tag to define any kind of item i 'd like to put into my list . A Book , an Author , a Bookmark are all tags . Language and Genre would also be tags . A book has authors , and languages , just like a language has books and authors.Edit2 : Even if you do n't plan to have a backing database , you should benefit from brushing up on your Entity-Relationship Model knowledgeI understand this is a highly relational structure . I do have a backing database but how it is stored in the database has little relevance with how to structure the data to be bound to a ListCollectionView <code> public class Base : ICustomItem { } public class Book : Base { public List < Author > Authors ; public List < Bookmark > Bookmarks ; } public class Author : Base { } public class Bookmark : Base { } public ObservableCollection ( ICustomItem ) MyItems ; public ListCollectionView MyItemsView { get ; } = new ListCollectionView ( MyItems ) ; | Architecting a collection of related items of different types |
C_sharp : I have an Item that contains a list of Product 's which are mapped to their respective ViewModel objects using AutoMapper.In my MVC project I have an Action method that displays an Item with a selected Product . For this i have a ViewModel called ItemDetailsViewModel that contains the flattened Item object , a list of ProductViewModel 's and a flattened selected Product.The difficulty I am having is best showing this flattened selected Product.Think of it like eBay where you have an Item and you can choose multiple variations e.g . by colour . For me , the multiple variations are the Products . When the user selects the Product I want to return the ItemDetails i.e . the Item , the list of Products and the selected Product.I was wondering the best way of doing this ? At the moment my method is mapping an Item to an ItemDetailsViewModel , selecting the desired ProductViewModel and then specifically mapping each property of the ProductViewModel back onto the ItemDetailsViewModel . Also , due to the Item and Product having the same named properties , the last line mapping the product back overwrites the Items id and code.Any suggestions on how best to configure the mapping ? I 've left out the mapping I have in place as it is mostly a direct one-to-one mapping apart from mapping the selected ProductViewModel back to the ItemDetailsViewModel.ClassesAction <code> Mapper.CreateMap < Item , ItemViewModel > ( ) .ReverseMap ( ) ; Mapper.CreateMap < ProductViewModel , ItemDetailsViewModel > ( ) .ForMember ( d = > d.ProductId , o = > o.MapFrom ( s = > s.Id ) ) .ForMember ( d = > d.ProductCode , o = > o.MapFrom ( s = > s.Code ) ) ; public class Item { public int Id { get ; set ; } public string Code { get ; set ; } public IList < Product > Products { get ; set ; } } public class Product { public int Id { get ; set ; } public string Code { get ; set ; } } public class ItemViewModel { public int Id { get ; set ; } public string Code { get ; set ; } public IList < ProductViewModel > Products { get ; set ; } } public class ItemDetailsViewModel : ItemViewModel { public int ProductId ; public string ProductCode ; } public class ProductViewModel { public int Id { get ; set ; } public string Code { get ; set ; } } public ActionResult ItemDetails ( ) { var item = new Item { Id = 1 , Code = `` Item1 '' , Products = new List < Product > ( ) { new Product { Id = 1 , Code = `` Product1 '' } , new Product { Id = 2 , Code = `` Product2 '' } , new Product { Id = 3 , Code = `` Product3 '' } , } } ; var productCode = `` Product2 '' ; var itemDetailsViewModel = Mapper.Map < ItemDetailsViewModel > ( item ) ; if ( itemDetailsViewModel.Products ! = null & & itemDetailsViewModel.Products.Count > 0 ) { ProductViewModel productViewModel = null ; if ( ! String.IsNullOrEmpty ( productCode ) ) productViewModel = itemViewModel.Products.FirstOrDefault ( e = > e.Code.Equals ( productCode , StringComparison.OrdinalIgnoreCase ) ) ; if ( productViewModel == null ) productViewModel = itemViewModel.Products [ 0 ] ; Mapper.Map < ProductViewModel , ItemDetailsViewModel > ( productViewModel , itemDetailsViewModel ) ; } } | How to flatten a conditional object in a list in automapper |
C_sharp : There are multiple related questions , but I 'm looking for a solution specific to my case . There is an array of ( usually ) 14 integers , each in the range of 1 to 34 . How can I quickly tell if each int in a specific , static list appears at least once in this array ? For reference , I 'm currently using this code , which was written to resemble the spec as closely as possible , so it can certainly be improved vastly : The required list is not dynamic , i.e . it will always be the same during runtime . Using Linq is optional , the main aspect is performance.Edit : The input array is not sorted.Input values may appear multiple times.The input array will contain at least 14 items , i.e . 1 more than the required array.There is only 1 required array and it is static.The values in required are distinct.You may assume that a histogram is cheap to create.Update : I am also interested in a solution for a sorted input array . <code> if ( array.Count < 13 ) { return ; } var required = new int [ ] { 0*9 + 1 , 0*9 + 9 , 1*9 + 1 , 1*9 + 9 , 2*9 + 1 , 2*9 + 9 , 3*9 + 1 , 3*9 + 2 , 3*9 + 3 , 3*9 + 4 , 3*9 + 5 , 3*9 + 6 , 3*9 + 7 , } ; IsThirteenOrphans = ! required.Except ( array ) .Any ( ) ; | How can I quickly tell if a list contains a list ? |
C_sharp : First of all , I want to say that I 'm new to C # , so this question may seem completely off track.I have a set of enumerables called ShapeType : And a method to return a random value from the enumerables : Every enumerable has a corresponding concrete class . And the question I 'm wondering about is if you can instantiate a class by using the random enumerable value randomShape , kind of like this : Is this possible or is it just wishful thinking ? <code> Cube , Sphere , Rectangle , Ellipse private static ShapeType GetRandomShape ( ) { Array values = Enum.GetValues ( typeof ( ShapeType ) ) ; Random random = new Random ( ) ; ShapeType randomShape = ( ShapeType ) values.GetValue ( random.Next ( values.Length ) ) ; return randomShape ; } private static Shape GetRandomShape ( ) { Array values = Enum.GetValues ( typeof ( ShapeType ) ) ; Random random = new Random ( ) ; ShapeType randomShape = ( ShapeType ) values.GetValue ( random.Next ( values.Length ) ) ; Shape shape = new randomShape ( ) ; // *Here use the randomShape-variable as type* return shape ; } | Use variable as type and instantiate it |
C_sharp : I have an application which takes a string value of the form % programfiles % \directory\tool.exe from its application config file.I want to make this into a useable filename so that I can call and have it execute the application . I 'm curently getting a System.ComponentModel.Win32Exception - The system can not find the file specifiedMany thanks for any help with this . <code> System.Diagnostics.Process.Start ( filename ) | How do I convert a string of the form % programfiles % \directory\tool.exe to a useable Filename in C # /.net ? |
C_sharp : I 'm trying to create a class that takes a lambda and stores it internally . The syntax would be something like : Usage : But I 'm having some trouble figuring out the details . I know that a lambda is an anon type until it 's assigned to either an expression or a delegate and that I would ( I believe ) have to use an implicit operator to get the syntax I 'm going for , but beyond that I 've hit a wall . I can use Expression or Func in my implicit operator if they 've already been assigned to a variable like so : But I 'd much prefer to just assign the lambda itself and have the class figure out the details . <code> class Lambda < TIn , TOut > { private Expression < Func < TIn , TOut > > expr ; private Func < TIn , TOut > > func ; public Lambda ( Expression < Func < TIn , TOut > > e ) { expr = e ; } public Lambda ( Func < TIn , TOut > f ) { func = f ; } public static implicit operator Lambda < TIn , TOut > ( [ lambdatype ] o ) { return new Lambda ( o ) ; } } Lambda < TIn , TOut > l = o = > ... ; Expression < Func < T1 , T2 > > e = o = > ... ; Func < T1 , T2 > f = o = > ... ; Lambda < T1 , T2 > l1 = e , l2 = f ; | Implicit Operators and lambdas |
C_sharp : I 'm trying to write a VBA parser ; in order to create a ConstantNode , I need to be able to match all possible variations of a Const declaration.These work beautifully : Const foo = 123Const foo $ = `` 123 '' Const foo As String = `` 123 '' Private Const foo = 123Public Const foo As Integer = 123Global Const foo % = 123But I have 2 problems : If there 's a comment at the end of the declaration , I 'm picking it up as part of the value : If there 's two or more constants declared in the same instruction , I 'm failing to match the entire instruction : Here is the regular expressions I 'm using : Obviously both issues are caused by the ( ? < value > . * ) $ part , which matches anything up until the end of the line . I got VariableNode to support multiple declarations in one instruction by enclosing the whole pattern in a capture group and adding an optional comma , but because constants have this value group , doing that resulted in the first constant having all following declarations captured as part of its value ... which brings me back to problem # 1.I wonder if it 's at all possible to solve problem # 1 with a regular expression , given that the value may be a string that contains an apostrophe , and possibly some escaped ( doubled-up ) double quotes.I think I can solve it in the ConstantNode class itself , in the getter for Value : I mean , I could implement some additional logic in here , to do what I ca n't do with a regex.If problem # 1 can be solved with a regex , then I believe problem # 2 can be as well ... or am I on the right track here ? Should I ditch the [ pretty complex ] regex patterns and think of another way ? I 'm not too familiar with greedy subexpressions , backreferences and other more advanced regex features - is this what 's limiting me , or it 's just that I 'm using the wrong hammer for this nail ? Note : it does n't matter that the patterns potentially match illegal syntax - this code will only run against compilable VBA code . <code> Const foo = 123 'this comment is included as part of the value Const foo = 123 , bar = 456 /// < summary > /// Gets a regular expression pattern for matching a constant declaration . /// < /summary > /// < remarks > /// Constants declared in class modules may only be < c > Private < /c > . /// Constants declared at procedure scope can not have an access modifier . /// < /remarks > public static string GetConstantDeclarationSyntax ( ) { return @ '' ^ ( ( Private|Public|Global ) \s ) ? Const\s ( ? < identifier > [ a-zA-Z ] [ a-zA-Z0-9_ ] * ) ( ? < specifier > [ % & @ ! # $ ] ) ? ( ? < as > \sAs\s ( ? < reference > ( ( ( ? < library > [ a-zA-Z ] [ a-zA-Z0-9_ ] * ) ) \. ) ? ( ? < identifier > [ a-zA-Z ] [ a-zA-Z0-9_ ] * ) ) ) ? \s\=\s ( ? < value > . * ) $ '' ; } /// < summary > /// Gets the constant 's value . Strings include delimiting quotes./// < /summary > public string Value { get { return RegexMatch.Groups [ `` value '' ] .Value ; } } | Parsing VBA Const declarations ... with regex |
C_sharp : I am working on an application in which have different repositories for different entities and now i have to put search logic , hence i am confused where should i put my search logic , should i create a new repository for search or should i put the logic in the existing repository , and if i should put in some existing repository the which one is it.the repositories are listed below <code> public class VendorRepository { } public class ProductRepository { } Public Class ProductBatchRepository { } | Best Practices | Where to put search logic if we have different repository for each entity |
C_sharp : I was working with some C # code today in the morning and I had something like : So , as I dont have a full understanding of the language framework I would like to know if GetDataTable ( ) gets called each time an iteration is done or if it just gets called once and the resulting data ( which would be Rows ) is saved in memory to loop through it . In any case , I declared a new collection to save it and work from there ... I added a new variable so instead I did : But im not quite sure if this is necessary.Thanks in advance . <code> foreach ( DataRow row in MyMethod.GetDataTable ( ) .Rows ) { //do something } DataRowCollection rowCollection = MyMethod.GetDataTable ( ) .Rows ; foreach ( DataRow row in rowCollection ) { //do something } | Does a method that returns a collection get called in every iteration in a foreach statement in C # ? |
C_sharp : I have some code that is meant to get files in a directory , which is simple enoughThe files are named as follows : My issue is that it is not picking up the last file.I have fixed the code by putting this instead : Saying get any files that contains both Totals and .csv , with anything after the .csv.What I do n't get is why it got the top four files , but not the bottom.I 'd have thought none of the files would be picked up by the original code ? <code> foreach ( var Totalfile in new DirectoryInfo ( rootfolder ) .GetFiles ( `` *Totals*.csv '' , SearchOption.TopDirectoryOnly ) ) Totals.CSV142344Totals.CSV142409Totals.CSV142433Totals.CSV142501Totals.CSV142528 foreach ( var Totalfile in new DirectoryInfo ( rootfolder ) .GetFiles ( `` *Totals*.csv* '' , SearchOption.TopDirectoryOnly ) ) | Directory.GetFiles does n't pick up all files |
C_sharp : allI have searched this question , and I found so many answers to it was not difficult to find a solution for my question.BUT , I have strange experience and I do n't know the reason that 's why I ask people to give me some advice.Here are my codes : Yes , they are ordinary thread codes.I expect all the thread array should be calling RunThread method 10 times.It should be likeThis is what I expect to be . The order is not important.But I get the result like below.What I expect is that RunThread function should carry the argument ( num ) from 0 to 9.And I can not figure out what that error message is . `` The thread `` ~~ and so on.Could anyone give me some clue on this ? <code> void SetThread ( ) { for ( int i = 0 ; i < _intArrayLength ; i++ ) { Console.Write ( string.Format ( `` SetThread- > i : { 0 } \r\n '' , i ) ) ; _th [ i ] = new Thread ( new ThreadStart ( ( ) = > RunThread ( i ) ) ) ; _th [ i ] .Start ( ) ; } } void RunThread ( int num ) { Console.Write ( string.Format ( `` RunThread- > num : { 0 } \r\n '' , num ) ) ; } SetThread- > i : 0SetThread- > i : 1SetThread- > i : 2SetThread- > i : 3SetThread- > i : 4SetThread- > i : 5SetThread- > i : 6SetThread- > i : 7SetThread- > i : 8SetThread- > i : 9RunThread- > num : 0RunThread- > num : 1RunThread- > num : 2RunThread- > num : 3RunThread- > num : 4RunThread- > num : 5RunThread- > num : 6RunThread- > num : 7RunThread- > num : 8RunThread- > num : 9 SetThread- > i : 0SetThread- > i : 1SetThread- > i : 2The thread ' < No Name > ' ( 0x18e4 ) has exited with code 0 ( 0x0 ) .The thread ' < No Name > ' ( 0x11ac ) has exited with code 0 ( 0x0 ) .The thread ' < No Name > ' ( 0x1190 ) has exited with code 0 ( 0x0 ) .The thread ' < No Name > ' ( 0x1708 ) has exited with code 0 ( 0x0 ) .The thread ' < No Name > ' ( 0xc94 ) has exited with code 0 ( 0x0 ) .The thread ' < No Name > ' ( 0xdac ) has exited with code 0 ( 0x0 ) .The thread ' < No Name > ' ( 0x12d8 ) has exited with code 0 ( 0x0 ) .The thread ' < No Name > ' ( 0x1574 ) has exited with code 0 ( 0x0 ) .The thread ' < No Name > ' ( 0x1138 ) has exited with code 0 ( 0x0 ) .The thread ' < No Name > ' ( 0xef0 ) has exited with code 0 ( 0x0 ) .SetThread- > i : 3RunThread- > num : 3RunThread- > num : 3RunThread- > num : 3SetThread- > i : 4RunThread- > num : 4SetThread- > i : 5SetThread- > i : 6RunThread- > num : 6RunThread- > num : 6SetThread- > i : 7RunThread- > num : 7SetThread- > i : 8RunThread- > num : 8SetThread- > i : 9RunThread- > num : 9RunThread- > num : 10 | How to pass arguments to thread in C # |
C_sharp : I have a data object with three fields , A , B and C. The problem is that the user can set any of them because : A * B = CSo if a user starts off by setting A & B , C will be calculated . but then if a user set C , A gets recalculated , so there is an implicit anchoring that is happening based off the last field that the user set.i want to avoid a solution with a lot of flag member variables . Any best practices on how i can code this class up without having a lot of stuff like this belowshould the logic of setting A , B , and C always be on the `` get '' or the `` set '' .Is there any cleaner way to doing this ? <code> public class Object { private double _A ; private double _B ; private double _C ; private bool _enteredA ; private bool _enteredB ; private bool _enteredC ; public double A { get { if ( _enteredC ) { return _C / _B ; } else { return _A ; } } } | 3 way calculation |
C_sharp : I 'm thinking of something along the lines of the `` Inline Task '' in MsBuild . For reference : http : //msdn.microsoft.com/en-us/library/dd722601.aspxI 'd like to find or create a framework which allows me to override a method via configuration . For example if I have a well known base class which has a method Execute ( args ) , how can I supply an overridden method implementation at deployment time , without requiring new code , build , release cycle ? I would like to actually plug in the method body into a config file or preferably a database table.I assume this would be done either with code dom , dynamic language integration , or perhaps something like powershell ( ? ) . I 'm looking for recommendations or perhaps a library someone has already written.The application is written in C # . Preferably the extension would also be in C # , but I 'm open to other ideas as well.Update : Technically I do n't even have to actually override a method . It would be sufficient to just be able to dynamically execute some external source code , passing in an arg and returning a result.Update . I ended up writing code to instantiate a PowerShell object and execute a script dynamically to return a value . Here is a snippet of code I used.Then in the calling code , I simply check the first PSObject in the return value , and pull the resulting value from it . It works great . Thanks for all the responses . <code> public static Collection < PSObject > ExecuteScript ( string code , string variableName , object variableValue ) { PowerShell ps = PowerShell.Create ( ) ; ps.AddScript ( code ) ; if ( ! string.IsNullOrWhiteSpace ( variableName ) ) { ps.Runspace.SessionStateProxy.SetVariable ( variableName , variableValue ) ; } var result = ps.Invoke ( ) ; return result ; } | How best to create and execute a method in a .NET ( C # ) class dynamically through configuration |
C_sharp : Can somebody explain why the .Net framework team decided that a delegate without subscribers should be null instead of an object with an empty InvocationList ? I 'd like to know the rationale that led to this decision.Thanks <code> void DoSomething ( ) { EventHandler handler = SomeEvent ; if ( handler ! = null ) //why is this null-check necessary ? { handler ( this , EventArgs.Empty ) ; } } | Why are delegates null rather than an empty list when there is no subscriber ? |
C_sharp : Consider this function , which you can think of as a truth table : The compiler insists on that last else clause . But from a truth table 's perspective , that is an impossible state.Yes , it works , and yes , I can live with it . But I 'm wondering if there is some mechanism in c # to avoid this sort of code , or if I 've missed something obvious ? UPDATE : For bonus points , and purely out of curiosity , are there any languages that deal with this sort of thing differently ? Maybe it 's not a language matter , but rather one of a smart compiler ( but the edge cases would be unimaginably complicated I suppose ) . <code> public Foo doSomething ( bool a , bool b ) { if ( a & & b ) return doAB ( ) ; else if ( a & & ! b ) return doA ( ) ; else if ( ! a & & b ) return doB ( ) ; else if ( ! a & & ! b ) return doNotANotB ( ) ; else throw new Exception ( `` Well done , you defeated boolean logic ! `` ) ; } | How can I avoid an impossible boolean state in c # ? |
C_sharp : I 'm trying to determine how AsParallel ( ) splits it 's 'source ' , and indeed what is meant by 'source ' ... For example ... Then put 500k varying CSVItem 's into CSVItemList.Then use : Will it only split the 'source ' ( meaning for example 250k records onto each of two threads ) onto multiple asynch threads and perform the OrderBy ( ) .ThenBy ( ) on each thread then merge the results ... Or will it separate the OrderBy ( ) and ThenBy ( ) onto separate threads and run them and then merge the results ... giving a strangely ordered list ? <code> public class CSVItem { public DateTime Date { get ; set ; } public string AccountNumber { get ; set ; } } List < CSVItem > CSVItemList = new List < CSVItem > ( ) ; CSVItemList = CSVItemList.AsParallel ( ) .OrderBy ( x = > x.AccountNumber ) .ThenBy ( q = > q.Date ) .ToList ( ) ; | How does AsParallel ( ) split it 's 'source ' ? |
C_sharp : Modern unit tests frameworks support awaiting the results of an asychronous unit test , like this : Is there any advantage of using this async approach over simply blocking ? Does the async only provide a benefit when running tests in parallel ? <code> public async Task SomeTest ( ) { var result = await SomeMethodAsync ( ) ; // ... Verify the result ... } public void SomeTest ( ) { var result = SomeMethodAsync ( ) .Result ; // ... Verify the result ... } | Advantage of async/await over blocking in unit tests |
C_sharp : The following two C # functions differ only in swapping the left/right order of arguments to the equals operator , == . ( The type of IsInitialized is bool ) . Using C # 7.1 and .NET 4.7.But the IL code for the second one seems much more complex . For example , B is:36 bytes longer ( IL code ) ; calls additional functions including newobj and initobj ; declares four locals versus just one.IL for function ' A'…IL for function ' B'… QuesionsIs there any functional , semantic , or other substantial runtime difference between A and B ? ( We 're only interested in correctness here , not performance ) If they are not functionally equivalent , what are the runtime conditions that can expose an observable difference ? If they are functional equivalents , what is B doing ( that always ends up with the same result as A ) , and what triggered its spasm ? Does B have branches that can never execute ? If the difference is explained by the difference between what appears on the left side of == , ( here , a property referencing expression versus a literal value ) , can you indicate a section of the C # spec that describes the details.Is there a reliable rule-of-thumb that can be used to predict the bloated IL at coding-time , and thus avoid creating it ? BONUS . How does the respective final JITted x86 or AMD64 code for each stack up ? [ edit ] Additional notes based on feedback in the comments . First , a third variant was proposed , but it gives identical IL as A ( for both Debug and Release builds ) . Sylistically , however , the C # for the new one does seem sleeker than A : Here also is the Release IL for each function . Note that the asymmetry A/C vs. B is still evident with the Release IL , so the original question still stands.Release IL for functions ' A ' , ' C'…Release IL for function ' B'…Lastly , a version using new C # 7 syntax was mentioned which seems to produce the cleanest IL of all : Release IL for function 'D'… <code> static void A ( ISupportInitialize x ) { if ( ( x as ISupportInitializeNotification ) ? .IsInitialized == true ) throw null ; } static void B ( ISupportInitialize x ) { if ( true == ( x as ISupportInitializeNotification ) ? .IsInitialized ) throw null ; } [ 0 ] bool flag nop ldarg.0 isinst [ System ] ISupportInitializeNotification dup brtrue.s L_000e pop ldc.i4.0 br.s L_0013L_000e : callvirt instance bool [ System ] ISupportInitializeNotification : :get_IsInitialized ( ) L_0013 : stloc.0 ldloc.0 brfalse.s L_0019 ldnull throwL_0019 : ret [ 0 ] bool flag , [ 1 ] bool flag2 , [ 2 ] valuetype [ mscorlib ] Nullable ` 1 < bool > nullable , [ 3 ] valuetype [ mscorlib ] Nullable ` 1 < bool > nullable2 nop ldc.i4.1 stloc.1 ldarg.0 isinst [ System ] ISupportInitializeNotification dup brtrue.s L_0018 pop ldloca.s nullable2 initobj [ mscorlib ] Nullable ` 1 < bool > ldloc.3 br.s L_0022L_0018 : callvirt instance bool [ System ] ISupportInitializeNotification : :get_IsInitialized ( ) newobj instance void [ mscorlib ] Nullable ` 1 < bool > : :.ctor ( ! 0 ) L_0022 : stloc.2 ldloc.1 ldloca.s nullable call instance ! 0 [ mscorlib ] Nullable ` 1 < bool > : :GetValueOrDefault ( ) beq.s L_0030 ldc.i4.0 br.s L_0037L_0030 : ldloca.s nullable call instance bool [ mscorlib ] Nullable ` 1 < bool > : :get_HasValue ( ) L_0037 : stloc.0 ldloc.0 brfalse.s L_003d ldnull throwL_003d : ret static void C ( ISupportInitialize x ) { if ( ( x as ISupportInitializeNotification ) ? .IsInitialized ? ? false ) throw null ; } ldarg.0 isinst [ System ] ISupportInitializeNotification dup brtrue.s L_000d pop ldc.i4.0 br.s L_0012L_000d : callvirt instance bool [ System ] ISupportInitializeNotification : :get_IsInitialized ( ) brfalse.s L_0016 ldnull throwL_0016 : ret [ 0 ] valuetype [ mscorlib ] Nullable ` 1 < bool > nullable , [ 1 ] valuetype [ mscorlib ] Nullable ` 1 < bool > nullable2 ldc.i4.1 ldarg.0 isinst [ System ] ISupportInitializeNotification dup brtrue.s L_0016 pop ldloca.s nullable2 initobj [ mscorlib ] Nullable ` 1 < bool > ldloc.1 br.s L_0020L_0016 : callvirt instance bool [ System ] ISupportInitializeNotification : :get_IsInitialized ( ) newobj instance void [ mscorlib ] Nullable ` 1 < bool > : :.ctor ( ! 0 ) L_0020 : stloc.0 ldloca.s nullable call instance ! 0 [ mscorlib ] Nullable ` 1 < bool > : :GetValueOrDefault ( ) beq.s L_002d ldc.i4.0 br.s L_0034L_002d : ldloca.s nullable call instance bool [ mscorlib ] Nullable ` 1 < bool > : :get_HasValue ( ) L_0034 : brfalse.s L_0038 ldnull throwL_0038 : ret static void D ( ISupportInitialize x ) { if ( x is ISupportInitializeNotification y & & y.IsInitialized ) throw null ; } [ 0 ] class [ System ] ISupportInitializeNotification y ldarg.0 isinst [ System ] ISupportInitializeNotification dup stloc.0 brfalse.s L_0014 ldloc.0 callvirt instance bool [ System ] ISupportInitializeNotification : :get_IsInitialized ( ) brfalse.s L_0014 ldnull throw L_0014 : ret | Argument order for '== ' with Nullable < T > |
C_sharp : I must be doing something dumb : So why when i = 7 is ans coming out at 2.0 ? i is an int <code> float ans = ( i/3 ) ; | Simple division |
C_sharp : Consider the following ( VS 16.8.0 Preview 2.1 C # 9.0 preview ) code : I am having a hard time understanding/addressing the errors in F3 , Seems like the compiler thinks johnAge there is long not long ? ( as I verified by hovering over it in VS ) despite the return of Archive < T > .GetAt being T ? Is there a way to have a generic Archive which will do what I want ( a GetAt method that return Nullable even when T is a non nullable basic type ie long ) ? <code> # nullable enableusing System.Collections.Generic ; class Archive < T > where T : notnull { readonly Dictionary < string , T > Dict = new ( ) ; public T ? GetAt ( string key ) { return Dict.TryGetValue ( key , out var value ) ? value : default ; } } class Manager { public int Age { get ; set ; } } class Main34 { long F3 ( ) { Archive < long > a = new ( ) ; var johnAge = a.GetAt ( `` john '' ) ; if ( johnAge is null ) return -1 ; // Error CS0037 Can not convert null to 'long ' because it is a non - nullable value type return johnAge ; } long F4 ( ) { Archive < Manager > a = new ( ) ; var johnAge = a.GetAt ( `` john '' ) ; //if ( johnAge is null ) return -1 ; return johnAge.Age ; // Correct ! warning `` Derefrencing of a possibly null reference '' will be removed if line above unremarked } } | C # 9 Nullable types issues |
C_sharp : I was under the impression that in .NET casting ( not converting ) is very cheap and fast . However , this does not seem to be the case for array . I 'm trying to do a very simple cast here , take a T1 [ ] and cast as T2 [ ] . where T1 : T2.There are 3 ways to do this and I 'm calling them the following : :And I created methods to do this , unfortunately , C # seems to create some rather strange code depending on if this is generic or not . ( If its generic DropCasting uses the castclass operator . And in both cases refuse to emit an 'as ' operator when T1 : T2 . Anyway , I wrote some Dynamic methods and I tested it to some surprising results ( string [ ] = > object [ ] ) : Dropcasting was ~18 times faster than either of the cast operators . Why is casting so slow for arrays ? For normal objects like string= > object , the difference was much less severe.Benchmark code below : Edit before anyone asks the same hold true for things like int [ ] - > uint [ ] which the clr specs should be cast without conversion . <code> DropCasting : T2 [ ] array2 = array ; CastClass : ( T2 [ ] ) array ; IsInst : array as T2 [ ] ; DropCast : 223msIsInst : 3648msCastClass : 3732ms DropCast : 386msIsInst : 611msCastClass : 519ms class Program { static readonly String [ ] strings = Enumerable.Range ( 0 , 10 ) .Select ( x = > x.ToString ( ) ) .ToArray ( ) ; static Func < string [ ] , object [ ] > Dropcast = new Func < Func < string [ ] , object [ ] > > ( ( ) = > { var method = new DynamicMethod ( `` DropCast '' , typeof ( object [ ] ) , new [ ] { typeof ( object ) , typeof ( string [ ] ) } , true ) ; var ilgen = method.GetILGenerator ( ) ; ilgen.Emit ( OpCodes.Ldarg_1 ) ; ilgen.Emit ( OpCodes.Ret ) ; return method.CreateDelegate ( typeof ( Func < string [ ] , object [ ] > ) ) as Func < string [ ] , object [ ] > ; } ) ( ) ; static Func < string [ ] , object [ ] > CastClass = new Func < Func < string [ ] , object [ ] > > ( ( ) = > { var method = new DynamicMethod ( `` CastClass '' , typeof ( object [ ] ) , new [ ] { typeof ( object ) , typeof ( string [ ] ) } , true ) ; var ilgen = method.GetILGenerator ( ) ; ilgen.Emit ( OpCodes.Ldarg_1 ) ; ilgen.Emit ( OpCodes.Castclass , typeof ( object [ ] ) ) ; ilgen.Emit ( OpCodes.Ret ) ; return method.CreateDelegate ( typeof ( Func < string [ ] , object [ ] > ) ) as Func < string [ ] , object [ ] > ; } ) ( ) ; static Func < string [ ] , object [ ] > IsInst = new Func < Func < string [ ] , object [ ] > > ( ( ) = > { var method = new DynamicMethod ( `` IsInst '' , typeof ( object [ ] ) , new [ ] { typeof ( object ) , typeof ( string [ ] ) } , true ) ; var ilgen = method.GetILGenerator ( ) ; ilgen.Emit ( OpCodes.Ldarg_1 ) ; ilgen.Emit ( OpCodes.Isinst , typeof ( object [ ] ) ) ; ilgen.Emit ( OpCodes.Ret ) ; return method.CreateDelegate ( typeof ( Func < string [ ] , object [ ] > ) ) as Func < string [ ] , object [ ] > ; } ) ( ) ; static Func < string [ ] , object [ ] > [ ] Tests = new Func < string [ ] , object [ ] > [ ] { Dropcast , IsInst , CastClass } ; static void Main ( string [ ] args ) { int maxMethodLength = Tests.Select ( x = > GetMethodName ( x.Method ) .Length ) .Max ( ) ; RunTests ( 1 , false , maxMethodLength ) ; RunTests ( 100000000 , true , maxMethodLength ) ; } static string GetMethodName ( MethodInfo method ) { return method.IsGenericMethod ? string.Format ( @ '' { 0 } < { 1 } > '' , method.Name , string.Join < Type > ( `` , '' , method.GetGenericArguments ( ) ) ) : method.Name ; } static void RunTests ( int count , bool displayResults , int maxLength ) { foreach ( var action in Tests ) { Stopwatch sw = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < count ; i++ ) { action ( strings ) ; } sw.Stop ( ) ; if ( displayResults ) { Console.WriteLine ( `` { 0 } : { 1 } ms '' , GetMethodName ( action.Method ) .PadRight ( maxLength ) , ( ( int ) sw.ElapsedMilliseconds ) .ToString ( ) .PadLeft ( 6 ) ) ; } GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; } } } | Why is casting arrays ( vectors ) so slow ? |
C_sharp : I have a Silverlight 5 application trying establish a socket connection to a server as follows : I have the following clientaccesspolicy.xml file at https : //subdomain.maindomain.com/clientaccesspolicy.xml : I am able to run a local instance of the Silverlight application from visual studio and can establish the socket connection , both running in-browser as well as out-of-browser . When I deploy the application , I am still able to connect using the out-of-browser version , but the in-browser version errors out with the following message : AccessDenied : An attempt was made to access a socket in a way forbidden by its access permissions.Within my local environment , where I am running from Visual studio , if I create an hosts file entry:127.0.0.1 myapp.localand update my localhost in-browser instance ( running from VS ) to use myapp.local , I can reproduce the same error , which suggests that the error occurs when the root domain is not localhost , regardless of where the application is hosted.I have checked my firewall and antivirus software 's event logs for signs that they could be blocking the connection request , but do not see any evidence of that.Has anyone else experienced this issue and offer suggestions of what my problem could be ? <code> var targetEndpoint = new DnsEndPoint ( `` subdomain.maindomain.com '' , 443 ) ; var clientSocket = new Socket ( AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.Tcp ) ; var socketAsyncEventArgs = new SocketAsyncEventArgs { RemoteEndPoint = targetEndpoint } ; socketAsyncEventArgs.Completed += AsyncConnectCallback ; clientSocket.ConnectAsync ( socketAsyncEventArgs ) ; < access-policy > < cross-domain-access > < policy > < allow-from http-request-headers= '' * '' http-methods= '' * '' > < domain uri= '' https : //subdomain.maindomain.com '' / > < domain uri= '' * '' / > < /allow-from > < grant-to > < resource path= '' / '' include-subpaths= '' true '' / > < socket-resource port= '' 4502 '' protocol= '' tcp '' / > < /grant-to > < /policy > < /cross-domain-access > < /access-policy > | Silverlight 5 Opening Socket AccessDenied |
C_sharp : We have implemented a localized version of an ASP.NET MVC website which has a URL structure as following : url : // { language } - { culture } / { controller } / { action } / { id } In this way we can generate URLs by language which are properly crawled by Google bot : http : //localhost/en-US/Homehttp : //localhost/fr-FR/HomeThe translation is achieved in two places . First we modified the default route of MVC with this one : Then we have created an action filter which switch to the current language available in the URL and if not available to the default one : The problem occurs if a user enter http : //localhost/Whatever . ASP.NET MVC returns `` Route not found '' . How can I pass a default parameter for the language if the user forgets to pass one ? I though that by setting the default value into route config would be enough , but it does n't work <code> routes.MapRoute ( name : `` Default '' , url : `` { language } - { culture } / { controller } / { action } / { id } '' , defaults : new { controller = `` Home '' , action = `` Index '' , id = UrlParameter.Optional , language = `` en '' , culture = `` US '' } ) ; public class LocalizationAttribute : ActionFilterAttribute { public override void OnActionExecuting ( ActionExecutingContext filterContext ) { string language = ( string ) filterContext.RouteData.Values [ `` language '' ] ? ? `` en '' ; string culture = ( string ) filterContext.RouteData.Values [ `` culture '' ] ? ? `` US '' ; Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo ( string.Format ( `` { 0 } - { 1 } '' , language , culture ) ) ; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo ( string.Format ( `` { 0 } - { 1 } '' , language , culture ) ) ; } } } | Pre-Append Route if not available |
C_sharp : I have been looking for a way of splitting a foreach loop into multiple parts and came across the following code : Would items.Skip ( currentPage * itemsPerPage ) .Take ( itemsPerPage ) be processed in every iteration , or would it be processed once , and have a temporary result used with the foreach loop automatically by the compiler ? <code> foreach ( var item in items.Skip ( currentPage * itemsPerPage ) .Take ( itemsPerPage ) ) { //Do stuff } | Linq optimisation within a foreach |
C_sharp : I noticed something strange when trying to pass a StringBuilder 's Append method to a function that took an Action < string > .For testing purposes , I just want to write the data into a StringBuilder , so I tried to call it like this : However , this gives a compile error , because the Append method does not match the required signature ( it returns a reference back to the StringBuilder , not void as my method wants ) : 'System.Text.StringBuilder System.Text.StringBuilder.Append ( string ) ' has the wrong return typeWithout thinking , I changed the code to this : This compiled fine.Then I got confused ; realising that s = > output.Append ( s ) should also return the StringBuilder , are n't they the same ? So , why does this work ? Why can s = > output.Append ( s ) have the return value discarded silently , yet output.Append can not ? <code> public void DoStuff ( Action < string > handler ) { // Do stuff , call handler ( `` data '' ) ; } var output = new StringBuilder ( ) ; DoStuff ( output.Append ) ; var output = new StringBuilder ( ) ; DoStuff ( s = > output.Append ( s ) ) ; | Why can ` s = > x.Append ( s ) ` can be passed as an Action < string > but ` x.Append ` ca n't ? |
C_sharp : To keep my code cleaner I often try to break down parts of my data access code in LINQ to SQL into private sub-methods , just like with plain-old business logic code . Let me give a very simplistic example : I 'm sure no one 's imagination would be stretched by imagining more complex examples with deeper nesting or using results of sets to filter other queries.My basic question is this : I 've seen some significant performance differences and even exceptions being thrown by just simply reorganizing LINQ to SQL code in private methods . Can anyone explain the rules for these behaviors so that I can make informed decisions about how to write efficient , clean data access code ? Some questions I 've had:1 ) When does passage of System.Linq.Table instace to a method cause query execution ? 2 ) When does using a System.Linq.Table in another query cause execution ? 3 ) Are there limits to what types of operations ( Take , First , Last , order by , etc . ) can be applied to System.Linq.Table passed a parameters into a method ? <code> public IEnumerable < Item > GetItemsFromRepository ( ) { var setA = from a in this.dataContext.TableA where /* criteria */ select a.Prop ; return DoSubquery ( setA ) ; } private IEnumerable < Item > DoSubQuery ( IEnumerable < DateTimeOffset > set ) { return from item in set where /* criteria */ select item ; } | Rules for LINQ to SQL across method boundaries |
C_sharp : Today I faced a problem and I 'm not able to get weather I understand something wrong about ASP.NET MVC ( and possibly MVC in general ) or I miss something about it 's implementation.So , I have a simple model hierarchy : Here is my HomeController 's Edit actions : Hese is my Edit.aspx view : The point is that in Edit ( HttpGet ) method I create Parent instance with two child Child elements having their IsSelected properties set to true and false respectively . After form is submitted in Edit ( HttpPost ) method I give my Parent object a new children collection of two Child elements with their IsSelected properties set to false and true respectively ( that is opposite from HttpGet method ) and call View ( ) method to render my model.But what I get after submit is checkboxes , rendered with Html.EditorFor ( ) and Html.CheckBoxFor ( ) do not changes their state . It looks like Html.EditorFor ( ) and Html.CheckBoxFor ( ) methods take data NOT from my model but from a posted form data.Could someone please explain me what is going on here and why ASP.NET MVC refuses to render my model ? Workarounds ? Fixes to my code ? Thanks in advance.P.S . I noticed this behavior in MVC2 and thought this was some kind of a bug , but when I tested this with MVC3 it did the same thing . <code> public class Child { public Child ( int notId , bool isSelected , string text ) { NotId = notId ; IsSelected = isSelected ; Text = text ; } public Child ( ) { } // naming : just to make sure I do not mess with some // conventional infrastructure public int NotId { get ; set ; } public bool IsSelected { get ; set ; } public string Text { get ; set ; } } public class Parent { public List < Child > Children { get ; set ; } } [ HttpGet ] public ActionResult Edit ( ) { var parent = new Parent { Children = new List < Child > { new Child ( 1 , true , `` a '' ) , new Child ( 2 , false , `` b '' ) } } ; return View ( parent ) ; } [ HttpPost ] public ActionResult Edit ( Parent parent ) { parent.Children = new List < Child > { new Child ( 4 , false , `` c '' ) , new Child ( 5 , true , `` d '' ) } ; return View ( parent ) ; } < ! -- Standart HTML elements ommited -- > < % Html.BeginForm ( ) ; % > < % for ( var i = 0 ; i < Model.Children.Count ; i++ ) { % > < div > < % =Html.LabelFor ( m = > m.Children [ i ] .IsSelected ) % > < % =Html.EditorFor ( m = > m.Children [ i ] .IsSelected ) % > < ! -- lamda -- > < % =Html.CheckBoxFor ( m = > m.Children [ i ] .IsSelected ) % > < ! -- lamda -- > < % =Html.CheckBox ( `` A '' , Model.Children [ i ] .IsSelected ) % > < ! -- simple -- > < /div > < % } % > < input type= '' submit '' value= '' Submit '' / > < % Html.EndForm ( ) ; % > | ASP.NET MVC rendering model not the way I expect |
C_sharp : I am trying to get better with IoC , DI and OOD for better testability and looser coupling.So when we design classes with heavy use of IoC and DI we can endup with classes with multiple dependencies for exampleIm thinking what should be the usual approach here . We can leave constructor with 3 parameters , but if we are building app using autofac ( for example ) most likely it will rarely be used other than by resolving types from some container instance likeso I am thinking maybe approach 2 is better , when we depend on multiple types from container . Anyway we will have to add reference to autofac somewhere , so any reasons not to do it now ? Autofac also provides delegate factory method approach http : //code.google.com/p/autofac/wiki/DelegateFactoriesSo we have also approach 3 - we will not use constructors to create our class instances , instead we will be calling resolved delegate from container and it will resolve dependencies for us.Since im fairly new to IoC its hard to say when we should use 1,2,3 . They have advantages and disadvantages.I think generally if class has 1 dependency we can probably always use approach 1.. other than that I am really not sure what to choose and when.UPDATE i have read about service locator anti pattern but Ive come up with 4th ( or true 3rd approach ) its close to ServiceLocator except its not , we pass an object that looks like thisAnd now we create Now we have decoupled our class from service implementations and its clear what real dependencies it needs ( if we assume all services availabe on passed object are required ) because we are n't passing a container that can contain 100 implementations . And that object can be even reused if that 3 service combination might be required in some another class in our application . So we are using constructor DI not ServiceLocator pattern . interface is clear and not overloaded with dependencies , new class might be a good reuse candidate.What would you say about this one ? <code> class Processor { private IService1 m_Service1 ; private IService2 m_Service2 ; private IService3 m_Service3 ; //approach 1 public Processor ( IService1 service1 , IService2 service2 , IService3 service3 ) { m_Service1 = service1 ; m_Service2 = service2 ; m_Service3 = service3 ; } //approach 2 public Processor ( IContainer container ) { m_Service1 = container.Resolve < IService1 > ( ) ; m_Service2 = container.Resolve < IService2 > ( ) ; m_Service3 = container.Resolve < IService3 > ( ) ; } //approach 3 public delegate Processor Factory ( ) ; } Processor proc = new Processor ( container.Resolve < IService1 > ( ) , container.Resolve < IService2 > ( ) , container.Resolve < IService3 > ( ) ) ; var processorFactory = container.Resolve < Processor.Factory > ( ) ; Processor processor = processorFactory.Invoke ( ) ; public class ServiceLocatorObject { private IService1 m_Service1 ; private IService2 m_Service2 ; private IService3 m_Service3 ; public IService1 Service1 { get { return m_Service1 ; } } public IService2 Service2 { get { return m_Service2 ; } } public IService3 Service3 { get { return m_Service3 ; } } public ServiceLocatorObject ( IService1 service1 , IService2 service2 , IService3 service3 ) { m_Service1 = service1 ; m_Service2 = service2 ; m_Service3 = service3 ; } } //approach 4public Processor ( ServiceLocatorObject servicesToUse ) { m_Services = servicesToUse ; } | OOD using IoC containers - how to construct dependant objects ? |
C_sharp : I need to connect my NET Framework 4 Client App , to a Webservice , deployed on a Apache CXF , with WS Security . That service is out of my control.The service is added to the project as a `` Service Reference '' .This is the proxy : Well . The server accepts my Request , and send the the response , in this way : I get the error `` Can not resolve KeyInfo for unwrapping key '' .Reading OASIS doc about that kind of soap messages , I think the message it 's ok.I have tried , with the custom encoder , changing `` X509IssuerSerial '' node , for a `` . Same error.I can , reading the message directly , perform a manual key decryption , using the cert . Then , with the key , I can decrypt the data . So data is correct.BUT , I do n't wa n't this . I want use the Service Reference.Going through NET Code , I see that stack trace : So , in `` System.ServiceModel.Security.WSSecurityJan2004.WrappedKeyTokenEntry.ReadTokenCore '' , it 's trying to `` CreateWrappedKeyToken '' , and the Exception it 's throw here : unwrappingToken = resolver.ExpectedWrapper ; if ( unwrappingToken ! = null ) ... So , in `` unwrappingToken = resolver.ExpectedWrapper '' , I get a `` null '' . This could be some kind of `` messages namespaces mismatch '' , or something like that , that I do not see ? Certificate it 's ok and valid . It has all the x509v3 properties , and the issuer it 's a trusted issuer ... Help me guys , my diopters are increasing with this ... <code> ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback ( AddressOf AcceptAllCertifications ) Dim oBinding As New CustomBinding ( ) Dim oSecurity As SecurityBindingElementoSecurity = AsymmetricSecurityBindingElement.CreateCertificateOverTransportBindingElement ( MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10 ) oSecurity.IncludeTimestamp = TrueoBinding.Elements.Add ( oSecurity ) oBinding.Elements.Add ( New CertFixEscapedComma.CertRefEncodingBindingElement ( ) ) ( This a custom message encoder ) CertFixEscapedComma.CertRefEncoder.CERTIFICADO = Convert.ToBase64String ( oCertificado.RawData ) oBinding.CloseTimeout = New TimeSpan ( 0 , 2 , 0 ) Dim oTransport As New HttpsTransportBindingElement ( ) oBinding.Elements.Add ( oTransport ) Dim oProxyClient As New NameServiceClient ( oBinding , New System.ServiceModel.EndpointAddress ( New Uri ( `` https : //url_service '' ) ) ) Dim oCertificado As X509Certificate2oCertificado = function_client_certificate ( ) ' this get the proper certoProxyClient.ClientCredentials.ClientCertificate.Certificate = oCertificadooProxyClient.name_function ( params ) 'call to the remote service < soap : Envelope xmlns : soap= '' http : //schemas.xmlsoap.org/soap/envelope/ '' > < soap : Header > < wsse : Security xmlns : wsse= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd '' xmlns : wsu= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd '' soap : mustUnderstand= '' 1 '' xmlns : soap= '' http : //schemas.xmlsoap.org/soap/envelope/ '' > < xenc : EncryptedKey xmlns : xenc= '' http : //www.w3.org/2001/04/xmlenc # '' Id= '' EK-4A5A4F8820EFD673E7152328322340610394 '' > < xenc : EncryptionMethod Algorithm= '' http : //www.w3.org/2001/04/xmlenc # rsa-oaep-mgf1p '' / > < ds : KeyInfo xmlns : ds= '' http : //www.w3.org/2000/09/xmldsig # '' > < wsse : SecurityTokenReference > < ds : X509Data > < ds : X509IssuerSerial > < ds : X509IssuerName > issuer name etc etc cetc < /ds : X509IssuerName > < ds : X509SerialNumber > 62535066537829860999033107852056725154 < /ds : X509SerialNumber > < /ds : X509IssuerSerial > < /ds : X509Data > < /wsse : SecurityTokenReference > < /ds : KeyInfo > < xenc : CipherData > < xenc : CipherValue > SlU4B4BlMhsEc0ek ... == < /xenc : CipherValue > < /xenc : CipherData > < xenc : ReferenceList > < xenc : DataReference URI= '' # ED-4A5A4F8820EFD673E7152328322340710395 '' / > < /xenc : ReferenceList > < /xenc : EncryptedKey > < wsu : Timestamp wsu : Id= '' TS-4A5A4F8820EFD673E7152328322340510393 '' > < wsu : Created > 2018-04-09T14:13:43.405Z < /wsu : Created > < wsu : Expires > 2018-04-09T14:18:43.405Z < /wsu : Expires > < /wsu : Timestamp > < /wsse : Security > < /soap : Header > < soap : Body > < xenc : EncryptedData xmlns : xenc= '' http : //www.w3.org/2001/04/xmlenc # '' Id= '' ED-4A5A4F8820EFD673E7152328322340710395 '' Type= '' http : //www.w3.org/2001/04/xmlenc # Content '' > < xenc : EncryptionMethod Algorithm= '' http : //www.w3.org/2001/04/xmlenc # aes128-cbc '' / > < ds : KeyInfo xmlns : ds= '' http : //www.w3.org/2000/09/xmldsig # '' > < wsse : SecurityTokenReference xmlns : wsse= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd '' xmlns : wsse11= '' http : //docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd '' wsse11 : TokenType= '' http : //docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1 # EncryptedKey '' > < wsse : Reference URI= '' # EK-4A5A4F8820EFD673E7152328322340610394 '' / > < /wsse : SecurityTokenReference > < /ds : KeyInfo > < xenc : CipherData > < xenc : CipherValue > ZB7P3tYgRE4R7RZc0TONazc93t ... . W5VoHVw5ywRj4D2hb9dIAaE8PQClm2vw== < /xenc : CipherValue > < /xenc : CipherData > < /xenc : EncryptedData > < /soap : Body > < /soap : Envelope > System.ServiceModel.dll ! System.ServiceModel.Security.WSSecurityJan2004.WrappedKeyTokenEntry.ReadTokenCore ( System.Xml.XmlDictionaryReader reader , System.IdentityModel.Selectors.SecurityTokenResolver tokenResolver ) System.ServiceModel.dll ! System.ServiceModel.Security.WSSecurityTokenSerializer.ReadTokenCore ( System.Xml.XmlReader reader , System.IdentityModel.Selectors.SecurityTokenResolver tokenResolver ) System.ServiceModel.dll ! System.ServiceModel.Security.WSSecurityOneDotZeroReceiveSecurityHeader.DecryptWrappedKey ( System.Xml.XmlDictionaryReader reader ) System.ServiceModel.dll ! System.ServiceModel.Security.ReceiveSecurityHeader.ReadEncryptedKey ( System.Xml.XmlDictionaryReader reader , bool processReferenceListIfPresent ) System.ServiceModel.dll ! System.ServiceModel.Security.ReceiveSecurityHeader.ExecuteFullPass ( System.Xml.XmlDictionaryReader reader ) System.ServiceModel.dll ! System.ServiceModel.Security.ReceiveSecurityHeader.Process ( System.TimeSpan timeout , System.Security.Authentication.ExtendedProtection.ChannelBinding channelBinding , System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy extendedProtectionPolicy ) System.ServiceModel.dll ! System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore ( ref System.ServiceModel.Channels.Message message , System.TimeSpan timeout ) System.ServiceModel.dll ! System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage ( ref System.ServiceModel.Channels.Message message , System.TimeSpan timeout ) System.ServiceModel.dll ! System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage ( ref System.ServiceModel.Channels.Message message , System.TimeSpan timeout , System.ServiceModel.Security.SecurityProtocolCorrelationState [ ] correlationStates ) System.ServiceModel.dll ! System.ServiceModel.Channels.SecurityChannelFactory < System.ServiceModel.Channels.IRequestChannel > .SecurityRequestChannel.ProcessReply ( System.ServiceModel.Channels.Message reply , System.ServiceModel.Security.SecurityProtocolCorrelationState correlationState , System.TimeSpan timeout ) System.ServiceModel.dll ! System.ServiceModel.Channels.SecurityChannelFactory < System.__Canon > .SecurityRequestChannel.Request ( System.ServiceModel.Channels.Message message , System.TimeSpan timeout ) System.ServiceModel.dll ! System.ServiceModel.Dispatcher.RequestChannelBinder.Request ( System.ServiceModel.Channels.Message message , System.TimeSpan timeout ) System.ServiceModel.dll ! System.ServiceModel.Channels.ServiceChannel.Call ( string action , bool oneway , System.ServiceModel.Dispatcher.ProxyOperationRuntime operation , object [ ] ins , object [ ] outs , System.TimeSpan timeout ) System.ServiceModel.dll ! System.ServiceModel.Channels.ServiceChannelProxy.InvokeService ( System.Runtime.Remoting.Messaging.IMethodCallMessage methodCall , System.ServiceModel.Dispatcher.ProxyOperationRuntime operation ) System.ServiceModel.dll ! System.ServiceModel.Channels.ServiceChannelProxy.Invoke ( System.Runtime.Remoting.Messaging.IMessage message ) mscorlib.dll ! System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke ( ref System.Runtime.Remoting.Proxies.MessageData msgData , int type ) ... mycode_calling_the_service ( ) ... WrappedKeySecurityToken CreateWrappedKeyToken ( string id , string encryptionMethod , string carriedKeyName , SecurityKeyIdentifier unwrappingTokenIdentifier , byte [ ] wrappedKey , SecurityTokenResolver tokenResolver ) { ISspiNegotiationInfo sspiResolver = tokenResolver as ISspiNegotiationInfo ; if ( sspiResolver ! = null ) { ISspiNegotiation unwrappingSspiContext = sspiResolver.SspiNegotiation ; // ensure that the encryption algorithm is compatible if ( encryptionMethod ! = unwrappingSspiContext.KeyEncryptionAlgorithm ) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError ( new MessageSecurityException ( SR.GetString ( SR.BadKeyEncryptionAlgorithm , encryptionMethod ) ) ) ; } byte [ ] unwrappedKey = unwrappingSspiContext.Decrypt ( wrappedKey ) ; return new WrappedKeySecurityToken ( id , unwrappedKey , encryptionMethod , unwrappingSspiContext , unwrappedKey ) ; } else { if ( tokenResolver == null ) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError ( new ArgumentNullException ( `` tokenResolver '' ) ) ; } if ( unwrappingTokenIdentifier == null || unwrappingTokenIdentifier.Count == 0 ) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError ( new MessageSecurityException ( SR.GetString ( SR.MissingKeyInfoInEncryptedKey ) ) ) ; } SecurityToken unwrappingToken ; SecurityHeaderTokenResolver resolver = tokenResolver as SecurityHeaderTokenResolver ; if ( resolver ! = null ) { { if ( ! resolver.CheckExternalWrapperMatch ( unwrappingTokenIdentifier ) ) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError ( new MessageSecurityException ( SR.GetString ( SR.EncryptedKeyWasNotEncryptedWithTheRequiredEncryptingToken , unwrappingToken ) ) ) ; } } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError ( new MessageSecurityException ( SR.GetString ( SR.UnableToResolveKeyInfoForUnwrappingToken , unwrappingTokenIdentifier , resolver ) ) ) ; } } | Apache CXF WS Security WebService from NET Client - Can not resolve KeyInfo for unwrapping key |
C_sharp : I have a main application that loads up some plugins . These plugins are loaded and run in separate app domains using a class that inherits from `` MarshalByRefObject '' ; This all works fine.What I need now is a way to handle when the plugin wants the main app to do something and a way to dynamically handle this in the main application . If the best way is to poll the plugin for a list of commands , then I can do that , although it seems a bit of a kludge.What are the best ways to send a request from the plugin across the app domain to the main app ? UPDATEAs an update to the question , I am looking to sent data across the app domain that makes the main app do something , like a `` File- > New '' operation or `` GetSomeData ( ) '' call . In doing this I need to make the Plugin wait for the main app to complete whatever it is doing , but also be able to decide , main app side , whether or not to execute the requested function/event.I was doing this by passing the plugin an interface . This interface was implemented by a class in the main app that defined some events . The main app could then subscribe to these events and the plugin could make the main app functions fire . The problem is that the interface only referenced the class as it was when I passed the interface . I.e if I created the class with no events subscribed , then passed the interface like this : the plugin would receive the interface , but any changes to the original class did not propagate . So adding : would not change the plugin 's version of the event . The plugin could do this : ... but the event that it tries to call is null . Now , this is not a problem if I make the main app subscribe to the event first , then pass the interface : The plugin could then call CallTheSubscribedFunction ( ) and the event would fire in the main app . I need to be able to subscribe to events like this on demand because some things/events/data in the main app are available at different times.So , a lot of info I was trying to avoid having to write out , but I guess my question was too general in relation to my issue.If anyone has suggestions please let me know . Again , my goal is to allow the plugin to trigger an event in the main app , wait for the main app to finish , then continue with it 's execution , where the main app may or may not be subscribed to the events.Update 2I realize the above info is specialized to my application , but I 'm looking for general suggestions as well . So , if using threads is an option , let me know how a general case might work . If another case would work better and I need to do some redesigning to implement it let me know that as well . Just looking for suggestions here . Thanks . <code> CallbackClass myCallbackClass = new CallbackClass ( ) ; pluginInterface.HeresMyCallbackClass ( ( ICallbackClass ) myCallbackClass ) ; myCallbackClass.MyMainAppEvent += new MainEventHandler ( MyMainAppFunction ) ; //code within pluginICallbackClass callToMainApp ; public HeresMyCallbackClass ( ICallbackClass cbClass ) { callToMainApp = cbClass ; } public CallAMainAppFunction ( ) { callToMainApp.CallTheSubscribedFunction ( ) ; //This is where it all goes wrong } CallbackClass myCallbackClass = new CallbackClass ( ) ; myCallbackClass.MyMainAppEvent += new MainEventHandler ( MyMainAppFunction ) ; //Subscribe firstpluginInterface.HeresMyCallbackClass ( ( ICallbackClass ) myCallbackClass ) ; | What ways can I send data from a plugin across an app domain that triggers an event in the main application in C # ? |
C_sharp : I found this other stack overflow question about files and directories , and the answer included this statement : His question was about .net , and I was coding in C # .net in Visual Studio . Is the ability to have both an assignment operator and an equals operator in the same statement work for all .net languages or is it specific to certain ones ? Also , can I get an explanation for how the above code works ? Assuming that path refers to a directory , I 'd expect isDir to be true , but can anyone explain why ? <code> bool isDir = ( File.GetAttributes ( path ) & FileAttributes.Directory ) == FileAttributes.Directory ; | How can a statement have both = and == ? |
C_sharp : Quick question . I have a listbox being populated from a directory listing . Each file contains its name and ~ # # # # # . I 'm trying to read it all into a string and replace the ~ # # # # with nothing . The # # # # could be digits from length 1-6 and could be anything from 0-9 . Here 's the code I 'm using : Example : I ca n't replace any number because I need the numbers before the ~ <code> string listItem = ( listBox1.SelectedItem.ToString ( ) .Replace ( `` ~* '' , '' '' ) ) ; Here223~123 -- - > HereHere224~2321 -- -- > Here | C # string replacement question |
C_sharp : I am using this iOS SegmentedControlRenderer on a page . But when I go to the page this way : Navigation.PushAsync ( new CFSPage ( ) ) and then click on the back arrow to go to the previous page , the OnElementChanged event in my customer iOS renderer is fired . The result with my renderer is that the following line gives a null reference error : segmentedControl.TintColor = e.NewElement ? .TintColor.ToUIColor ( ) ; Can someone please explain what 's the purpose of the ? here and also should this line be after or should it be inside the if ( e.NewElement ! = null ) check . Am I correct in saying that the following lines should NOT be executed if there is no NewElement ? This renderer as is does n't have an Is that something that 's missing ? Renderer <code> segmentedControl.TintColor = e.NewElement ? .TintColor.ToUIColor ( ) ; SetNativeControl ( segmentedControl ) ; SetSelectedSegment ( ) ; protected override void Dispose ( bool disposing ) public class SegmentedControlRenderer : ViewRenderer < SegmentedControl , UISegmentedControl > { protected override void OnElementChanged ( ElementChangedEventArgs < SegmentedControl > e ) { base.OnElementChanged ( e ) ; UISegmentedControl segmentedControl = null ; if ( Control == null ) { segmentedControl = new UISegmentedControl ( ) ; for ( var i = 0 ; i < e.NewElement.Children.Count ; i++ ) { segmentedControl.InsertSegment ( Element.Children [ i ] .Text , i , false ) ; } SetNativeControl ( segmentedControl ) ; SetSelectedSegment ( ) ; } if ( e.OldElement ! = null ) { if ( segmentedControl ! = null ) segmentedControl.ValueChanged -= NativeValueChanged ; } if ( e.NewElement ! = null ) { segmentedControl.ValueChanged += NativeValueChanged ; } segmentedControl.TintColor = e.NewElement ? .TintColor.ToUIColor ( ) ; SetNativeControl ( segmentedControl ) ; SetSelectedSegment ( ) ; } protected override void OnElementPropertyChanged ( object sender , System.ComponentModel.PropertyChangedEventArgs e ) { base.OnElementPropertyChanged ( sender , e ) ; if ( e.PropertyName == nameof ( SegmentedControl.SelectedSegment ) ) SetSelectedSegment ( ) ; if ( e.PropertyName == SegmentedControl.TintColorProperty.PropertyName ) SetSegmentTintColor ( ) ; } void NativeValueChanged ( object sender , EventArgs e ) { if ( Element is SegmentedControl formsElement ) { formsElement.SelectedSegment = ( int ) Control.SelectedSegment ; } ; } void SetSegmentTintColor ( ) { if ( Element is SegmentedControl formsElement ) Control.TintColor = formsElement.TintColor.ToUIColor ( ) ; } void SetSelectedSegment ( ) { if ( Element is SegmentedControl formsElement ) { if ( formsElement.SelectedSegment > = 0 & & formsElement.SelectedSegment < Control.NumberOfSegments ) Control.SelectedSegment = formsElement.SelectedSegment ; } } } | Does a controls OnElementChanged ( ) get called when I leave a page ? |
C_sharp : I 'm trying to open a thumbscache.db file , I 've tried to open it like any other database but no use . I 've also looked for any API or support in C # . Kindly suggest if there is another way.BTW below is my approach so far.1 . Open it like any other db.But this exception comes up.2 . Open it using ShellFileAnd instead of thumbscache it gives file thumb icon.3 . Opening as OLE Document using OpenMcdf And this exception comes up . <code> path = Environment.GetFolderPath ( Environment.SpecialFolder.LocalApplicationData ) ; path += @ '' \Microsoft\Windows\Explorer\thumbcache_1280.db '' ; datasource = `` Data source = `` + path ; SQLiteCommand cmd = new SQLiteCommand ( ) ; SQLiteConnection conn = new SQLiteConnection ( datasource ) ; cmd.Connection = conn ; cmd.CommandText = `` SELECT * FROM Filename '' ; conn.Open ( ) ; SQLiteDataAdapter sqda = new SQLiteDataAdapter ( cmd ) ; DataTable dt = new DataTable ( ) ; sqda.Fill ( dt ) ; dataGridView1.DataSource = dt ; conn.Close ( ) ; ShellFile shellFile = ShellFile.FromFilePath ( path ) ; Bitmap bitmap = shellFile.Thumbnail.ExtraLargeBitmap ; pbThumbs.Image = bitmap ; path = Environment.GetFolderPath ( Environment.SpecialFolder.LocalApplicationData ) ; path += @ '' \Microsoft\Windows\Explorer\thumbcache_1280.db '' ; CompoundFile cf = new CompoundFile ( path ) ; CFStream foundStream = cf.RootStorage.GetStream ( `` Filename '' ) ; byte [ ] temp = foundStream.GetData ( ) ; | How to open Thumbscache.db |
C_sharp : Every time we need a high decimal-precision , we use decimals to do the calculations . Is there any way to check if the precision did suffice for the calculation ? I would like to make the following code throw an exception : It does n't really matter in real code , but it would be nice to be safe . <code> decimal almostMax = Decimal.MaxValue - 1 ; decimal x = almostMax + 0.1m ; // This should create an exception , since x equals almostMax.Assert.AreEqual ( x , almostMax ) ; // This does NOT fail . | How to get an exception on inaccurate calculation ? |
C_sharp : I 've created a simple .NET Framework 4.7.2 WPF app with two controls - a text box and a button . Here is my code behind : After pressing StartTest button I see the following results in the Output text box : My question is why [ 7 ] Task delay has been cancelled . is executed in the same thread where token cancellation is being requested ? What I would expect to see is [ 7 ] Before cancellation . followed by [ 7 ] After cancellation . and then Task delay has been cancelled.. Or at least Task delay has been cancelled . being executed in another thread.Note that if I execute cancellationTokenSource.Cancel ( ) from the main thread then the output looks as expected : UPDATEInterestingly when I replacewith.NET keeps that background thread busy and the output is again as expected : UPDATE 2I 've updated the code example slightly in the hope to make a bit clearer.Note that this is not purely hypothetical question but an actual problem I 've spent quite some time to understand in our production code . But for the sake of brevity I 've created this extremely simplified code example that illustrates the same behaviour . <code> private async void StartTest_Click ( object sender , RoutedEventArgs e ) { Output.Clear ( ) ; var cancellationTokenSource = new CancellationTokenSource ( ) ; // Fire and forget Task.Run ( async ( ) = > { try { await Task.Delay ( TimeSpan.FromMinutes ( 1 ) , cancellationTokenSource.Token ) ; } catch ( OperationCanceledException ) { Task.Delay ( TimeSpan.FromSeconds ( 3 ) ) .Wait ( ) ; Print ( `` Task delay has been cancelled . `` ) ; } } ) ; await Task.Delay ( TimeSpan.FromSeconds ( 1 ) ) ; await Task.Run ( ( ) = > { Print ( `` Before cancellation . `` ) ; cancellationTokenSource.Cancel ( ) ; Print ( `` After cancellation . `` ) ; } ) ; } private void Print ( string message ) { var threadId = Thread.CurrentThread.ManagedThreadId ; var time = DateTime.Now.ToString ( `` HH : mm : ss.ffff '' ) ; Dispatcher.Invoke ( ( ) = > { Output.AppendText ( $ '' { time } [ { threadId } ] { message } \n '' ) ; } ) ; } 12:05:54.1508 [ 7 ] Before cancellation.12:05:57.2431 [ 7 ] Task delay has been cancelled.12:05:57.2440 [ 7 ] After cancellation . 12:06:59.5583 [ 1 ] Before cancellation.12:06:59.5603 [ 1 ] After cancellation.12:07:02.5998 [ 5 ] Task delay has been cancelled . await Task.Delay ( TimeSpan.FromMinutes ( 1 ) , cancellationTokenSource.Token ) ; while ( true ) { await Task.Delay ( TimeSpan.FromMilliseconds ( 100 ) ) ; cancellationTokenSource.Token.ThrowIfCancellationRequested ( ) ; } 12:08:15.7259 [ 5 ] Before cancellation.12:08:15.7289 [ 5 ] After cancellation.12:08:18.8418 [ 7 ] Task delay has been cancelled.. | Unexpected task cancellation behaviour |
C_sharp : I have these two statements : What I would like to do is to check if changes ( ) = 0 in the first statement before running the second statement . Can anyone tell me how I can group together these two statements in to one so I can check the value of changes ( ) ? <code> db2.Execute ( `` UPDATE CLICKHISTORY SET `` + `` DAYOFYEAR = `` + dayOfYear + `` , `` + `` YEAR = `` + year + `` , `` + `` MONTH = `` + month + `` , `` + `` DAY = `` + day + `` , `` + `` BTNACOUNT = BTNACOUNT + 1 WHERE YYMMDD = `` + yymmdd ) ; db2.Execute ( `` INSERT INTO CLICKHISTORY `` + `` ( YYMMDD , DAYOFYEAR , YEAR , MONTH , DAY , BTNACOUNT ) `` + `` VALUES ( `` + yymmdd + `` , `` + dayOfYear + `` , `` + year + `` , `` + month + `` , `` + day + `` , `` + `` 1 ) WHERE changes ( ) = 0 '' ) ; | How to combine two SQLite statements running in C # ? |
C_sharp : We 've been using EF 4.0 with a database-first approach using an .edmx model.We 're now upgrading to EF 6.1.3 , and we 're investigating whether to go with or without that .edmx model . We definitely still want to be in control of our database schema - so we 'll be creating new tables etc . with SQL script and then generating the EF model ( either .edmx or just code classes ) from the existing database.During my trials with Visual Studio 2013 , I noticed an annoying point when EF 6 creates the classes from the existing database . I have a Customer class which links to a Contact class three times - once for the DesignContact , once for the SalesContact and a third time for the SupportContact . Those are stored as DesignContactId ( INT ) etc . columns in the Customer table.You can create those classes using this T-SQL : When creating the classes from the database , I see this : the Customer class has my three xxxContactId columns as fields - that 's as expectedEF also generates three navigation properties of type Contact - but it calls them Contact , Contact1 , Contact2 - uuuuuggghHHHH ! I 'm trying to find a way to get around those horribly bad named navigation properties ... .. these are bad because : their not intuitive - which one points to which contact now ? are the `` stable '' , or could they change over time , if a fourth relationship to Contact is introduced ? Not sure ... .. ( ca n't find any docs on this ) just their names are absolutely horrible ... ... why are n't they called DesignContact ( based on DesignContactId ) , SalesContact ( based on SalesContactId ) etc . ? In EF 4.1 and up , you were able to add T4 templates to the .edmx and influence the generation process - is that still possible somehow with EF6 , if you 're doing `` Generate code-first from existing database '' approach ? I could n't find any blog post or article on that topic anymore ... ..Or is there another way to influence how EF generates the classes - most notably the navigation properties ? Can I define some kind of custom convention or something to influence this ? <code> CREATE TABLE dbo.Contact ( ContactID INT NOT NULL CONSTRAINT PK_Contact PRIMARY KEY CLUSTERED , Name VARCHAR ( 200 ) , Address VARCHAR ( 200 ) , ZipCode VARCHAR ( 20 ) , City VARCHAR ( 100 ) , Phone VARCHAR ( 100 ) ) CREATE TABLE dbo.Customer ( CustomerID INT NOT NULL CONSTRAINT PK_Customer PRIMARY KEY CLUSTERED , Name VARCHAR ( 200 ) , -- other properties DesignContactID INT CONSTRAINT FK_Customer_DesignContact FOREIGN KEY REFERENCES dbo.Contact ( ContactID ) , SalesContactID INT CONSTRAINT FK_Customer_SalesContact FOREIGN KEY REFERENCES dbo.Contact ( ContactID ) , SupportContactID INT CONSTRAINT FK_Customer_SupportContact FOREIGN KEY REFERENCES dbo.Contact ( ContactID ) , ) | Influencing how entity classes are created in EF 6 code-first from database |
C_sharp : I 'm working on upgrading my .NET Core 2.2 MVC application to 3.0 . In this application I 'm authenticating to a controller using a JWT token . The token contains several claims , but when I try to access them through User.Claims the resulting list is always empty.In my Startup.cs I have the authentication setup like so : In Core 2.2 I was able to access my claims using code similar to the following : However , when I migrate the same code to Core 3.0 , I authenticate properly , but I get no claims for the User object . Did I miss a step in converting this to 3.0 ? Does User not get automatically populated with information anymore or something ? <code> public class Startup { public void ConfigureServices ( IServiceCollection services ) { // Code removed for clarity // services.AddAuthentication ( JwtBearerDefaults.AuthenticationScheme ) .AddJwtBearer ( options = > { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true , ValidateAudience = true , ValidateLifetime = true , ValidateIssuerSigningKey = true , ValidIssuer = JwtManager.Issuer , ValidAudience = `` MyAudience '' , IssuerSigningKey = `` MySigningKey '' } ; } ) ; } } [ Authorize ( AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme ) ] public class MyController : Controller { [ HttpGet ( `` MyController/Action '' ) ] public ActionResult < Aggregate [ ] > GetAction ( ) { var username = User.FindFirstValue ( `` MyUsernameClaim '' ) ; if ( username == null ) { return Forbid ( ) ; } // Do Stuff // } } | User.Claims Is Empty In MVC Application |
C_sharp : I can calculate cluster membership with KMeans pretty easily : Can I calculate partial membership with the standard KMeans algorithm ? A coworker suggested using the mean and variances of the cluster members to determine proportional membership and today I 've been looking into fuzzy sets and their implementations for F # . For example , here is some documentation for the Accord.net implementation for fuzzy sets . I can translate/run the example for F # but at first glance , I do n't see an easy way to get the data from my Kmeans run above to fit the format of assigning partial membership.Questions : How would I use the mean/variance of cluster members to calculate partial membership ? Is there an easy way to calculate partial membership with KMeans clustering with the Accord.net library ? The KMeans algorithm in Accord.net is simple to implement ; should I spend some time trying to learn this method of clustering/membership to suit my problem rather than try and force Kmeans clustering to suit my needs ? <code> open Systemopen System.IOopen Utilsopen Accordopen Accord.Math open Accord.MachineLearninglet vals = [ | [ |1.0 ; 2.0 ; 3.0 ; 2.0| ] [ |1.1 ; 1.9 ; 3.1 ; 4.0| ] [ |2.0 ; 3.0 ; 4.0 ; 4.0| ] [ |3.0 ; 3.1 ; 2.0 ; 3.0| ] [ |2.0 ; 4.0 ; 3.0 ; 6.0| ] [ |1.0 ; 5.0 ; 5.0 ; 7.0| ] [ |4.0 ; 3.0 ; 6.0 ; 8.0| ] [ |5.0 ; 4.0 ; 3.0 ; 6.0| ] [ |6.0 ; 4.0 ; 8.0 ; 7.0| ] [ |5.0 ; 6.0 ; 5.0 ; 9.0| ] [ |4.0 ; 2.0 ; 7.0 ; 8.0| ] [ |8.0 ; 9.0 ; 3.1 ; 2.2| ] [ |8.0 ; 9.0 ; 2.0 ; 2.0| ] [ |10.0 ; 2.0 ; 3.0 ; 2.0| ] [ |10.1 ; 1.9 ; 3.1 ; 4.0| ] [ |20.0 ; 3.0 ; 4.0 ; 4.0| ] [ |22.0 ; 7.0 ; 2.0 ; 3.0| ] [ |21.0 ; 4.0 ; 3.0 ; 6.0| ] | ] let kmeans = new KMeans 5let clusterModel = kmeans.Learn valslet clusters = clusterModel.Decide vals | Find partial membership with KMeans clustering algorithm |
C_sharp : Let 's say I have a class that will be called from multiple threads , and am going to store some data in an ImmutableDictionary in a private field in this classCould this be called in such a way by multiple threads that you will get an error about the key already existing in the dictionary ? Thread1 checks dictionary sees falseThread2 checks dictionary sees falseThread1 adds value and reference to _dict is updatedThread2 adds value , but it is already added because it uses the same reference ? <code> public class Something { private ImmutableDictionary < string , string > _dict ; public Something ( ) { _dict = ImmutableDictionary < string , string > .Empty ; } public void Add ( string key , string value ) { if ( ! _dict.ContainsKey ( key ) ) { _dict = _dict.Add ( key , value ) ; } } } | Using Bcl ImmutableDictionary in private field |
C_sharp : I believe ( correct me if i am wrong ) , according to the C # rule for value types , there is no default constructor . The CLR will define the one for zeroing out the field values.For reference type : Will the default constructor be supplied by C # or the CLR ? <code> class Test { private string Name ; } | Does the C # Compiler supply a default constructor for reference types ( if one not specified ) or does the CLR ? |
C_sharp : My class with an event : Derived event class : Some other class that register it to the event : What have I gained from following the .Net convention ? It would make more sense to have a contract like thisDoing it this way , I do n't need to create a new class and is easier to understand.I am not coding a .Net library . This code is only going to be used in this project . I like conventions but am I right when I say that in this example it does not make sense or have i missunderstood something ? <code> public class WindowModel { public delegate void WindowChangedHandler ( object source , WindowTypeEventArgs e ) ; public event WindowChangedHandler WindowChanged ; public void GotoWindow ( WindowType windowType ) { this.currentWindow = windowType ; this.WindowChanged.Invoke ( this , new WindowTypeEventArgs ( windowType ) ) ; } } public class WindowTypeEventArgs : EventArgs { public readonly WindowType windowType ; public WindowTypeEventArgs ( WindowType windowType ) { this.windowType = windowType ; } } private void SetupEvents ( ) { this.WindowModel.WindowChanged += this.ChangeWindow ; } private void ChangeWindow ( object sender , WindowTypeEventArgs e ) { //change window } public delegate void WindowChangedHandler ( WindowType windowType ) ; public event WindowChangedHandler WindowChanged ; | Events convention - I do n't get it |
C_sharp : I am pretty sure this was asked before but unfortunately the only thing I 've found was this that was not solution for me . In my current project I do something like : This code does not work of course because I 've not cast obj because its type changes dynamically.How can I cast it dynamically ? <code> private object obj ; private void Initialize ( ) { obj.Initialize ( ) ; } private void CreateInstanceA ( ) { obj = Activator.CreateInstance ( typeof ( MyClassA ) ) ; } private void CreateInstanceB ( ) { obj = Activator.CreateInstance ( typeof ( MyClassB ) ) ; } | How can I cast object dynamically ? |
C_sharp : Using xUnit 's Assert.Throws , I stumbled upon this ( to me ) hard to explain overload resolution issue . In xUnit , this method is marked obsolete : The question is , why does an inline statement lambda ( or expression ) that simply throws an exception resolve to this overload ( and therefore does n't compile ) ? <code> [ Obsolete ( `` You must call Assert.ThrowsAsync < T > ( and await the result ) `` + `` when testing async code . `` , true ) ] public static T Throws < T > ( Func < Task > testCode ) where T : Exception { throw new NotImplementedException ( ) ; } using System ; using Xunit ; class Program { static void Main ( string [ ] args ) { // this compiles ( of course ) // resolves into the overload accepting an ` Action ` Assert.Throws < Exception > ( ( ) = > ThrowException ( ) ) ; // line below gives error CS0619 'Assert.Throws < T > ( Func < Task > ) ' is obsolete : // 'You must call Assert.ThrowsAsync < T > ( and await the result ) when testing async code . ' Assert.Throws < Exception > ( ( ) = > { throw new Exception ( ) ; } ) ; } static void ThrowException ( ) { throw new Exception ( `` Some message '' ) ; } } | Why does this Assert.Throws call resolve this way ? |
C_sharp : We have this code which serves a download : It works fine , except that the log download code runs as soon as the download starts seemingly , not when the download has fully completed as we expect.Can someone explain why this is , and how to change it so it only logs when it 's completed ? We do n't want to count partial downloads . <code> public class downloadRelease : IHttpHandler { public void ProcessRequest ( HttpContext context ) { -- snip -- context.Response.Clear ( ) ; context.Response.ContentType = `` application/octet-stream '' ; context.Response.AddHeader ( `` Content-Disposition '' , `` attachment ; filename= '' + OriginalFileName ) ; context.Response.WriteFile ( Settings.ReleaseFileLocation + ActualFileName ) ; // Log download Constructor.VersionReleaseDownload.NewReleaseDownload ( ActualFileName ) ; | Only count a download once it 's served |
C_sharp : What is the best way in C # to get a collection of objects representing the changes between two XML texts , e.g . : First : Second : Changes : The point is to then pass the changes as a collection of objects onto a GUI which can appropriately display them.What is the best way to go about this , i.e . structure the class ( es ) that represents the changes and traverse/examine the XML in order to identify the changes most accurately ? <code> < Customer > < Id > 1 < /Id > < FirstName > Angie < /FirstName > < LastName > Jones < /LastName > < ZipCode > 23434 < /ZipCode > < Contracts > < Contract > < Id > 234 < /Id > < Title > Test Contract 1 < /Title > < /Contract > < /Contracts > < /Customer > < Customer > < Id > 1 < /Id > < FirstName > Angie < /FirstName > < MiddleName > S. < /MiddleName > < LastName > Jones-Smith < /LastName > < Contracts > < Contract > < Id > 234 < /Id > < Title > Test Contract 1 < /Title > < /Contract > < Contract > < Id > 534 < /Id > < Title > Test Contract 2 < /Title > < /Contract > < /Contracts > < /Customer > Kind : Node : Before After -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Change Customer/LastName Jones Jones-SmithAddition Customer/MiddleName S.Deletion Customer/ZipCodeAddition Customer/Contracts [ 1 ] < Contract > < Id > 534 < /Id > < Title > Test Contract 2 < /Title > < /Contract > | How to get a collection of objects representing the diff between two XML texts ? |
C_sharp : What would be the way to call some method by name , like `` Method1 '' , if I 've got an Object and it 's Type ? I want to do something like this : Is this somehow possible ? I do realize that this would be slow , it 's inconvenient , but unfortunately I 've got no other ways to implement this in my case . <code> Object o ; Type t ; // At this point I know , that ' o ' actually has// 't ' as it 's type.// And I know that 't ' definitely has a public method 'Method1'.// So , I want to do something like : Reflection.CallMethodByName ( o , `` Method1 '' ) ; | How do you call a method by its `` name '' ? |
C_sharp : I want to write a rule that will fail if an object allocation is made within any method called by a method marked with a particular attribute.I 've got this working so far , by iterating up all methods calling my method to check using CallGraph.CallersFor ( ) , to see if any of those parent methods have the attribute.This works for checking parent methods within the same assembly as the method to be checked , however reading online , it appears that at one time CallGraph.CallersFor ( ) did look at all assemblies , however now it does not.Question : Is there a way of getting a list of methods that call a given method , including those in a different assembly ? Alternative Answer : If the above is not possible , how do i loop through every method that is called by a given method , including those in a different assembly.Example : I do n't really mind where the rule reports the error , at this stage getting the error is enough . <code> -- -- -In Assembly Apublic class ClassA { public MethodA ( ) { MethodB ( ) ; } public MethodB ( ) { object o = new object ( ) ; // Allocation i want to break the rule // Currently my rule walks up the call tree , // checking for a calling method with the NoAllocationsAllowed attribute . // Problem is , because of the different assemblies , // it ca n't go from ClassA.MethodA to ClassB.MethodB . } } -- -- In Assembly Bpublic var ClassAInstance = new ClassA ( ) ; public class ClassB { [ NoAllocationsAllowed ] // Attribute that kicks off the rule-checking . public MethodA ( ) { MethodB ( ) ; } public MethodB ( ) { ClassAInstance.MethodA ( ) ; } } | Determining if a method calls a method in another assembly containing a new statement and vice-versa |
C_sharp : I 'm trying to build a code sample to show the optimization of code by the compiler when multiplying with a power of 2 number . Yet when I turn Optimize code on the IL remains mainly the same . Any ideas what I 'm doing wrong here ? The code : Non Optimized IL : Optimized IL : I thought the compiler would optimize the mul statement to a shl statement ? My knowledge of IL is very limited ( if not non-existing ) . <code> int nr ; int result ; var stopwatch = new Stopwatch ( ) ; nr = 5 ; stopwatch.Start ( ) ; result = nr * 4 ; stopwatch.Stop ( ) ; Console.WriteLine ( result ) ; Console.WriteLine ( stopwatch.Elapsed.ToString ( ) + `` ms ellapsed '' ) ; stopwatch.Reset ( ) ; stopwatch.Start ( ) ; result = nr < < 2 ; stopwatch.Stop ( ) ; Console.WriteLine ( result ) ; Console.WriteLine ( stopwatch.Elapsed.ToString ( ) + `` ms ellapsed '' ) ; .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 130 ( 0x82 ) .maxstack 2 .locals init ( [ 0 ] int32 nr , [ 1 ] int32 result , [ 2 ] class [ System ] System.Diagnostics.Stopwatch stopwatch , [ 3 ] valuetype [ mscorlib ] System.TimeSpan CS $ 0 $ 0000 , [ 4 ] valuetype [ mscorlib ] System.TimeSpan CS $ 0 $ 0001 ) IL_0000 : newobj instance void [ System ] System.Diagnostics.Stopwatch : :.ctor ( ) IL_0005 : stloc.2 IL_0006 : ldc.i4.5 IL_0007 : stloc.0 IL_0008 : ldloc.2 IL_0009 : callvirt instance void [ System ] System.Diagnostics.Stopwatch : :Start ( ) IL_000e : ldloc.0 IL_000f : ldc.i4.4 IL_0010 : mul IL_0011 : stloc.1 IL_0012 : ldloc.2 IL_0013 : callvirt instance void [ System ] System.Diagnostics.Stopwatch : :Stop ( ) IL_0018 : ldloc.1 IL_0019 : call void [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_001e : ldloc.2 IL_001f : callvirt instance valuetype [ mscorlib ] System.TimeSpan [ System ] System.Diagnostics.Stopwatch : :get_Elapsed ( ) IL_0024 : stloc.3 IL_0025 : ldloca.s CS $ 0 $ 0000 IL_0027 : constrained . [ mscorlib ] System.TimeSpan IL_002d : callvirt instance string [ mscorlib ] System.Object : :ToString ( ) IL_0032 : ldstr `` ms ellapsed '' IL_0037 : call string [ mscorlib ] System.String : :Concat ( string , string ) IL_003c : call void [ mscorlib ] System.Console : :WriteLine ( string ) IL_0041 : ldloc.2 IL_0042 : callvirt instance void [ System ] System.Diagnostics.Stopwatch : :Reset ( ) IL_0047 : ldloc.2 IL_0048 : callvirt instance void [ System ] System.Diagnostics.Stopwatch : :Start ( ) IL_004d : ldloc.0 IL_004e : ldc.i4.2 IL_004f : shl IL_0050 : stloc.1 IL_0051 : ldloc.2 IL_0052 : callvirt instance void [ System ] System.Diagnostics.Stopwatch : :Stop ( ) IL_0057 : ldloc.1 IL_0058 : call void [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_005d : ldloc.2 IL_005e : callvirt instance valuetype [ mscorlib ] System.TimeSpan [ System ] System.Diagnostics.Stopwatch : :get_Elapsed ( ) IL_0063 : stloc.s CS $ 0 $ 0001 IL_0065 : ldloca.s CS $ 0 $ 0001 IL_0067 : constrained . [ mscorlib ] System.TimeSpan IL_006d : callvirt instance string [ mscorlib ] System.Object : :ToString ( ) IL_0072 : ldstr `` ms ellapsed '' IL_0077 : call string [ mscorlib ] System.String : :Concat ( string , string ) IL_007c : call void [ mscorlib ] System.Console : :WriteLine ( string ) IL_0081 : ret } // end of method Program : :Main .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 130 ( 0x82 ) .maxstack 2 .locals init ( [ 0 ] int32 nr , [ 1 ] int32 result , [ 2 ] class [ System ] System.Diagnostics.Stopwatch stopwatch , [ 3 ] valuetype [ mscorlib ] System.TimeSpan CS $ 0 $ 0000 , [ 4 ] valuetype [ mscorlib ] System.TimeSpan CS $ 0 $ 0001 ) IL_0000 : newobj instance void [ System ] System.Diagnostics.Stopwatch : :.ctor ( ) IL_0005 : stloc.2 IL_0006 : ldc.i4.5 IL_0007 : stloc.0 IL_0008 : ldloc.2 IL_0009 : callvirt instance void [ System ] System.Diagnostics.Stopwatch : :Start ( ) IL_000e : ldloc.0 IL_000f : ldc.i4.4 IL_0010 : mul IL_0011 : stloc.1 IL_0012 : ldloc.2 IL_0013 : callvirt instance void [ System ] System.Diagnostics.Stopwatch : :Stop ( ) IL_0018 : ldloc.1 IL_0019 : call void [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_001e : ldloc.2 IL_001f : callvirt instance valuetype [ mscorlib ] System.TimeSpan [ System ] System.Diagnostics.Stopwatch : :get_Elapsed ( ) IL_0024 : stloc.3 IL_0025 : ldloca.s CS $ 0 $ 0000 IL_0027 : constrained . [ mscorlib ] System.TimeSpan IL_002d : callvirt instance string [ mscorlib ] System.Object : :ToString ( ) IL_0032 : ldstr `` ms ellapsed '' IL_0037 : call string [ mscorlib ] System.String : :Concat ( string , string ) IL_003c : call void [ mscorlib ] System.Console : :WriteLine ( string ) IL_0041 : ldloc.2 IL_0042 : callvirt instance void [ System ] System.Diagnostics.Stopwatch : :Reset ( ) IL_0047 : ldloc.2 IL_0048 : callvirt instance void [ System ] System.Diagnostics.Stopwatch : :Start ( ) IL_004d : ldloc.0 IL_004e : ldc.i4.2 IL_004f : shl IL_0050 : stloc.1 IL_0051 : ldloc.2 IL_0052 : callvirt instance void [ System ] System.Diagnostics.Stopwatch : :Stop ( ) IL_0057 : ldloc.1 IL_0058 : call void [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_005d : ldloc.2 IL_005e : callvirt instance valuetype [ mscorlib ] System.TimeSpan [ System ] System.Diagnostics.Stopwatch : :get_Elapsed ( ) IL_0063 : stloc.s CS $ 0 $ 0001 IL_0065 : ldloca.s CS $ 0 $ 0001 IL_0067 : constrained . [ mscorlib ] System.TimeSpan IL_006d : callvirt instance string [ mscorlib ] System.Object : :ToString ( ) IL_0072 : ldstr `` ms ellapsed '' IL_0077 : call string [ mscorlib ] System.String : :Concat ( string , string ) IL_007c : call void [ mscorlib ] System.Console : :WriteLine ( string ) IL_0081 : ret } // end of method Program : :Main | When does the compiler optimize my code |
C_sharp : Areo Glass Effect and windowStyle set to none and AllowTransparency causes widow resize to not function properlyAfter adding the Areo Glass theme to my window and setting WindowState to None the window does not resize properly . I can go as large as I want but when resizing down smaller the glass effect stays the same width and height.For example I click Maximize . The window Expands to the full screen size . But when restoring my window restores back down but not the glass effect.All I really want is the blur effect . I Do n't care about the glass , but this seems to be the only way I can get a transparent blur.How can I fix this ? xamlC # <code> < Window x : Class= '' WpfApplication2.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' AllowsTransparency= '' True '' WindowStyle= '' None '' ResizeMode= '' CanResizeWithGrip '' Background= '' Transparent '' > < Border BorderThickness= '' 1 '' Margin= '' 0,35,0,0 '' BorderBrush= '' Orange '' > < Grid Background= '' # 0CFFA500 '' > < DockPanel VerticalAlignment= '' Top '' HorizontalAlignment= '' Stretch '' Height= '' 35 '' Background= '' # 4effffff '' > < DockPanel.Resources > < Style x : Key= '' WindowIconStyle '' TargetType= '' { x : Type Button } '' > < Setter Property= '' FontSize '' Value= '' 16 '' / > < Setter Property= '' Foreground '' Value= '' # 444 '' / > < Setter Property= '' Height '' Value= '' 30 '' > < /Setter > < Setter Property= '' Width '' Value= '' 30 '' > < /Setter > < Setter Property= '' FontFamily '' Value= '' Webdings '' > < /Setter > < Setter Property= '' Background '' Value= '' # ff0000 '' > < /Setter > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type Button } '' > < Border BorderBrush= '' Transparent '' BorderThickness= '' 0.5,0,0.5,0 '' > < ContentPresenter HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' / > < /Border > < /ControlTemplate > < /Setter.Value > < /Setter > < Style.Triggers > < Trigger Property= '' IsMouseOver '' Value= '' True '' > < Setter Property= '' Background '' Value= '' # 77abff '' / > < Setter Property= '' Foreground '' Value= '' # 000000 '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type Button } '' > < Border BorderBrush= '' Black '' BorderThickness= '' 1,0,1,0 '' > < Border.Background > < LinearGradientBrush EndPoint= '' 0.5,1 '' MappingMode= '' RelativeToBoundingBox '' StartPoint= '' 0.5,0 '' > < GradientStop Color= '' Black '' Offset= '' 1 '' / > < GradientStop Color= '' White '' Offset= '' 0.952 '' / > < GradientStop Color= '' Black '' Offset= '' 0 '' / > < GradientStop Color= '' # FFF7F7F7 '' Offset= '' 0.044 '' / > < /LinearGradientBrush > < /Border.Background > < ContentPresenter HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' / > < /Border > < /ControlTemplate > < /Setter.Value > < /Setter > < /Trigger > < Trigger Property= '' IsPressed '' Value= '' True '' > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type Button } '' > < Border BorderBrush= '' # 444 '' BorderThickness= '' 1,0,1,0 '' > < Border.Background > < LinearGradientBrush EndPoint= '' 0.5,1 '' MappingMode= '' RelativeToBoundingBox '' StartPoint= '' 0.5,0 '' > < GradientStop Color= '' # 444 '' Offset= '' 1 '' / > < GradientStop Color= '' # ffececec '' Offset= '' 0.952 '' / > < GradientStop Color= '' # 444 '' Offset= '' 0 '' / > < GradientStop Color= '' # ffececec '' Offset= '' 0.044 '' / > < /LinearGradientBrush > < /Border.Background > < ContentPresenter HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' / > < /Border > < /ControlTemplate > < /Setter.Value > < /Setter > < /Trigger > < /Style.Triggers > < /Style > < /DockPanel.Resources > < Button DockPanel.Dock= '' Right '' VerticalAlignment= '' Center '' HorizontalAlignment= '' Right '' Click= '' TriggerClose '' Style= '' { StaticResource WindowIconStyle } '' Content= '' r '' / > < Button x : Name= '' btnMaximize '' DockPanel.Dock= '' Right '' VerticalAlignment= '' Center '' HorizontalAlignment= '' Right '' Click= '' TriggerMaximize '' Style= '' { StaticResource WindowIconStyle } '' Content= '' c '' / > < Button DockPanel.Dock= '' Right '' VerticalAlignment= '' Center '' HorizontalAlignment= '' Right '' Click= '' TriggerMinimize '' Style= '' { StaticResource WindowIconStyle } '' Content= '' 0 '' / > < StatusBar Background= '' Transparent '' MouseDoubleClick= '' TriggerMaximize '' MouseMove= '' TriggerMoveWindow '' > < TextBlock DockPanel.Dock= '' Left '' x : Name= '' txtTitle '' Text= '' Title '' FontSize= '' 16 '' Padding= '' 10,0,0,0 '' / > < /StatusBar > < /DockPanel > < Border BorderThickness= '' 0,1,0,0 '' Margin= '' 0,35,0,0 '' BorderBrush= '' # f7000000 '' > < /Border > < /Grid > < /Border > < /Window > using System ; using System.Runtime.InteropServices ; using System.Windows ; using System.Windows.Input ; using System.Windows.Interop ; namespace WpfApplication2 { public partial class MainWindow : Window { # region Constants private System.Windows.Window me { get ; set ; } private const int WM_DWMCOMPOSITIONCHANGED = 0x031E ; private const int DWM_BB_ENABLE = 0x1 ; # endregion //Constants # region Structures [ StructLayout ( LayoutKind.Sequential ) ] private struct DWM_BLURBEHIND { public int dwFlags ; public bool fEnable ; public IntPtr hRgnBlur ; public bool fTransitionOnMaximized ; } [ StructLayout ( LayoutKind.Sequential ) ] private struct MARGINS { public int cxLeftWidth ; public int cxRightWidth ; public int cyTopHeight ; public int cyBottomHeight ; } # endregion //Structures # region APIs [ DllImport ( `` dwmapi.dll '' , PreserveSig = false ) ] private static extern void DwmEnableBlurBehindWindow ( IntPtr hwnd , ref DWM_BLURBEHIND blurBehind ) ; [ DllImport ( `` dwmapi.dll '' ) ] private static extern int DwmExtendFrameIntoClientArea ( IntPtr hWnd , ref MARGINS pMargins ) ; [ DllImport ( `` dwmapi.dll '' , PreserveSig = false ) ] private static extern bool DwmIsCompositionEnabled ( ) ; # endregion //APIs public MainWindow ( ) { SourceInitialized += OnSourceInitialized ; InitializeComponent ( ) ; } private void OnSourceInitialized ( object sender , EventArgs eventArgs ) { me = ( Window ) sender ; if ( Environment.OSVersion.Version.Major > = 6 ) { var hwnd = new WindowInteropHelper ( me ) .Handle ; var hs = HwndSource.FromHwnd ( hwnd ) ; hs.CompositionTarget.BackgroundColor = System.Windows.Media.Colors.Transparent ; hs.AddHook ( new HwndSourceHook ( this.WndProc ) ) ; this.InitializeGlass ( hwnd ) ; } } public System.Windows.Media.Color GetAreoColor ( ) { int icolor = ( int ) Microsoft.Win32.Registry.GetValue ( @ '' HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM '' , `` ColorizationColor '' , null ) ; var c = System.Drawing.Color.FromArgb ( icolor ) ; return System.Windows.Media.Color.FromArgb ( c.A , c.R , c.G , c.B ) ; } private static String ConverterToHex ( System.Drawing.Color c ) { return String.Format ( `` # { 0 } { 1 } { 2 } '' , c.R.ToString ( `` X2 '' ) , c.G.ToString ( `` X2 '' ) , c.B.ToString ( `` X2 '' ) ) ; } # region Methods # region InitializeGlass public void InitializeGlass ( IntPtr hwnd ) { if ( ! DwmIsCompositionEnabled ( ) ) return ; // fill the background with glass var margins = new MARGINS ( ) ; margins.cxLeftWidth = margins.cxRightWidth = margins.cyBottomHeight = margins.cyTopHeight = -1 ; DwmExtendFrameIntoClientArea ( hwnd , ref margins ) ; // initialize blur for the window DWM_BLURBEHIND bbh = new DWM_BLURBEHIND ( ) ; bbh.fEnable = true ; // bbh.fTransitionOnMaximized = true ; bbh.dwFlags = DWM_BB_ENABLE ; DwmEnableBlurBehindWindow ( hwnd , ref bbh ) ; } # endregion //InitializeGlass # region WndProc private IntPtr WndProc ( IntPtr hwnd , int msg , IntPtr wParam , IntPtr lParam , ref bool handled ) { if ( msg == WM_DWMCOMPOSITIONCHANGED ) { this.InitializeGlass ( hwnd ) ; handled = false ; } return IntPtr.Zero ; } # endregion //WndProc # endregion //Methods private void TriggerMoveWindow ( object sender , MouseEventArgs e ) { if ( e.LeftButton == MouseButtonState.Pressed ) { if ( WindowState == System.Windows.WindowState.Maximized ) { WindowState = System.Windows.WindowState.Normal ; double pct = PointToScreen ( e.GetPosition ( this ) ) .X / System.Windows.SystemParameters.PrimaryScreenWidth ; Top = 0 ; Left = e.GetPosition ( this ) .X - ( pct * Width ) ; } Application.Current.MainWindow.DragMove ( ) ; } } private void TriggerMaximize ( object sender , EventArgs e ) { if ( WindowState == System.Windows.WindowState.Maximized ) { WindowState = System.Windows.WindowState.Normal ; btnMaximize.FontFamily = new System.Windows.Media.FontFamily ( `` Webdings '' ) ; btnMaximize.Content = `` c '' ; } else if ( WindowState == System.Windows.WindowState.Normal ) { WindowState = System.Windows.WindowState.Maximized ; btnMaximize.FontFamily = new System.Windows.Media.FontFamily ( `` Wingdings '' ) ; btnMaximize.Content = `` r '' ; InvalidateVisual ( ) ; } } private void TriggerClose ( object sender , RoutedEventArgs e ) { Close ( ) ; } private void TriggerMinimize ( object sender , RoutedEventArgs e ) { WindowState = System.Windows.WindowState.Minimized ; } } } | Areo Glass Effect and windowStyle set to none causes window resize to not function properly |
C_sharp : C # 6.0 in a Nutshell by Joseph Albahari and Ben Albahari ( O ’ Reilly ) . Copyright 2016 Joseph Albahari and Ben Albahari , 978-1-491-92706-9.states the following at page 96 , after introducing Implicit Calling of Parameterless Base-Class Constructor : If the base class has no accessible parameterless constructor , subclasses are forced to use the base keyword in their constructors.I am trying to create a code snippet to corroborate that , but did not yet succeed.My snippet : I expected to get a compiler error , following the book affirmation , but I get none . The code runs and correctly prints 1000.My question is : what does the book mean with subclasses being forced to use the base keyword ? I am trying to reproduce such scenario.What am I missing ? <code> public class X { public int Num { get ; set ; } public void Method_1 ( ) { Console.WriteLine ( `` X '' ) ; } public virtual void Method_2 ( ) { Console.WriteLine ( Num ) ; } } public class Y : X { public Y ( ) { Num = 1000 ; } } private static void Main ( string [ ] args ) { new Y ( ) .Method_2 ( ) ; } | When are derived classes constructors forced to use base keyword ? |
C_sharp : I 'm writing a program that is container for other , smaller programs . It loads it 's modules via Assembly.Load , finds types implementing IModule and makes instances of them.In WPF MainWindow I have a RoutedViewHost , which will display everything.In my AppBoostrapper , I have the following : Then , in my sample module : Also , each module has its MainViewModel , which is displayed by RoutedViewHost when module is chosen.Unfortunately , this does not work . I get the following error : ReactiveUI.RoutedViewHost ERROR Could n't find an IPlatformOperations . This should never happen , your dependency resolver is brokenThe ModuleLoader.Load goes like this : There is no error if I just create the instance instead of loading the assembly . If this is important , SampleModule also uses ReactiveUI.I 've tried adding Locator.CurrentMutable.InitializeReactiveUI ( ) ; in various places ( MainWindow constructor , App constructor , module static constructor ) , but nothing helped . Any ideas ? EDIT : if this is important , MainWindow is a MetroWindow from mahapps.metroEDIT2 : I tried to register PlatformOperations , as @ Wouter suggested with : ` var iPlatformOperations = Type.GetType ( `` ReactiveUI.IPlatformOperations , ReactiveUI , Version=7.4.0.0 , Culture=neutral , PublicKeyToken=null '' ) ; resolver.Register ( ( ) = > new PlatformOperations ( ) , iPlatformOperations ) ; ` both before module loading and after , but nothing changes . <code> private ReactiveList < IModule > LoadModules ( IMutableDependencyResolver resolver ) { var modules = ModuleLoader.Load ( ModulesDirectory ) ; // var modules = new IModule [ ] { new SampleModuleClass ( ) , } ; // this works perftectly ! foreach ( var module in modules ) { try { module.RegisterDependencies ( this , resolver ) ; } catch ( Exception e ) { Log.Error ( e , `` Could not register dependecies for module `` + module.Name ) ; } } Log.Debug ( `` Modules loaded : `` + string.Join ( `` , `` , modules.Select ( x = > x.Name ) ) ) ; return new ReactiveList < IModule > ( modules ) ; } public void RegisterDependencies ( IMainScreen screen , IMutableDependencyResolver resolver ) { _screen = screen ; _resolver = resolver ; resolver.Register ( ( ) = > new SampleView ( ) , typeof ( IViewFor < SampleViewModel > ) ) ; resolver.Register ( ( ) = > new GetNameDialogView ( ) , typeof ( IViewFor < GetNameDialogViewModel > ) ) ; Log.Debug ( `` Dependecies registered '' ) ; } public static IModule [ ] Load ( string path ) { if ( ! Directory.Exists ( path ) ) { Directory.CreateDirectory ( path ) ; Log.Error ( `` No modules directory found - creating '' ) ; return new IModule [ 0 ] ; } var moduleTypes = GetTypes ( path ) ; return moduleTypes.Select ( MakeInstance ) .Where ( x = > x ! = null ) .ToArray ( ) ; } private static IModule MakeInstance ( Type type ) { try { var module = type.GetConstructor ( new Type [ ] { } ) ? .Invoke ( new object [ ] { } ) as IModule ; if ( module ! = null ) { Log.Info ( `` { 0 } module succesfully instatiated '' , module.Name ) ; return module ; } Log.Error ( `` Could not instantiate { 0 } '' , type.FullName ) ; return null ; } catch ( Exception exception ) { Log.Error ( exception , `` Exception during instatiating { 0 } '' , type.FullName ) ; return null ; } } private static List < Type > GetTypes ( string path ) { var di = new DirectoryInfo ( path ) ; var moduleTypes = new List < Type > ( ) ; foreach ( var dir in di.GetDirectories ( ) ) { FileInfo [ ] files = dir.GetFiles ( `` *.dll '' ) ; foreach ( var file in files ) { Assembly newAssembly = Assembly.LoadFile ( file.FullName ) ; Type [ ] types = newAssembly.GetExportedTypes ( ) ; foreach ( var type in types ) { if ( type.IsClass & & ! type.IsAbstract & & ( type.GetInterface ( typeof ( IModule ) .FullName ) ! = null ) ) { moduleTypes.Add ( type ) ; Log.Debug ( `` Loaded { 0 } type '' , type.Name ) ; } } } } return moduleTypes ; } | `` Could n't find an IPlatformOperations . This should never happen , your dependency resolver is broken '' on WPF |
C_sharp : For example I have the following flag enum : According to MS Guidelines : DO name flag enums with plural nouns or noun phrases and simple enums with singular nouns or noun phrases.So I 've used plural form here . Now , there is another guideline to name your collections in plural form : DO name collection properties with a plural phrase describing the items in the collection instead of using a singular phrase followed by `` List '' or `` Collection . `` I have a class something like this : The problem is it gets very confusing when I try to work with separate items in that collection - they 're also colors.So how should I name a collection of flags then ? EDIT : Ok , the example is not very clear , I agree . Maybe this one is better : After text processor has finished , it has several results - one for each operations in Operations collection ( already confusing ) , e.g . one for SpellChecking AND TextFormatting , and another for Translation only . <code> [ Flags ] public enum Colors { Red = 1 , Green = 2 , Blue = 4 } public class Foo { public IEnumerable < Colors > Colors { get ; set ; } } [ Flags ] public enum Operations { TextFormatting = 1 , SpellChecking = 2 , Translation = 4 } public class TextProcessingParameters { public IEnumerable < Operations > Operations { get ; set ; } // other parameters , including parameters for different operations } | How to name a collection of flags ? |
C_sharp : I 'm looking at domain events , specifically at 2 possibilities : A . Using `` generic '' events like that : then the consumer would figure out the new state and do something . Since I 'm using Rx this would be not that hard ( and way better than a switch/case ) : B . Using specific events : this would lead to way more event classes , which on one hand may get too many , on the other hand event class names contain language and this may be a plus point.Do you have any recommendations ? I 'm not experienced with domain events and ca n't really make a qualified decision here ( both seem not to have any major drawbacks ) <code> public class OrderStateChangedEvent : IEvent { public Guid OrderId { get ; } public OrderState NewState { get ; } } var subscription = DomainEvents .AsObservable < OrderStateChangedEvent > ( ) .Where ( e = > e.NewState == OrderState.OrderCompleted ) .Subscribe ( OnOrderCompleted ) ; public class OrderCompletedEvent : IEvent { public Guid OrderId { get ; } } | DDD generic vs. specific domain events |
C_sharp : I was trying to create an example for deadlock . I tried the following code . But instead of creating deadlock , it worked like charm . Help me in understanding why it did n't create a deadlock . What change in this code would create a deadlock ? <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading ; namespace ReferenceTypes { class DeadLockExample { static int a ; static int b ; public static void Main ( string [ ] args ) { DeadLockExample.a = 20 ; DeadLockExample.b = 30 ; DeadLockExample d = new DeadLockExample ( ) ; Thread tA = new Thread ( new ThreadStart ( d.MethodA ) ) ; Thread tB = new Thread ( new ThreadStart ( d.MethodB ) ) ; tA.Start ( ) ; tB.Start ( ) ; Console.ReadLine ( ) ; } private void MethodA ( ) { lock ( this ) { Console.WriteLine ( a ) ; Thread.Sleep ( 1000 ) ; Console.WriteLine ( b ) ; } } private void MethodB ( ) { lock ( this ) { Console.WriteLine ( b ) ; Thread.Sleep ( 1000 ) ; Console.WriteLine ( a ) ; } } } } | Dead lock in Multithreading |
C_sharp : I 'm working on obtaining RSS feeds like so : XmlReader.Create ( ) in this case can throw up to 4 exceptions related to things like the parameter being null , 404 error , etc.Should I try to validate the Uri ( make sure it 's not null , 404 , correct doctype , etc ) before I call that line or should I just handle the exceptions ? I know I 've read numerous times on SO that exceptions should be used for truly exceptional circumstances and I agree this does n't seem to meet that prerequisite but it seems easier to just handle the exceptions . <code> SyndicationFeed rss = SyndicationFeed.Load ( XmlReader.Create ( textBox1.Text ) ) ; | Catch exception , validate input or both ? |
C_sharp : Edit : It seems that by trying to provide some solutions to my own problem I blurred the whole problem . So I 'm modifying the question little bit.Suppose I have this class : It is actually not important what 's going on in these methods . The important is that I have multiple unit tests to cover GetProtocolHeader method covering all situations ( returning correct header , null or exception ) and now I 'm writing unit tests for GetProtocolHeaderValue . If GetProtocolHeaderValue would be dependent on external dependency I would be able to mock it and inject it ( I 'm using Moq + NUnit ) . Then my unit test would just test expectation that external dependency was called and returned expected value . The external dependency would be tested by its own unit test and I would be done but how to correctly proceed in this example where method is not external dependency ? Clarification of the problem : I believe my test suite for GetProtocolHeaderValue must test situation where GetProtocolHeader returns header , null or exception . So the main question is : Should I write tests where GetProtocolHeader will be really executed ( some tests will be duplicated because they will test same code as tests for GetProtocolHeader itself ) or should I use mocking approach described by @ adrift and @ Eric Nicholson where I will not run real GetProtoclHeader but just configure mock to return header , null or exception when this method is called ? <code> public class ProtocolMessage : IMessage { public IHeader GetProtocolHeader ( string name ) { // Do some logic here including returning null // and throw exception in some cases return header ; } public string GetProtocolHeaderValue ( string name ) { IHeader header = GetProtocolHeader ( name ) ; // Do some logic here including returning null // and throw exception in some cases return value ; } } | How to keep my unit tests DRY when mocking does n't work ? |
C_sharp : Not sure if there 's a algorithm to describe this problem but are there any elegant methods to combine the list in a custom sequence . For example : I would like the contents of combined to contain a sequence as follows : The number of records in each list may not be equal . EDITWhen the number of records in each list may not be equal i mean : Expected results : <code> List < string > list1 = new List < string > ( ) ; List < string > list2 = new List < string > ( ) ; List < string > list3 = new List < string > ( ) ; list1.Add ( `` a '' ) ; list1.Add ( `` b '' ) ; list1.Add ( `` c '' ) ; list2.Add ( `` d '' ) ; list2.Add ( `` e '' ) ; list2.Add ( `` f '' ) ; list3.Add ( `` g '' ) ; list3.Add ( `` h '' ) ; list3.Add ( `` i '' ) ; List < string > combined = new List < string > ( ) ; a //First record in list1d //First record in list2g //First record in list3b //Second record in list1e //Second record in list2h //Second record in list3c //Third record in list1 f //Third record in list2 i //Third record in list3 List < string > list1 = new List < string > ( ) ; List < string > list2 = new List < string > ( ) ; List < string > list3 = new List < string > ( ) ; list1.Add ( `` a '' ) ; list2.Add ( `` b '' ) ; list2.Add ( `` c '' ) ; list3.Add ( `` d '' ) ; list3.Add ( `` e '' ) ; list3.Add ( `` f '' ) ; List < string > combined = new List < string > ( ) ; a //First record in list1b //First record in list2d //First record in list3c //Second record in list2e //Second record in list3f //Third record in list3 | How to combine multiple lists with custom sequence |
C_sharp : I have some code for strongly typing Includes ( ) 's in linq , like so ... My question is , is there anyway I can write a more generic function account for any level of successive includes ? Rather than having to rewrite it for say 3 , 4 , etc include types ? <code> public static ObjectQuery < T > Include < T > ( this ObjectQuery < T > mainQuery , Expression < Func < T , object > > subSelector ) { return mainQuery.Include ( ( ( subSelector.Body as MemberExpression ) .Member as System.Reflection.PropertyInfo ) .Name ) ; } /// < summary > /// Old way : ( from dbUser in DataSource.DataContext.Users.Include ( `` UserSubscriptions.ChurchSubscriptions '' ) select dbUser ) ; /// New way : ( from dbUser in DataSource.DataContext.Users.Include < Users , UserSubscriptions > ( u = > u.UserSubscriptions , s = > s.ChurchSubscriptions ) select dbUser ) ; /// < /summary > public static ObjectQuery < T > Include < T , Q > ( this ObjectQuery < T > mainQuery , Expression < Func < T , object > > tSubSelector , Expression < Func < Q , object > > qSubSelector ) { string tProperty = ( ( tSubSelector.Body as MemberExpression ) .Member as System.Reflection.PropertyInfo ) .Name ; string qProperty = ( ( qSubSelector.Body as MemberExpression ) .Member as System.Reflection.PropertyInfo ) .Name ; string path = string.Format ( `` { 0 } . { 1 } '' , tProperty , qProperty ) ; return mainQuery.Include ( path ) ; } | Query Extension for LINQ |
C_sharp : I 'm using Visual Studio 2012 Update 1 and .NET 4.5 here is the code.It appears the last function call is incorrectly resolving to Func instead of Action and it has something to do with unconditionally throwing an exception.Is this a BUG ? Thanks . <code> void Test ( Action a ) { } void Test ( Func < int > a ) { } void TestError ( ) { bool throwException = true ; //Resolves to Test ( Action a ) Test ( ( ) = > { } ) ; //Resolves to Test ( Action a ) Test ( ( ) = > { if ( throwException ) throw new Exception ( ) ; } ) ; //Resolves to Test ( Func < int > a ) // ( This seems like a bug since there is no return value ) Test ( ( ) = > { throw new Exception ( ) ; } ) ; //Resolves to Test ( Action a ) // ( With warning unreachable code detected ) Test ( ( ) = > { throw new Exception ( ) ; return ; //unreachable code detected } ) ; } | Resolving incorrect function at compile time BUG ? |
C_sharp : I am currently working on an extension method that facilitates what the question 's title suggests.I could , of course . use the GetMetohd ( `` Invoke '' ) method call on the type and be done with it , But something tells me this is not the `` safest '' way to go.Classes and types may change , including those in the BCL.So I 've come up with the following LINQ statement , which works just fine : The thing is , even this feels somewhat iffy , since one day Action can change and contain another method with such traits.. even if I add the `` HasGenericParameters '' constraint , there 's no assurance of safety.Do you have any ideas regarding a way to obtain the exact MethodInfo instance relevant to <code> public static class ActionExtensions { public static MethodInfo GetInvoke < T > ( this Action < T > obj ) { var actionType = obj.GetType ( ) ; var tType= typeof ( T ) ; return ( from methodInfo in actionType.GetMethods ( ) let par = methodInfo.GetParameters ( ) where par.Length == 1 & & par [ 0 ] .ParameterType == tType select methodInfo ) .FirstOrDefault ( ) ; } } `` Action < T > .Invoke ( ) '' | Safest way to get the Invoke MethodInfo from Action < T > 's Instance |
C_sharp : I have a system in which the main form is the menu , and it pops up a login form on loading . Originally it loaded the login form below the menu , so I used this.topmost = true to make it come to the front . ( as bring to front and send to back did not work ) However , if the user then clicks on something else , say chrome , then it still stays at the top of the z-order , by definition of topmost.I tried to use the deactivate event , but this meant that on load it once again comes up behind the menu form . How could I stop it from loading behind my menu form , and yet when it loses focus stop it from being topmost ? In the Menu form : <code> private void login_Deactivate ( object sender , EventArgs e ) { // do not want it to remain top most when the application is not in focus . this.TopMost = false ; } private void Menu_Load ( object sender , EventArgs e ) { openLogin ( ) } private void openLogin ( ) { Cursor.Current = Cursors.WaitCursor ; login theForm = new login ( this ) ; this.Enabled = false ; theForm.Show ( ) ; Cursor.Current = Cursors.Default ; theForm.Activate ( ) ; theForm.TopMost = true ; // Make the login form display over the Menu } | Login form not losing focus correctly |
C_sharp : I 'm trying to read information from an SSL certificate ( in this case I 've saved a copy of StackOverflow 's via Chrome ) but for some reason the moment I build it and run it from within a Linux Docker container , it fails to output anything.On Windows the output is what I expect : But the output from the same application on the Docker container is as follows : Here is my code : Is this a bug in .NET Core ( 2.2 ) , or do I need to read the certificate differently under Linux ? <code> S*.stackexchange.comstackexchange.comstackoverflow.com*.stackoverflow.comstackauth.comsstatic.net*.sstatic.netserverfault.com*.serverfault.comsuperuser.com*.superuser.comstackapps.comopenid.stackauth.com*.meta.stackexchange.commeta.stackexchange.commathoverflow.net*.mathoverflow.netaskubuntu.com*.askubuntu.comstacksnippets.net*.blogoverflow.comblogoverflow.com*.meta.stackoverflow.com*.stackoverflow.emailstackoverflow.emailstackoverflow.blogE SE const string ALT_NAME_KEY = `` Subject Alternative Name '' ; string certificateData = `` LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tDQpNSUlJUERDQ0J5U2dBd0lCQWdJUUIyWEdUblRsa2RhQU9jb3FoSFZqOERBTkJna3Foa2lHOXcwQkFRc0ZBREJ3DQpNUXN3Q1FZRFZRUUdFd0pWVXpFVk1CTUdBMVVFQ2hNTVJHbG5hVU5sY25RZ1NXNWpNUmt3RndZRFZRUUxFeEIzDQpkM2N1WkdsbmFXTmxjblF1WTI5dE1TOHdMUVlEVlFRREV5WkVhV2RwUTJWeWRDQlRTRUV5SUVocFoyZ2dRWE56DQpkWEpoYm1ObElGTmxjblpsY2lCRFFUQWVGdzB4T0RFd01EVXdNREF3TURCYUZ3MHhPVEE0TVRReE1qQXdNREJhDQpNR294Q3pBSkJnTlZCQVlUQWxWVE1Rc3dDUVlEVlFRSUV3Sk9XVEVSTUE4R0ExVUVCeE1JVG1WM0lGbHZjbXN4DQpIVEFiQmdOVkJBb1RGRk4wWVdOcklFVjRZMmhoYm1kbExDQkpibU11TVJ3d0dnWURWUVFEREJNcUxuTjBZV05yDQpaWGhqYUdGdVoyVXVZMjl0TUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUE5S2s2DQpOWFVQMW9jWHQ4OW1UMWNJeGFkQmh6Q0wwWVRxUDAxL0RTb3RVSFJ6VjcwcU9DVDdBZE1UMEsxSmk2ckZ5YXB6DQpSaXFVSWhBa2hFc2VYUnAwTU5yMjFmU1V3NFZvQ2IrSW1PNmduSWx6b2xraHJwSzZJeTM0S3lVM3p5dDhYWUQrDQptWTNpOEdqUFpPeXNSSk5MeTNvdVFCbXp1T21VLzJGb21ubWlFR0YwMm1WZ2IzZXY4UHJjbnQ3ZENpRjdsaUJJDQpzZDN6a1BlWHZUVlljVmNiL01CckZFemM0RnVJdXBoVGlKYm9Oejh3SHY5K1BYQVhVVUg4VEVTclVmRlBDS0pIDQp3ZDlFQW9OWDhqUFUxVEl4aUNvZTZYTjVFMW1QeUdneXZFbmFjSC9IZXJLL2VMYzQ2TDdZV1ZHUnlqSFdhYVRLDQowckpoS2draDU5cXNXQmRuNXdJREFRQUJvNElFMWpDQ0JOSXdId1lEVlIwakJCZ3dGb0FVVVdqL2tLOENCM1U4DQp6TmxsWkdLaUVyaFpjanN3SFFZRFZSME9CQllFRkpxS3dXN0I4azM2MlhzQzFJK3pBNnhxUGNaWU1JSUIvQVlEDQpWUjBSQklJQjh6Q0NBZStDRXlvdWMzUmhZMnRsZUdOb1lXNW5aUzVqYjIyQ0VYTjBZV05yWlhoamFHRnVaMlV1DQpZMjl0Z2hGemRHRmphMjkyWlhKbWJHOTNMbU52YllJVEtpNXpkR0ZqYTI5MlpYSm1iRzkzTG1OdmJZSU5jM1JoDQpZMnRoZFhSb0xtTnZiWUlMYzNOMFlYUnBZeTV1WlhTQ0RTb3VjM04wWVhScFl5NXVaWFNDRDNObGNuWmxjbVpoDQpkV3gwTG1OdmJZSVJLaTV6WlhKMlpYSm1ZWFZzZEM1amIyMkNEWE4xY0dWeWRYTmxjaTVqYjIyQ0R5b3VjM1Z3DQpaWEoxYzJWeUxtTnZiWUlOYzNSaFkydGhjSEJ6TG1OdmJZSVViM0JsYm1sa0xuTjBZV05yWVhWMGFDNWpiMjJDDQpHQ291YldWMFlTNXpkR0ZqYTJWNFkyaGhibWRsTG1OdmJZSVdiV1YwWVM1emRHRmphMlY0WTJoaGJtZGxMbU52DQpiWUlRYldGMGFHOTJaWEptYkc5M0xtNWxkSUlTS2k1dFlYUm9iM1psY21ac2IzY3VibVYwZ2cxaGMydDFZblZ1DQpkSFV1WTI5dGdnOHFMbUZ6YTNWaWRXNTBkUzVqYjIyQ0VYTjBZV05yYzI1cGNIQmxkSE11Ym1WMGdoSXFMbUpzDQpiMmR2ZG1WeVpteHZkeTVqYjIyQ0VHSnNiMmR2ZG1WeVpteHZkeTVqYjIyQ0dDb3ViV1YwWVM1emRHRmphMjkyDQpaWEptYkc5M0xtTnZiWUlWS2k1emRHRmphMjkyWlhKbWJHOTNMbVZ0WVdsc2doTnpkR0ZqYTI5MlpYSm1iRzkzDQpMbVZ0WVdsc2doSnpkR0ZqYTI5MlpYSm1iRzkzTG1Kc2IyY3dEZ1lEVlIwUEFRSC9CQVFEQWdXZ01CMEdBMVVkDQpKUVFXTUJRR0NDc0dBUVVGQndNQkJnZ3JCZ0VGQlFjREFqQjFCZ05WSFI4RWJqQnNNRFNnTXFBd2hpNW9kSFJ3DQpPaTh2WTNKc015NWthV2RwWTJWeWRDNWpiMjB2YzJoaE1pMW9ZUzF6WlhKMlpYSXRaell1WTNKc01EU2dNcUF3DQpoaTVvZEhSd09pOHZZM0pzTkM1a2FXZHBZMlZ5ZEM1amIyMHZjMmhoTWkxb1lTMXpaWEoyWlhJdFp6WXVZM0pzDQpNRXdHQTFVZElBUkZNRU13TndZSllJWklBWWI5YkFFQk1Db3dLQVlJS3dZQkJRVUhBZ0VXSEdoMGRIQnpPaTh2DQpkM2QzTG1ScFoybGpaWEowTG1OdmJTOURVRk13Q0FZR1o0RU1BUUlDTUlHREJnZ3JCZ0VGQlFjQkFRUjNNSFV3DQpKQVlJS3dZQkJRVUhNQUdHR0doMGRIQTZMeTl2WTNOd0xtUnBaMmxqWlhKMExtTnZiVEJOQmdnckJnRUZCUWN3DQpBb1pCYUhSMGNEb3ZMMk5oWTJWeWRITXVaR2xuYVdObGNuUXVZMjl0TDBScFoybERaWEowVTBoQk1raHBaMmhCDQpjM04xY21GdVkyVlRaWEoyWlhKRFFTNWpjblF3REFZRFZSMFRBUUgvQkFJd0FEQ0NBUVlHQ2lzR0FRUUIxbmtDDQpCQUlFZ2ZjRWdmUUE4Z0IzQUtTNUNaQzBHRmdVaDdzVG9zeG5jQW84TlpnRStSdmZ1T04zelE3SURkd1FBQUFCDQpaa0lKK1NNQUFBUURBRWd3UmdJaEFQQ2FkeHY0N2NCNFFPT3ZOOXMvUjIzRWVwRWJTSTQvTXVBZGY1dktlVTc5DQpBaUVBMmdaM084bnp1VVZhblJXOWZnNm1nZnNMMDhObi9aR203M08vRjNJR1gyVUFkd0NIZGIvbldYejRqRU9aDQpYNzN6YnY5V2pVZFdOdjlLdFdEQnRPci9YcUNERHdBQUFXWkNDZm9HQUFBRUF3QklNRVlDSVFEUWpmbVZCcSsvDQp5MmdCSy9lRTl4Nmp6OWhUWjV0SWZoa1N0Uzg1Zk1BeGVnSWhBTUF1Tmt5dU80dDA2RWlFZ01XaWFsSlp1QW5rDQpRdzI5R2NlSUJHOHIxQXAzTUEwR0NTcUdTSWIzRFFFQkN3VUFBNElCQVFBQWs4NzMvKzJRc3dLZkpTUW4raVplDQpaYzh1aUdnOTlwbWQwMDhFMmNtR0VycU56UGNsSzlJTmJQand4bDl6SWdUY1hwRi9VdEJWVlMxWjdYbzgzcWZzDQpHTVBkTXpZdDNGK2hRcFFZTGhsR0YrNUpmMng2WmIxempUL2FNM0dNZEdpKzZPUFYrWUhsL3dnVWU0NU42a1J1DQpEWm5WTDE2NytXM2wybkQrbVNoTy83eHF3SGladXowR0h5QkhScDVpNDNibEgwdmc2N3NKOGd1TjgxcGFwdXBZDQoydjc4RmN2UjhqMEVMZmd5ZWh0V3BqRjN2ektTcS9yWTJzTVhUWXpTUHFNZWtzc2VITmhTTVlVNld3OWg5cHlNDQphVm53OXZhaHFmN25LSEhjQzJWUlRVZ2tRZm45eURtbUJPbzBuUThYZ2ZwZDY1L1BheFZmQm51S2ZFa1hCZnBNDQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tDQo= '' ; var secretData = Convert.FromBase64String ( certificateData ) ; string [ ] urls = null ; using ( var cert = new X509Certificate2 ( secretData ) ) { urls = cert.Extensions .OfType < X509Extension > ( ) .Where ( e = > e.Oid.FriendlyName == ALT_NAME_KEY ) .Select ( e = > new AsnEncodedData ( e.Oid , e.RawData ) ) .Append ( new AsnEncodedData ( cert.SubjectName.Oid , cert.SubjectName.RawData ) ) .Select ( d = > d.Format ( true ) ) .SelectMany ( d = > Regex.Matches ( d , `` \\b ( ? : CN|DNS Name ) = ( ? < domain > .* ) ( ? : \\b| $ ) '' ) .OfType < Match > ( ) .Where ( m = > m.Success ) .Select ( m = > m.Groups [ `` domain '' ] .Value ) ) .Distinct ( ) .ToArray ( ) ; } Console.WriteLine ( `` S '' ) ; foreach ( var r in urls ) { Console.WriteLine ( r ) ; } Console.WriteLine ( `` E '' ) ; | Ca n't read certificate when running in Linux Docker container - works on Windows |
C_sharp : Here 's the setup : Having the following data : Now I 'm trying to get the following result in ONE linq statement : I 've tried grouping , using selectmany , joins and I ca n't seem to find the proper way.Any Linq wiz around ? P.S : Also , I want to traverse the master list only once ... ; ) <code> public class Parent { public List < Child > ChildrenA = new List < Child > ( ) ; public List < Child > ChildrenB = new List < Child > ( ) ; } public class Child { public Child ( string name ) { Name=name ; } public string Name { get ; set ; } } var parents = new List < Parent > ( ) ; parents.Add ( new Parent ( ) ) ; parents [ 0 ] .ChildrenA.Add ( new Child ( `` A1 '' ) ) ; parents [ 0 ] .ChildrenA.Add ( new Child ( `` A2 '' ) ) ; parents [ 0 ] .ChildrenB.Add ( new Child ( `` B1 '' ) ) ; parents.Add ( new Parent ( ) ) ; parents [ 1 ] .ChildrenA.Add ( new Child ( `` A3 '' ) ) ; var result = ... // would be an anonymous typeAssert.That ( result.ChildrenA.Count , Is.EqualTo ( 3 ) ) ; Assert.That ( result.ChildrenA [ 0 ] .Name , Is.EqualTo ( `` A1 '' ) ) ; Assert.That ( result.ChildrenA [ 1 ] .Name , Is.EqualTo ( `` A2 '' ) ) ; Assert.That ( result.ChildrenA [ 2 ] .Name , Is.EqualTo ( `` A3 '' ) ) ; Assert.That ( result.ChildrenB.Count , Is.EqualTo ( 1 ) ) ; Assert.That ( result.ChildrenB [ 0 ] .Name , Is.EqualTo ( `` B1 '' ) ) ; | Using Linq and C # , trying to get two lists from a list of master items grouped by two inner lists |
C_sharp : I 'm try to parse this xml , but c # keeps throwing an exception saying it has invalid characters . I ca n't copy the text from the messagebox directly , so I 've screened it . http : //img29.imageshack.us/img29/694/xmler.jpgEdit : copied textHere 's the code to get the string <code> < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < user > < id > 9572 < /id > < screen_name > fgfdgfdgfdgffg44 < /screen_name > < /user > string strRetPage = System.Text.Encoding.GetEncoding ( 1251 ) .GetString ( RecvBytes , 0 , bytes ) ; while ( bytes > 0 ) { bytes = socket.Receive ( RecvBytes , RecvBytes.Length , 0 ) ; strRetPage = strRetPage + System.Text.Encoding.GetEncoding ( 1251 ) .GetString ( RecvBytes , 0 , bytes ) ; } start = strRetPage.IndexOf ( `` < ? xml '' ) ; string servReply = strRetPage.Substring ( start ) ; servReply = servReply.Trim ( ) ; servReply = servReply.Replace ( `` \r '' , `` '' ) ; servReply = servReply.Replace ( `` \n '' , `` '' ) ; servReply = servReply.Replace ( `` \t '' , `` '' ) ; XmlTextReader txtRdr = new XmlTextReader ( servReply ) ; | XmlTextReader issue |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.