text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : Here is the relevant code . Mind you , I did this in Notepad++ instead of copying in my code for my project at work . If I misspelled a class name in it , assume it is not misspelled in my code . No compile errors.Model : Controller : View ( Razor ) : This will `` work '' , but wo n't set values on any of the rendered option elements in the select : I know of the SelectList constructor that takes in the property names to use to render the value and text in the option elements , but it is of no use ( that I can see ) when using a collection of a primitive type like an int.Question : I know I can change my view model 's IList < int > to IList < SelectListItem > , and create SelectListItem objects to represent each int , but that seems a bit ridiculous ( as I think the constructor should n't leave the values blank , and should default to using the text ) . Am I missing something obvious here , or am I going to have to move away from using primitive types here ? <code> public class MyViewModel { public int SelectedSomething { get ; set ; } public IList < int > Somethings { get ; set ; } } public class MyController { public ActionResult Index ( ) { var viewModel = new MyViewModel ( ) ; viewModel.Somethings = Enumerable.Range ( 1 , 12 ) .ToList ( ) ; return View ( viewModel ) ; } } @ Html.DropDownListFor ( x = > x.SelectedSomething , new SelectList ( Model.Somethings , Model.SelectedSomething ) , `` Select an Option '' ) < select > < option value= '' '' > Select an Option < /option > < option > 1 < /option > < option > 2 < /option > < option > 3 < /option > < option > 4 < /option > < option > 5 < /option > < option > 6 < /option > < option > 7 < /option > < option > 8 < /option > < option > 9 < /option > < option > 10 < /option > < option > 11 < /option > < option > 12 < /option > < /select > | Correct way to use DropDownListFor with a list of primitive types ? |
C_sharp : I have many entities that have the IsActive property . For internal reasons , I need all those fields to be nullable . On the other hand , for every entity I may have to do a double test in tens of places in the application : ( null are treated as true ) If I create a method likeIt still wo n't hide the property ( at least from inside the class ) so it 's error prone.I tried to find a way to override , but of course I ca n't change the return type to plain bool.What would you do to avoid redundancy in this case ? <code> if ( language.IsActive == null || language.IsActive.value ) class Language { public bool IsActiveLanguage ( ) { return language.IsActive == null || language.IsActive.value ; } } | Avoiding to repeatedly test for nulls on the same properties |
C_sharp : I use dotMemory to profile my application and I noticed the below behavior : inside my code there are some points where I perform garbage collection manually by using Inside dotMemory I see that memory is actually freed in these points but if after that I click 'Force GC ' even more garabage is collected . What is the way they are doing this and why that memory was not collected by my code and is it possilbe to achieve the same level of collection ? I 'm attaching the screenshot where you can see that the gen 2 is almost halved by dotMemoryI 've also tried to perform multiple collections i.e.and even though it seems to reclaim a bit more memory it never comes close to how dotMemory performs <code> GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; | What exactly happens when I ask dotMemory to force garbage collection |
C_sharp : Is it possible for a constructor to be pre-empted in C # ? For example , consider the code : Somewhere else in the code two threads have access to a variable of type A , the first thread calls the constructor which is pre-empted at point # 1 . Then the second thread tests for ready and finds it to still be true therefore it does something bad.Is this scenario possible ? More specifically : Can a constructor be pre-empted ? If so , does this mean that there should be synchronization code such as lock in the constructor ? Is the object being constructed only assigned to the shared variable after the constructor exits , thereby avoiding the question altogether ? <code> public class A { public bool ready = true ; public A ( ) { ready = false ; // Point # 1 // Other initialization stuff ready = true ; // Point # 2 } } | Can a constructor be pre-empted ? |
C_sharp : I wanted to learn more about C # language and a lot of people have recommended digging into the C # specification , so I went and downloaded a copy of it from MSDN and started reading and going through the examples.C # Specification Introducton - Section 1.6.7.5 Operators `` The List class declares two operators , operator == and operator ! = , and thus gives new meaning to expressions that apply those operators to List instances . Specifically , the operators define equality of two List instances as comparing each of the contained objects using their Equals methods . The following example uses the == operator to compare two List instances . `` I do n't understand why the output would be True and False as opposed to both being False.I pop this into Visual Studio and sure enough I got both the Console.WriteLine ( ) as 'False ' as opposed to both being 'True ' and 'False ' as specified in the comments . It also states that the List-of-T declares a single event member called Changed , I could not for the life of me find it , I went into the decompiler and had a look as well.Maybe I 'm completely mis-reading it or I 've got the wrong C # specification . <code> using System ; class Test { static void Main ( ) { List < int > a = new List < int > ( ) ; a.Add ( 1 ) ; a.Add ( 2 ) ; List < int > b = new List < int > ( ) ; b.Add ( 1 ) ; b.Add ( 2 ) ; Console.WriteLine ( a == b ) ; // Outputs `` True '' b.Add ( 3 ) ; Console.WriteLine ( a == b ) ; // Outputs `` False '' } } | C # Specification - Section 1.6.7.5 can someone please explain this example ? |
C_sharp : What is the difference between the following two snippets of code : andI have started using using a lot more but I am curious as to what the actually benefits are as compared to scoping objects.Edit : Useful tidbits I took from this : Jon Skeet : Note that this does not force garbage collection in any way , shape or form . Garbage collection and prompt resource clean-up are somewhat orthogonal.Will Eddins comment : Unless your class implements the IDisposable interface , and has a Dispose ( ) function , you do n't use using . <code> using ( Object o = new Object ( ) ) { // Do something } { Object o = new Object ( ) ; // Do something } | Difference between 'using ' and scoping ? |
C_sharp : I have function in c++ something like this : And I can use functions in two ways : When I write code in C # I used ref keyword : but compiler said : A ref or out parameter can not have a default value.How can I solve this problem ? <code> // C++bool Foo ( int* retVal = NULL ) { // ... if ( retVal ! = NULL ) *retVal = 5 ; // ... return true ; } int ret ; Foo ( & ret ) ; Foo ( ) ; // C # bool Foo ( ref int retVal = null ) { // ... if ( retVal ! = null ) { retVal = 5 ; } // ... return true ; } | How to convert optional pointer argument from C++ code to C # |
C_sharp : Given the code : Inputting the value 0x300 yields the result 0x69D04700 . This is only the lower 32 bits of the result.Given the result 0x69D04700 and the factor 0x123456D , is it possible to retrieve all numbers such that ( value * 0x123456D ) & 0xFFFFFFFF = 0x69D04700 in a fast way ? Edit : The code I show is pseudocode - I ca n't widen the return type . <code> uint Function ( uint value ) { return value * 0x123456D ; } | Reversing multiplication operation that has overflowed |
C_sharp : I have the following LINQ query : Which translates to the following when run : Now I 'm pretty sure that the reason there is a sub-select is because I have the base LINQ query surrounded by ( ) and then perform .Distinct ( ) but I do n't know enough about LINQ to be sure of this . If that 's indeed the case is there a way to restructure/code my query so that a sub-select does n't occur ? I know that it probably seems that I 'm just nit-picking here but I 'm just curious . <code> var queryGroups = ( from p in db.cl_contact_event select new Groups { inputFileName = p.input_file_name } ) .Distinct ( ) ; SELECT [ Distinct1 ] . [ C1 ] AS [ C1 ] , [ Distinct1 ] . [ input_file_name ] AS [ input_file_name ] FROM ( SELECT DISTINCT [ Extent1 ] . [ input_file_name ] AS [ input_file_name ] , 1 AS [ C1 ] FROM [ mel ] . [ cl_contact_event ] AS [ Extent1 ] ) AS [ Distinct1 ] | Why does LINQ-to-Entities put this query in a sub-select ? |
C_sharp : Can anyone explain , why does the following code produce the error ? ( Compiling in Microsoft Visual Studio 2008 ) the error is The call is ambiguous between the following methods or properties : 'ConsoleApplication1.Program.M1 < ConsoleApplication1.Base1 > ( ConsoleApplication1.Base1 , ConsoleApplication1.I1 ) ' and 'ConsoleApplication1.Program.M1 < ConsoleApplication1.Base1 > ( ConsoleApplication1.Base1 , ConsoleApplication1.I2 ) ' I thought the compiler could distinguish between two methods using the `` where '' clauses <code> class Base1 { } ; class Base2 { } interface I1 { } interface I2 { } class C : I1 , I2 { } static class Program { static T M1 < T > ( this T t , I1 x ) where T : Base1 { return t ; } static T M1 < T > ( this T t , I2 x ) where T : Base2 { return t ; } static void Main ( string [ ] args ) { Base1 b1 = new Base1 ( ) ; C c = new C ( ) ; b1.M1 ( c ) ; } } | Why is this call ambiguous ? |
C_sharp : I 'm confused why this compiles : MyDelegate should be a pointer to a method that takes two int parameters and returns another int , right ? Why am I allowed to assign a method that takes no parameters ? Interestingly , these does n't compile ( it complains about the signature mismatches , as I 'd expect ) Thanks for any help ! Ryan <code> private delegate int MyDelegate ( int p1 , int p2 ) ; private void testDelegate ( ) { MyDelegate imp = delegate { return 1 ; } ; } private void testDelegate ( ) { // Missing param MyDelegate imp = delegate ( int p1 ) { return 1 ; } ; // Wrong return type MyDelegate imp2 = delegate ( int p1 , int p2 ) { return `` String '' ; } ; } | Why does a delegate with no parameters compile ? |
C_sharp : ( Note : I already asked this question , but the answer was specific to Java , and so I am asking the same question for C # and the .NET framework . It is NOT a duplicate . ) I have been using this pattern for a while , but I only recently came to think that it might not be OK to do this . Basically , I use some variant of this pattern : *The user is responsible for making sure Start is only called once . Update is called wherever and whenever.I 've always assumed this is threadsafe in C # /the .NET framework , because even though nothing is strictly synchronized , I only ever set completed to true . Once it has been observed to be true , it will not reset to false . It is initialized to false in the constructor , which is by definition thread safe ( unless you do something stupid in it ) . So , is it thread safe to use unresettable flags in this way ? ( And if so , does it even provide any performance benefits ? ) Thanks <code> public class SampleAsync { public SampleAsync ( ) { } private bool completed ; public void Start ( ) { var worker = new BackgroundWorker ( ) ; worker.DoWork += ( sender , e ) = > { // ... do something on a different thread completed = true ; } ; worker.RunWorkerAsync ( ) ; } public void Update ( ) { if ( ! completed ) return ; // ... do something else } } | Are unresettable `` flags '' threadsafe in C # /.NET ? |
C_sharp : I have the following recursive code and i am getting a stackoverflow exception . I ca n't figure out the root cause because once i get the exception , i dont get the full call stack in Visual studio.The idea is that there are org teams that roll up into larger `` Main '' teams.Does anyone see a flaw on this code below that could be the culprit ? <code> private Unit GetUnit ( Unit organisationalUnit ) { if ( organisationalUnit.IsMainUnit ) { return organisationalUnit ; } if ( organisationalUnit.Parent == null ) return null ; return GetUnit ( organisationalUnit.Parent ) ; } | how can i get catch the root of a stackoverflow exception on recursive code |
C_sharp : If I have a task running on a worker thread and when it finds something wrong , is it possible to pause and wait for the user to intervene before continuing ? For example , suppose I have something like this : Is it possible to substitute WaitForUserInput ( ) with something that runs on the UI thread , waits for the user 's intervention , and then acts accordingly ? If so , how ? I 'm not looking for complete code or anything ; if someone could point me in the right direction , I would be grateful . <code> async void btnStartTask_Click ( object sender , EventArgs e ) { await Task.Run ( ( ) = > LongRunningTask ( ) ) ; } // CPU-boundbool LongRunningTask ( ) { // Establish some connection here . // Do some work here . List < Foo > incorrectValues = GetIncorrectValuesFromAbove ( ) ; if ( incorrectValues.Count > 0 ) { // Here , I want to present the `` incorrect values '' to the user ( on the UI thread ) // and let them select whether to modify a value , ignore it , or abort . var confirmedValues = WaitForUserInput ( incorrectValues ) ; } // Continue processing . } | How to pause task running on a worker thread and wait for user input ? |
C_sharp : Possible Duplicate : C # Captured Variable In Loop I am pretty new to multi-threading programming.When I ran the code below and only the last child got executed.Can some one tell me what happened ? Thank you very much.Output <code> private void Process ( ) { Dictionary < int , int > dataDict = new Dictionary < int , int > ( ) ; dataDict.Add ( 1 , 2000 ) ; dataDict.Add ( 2 , 1000 ) ; dataDict.Add ( 3 , 4000 ) ; dataDict.Add ( 4 , 3000 ) ; foreach ( KeyValuePair < int , int > kvp in dataDict ) { Console.WriteLine ( `` Ready for [ `` + kvp.Key.ToString ( ) + `` ] '' ) ; Task.Factory.StartNew ( ( ) = > DoSomething ( kvp.Value , kvp.Key ) ) ; } private static void DoSomething ( int waitTime , int childID ) { { Console.WriteLine ( `` Start task [ `` + childID.ToString ( ) + `` ] '' ) ; Thread.Sleep ( waitTime ) ; Console.WriteLine ( `` End task [ `` + childID.ToString ( ) + `` ] '' ) ; } } Ready for [ 1 ] Ready for [ 2 ] Ready for [ 3 ] Ready for [ 4 ] Start task [ 4 ] Start task [ 4 ] Start task [ 4 ] Start task [ 4 ] End task [ 4 ] End task [ 4 ] End task [ 4 ] End task [ 4 ] | Confused about multi-threading in a loop for C # |
C_sharp : The loop : It just does a repeated find-and-replace on a bunch of keys . The dictionary is just < string , string > .I can see 2 improvements to this . Every time we do pattern.Replace it searches from the beginning of the string again . It would be better if when it hit the first { , it would just look through the list of keys for a match ( perhaps using a binary search ) , and then replace the appropriate one.The pattern ! = before bit is how I check if anything was replaced during that iteration . If the pattern.Replace function returned how many or if any replaces actually occured , I would n't need this.However ... I do n't really want to write a big nasty thing class to do all that . This must be a fairly common scenario ? Are there any existng solutions ? Full ClassThanks to Elian Ebbing and ChrisWue.Example UsagePurposeFor building complex regular expressions that may extend eachother . Namely , I 'm trying to implement the css spec . <code> var pattern = _dict [ key ] ; string before ; do { before = pattern ; foreach ( var pair in _dict ) if ( key ! = pair.Key ) pattern = pattern.Replace ( string.Concat ( `` { `` , pair.Key , `` } '' ) , string.Concat ( `` ( `` , pair.Value , `` ) '' ) ) ; } while ( pattern ! = before ) ; return pattern ; class FlexDict : IEnumerable < KeyValuePair < string , string > > { private Dictionary < string , string > _dict = new Dictionary < string , string > ( ) ; private static readonly Regex _re = new Regex ( @ '' { ( [ _a-z ] [ _a-z0-9- ] * ) } '' , RegexOptions.Compiled | RegexOptions.IgnoreCase ) ; public void Add ( string key , string pattern ) { _dict [ key ] = pattern ; } public string Expand ( string pattern ) { pattern = _re.Replace ( pattern , match = > { string key = match.Groups [ 1 ] .Value ; if ( _dict.ContainsKey ( key ) ) return `` ( `` + Expand ( _dict [ key ] ) + `` ) '' ; return match.Value ; } ) ; return pattern ; } public string this [ string key ] { get { return Expand ( _dict [ key ] ) ; } } public IEnumerator < KeyValuePair < string , string > > GetEnumerator ( ) { foreach ( var p in _dict ) yield return new KeyValuePair < string , string > ( p.Key , this [ p.Key ] ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return GetEnumerator ( ) ; } } class Program { static void Main ( string [ ] args ) { var flex = new FlexDict { { `` h '' , @ '' [ 0-9a-f ] '' } , { `` nonascii '' , @ '' [ \200-\377 ] '' } , { `` unicode '' , @ '' \\ { h } { 1,6 } ( \r\n| [ \t\r\n\f ] ) ? `` } , { `` escape '' , @ '' { unicode } |\\ [ ^\r\n\f0-9a-f ] '' } , { `` nmstart '' , @ '' [ _a-z ] | { nonascii } | { escape } '' } , { `` nmchar '' , @ '' [ _a-z0-9- ] | { nonascii } | { escape } '' } , { `` string1 '' , @ '' '' '' ( [ ^\n\r\f\\ '' '' ] |\\ { nl } | { escape } ) * '' '' '' } , { `` string2 '' , @ '' ' ( [ ^\n\r\f\\ ' ] |\\ { nl } | { escape } ) * ' '' } , { `` badstring1 '' , @ '' '' '' ( [ ^\n\r\f\\ '' '' ] |\\ { nl } | { escape } ) *\\ ? `` } , { `` badstring2 '' , @ '' ' ( [ ^\n\r\f\\ ' ] |\\ { nl } | { escape } ) *\\ ? `` } , { `` badcomment1 '' , @ '' /\* [ ^* ] *\*+ ( [ ^/* ] [ ^* ] *\*+ ) * '' } , { `` badcomment2 '' , @ '' /\* [ ^* ] * ( \*+ [ ^/* ] [ ^* ] * ) * '' } , { `` baduri1 '' , @ '' url\ ( { w } ( [ ! # $ % & *-\ [ \ ] -~ ] | { nonascii } | { escape } ) * { w } '' } , { `` baduri2 '' , @ '' url\ ( { w } { string } { w } '' } , { `` baduri3 '' , @ '' url\ ( { w } { badstring } '' } , { `` comment '' , @ '' /\* [ ^* ] *\*+ ( [ ^/* ] [ ^* ] *\*+ ) */ '' } , { `` ident '' , @ '' - ? { nmstart } { nmchar } * '' } , { `` name '' , @ '' { nmchar } + '' } , { `` num '' , @ '' [ 0-9 ] +| [ 0-9 ] *\ . [ 0-9 ] + '' } , { `` string '' , @ '' { string1 } | { string2 } '' } , { `` badstring '' , @ '' { badstring1 } | { badstring2 } '' } , { `` badcomment '' , @ '' { badcomment1 } | { badcomment2 } '' } , { `` baduri '' , @ '' { baduri1 } | { baduri2 } | { baduri3 } '' } , { `` url '' , @ '' ( [ ! # $ % & *-~ ] | { nonascii } | { escape } ) * '' } , { `` s '' , @ '' [ \t\r\n\f ] + '' } , { `` w '' , @ '' { s } ? `` } , { `` nl '' , @ '' \n|\r\n|\r|\f '' } , { `` A '' , @ '' a|\\0 { 0,4 } ( 41|61 ) ( \r\n| [ \t\r\n\f ] ) ? `` } , { `` C '' , @ '' c|\\0 { 0,4 } ( 43|63 ) ( \r\n| [ \t\r\n\f ] ) ? `` } , { `` D '' , @ '' d|\\0 { 0,4 } ( 44|64 ) ( \r\n| [ \t\r\n\f ] ) ? `` } , { `` E '' , @ '' e|\\0 { 0,4 } ( 45|65 ) ( \r\n| [ \t\r\n\f ] ) ? `` } , { `` G '' , @ '' g|\\0 { 0,4 } ( 47|67 ) ( \r\n| [ \t\r\n\f ] ) ? |\\g '' } , { `` H '' , @ '' h|\\0 { 0,4 } ( 48|68 ) ( \r\n| [ \t\r\n\f ] ) ? |\\h '' } , { `` I '' , @ '' i|\\0 { 0,4 } ( 49|69 ) ( \r\n| [ \t\r\n\f ] ) ? |\\i '' } , { `` K '' , @ '' k|\\0 { 0,4 } ( 4b|6b ) ( \r\n| [ \t\r\n\f ] ) ? |\\k '' } , { `` L '' , @ '' l|\\0 { 0,4 } ( 4c|6c ) ( \r\n| [ \t\r\n\f ] ) ? |\\l '' } , { `` M '' , @ '' m|\\0 { 0,4 } ( 4d|6d ) ( \r\n| [ \t\r\n\f ] ) ? |\\m '' } , { `` N '' , @ '' n|\\0 { 0,4 } ( 4e|6e ) ( \r\n| [ \t\r\n\f ] ) ? |\\n '' } , { `` O '' , @ '' o|\\0 { 0,4 } ( 4f|6f ) ( \r\n| [ \t\r\n\f ] ) ? |\\o '' } , { `` P '' , @ '' p|\\0 { 0,4 } ( 50|70 ) ( \r\n| [ \t\r\n\f ] ) ? |\\p '' } , { `` R '' , @ '' r|\\0 { 0,4 } ( 52|72 ) ( \r\n| [ \t\r\n\f ] ) ? |\\r '' } , { `` S '' , @ '' s|\\0 { 0,4 } ( 53|73 ) ( \r\n| [ \t\r\n\f ] ) ? |\\s '' } , { `` T '' , @ '' t|\\0 { 0,4 } ( 54|74 ) ( \r\n| [ \t\r\n\f ] ) ? |\\t '' } , { `` U '' , @ '' u|\\0 { 0,4 } ( 55|75 ) ( \r\n| [ \t\r\n\f ] ) ? |\\u '' } , { `` X '' , @ '' x|\\0 { 0,4 } ( 58|78 ) ( \r\n| [ \t\r\n\f ] ) ? |\\x '' } , { `` Z '' , @ '' z|\\0 { 0,4 } ( 5a|7a ) ( \r\n| [ \t\r\n\f ] ) ? |\\z '' } , { `` Z '' , @ '' z|\\0 { 0,4 } ( 5a|7a ) ( \r\n| [ \t\r\n\f ] ) ? |\\z '' } , { `` CDO '' , @ '' < ! -- '' } , { `` CDC '' , @ '' -- > '' } , { `` INCLUDES '' , @ '' ~= '' } , { `` DASHMATCH '' , @ '' \|= '' } , { `` STRING '' , @ '' { string } '' } , { `` BAD_STRING '' , @ '' { badstring } '' } , { `` IDENT '' , @ '' { ident } '' } , { `` HASH '' , @ '' # { name } '' } , { `` IMPORT_SYM '' , @ '' @ { I } { M } { P } { O } { R } { T } '' } , { `` PAGE_SYM '' , @ '' @ { P } { A } { G } { E } '' } , { `` MEDIA_SYM '' , @ '' @ { M } { E } { D } { I } { A } '' } , { `` CHARSET_SYM '' , @ '' @ charset\b '' } , { `` IMPORTANT_SYM '' , @ '' ! ( { w } | { comment } ) * { I } { M } { P } { O } { R } { T } { A } { N } { T } '' } , { `` EMS '' , @ '' { num } { E } { M } '' } , { `` EXS '' , @ '' { num } { E } { X } '' } , { `` LENGTH '' , @ '' { num } ( { P } { X } | { C } { M } | { M } { M } | { I } { N } | { P } { T } | { P } { C } ) '' } , { `` ANGLE '' , @ '' { num } ( { D } { E } { G } | { R } { A } { D } | { G } { R } { A } { D } ) '' } , { `` TIME '' , @ '' { num } ( { M } { S } | { S } ) '' } , { `` PERCENTAGE '' , @ '' { num } % '' } , { `` NUMBER '' , @ '' { num } '' } , { `` URI '' , @ '' { U } { R } { L } \ ( { w } { string } { w } \ ) | { U } { R } { L } \ ( { w } { url } { w } \ ) '' } , { `` BAD_URI '' , @ '' { baduri } '' } , { `` FUNCTION '' , @ '' { ident } \ ( `` } , } ; var testStrings = new [ ] { @ '' '' '' str '' '' '' , @ '' 'str ' '' , `` 5 '' , `` 5 . `` , `` 5.0 '' , `` a '' , `` alpha '' , `` url ( hello ) '' , `` url ( \ '' hello\ '' ) '' , `` url ( \ '' blah ) '' , @ '' \g '' , @ '' /*comment*/ '' , @ '' /**/ '' , @ '' < ! -- '' , @ '' -- > '' , @ '' ~= '' , `` |= '' , @ '' # hash '' , `` @ import '' , `` @ page '' , `` @ media '' , `` @ charset '' , `` ! /*iehack*/important '' } ; foreach ( var pair in flex ) { Console.WriteLine ( `` { 0 } \n\t { 1 } \n '' , pair.Key , pair.Value ) ; } var sw = Stopwatch.StartNew ( ) ; foreach ( var str in testStrings ) { Console.WriteLine ( `` { 0 } matches : `` , str ) ; foreach ( var pair in flex ) { if ( Regex.IsMatch ( str , `` ^ ( `` + pair.Value + `` ) $ '' , RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture ) ) Console.WriteLine ( `` { 0 } '' , pair.Key ) ; } } Console.WriteLine ( `` \nRan in { 0 } ms '' , sw.ElapsedMilliseconds ) ; Console.ReadLine ( ) ; } } | How can I speed this loop up ? Is there a class for replacing multiple terms at at time ? |
C_sharp : To follow my previous post here = > Binding SelectedItem of ComboBox in DataGrid with different typeI have now a datagrid containing 2 columns , one with a text , the other with a combobox ( in a datatemplate , written thru the C # code , not the Xaml ) . After having done some choice on the combobox , I now would like to parse the result but the value of the cell containing my combobox stay empty : The result is that I cant get the values of my ( previously generated ) combobox.I suppose one binding must missed somewhere ... This is the combobox creation code : Any idea/advice ? <code> foreach ( DataRowView row in Datagrid1.Items ) { var firstColumNresult = row.Row.ItemArray [ 0 ] ; // Return correctly a stringvar myrow = row.Row.ItemArray [ 1 ] ; // always empty ... } DataTable tableForDG = new DataTable ( ) ; tableForDG.Columns.Add ( new DataColumn { ColumnName = `` Name '' , Caption = `` Name '' } ) ; tableForDG.Columns.Add ( new DataColumn { ColumnName = `` Attachment '' , Caption = `` Attachment '' } ) ; // this column will be replacedtableForDG.Columns.Add ( new DataColumn { ColumnName = `` AttachmentValue '' , Caption = `` AttachmentValue '' } ) ; tableForDG.Columns.Add ( new DataColumn { ColumnName = `` DisplayCombo '' , Caption = `` DisplayCombo '' , DataType=bool } ) ; // Populate dataviewDataView myDataview = new DataView ( tableForDG ) ; foreach ( var value in listResults ) // a list of string { DataRowView drv = myDataview.AddNew ( ) ; drv [ `` Name '' ] = value.Name ; drv [ `` Attachment '' ] = value.Name ; // this column will be replaced ... drv [ `` DisplayCombo '' ] = true ; // but it can be false on my code ... } var DG = myDataview ; // Datagrid1.ItemsSource = DG ; Datagrid1.AutoGenerateColumns = true ; Datagrid1.Items.Refresh ( ) ; DataGridTemplateColumn dgTemplateColumn = new DataGridTemplateColumn ( ) ; dgTemplateColumn.Header = `` Attachment '' ; var newCombobox = new FrameworkElementFactory ( typeof ( ComboBox ) ) ; newCombobox.SetValue ( ComboBox.NameProperty , `` myCBB '' ) ; Binding enableBinding = new Binding ( ) ; newCombobox.SetValue ( ComboBox.IsEnabledProperty , new Binding ( `` DisplayCombo '' ) ) ; newCombobox.SetValue ( ComboBox.SelectedValueProperty , new Binding ( `` AttachmentValue '' ) ) ; List < string > listUnitAlreadyAttached = new List < string > ( ) ; // fill the list ... enableBinding.Source = listUnitAlreadyAttached ; newCombobox.SetBinding ( ComboBox.ItemsSourceProperty , enableBinding ) ; var dataTplT = new DataTemplate ( ) ; dataTplT.VisualTree = newCombobox ; dgTemplateColumn.CellTemplate = dataTplT ; Datagrid1.Columns [ 1 ] = dgTemplateColumn ; | How to get value of a programmatically written combobox in a datagrid in wpf ? |
C_sharp : I am trying to understand one thing in this code : And Output is : And the thing that I do n't understand when you pass null to y , I believe it calls public static implicit operator Nullable < T > ( T value ) but the definition of this method initializes a new struct passing value which is assigned null however constructor method does n't check whether it is null or not so it can assign default ( T ) to value.How come we can even assign null to struct here and it works fine ? Can you guys what I am missing out here ? I do n't understand how it just bypassed null and returned default value.Nullable code inner definition : http : //codepaste.net/gtce6d <code> Nullable < Int32 > x = 5 ; Nullable < Int32 > y = null ; Console.WriteLine ( `` x : HasValue= { 0 } , Value= { 1 } '' , x.HasValue , x.Value ) ; Console.WriteLine ( `` y : HasValue= { 0 } , Value= { 1 } '' , y.HasValue , y.GetValueOrDefault ( ) ) ; x : HasValue=True , Value=5y : HasValue=False , Value=0 | How CLR can bypass throwing error when assigning a null value to the struct ? |
C_sharp : I use private and public methods all the time . However , I do not understand why they work.Creating a small Hello World Program : The IL created for the public method : The IL created for the private method : It 's the exact same.How does the JIT differentiate and verify that the private/public rules were followed ? <code> public class CallPublicHelloWorld { public void CallHelloWorld ( ) { publicHelloWorld ( ) ; privateHelloWorld ( ) ; } private void privateHelloWorld ( ) { Console.WriteLine ( `` Hello World '' ) ; } public void publicHelloWorld ( ) { Console.WriteLine ( `` Hello World '' ) ; } } IL_0000 : nopIL_0001 : ldstr `` Hello World '' IL_0006 : call void [ mscorlib ] System.Console : :WriteLine ( string ) IL_000b : nopIL_000c : ret IL_0000 : nopIL_0001 : ldstr `` Hello World '' IL_0006 : call void [ mscorlib ] System.Console : :WriteLine ( string ) IL_000b : nopIL_000c : ret | How does C # verify the C # Private Definition ? |
C_sharp : I 'm having a problem . I 'm making a utility to do procedural generated maps.I have a room pool and each rooms are disposed in a table of room . I have a method to connect all the room together which walk in the table and connect adjacent rooms . I have an enum which contains the type of rooms : In the connection method I check the neighborhood to see what kind of room it is : But when i check if the type of room is Start , it 's always true and the connection is added . I do n't know why this happens . where i set the TypeOfRoom : img3 <code> public enum RoomType { Default = 0 , Building , Boss , Item , Standard , Start , } if ( neighbourhood [ 2 , 1 ] ! = null ) { if ( firstLevel.isOn ) { if ( neighbourhood [ 2,1 ] .TypeOfRoom == RoomType.Start ) { roomGrid [ x , y ] .AddConnection ( neighbourhood [ 2 , 1 ] , Location.RIGHT ) } } else if ( neighbourhood [ 2,1 ] .TypeOfRoom ! = RoomType.Boss ) roomGrid [ x , y ] .AddConnection ( neighbourhood [ 2 , 1 ] , Location.RIGHT ) ; } | If statement always true with enum in comparison |
C_sharp : I have a C # app . In this app , I have some XML that looks like this : I 'm trying to convert this XML into a C # object . My class looks something like this : When I run var list = List.Deserialize ( xml ) ; I get a List object back . The name of the List is properly set . However , the Items property is null . Why are n't the Items getting deserialized ? How do I get the Items populated with the key/value pairs listed ? Thank you <code> string xml = @ '' < list name= '' '' Groceries '' '' > < add key= '' '' 1 '' '' value= '' '' Milk '' '' / > < add key= '' '' 2 '' '' value= '' '' Eggs '' '' / > < add key= '' '' 3 '' '' value= '' '' Bread '' '' / > < /list > '' ; public class List : ConfigurationElement , IXmlSerializable { [ ConfigurationProperty ( `` name '' , IsRequired = true , IsKey = true , DefaultValue = `` '' ) ] public string Name { get { return ( string ) ( this [ `` name '' ] ) ; } set { this [ `` name '' ] = value ; } } [ ConfigurationProperty ( `` '' , IsRequired = false , IsKey = false , IsDefaultCollection=true ) ] public KeyValueConfigurationCollection Items { get { var items = base [ `` items '' ] as KeyValueConfigurationCollection ; return items ; } set { if ( base.Properties.Contains ( `` items '' ) ) { base [ `` items '' ] = value ; } else { var configProperty = new ConfigurationProperty ( `` items '' , typeof ( KeyValueConfigurationCollection ) , value ) ; base.Properties.Add ( configProperty ) ; } } } public XmlSchema GetSchema ( ) { return this.GetSchema ( ) ; } public void ReadXml ( XmlReader reader ) { this.DeserializeElement ( reader , false ) ; } public void WriteXml ( XmlWriter writer ) { this.SerializeElement ( writer , false ) ; } public static List Deserialize ( string xml ) { List list= null ; var serializer = new XmlSerializer ( typeof ( List ) ) ; using ( var reader = new StringReader ( xml ) ) { list = ( List ) ( serializer.Deserialize ( reader ) ) ; } return list ; } } | C # - Xml Deserialization of KeyValueConfigurationCollection |
C_sharp : I have been trying to read data from the Twitter stream API using C # , and since sometimes the API will return no data , and I am looking for a near-realtime response , I have been hesitant to use a buffer length of more than 1 byte on the reader in case the stream does n't return any more data for the next day or two.I have been using the following line : Now that I plan to scale the application up , I think a size of 1 will result in a lot of CPU usage , and want to increase that number , but I still do n't want the stream to just block . Is it possible to get the stream to return if no more bytes are read in the next 5 seconds or something similar ? <code> input.BeginRead ( buffer , 0 , buffer.Length , InputReadComplete , null ) ; //buffer = new byte [ 1 ] | Consuming a HTTP stream without reading one byte at a time |
C_sharp : Is there a way to mark a type ( or even better , an interface ) so that no instances of it can be stored in a field ( in a similar way to TypedReference and ArgIterator ) ? In the same way , is there a way to prevent instances from being passed through anonymous methods and -- In general -- To mimic the behavior of the two types above ? Can this be done through ILDasm or more generally through IL editing ? Since UnconstrainedMelody achieves normally unobtainable results through binary editing of a compiled assembly , maybe there 's a way to `` mark '' certain types ( or even better , abstract ones or marker interfaces ) through the same approach.I doubt it ’ s hardcoded in the compiler because the documentation for the error CS0610 states : There are some types that can not be used as fields or properties . These types include ... Which in my opinion hints that the set of types like those can be extended -- But I could be wrong.I 've searched a bit on SO and while I understand that throwing a compiler error programmatically ca n't be done , I could find no source stating that certain `` special '' types ' behaviors could n't be replicated.Even if the question is mostly academic , there could be some usages for an answer . For example , it could be useful sometimes to be sure that a certain object 's lifetime is constrained to the method block which creates it.EDIT : RuntimeArgumentHandle is one more ( unmentioned ) non-storable type.EDIT 2 : If it can be of any use , it seems that the CLR treats those types in a different way as well , if not only the compiler ( still assuming that the types are in no way different from others ) . The following program , for example , will throw a TypeLoadException regarding TypedReference* . I 've adapted it to make it shorter but you can work around it all you want . Changing the pointer 's type to , say , void* will not throw the exception . <code> using System ; unsafe static class Program { static TypedReference* _tr ; static void Main ( string [ ] args ) { _tr = ( TypedReference* ) IntPtr.Zero ; } } | Make type 's instances non-storable |
C_sharp : [ Edit : It looks like the original question involved a double and not an integer . So I think this question stands if we change the integer to a double . ] I have rare issue with reading integer properties from a class used in multiple threads that sometimes returns a zero value . The values are not changed after initialization . This question addresses that . The consensus is that even though I 'm accessing an integer I need to synchronize the properties . ( Some of the original answers have been deleted ) . I have n't chosen an answer there because I have not resolved my issue yet.So I ’ ve done some research on this and I ’ m not sure which of .Net 4 ’ s locking mechanisms to use or if the locks should be outside the class itself.This is what I thought about using : But I ’ ve read that this is horribly slow . Another alternative is to lock the instance of ConfigData on the user side but that seems to be a lot of work . Another alternative I ’ ve seen is Monitor.Enter and Monitor.Exit but I think Lock is the same thing with less syntax . So what is a best practice for making a class 's properties thread safe ? <code> public class ConfigInfo { private readonly object TimerIntervalLocker = new object ( ) ; private int _TimerInterval ; public int TimerInterval { get { lock ( TimerIntervalLocker ) { return _TimerInterval ; } } } private int _Factor1 ; public int Factor1 { set { lock ( TimerIntervalLocker ) { _Factor1 = value ; _TimerInterval = _Factor1 * _Factor2 ; } } get { lock ( TimerIntervalLocker ) { return _Factor1 ; } } } private int _Factor2 ; public int Factor2 { set { lock ( TimerIntervalLocker ) { _Factor2 = value ; _TimerInterval = _Factor1 * _Factor2 ; } } get { lock ( TimerIntervalLocker ) { return _Factor2 ; } } } } | What is a best practice for making a class 's properties thread safe ? |
C_sharp : For example , consider this : The eventStream is a long lived source of events . A short lived client will use this method to subscribe for some period of time , and then unsubscribe by calling Dispose on the returned IDisposable.However , while the eventStream still exists and should be kept in memory , there has been 2 new IObservables created by this method - the one returned by the Where ( ) method that is presumably held in memory by the eventStream , and the one returned by the Cast < T > ( ) method that is presumably held in memory by the one returned by the Where ( ) method.How will these 'intermediate IObservables ' ( is there a better name for them ? ) get cleaned up ? Or will they now exist for the lifetime of the eventStream even though they no longer have subscriptions and no one else references them except for their source IObservable and therefor will never have subscriptions again ? If they are cleaned up by informing their parent they no longer have subscriptions , how do they know nothing else has taken a reference to them and may at some point later subscribe to them ? <code> public IDisposable Subscribe < T > ( IObserver < T > observer ) { return eventStream.Where ( e = > e is T ) .Cast < T > ( ) .Subscribe ( observer ) ; } | Do 'Intermediate IObservables ' without final subscribers get kept in memory for the lifetime of the root IObservable |
C_sharp : The above compiles , but ... Does not.Replacing it with : Will obviously compile though . Is this inconsistancy or am i being stupid , or am i just wrong : S . <code> private string [ ] GetRoles ( ) { string [ ] foo = { `` Test '' } ; return foo ; } private string [ ] GetRoles ( ) { return { `` Test '' } ; } return new string [ ] { `` Test '' } ; | Inconsistent syntax c # ? |
C_sharp : I work for myself , I am a self-employed coder and as a result I do n't have the luxury of code reviews or the ability to improve based upon peer programming . I am going to use this as an exercise to see if the StackOverflow community might help to review a simple method which i 've written ; This is a method that takes a numeric representation of a date and converts it to a DateTime DataType . I would like the method to be reviewed to acheive the fastest possible execution time because it 's being executed within a loop.Any comments on the method is appreciated as this will be an exercise for me . i look forward to some responses . <code> internal static DateTime CONVERT_To_DateTime ( int binDate ) { // 3/10/2008 = 1822556159 // 2/10/2008 = 1822523391 // 1/10/2008 = 1822490623 // 30/09/2008 = 1822392319 // 29/09/2008 = 1822359551 // September 30th 2008 // 1822392319 = 0x6c9f7fff // 0x6c = 108 = 2008 ( based on 1900 start date ) // 0x9 = 9 = September // 0xf7fff - take top 5 bits = 0x1e = 30 // October 1st 2008 // 1822490623 = 0x6ca0ffff // 0 x6c = 108 = 2008 // 0 xa = 10 = October // 0x0ffff - take top 5 bits = 0x01 = 1 // OR using Binary ( used by this function ) // a = 1822556159 ( 3/10/2008 ) // 1101100 1010 00011 111111111111111 // b = 1822523391 ( 2/10/2008 ) // 1101100 1010 00010 111111111111111 // c = 1822490623 ( 1/10/2008 ) // 1101100 1010 00001 111111111111111 // D = 1822392319 ( 30/09/2008 ) // 1101100 1001 11110 111111111111111 // Excess 111111 are probably used for time/seconds which // we do not care for at the current time var BaseYear = 1900 ; // Dump the long date to binary var strBinary = Convert.ToString ( binDate ) ; // Calculate the year var strBYear = strBinary.Substring ( 0 , 7 ) ; var iYear = Convert.ToInt32 ( strBYear , 2 ) + BaseYear ; // Calculate the month var strBMonth = strBinary.Substring ( 7 , 4 ) ; var iMonth = Convert.ToInt32 ( strBMonth , 2 ) ; // Calculate the day var strBDay = strBinary.Substring ( 11 , 5 ) ; var iDay = Convert.ToInt32 ( strBDay , 2 ) ; // ensure that month and day have two digits var strDay = iDay < 10 ? `` 0 '' + iDay : iDay.ToString ( ) ; var strMonth = iMonth < 10 ? `` 0 '' + iMonth : iMonth.ToString ( ) ; // Build the final date var convertedDate = iYear + strMonth + strDay ; return DateTime.ParseExact ( convertedDate , `` yyyyMMdd '' , null ) ; } | Refactor for Speed : Convert To a Date |
C_sharp : I have the following C # code which initializes a new dictionary with int keys and List < string > values : If I decompile an executable made from this snippet back to C # the corresponding part looks like this : Everything seems normal and is working properly here.But when I have the following code : which again seems like normal code and compiles successfully , but during runtime I get the following exception : System.Collections.Generic.KeyNotFoundException : 'The given key was not present in the dictionary . 'When I look into the decompiled code of the second example I can see that it is different from the first one : And of course this explains the exception.So now my questions are : Is this expected behavior and is it documented somewhere ? Why is the syntax above allowed but the following syntax is not ? Why is the following syntax not allowed then ? Similar but different questions : What happens under the hood when using array initialization syntax to initialize a Dictionary instance on C # ? How to make inline array initialization work like e.g . Dictionary initialization ? <code> var dictionary = new Dictionary < int , List < string > > { [ 1 ] = new List < string > { `` str1 '' , `` str2 '' , `` str3 '' } , [ 2 ] = new List < string > { `` str4 '' , `` str5 '' , `` str6 '' } } ; Dictionary < int , List < string > > expr_06 = new Dictionary < int , List < string > > ( ) ; expr_06 [ 1 ] = new List < string > { `` str1 '' , `` str2 '' , `` str3 '' } ; expr_06 [ 2 ] = new List < string > { `` str4 '' , `` str5 '' , `` str6 '' } ; var dictionary2 = new Dictionary < int , List < string > > { [ 1 ] = { `` str1 '' , `` str2 '' , `` str3 '' } , [ 2 ] = { `` str4 '' , `` str5 '' , `` str6 '' } } ; Dictionary < int , List < string > > expr_6E = new Dictionary < int , List < string > > ( ) ; expr_6E [ 1 ] .Add ( `` str1 '' ) ; expr_6E [ 1 ] .Add ( `` str2 '' ) ; expr_6E [ 1 ] .Add ( `` str3 '' ) ; expr_6E [ 2 ] .Add ( `` str4 '' ) ; expr_6E [ 2 ] .Add ( `` str5 '' ) ; expr_6E [ 2 ] .Add ( `` str6 '' ) ; List < string > list = { `` test '' } ; var dict = new Dictionary < int , string [ ] > { [ 1 ] = { `` test1 '' , `` test2 '' , `` test3 '' } , [ 2 ] = { `` test4 '' , `` test5 '' , `` test6 '' } } ; | Dictionary initializer has different behavior and raises run-time exception when used in combination of array initializer |
C_sharp : Suppose I initialize members of a class like this : Does the compiler generate a default constructor in this situation ? In general , I know that a constructor may initialize the value of class instance variables and may also perform some other initialization operations appropriate for the class . But in the above example , I have initialized the value of i and j outside of a constructor . In this situation , does the compiler still generate a default constructor ? If so , what does the default constructor do ? <code> class A { public int i=4 ; public double j=6.0 ; } | In C # , is a default constructor generated when class members are initialized ? |
C_sharp : I 'm writing a bunch of unit tests for my ASP.NET MVC app using Entity Framework ( against a SQL Server database ) .I 'm using Rowan Miller 's excellent Nuget packages `` EntityFramework.Testing '' and `` EntityFramework.Testing.Moq '' to allow me to unit test EF code ( without actually having a real SQL Server database around ) .This is my NUnit 3.5 test fixture ( in reality , it has a lot more tests - but it 's just to show how things are set up ) : As you can see , in the [ SetUp ] method , I 'm calling SetupTestData which is creating the Mock < MyModel > for mocking the entire DbContext , and it sets up a MockDbSet < Contact > to handle my contacts.Most tests works just fine against this setup - until I came across the SaveContact method here : As you can see , if I 'm trying to save a Contact that already exists , all I 'm doing is setting it 's State flag to Modified and letting EF handle all the rest.Works great at runtime - but here in the test , it causes the test code to want to connect to the database - which I do n't have at hand.So what do I need to do additionally to make it possible to unit-test this line of code using my EF Mocking infrastructure ? Can it be done at all ? <code> [ TestFixture ] public class ContactsUseCaseTests : MyUnitTestBase { private Mock < MyModel > _mockDbContext ; private MockDbSet < Contact > _mockDbSetContact ; private IContactsUseCase _usecase ; [ SetUp ] public void InitializeTest ( ) { SetupTestData ( ) ; _usecase = new ContactsUseCase ( _mockDbContext.Object ) ; } [ Test ] public void TestSaveEntryNotNewButNotFound ( ) { // Arrange Contact contact = new Contact { ContactId = 99 , FirstName = `` Leo '' , LastName = `` Miller '' } ; // Act _usecase.SaveContact ( contact , false ) ; // Assert _mockDbSetContact.Verify ( x = > x.Add ( It.IsAny < Contact > ( ) ) , Times.Once ) ; _mockDbContext.Verify ( x = > x.SaveChanges ( ) , Times.Once ) ; } private void SetupTestData ( ) { var contacts = new List < Contact > ( ) ; contacts.Add ( new Contact { ContactId = 12 , FirstName = `` Joe '' , LastName = `` Smith '' } ) ; contacts.Add ( new Contact { ContactId = 17 , FirstName = `` Daniel '' , LastName = `` Brown '' } ) ; contacts.Add ( new Contact { ContactId = 19 , FirstName = `` Frank '' , LastName = `` Singer '' } ) ; _mockDbSetContact = new MockDbSet < Contact > ( ) .SetupAddAndRemove ( ) .SetupSeedData ( contacts ) .SetupLinq ( ) ; _mockDbContext = new Mock < MyModel > ( ) ; _mockDbContext.Setup ( c = > c.ContactList ) .Returns ( _mockDbSetContactList.Object ) ; _mockDbContext.Setup ( c = > c.Contact ) .Returns ( _mockDbSetContact.Object ) ; } } public void SaveContact ( Contact contactToSave , bool isNew ) { if ( isNew ) { ModelContext.Contact.Add ( contactToSave ) ; } else { ModelContext.Entry ( contactToSave ) .State = EntityState.Modified ; } ModelContext.SaveChanges ( ) ; } ModelContext.Entry ( contactToSave ) .State = EntityState.Modified ; | Unit-testing EF 's state management code |
C_sharp : This is a constructor in one of my classes : The Code Contracts static checker flags an error : warning : CodeContracts : ensures is false : PrereleaseVersion ! = nullMaybe < T > is a collection containing zero or one elements.As far as I can see , the only way that can be null is if there 's an exception before it is assigned , which should make the Ensures requirements irrelevant . Am I going code blind ? Can you see the problem ... ? Update : Posting implementation of Maybe in response to comments . <code> public SemanticVersion ( string version ) { Contract.Requires < ArgumentException > ( ! string.IsNullOrEmpty ( version ) ) ; Contract.Ensures ( MajorVersion > = 0 ) ; Contract.Ensures ( MinorVersion > = 0 ) ; Contract.Ensures ( PatchVersion > = 0 ) ; Contract.Ensures ( PrereleaseVersion ! = null ) ; Contract.Ensures ( BuildVersion ! = null ) ; var match = SemanticVersionRegex.Match ( version ) ; if ( ! match.Success ) { var message = $ '' The version number ' { version } ' is not a valid semantic version number . `` ; throw new ArgumentException ( message , nameof ( version ) ) ; } MajorVersion = int.Parse ( match.Groups [ `` major '' ] .Value , CultureInfo.InvariantCulture ) ; MinorVersion = int.Parse ( match.Groups [ `` minor '' ] .Value , CultureInfo.InvariantCulture ) ; PatchVersion = int.Parse ( match.Groups [ `` patch '' ] .Value , CultureInfo.InvariantCulture ) ; PrereleaseVersion = match.Groups [ `` prerelease '' ] .Success ? new Maybe < string > ( match.Groups [ `` prerelease '' ] .Value ) : Maybe < string > .Empty ; BuildVersion = match.Groups [ `` build '' ] .Success ? new Maybe < string > ( match.Groups [ `` build '' ] .Value ) : Maybe < string > .Empty ; } using System.Collections ; using System.Collections.Generic ; using System.Diagnostics.Contracts ; using System.Linq ; namespace TA.CoreTypes { /// < summary > /// Represents an object that may or may not have a value ( strictly , a collection of zero or one elements ) . Use /// LINQ expression /// < c > maybe.Any ( ) < /c > to determine if there is a value . Use LINQ expression /// < c > maybe.Single ( ) < /c > to retrieve the value . /// < /summary > /// < typeparam name= '' T '' > The type of the item in the collection. < /typeparam > public class Maybe < T > : IEnumerable < T > { private static readonly Maybe < T > EmptyInstance = new Maybe < T > ( ) ; private readonly IEnumerable < T > values ; /// < summary > /// Initializes a new instance of the < see cref= '' Maybe { T } '' / > with no value . /// < /summary > private Maybe ( ) { values = new T [ 0 ] ; } /// < summary > /// Initializes a new instance of the < see cref= '' Maybe { T } '' / > with a value . /// < /summary > /// < param name= '' value '' > The value. < /param > public Maybe ( T value ) { Contract.Requires ( value ! = null ) ; values = new [ ] { value } ; } /// < summary > /// Gets an instance that does not contain a value . /// < /summary > /// < value > The empty instance. < /value > public static Maybe < T > Empty { get { Contract.Ensures ( Contract.Result < Maybe < T > > ( ) ! = null ) ; return EmptyInstance ; } } public IEnumerator < T > GetEnumerator ( ) { Contract.Ensures ( Contract.Result < IEnumerator < T > > ( ) ! = null ) ; return values.GetEnumerator ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { Contract.Ensures ( Contract.Result < IEnumerator > ( ) ! = null ) ; return GetEnumerator ( ) ; } [ ContractInvariantMethod ] private void ObjectInvariant ( ) { Contract.Invariant ( values ! = null ) ; } [ Pure ] public override string ToString ( ) { Contract.Ensures ( Contract.Result < string > ( ) ! = null ) ; if ( Equals ( Empty ) ) return `` { no value } '' ; return this.Single ( ) .ToString ( ) ; } } public static class MaybeExtensions { public static bool None < T > ( this Maybe < T > maybe ) { if ( maybe == null ) return true ; if ( maybe == Maybe < T > .Empty ) return true ; return ! maybe.Any ( ) ; } } } | Why does Code Contracts claim that `` Ensures is false '' for this code ? |
C_sharp : I 'm trying to convert this C # code to C++ : Pretty clear this calls for std : :function . Since this is a larger project I used a tool to do all the conversion and this is what it came up with : I assumed using std : :function < void ( ) > is a translation error , so I changed them to Action . So , my final version is this : But this does n't compile , with the understandable error that Action is already defined ( when reaching the second using line ) . However , there 's the possibility to have template functions with overloads ( same name , different template parameters ) , so I wonder why this does n't work for my alias templates . Is it simply not supported or do I miss something ? Also , maybe I did not fully understand co- and contravariance , but in my opinion they do not apply to this problem ( no type inheritance involved here ) , so I do n't see what the converter tool wants to tell me by these comments . <code> public delegate void Action < in T > ( T obj ) ; public delegate void Action < in T1 , in T2 > ( T1 arg1 , T2 arg2 ) ; public delegate void Action < in T1 , in T2 , in T3 > ( T1 arg1 , T2 arg2 , T3 arg3 ) ; # include < functional > template < typename T > //C # TO C++ CONVERTER TODO TASK : C++ does not allow specifying covariance or contravariance in a generic type list : //ORIGINAL LINE : public delegate void System : :Action < in T > ( T obj ) ; using std : :function < void ( ) > = std : :function < void ( T obj ) > ; template < typename T1 , typename T2 > //C # TO C++ CONVERTER TODO TASK : C++ does not allow specifying covariance or contravariance in a generic type list : //ORIGINAL LINE : public delegate void System : :Action < in T1 , in T2 > ( T1 arg1 , T2 arg2 ) ; using std : :function < void ( ) > = std : :function < void ( T1 arg1 , T2 arg2 ) > ; template < typename T1 , typename T2 , typename T3 > //C # TO C++ CONVERTER TODO TASK : C++ does not allow specifying covariance or contravariance in a generic type list : //ORIGINAL LINE : public delegate void System : :Action < in T1 , in T2 , in T3 > ( T1 arg1 , T2 arg2 , T3 arg3 ) ; using std : :function < void ( ) > = std : :function < void ( T1 arg1 , T2 arg2 , T3 arg3 ) > ; template < typename T > using Action = std : :function < void ( T obj ) > ; template < typename T1 , typename T2 > using Action = std : :function < void ( T1 arg1 , T2 arg2 ) > ; template < typename T1 , typename T2 , typename T3 > using Action = std : :function < void ( T1 arg1 , T2 arg2 , T3 arg3 ) > ; | C # to C++11 conversion : delegate templates |
C_sharp : I am trying to setup blazor server side but I keep getting this problem when trying to install itfollowing this tutorial from microsoft and I get this error in powershell window <code> PS D : \blazorTesting > dotnet new blazorserverside -o WebApplicationServerSideUsage : new [ options ] Options : -h , -- help Displays help for this command . -l , -- list Lists templates containing the specified name . If no name is specified , lists all templates . -n , -- name The name for the output being created . If no name is specified , the name of the current directory is used . -o , -- output Location to place the generated output . -i , -- install Installs a source or a template pack . -u , -- uninstall Uninstalls a source or a template pack . -- nuget-source Specifies a NuGet source to use during install . -- type Filters templates based on available types . Predefined values are `` project '' , `` item '' or `` other '' . -- dry-run Displays a summary of what would happen if the given command line were run if it would result in a template creation . -- force Forces content to be generated even if it would change existing files . -lang , -- language Filters templates based on language and specifies the language of the template to create.Unable to determine the desired template from the input template name : blazorserverside.The following templates partially match the input . Be more specific with the template name and/or language.Templates Short Name Language Tags -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -Blazor ( server-side ) blazorserverside [ C # ] Web/BlazorBlazor ( Server-side in ASP.NET Core ) blazorserverside [ C # ] Web/Blazor/ServerSideExamples : dotnet new blazorserverside dotnet new blazorserverside -- auth Individual dotnet new -- help | Unable to determine the desired template from the input template name : blazorserverside |
C_sharp : I wrote the following test ( actually used in a wider context ) Why does n't the task manager show any sign of the allocated 100 megabytes before the first key press ? If this is by design , how else can I test the consumption of unmanaged heap memory ? <code> IntPtr x = Marshal.AllocHGlobal ( 100000000 ) ; Console.Write ( `` Press any key to continue . . . `` ) ; Console.ReadKey ( true ) ; Marshal.FreeHGlobal ( x ) ; Console.ReadKey ( true ) ; | Unmanaged memory not showing up in task manager |
C_sharp : I was perusing the .Net Reference Source and found this gem in ButtonBase.cs at line 408 : Question being , what would motivate someone to use the exceptionThrown flag over just writing it as Is it just stylistic or is there some side-effect I am missing ? <code> bool exceptionThrown = true ; try { OnClick ( ) ; exceptionThrown = false ; } finally { if ( exceptionThrown ) { // Cleanup the buttonbase state SetIsPressed ( false ) ; ReleaseMouseCapture ( ) ; } } try { OnClick ( ) ; } catch { SetIsPressed ( false ) ; ReleaseMouseCapture ( ) ; throw ; } | Is there a reason for using Try/Finally with ExceptionThrown variable over Try/Catch |
C_sharp : In C # , will the folloing code throw e containing the additional information up the call stack ? <code> ... catch ( Exception e ) { e.Data.Add ( `` Additional information '' , '' blah blah '' ) ; throw ; } | Exception throwing |
C_sharp : I have looked , but could n't find a definitive answer for some of my exception questions , especially regarding C # best practices.Perhaps I will always be confused about the best way to use exceptions , I ran across this article which basically says 'always use exceptions , never use error codes or properties ' http : //www.eggheadcafe.com/articles/20060612.asp . I 'll definitely buy that , but here 's my dilemma : I have a function 'caller ' which calls 'callee ' . 'callee ' performs a few different things , each of which might throw the same type of exception . How do I relay meaningful information back to 'caller ' about what 'callee ' was doing at the time of the exception ? I could throw a new exception like below , but I 'm worried I 'll mess up the stacktrace which is bad : Thanks , Mark <code> //try to log in and get SomeException catch ( SomeException ex ) { throw new SomeException ( `` Login failed '' , ex ) ; } ... //try to send a file and get SomeExceptioncatch ( SomeException ex ) { throw new SomeException ( `` Sending file failed '' , ex ) : } | Mixing errors and exceptions in C # |
C_sharp : I want to make an SS application . But I have problem on this subject . I want user to be able to select a special area to take screenshot . I also want the desktop is live while the user is selecting the area . For example user wants to take an SS of a video 's specific frame . The user must be able to do this while video is playing . I have tried this using drawing directly on the desktop . But it flickers so much . How can I fix this or is there an alternative way to do ? My code : <code> [ DllImport ( `` User32.dll '' ) ] static extern IntPtr GetDC ( IntPtr hwnd ) ; [ DllImport ( `` user32.dll '' ) ] static extern bool InvalidateRect ( IntPtr hWnd , IntPtr lpRect , bool bErase ) ; public Form1 ( ) { InitializeComponent ( ) ; this.Load += Form1_Load ; } void Form1_Load ( object sender , EventArgs e ) { Start ( ) ; } IntPtr handle ; Graphics grp ; void Start ( ) { handle = GetDC ( IntPtr.Zero ) ; grp = Graphics.FromHdc ( handle ) ; grp.SmoothingMode = SmoothingMode.HighQuality ; timer2.Start ( ) ; } private void timer2_Tick ( object sender , EventArgs e ) { grp.DrawLine ( Pens.Red , 0 , Cursor.Position.Y , Screen.PrimaryScreen.Bounds.Width , Cursor.Position.Y ) ; InvalidateRect ( IntPtr.Zero , IntPtr.Zero , false ) ; } | How to do a screenshot area selection by drawing on desktop to take screenshot ? |
C_sharp : I have a rather simple LDAP client that works ok when connecting to the 389 port ( LDAP ) but fails with a `` LDAP server unavailable '' when I try to connect to the 636 port ( LDAPS ) .If I add the following at [ CODE MODIFICATION HERE ] to accept all server certificates , it works : The certificate is signed by a self-signed CA , I have added the CA public certificate to the Local Computer list of `` Trusted Root Certification Authorities '' 1.If I check the server certificate with openSSL using that CA 's certificate , it validates it . Also , I have tried LdapAdmin and when the CA is in that list , no warning is shown when connecting to the LDAP server.If I use the VerifyServerCertificateCallback to print the contents of the certificate : it shows me the thumbprint of the server certificate but yet verify fails.What can I be ? It seems that I am missing something very basic , but I can not understand what.UPDATE : I checked @ FrankNielsen 's suggestion and I added this code in the VerifyServerCertificateCallback : And it returns : Chain Information Chain revocation flag : ExcludeRoot Chain revocation mode : NoCheck Chain verification flag : NoFlag Chain verification time : 07/10/2019 15:53:00 Chain status length : 0 Chain application policy count : 0 Chain certificate policy count : 0 Chain Element Information Number of chain elements : 2 Chain elements synchronized ? False Element issuer name : CN=dexter-SCPDPRDEXTER01V-CA , DC=dexter , DC=local Element certificate valid from : 02/09/2019 12:24:22 Element certificate valid until : 01/09/2020 12:24:22 Element certificate is valid : False Element error status length : 0 Element information : Thumbprint : 63DCF4EFE0C96EF021BCC9CE662E2627A3CDF399 Number of element extensions : 9 Element issuer name : CN=dexter-SCPDPRDEXTER01V-CA , DC=dexter , DC=local Element certificate valid from : 11/06/2019 7:39:01 Element certificate valid until : 11/06/2069 7:49:01 Element certificate is valid : True Element error status length : 0 Element information : Thumbprint : 7BD9C718E336A50FA006CAEF539895C7E3EA5DA0 Number of element extensions : 4 The certificates match what would be expected ( the CA is retrieved ) , the CA return true to Verify ( ) but the server certificate returns false to Verify ( ) .1And for good measure , I also did try adding it to `` Intermediate Certification Authorities '' to no avail . <code> namespace MyNS { class ProgramLdap { private static LdapConnection CreateConnection ( String baseDn , string usuario , string password ) { LdapConnection ldapConnection = new LdapConnection ( new LdapDirectoryIdentifier ( `` myserver.example '' , 636 , true , false ) ) ; ldapConnection.SessionOptions.SecureSocketLayer = true ; ldapConnection.SessionOptions.ProtocolVersion = 3 ; // [ CODE MODIFICATION HERE ] ldapConnection.Credential = new NetworkCredential ( usuario , password ) ; ldapConnection.AuthType = AuthType.Basic ; ldapConnection.Timeout = new TimeSpan ( 1 , 0 , 0 ) ; return ldapConnection ; } static void Main ( string [ ] args ) { LdapConnection ldapConnection = CreateConnection ( `` '' , `` myLdapUser '' , `` noneOfYourBusiness '' ) ; SearchRequest searchRequest = new SearchRequest ( `` ou=usuarios , dc=Dexter , dc=local '' , String.Format ( `` ( & ( objectclass=person ) ( cn= { 0 } ) ) '' , user ) , SearchScope.Subtree , new string [ 0 ] ) ; SearchResponse searchResponse = ( SearchResponse ) ldapConnection.SendRequest ( searchRequest ) ; System.Diagnostics.Debug.WriteLine ( `` Resultados `` + searchResponse.Entries.Count ) ; } } } ldapConnection.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback ( ( conn , certificate ) = > true ) ; ldapConnection.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback ( ( conn , certificate ) = > { X509Certificate2 certificate2 = new X509Certificate2 ( certificate ) ; bool verify = certificate2.Verify ( ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` certificate2.Verify { 0 } ; Name { 1 } ; NameOID { 2 } ; FriendlyName { 3 } ; Thumbprint { 4 } ; Algorithm FriendlyName { 5 } '' , verify , certificate2.SubjectName.Name , certificate2.SubjectName.Oid , certificate2.FriendlyName , certificate2.Thumbprint , certificate2.SignatureAlgorithm.FriendlyName ) ) ; foreach ( X509Extension extension in certificate2.Extensions ) { System.Diagnostics.Debug.WriteLine ( extension.ToString ( ) + `` `` + extension.Oid.FriendlyName + `` `` + Encoding.UTF8.GetString ( extension.RawData ) ) ; } return verify ; } ) ; ( conn , certificate ) = > { X509Chain ch = new X509Chain ( ) ; ch.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck ; ch.Build ( new X509Certificate2 ( certificate ) ) ; System.Diagnostics.Debug.WriteLine ( `` Chain Information '' ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Chain revocation flag : { 0 } '' , ch.ChainPolicy.RevocationFlag ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Chain revocation mode : { 0 } '' , ch.ChainPolicy.RevocationMode ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Chain verification flag : { 0 } '' , ch.ChainPolicy.VerificationFlags ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Chain verification time : { 0 } '' , ch.ChainPolicy.VerificationTime ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Chain status length : { 0 } '' , ch.ChainStatus.Length ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Chain application policy count : { 0 } '' , ch.ChainPolicy.ApplicationPolicy.Count ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Chain certificate policy count : { 0 } { 1 } '' , ch.ChainPolicy.CertificatePolicy.Count , Environment.NewLine ) ) ; System.Diagnostics.Debug.WriteLine ( `` Chain Element Information '' ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Number of chain elements : { 0 } '' , ch.ChainElements.Count ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Chain elements synchronized ? { 0 } { 1 } '' , ch.ChainElements.IsSynchronized , Environment.NewLine ) ) ; foreach ( X509ChainElement element in ch.ChainElements ) { System.Diagnostics.Debug.WriteLine ( String.Format ( `` Element issuer name : { 0 } '' , element.Certificate.Issuer ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Element certificate valid from : { 0 } '' , element.Certificate.NotBefore ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Element certificate valid until : { 0 } '' , element.Certificate.NotAfter ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Element certificate is valid : { 0 } '' , element.Certificate.Verify ( ) ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Element error status length : { 0 } '' , element.ChainElementStatus.Length ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Element information : { 0 } '' , element.Information ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Thumbprint : { 0 } '' , element.Certificate.Thumbprint ) ) ; System.Diagnostics.Debug.WriteLine ( String.Format ( `` Number of element extensions : { 0 } { 1 } '' , element.Certificate.Extensions.Count , Environment.NewLine ) ) ; if ( ch.ChainStatus.Length > 1 ) { for ( int index = 0 ; index < element.ChainElementStatus.Length ; index++ ) { System.Diagnostics.Debug.WriteLine ( element.ChainElementStatus [ index ] .Status ) ; System.Diagnostics.Debug.WriteLine ( element.ChainElementStatus [ index ] .StatusInformation ) ; } } } return true ; } ) ; | .Net program does not get validated server certificate |
C_sharp : The documentation of constant pattern matching with the is-operator ( expr is constant ) states : The constant expression is evaluated as follows : If expr and constant are integral types , the C # equality operator determines whether the expression returns true ( that is , whether expr == constant ) .Otherwise , the value of the expression is determined by a call to the static Object.Equals ( expr , constant ) method.Therefore , when using this codeI expect it to use the == operator ( case 1 ) and generate this code : However , in reality , the integer parameter and the constant ( literal ) are boxed in order to be passed to the static Object.Equals method ( case 2 ) : Why is that the case ? <code> public bool IsZero ( int value ) { return value is 0 ; } .method public hidebysig instance bool IsZero ( int32 'value ' ) cil managed { .maxstack 8 ldarg.1 ldc.i4.0 ceq ret } .method public hidebysig instance bool IsZero ( int32 'value ' ) cil managed { .maxstack 8 ldc.i4.0 box [ mscorlib ] System.Int32 ldarg.1 box [ mscorlib ] System.Int32 call bool [ mscorlib ] System.Object : :Equals ( object , object ) ret } | Why does the is-operator cause unnecessary boxing ? |
C_sharp : I have a class of 3 different linked lists ( for saving the entities in a game I 'm working on ) . The lists are all of objects with the same base type , but I keep them separate for processing reasons . Note that IEntity , IObject and IUndead all inherited from IEntity.I have 3 methods for retrieving each of the lists , currently based on their parameters . The fact that there are 3 is fine , since I know each list will in some way or another require its own accessor . Passing an instantiated object is not ideal though , as I may want to retrieve a list somewhere without having an object of similar type at hand . Note that the object here is not even used in the GetList methods , they are only there to determine which version to use . Here is an example where I have an instantiated object at hand : I do n't like this current implementation as I may not always have an instantiated object at hand ( when rendering the entities for example ) . I was thinking of doing it generically but I 'm not sure if this is possible with what I want to do . With this I also need 3 Delete methods ( and 3 of any other , such as add and so forth ) - one for each type , IUndead , IObject and ILiving . I just feel that this is not the right way of doing it.I 'll post what I have tried to do so far on request , but my generics is rather bad and I feel that it would be a waste for anyone to read this as well.Finally , performance is very important . I 'm not prematurely optimizing , I am post-optimizing as I have working code already , but need it to go faster . The getlist methods will be called very often and I want to avoid any explicit type checking . <code> public class EntityBucket { public LinkedList < IEntity > undeadEntities ; public LinkedList < IEntity > objects ; public LinkedList < IEntity > livingEntities ; public EntityBucket ( ) { undeadEntities = new LinkedList < IEntity > ( ) ; objects = new LinkedList < IEntity > ( ) ; livingEntities = new LinkedList < IEntity > ( ) ; } public LinkedList < IEntity > GetList ( IObject e ) { return objects ; } public LinkedList < IEntity > GetList ( IUndead e ) { return undeadEntities ; } public LinkedList < IEntity > GetList ( ILiving e ) { return livingEntities ; } } public void Delete ( IUndead e , World world ) { ... .. LinkedList < IEntity > list = buckets [ k ] .GetList ( e ) ; ... .. } | C # , generic way to access different lists within a class |
C_sharp : We had a bit of an incident today which has got me thinking . We have a project with a pretty standard web.config transform setup for our various configs . There is a section which controls access to our DAO services which looks like this : And a transform like this : Hopefully you will have spotted the error here - the name for the DaoEndPoint does n't match . Unfortunately the dev who created it did n't , and had also been locally debugging against the live services , which caused the test deployment to , yup , point to live . We luckily picked it up pretty quickly , but I 'm sure you can see the potential for extreme pain here ! I got thinking about your intent when creating transform files and it seems to me that if you put in a transform that you intend to transform something . So it would be nice if the transform ( and therefore the deploy ) failed if there was a DaoEndPoint transform but no matching DaoEndPoint item in the main .config file.So I 'm sort of canvasing for people 's opinions , is this something that would be useful ? Is it plain overkill ? Am I totally missing the point ? Also , is there anything out there that does this ? I 'm happy to dig about and develop a solution , but I 'd be happier if someone had done the legwork for me ; ) <code> < endpoint address= '' http : //myserver/myservice1.svc/basicHttp '' binding= '' basicHttpBinding '' contract= '' MyAssembly.IItem '' name= '' DataAccessEndPoint '' kind= '' '' endpointConfiguration= '' '' / > < endpoint address= '' http : //myserver/myservice2.svc/basicHttp '' binding= '' basicHttpBinding '' contract= '' MyAssembly.IItem2 '' name= '' LoggingEndPoint '' kind= '' '' endpointConfiguration= '' '' / > < endpoint address= '' http : //mytestserver/myservice1.svc '' name= '' DaoEndPoint '' xdt : Transform= '' SetAttributes '' xdt : Locator= '' Match ( name ) '' / > < endpoint address= '' http : //mytestserver/myservice2.svc '' name= '' LoggingEndPoint '' xdt : Transform= '' SetAttributes '' xdt : Locator= '' Match ( name ) '' / > | Failing web.config transform when no value exists for a transform |
C_sharp : I 'm working on a project where the MongoDB model will be similar to Facebook . So we all know how FB works , a user `` likes '' a band/company page , and that user will see all the posts from that page.Is the below model how I should design this ? If a Page has million likes , then each Post will have a million sub documents of Like . That does not seem right , there must be a better way that I cant think of.Thanks . <code> public class Person { public ObjectId Id { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } } public class Page { public ObjectId Id { get ; set ; } public string Name { get ; set ; } public List < Like > PersonLikes { get ; set ; } } public class Like { public ObjectId Id { get ; set ; } public ObjectId UserId { get ; set ; } public DateTime DateLiked { get ; set ; } } public class Post { public ObjectId Id { get ; set ; } public ObjectId PageId { get ; set ; } public string Message { get ; set ; } public List < Like > PersonLikes { get ; set ; } } | C # mongodb model like Facebook |
C_sharp : I 'm attempting to use CryptUnprotectData to read a password protected using CryptProtectData into a SecureString and use that to connect to a database . I can get the correct password out , but trying to create a new SqlConnection after that fails with the following : It 's enough to simply call CryptUnprotectData for the SqlConnection to fail , the connection itself does n't need to use the returned SecureString.I 'm using the extension methods from here as described in this post for my minimal repro : If i create a new SqlConnection before I load the password , I can create new SqlConnections fine for the duration of the application as it seems to use the same SqlConnectionFactory , but that means as a workaround I have to do something like this at the start of the application : ... which I 'd like to avoid.The following do not help : Debug vs Release buildDebugging in Visual Studio vs running through the command lineChanging the CryptProtectFlags that is passed to CryptUnprotectData.Removing RuntimeHelpers.PrepareConstrainedRegions ( ) from the protection method.Windows 10 , VS Enterprise 2015 , Console Application ( .NET 4.6.1 ) UPDATE : Running the data protection code in another threads gives a similar exception with a different root cause : <code> System.TypeInitializationException was unhandled HResult=-2146233036 Message=The type initializer for 'System.Data.SqlClient.SqlConnection ' threw an exception . Source=System.Data TypeName=System.Data.SqlClient.SqlConnection StackTrace : at System.Data.SqlClient.SqlConnection..ctor ( ) at System.Data.SqlClient.SqlConnection..ctor ( String connectionString , SqlCredential credential ) at System.Data.SqlClient.SqlConnection..ctor ( String connectionString ) at ProtectedSqlTest.Program.Main ( ) in C : \Git\ProtectedSqlTest\ProtectedSqlTest\Program.cs : line 16 at System.AppDomain._nExecuteAssembly ( RuntimeAssembly assembly , String [ ] args ) at System.AppDomain.ExecuteAssembly ( String assemblyFile , Evidence assemblySecurity , String [ ] args ) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ( ) at System.Threading.ThreadHelper.ThreadStart_Context ( Object state ) at System.Threading.ExecutionContext.RunInternal ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( ) InnerException : HResult=-2146233036 Message=The type initializer for 'System.Data.SqlClient.SqlConnectionFactory ' threw an exception . Source=System.Data TypeName=System.Data.SqlClient.SqlConnectionFactory StackTrace : at System.Data.SqlClient.SqlConnection..cctor ( ) InnerException : HResult=-2146233036 Message=The type initializer for 'System.Data.SqlClient.SqlPerformanceCounters ' threw an exception . Source=System.Data TypeName=System.Data.SqlClient.SqlPerformanceCounters StackTrace : at System.Data.SqlClient.SqlConnectionFactory..cctor ( ) InnerException : HResult=-2147024809 Message=The parameter is incorrect . ( Exception from HRESULT : 0x80070057 ( E_INVALIDARG ) ) Source=mscorlib StackTrace : at System.Globalization.TextInfo.InternalChangeCaseString ( IntPtr handle , IntPtr handleOrigin , String localeName , String str , Boolean isToUpper ) at System.Globalization.TextInfo.ToLower ( String str ) at System.String.ToLower ( CultureInfo culture ) at System.Diagnostics.PerformanceCounterLib.GetPerformanceCounterLib ( String machineName , CultureInfo culture ) at System.Diagnostics.PerformanceCounterLib.IsCustomCategory ( String machine , String category ) at System.Diagnostics.PerformanceCounter.InitializeImpl ( ) at System.Diagnostics.PerformanceCounter.set_RawValue ( Int64 value ) at System.Data.ProviderBase.DbConnectionPoolCounters.Counter..ctor ( String categoryName , String instanceName , String counterName , PerformanceCounterType counterType ) at System.Data.ProviderBase.DbConnectionPoolCounters..ctor ( String categoryName , String categoryHelp ) at System.Data.SqlClient.SqlPerformanceCounters..ctor ( ) at System.Data.SqlClient.SqlPerformanceCounters..cctor ( ) InnerException : class Program { const string ProtectedSecret = /* SNIP - base 64 encoded protected data here */ ; static void Main ( ) { // calling AppendProtectedData breaks the following SqlConnection // without the following line the application works fine new SecureString ( ) .AppendProtectedData ( Convert.FromBase64String ( ProtectedSecret ) ) ; using ( var conn = new SqlConnection ( `` Server= ( localdb ) \\MSSqlLocalDb ; Trusted_Connection=true '' ) ) using ( var cmd = new SqlCommand ( `` select 1 '' , conn ) ) { conn.Open ( ) ; cmd.ExecuteNonQuery ( ) ; } } } new SqlConnection ( ) .Dispose ( ) ; System.TypeInitializationException was unhandled HResult=-2146233036 Message=The type initializer for 'System.Data.SqlClient.SqlConnection ' threw an exception . Source=System.Data TypeName=System.Data.SqlClient.SqlConnection StackTrace : at System.Data.SqlClient.SqlConnection..ctor ( ) at System.Data.SqlClient.SqlConnection..ctor ( String connectionString , SqlCredential credential ) at System.Data.SqlClient.SqlConnection..ctor ( String connectionString ) at ProtectedSqlTest.Program.Main ( ) in C : \Git\ProtectedSqlTest\ProtectedSqlTest\Program.cs : line 17 at System.AppDomain._nExecuteAssembly ( RuntimeAssembly assembly , String [ ] args ) at System.AppDomain.ExecuteAssembly ( String assemblyFile , Evidence assemblySecurity , String [ ] args ) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ( ) at System.Threading.ThreadHelper.ThreadStart_Context ( Object state ) at System.Threading.ExecutionContext.RunInternal ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( ) InnerException : HResult=-2146233036 Message=The type initializer for 'System.Data.SqlClient.SqlConnectionFactory ' threw an exception . Source=System.Data TypeName=System.Data.SqlClient.SqlConnectionFactory StackTrace : at System.Data.SqlClient.SqlConnection..cctor ( ) InnerException : HResult=-2146233036 Message=The type initializer for 'System.Data.SqlClient.SqlPerformanceCounters ' threw an exception . Source=System.Data TypeName=System.Data.SqlClient.SqlPerformanceCounters StackTrace : at System.Data.SqlClient.SqlConnectionFactory..cctor ( ) InnerException : BareMessage=Configuration system failed to initialize HResult=-2146232062 Line=0 Message=Configuration system failed to initialize Source=System.Configuration StackTrace : at System.Configuration.ClientConfigurationSystem.EnsureInit ( String configKey ) at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem ( String sectionName ) at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection ( String sectionName ) at System.Configuration.ConfigurationManager.GetSection ( String sectionName ) at System.Configuration.PrivilegedConfigurationManager.GetSection ( String sectionName ) at System.Diagnostics.DiagnosticsConfiguration.Initialize ( ) at System.Diagnostics.DiagnosticsConfiguration.get_SwitchSettings ( ) at System.Diagnostics.Switch.InitializeConfigSettings ( ) at System.Diagnostics.Switch.InitializeWithStatus ( ) at System.Diagnostics.Switch.get_SwitchSetting ( ) at System.Data.ProviderBase.DbConnectionPoolCounters..ctor ( String categoryName , String categoryHelp ) at System.Data.SqlClient.SqlPerformanceCounters..ctor ( ) at System.Data.SqlClient.SqlPerformanceCounters..cctor ( ) InnerException : HResult=-2147024809 Message=Item has already been added . Key in dictionary : 'MACHINE ' Key being added : 'MACHINE ' Source=mscorlib StackTrace : at System.Collections.Hashtable.Insert ( Object key , Object nvalue , Boolean add ) at System.Collections.Hashtable.Add ( Object key , Object value ) at System.Configuration.Internal.InternalConfigRoot.GetConfigRecord ( String configPath ) at System.Configuration.ClientConfigurationSystem.EnsureInit ( String configKey ) InnerException : | P/Invoke CryptUnprotectData breaks SqlConnection constructor |
C_sharp : IEnumerable does not guarantee that enumerating twice will yield the same result . In fact , it 's quite easy to create an example where myEnumerable.First ( ) returns different values when executed twice : This is not just an academic example : Using the popular from ... in ... select new A ( ... ) will create exactly this situation . This can lead to unexpected behaviour : I understand why this happens . I also know that this could be fixed by executing ToList ( ) on the Enumerable or by overriding == for class A . That 's not my question.The question is : When you write a method that takes an arbitrary IEnumerable and you want the property that the sequence is only evaluated once ( and then the references are `` fixed '' ) , what 's the canonical way to do this ? ToList ( ) seems to be used mostly , but if the source is fixed already ( for example , if the source is an array ) , the references are copied to a list ( unnecessarily , since all I need is the fixed property ) . Is there something more suitable or is ToList ( ) the `` canonical '' solution for this issue ? <code> class A { public A ( string value ) { Value = value ; } public string Value { get ; set ; } } static IEnumerable < A > getFixedIEnumerable ( ) { return new A [ ] { new A ( `` Hello '' ) , new A ( `` World '' ) } ; } static IEnumerable < A > getDynamicIEnumerable ( ) { yield return new A ( `` Hello '' ) ; yield return new A ( `` World '' ) ; } static void Main ( string [ ] args ) { IEnumerable < A > fix = getFixedIEnumerable ( ) ; IEnumerable < A > dyn = getDynamicIEnumerable ( ) ; Console.WriteLine ( fix.First ( ) == fix.First ( ) ) ; // true Console.WriteLine ( dyn.First ( ) == dyn.First ( ) ) ; // false } fix.First ( ) .Value = `` NEW '' ; Console.WriteLine ( fix.First ( ) .Value ) ; // prints NEWdyn.First ( ) .Value = `` NEW '' ; Console.WriteLine ( dyn.First ( ) .Value ) ; // prints Hello | Is there a canonical way to `` fix '' a `` dynamic '' IEnumerable ? |
C_sharp : I have a Windows Forms application where I need to make all fonts of all UI elements configurable from a separate file . I.e . I want to be able to specify that a label has a font `` TitleBarBoldFont '' which would resolve to a real font , depending on the current locale . The configuration file may contain a corresponding section like this : My question is : is there a standard .NET/Windows Forms way to achieve this so that I could specify my custom fonts in the WinForms designer and would n't have to explicitly call a font resolution method for each GUI element in the code ? <code> < Font fontID= '' TitleBarBoldFont '' > < Display facename= '' Helvetica '' pointSize= '' 12 '' > < Override lang= '' ja '' facename= '' Meiryo Bold '' pointSize= '' 12 '' / > < Override lang= '' zh '' facename= '' SimHei '' pointSize= '' 12 '' / > < Override lang= '' ru '' facename= '' Arial Bold '' pointSize= '' 12 '' / > < /Display > < /Font > | Looking for the optimal way to use custom font definitions in WinForms application |
C_sharp : suppose this is my txt file : im reading content of this file with : Now i want to read data in stdList , but read only value every 2 line ( in this case i 've to read `` line2 '' and `` line4 '' ) .can anyone put me in the right way ? <code> line1line2line3line4line5 string line ; List < string > stdList = new List < string > ( ) ; StreamReader file = new StreamReader ( myfile ) ; while ( ( line = file.ReadLine ( ) ) ! = null ) { stdList.Add ( line ) ; } finally { //need help here } | reading string each number c # |
C_sharp : This is a question for a job application : '' A father has two sons and 999 paintings . Each painting has a different value : first is worth 1 , second is worth 2 and so on , until the final painting is worth 999 . He would like to divide all of his paintings to his two sons , so that each son gets equal value . How many ways are there to do that with 999 paintings ? Example : if father had 7 paintings , he could divide them fairly by giving the first son paintings 1,6 and 7 . Second son would get 2,3,4 and 5 . Both would have equal value in sum , 14 . In case when there are 7 paintings , father can fairly divide them in 4 ways ( other 3 not listed here ) , so the solution is 4.HINT : the number might be large , so send us the last 10 digits and sketch of your solution . `` What I did was try to use a brute force approach , adding up all the possible combinations by writing a c # program which writes it 's own c # program with loops within loops , like this : And then adding this after the if blocks in the result : This approach should technically work ( as tested on a smaller number of paintings ) , but the problem is it is a HUUUGE number and it would take like a million years or so to calculate the result on my computer this way ... Is there some mathematical trick to do this in a reasonable amount of time ? <code> StringBuilder sb = new StringBuilder ( ) ; for ( short i = 2 ; i < = 999 ; i++ ) //starts from 2 because 1 is always added to the total for one side { sb.AppendLine ( `` for ( byte i '' + i.ToString ( ) + `` = 0 ; i '' + i.ToString ( ) + `` < 2 ; i '' + i.ToString ( ) + `` ++ ) '' ) ; sb.AppendLine ( `` { `` ) ; } for ( int i = 2 ; i < = 999 ; i++ ) { sb.Append ( `` if ( i '' + i.ToString ( ) + `` == 1 ) { total += `` + i.ToString ( ) + `` ; } \n '' ) ; } for ( short i = 2 ; i < = 999 ; i++ ) { sb.AppendLine ( `` } '' ) ; } if ( total == 249750 ) { count++ ; //count is a BigInteger } total = 1 ; | Father , two sons , 999 paintings |
C_sharp : I 'm trying to load some .dll files dynamically . The Files are Plugins ( self-written for now ) which have at least one class that implements MyInterface . For each file I 'm doing the following : Running this causes a cast exception , but I ca n't find a workaround . Anyway I am wondering why this does n't work at all . I 'm looking for a solution in .NET Framework 3.5.Another thing that happened to me was getting null in p after running the following at the point before adding a new entry to _myList in the code above : This code was the first attempt on loading the plugins , I did n't find out why p was null yet.I hope someone can lead me to the right way : ) <code> Dictionary < MyInterface , bool > _myList ; // ... code Assembly assembly = Assembly.LoadFrom ( currentFile.FullName ) ; foreach ( Type type in assembly.GetTypes ( ) ) { var myI = type.GetInterface ( `` MyInterface '' ) ; if ( myI ! = null ) { if ( ( myI.Name == `` MyInterface '' ) & & ! type.IsAbstract ) { var p = Activator.CreateInstance ( type ) ; _myList.Add ( ( MyInterface ) p , true ) ; } } } var p = type.InvokeMember ( null , BindingFlags.CreateInstance , null , null , null ) as MyInterface ; | C # cast a class to an Interface List |
C_sharp : I 'm currently working on some C # /C++ code which makes use of invoke . In the C++ side there is a std : :vector full of pointers each identified by index from the C # code , for example a function declaration would look like this : But now I 'm thinking , since I 'm working with pointers could n't I sent to C # the pointer address itself then in code I could do something like this : Obviously that 's a quick version of what I 'm getting at ( and probably wo n't compile ) .Would the pointer address be guaranteed to stay constant in C++ such that I can safely store its address in C # or would this be too unstable or dangerous for some reason ? <code> void SetName ( char* name , int idx ) void SetName ( char*name , int ptr ) { ( ( TypeName* ) ptr ) - > name = name ; } | Is it safe to keep C++ pointers in C # ? |
C_sharp : I have seven words in the array : the x is generated from another array : that means each x can be either a or b or c or d. It is randomly generated . this could be an example : my question is how can I check if there are five x which has the same value ? This is for a poker app Im working on . <code> string [ 7 ] = { x , x , x , x , x , x , x } ; string [ 4 ] = { a , b , c , d } ; string [ 7 ] = { a , a , d , a , a , c , a } | Compare 7 words to eachother to see if 5 of them are equal . How ? |
C_sharp : I have a C # app that uses a custom section for configuration . I have that section of XML defined as a string . The string looks like this : This XML matches the schema defined by the classes I described here . When I pass the above string to the Departments.Deserialize method , I receive an error . The error says : `` Unrecognized element 'add ' '' . The debugger jumps to this line in my Departments class.I assume that the error is referring to the 'add ' elements in the 'product ' element . However , the Product ConfigurationElement has a property named KeyValueConfigurationCollection Items . For that reason , it seems that add would work . Why am I getting this error how do I fix my code so that the XML string shown above can be deserialized ? <code> var xml = @ '' < departments > < department id= '' '' 1 '' '' name= '' '' Sporting Goods '' '' > < products > < product name= '' '' Basketball '' '' price= '' '' 9.99 '' '' > < add key= '' '' Color '' '' value= '' '' Orange '' '' / > < add key= '' '' Brand '' '' value= '' '' [ BrandName ] '' '' / > < /product > < /products > < /department > < /departments > '' ; public void ReadXml ( XmlReader reader ) { this.DeserializeElement ( reader , false ) ; } | Unable to Deserialize XML in C # - Unrecgnized element 'add ' |
C_sharp : I am developing a windows application using c # . I am loading a file ( html , txt , xhtml ) to the text box . I want to test the occurrence of following cases in my text box.For all the occurrences of the above condition I want to highlight the particular found text in the textbox . I am trying to use the regular expression . I am inserting all the cases in the array list and checking one by one . For the first case if the text in the textbox is like hjhdf , dfsjf then it will show the message box , if any text before and after this particular text then it will not show the messagebox . <code> , ( comma ) with closeup text ( ex . text1 , text2 ) . ( dot ) with closeup text ( ex . text1.text2 ) : ( colon ) with closeup text ( ex . text1 : text2 ) , ( comma ) with closeup ' i.e ( left single quotation mark ) '' ( doublequote ) with closeup text ' ( single quote ) with closeup text < /i > with closeup text ( ex . < /i > text ) < /span > with closeup text . string regexerror = wordToFind ; Regex myregex = new Regex ( `` ^ [ , ] * [ a-zA-Z ] * $ '' ) ; bool isexist = myregex.IsMatch ( rtbFileDisplay.Text ) ; if ( isexist ) { MessageBox.Show ( `` Hi '' ) ; } | Multiple occurrence of regular expression in a multiline textbox |
C_sharp : I have a strange problem and it 's been frustrating me for the past few hours . I ca n't seem to find anything related ; perhaps I 'm not being specific enough , as I 'm not sure how to word it correctly , or it 's a strangely unique problem.There 's a form a user fills in to update their account information , everything works as it should , except for one text area . This text areas ' ( which is bound to the property Comments of UserInfo ) value becomes null once the form is POSTed . The Comments property is the only property which is null.When It OccursA ) No existing value , user inputs a value , property is null.B ) Existing value , user does/does n't change something/anything , property is null.I 'll only include the relevant code to keep things clean and simple . Hopefully it 's enough.Controller Actions Razor View HTML UserInfo Model Yes , I do use FluentValidation on the model . I removed it to see if it was the cause , but it wasn't.Things I 've Tried On the POST action , I 've used FormCollection formCollection instead of UserInfo userInfo.Threw an exception on the POST action to prove the value becomes null when posted.Created a new property with a different name.Manually gave the property a value before returning the view . The value became null when it was posted.Manually gave the property a value in the POST action to prove it was n't the DB or SQL . This worked.Removed the Fluent Validation attribute from the model ( as said above ) .Used [ Bind ( Prefix = `` '' ) ] before UserInfo userInfo . This did n't change anything.It 's frustrated me to the point where I have to ask : What the hell is going ? Am I doing something wrong ? I must be overlooking something . There is another text area on the page which works as it should . It 's just the text area for Comments which always returns null values regardless of the conditions . <code> public ActionResult Edit_Information ( long id ) { // Get user info from the database . // Return the view with the user info from the DB etc . } [ HttpPost ] public ActionResult Edit_Information ( long id , UserInfo userInfo ) { if ( ! this.ModelState.IsValid ) { // Invalid return View ( userInfo ) ; } // Update the information in the DB . // Redirect the user back to their account . } < div style= '' width : 700px ; margin-left : auto ; margin-right : auto ; text-align : left '' > @ Html.ValidationMessageFor ( x = > x.Comments ) < /div > @ Html.Partial ( `` ~/Views/Shared/_EditorSmiles.cshtml '' ) @ Html.TextAreaFor ( x = > x.Comments , new { @ class = `` EditorArea profile-comments '' } ) [ Validator ( typeof ( UserInfoValidator ) ) ] public class UserInfo { public string Comments { get ; set ; } } | That text area of nullness |
C_sharp : I have the following line of code : Exists on the left hand side is a property of the User class . Its type is just bool , not bool ? . The Exists method on the right hand side is an API method to check if a given entity exists in the repository . It returns Task < bool > . I want to check if the repository is null first so I use the null conditional operator . I thought that if the repository is null then the whole right hand side would just return null , which can not be assigned to a bool type , but the compiler seems to be fine with it . Does it just default to a false value somehow ? <code> user.Exists = await this.repository ? .Exists ( id ) ; | Why can the null conditional operator be used when setting the value of a bool without using a nullable bool ? |
C_sharp : Consider the following : The first Write in DoItAsync ( ) executes.SomeLongJobAsync ( ) starts.The WriteLine in DoItAsync ( ) executes.DoItAsync ( ) pauses while SomeLongJobAsync ( ) works away until it 's done.SomeLongJobAsync ( ) completes , so DoItAsync ( ) returns.Meanwhile , the UI is responsive.On what thread does SomeLongJobAsync ( ) execute ? <code> private async void btnSlowPoke_Click ( object sender , EventArgs e ) { await DoItAsync ( ) ; } private async Task < int > SomeLongJobAsync ( ) { for ( int x = 0 ; x < 999999 ; x++ ) { //ponder my existence for one second await Task.Delay ( 1000 ) ; } return 42 ; } public async Task < int > DoItAsync ( ) { Console.Write ( `` She 'll be coming round the mountain '' ) ; Task < int > t = SomeLongJobAsync ( ) ; // < -- On what thread does this execute ? Console.WriteLine ( `` when she comes . `` ) ; return await t ; } | Where do 'awaited ' tasks execute ? |
C_sharp : As you probably know in D language we have an ability called Voldemort Types and they are used as internal types that implement particular range function : Here is how the Voldemort type can be used : Now I want to make sure that , Is this the equivalent to delegate in C # ? <code> auto createVoldemortType ( int value ) { struct TheUnnameable { int getValue ( ) { return value ; } } return TheUnnameable ( ) ; } auto voldemort = createVoldemortType ( 123 ) ; writeln ( voldemort.getValue ( ) ) ; // prints 123 public static void Main ( ) { var voldemort = createVoldemortType ( 123 ) ; Console.WriteLine ( voldemort ( ) ) ; } public static Func < int > createVoldemortType ( int value ) { Func < int > theUnnameable = delegate ( ) { return value ; } ; return theUnnameable ; } | Voldemort types in C # |
C_sharp : I 'm currently trying to bulkinsert a datatable into a database . It works fine and fast . The only problem occursif there are any rows that are already in the database ( duplicate key ) . To counter this I have modified my program so that I first check for each new entry if it already exists in the database or not.Which is ... ... .slow ( In the current cases I do n't have many entries but later on its over 200k entries that I need to check and that a few times ) .Thus I need to make it faster as it is now ( if possible ) .The datatable is structured this way : What I have so far is the following : Now my question is : Is there any way to do this faster in order to not get the key violation problem ? <code> DataTable transactionTable.Columns.Add ( `` DeviceId '' , typeof ( Int32 ) ) ; transactionTable.Columns.Add ( `` LogDate '' , typeof ( DateTime ) ) ; transactionTable.Columns.Add ( `` LogType '' , typeof ( Int32 ) ) ; transactionTable.Columns.Add ( `` LogText '' , typeof ( String ) ) ; transactionTable.PrimaryKey = new DataColumn [ 3 ] { transactionTable.Columns [ 0 ] , transactionTable.Columns [ 1 ] , transactionTable.Columns [ 2 ] } ; DataTable insertTable = transactionTable.Copy ( ) ; insertTable.Clear ( ) ; using ( SqlConnection sqlcon = new SqlConnection ( this.GetConnString ( ) ) ) { sqlcon.Open ( ) ; foreach ( var entry in transactionTable.AsEnumerable ( ) ) { using ( SqlCommand sqlCom = sqlCon.CreateCommand ( ) ) { sqlCom.Parameters.Clear ( ) ; sqlCom.CommandText = `` SELECT 1 FROM myTable WHERE '' + `` DeviceId = @ DeviceId AND LogDate = @ LogDate '' + `` AND LogType = @ LogType '' sqlCom.Parameters.AddWithValue ( `` @ DeviceId '' , entry.Field < Int32 > ( `` DeviceId '' ) ) ; sqlCom.Parameters.AddWithValue ( `` @ LogDate '' , entry.Field < DateTime > ( `` LogDate '' ) ) ; sqlCom.Parameters.AddWithValue ( `` @ LogType '' , entry.Field < Int32 > ( `` LogType '' ) ) ; using ( SqlDataREader myRead = sqlCon.ExecuteReader ( ) { myRead.Read ( ) ; if ( myRead.HasRows == false ) { insertTable.Rows.Add ( entry.ItemArray ) ; } } } } } // And afterwards the bulkinsert which I think is out of scope for the question itself // ( I use the insertTable there ) | How to fast reduce a datatable according to existing entries in a DB |
C_sharp : This issue has been on/off bugging me and I 've written 4 wrappers now . I 'm certain I 'm doing it wrong and need to figure out where my understanding is branching off.Let 's say I 'm using the Rectangle class to represent bars of metal . ( this works better then animals ) So say the base class is called `` Bar '' .So . Now we make a rectangle , say 300 units by 10 units.Fantastic , so we have a base bar.Now let 's say we want to make this bar have a material - say steel . So . . .So if I did this . . .From what I get from this if I call CreateSteelBar , it creates a steelbar that calls CreateBar . So I end up with a steel bar with a 300 by 10 rectangle , and a nulled or empty string for material . Then I set the material to steel.When I try something similar in my program , it keeps telling I can not implicitly create a higher up class from a lower down class . I would have figured this is why inheritance exists considering all the inherits from animal examples I see , but am hoping someone can clear me up.Also , I 'm certain I could call SteelBar = CreateBar ( ) ; but I did it the long way here . <code> private class Bar { internal Rectangle Area ; } private Bar CreateBar ( ) { Bar1 = new Bar1 ( ) ; Bar1.Area = new Rectangle ( new Point ( 0,0 ) , new Size ( 300,10 ) ) ; return Bar1 ; } private class SteelBar : Bar { string Material ; } private SteelBar CreateSteelBar ( ) { SteelBar SteelB = new SteelB ( ) ; Bar B = CreateBar ( ) ; SteelB = B ; SteelB.Material = `` Steel '' ; return SteelB ; } | C # base inheritance |
C_sharp : Is there any performance benefit to explicitly calling a method directly from a namespace class library rather than using the namespace ? Here is an example of a situation I 'm referring to : vs . <code> // usingusing System.Configuration ; public class MyClass { private readonly static string DBConn = ConfigurationManager.ConnectionStrings [ `` DBConn '' ] .ConnectionString ; } //explicitpublic class MyClass { private readonly static string DBConn = System.Configuration.ConfigurationManager.ConnectionStrings [ `` DBConn '' ] .ConnectionString ; } | Is there a performance difference between using a namespace vs explicitly calling the class from the namespace ? |
C_sharp : Having How can I translate for ( x = 0 ; x < 1ULL < < ( 2*k ) ; ++x ) unsigned long long 1ULL and bitwise to c # ? I was tryingHow to translate that parts of code x < 1ULL < < ( 2*k ) ; and `` ACGT '' [ y & 3 ] ? <code> int i , k ; unsigned long long x , y ; k = 5 ; for ( x = 0 ; x < 1ULL < < ( 2*k ) ; ++x ) { for ( i = 0 , y = x ; i < k ; ++i , y > > = 2 ) putchar ( `` ACGT '' [ y & 3 ] ) ; putchar ( '\n ' ) ; } public static ulong aux ( int val ) { ulong result = ? ? ? ? ? < < val ; return result ; } public static void main ( ) { int i ; int k =5 ; ulong x , y ; for ( x = 0 ; x < aux ( 2*k ) ; ++x ) { for ( i = 0 , y = x ; i < k ; ++i , y > > = 2 ) { Console.Write ( `` ACGT '' [ y & 3 ] ) ; } Console.WriteLine ( ) ; } | translate C unsigned long long and bitwise in for loop to c # |
C_sharp : I would like to know if there 's a specific constraint for numerical types that allows casting to work in the following case : I tried boxing and unboxing like : But this only works if T == byte . Otherwise I get an InvalidCastException.T is always a number type ( like short , float , and so on ) . <code> class MyClass < T > { ... void MyMethod ( ) { ... . byte value = AnotherObject.GetValue ( ) Tvalue = ( T ) value ; ... . } ... } Tvalue = ( T ) ( object ) value ; | Converting numerical concrete type to numerical generic type |
C_sharp : After a bit of programming one of my classes used generics in a way I never seen before . I would like some opinions of this , if it 's bad coding or not.is this an OK use of generics or not ? I 'm mostly thinking about the constraint to `` itself '' . I sometimes feel like generics can `` explode '' to other classes where I use the Base class . <code> abstract class Base < T > : where T : Base < T > { // omitted methods and properties . virtual void CopyTo ( T instance ) { /*code*/ } } class Derived : Base < Derived > { override void CopyTo ( Derived instance ) { base.CopyTo ( instance ) ; // copy remaining stuff here } } | Weird use of generics |
C_sharp : I am trying to write documentation comments however I have a problem.When I reach the < T > Visual studio thinks I am trying to add another tag . what is the correct way to add comments like that ( and if I could make them click able in the generated help text that would be a extra bonus ) <code> /// < summary > /// Inserts an element into the System.Collections.Generic.List < T > at the specified/// index./// < /summary > | How to add items enclosed by < > to documentation comments |
C_sharp : I am working on a calculation module using C # , and I bumped on this : I know this is a wrong initialization that returns v = 0.0 instead of v = 0.04The c # rules says I must ensure at least one of the member is a double , like this : However , I have many many initializations of that kind that involves integer variables operations , and I feel lazy to browse my code line by line to detect such mistakes.Instead , is it possible to get warned by the compiler about this ? <code> double v = 4 / 100 ; double v = ( double ) 4 / 100 ; double v = 4.0 / 100 ; | How to be warned about potential arithmetic errors due to type conversion ? |
C_sharp : I 'm using .NET 4.8 and declare a record with a Deconstructor : Then I use the following code which is compiled and it works fine : While this code does n't work an error is generated : '' Error CS0029 Can not implicitly convert type 'ConsoleApp4.Product ' to 'System.Tuple < string , int > ' '' ) : The declaration var ( name , categoryId ) is not clear . What is it ? What is the type of this variable ? How is this construction called in the specification ? Is that an auto-generated type behind the scene and the name and the categoryId are its properties ? <code> public record Product { public string Name { get ; } public int CategoryId { get ; } public Product ( string name , int categoryId ) = > ( Name , CategoryId ) = ( name , categoryId ) ; public void Deconstruct ( out string name , out int categoryId ) = > ( name , categoryId ) = ( Name , CategoryId ) ; } var product = new Product ( `` VideoGame '' , 1 ) ; var ( name , categoryId ) = product ; string s = name ; int i = categoryId ; var product = new Product ( `` VideoGame '' , 1 ) ; Tuple < string , int > t = product ; string s = t.Item1 ; int i = t.Item2 ; | What is the variable declaration `` var ( name , categoryId ) = object '' called in C # ? |
C_sharp : I am trying to make a regex match which is discarding the lookahead completely . This is the match and this is my regex101 test.But when an email starts with - or _ or . it should not match it completely , not just remove the initial symbols . Any ideas are welcome , I 've been searching for the past half an hour , but ca n't figure out how to drop the entire email when it starts with those symbols . <code> \w+ ( [ -+. ] \w+ ) * @ \w+ ( [ -. ] \w+ ) *\.\w+ ( [ - . ] \w+ ) * | Regex lookahead discard a match |
C_sharp : I 'm currently programming my own implementation of priority queue / sorted list and I would like to have it concurrent.In order to have it thread safe I 'm using lock ( someObject ) and I would like to verify some behavior of mutexes in C # .Inner representation of my sorted list is basically linked list with head and slots linked together.Something like : Every time I 'm manipulating with head I have to use lock ( someObject ) because of thread safety.In order to implement ICollection interface I have to implement public IEnumerator < T > GetEnumerator ( ) . In this method I have take my head and read from it so I should use mutex.My question is : Is syncLock locked for whole time in enumerator ( so it will be unlocked after reaching end of the method ) or it is automatically unlocked after yielding value ? <code> internal class Slot { internal T Value ; internal Slot Next ; public Slot ( T value , Slot next = null ) { Value = value ; Next = next ; } } public IEnumerator < T > GetEnumerator ( ) { lock ( syncLock ) { var curr = head ; while ( curr ! = null ) { yield return curr.Value ; curr = curr.Next ; } } } | Concurrent collection enumerator |
C_sharp : I 'm having a brain fart trying to make the following method more generic such that any List < T > can be passed in for the columnValues parameter . Here 's what I have : I could change it to a List < object > and convert the original list prior to passing it to the method but I 'm sure there is a better option : - ) Edit : Frank 's post made me rethink this . In most cases that source List < T > would be a List < object > since the column values will most likely be different types . For my initial use a List < string > made sense because I was creating a dataset from a CSV parse which is all text at that point . <code> public static DataRow NewRow ( this DataTable dataTable , List < string > columnValues ) { DataRow returnValue = dataTable.NewRow ( ) ; while ( columnValues.Count > returnValue.Table.Columns.Count ) { returnValue.Table.Columns.Add ( ) ; } returnValue.ItemArray = columnValues.ToArray ( ) ; return returnValue ; } | How can I make this extension method more generic ? |
C_sharp : For example , we know that `` int '' type in C # is nothing but a structure which is actually System.Int32 . If that so , then if `` using system ; '' is commented in a program , then int type should not be able to use . But still int type can be used . My question is , from where these types are coming from ? <code> //using System ; class Program { static void Main ( ) { int x = 0 ; // it still work , though int is under System namespace , why ? ? } } | In C # where does the key words come from if `` using system '' is commented ? |
C_sharp : I am building a POC application using the new MIP SDK on C # . One of the requirements is to use username/password stored on the server . All the example applications are using OAuth2 login with a popup window for user credentials input.I believe that properly implementing the IAuthDelegate may help , but in-line documentation was not of much help.in my engine init method I am following the SDK exampleand the AuthDelegateImplementation having following codeThanks for your help , C . <code> var authDelegate = new AuthDelegateImplementation ( appInfo ) ; //Initialize and instantiate the File Profile //Create the FileProfileSettings object var profileSettings = new FileProfileSettings ( path : `` mip_data '' , useInMemoryStorage : true , authDelegate : authDelegate , consentDelegate : new ConsentDelegateImplementation ( ) , applicationInfo : appInfo , minimumLogLevel : LogLevel.Trace ) ; Console.WriteLine ( `` Load the Profile async and wait for the result '' ) ; var fileProfile = Task.Run ( async ( ) = > await MIP.LoadFileProfileAsync ( profileSettings ) ) .Result ; public string AcquireToken ( Identity identity , string authority , string resource ) { AuthenticationContext authContext = new AuthenticationContext ( authority ) ; AuthenticationResult result = authContext.AcquireTokenAsync ( resource : resource , clientId : _appInfo.ApplicationId , redirectUri : new Uri ( redirectUri ) , parameters : new PlatformParameters ( PromptBehavior.Auto , null ) , userId : UserIdentifier.AnyUser ) .Result ; return result.AccessToken ; } | Microsoft Information Protection SDK : using username/password to login |
C_sharp : I 'm new using .NET MVC Web Application . I 'm using the version 4 of Web Application.I 'm developing a page to manage the roles of the simple membership provider , and I want to it be dynamically . To clear what I mean , it would be something like this : Something really simple as that . To do so , I have a complex ViewModel such as this : In my View , I have something like this to display the role names : And , I have a DisplayTemplates Folder , with the AllRoleNames.cshtml file in it , and here is what 's inside ( I 'm not worried about the layout of the page yet ) : So far , so good . It displays the name correctly.But , when I try to press the Save button , the MVC should get the proper names from the html to bind to object Model in my HTTP Post Controller Action : But I get an empty model . ( I 'm just worried to the list of roles name for now , because once I figure out what 's happening with it , I can also figure out what 's happening with my list of UserInRoles object ) .I could find out why the MVC is not binding correctly . It 's because the html generated is something like this : The name attribute is being generated as `` AllRoleNames . [ 0 ] '' when it should be `` AllRoleNames [ 0 ] '' . There is an extra dot there . So , I found this question with a hack proposed by the answer . It could work , but when I tested , I saw that my HtmlFieldPrefix already was without the dot , so of course it did n't work.My question is , why is MVC generating these names with the dots , and is there a way to tell it to generate it correctly ? I hope my question is clear , but if not , I can provide more details.Thanks in advance ! <code> public class UserInRolesModel { public List < string > AllRoleNames { get ; set ; } public List < UserInRoles > UsersInRoles { get ; set ; } public UserInRolesModel ( ) { AllRoleNames = new List < string > ( ) ; UsersInRoles = new List < UserInRoles > ( ) ; } public UserInRolesModel ( List < string > allRoleNames , List < UserInRoles > usersInRoles ) { AllRoleNames = allRoleNames ; UsersInRoles = usersInRoles ; } } public class UserInRoles { public UserInRoles ( string user , List < string > userRoles , IEnumerable < string > allRoleNames ) { User = user ; Roles = SetRoles ( userRoles , allRoleNames ) ; } private List < bool > SetRoles ( List < string > userRoles , IEnumerable < string > allRoleNames ) { return allRoleNames.Select ( userRoles.Contains ) .ToList ( ) ; } public string User { get ; set ; } public List < bool > Roles { get ; set ; } public void UpdateRoles ( List < string > allRoleNames ) { var roleProvider = ( SimpleRoleProvider ) System.Web.Security.Roles.Provider ; var rolesAdded = new List < string > ( ) ; for ( int i = 0 ; i < Roles.Count ; i++ ) { if ( Roles [ i ] ) { rolesAdded.Add ( allRoleNames [ i ] ) ; } } roleProvider.AddUsersToRoles ( new [ ] { User } , rolesAdded.ToArray ( ) ) ; } } < th > < strong > @ Html.DisplayFor ( m = > m.AllRoleNames , `` AllRoleNames '' ) < /strong > < /th > @ model List < string > @ if ( Model ! = null ) { for ( int i = 0 ; i < Model.Count ; i++ ) { @ Html.HiddenFor ( m = > m [ i ] ) @ Html.DisplayFor ( m = > m [ i ] ) } } [ HttpPost ] public ActionResult AdminUsers ( UserInRolesModel model ) { //code to save roles goes here return View ( model ) ; } < input id= '' AllRoleNames__0_ '' name= '' AllRoleNames . [ 0 ] '' type= '' hidden '' value= '' Admin '' > Admin < input id= '' AllRoleNames__1_ '' name= '' AllRoleNames . [ 1 ] '' type= '' hidden '' value= '' Extrator '' > Extrator | Binding issue in a list at a complex model to an mvc application |
C_sharp : The argument to my function f ( ) must implement two different interfaces that are not related to each other by inheritance , IFoo and IBar . I know of two different ways of doing this . The first is to declare an empty interface that inherits from both : This , of course , requires that the classes declare themselves as implementing IFooBar rather than IFoo and IBar separately.The second way is to make f ( ) generic with a constraint : Which of these do you prefer , and why ? Are there any non-obvious advantages or disadvantages to each ? <code> public interface IFooBar : IFoo , IBar { // nothing to see here } public int f ( IFooBar arg ) { // etc . } public int f < T > ( T arg ) where T : IFoo , IBar { // etc . } | C # : Preferred pattern for functions requiring arguments that implement two interfaces |
C_sharp : We are trying to use an IEnumerable as a factory that generates different objects each time we iterate over it . Those should be GC'ed as soon as possible . Note however that we keep a reference to the enumerator so we can call it again . So our program basically looks like this : Looking at that code in the debugger : You can see that when the breakpoint is hit the IEnumerable has a reference to `` CCC '' . This should n't really happen . IEnumerable should only generate an IEnumerator when GetEnumerator is called . Is this expected behavior that IEnumerable can contain state ? <code> public class YieldSpec { public static IEnumerable < string > Strings ( ) { yield return `` AAA '' ; yield return `` BBB '' ; yield return `` CCC '' ; } public void YieldShouldAllowGC ( ) { var e = Strings ( ) ; foreach ( var a in e ) { Console.WriteLine ( a ) ; } } } | When using `` yield '' why does compiler-generated type implement both IEnumerable and IEnumerator |
C_sharp : I 've used try and catch statements as an easy way to keep my code running without things crashing ( I would wrap everything in a big try ) . Recently , I 've wanted to start using try and catch statements more correctly . Here as an example I have questions about : In the above Ninja class , the entire contents of my ThrowShirikin method is contained in a try loop . Since there is only one opportunity for an input error ( in this case , when numberOfShirikins == 0 ) , should n't only the lines of code that check for this be contained in the try loop ? See below : ^But what I have here seems a bit clunky . Any suggestions and input on how I 'm understanding the use of try catch statements ? Thanks ! Edit : Or I could do something like this so the //Throw shirikin code never executes if there is an invalid value for numberOfShirikins ? : <code> public class Ninja { Ninja ( ) { } public void ThrowShirikin ( int numberOfShirikins ) { try { if ( numberOfShirikins == 0 ) { throw new System.ArgumentException ( `` Invalid number of shirikins '' ) ; } //Throw shirikin } catch ( ArgumentException e ) { MessageBox.Show ( e.Message ) ; } } } public class Ninja { Ninja ( ) { } public void ThrowShirikin ( int numberOfShirikins ) { bool errorsExist = false ; try { if ( numberOfShirikins == 0 ) { errorsExist = true ; throw new System.ArgumentException ( `` Invalid number of shirikins '' ) ; } } catch ( ArgumentException e ) { MessageBox.Show ( e.Message ) ; } if ( ! errorsExist ) { //Throw shirikin } } } public class Ninja { Ninja ( ) { } public void ThrowShirikin ( int numberOfShirikins ) { try { if ( numberOfShirikins == 0 ) { throw new System.ArgumentException ( `` Invalid number of shirikins '' ) ; return ; } } catch ( ArgumentException e ) { MessageBox.Show ( e.Message ) ; } //Throw shirikin } } | Question About Where To Position Try And Catch statements |
C_sharp : Is there such a thing as a LINQ Query Provider for querying C # files ? I have a Winforms app that I use to assist me in generating code as well as to supplement Visual Studio 's editing capabilities for existing code . One thing I would like to be able to do is to query a given class to see if a method exists . Or query for a list of classes , or query for classes with a particular type in the method signature , etc.Further , I would love to be able to run the usual CRUDs on said C # files , but I realize that this may be out of scope for this question.SOLVED ! Thanks to the folks who suggested Roslyn , and especially thanks to the code sample provided by Konrad Kokosa below , I was able to get exactly what I needed.First thing you need to do is download the Roslyn DLLs ( I used NuGet ) . Then query away . Here is another example for getting an alphabetized list of all methods in a class : <code> static List < string > GetMethodList ( string filename , string className ) { var syntaxTree = SyntaxTree.ParseFile ( filename ) ; var root = syntaxTree.GetRoot ( ) ; var @ class = root.DescendantNodes ( ) .OfType < ClassDeclarationSyntax > ( ) .FirstOrDefault ( md = > md.Identifier.ValueText.Equals ( className ) ) ; return ( List < string > ) @ class.DescendantNodes ( ) .OfType < MethodDeclarationSyntax > ( ) .ToList ( ) .OrderBy ( m = > m.Identifier.ValueText ) .Select ( m = > m.Identifier.ValueText ) ; } | Is there a LINQ Query Provider for querying C # files ? |
C_sharp : I have two IQueryable collections having this kind of type Collection 1 , with the following Name values : Collection 2 , with the following Name values : What I would like to get is a third collection having Name values from Collections 1 and 2 matched , and if there is no match , than null ( empty ) , so as follows : How is it possible to achieve this with C # , LINQ ? <code> public class Property { public string Name { get ; set ; } } A A A B A B B Result Collection : A AA null A null B B null B | C # Linq full outer join on repetitive values |
C_sharp : I 'm trying to generate a certificate self-signed by a KeyPair stored in Azure KeyVault.My end result is a certificate with an invalid signature : Generating the certificate parameters : Fetching a reference to the Azure KeyVault stored key ( HSM like service ) : The key is successfully retrieved.I then try to generate a ECPublicKeyParameters object with the key 's public data : Next step is generating a certificate signed with the key . I implemented a new ISignatureFactory object that should sign with an external signature function of KeyVault : This is my custom AzureKeyVaultSignatureFactory : Then I convert and write the certificate to a file : What am I doing wrong ? Maybe constructing the ECCurve from X/Y is not enough ? Thanks ! <code> DateTime startDate = DateTime.Now.AddDays ( -30 ) ; DateTime expiryDate = startDate.AddYears ( 100 ) ; BigInteger serialNumber = new BigInteger ( 32 , new Random ( ) ) ; X509V1CertificateGenerator certGen = new X509V1CertificateGenerator ( ) ; X509Name selfSignedCA = new X509Name ( `` CN=Test Root CA '' ) ; certGen.SetSerialNumber ( serialNumber ) ; certGen.SetIssuerDN ( selfSignedCA ) ; //Self Signed certGen.SetNotBefore ( startDate ) ; certGen.SetNotAfter ( expiryDate ) ; certGen.SetSubjectDN ( selfSignedCA ) ; //Create a client connector to Azure KeyVault var keyClient = new Azure.Security.KeyVault.Keys.KeyClient ( vaultUri : new Uri ( `` https : //xxxx.vault.azure.net/ '' ) , credential : new ClientSecretCredential ( tenantId : `` xxxx '' , //Active Directory clientId : `` xxxx '' , //Application id ? clientSecret : `` xxxx '' ) ) ; var x = keyClient.GetKey ( `` key-new-ec '' ) ; //Fetch the reference to the key X9ECParameters x9 = ECNamedCurveTable.GetByName ( `` P-256 '' ) ; Org.BouncyCastle.Math.EC.ECCurve curve = x9.Curve ; var ecPoint = curve.CreatePoint ( new Org.BouncyCastle.Math.BigInteger ( 1 , x.Value.Key.X ) , new Org.BouncyCastle.Math.BigInteger ( 1 , x.Value.Key.Y ) ) ; ECDomainParameters dParams = new ECDomainParameters ( curve , ecPoint , x9.N ) ; ECPublicKeyParameters pubKey = new ECPublicKeyParameters ( ecPoint , dParams ) ; certGen.SetPublicKey ( pubKey ) ; //Setting the certificate 's public key with the fetched one AzureKeyVaultSignatureFactory customSignatureFactory = new AzureKeyVaultSignatureFactory ( 1 ) ; Org.BouncyCastle.X509.X509Certificate cert = certGen.Generate ( customSignatureFactory ) ; public class AzureKeyVaultSignatureFactory : ISignatureFactory { private readonly int _keyHandle ; public AzureKeyVaultSignatureFactory ( int keyHandle ) { this._keyHandle = keyHandle ; } public IStreamCalculator CreateCalculator ( ) { var sig = new CustomAzureKeyVaultDigestSigner ( this._keyHandle ) ; sig.Init ( true , null ) ; return new DefaultSignatureCalculator ( sig ) ; } internal class CustomAzureKeyVaultDigestSigner : ISigner { private readonly int _keyHandle ; private byte [ ] _input ; public CustomAzureKeyVaultDigestSigner ( int keyHandle ) { this._keyHandle = keyHandle ; } public void Init ( bool forSigning , ICipherParameters parameters ) { this.Reset ( ) ; } public void Update ( byte input ) { return ; } public void BlockUpdate ( byte [ ] input , int inOff , int length ) { this._input = input.Skip ( inOff ) .Take ( length ) .ToArray ( ) ; } public byte [ ] GenerateSignature ( ) { //Crypto Client ( Specific Key ) try { //Crypto Client ( Specific Key ) CryptographyClient identitiesCAKey_cryptoClient = new CryptographyClient ( keyId : new Uri ( `` https : //xxxx.vault.azure.net/keys/key-new-ec/xxxx '' ) , credential : new ClientSecretCredential ( tenantId : `` xxxx '' , //Active Directory clientId : `` xxxx '' , //Application id ? clientSecret : `` xxxx '' ) ) ; SignResult signResult = identitiesCAKey_cryptoClient.SignData ( SignatureAlgorithm.ES256 , this._input ) ; return signResult.Signature ; } catch ( Exception ex ) { throw ex ; } return null ; } public bool VerifySignature ( byte [ ] signature ) { return false ; } public void Reset ( ) { } public string AlgorithmName = > `` SHA-256withECDSA '' ; } public object AlgorithmDetails = > new AlgorithmIdentifier ( X9ObjectIdentifiers.ECDsaWithSha256 , DerNull.Instance ) ; } //convert to windows type 2 and get Base64 X509Certificate2 cert2 = new X509Certificate2 ( DotNetUtilities.ToX509Certificate ( cert ) ) ; byte [ ] encoded = cert2.GetRawCertData ( ) ; string certOutString = Convert.ToBase64String ( encoded ) ; System.IO.File.WriteAllBytes ( @ '' test-signed2.cer '' , encoded ) ; //-this is good ! | Invalid signature when creating a certificate using BouncyCastle with an external Azure KeyVault ( HSM ) Key |
C_sharp : Suppose I want to be able to write queries likeWhere < Product > ( t= > t.Version > new Version ( 1,2,0,0 ) ) In Product table I store only Int64 NumVersion field , so Version property is mapped as component , and currently I query it like Where < Product > ( t= > t.Version.NumVersion > new Version ( 1,2,0,0 ) .NumVersion ) In C # I can 1 . Overload comparison operators , 2 . Make it implicitly casted to long like : This will allow me to compare Version objects , but how to make NHibernate understand this and generate proper SQL ? <code> public class Version { public byte Major { get ; set ; } public byte Minor { get ; set ; } public short Build { get ; set ; } public int Revision { get ; set ; } private long NumVersion { //get { } //set { } //Some logic that make Int64 number that represents this verion } } public static implicit operator long ( Version v ) { return v.NumVersion ; } | NHibernate and operator overloading |
C_sharp : I 'm using Tridion 2011 's Event System to perform some additional actions when un-publishing components . I 'm using code found here to publish a related component.I 'm registering my event handler as follows : ... and my handler method is as follows : My problem is that the UnPublishEventArgs.Targets property is an IList < PublishingTarget > , which at runtime turns out to be a List < TargetType > , and I need to get a PublicationTarget object to be able to call PublishEngine.Publish ( ... ) .My question is : is there a way to get the current ( un- ) PublicationTarget from an UnPublish event ? Can anyone offer any help ? <code> EventSystem.Subscribe < Component , UnPublishEventArgs > ( RemoveAndRepublish , EventPhases.Initiated ) ; public void RemoveAndRepublish ( Component cmp , UnPublishEventArgs args , EventPhases phase ) { // ... code to locate related component , and perform required actions ... var instruction = new PublishInstruction ( cmp.Session ) { DeployAt = DateTime.Now , RenderInstruction = new RenderInstruction ( cmp.Session ) { RenderMode = RenderMode.Publish } , ResolveInstruction = new ResolveInstruction ( cmp.Session ) { IncludeComponentLinks = true } , RollbackOnFailure = true , StartAt = DateTime.MinValue } ; var target = args.Targets.FirstOrDefault ( ) ; PublishEngine.Publish ( new [ ] { related } , instruction , new [ ] { target } ) ; } | How to get the ( un- ) PublicationTarget for component UnPublish event in Tridion 2011 ? |
C_sharp : This may be a rather long and involved question . Let me start by saying that I 'm developing in C # and XAML . I want to create a control that stacks the following template : for a sequence of items , in two columns , like so : Notice that they are ordered first by height and then left to right.This is relatively simple to do as a two column grid with a vertical stack panel in each . To me , this is a representation of a sequence of items , so it makes sense to render this as a control that inherits from ItemsControl . How would I go about doing that ? Setting an ItemTemplate seems obvious , everything else escapes me . <code> _____________| || Text || Image || More Text ||___________| ______ ______| | | || 1 | | 2 ||____| | || | |____|| 3 | | || | | 4 || | |____||____| | || | | 5 || 6 | | || | | Create two-column , vertically-stacked columns control for Windows Phone 8 |
C_sharp : Can the compiler or processor reorder the following instructions so that another Thread sees a == 0 and b == 1 ? Assuming int a = 0 , b = 0 ; somewhere . <code> System.Threading.Interlocked.CompareExchange < int > ( ref a , 1 , 0 ) ; System.Threading.Interlocked.CompareExchange < int > ( ref b , 1 , 0 ) ; | .Net CompareExchange reordering |
C_sharp : Sanity-check here . Suppose I start a task but I do n't await it and I do n't store a reference to it . In other words , I just run : Clearly , without keeping a reference to the Task returned by PerformLongOperation ( ) , I have no way of knowing if and when it completes . But suppose that that 's not necessary in certain instances.Is there any danger of garbage collection noticing the task running with no references to it , and cancelling it and cleaning it up ? <code> async Task PerformLongOperation ( ) { await Task.Delay ( 10 * 1000 ) ; Debug.WriteLine ( `` All done ! `` ) ; } void DoSomething ( ) { // Kick off the operation and allow it to complete when it does . PerformLongOperation ( ) ; } | Will a task ever be interrupted by garbage collection if there are no references to it ? |
C_sharp : I 'm a bit confused about the following.Given this class : Why is an InvalidCastException thrown when I try to do the following ? <code> public class SomeClassToBeCasted { public static implicit operator string ( SomeClassToBeCasted rightSide ) { return rightSide.ToString ( ) ; } } IList < SomeClassToBeCasted > someClassToBeCastedList = new List < SomeClassToBeCasted > { new SomeClassToBeCasted ( ) } ; IEnumerable < string > results = someClassToBeCastedList.Cast < string > ( ) ; foreach ( var item in results ) { Console.WriteLine ( item.GetType ( ) ) ; } | C # .net casting question |
C_sharp : Recentelly I found an issue that at the beginning did n't appeared so dubious . Let me start by describing the big picture of my environment : I have a domain model respecting the Table Module architecture that consumes a data access layer written using Entity Framework 6.x . My application is a windows forms application , both domain model and data access layer runs on client and I am using .NET 4.0 ( fortunatelly , EF 6 is still compatible with .NET 4.0 ) My goal : Create a cache of commmon nomenclators that are commonly used in combo boxes / lookups . This cache will be refreshed on demand by our users ( there is a button on the right of every control that presents a nomenclator that can refresh the cache ) . So far , so good . I 've started to write this cache . In just a few words , my cache consists of a collection of TableCaches < T > instances and each of them is able to get a List from memory or from database ( if something has been changed ) . Next , imagine that you have a business like this : In my mind an ideea started to grow : What if I can do a trick so that my `` Container '' sometimes gives fake collections , collections found in my cache ? . But here I found the biggest issue : The .NET compiler does something tricky at compile time : It checks whether your collections are IQueriable < OfSomething > . If true , it burns inside IL code calls to extention methods that deals with expression tree like calls , otherwise it will simple call LINQ to Objects extention methods . I also tried ( just for research purposes ) this : and wrote in my module : Why I 've tried this ? I just hoped that the runtime will emit correct MSIL extention methods calls whenever it sees that the generic type parameters are actually IQueryable < T > . But unfortunatelly this naive try proved me that I forgot some of the deep things related to how CLR and .NET compiler works . I remembered that in .NET world , you should expect compilation in two steps : step 1 is the normal compilation that contains also syntactic sugar resolution ( type inference is resolved , anonymous types are generated , anonymous functions are transformed into real methods on some anonymous types or maybe on our types , etc . ) . Unfortunatelly for me , in this category are found all LINQ expressions.The second step is found at runtime , when CLR does some additional MSIL code emition from various reasons : A new generic type gets emitted , Expression trees are compiled , user code creates new types / methods at runtime , etc . The last thing I 've tried is ... I said OK I will treat all collections as IQueryable . The nice thing is that no matter what you will do ( database calls or in memory calls ) the compiler will emit calls to Expression trees LINQ extention methods . It works BUT it is veeeeery slow because in the end the expression gets compiled every time ( even for in memory collections ) . The code is below : In the end , I wrote the code below that works but.. damn it , I duplicate my code ! ! ! What should I do ? . I also know that EF does make a cache but the lifetime is short ( only for the lifetime of your context instance ) and it 's not at query level but only at row level . Correct me if I am wrong ! Thanks in advance . <code> public class PersonsModule { public List < Person > GetAllByCityId ( int cityId ) { using ( var ctx = new Container ( ) ) { return ( from p in ctx.Persons join addr in ctx.Addresses on p.AddressId equals addr.Id where addr.CityId == cityId select p ) .ToList ( ) ; } } } public class Determinator < TCollectionTypePersons , TCollectionTypeAddresses > where TCollectionTypePersons : IEnumerable < Person > where TCollectionTypeAddresses : IEnumerable < Address > { public List < Person > GetInternal ( TCollectionTypePersons persons , TCollectionTypeAddresses addresses , int cityId ) { return ( from p in persons join addr in addresses on p.AddressId equals addr.Id where addr.CityId == cityId select p ) .ToList ( ) ; } } public class PersonsModule { private ICache _cache ; public PersonsModule ( ICache cache ) { _cache = cache ; } public PersonsModule ( ) { } public List < Person > GetAllByCityId ( int cityId ) { if ( _cache == null ) { using ( var ctx = new Container ( ) ) { var determinator = new Determinator < IQueryable < Person > , IQueryable < Address > > ( ) ; return determinator.GetInternal ( ctx.Persons , ctx.Addresses , cityId ) ; } } else { var determinator = new Determinator < IEnumerable < Person > , IEnumerable < Address > > ( ) ; return determinator.GetInternal ( _cache.Persons , _cache.Addresses , cityId ) ; } } } public class PersonsModuleHelper { private IQueryable < Person > _persons ; private IQueryable < Address > _addresses ; public PersonsModuleHelper ( IEnumerable < Person > persons , IEnumerable < Address > addresses ) # # Heading # # { _persons = persons.AsQueryable ( ) ; _addresses = addresses.AsQueryable ( ) ; } private List < Person > GetPersonsByCityId ( int cityId ) { return ( from p in _persons join addr in _addresses on p.AddressId equals addr.Id where addr.CityId == cityId select p ) .ToList ( ) ; } } public class PersonsModuleHelper { private bool _usecache ; private IEnumerable < Person > _persons ; private IEnumerable < Address > _addresses ; public PersonsModuleHelper ( bool useCache , IEnumerable < Person > persons , IEnumerable < Address > addresses ) { _usecache = useCache ; _persons = persons ; _addresses = addresses ; } private List < Person > GetPersonsByCityId ( int cityId ) { if ( _usecache ) { return GetPersonsByCityIdUsingEnumerable ( cityId ) ; } else { return GetPersonsByCityIdUsingQueriable ( cityId , _persons.AsQueryable ( ) , _addresses.AsQueryable ( ) ) ; } } private List < Person > GetPersonsByCityIdUsingEnumerable ( int cityId ) { return ( from p in _persons join addr in _addresses on p.AddressId equals addr.Id where addr.CityId == cityId select p ) .ToList ( ) ; } private List < Person > GetPersonsByCityIdUsingQueriable ( int cityId , IQueryable < Person > persons , IQueryable < Address > addresses ) { return ( from p in persons join addr in addresses on p.AddressId equals addr.Id where addr.CityId == cityId select p ) .ToList ( ) ; } } | Caching domain model data |
C_sharp : In Visual Studio Professional 2010 whenever I type the following : It automatically changes to : Is there a way to make it not do this ? `` Object '' does not have the properties of the object I want to anonymously create . <code> new { new object { | Visual Studio Professional 2010 : Stop `` new { `` from autocompleting into `` new object { `` ( C # ) |
C_sharp : I have a C # program that has a list that does writes and reads in separate threads . The write is user initiated and can change the data at any random point in time . The read runs in a constant loop . It does n't matter if the read is missing data in any given loop , as long as the data it does receive is valid and it get 's the new data in a future loop.After considering ConcurrentBag , I settled on using locks for a variety of reasons ( simplicity being one of them ) . After implementing the locks , a coworker mentioned to me that using temporary references to point to the old List in memory would work just as well , but I am concerned about what will happen if the new assignment and the reference assignment would happen at the same time . Q : Is the temporary reference example below thread safe ? Update : User input provides a list of strings which are used in DoStuff ( ) . You can think of these strings as a definition of constants and as such the strings need to be persisted for future loops . They are not deleted in DoStuff ( ) , only read . UserInputHandler is the only thread that will ever change this list and DoStuff ( ) is the only thread that will ever read from this list . Nothing else has access to it.Additionally , I am aware of the the Concurrent namespace and have used most of the collections in it in other projects , but , I have chosen not to use them here because of extra code complexity that they add ( i.e . ConcurrentBag does n't have a simple Clear ( ) function , etc. ) . A simple lock is good enough in this situation . The question is only whether the second example below is thread safe . LockReference <code> static List < string > constants = new List < string > ( ) ; //Thread Apublic void UserInputHandler ( List < string > userProvidedConstants ) { lock ( items ) { items.Clear ( ) ; foreach ( var constant in userProvidedConstants ) { constants.Add ( constant ) ; } } } //Thread Bpublic void DoStuff ( ) { lock ( items ) { //Do read only actions with items here foreach ( var constant in constants ) { //readonly actions } } } static List < string > constants = new List < string > ( ) ; //Thread Apublic void UserInputHandler ( List < string > userProvidedConstants ) { lock ( items ) { items = new List < string > ( ) ; foreach ( var constant in userProvidedConstants ) { constants.Add ( constant ) ; } } } //Thread Bpublic void DoStuff ( ) { var constantsReference = constants ; //Do read only actions with constantsReference here foreach ( var constant in constantsReference ) { //readonly actions } } | Thread Safety : Lock vs Reference |
C_sharp : When I use asp-controller and asp-action in a < a > tag for another Action than the current , in a View called by a Controller Method with a [ Route ] attribute , the generated link have an empty href attribute.In the Controller : In the View : Generated html : As you can see , the first link is not generated correctly . All of the links that target another Action than the currenct Action are generated with an empty href tag.When I remove the [ Route ] attribute of the ShowSection action : As you can see , the links are correctly generated.How can I fix this while keeping my [ Route ] attributes ( or with an alternative ) ? <code> public class ForumController : Controller { [ Route ( `` [ action ] / { sectionId : int } '' ) ] public async Task < IActionResult > ShowSection ( int sectionId ) { //some code } } < a asp-controller= '' Forum '' asp-action= '' Index '' > Index < /a > < a asp-controller= '' Forum '' asp-action= '' ShowSection '' asp-route-sectionId= '' @ Model.ParentSection.Id '' > @ Model.ParentSection.Name < /a > < a href= '' '' > Index < /a > < a href= '' /ShowSection/1 '' > Général < /a > < a href= '' /Forum '' > Index < /a > < a href= '' /Forum/ShowSection ? sectionId=1 '' > Général < /a > | Strange behaviour between tag-helpers and Route attribute in asp.net 5 MVC6 |
C_sharp : I am facing a problem in which I need to transform dates in a given input format into a target one . Is there any standard way to do this in C # ? As an example say we have yyyy.MM.dd as the source format and the target format is MM/dd/yyy ( current culture ) .The problem arises since I am using a parsing strategy that gives priority to the current culture and then if it fails it tries to parse from a list of known formats . Now say we have two equivalent dates one in the source culture above ( 2015.12.9 ) and the other in the current culture ( 9/12/2015 ) . Then if we attempt to parse this two dates the month will be 12 for the first case and in the second will be 9 , so we have an inconsistency ( they were supposed to mean be the same exact date ) . I believe that if existing it should be something as Any ideas ? EDIT : Thank you all for your ideas and suggestions , however the interpretation most of you gave to my question was not quite right . What most of you have answered is a direct parse in the given format and then a conversion to the CurrentCulture . This will still return 12 as month , although it is in the CurrentCulture format . My question thus was , is there any standard way to transform the date in yyyy.MM.d to the format MM/dd/yyy so that the month is now in the correct place and THEN parsed it in the target culture . Such function is likely to be unexisting . <code> DateTime.Convert ( 2015.12.9 , 'yyyy/MM/dd ' , CultureInfo.CurrentCulture ) . DateTime.ParseExact ( `` 2015.12.9 '' , `` yyyy.MM.dd '' , CultureInfo.CurrentCulture ) | Transform between datetime formats |
C_sharp : I have some classes in C # which I would like to use them in pipelines , I 've seen articles about it but I have n't been able to do it yet.Here 's how I am using it right now : And I want to be able to use it like this with pipelines : Here are my C # classes : And I am struggling to make these function available to call in the pipeline form.I also added a comment like call this method in pipeline before each comment that I need to call . <code> $ suite = [ MyProject.SuiteBuilder ] : :CreateSuite ( 'my house ' ) $ houseSet = $ suite.AddSet ( 'doors ' , 'These represents doors ' ) $ houseSet.AddOption ( 'blue ' , 'kitchen ' ) $ houseSet.AddOption ( 'black ' , 'bedreoom ' ) $ houseSet.AddOption ( 'white ' , 'toilet ' ) $ suite = [ MyProject.SuiteBuilder ] : :CreateSuite ( 'my house ' ) $ suite | AddSet ( 'doors ' , 'These represents doors ' ) ` | AddOption ( 'blue ' , 'kitchen ' ) ` | AddOption ( 'black ' , 'bedreoom ' ) ` | AddOption ( 'white ' , 'toilet ' ) //SuiteBuilder.cspublic static class SuiteBuilder { public static Suite CreateTestSuite ( string name ) { return new Suite ( name ) ; } } //Suite.cspublic class Suite : PSCmdlet { public string Name { get ; set ; } public IEnumerable < Set > Sets { get ; set ; } public Suite ( string name ) { Name = name ; Sets = new List < Set > ( ) ; } // call this method in pipeline public Set AddSet ( string type , string description ) { Sets.Add ( new Set ( type , description ) ) ; return Sets.Last ( ) ; } } //Set.cspublic class Set : PSCmdlet { public string Type { get ; set ; } public string Description { get ; set ; } public IEnumerable < Option > Options { get ; set ; } public Set ( string type , string description ) { Type = type ; Description = description ; Options = new List < Option > ( ) ; } // call this method from pipeline public Set AddOption ( string color , string place ) { Options.Add ( new Option ( color , place ) ) ; return this ; } } //option.cspublic class Option : PSCmdlet { public string Color { get ; set ; } public string Place { get ; set ; } public Option ( string color , string place ) { Color = color ; Place = place ; } } | Create PowerShell Cmdlets in C # - Pipeline chaining |
C_sharp : Can someone tell me the difference the following two LINQ statements please ? andChkUnique ! = null returns false for the top one when a match can not be found and true for the latter and I ca n't figure out why this is happening.I 'm new to LINQ so I could have missed something really basic but its driving me nuts at the moment . <code> var ChkUnique = DB.BusinessFile.FirstOrDefault ( c = > c.ROCNo == txtBoxID.Text ) ; var ChkUnique = from c in DB.BusinessFile where c.ROCNo == ( string ) txtBoxID.Text select c ; | LINQ - Different syntax style , different result ? |
C_sharp : Recently , in a book i read this code . Can you define the means of this code and how this code works . <code> int i = 0 ; for ( ; i ! = 10 ; ) { Console.WriteLine ( i ) ; i++ ; } | How this looping works in c # |
C_sharp : Why does System.Convert has ToDateTime that accepts DateTime ? The method documentation states the value remain unchanged . <code> //// Summary : // Returns the specified System.DateTime object ; no actual conversion is performed.//// Parameters : // value : // A date and time value.//// Returns : // value is returned unchanged.public static DateTime ToDateTime ( DateTime value ) ; | Why does System.Convert has ToDateTime that accepts DateTime ? |
C_sharp : There are a lot of questions on SO lamenting the fact that Code Analysis rule CA2000 is being applied possibly too rigorously by VS2010 , but I seem to have run into a case where it should be applied , but isn't.Consider the following code : Now if I run Code Analysis in Visual Studio 2010 on this , it will complain about newImage not being disposed ( easy fix , put it in another using block ) , but it does n't complain about srcImage ( which also has a Dispose ( ) method that I 'm never calling ) . Does anyone know why Code Analysis does n't complain here ? <code> Image srcImage = Image.FromFile ( source ) ; Bitmap newImage = new Bitmap ( newWidth , newHeight ) ; using ( Graphics gr = Graphics.FromImage ( newImage ) ) { gr.DrawImage ( srcImage , new Rectangle ( 0 , 0 , newWidth , newHeight ) ) ; } newImage.Save ( destination , ImageFormat.Jpeg ) ; | Why does Bitmap cause rule CA2000 , but Image does not ? |
C_sharp : I have a method that takes a generic parameter T. Internally , to decide what other methods to call , I need to know ( without constraining it ) if that parameter is a List or just something.How do I do that ? I 've been using but that feels like a dirty approach . What 's cleaner ? <code> var isList = typeof ( T ) .Name.ToLower ( ) .Contains ( `` list ` 1 '' ) ; | Is my generic type a list , or just an item ? |
C_sharp : After reading this article & that article - I got confused.It says : If there are two methods at different levels of the hierarchy , the `` deeper '' one will be chosen first , even if it is n't a `` better function member '' for the call.Also - It turns out that if you override a base class method in a child class , that does n't count as declaring it.Now let 's go back to my question : Case 1OK.According to the article `` deeper '' one will be chosen first , even if it is n't a `` better function . and it does n't count the override ... So it is right and the program emits `` 3 '' . ( Foo ( object x ) is executed ) Let 's change line order of 1 line : Case 2Now it emits `` 2 '' .Now lets change all int to object and all object to int : Case 3Questions : Question # 1 : in case 2 , Child inherited the Foo ( object x ) from its father AND he also overrides a method . but didnt we just say that : It turns out that if you override a base class method in a child class , that does n't count as declaring it ? ? ? in fact , we didnt also declared the inherited function ... so what is the rule here in this situation ? Question # 2 : in case 3 , Child inherited the Foo ( int x ) from its father AND he also overrides a method . but now , he chooses its father function ... .it seems like override is winning only if it has exact match.again , what is the rule here in this situation ? <code> public class Base { public virtual void Foo ( int x ) { `` 1 '' .Dump ( ) ; } } public class Child : Base { public void Foo ( object x ) { `` 3 '' .Dump ( ) ; } public override void Foo ( int x ) { `` 2 '' .Dump ( ) ; } } void Main ( ) { Child c = new Child ( ) ; c.Foo ( 10 ) ; //emits 3 } public class Base { public virtual void Foo ( int x ) { `` 1 '' .Dump ( ) ; } public void Foo ( object x ) { `` 3 '' .Dump ( ) ; } // < line being moved here } public class Child : Base { public override void Foo ( int x ) { `` 2 '' .Dump ( ) ; } } void Main ( ) { Child c = new Child ( ) ; c.Foo ( 10 ) ; //emits 2 ! ! ! ! } public class Base { public virtual void Foo ( object x ) { `` 1 '' .Dump ( ) ; } public void Foo ( int x ) { `` 3 '' .Dump ( ) ; } } public class Child : Base { public override void Foo ( object x ) { `` 2 '' .Dump ( ) ; } } void Main ( ) { Child c = new Child ( ) ; c.Foo ( 1 ) ; //emits `` 3 '' } | Overloading across inheritance boundaries in c # ? |
C_sharp : We are using BasicHttpBinding in a service and also we have set the concurrency mode to multiple and instance context mode to single like belowWe have consumed this service in console through reference . We are having an issue that after some time we are seeing messages are pilled in IIS worker process.For example - > In 1 minute , it is showing as only one thread in worker process in IIS but after some time we are seeing multiple request in IIS ? Could anyone help here like why after some time we are seeing messages queued up in IIS ? Below is binding in config <code> [ ServiceBehavior ( InstanceContextMode=InstanceContextMode.Single , ConcurrencyMode =ConcurrencyMode.Multiple ) ] public class Service1 : IService1 < binding name= '' BasicHttpBinding_Common '' closeTimeout= '' 00:10:00 '' openTimeout= '' 00:10:00 '' receiveTimeout= '' 00:10:00 '' sendTimeout= '' 00:10:00 '' allowCookies= '' false '' bypassProxyOnLocal= '' false '' | Requests are piling up in WCF IIS server |
C_sharp : Are there any way to turn of the autoformatting of C # code that is inlined inside HTML when making a MVC application ? It seems that it use the C # Text Editor settings for the inline code as well , but I do n't want to use the same formatting inside the HTML file as the normal code files.For example , if I write < % somecodehere { % > , then some HTML in between , and then I put the < % } % > at the end , Visual Studio automatically reformats the code to this : For the MVC code , I think it looks much tidyer like thisBut I do n't see how to change this without messing up the formatting for my normal code files . <code> < % using ( Html.BeginForm ( ) ) { % > ... < % } % > < % using ( Html.BeginForm ( ) ) { % > ... < % } % > | Autoformating of inline code in MVC |
C_sharp : Ok , I must be doing something dumb , but should n't this work ? I have following three lists : Each list has the proper values and count . I can return any one of these lists : And I can return a any two of these lists : However , when I try to return all three : I get the exception : Unable to create a constant value of type 'Entity.TPM_VIEWS ' . Only primitive types or enumeration types are supported in this context.What am I doing wrong ? All three values are indeed enumerable . Mostly , I 'm asking this question because it 's the best possible way to guarantee I 'll notice the problem 30 seconds after posting.UPDATE : I 'm 93 % sure the problem is here : This looks like an enumerable list of TPM_VIEWS object , and I can call ToList ( ) on it and get the correct data , but it does n't play well with the other lists.UPDATE 2 : This actually works . Points to the person who can tell me why ! <code> var commonViews = ( from v in context.TPM_VIEWS where v.VIEWID < 0 select v ) ; // IQueryable < TPM_VIEWS > var ownedViews = ( from v in context.TPM_VIEWS where v.OWNERID == userId & & v.VIEWID > 0 select v ) ; // IQueryable < TPM_VIEWS > var sharedViews = ( from v in context.TPM_USER.Include ( `` TPM_VIEWS2 '' ) where v.USERID == userId select v ) .First ( ) .TPM_VIEWS2 ; // EntityCollection < TPM_VIEWS > return commonViews.ToList ( ) ; return commonViews.Concat ( ownedViews ) .ToList ( ) ; return commonViews.Concat ( ownedViews ) .Concat ( sharedViews ) .ToList ( ) ; var sharedViews = ( from v in context.TPM_USER.Include ( `` TPM_VIEWS2 '' ) where v.USERID == userId select v ) .First ( ) .TPM_VIEWS2 ; commonViews.ToList ( ) .Concat ( ownedViews.ToList ( ) ) .Concat ( sharedViews.ToList ( ) ) .ToList ( ) ; | Concatenating three lists into one with LINQ throws an exception |
C_sharp : I 'm reading some examples and i keep seeing code with [ SOMETHING ] before methods and I 'd like to know what that 's called and how it 's used . Can you define you own [ SOMETHING ] or is there a defined list of these things ? Here 's some code examples I found that use this thing but do n't explain anything about it.Sometimes they even put parameters in it too like [ HandleError ( Order = 2 ) ] Whats going on here . I feel like this is SUPER important but none of the reference books I 've read explain it they just use them.Thanks ahead of time . <code> [ HandleError ] public class HomeController : Controller { public ActionResult Index ( ) { ViewData [ `` Message '' ] = `` Welcome to ASP.NET MVC ! `` ; return View ( ) ; } public ActionResult About ( ) { return View ( ) ; } } | .NET MVC 3 semantics |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.