lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I have a class defined like this : But when I serialize it , `` version '' does n't show up in the attribute ( while `` action '' does ) .What 's going wrong ?
[ XmlRoot ( ElementName= '' request '' ) ] public class Request { # region Attributes [ XmlAttribute ( AttributeName = `` version '' ) ] public string Version { get { return `` 1.0 '' ; } } [ XmlAttribute ( AttributeName = `` action '' ) ] public EAction Action { get ; set ; } # endregion
C # Xml why does n't my attribute appears ?
C#
Suppose I have a method which changes the state of an object , and fires an event to notify listeners of this state change : The event handlers may throw an exception even if IncreaseCounter successfully completed the state change . So we do not have strong exception safety here : The strong guarantee : that the operation has either completed successfully or thrown an exception , leaving the program state exactly as it was before the operation started.Is it possible to have strong exception safety when you need to raise events ?
public class Example { public int Counter { get ; private set ; } public void IncreaseCounter ( ) { this.Counter = this.Counter + 1 ; OnCounterChanged ( EventArgs.Empty ) ; } protected virtual void OnCounterChanged ( EventArgs args ) { if ( CounterChanged ! = null ) CounterChanged ( this , args ) ; } public event EventHandler CounterChanged ; }
Can I have strong exception safety and events ?
C#
I 've just started experimenting with CodeContracts in .NET 4 on an existing medium-sized project , and I 'm surprised that the static checker is giving me compile-time warnings about the following piece of code : Why is the CodeContracts static checker complaining about the strs.Add ( ... ) line ? There 's no possible way for strs to be null , right ? Am I doing something wrong ?
public class Foo { private readonly List < string > strs = new List < string > ( ) ; public void DoSomething ( ) { // Compiler warning from the static checker : // `` requires unproven : source ! = null '' strs.Add ( `` hello '' ) ; } }
CodeContracts - false positives
C#
I have the following expression : When I perform a split as follows : Then it gives me three entries : Why does it give an empty line as the third entry and how can I avoid this ?
`` < p > What ? < /p > \n < pre > Starting Mini < /pre > '' var split = content .Split ( new [ ] { `` < pre > '' , `` < /pre > '' } , StringSplitOptions.None ) ; `` < p > What ? < /p > \n '' '' Starting Mini '' '' ''
Why does C # split give me an array ending in an empty line ?
C#
I 'm new to COBOL and I have been trying to read record information from a text file that is an output from the table.Most non-comp data-types i 'm okay with , it 's the 'COMP ' ones i 'm getting stuck on.I 've been trying to figure this out all day today reading as much as I can on this.The date fields below are the ones I ca n't convert to a date-string : From my understanding all those types above are going to be 4 bytes each in the file . They are supposed to be dates that should represent YYMMDD , but the data just does n't seem to be as small as that . I 've looked into EBCDIC and reversing the byte [ ] data and using BitConverter.ToUNIT32 ( ) and changing the Encoding used to read the file with no luck.I read that dates that are computed into an integer are stored as the number of days from Jan 1st 1601 , hence why code below is trying to add the value to 1601 . ( http : //www.techtricky.com/cobol-date-functions-list-add-find-duration/ ) My issue is that the either the data from the text file just is n't right or i 'm missing a step to get what should be a date similar to YYMMDD.The data for the 3 above are as follows : And how i 'm opening the file , I 've changed the encoding to ascii with no luck : Code used to try and read the COMP fields : Is the data malformed ? Or am i missing something ? UPDATEThe task i 'm trying to accomplish is to replicate a COBOL program that transforms the data from one definition into another but in CSV format , as the program outputs a .dat file.SourceMy inexperienced interpretation of the source definition is that the data in the text file is either a PUA-ICGROUP or PUA-PUGROUP . Looking at the COBOL program it chooses PUA-ICGROUP when PUA-HEADER > PUA-KEY > PUA-RTYPE = `` 03 '' , everything else is PUA-PUGROUP.DefinitionOutput DefinitionPROGRAMBelow is a small extract of what the cobol program is doing to the dates regardless of weather their source is COMP or not . ( i did not write this code ) . it seems to be trying to fix the 2kY issue.Program Working-Storage SectionThe DATACopied from Notepad++ , each line starts at '220 ... ' and end column is 135 before going onto next line , meaning length is 134 ( ? ) Noticed that above is missing some symbols : Update 2I 've acepted Rick Smith 's answer below as when i put his data in i get the correct date-time values . So either my data is fudged or its somthing else as my data throws errors or date-time values 1000s of years in the future.I 've been able to get the ouput CSV of what these date time should actually be which are : [ using : int n = ( ( b [ 0 ] < < 16 ) + ( b [ 1 ] < < 8 ) + b [ 2 ] ) ; ] Update 3turns out it was bad data ...
05 VALDATE PIC 9 ( 6 ) COMP05 PAYDATE PIC 9 ( 6 ) COMP05 SYSDATE PIC 9 ( 6 ) COMP [ 32 ] [ 237 ] [ 44 ] [ 4 ] | 00100000 11101101 00101100 00000100 [ 33 ] [ 14 ] [ 32 ] [ 237 ] | 00100001 00001110 00100000 11101101 [ 131 ] [ 48 ] [ 48 ] [ 48 ] | 10000011 00110000 00110000 00110000 using ( BinaryReader reader = new BinaryReader ( File.Open ( nFilePath , FileMode.Open ) , Encoding.Default ) ) public class DateFromUIntExtractor : LineExtractor { public DateFromUIntExtractor ( ) : base ( 4 ) { } public override string ExtractText ( BinaryReader nReader ) { // e.g 32,237,44,44 , included but commented out things i 've tried byte [ ] data = nReader.ReadBytes ( Length ) ; // Length = 4 //Array.Reverse ( data ) ; - Makes num = 552414212 //data = ConvertAsciiToEbcdic ( data ) ; int num = BitConverter.ToUInt32 ( data , 0 ) ; // in this example num = 70053152 DateTime date = new DateTime ( 1601,1,1 ) ; date = date.AddDays ( num ) ; // Error : num is too big Extract = date.ToString ( `` yyyyMMdd '' ) ; return Extract ; } } C-WRITE-START . IF PUA-RTYPE = 3 THEN PERFORM C-WRITE-A ELSE PERFORM C-WRITE-B END-IF.C-WRITE-EXIT . EXIT . 01 DLRPUARC . 03 PUA-HEADER . 05 PUA-KEY . 07 PUA-CDELIM PIC 99 . 07 PUA-SUPNO PIC 9 ( 7 ) . 07 PUA-RTYPE PIC 99 . 07 PUA-REF PIC 9 ( 9 ) . 07 PUA-SEQ PIC 999 . 05 PUA-ALTKEY . 07 PUA-ACDELIM PIC 99 . 07 PUA-ASUPNO PIC 9 ( 7 ) . 07 PUA-ATRNDATE PIC 9 ( 6 ) . 07 PUA-ARTYPE PIC 99 . 07 PUA-AREF PIC 9 ( 9 ) . 07 PUA-ASEQ PIC 999 . 05 FILLER PIC X ( 82 ) . 03 PUA-ICGROUP REDEFINES PUA-HEADER . 05 FILLER PIC X ( 52 ) . 05 PUA-ICEXTREF PIC X ( 10 ) . 05 PUA-ICORDNO PIC 9 ( 11 ) . 05 PUA-ICVALDATE PIC 9 ( 6 ) COMP . 05 PUA-ICPAYDATE PIC 9 ( 6 ) COMP . 05 PUA-ICSYSDATE PIC 9 ( 6 ) COMP . 05 PUA-ICTRNVAL PIC S9 ( 9 ) . 05 PUA-ICCLRREF PIC 9 ( 6 ) . 05 PUA-ICDELDATE PIC 9 ( 6 ) COMP . 05 PUA-ICOTHQRY PIC X . 05 PUA-ICPRCQRY PIC X . 05 PUA-ICMRSQRY PIC X . 05 PUA-ICDSCTYPE PIC 9 . 05 PUA-ICDSCVAL PIC S9 ( 9 ) COMP . 05 PUA-ICVATCODE PIC 9 . 05 PUA-ICVATAMT PIC S9 ( 8 ) COMP . 05 PUA-ICTAXAMT PIC S9 ( 8 ) COMP . 05 PUA-ICMRSREF PIC 9 ( 6 ) . 05 PUA-ICSUBDIV PIC 9 . 05 PUA-ICCOSTCTR PIC X ( 5 ) . 05 PUA-ICSEQIND PIC X . 05 FILLER PIC X ( 4 ) . 03 PUA-PUGROUP REDEFINES PUA-HEADER . 05 FILLER PIC X ( 52 ) . 05 PUA-PUEXTREF PIC X ( 10 ) . 05 PUA-PUORDNO PIC 9 ( 11 ) . 05 PUA-PUVALDATE PIC 9 ( 6 ) COMP . 05 FILLER PIC XXX . 05 PUA-PUSYSDATE PIC 9 ( 6 ) COMP . 05 PUA-PUTRNVAL PIC S9 ( 9 ) . 05 PUA-PUCLRREF PIC 9 ( 6 ) . 05 PUA-PUDELDATE PIC 9 ( 6 ) COMP . 05 PUA-PUOTHQRY PIC X . 05 PUA-PUSUBDIV PIC 9 . 05 FILLER PIC X ( 32 ) . 01 OUT-A-REC . 03 OUT-A-PUA-CDELIM PIC 99 . 03 OUT-A-PUA-SUPNO PIC 9 ( 7 ) . 03 OUT-A-PUA-RTYPE PIC 99 . 03 OUT-A-PUA-REF PIC 9 ( 9 ) . 03 OUT-A-PUA-SEQ PIC 999 . 03 OUT-A-PUA-ATRNDATE PIC 9 ( 8 ) . 03 OUT-A-PUA-ICEXTREF PIC X ( 10 ) . 03 OUT-A-PUA-ICORDNO PIC 9 ( 11 ) . 03 OUT-A-PUA-ICVALDATE PIC 9 ( 8 ) . 03 OUT-A-PUA-ICPAYDATE PIC 9 ( 8 ) . 03 OUT-A-PUA-ICSYSDATE PIC 9 ( 8 ) . 03 OUT-A-PUA-ICTRNVAL PIC S9 ( 9 ) SIGN LEADING SEPARATE . 03 OUT-A-PUA-ICCLRREF PIC 9 ( 6 ) . 03 OUT-A-PUA-ICDELDATE PIC 9 ( 8 ) . 03 OUT-A-PUA-ICOTHQRY PIC X . 03 OUT-A-PUA-ICPRCQRY PIC X . 03 OUT-A-PUA-ICMRSQRY PIC X . 03 OUT-A-PUA-ICDSCTYPE PIC 9 . 03 OUT-A-PUA-ICDSCVAL PIC S9 ( 9 ) SIGN LEADING SEPARATE . 03 OUT-A-PUA-ICVATCODE PIC 9 . 03 OUT-A-PUA-ICVATAMT PIC S9 ( 8 ) SIGN LEADING SEPARATE . 03 OUT-A-PUA-ICTAXAMT PIC S9 ( 8 ) SIGN LEADING SEPARATE . 03 OUT-A-PUA-ICMRSREF PIC 9 ( 6 ) . 03 OUT-A-PUA-ICSUBDIV PIC 9 . 03 OUT-A-PUA-ICCOSTCTR PIC X ( 5 ) . 03 OUT-A-PUA-ICSEQIND PIC X . 03 OUT-A-CTRL-M PIC X . 03 OUT-A-NL PIC X.FD F-OUTPUTB LABEL RECORDS OMITTED.01 OUT-B-REC . 03 OUT-B-PUA-CDELIM PIC 99 . 03 OUT-B-PUA-SUPNO PIC 9 ( 7 ) . 03 OUT-B-PUA-RTYPE PIC 99 . 03 OUT-B-PUA-REF PIC 9 ( 9 ) . 03 OUT-B-PUA-SEQ PIC 999 . 03 OUT-B-PUA-ATRNDATE PIC 9 ( 8 ) . 03 OUT-B-PUA-PUEXTREF PIC X ( 10 ) . 03 OUT-B-PUA-PUORDNO PIC 9 ( 11 ) . 03 OUT-B-PUA-PUVALDATE PIC 9 ( 8 ) . 03 OUT-B-PUA-PUSYSDATE PIC 9 ( 8 ) . 03 OUT-B-PUA-PUTRNVAL PIC S9 ( 9 ) SIGN LEADING SEPARATE . 03 OUT-B-PUA-PUCLRREF PIC 9 ( 6 ) . 03 OUT-B-PUA-PUDELDATE PIC 9 ( 8 ) . 03 OUT-B-PUA-PUOTHQRY PIC X . 03 OUT-B-PUA-PUSUBDIV PIC 9 . 03 OUT-B-CTRL-M PIC X . 03 OUT-B-NL PIC X . IF PUA-ATRNDATE IS ZERO THEN MOVE ZERO TO OUT-A-PUA-ATRNDATEELSE MOVE PUA-ATRNDATE TO W-DATE-6DIGIT MOVE W-DATE-SEG1 TO W-DATE-YY MOVE W-DATE-SEG2 TO W-DATE-MM MOVE W-DATE-SEG3 TO W-DATE-DD IF W-DATE-YY > 50 THEN MOVE `` 19 '' TO W-DATE-CC ELSE MOVE `` 20 '' TO W-DATE-CC END-IF MOVE W-DATE-CCYYMMDD TO OUT-A-PUA-ATRNDATEEND-IF.MOVE PUA-ICEXTREF TO OUT-A-PUA-ICEXTREF.MOVE PUA-ICORDNO TO OUT-A-PUA-ICORDNO.IF PUA-ICVALDATE IS ZERO THEN MOVE ZERO TO OUT-A-PUA-ICVALDATEELSE MOVE PUA-ICVALDATE TO W-DATE-6DIGIT MOVE W-DATE-SEG1 TO W-DATE-YY MOVE W-DATE-SEG2 TO W-DATE-MM MOVE W-DATE-SEG3 TO W-DATE-DD IF W-DATE-YY > 50 THEN MOVE `` 19 '' TO W-DATE-CC ELSE MOVE `` 20 '' TO W-DATE-CC END-IF MOVE W-DATE-CCYYMMDD TO OUT-A-PUA-ICVALDATEEND-IF . 01 W-DATE-6DIGIT PIC 9 ( 6 ) .01 W-DATE-6DIGIT-REDEF REDEFINES W-DATE-6DIGIT . 03 W-DATE-SEG1 PIC 99 . 03 W-DATE-SEG2 PIC 99 . 03 W-DATE-SEG3 PIC 99.01 W-DATE-CCYYMMDD PIC 9 ( 8 ) .01 W-DATE-CCYYMMDD-REDEF REDEFINES W-DATE-CCYYMMDD . 03 W-DATE-CC PIC 99 . 03 W-DATE-YY PIC 99 . 03 W-DATE-MM PIC 99 . 03 W-DATE-DD PIC 99 . 2200010010300005463400022000100106062003000054634000062703 09720200000 í , ! íƒ00056319D001144ÕšNNN0 1 G¨ 000000197202G 2200010010300005463500022000100106062903000054635000062858 09720200000 í , í '' íƒ00082838 { 050906±RNNN0 1 áð 000000197202G 2200010010300005465500022000100106073003000054655000063378 09720200000 í í† í00179637A050906±RNNN0 1 000000197202G 2200010010300005463400022000100106062003000054634000062703 09720200000 í , [ EOT ] ! [ SO ] íƒ00056319D001144 [ SOH ] ÕšNNN0 1 [ SOH ] G¨ 000000197202G 2200010010300005463500022000100106062903000054635000062858 09720200000 í , í '' íƒ00082838 { 050906 [ SOH ] ±RNNN0 1 [ SOH ] áð 000000197202G 2200010010300005465500022000100106073003000054655000063378 09720200000 í í† í00179637A050906 [ SOH ] ±RNNN0 1 [ EOT ] [ NAK ] [ EM ] 000000197202G HEX : 0x20 0xED 0x2CBIN : 32 237 44INT : 2157868 ( longer than 6 digit ) Actual DATE : 2006-07-16HEX : 0x04 0x21 0x0eBIN : 4 33 14INT : 270606 ( correct but segments are in reverse ) Actual DATE : 2006-06-27HEX : 0x20 0xED 0x83BIN : 32 237 131INT : 2157955 ( longer than 6 digits ) Actual DATE : 2006-08-03
Read COBOL COMP data in C #
C#
I am Working on Xamarin.iOS.In the TableView . I am bind the Cell with Button.For Button Click I am doing Subscribe and Unsubscribe Cell event by below codethis is not working fine when I call data api again and set to the TableView.Explanation : When I open ViewController first time cell button click event fire 1 time . And I open it second time it will fire cell button click event 2 time . I am using upper code for subscribe and unsubscribe button event then why it will called multiple time.this issue i am facing in iOS 11.2First Way : Source Class full codeInside ViewController I use thatSecond wayBut this method is called multiple times if I open the ViewController a second time .
cell.btn_Click.Tag = indexPath.Row ; cell.btn_Click.TouchUpInside -= BtnClickEvent ; cell.btn_Click.TouchUpInside += BtnClickEvent ; class StockListSourceClass : UITableViewSource { private List < PacketAndPacketDetailItem > stockLists ; private List < string > serialNoList ; private UINavigationController navigationController ; public static event EventHandler BtnClickEvented ; public StockListSourceClass ( List < PacketAndPacketDetailItem > stockLists , List < string > serialNolist , UINavigationController navigationController ) { this.stockLists = stockLists ; this.serialNoList = serialNolist ; this.navigationController = navigationController ; } public override UITableViewCell GetCell ( UITableView tableView , NSIndexPath indexPath ) { StockTableViewCell cell = tableView.DequeueReusableCell ( StockTableViewCell.Key ) as StockTableViewCell ? ? StockTableViewCell.Create ( ) ; var item = stockLists [ indexPath.Row ] ; if ( serialNoList.Contains ( item.SerialNo ) ) cell.BindData ( item , true ) ; else cell.BindData ( item , false ) ; cell.SelectionStyle = UITableViewCellSelectionStyle.None ; cell.PreservesSuperviewLayoutMargins = false ; cell.SeparatorInset = UIEdgeInsets.Zero ; cell.LayoutMargins = UIEdgeInsets.Zero ; cell.SetNeedsLayout ( ) ; cell.LayoutIfNeeded ( ) ; cell.btn_Click.Tag = indexPath.Row ; cell.btn_Click.TouchUpInside -= BtnClickEvent ; cell.btn_Click.TouchUpInside += BtnClickEvent ; cell.btn_Click.TouchUpInside += ( sender , e ) = > { var imageName = ( ( UIButton ) sender ) .TitleLabel.Text ; if ( imageName.Equals ( `` unchecked '' ) ) { ( ( UIButton ) sender ) .SetBackgroundImage ( UIImage.FromBundle ( `` checked '' ) , UIControlState.Normal ) ; ( ( UIButton ) sender ) .TitleLabel.Text = `` checked '' ; } else { ( ( UIButton ) sender ) .SetBackgroundImage ( UIImage.FromBundle ( `` unchecked '' ) , UIControlState.Normal ) ; ( ( UIButton ) sender ) .TitleLabel.Text = `` unchecked '' ; } } ; return cell ; } public void BtnClickEvent ( object sender , EventArgs e ) { var row = ( ( UIButton ) sender ) .Tag ; MarketSheetViewController.RowNo = ( int ) row ; if ( BtnClickEvented ! = null ) { BtnClickEvented ( stockLists [ ( int ) row ] .SerialNo , EventArgs.Empty ) ; } } public override nint RowsInSection ( UITableView tableview , nint section ) { return stockLists.Count ; } public override void RowSelected ( UITableView tableView , NSIndexPath indexPath ) { var storyboard = UIStoryboard.FromName ( `` Main '' , null ) ; var webController = storyboard.InstantiateViewController ( `` PacketDetailViewController '' ) as PacketDetailViewController ; webController.item = stockLists [ indexPath.Row ] ; this.navigationController.PushViewController ( webController , true ) ; } } StockListSourceClass.BtnClickEvented += ( sender , e ) = > { if ( ! ( serialNoList.Contains ( stockLists [ RowNo ] .SerialNo ) ) ) serialNoList.Add ( stockLists [ RowNo ] .SerialNo ) ; else serialNoList.Remove ( stockLists [ RowNo ] .SerialNo ) ; SetUpperPanelData ( ) ; } ; cell.btn_Click.TouchUpInside += ( sender , e ) = > { var imageName = ( ( UIButton ) sender ) .TitleLabel.Text ; if ( imageName.Equals ( `` unchecked '' ) ) { ( ( UIButton ) sender ) .SetBackgroundImage ( UIImage.FromBundle ( `` checked '' ) , UIControlState.Normal ) ; ( ( UIButton ) sender ) .TitleLabel.Text = `` checked '' ; } else { ( ( UIButton ) sender ) .SetBackgroundImage ( UIImage.FromBundle ( `` unchecked '' ) , UIControlState.Normal ) ; ( ( UIButton ) sender ) .TitleLabel.Text = `` unchecked '' ; } var row = ( ( UIButton ) sender ) .Tag ; MarketSheetViewController.RowNo = ( int ) row ; if ( BtnClickEvented ! = null ) { BtnClickEvented ( stockLists [ ( int ) row ] .SerialNo , EventArgs.Empty ) ; } } ;
Subscribe and Unsubscribe cell button Click event is not Working in iOS 11
C#
I have a simple test code that works as expected in .NET3.5 , but the same code behaves completely different on a project created with .NET4.5.1.First of all , the weird thing is that the NullReferenceException type exception is completely ignored in .NET4.5.1 when running the compiled RELEASE exe file . Basically , no error is thrown , although in debug mode the exception is thrown.Second of all ( and most importantly ) , if the error is different than NullReferenceException , such as “ index out of range ” for example , then the exception is actually thrown as expected , but the “ finally ” block is never hit which is not the behavior I expected from the try-catch-finally block . I tried in different machines , and had 2 other colleagues of mine also trying and we all got the same result.It seems that either I never really understood the try-catch-finally block , or .NET4.5.1 handles exception in a different way , or there is some bug with .NET4.5.1 . All I know is that the code above works in .NET3.5 as I expected it to work , but I don ’ t seem to get the same result when running it in .NET4.5.1 .Can someone shed some light on this ? I am at a total loss right now.EDITBased on Eric J answer I was able to resolve the NullReferenceException issue . Since I asked 2 questions , I 'll create a new thread for the second question.Try-Catch-Finally block problems with .NET4.5.1
class Program { static void Main ( string [ ] args ) { try { string a = null ; var x = a.Length ; } catch ( Exception ex ) { throw ; } finally { Console.WriteLine ( `` This is the finally block . `` ) ; } Console.WriteLine ( `` You should not be here if an exception occured ! `` ) ; } }
Try-Catch-Finally block issues with .NET4.5.1
C#
Should this regex pattern throw an exception ? Does for me.The error is : parsing `` ^\d { 3 } [ a '' - Unterminated [ ] set.I feel dumb . I do n't get the error . ( My RegexBuddy seems okay with it . ) A little more context which I hope does n't cloud the issue : I am writing this for a CLR user defined function in SQL Server : Setting it up withAnd testing it with :
^\d { 3 } [ a-z ] [ Microsoft.SqlServer.Server.SqlFunction ( IsDeterministic=true ) ] public static SqlChars Match ( SqlChars input , SqlString pattern , SqlInt32 matchNb , SqlString name , SqlBoolean compile , SqlBoolean ignoreCase , SqlBoolean multiline , SqlBoolean singleline ) { if ( input.IsNull || pattern.IsNull || matchNb.IsNull || name.IsNull ) return SqlChars.Null ; RegexOptions options = RegexOptions.IgnorePatternWhitespace | ( compile.Value ? RegexOptions.Compiled : 0 ) | ( ignoreCase.Value ? RegexOptions.IgnoreCase : 0 ) | ( multiline.Value ? RegexOptions.Multiline : 0 ) | ( singleline.Value ? RegexOptions.Singleline : 0 ) ; Regex regex = new Regex ( pattern.Value , options ) ; MatchCollection matches = regex.Matches ( new string ( input.Value ) ) ; if ( matches.Count == 0 || matchNb.Value > ( matches.Count-1 ) ) return SqlChars.Null ; Match match = matches [ matchNb.Value ] ; int number ; if ( Int32.TryParse ( name.Value , out number ) ) { return ( number > ( match.Groups.Count - 1 ) ) ? SqlChars.Null : new SqlChars ( match.Groups [ number ] .Value ) ; } else { return new SqlChars ( match.Groups [ name.Value ] .Value ) ; } } CREATE FUNCTION Match ( @ input NVARCHAR ( max ) , @ pattern NVARCHAR ( 8 ) , @ matchNb INT , @ name NVARCHAR ( 64 ) , @ compile BIT , @ ignoreCase BIT , @ multiline BIT , @ singleline BIT ) RETURNS NVARCHAR ( max ) AS EXTERNAL NAME [ RegEx ] . [ UserDefinedFunctions ] . [ Match ] GO SELECT dbo.Match ( N'123x45.6789 ' -- @ input , N'^\d { 3 } [ a-z ] ' -- @ pattern,0 -- @ matchNb,0 -- @ name,0 -- @ compile,1 -- @ ignoreCase,0 -- @ multiline,1 -- @ singleline )
Should this regex pattern throw an exception ?
C#
SetPartitions method accepts an array of prime numbers such as 2 , 3 , 5 , 2851 , 13.In the above example , it should assign : How to implement the logic ?
public int Partition1 { get ; set ; } public int Partition1 { get ; set ; } private void SetPartitions ( List < int > primeNumbers ) { this.Partition1 = // get the product of the prime numbers closest to 10000 this.Partition2 = // get the product of the remaining prime numbers } this.Partition1 = 2851 * 3 ; // which is 8553 and closest possible to 10000this.Partition2 = 2 * 5 * 13 ;
How to find out the closest possible combination of some given prime numbers to 10000 ?
C#
I 'm trying to use the SearchBox control introduced in Windows 8.1 , but I ca n't figure out how to display the image in the result suggestions . The suggestions appear , but the space where the image should be remains blank : Here 's my XAML : And my code behind : Am I missing something ? Some extra details : I tried to debug it with XAML Spy ; each suggestion ListViewItem has its Content set to an instance of Windows.ApplicationModel.Search.Core.SearchSuggestion . On these SearchSuggestion objects , I noticed that the Text , Tag , DetailText , and ImageAlternateText properties are set to their correct value , but the Image property is null ... EDIT : So apparently AppendResultSuggestion accepts only an instance of RandomAccessStreamReference , not any other implementation of IRandomAccessStreamReference . I think this is a bug , since it 's inconsistent with what is conveyed by the method signature . I filed it on Connect , please vote for it if you want it fixed !
< SearchBox SuggestionsRequested= '' SearchBox_SuggestionsRequested '' / > private async void SearchBox_SuggestionsRequested ( SearchBox sender , SearchBoxSuggestionsRequestedEventArgs args ) { var deferral = args.Request.GetDeferral ( ) ; try { var imageUri = new Uri ( `` ms-appx : ///test.png '' ) ; var imageRef = await StorageFile.GetFileFromApplicationUriAsync ( imageUri ) ; args.Request.SearchSuggestionCollection.AppendQuerySuggestion ( `` test '' ) ; args.Request.SearchSuggestionCollection.AppendSearchSeparator ( `` Foo Bar '' ) ; args.Request.SearchSuggestionCollection.AppendResultSuggestion ( `` foo '' , `` Details '' , `` foo '' , imageRef , `` Result '' ) ; args.Request.SearchSuggestionCollection.AppendResultSuggestion ( `` bar '' , `` Details '' , `` bar '' , imageRef , `` Result '' ) ; args.Request.SearchSuggestionCollection.AppendResultSuggestion ( `` baz '' , `` Details '' , `` baz '' , imageRef , `` Result '' ) ; } finally { deferral.Complete ( ) ; } }
Image not shown for result suggestions in SearchBox
C#
I use C # , .NET 4.5 , Console application.I added WSDL file in service reference . Inside WSDL are validation rules like : There is XSD file too , with details of validation rules like : And I have automatically generated properties from WSDL in Reference.cs like : I serialize xRequest object into XML and I want to validate it.How can I validate XML with XSD , when part of validation rules are in WSDL ?
< xs : complexType name= '' xRequest '' > < xs : sequence > < xs : element name= '' SenderDateTime '' type= '' ip : grDateTime '' / > < xs : element name= '' SenderId '' type= '' ip : grIdentifier '' / > < /xs : sequence > < /xs : complexType > < xs : simpleType name= '' grDateTime '' > < xs : restriction base= '' xs : dateTime '' > < xs : pattern value= '' [ 0-9 ] { 4,4 } \- [ 0-9 ] { 2,2 } \- [ 0-9 ] { 2,2 } [ T ] [ 0-9 ] { 2,2 } : [ 0-9 ] { 2,2 } : [ 0-9 ] { 2,2 } ( \ . [ 0-9 ] { 1,6 } ) { 0,1 } '' / > < /xs : restriction > < /xs : simpleType > public partial class xRequest { private string senderIdField ; [ System.Xml.Serialization.XmlElementAttribute ( Form=System.Xml.Schema.XmlSchemaForm.Unqualified , Order=1 ) ] public string SenderId { get { return this.senderIdField ; } set { this.senderIdField = value ; this.RaisePropertyChanged ( `` SenderId '' ) ; } } }
How validate XML with XSD , when part of validation rules are in WSDL
C#
It has been a while since I 'd understood covariance , but should n't this compile ? Anything bar can return is also an IMyInterface . What seems to be the problem ?
public void Foo < T > ( Func < T > bar ) where T : IMyInterface { Func < IMyInterface > func = bar ; }
Covariance , delegates and generic type constraints
C#
I surfed into this site a few days ago on `` Anonymous Recursion in C # '' . The thrust of the article is that the following code will not work in C # : The article then goes into some detail about how to use currying and the Y-combinator to get back to `` Anonymous Recursion '' in C # . This is pretty interesting but a tad complex for my everyday coding I am afraid . At this point at least ... I like to see stuff for myself so I opened the Mono CSharp REPL and entered that line . No errors . So , I entered fib ( 8 ) ; . Much to my great surprise , it worked ! The REPL replied back with 21 ! I thought maybe this was some magic with the REPL , so I fired-up 'vi ' , typed in the following program , and compiled it.It built and ran perfectly too ! I am running Mono 2.10 on a Mac . I do not have access to a Windows machine right now so I can not test this on .NET on Windows.Has this been fixed on .NET as well or is this a silent feature of Mono ? The article is a couple of years old.If it is Mono only , I can not wait for the next job interview where they ask me to write a Fibinocci function in the language of my choice ( Mono C # ) where I have to provide the caveat that .NET will not work . Well , actually I can wait since I love my job . Still , interesting ... Update : Mono is not really doing `` anonymous '' recursion as it is using fib as a named delegate . My bad . The fact that the Mono C # compiler assumes a null value for fib before assignment is a bug as noted below . I say `` compiler '' because the .NET CLR would run the resulting assembly just fine even though the .NET C # compiler would not compile the code.For all the interview Nazis out there : can be replaced with an iterative version : You might want to do this because the recursive version is inefficient in a language like C # . Some might suggest using memoization but , since this is still slower than the iterative method , they may just be being wankers . : - ) At this point though , this becomes more of an ad for functional programming than anything else ( since the recursive version is so much nicer ) . It really does not have anything to do with my original question , but some of the answers thought that it was important .
Func < int , int > fib = n = > n > 1 ? fib ( n - 1 ) + fib ( n - 2 ) : n ; using System ; public class Program { public static void Main ( string [ ] args ) { int x = int.Parse ( args [ 0 ] ) ; Func < int , int > fib = n = > n > 1 ? fib ( n - 1 ) + fib ( n - 2 ) : n ; Console.WriteLine ( fib ( x ) ) ; } } Func < int , int > fib = n = > n > 1 ? fib ( n - 1 ) + fib ( n - 2 ) : n ; Func < int , int > fib = n = > { int old = 1 ; int current = 1 ; int next ; for ( int i = 2 ; i < n ; i++ ) { next = current + old ; old = current ; current = next ; } return current ; } ;
Does `` Anonymous Recursion '' work in .NET ? It does in Mono
C#
I have the follow extension method I have been using . I was not aware until recently that EF Core 2.x , by default , performs mixed evaluation , which means that for the things it does n't know how to convert into SQL , it will pull down everything from the database , and then perform the LINQ queries in memory . I have since disabled this behavior . Anyway , here is my extension method : Entity framework then throws an exception ( because I have configured it at this point to do this , instead of take everything from the DB and evaluate locally ) with the following message : Error generated for warning 'Microsoft.EntityFrameworkCore.Query.QueryClientEvaluationWarning : The LINQ expression 'where Not ( Convert ( [ x ] , IDeletable ) .Deleted ) ' could not be translated and will be evaluated locally. ' . This exception can be suppressed or logged by passing event ID 'RelationalEventId.QueryClientEvaluationWarning ' to the 'ConfigureWarnings ' method in 'DbContext.OnConfiguring ' or 'AddDbContext'.This extension method it being used in quite a few places , so I would rather fix if and make it work ( be evaluated at the database ) rather than go and remove it across many projects , then have to replace it with .Where ( x = > ! x.Deleted ) .Has anyone else ran into this and know how to make an IQueryable extension that is evaluated at the Database ( converted to SQL at run time ) ? It seems that perhaps EF is looking at only the concrete class when it comes to converting LINQ to SQL ? UPDATE : One of the comments asked for an example . Doing some additional testing , I can see that this is when applied to an IQueryable returned from EF Core 's .FromSql . If .NonDeleted ( ) is applied directly on the entity Organization , it seems to work correctly.// Repository layer
public static class RepositoryExtensions { public static IQueryable < T > NonDeleted < T > ( this IQueryable < T > queryable ) where T : IDeletable { return queryable.Where ( x = > ! x.Deleted ) ; } } // Service layerpublic class OrganizationService { public IEnumerable < Data.Entities.Organization > GetAllForUser ( int ? userId ) { return _repository.GetOrganizationsByUserId ( userId.GetValueOrDefault ( ) ) .NonDeleted ( ) ; } } using PrivateNameSpace.Common.EntityFramework ; using PrivateNameSpace.Data.DbContext ; using PrivateNameSpace.Data.Repos.Interfaces ; using Microsoft.EntityFrameworkCore ; using System.Data.SqlClient ; using System.Linq ; public class OrganizationRepository : Repository < Entities.Organization , int , OrganizationContext > , IOrganizationRepository { private const string storedProcedure = `` dbo.sproc_organizations_by_userid '' ; public OrganizationRepository ( OrganizationContext context ) : base ( context ) { DbSet = Context.Organizations ; } public IQueryable < Entities.Organization > GetOrganizationsByUserId ( int userId ) { var sql = $ '' { Sproc } @ UserId '' ; var result = Context.Organizations.FromSql ( sql , new SqlParameter ( `` @ UserId '' , userId ) ) ; return result ; } }
EF Core 2.x - IQueryable extension is getting evaluated at the client and not the database
C#
What could be the purpose of the tilde in this code block ? ^ Operator ( C # Reference ) Visual Studio 2010Binary ^ operators are predefined for the integral types and bool . For integral types , ^ computes the bitwise exclusive-OR of its operands . For bool operands , ^ computes the logical exclusive-or of its operands ; that is , the result is true if and only if exactly one of its operands is true.~ Operator ( C # Reference ) Visual Studio 2010The ~ operator performs a bitwise complement operation on its operand , which has the effect of reversing each bit . Bitwise complement operators are predefined for int , uint , long , and ulong.The ~ ( tilde ) operator performs a bitwise complement on its single integer operand . ( The ~ operator is therefore a unary operator , like ! and the unary - , & , and * operators . ) Complementing a number means to change all the 0 bits to 1 and all the 1s to 0sWhat would be a reason why it would be used in this context ( as opposed to simply excluding it ) ?
public override int GetHashCode ( ) { return ~this.DimensionId.Id ^ this.ElementId.Id ; }
What is the purpose of the tilde in this situation ?
C#
Is it possible in C # ( I 'm using .Net 4.5 , but asking more generally ) to determine if two implementations of a generic type are functionally equivalent ? As an example of the need , suppose I have an IMapper interface defined as : My ideal implementation of this is : This would be functionally equivalent to : but the compiler ( rightly ) recognizes these as different types . Is there a way I can tell the compiler to treat these two types as equivalent ( and perhaps even interchangeable ) ? I 've also looked at this : but I found that I ca n't properly identify an abstraction so that I can inject ( into constructors , etc . ) the concrete class without creating a `` middle-man '' interface : I think the `` middle-man '' approach is more `` correct '' , but I 'd prefer not to create a superfluous type . Also , it still carries the problem where swapping the type arguments creates two different , yet functionally equivalent , types.Is there a better way to achieve my goal ?
public interface IMapper < TTo , TFrom > { TTo MapFrom ( TFrom obj ) ; TFrom MapFrom ( TTo obj ) ; } public class MyMapper : IMapper < A , B > { A MapFrom ( B obj ) { ... } B MapFrom ( A obj ) { ... } } public class MyEquivalentMapper : IMapper < B , A > { B MapFrom ( A obj ) { ... } A MapFrom ( B obj ) { ... } } public interface ISingleMapper < out TTo , in TFrom > { TTo MapFrom ( TFrom obj ) ; } public class MyAlternateMapper : ISingleMapper < A , B > , ISingleMapper < B , A > { A MapFrom ( B obj ) { ... } B MapFrom ( A obj ) { ... } } public interface IBidirectionalMapper < TTo , TFrom > : ISingleMapper < TTo , TFrom > , ISingleMapper < TFrom , TTo > { TTo MapFrom ( TFrom obj ) ; TFrom MapFrom ( TTo obj ) ; } public class MyAlternateMapper : IBidirectionalMapper < A , B > { A MapFrom ( B obj ) { ... } B MapFrom ( A obj ) { ... } }
Determine type equivalence
C#
Consider this codeI 'm just taking my database type and converting to MailMessage.It get 's sent in another function . Code analysis tells me I 'm not disposing `` msg '' which is correct . But if I do it here - I get exception when I 'm trying to send it.Also , it complains about not disposing MemoryStream here : msg.Attachments.Add ( new Attachment ( new MemoryStream ( attachment.Data ) , attachment.Name ) ) ; I have no idea on how to properly dispose it . I tried different things but was getting exceptions when sending mail saying `` Stream is closes ''
private MailMessage GetMailMessageFromMailItem ( Data.SystemX.MailItem mailItem ) { var msg = new MailMessage ( ) ; foreach ( var recipient in mailItem.MailRecipients ) { var recipientX = Membership.GetUser ( recipient.UserKey ) ; if ( recipientX == null ) { continue ; } msg.To.Add ( new MailAddress ( recipientX.Email , recipientX.UserName ) ) ; } msg.From = new MailAddress ( ConfigurationManager.AppSettings [ `` EmailSender '' ] , ConfigurationManager.AppSettings [ `` EmailSenderName '' ] ) ; msg.Subject = sender.UserName ; if ( ! string.IsNullOrEmpty ( alias ) ) msg.Subject += `` ( `` + alias + `` ) '' ; msg.Subject += `` `` + mailItem.Subject ; msg.Body = mailItem.Body ; msg.Body += Environment.NewLine + Environment.NewLine + `` To reply via Web click link below : '' + Environment.NewLine ; msg.Body += ConfigurationManager.AppSettings [ `` MailPagePath '' ] + `` ? AID= '' + ContextManager.AccountId + `` & RUN= '' + sender.UserName ; if ( mailItem.MailAttachments ! = null ) { foreach ( var attachment in mailItem.MailAttachments ) { msg.Attachments.Add ( new Attachment ( new MemoryStream ( attachment.Data ) , attachment.Name ) ) ; } } return msg ; }
Code analysis complains I 'm not disposing objects . What is wrong here ?
C#
i am new to this and i am creating simple application in which i click a button and a notification on desktop should be displayed . i am doing this in windows form c # the error is `` NullReferenceException was unhandledi have one button Notify in form1 . i have tried this : form1.cscode for HTMLPage1.html : even if i simply put alert ( `` Hi '' ) in notifyMe ( ) function , nothing else . still it displays the same error .
public Form1 ( ) { InitializeComponent ( ) ; this.Load += new EventHandler ( Form1_Load ) ; webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler ( webBrowser1_DocumentCompleted ) ; webBrowser1.ScriptErrorsSuppressed = true ; } private void btnNotify_Click ( object sender , EventArgs e ) { webBrowser1.Document.InvokeScript ( `` notifyMe '' ) ; } private void Form1_Load ( object sender , EventArgs e ) { string CurrentDirectory = Directory.GetCurrentDirectory ( ) ; webBrowser1.Navigate ( Path.Combine ( CurrentDirectory , '' HTMLPage1.html '' ) ) ; } private void webBrowser1_DocumentCompleted ( object sender , WebBrowserDocumentCompletedEventArgs e ) { webBrowser1.ObjectForScripting = this ; < html lang= '' en '' xmlns= '' http : //www.w3.org/1999/xhtml '' > < head > < meta charset= '' utf-8 '' / > < title > < /title > < script language= '' javascript '' type= '' text/javascript '' > document.addEventListener ( 'DOMContentLoaded ' , function ( ) { if ( Notification.permission ! == `` granted '' ) Notification.requestPermission ( ) ; } ) ; function notifyMe ( ) { if ( ! Notification ) { alert ( 'Desktop notifications not available in your browser . Try Chromium . ' ) ; return ; } if ( Notification.permission ! == `` granted '' ) Notification.requestPermission ( ) ; else { var notification = new Notification ( 'Notification title ' , { icon : 'http : //cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png ' , body : `` Hey there ! You 've been notified ! `` , } ) ; notification.onclick = function ( ) { window.open ( `` http : //stackoverflow.com/a/13328397/1269037 '' ) ; } ; } } < /script > < /head > < body > < /body > < /html >
desktop notification using javascript in windows form
C#
I am able to get faces from Live Web Cam as a list of Windows.Media.FaceAnalysis DetectedFace objects . Now I would like to pass these faces to Microsoft Cognitive Services API to detect faces and get the face attributes . How can I do this ?
IList < DetectedFace > faces = null ; // Create a VideoFrame object specifying the pixel format we want our capture image to be ( NV12 bitmap in this case ) .// GetPreviewFrame will convert the native webcam frame into this format.const BitmapPixelFormat InputPixelFormat = BitmapPixelFormat.Nv12 ; using ( VideoFrame previewFrame = new VideoFrame ( InputPixelFormat , ( int ) this.videoProperties.Width , ( int ) this.videoProperties.Height ) ) { await this.mediaCapture.GetPreviewFrameAsync ( previewFrame ) ; // The returned VideoFrame should be in the supported NV12 format but we need to verify this . if ( FaceDetector.IsBitmapPixelFormatSupported ( previewFrame.SoftwareBitmap.BitmapPixelFormat ) ) { faces = await this.faceDetector.DetectFacesAsync ( previewFrame.SoftwareBitmap ) ; // Now pass this faces to Cognitive services API // faceClient.DetectAsync } }
How to detect face attributes using Microsoft Cognitive service by providing Windows.Media.FaceAnalysis DetectedFace list ?
C#
What Am I missing ? Error 2 Argument 1 : can not convert from 'System.Func ' to 'System.Collections.Generic.IComparer ' Error 1 The best overloaded method match for 'System.Collections.Generic.List.Sort ( System.Collections.Generic.IComparer ) ' has some invalid argumentsWhen I haveit works fine . Are they not the same thing ?
List < bool > test = new List < bool > ( ) ; test.Sort ( new Func < bool , bool , int > ( ( b1 , b2 ) = > 1 ) ) ; private int func ( bool b1 , bool b2 ) { return 1 ; } private void something ( ) { List < bool > test = new List < bool > ( ) ; test.Sort ( func ) ; }
About list sorting and delegates & lambda expressions Func stuff
C#
I 'm trying to implement undo functionality with C # delegates . Basically , I 've got an UndoStack that maintains a list of delegates implementing each undo operation . When the user chooses Edit : Undo , this stack pops off the first delegate and runs it . Each operation is responsible for pushing an appropriate undo delegate unto the stack . So suppose I have a method called `` SetCashOnHand . '' It looks like this : So this method constructs an undo delegate , does the operation , and ( assuming it succeeds ) pushes the undo delegate onto the UndoStack . ( UndoStack is smart enough that if undoStack.Push is called in the context of an undo , the delegate goes on the redo stack instead . ) My trouble is that it 's a little annoying to `` cache '' this.cashOnHand into the coh variable . I wish I could just write this : But of course that wo n't get the present value of cashOnHand ; it defers looking up the value until the delegate is called , so the code winds up doing nothing . Is there any way I can `` dereference '' cashOnHand when constructing the delegate , other than stuffing the value into a local variable like coh ? I 'm not really interested in hearing about better ways to do Undo . Please think of this as a generic question about delegates , with Undo just the example to make the question more clear .
public void SetCashOnHand ( int x ) { int coh = this.cashOnHand ; undo u = ( ) = > this.setCashOnHand ( coh ) ; this.cashOnHand = x ; undoStack.Push ( u ) ; } undo u = ( ) = > this.setCashOnHand ( this.cashOnHand ) ;
C # Lambdas : How *Not* to Defer `` Dereference '' ?
C#
UPDATE : the next version of C # has a feature under consideration that would directly answer this issue . c.f . answers below.Requirements : App data is stored in arrays-of-structs . There is one AoS for each type of data in the app ( e.g . one for MyStruct1 , another for MyStruct2 , etc ) The structs are created at runtime ; the more code we write in the app , the more there will be.I need one class to hold references to ALL the AoS 's , and allow me to set and get individual structs within those AoS'sThe AoS 's tend to be large ( 1,000 's of structs per array ) ; copying those AoS 's around would be a total fail - they should never be copied ! ( they never need to ! ) I have code that compiles and runs , and it works ... but is C # silently copying the AoS 's under the hood every time I access them ? ( see below for full source ) Notes : I need to ensure C # sees this as an array of value-types , instead of an array of objects ( `` do n't you DARE go making an array of boxed objects around my structs ! '' ) . As I understand it : Generic T [ ] ensures that ( as expected ) I could n't figure out how to express the type `` this will be an array of structs , but I ca n't tell you which structs at compile time '' other than System.Array . System.Array works -- but maybe there are alternatives ? In order to index the resulting array , I have to typecast back to T [ ] . I am scared that this typecast MIGHT be boxing the Array-of-Structs ; I know that if it were ( T ) instead of ( T [ ] ) , it would definitely box ; hopefully it does n't do that with T [ ] ? Alternatively , I can use the System.Array methods , which definitely boxes the incoming and outgoing struct . This is a fairly major problem ( although I could workaround it if were the only way to make C # work with Array-of-struct )
public Dictionary < System.Type , System.Array > structArraysByType ; public void registerStruct < T > ( ) { System.Type newType = typeof ( T ) ; if ( ! structArraysByType.ContainsKey ( newType ) ) { structArraysByType.Add ( newType , new T [ 1000 ] ) ; // allowing up to 1k } } public T get < T > ( int index ) { return ( ( T [ ] ) structArraysByType [ typeof ( T ) ] ) [ index ] ; } public void set < T > ( int index , T newValue ) { ( ( T [ ] ) structArraysByType [ typeof ( T ) ] ) [ index ] = newValue ; }
Storing a C # reference to an array of structs and retrieving it - possible without copying ?
C#
I want to do something like this : This does n't work as written ; is there some minimal workaround to make it work ? Basically I want 0 to chain until non-zero ( or end of chain ) .
public override int CompareTo ( Foo rhs ) { return Bar.CompareTo ( rhs.Bar ) ? ? Baz.CompareTo ( rhs.Baz ) ? ? Fuz.CompareTo ( rhs.Fuz ) ? ? 0 ; }
Can I use the coalesce operator on integers to chain CompareTo ?
C#
Possible Duplicate : What is the difference between String.Empty and “ ” Which of the following should I use for assigning an empty string and why ? or
string variableName = `` '' ; string variableName = string.Empty ;
Which should I use for empty string and why ?
C#
I do n't get it . The As operator : Then why does the following work ? Baby is a struct , creating it will put value in stack . There is no reference involve here.There are certainly no nullable types here.Any explanation as to why I 'm wrong ?
struct Baby : ILive { public int Foo { get ; set ; } public int Ggg ( ) { return Foo ; } } interface ILive { int Ggg ( ) ; } void Main ( ) { ILive i = new Baby ( ) { Foo = 1 } as ILive ; // ? ? ? ? ? ? Console.Write ( i.Ggg ( ) ) ; // Output : 1 }
The as operator on structures ?
C#
I have the following class declaration : I have an Html helper method : This is my ASP.NET MVC ascx : When I pass in an IQueryable collection to the ascx , I get this error : Compiler Error Message : CS1928 : 'System.Web.Mvc.HtmlHelper > ' does not contain a definition for 'TagCloud ' and the best extension method overload 'EDN.MVC.Helpers.EdnHelpers.TagCloud ( System.Web.Mvc.HtmlHelper , System.Linq.IQueryable , int , string ) ' has some invalid argumentsIf I try to explicitly convert the object collection with this : I get the same error - the values I 'm passing in are not liked by the compiler.Should n't my EntityTag class automatically be supported as IQueryable ? What am I missing ? It 's got to be something obvious . ( I hope . )
public class EntityTag : BaseEntity , ITaggable public static string TagCloud ( this HtmlHelper html , IQueryable < ITaggable > taggables , int numberOfStyleVariations , string divId ) < % @ Control Language= '' C # '' Inherits= '' System.Web.Mvc.ViewUserControl < IQueryable < EDN.MVC.Models.EntityTag > > '' % > < % @ Import Namespace= '' EDN.MVC.Helpers '' % > < % = Html.TagCloud ( Model , 6 , `` entity-tags '' ) % > public static string TagCloud ( this HtmlHelper html , IQueryable < Object > taggables , int numberOfStyleVariations , string divId ) { var tags = new List < ITaggable > ( ) ; foreach ( var obj in taggables ) { tags.Add ( obj as ITaggable ) ; } return TagCloud ( html , tags.AsQueryable ( ) , numberOfStyleVariations , divId ) ; }
Why does n't c # support an object with an interface as a parameter ?
C#
I was going through a website I 've taken over and came across this section in one of the pages : Apparently anyone who has ever used the site without javascript would not be able to log out properly ( surprisingly enough , this has never come up ) .So the first thing that comes to mind isThen I realized I do n't know why I 'm keeping the javascript call around at all . I 'm just a little confused as to why it would have been written like that in the first place when a regular link would have worked just fine . What benefit does window.location have over just a regular link ? This is also the only place in the website I 've seen something like this done ( so far ) .Edit : The programmer before me was highly competent , which is actually why I was wondering if there was something I was n't taking into account or if he just made a simple oversight .
< a href= '' javascript : window.location= ' < % =GetSignOutUrl ( ) % > ' ; '' > // img < /a > < a href= '' < % =GetSignOutUrl ( ) '' onclick= '' javascript : window.location= ' < % =GetSignOutUrl ( ) % > ' ; '' > // img < /a >
Why use window.location in a hyperlink ?
C#
Here 's an example : In the VS2008 output window this shows : A first chance exception of type 'System.ArgumentException ' occurred in System.Drawing.dll Additional information : Parameter is not valid . ( pic http : //i.imgur.com/nM2oNm1.png ) This is on Windows 7.Documentation herehttps : //msdn.microsoft.com/en-us/library/vstudio/system.drawing.drawing2d.lineargradientbrush.wrapmode ( v=vs.90 ) .aspx confirms LinearGradientBrush.WrapMode accepts a WrapMode `` Gets or sets a WrapMode enumeration that indicates the wrap mode for this LinearGradientBrush . `` and this https : //msdn.microsoft.com/en-us/library/vstudio/system.drawing.drawing2d.wrapmode ( v=vs.90 ) .aspx confirms that WrapMode.Clamp is valid for gradient : '' Clamp The texture or gradient is not tiled . ''
public MainForm ( ) { InitializeComponent ( ) ; LinearGradientBrush brush = new LinearGradientBrush ( new Rectangle ( 0,0,100,100 ) , Color.Blue , Color.White , angle:0 ) ; brush.WrapMode = WrapMode.Tile ; // OK brush.WrapMode = WrapMode.Clamp ; // Causes Unhandled exception alert , offering break }
Why does setting LinearGradientBrush.WrapMode to Clamp fail with ArgumentException ( `` parameter is not valid '' ) ?
C#
I just installed the fresh released Community Edition of Visual Studio 2015 ( RTM ) and I 'm trying to get my open source project working under VS2015 and C # 6.0 . Some of my .cs are shared across projects . This way I 'm able to build both a PCL version ( with limited functionality ) and a 'full ' version of the core library.For some reason however , some code files build properly in the full project , but fail when built in the PCL project ( where everything compiles under C # 5 and Visual Studio 2013 ) . The compiler seems to be unable to resolve a cref in an XML comment when building the PCL version . Here is a simplified code example that fails on my machine : The compile error I 'm getting is : CS1580 Invalid type for parameter Type in XML comment cref attribute : ' Y ( Type ) ' SimpleInjector.PCLWeird thing is though that the IntelliSense support in the XML comments ( Wow ! we have IntelliSense in XML comments now ! ) actually works , and the method Y ( Type ) is selectable through the drop down list . But after selecting this , a compile error is generated ( in PCL only ) .My question of course is how to fix this ? Is this a common problem ? Could project 's configuration have anything to do with this ? Is this a known bug ?
/// < summary > < /summary > public class A { // Compile error on next line : /// < summary > < see cref= '' Y ( Type ) '' / > . < /summary > public void X ( ) { } /// < summary > < /summary > /// < param name= '' x '' > < /param > public void Y ( Type x ) { } /// < summary > < /summary > /// < param name= '' i '' > < /param > public void Y ( int i ) { } }
Visual Studio 2015 / C # 6 / Roslyn ca n't compile XML comments in PCL project
C#
Apologies if this seems a simple question , but I mostly just want to check that the solution I have is the most sensible/holds for all cases.The pre-existing SQL Server database we work with stores a 'period ' as inclusive start - > inclusive end UTC DateTime values . ( Both start & end columns are datetime2 ( 7 ) , automatically-converted to System.DateTime instances of DateTimeKind.UTC before we start working with them ) .So , if I need to store the `` whole day/month/year , given the user 's time-zone '' I need to find `` The last possible instant of a specified LocalDate , in a particular DateTimeZone '' .The methods I have are as follows : I think I also need to avoid ( anywhere else ) mapping a `` end of date '' LocalDateTime using .AtLeniently ( .. ) since if 23:59:59.9999999 is `` skipped '' and does not exist in the target DateTimeZone , then it would be mapped to the next available instant on the 'outer ' side of the gap 00:00:00.000000 , which would give me an exclusive ZonedDateTime value.Amended Methods :
public static LocalDateTime AtEndOfDay ( this LocalDate localDate ) { return localDate .PlusDays ( 1 ) .AtMidnight ( ) .PlusTicks ( -1 ) ; } public static ZonedDateTime AtEndOfDay ( this DateTimeZone zone , LocalDate localDate ) { return zone .AtStartOfDay ( localDate.PlusDays ( 1 ) ) .Plus ( Duration.FromTicks ( -1 ) ) ; } public static LocalDateTime AtEndOfDay ( this LocalDate localDate ) { // TODO : Replace with localDate.At ( LocalTime.MaxValue ) when NodaTime 2.0 is released . return localDate .PlusDays ( 1 ) .AtMidnight ( ) .PlusTicks ( -1 ) ; } public static ZonedDateTime AtEndOfDay ( this DateTimeZone zone , LocalDate localDate ) { return zone .AtStartOfDay ( localDate.PlusDays ( 1 ) ) .Plus ( -Duration.Epsilon ) ; } public static ZonedDateTime AtEndOfDayInZone ( this LocalDate localDate , DateTimeZone zone ) { return zone.AtEndOfDay ( localDate ) ; }
What is the neatest way to find the last possible instant of a LocalDate , in a particular time-zone ?
C#
Consider this basic implementation of the maybe monad : Its purpose is to handle a chain of functions returning optional values in a clean way : In the above case both GetOrder and GetClient return a Maybe < T > , but handling of the None case is hidden inside Bind . So far so good.But how would I bind a Maybe < T > to an async function , i.e . a function returning Task < Maybe < T > > instead ? For instance the following code fails with compiler errors , because Bind expects a Func < T , Maybe < U > > rather than a Func < T , Task < Maybe < U > > > : I tried to await the Task inside the lambda passed to Bind , but that forced me to add an overload of Bind that accepts functions returning a Task : As you can see , the code is not running async anymore , and instead blocks with Result . Meh.Second try was to await the task inside the new Bind : But now Bind has to wrap the Maybe < T > in a Task and chaining will look ugly : Is there a nicer solution to this ? I created a fully working example , in case I missed some details in the explanation .
public class Maybe < T > { private readonly T value ; private Maybe ( bool hasValue , T value ) : this ( hasValue ) = > this.value = value ; private Maybe ( bool hasValue ) = > HasValue = hasValue ; public bool HasValue { get ; } public T Value = > HasValue ? value : throw new InvalidOperationException ( ) ; public static Maybe < T > None { get ; } = new Maybe < T > ( false ) ; public static Maybe < T > Some ( T value ) = > new Maybe < T > ( true , value ) ; public Maybe < U > Bind < U > ( Func < T , Maybe < U > > f ) = > HasValue ? f ( value ) : Maybe < U > .None ; } var client = Maybe < int > .Some ( 1 ) .Bind ( orderId = > GetOrder ( orderId ) ) .Bind ( order = > GetClient ( order.ClientId ) ) ; Console.WriteLine ( client ) ; var client = Maybe < int > .Some ( 1 ) .Bind ( orderId = > GetOrderAsync ( orderId ) ) .Bind ( order = > GetClientAsync ( order.ClientId ) ) ; Console.WriteLine ( client ) ; public Maybe < U > Bind < U > ( Func < T , Task < Maybe < U > > > f ) = > HasValue ? f ( value ) .Result : Maybe < U > .None ; public async Task < Maybe < U > > Bind < U > ( Func < T , Task < Maybe < U > > > f ) = > HasValue ? await f ( value ) : Maybe < U > .None ; var asyncClient = await ( await Maybe < int > .Some ( 2 ) .Bind ( orderId = > GetOrderAsync ( orderId ) ) ) .Bind ( order = > GetClientAsync ( order.ClientId ) ) ;
How do I do a monadic bind to an async function ?
C#
I have an extension method likeAnd I have two classesandI call RemoveDetail from an Action accepted by method public static void Foreach < T > ( this IEnumerable < T > source , Action < T > action ) ; : ReSharper suggest me to replace this call with method group likeThis worked fine in VS2013 and previous but it fails on compilation in VS2015 with 'Principal ' does not contain a definition for 'RemoveDetail ' and no extension method 'RemoveDetail ' accepting a first argument of type 'Principal ' could be found ( are you missing a using directive or an assembly reference ? ) Anyone has a suggestion ? Do I have to update all of the usages and make ReSharper to avoid this replacement ?
public static void RemoveDetail < TMaster , TChild > ( this TMaster master , TChild child ) where TMaster : class , IMaster < TChild > where TChild : class , IDetail < TMaster > ; public class Principal : IMaster < Permission > { public virtual IEnumerable < Permission > Permissions { get ; } } public class Permission : IDetail < Principal > aPrincipal.Permissions.Foreach ( x = > aPrincipal.RemoveDetail ( x ) ) ; aPrincipal.Permissions.Foreach ( aPrincipal.RemoveDetail ) ;
Visual Studio 2015 extension method call as method group
C#
I have a list of objects that have a property Rank . This is an integer.I want to sort by rank on my view but when i do this : i get all of the zeros ( meaning these have n't been set at the top ) I want to order by 1 -- > n but have the zeros be at the bottom of the list.I would like it to be as efficient a sort as possible as the list is quite long
myObjects = myObjects.Orderby ( r= > r.Rank ) ;
How can I sort but put zeros at the bottom ?
C#
I 'm developping a webapplication . For the security of the users information i need a https connection . I 'm developping this local at the moment . I have followed the tutorial on : http : //weblogs.asp.net/dwahlin/archive/2009/08/25/requiring-ssl-for-asp-net-mvc-controllers.aspxWhen I build my project the page loads but the url is : http : // ... In my code i have placed : code from site : What am i missing that the url is n't https based ? Is this because I 'm working local ? Thanks in advance
[ RequiresSSL ] public ActionResult Index ( ) { //var model = Adapter.EuserRepository.GetAll ( ) ; return View ( db.Eusers.ToList ( ) ) ; } using System ; using System.Collections.Generic ; using System.Linq ; using System.Web ; using System.Web.Mvc ; namespace extranet.Helpers { public class RequiresSSL : ActionFilterAttribute { public override void OnActionExecuting ( ActionExecutingContext filterContext ) { HttpRequestBase req = filterContext.HttpContext.Request ; HttpResponseBase res = filterContext.HttpContext.Response ; //Check if we 're secure or not and if we 're on the local box if ( ! req.IsSecureConnection & & ! req.IsLocal ) { var builder = new UriBuilder ( req.Url ) { Scheme = Uri.UriSchemeHttps , Port = 443 } ; res.Redirect ( builder.Uri.ToString ( ) ) ; } base.OnActionExecuting ( filterContext ) ; } } }
How to use https in c # ?
C#
Is it somehow possible to set alternate names for querystring parameters in ASP.NET MVC ? I have this simple controller Index action : Calling http : //mysite.com/mypage/ ? color=yellow works quite nicely , the color parameter automatically picks up its value `` yellow '' from the querystring.But now I would like to have a localized variant of the same page , with “ pretty ” localized parameters , but still working with the same controller method . Example : http : //mysite.com/mypage/ ? farve=gul . Here I would like “ gul ” to be passed in as the color parameter to the default Index ( ) ation method.How do I set mappings for alternate names for querystring parameters ?
public ActionResult Index ( color = `` '' ) { ... }
Alternate names for querystring parameters
C#
Broken code The code above is expecting to express : The conclusion infers the premise because of the premise implies the conclusion . The the premise implies the conclusion because of the conclusion infers the premise . It would be circular reasoning , and definitely will cause stack overflow . I then redesign it as follows : Working code But that means : It fails on the correct logic that it can not go without Paradox < T > which I initially named Predicate < T > but is conflict with System.Predicate < T > . It 's defective that T must implement IConvertable unlike the code former . To be clear , I 'm trying to make the code not only works but also represent like logical formulas that I can further reuse it to reason about logic without a constraint of T implements IConvertable . Is there a way make the logic correct and get rid of the defective design ?
public static partial class LogicExtensions { public static bool Implies < T > ( this T premise , T conclusion ) { return conclusion.Infers ( premise ) ; } public static bool Infers < T > ( this T premise , T conclusion ) { return premise.Implies ( conclusion ) ; } } public delegate bool Paradox < T > ( T premise , T conclusion , Paradox < T > predicate=null ) ; public static partial class LogicExtensions { public static bool Implies < T > ( this T premise , T conclusion , Paradox < T > predicate=null ) { if ( null==predicate ) return conclusion.Infers ( premise , Implies ) ; if ( Infers ! =predicate ) return predicate ( premise , conclusion ) ; return LogicExtensions.Implies ( conclusion as IConvertible , premise as IConvertible ) ; } public static bool Infers < T > ( this T premise , T conclusion , Paradox < T > predicate=null ) { if ( null==predicate ) return premise.Implies ( conclusion , Infers ) ; if ( Implies ! =predicate ) return predicate ( premise , conclusion ) ; return LogicExtensions.Implies ( conclusion as IConvertible , premise as IConvertible ) ; } static bool Implies < T > ( T premise , T conclusion ) where T : IConvertible { var x=premise.ToUInt64 ( null ) ; return x== ( x & conclusion.ToUInt64 ( null ) ) ; } }
Informal fallacy causes stack overflow
C#
I am trying to create a parallel event subscriber . This is my first attempt : In your expert opinion , is this a valid approach ? Could you please suggest any improvements ? PS : Maybe : would be better ?
using System ; using System.Collections.Generic ; using System.Threading.Tasks ; using EventStore.ClientAPI ; namespace Sandbox { public class SomeEventSubscriber { private Position ? _latestPosition ; private readonly Dictionary < Type , Action < object > > _eventHandlerMapping ; private IEventStoreConnection _connection ; public Dictionary < Type , Action < object > > EventHandlerMapping { get { return _eventHandlerMapping ; } } public SomeEventSubscriber ( ) { _eventHandlerMapping = CreateEventHandlerMapping ( ) ; _latestPosition = Position.Start ; } public void Start ( ) { ConnectToEventstore ( ) ; } private void ConnectToEventstore ( ) { _connection = EventStoreConnectionWrapper.Connect ( ) ; _connection.Connected += ( sender , args ) = > _connection.SubscribeToAllFrom ( _latestPosition , false , EventOccured , LiveProcessingStarted , HandleSubscriptionDropped ) ; } private Dictionary < Type , Action < object > > CreateEventHandlerMapping ( ) { return new Dictionary < Type , Action < object > > { { typeof ( FakeEvent1 ) , o = > Handle ( o as FakeEvent1 ) } , { typeof ( FakeEvent2 ) , o = > Handle ( o as FakeEvent2 ) } , } ; } private async Task Handle ( FakeEvent1 eventToHandle ) { SomethingLongRunning ( eventToHandle ) ; } private async Task Handle ( FakeEvent2 eventToHandle ) { SomethingLongRunning ( eventToHandle ) ; } private async Task SomethingLongRunning ( BaseFakeEvent eventToHandle ) { Console.WriteLine ( `` Start Handling : `` + eventToHandle.GetType ( ) ) ; var task = Task.Delay ( 10000 ) ; await task ; Console.WriteLine ( `` Finished Handling : `` + eventToHandle.GetType ( ) ) ; } private void EventOccured ( EventStoreCatchUpSubscription eventStoreCatchUpSubscription , ResolvedEvent resolvedEvent ) { if ( resolvedEvent.OriginalEvent.EventType.StartsWith ( `` $ '' ) || resolvedEvent.OriginalEvent.EventStreamId.StartsWith ( `` $ '' ) ) return ; var @ event = EventSerialization.DeserializeEvent ( resolvedEvent.OriginalEvent ) ; if ( @ event ! = null ) { var eventType = @ event.GetType ( ) ; if ( _eventHandlerMapping.ContainsKey ( eventType ) ) { var task = Task.Factory.StartNew ( ( ) = > _eventHandlerMapping [ eventType ] ( event ) ) ; Console.WriteLine ( `` The task is running asynchronously ... '' ) ; } } if ( resolvedEvent.OriginalPosition ! = null ) _latestPosition = resolvedEvent.OriginalPosition.Value ; } private void HandleSubscriptionDropped ( EventStoreCatchUpSubscription subscription , SubscriptionDropReason dropReason , Exception ex ) { if ( dropReason == SubscriptionDropReason.ProcessingQueueOverflow ) { //TODO : Wait and reconnect probably with back off } if ( dropReason == SubscriptionDropReason.UserInitiated ) return ; if ( SubscriptionDropMayBeRecoverable ( dropReason ) ) { Start ( ) ; } } private static bool SubscriptionDropMayBeRecoverable ( SubscriptionDropReason dropReason ) { return dropReason == SubscriptionDropReason.Unknown || dropReason == SubscriptionDropReason.SubscribingError || dropReason == SubscriptionDropReason.ServerError || dropReason == SubscriptionDropReason.ConnectionClosed ; } private static void LiveProcessingStarted ( EventStoreCatchUpSubscription eventStoreCatchUpSubscription ) { } } } Task.Run ( ( ) = > _eventHandlerMapping [ eventType ] ( @ event ) ) ;
parallel event subscriber .net 4.5
C#
I have a C # .Net 4.0 Application on the one hand and on the other a VB6 App . I created a COM Interface by making the Project COM Visible and actived register COM Interop.I Tested the COM interface by implementing a C # Application wich imports the new tlb file . All seems to be fine . As next step I tried to use the dll with vb6 . The dll could be loaded but now i ca n't see all public classes . In C # I see 4 classes in vb6 I can only see 3 . The class I ca n't see is a `` special '' one cause it impelements an interface and serves events . The class is marked with and the COMEvents interface is likeI have to say that all worked fine . Than i added a project which only effects other assemblys wich are loaded on runtime by the COM interface project . They implement an interface which changed . Thats the only change i made to the com interface is adding additonal parameter to a method . Why ca n't I see the Class any more ? And why is it only the class I changed but in no `` risky '' way ? need help thanks ! P.S : I Tried up to now : - > all Project are Build x86- > Project Build on x86 Machine - > Dependency Walker ( GPSVC.DLL and IESHIMS.DLL are missing but they did also before and i do n't think they have anny effect cause the tlb is build and could be loaded ) - > tryied tlbexp.exe but get an dependencie error cause assambly runtime is newer than current one . wtf ? )
[ ComSourceInterfaces ( typeof ( COMEvents ) ) ] [ Guid ( `` 11947063-4665-4DE1-931D-9915CCD01794 '' ) ] [ InterfaceType ( ComInterfaceType.InterfaceIsIDispatch ) ] public interface COMEvents { void MethodOne ( ) ; void MethodTwo ( ) ; }
COM class visibility : C # to VB6
C#
I think so . But take a look at a built-in class in ASP.NET : Suppose I have an instance of HttpPostedFile called file . Since there is no Dispose method to explicitly invoke , file.InputStream.Dispose ( ) wo n't be invoked until it 's destructed , which I think goes against the original intention of IDisposable . I think the correct implementation should contain a standard IDisposable implementation . So , if one of the members implements IDisposable , the class needs to implement it too.What are your opinions ? It seems to be a bit complicated .
public sealed class HttpPostedFile { public Stream InputStream { get ; } // Stream implements IDisposable // other properties and methods }
Should we implement IDisposable if one member is IDisposable
C#
With a generic List , what is the quickest way to check if an item with a certain condition exists , and if it exist , select it , without searching twice through the list : For Example :
if ( list.Exists ( item = > item == ... ) ) { item = list.Find ( item = > item == ... ) ... . }
Checking for item in Generic List before using it
C#
The SituationWe are selling a Windows Forms Application to customers all over the world.We installed it in several countries in Europe and America . No problems.Last week we installed our software in South-Korea and recognized a strange behaviour ... The problem occurs only on the customers office PCs , but on all of them.Some have Windows 7 Professional K , some have Windows XP.The customer bought a new PC with an installed Windows 7 Ultimate.On this PC , there is no problem.The FunctionAll elements in our application are derived from a `` parent-user-control '' that offers special functions.One of these functions is `` autosizing and positioning '' .When the parent changes size , this function of all childs is called.When our application starts , we store the `` ClientSize '' : Whenever the size of the application changes , we calculate the scaling factor and raise an event with it : Now , each child that subscribed , performs automatic resizing and positioning : The ProblemWhen our application starts on the customers PCs in South-Korea , the width is about 20 % to small.That means , on the right side is an area where is just a grey background.The height is about 10 % to high.That means , the items located on the bottom of our application are outside the screen.The FixFirst , we thought the problem comes from the Windows DPI setting.When I set my Laptop to 125 % , it looked similar.But , the customers PCs are all set to 100 % ... Then , we thought about the screen resolution.All have different ones , some the same as my Laptop ... All have different grafic adapters ... All have .NET 4.5.1 ... The only way , that solved the problem , was a strange one : In the `` Designer '' file , manually changing the ClientSize from ( 1016 , 734 ) to about ( 900 , 800 ) .This made it look good on most customer PCs . But not on all.The QuestionWhat can be the real solution for this problem ? Where can it come from ?
InitializeComponent ( ) ; this.m_actSize = this.ClientSize ; void myFormSizeChanged ( object sender , EventArgs e ) { this.m_xFactor = ( float ) this.ClientSize.Width / ( float ) this.m_actSize.Width ; this.m_yFactor = ( float ) this.ClientSize.Height / ( float ) this.m_actSize.Height ; if ( this.m_MyOnResize ! = null ) this.m_MyOnResize ( this.m_xFactor , this.m_yFactor ) ; } void MyParentUserControl_MyOnResize ( float v_xFactor , float v_yFactor ) { this.Location = new Point ( ( int ) ( this.m_actLocation.X * v_xFactor ) , ( int ) ( this.m_actLocation.Y * v_yFactor ) ) ; this.Size = new Size ( ( int ) ( this.m_actSize.Width * v_xFactor ) , ( int ) ( this.m_actSize.Height * v_yFactor ) ) ; } this.AutoScaleDimensions = new System.Drawing.SizeF ( 6F , 13F ) ; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font ; this.BackColor = System.Drawing.SystemColors.ScrollBar ; this.ClientSize = new System.Drawing.Size ( 1016 , 734 ) ;
Wrong scaling on Korean PCs
C#
The following code using LINQ in NHibernate returns a different result from in-memory LINQ and EF LINQ . What is the correct way to do this in NHibernate ? It is fine to use QueryOver if the LINQ version is indeed broken.Expected resultsActual resultsLogged SQLThe full code is in the bug report Incorrect result when using GroupBy with FirstUpdate 2019-8-9The query should not use ID . I have changed it to a non-unique property . I would appreciate if the solution only query once to SQLite .
using ( var session = factory.OpenSession ( ) ) using ( var transaction = session.BeginTransaction ( ) ) { for ( int i = 0 ; i < 10 ; ++i ) { session.Save ( new A ( ) { X = i % 2 , Y = i / 2 , } ) ; } transaction.Commit ( ) ; } using ( var session = factory.OpenSession ( ) ) using ( var transaction = session.BeginTransaction ( ) ) { //===================================== var expected = session.Query < A > ( ) .ToList ( ) // < -- copy to memory .GroupBy ( a = > a.X ) .Select ( g = > g.OrderBy ( y = > y.Y ) .First ( ) ) .ToList ( ) ; Console.WriteLine ( string.Join ( `` `` , expected.Select ( a = > a.Id ) ) ) ; //===================================== var actual = session.Query < A > ( ) .GroupBy ( a = > a.X ) .Select ( g = > g.OrderBy ( y = > y.Y ) .First ( ) ) .ToList ( ) ; Console.WriteLine ( string.Join ( `` `` , actual.Select ( a = > a.Id ) ) ) ; } public class A { public int Id { get ; set ; } public int X { get ; set ; } // indexed public int Y { get ; set ; } // indexed } 1 2 1 1 NHibernate : select ( select program_a0_.Id as id1_0_ from `` A '' program_a0_ order by program_a0_.Y asc limit 1 ) as col_0_0_ from `` A '' program_a0_ group by program_a0_.X
How to query the first entry in each group in NHibernate
C#
I have mainly worked in C++ and I am now using C # at my new job , and after doing some reading on here about the 'ref ' keyword and c # value vs reference types I am still finding some confusion with them.As far as I 'm understanding these if you were passing these to a method these would be analogous C++ styles : Value types : and Reference types : and 'ref ' / pointerandIs this a correct analogy ?
public void CSharpFunc ( value ) public void CPlusplusFunc ( value ) public void CSharpFunc ( reference ) public void CPlusPlusFunc ( & reference ) public void CSharpFunc ( ref bar ) public void CPlusPlus ( *bar )
Use of C # 'ref ' keyword compared to C++
C#
I have this COM method signature , declared in C # : I call it like this : Does the .NET interop layer first copy the whole array to a temporary unmanaged memory buffer , then copy it back ? Or does the array get automatically pinned and passed by reference ? For the sake of trying , I did this in the COM object ( C++ ) : I do get ' Ώ ' back when I check buff [ 1 ] in C # upon return . But I do n't think this is a strong proof that the array gets pinned , rather than copied back and forth .
void Next ( ref int pcch , [ MarshalAs ( UnmanagedType.LPArray , SizeParamIndex = 0 ) ] char [ ] pchText ) ; int cch = 100 ; var buff = new char [ cch ] ; com.Next ( ref cch , buff ) ; *pcch = 1 ; pchText [ 0 ] = L ' A ' ; pchText [ 1 ] = L'\x38F ' ; // ' Ώ '
Does .NET interop copy array data back and forth , or does it pin the array ?
C#
Using c # Web Api 2 , I have code that throws an InvalidOperationException . When returning a status code of 302 , how do provide a location for the redirect using the HandleException annotation ? Edit : Sorry , I asked this question in a bit of haste . The above class uses a HandleExceptionAttribute class which inherits from ExceptionFilterAttribute . I did n't realize this at the time I was trying to debug their unit test . The problem does n't arise in a unit test , but does show up using a Visual Studio .webtest that requires the redirect url . The class that inherits from ExceptionFilterAttribute did not provide a parameter that allows for the redirected URL to be supplied . Sorry for an incomplete question and thanks for taking time to answer .
[ HandleException ( typeof ( InvalidOperationException ) , HttpStatusCode.Found , ResponseContent = `` Custom message 12 '' ) ] public IHttpActionResult GetHandleException ( int num ) { switch ( num ) { case 12 : throw new InvalidOperationException ( `` DONT SHOW invalid operation exception '' ) ; default : throw new Exception ( `` base exception '' ) ; } } /// < summary > /// This attribute will handle exceptions thrown by an action method in a consistent way /// by mapping an exception type to the desired HTTP status code in the response . /// It may be applied multiple times to the same method . /// < /summary > [ AttributeUsage ( AttributeTargets.Method , Inherited = false , AllowMultiple = true ) ] public sealed class HandleExceptionAttribute : ExceptionFilterAttribute {
How do you specify the location when using handleexeption annotation for a 302 status code
C#
When should locks be used ? Only when modifying data or when accessing it as well ? Should there be a lock around the the entire block or is it ok to just add it to the actual modification ? My understanding is that there still could be some race condition where one call might not have found it and started to add it while another call right after might have also run into the same situation - but I 'm not sure . Locking is still so confusing . I have n't run into any issues with the above similar code but I could just be lucky so far . Any help above would be appriciated as well as any good resources for how/when to lock objects .
public class Test { static Dictionary < string , object > someList = new Dictionary < string , object > ( ) ; static object syncLock = new object ( ) ; public static object GetValue ( string name ) { if ( someList.ContainsKey ( name ) ) { return someList [ name ] ; } else { lock ( syncLock ) { object someValue = GetValueFromSomeWhere ( name ) ; someList.Add ( name , someValue ) ; } } } }
locking only when modifying vs entire method
C#
I have a class similar to : I then created a method to pull the names from the class.So when I get my array it would be in the following order : I was wondering if it was possible to change the order so that the base class fields were first followed by the derived class fields ?
public class MyClass : MyBaseClass { public string Field1 { get ; set ; } public string Field2 { get ; set ; } public string Field3 { get ; set ; } public string Field4 { get ; set ; } } public class MyBaseClass { public string BaseField1 { get ; set ; } public string BaseField2 { get ; set ; } public string BaseField3 { get ; set ; } public string BaseField4 { get ; set ; } } private void MyMethod < T > ( List < T > listData ) where T : class { String [ ] fieldNames = Array.ConvertAll < PropertyInfo , String > ( typeof ( T ) .GetProperties ( ) , delegate ( PropertyInfo fo ) { return fo.Name ; } ) ; // Do something with the fieldNames array ... . } Field1Field2Field3Field4BaseField1BaseField2BaseField3BaseField4
How to get a list of property names in a class in certain a order
C#
This may seem a little crazy , but it 's an approach I 'm considering as part of a larger library , if I can be reasonably certain that it 's not going to cause weird behavior.The approach : Run async user code with a SynchronizationContext that dispatches to a thread pool . The user code would look something like : I 'm not certain whether access to someState would be threadsafe . While the code would run in one `` thread '' such that the operations are , in fact , totally ordered , it could still be split across multiple threads beneath the hood . If my understanding is correct , ordering ought to be safe on x86 , and since the variable is n't shared I wo n't need to worry about compiler optimizations and so on.More importantly though , I 'm concerned as to whether this will be guaranteed thread-safe under the ECMA or CLR memory models.I 'm fairly certain I 'll need to insert a memory barrier before executing a queued piece of work , but I 'm not totally confident in my reasoning here ( or that this approach might be unworkable for entirely separate reasons ) .
async void DoSomething ( ) { int someState = 2 ; await DoSomethingAsync ( ) ; someState = 4 ; await DoSomethingElseAsync ( ) ; // someState guaranteed to be 4 ? }
Multiplexing C # 5.0 's async over a thread pool -- thread safe ?
C#
Expected end results is to get an IEnumerable with 1.2 , 2.3 , 3.1 , 4.2 which represents the SubTierId of each subTier.but what happens is I get this return type . What is the best way so that I just get a single IEnumerable of the SubSubTier ?
Top Tier Object SubTier Objects SubSubTier Objects 1.1,1.2,1.3 : SubTierId = 2 SubSubTier Objects 2.1,2.2,1.3 : SubTierId = 3 SubTier Objects SubSubTier Objects 3.1,3.2,3.3 : SubTierId = 1 SubSubTier Objects 4.1,4.2,4.3 : SubTierId = 2 SubSubTiers mySubSubTier = allTiers.Select ( topTier = > topTier.SubTiers.Where ( sbTier = > sbTier.Id == topTier.SubTierId ) ) ; IEnumerable < IEnumerable < SubSubTier > >
How to get Sub objects based on value using linq ?
C#
I ran into what I think is a really odd situation with entity framework . Basically , if I update an row directly with a sql command , when I retrive that row through linq it does n't have the updated information . Please see the below example for more information.First I created a simple DB tableThen I created a console application to add an object to the DB , update it with a sql command and then retrieve the object that was just created . Here it is : The write line at the bottom prints out `` Before '' however I would expect that it prints out `` After '' . The odd thing about it is that if I run profiler I see the sql query run and if I run the query in management studio myself , it returns `` After '' as the name . I am running sql server 2014.Can someone please help me understand what is going on here ? UPDATE : It is going to the database on the FirstOrDefault line . Please see the attached screen shot from sql profiler . So my question really is this:1 ) If it is caching , should n't it not be going to the DB ? Is this a bug in EF ? 2 ) If it is going to the db and spending the resources , should n't EF update the object .
CREATE TABLE dbo.Foo ( Id int NOT NULL PRIMARY KEY IDENTITY ( 1,1 ) , Name varchar ( 50 ) NULL ) public class FooContext : DbContext { public FooContext ( ) : base ( `` FooConnectionString '' ) { } public IDbSet < Foo > Foo { get ; set ; } protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { modelBuilder.Entity < Foo > ( ) .ToTable ( `` Foo '' ) ; base.OnModelCreating ( modelBuilder ) ; } } public class Foo { [ Key ] public int Id { get ; set ; } public string Name { get ; set ; } } public class Program { static void Main ( string [ ] args ) { //setup the context var context = new FooContext ( ) ; //add the row var foo = new Foo ( ) { Name = `` Before '' } ; context.Foo.Add ( foo ) ; context.SaveChanges ( ) ; //update the name context.Database.ExecuteSqlCommand ( `` UPDATE Foo Set Name = 'After ' WHERE Id = `` + foo.Id ) ; //get the new foo var newFoo = context.Foo.FirstOrDefault ( x = > x.Id == foo.Id ) ; //I would expect the name to be 'After ' but it is 'Before ' Console.WriteLine ( string.Format ( `` The new name is : { 0 } '' , newFoo.Name ) ) ; Console.ReadLine ( ) ; } }
Unexpected behavior in entity framework
C#
I just came across a strange behavior with using async methods in structures . Can somebody explain why this is happening and most importantly if there is a workaround ? Here is a simple test structure just for the sake of a demonstration of the problemNow , let 's use the structure and do the following callsThe first line instantiates the structure and the sInstance._Value value is 25 . The second line updates the sInstance._Value value and it becomes 35 . Now the third line does not do anything but I would expect it to update the sInstance._Value value to 45 however the sInstance._Value stays 35 . Why ? Is there a way to write an async method for a structure and change a structure field 's value ?
public struct Structure { private int _Value ; public Structure ( int iValue ) { _Value = iValue ; } public void Change ( int iValue ) { _Value = iValue ; } public async Task ChangeAsync ( int iValue ) { await Task.Delay ( 1 ) ; _Value = iValue ; } } var sInstance = new Structure ( 25 ) ; sInstance.Change ( 35 ) ; await sInstance.ChangeAsync ( 45 ) ;
Struct 's private field value is not updated using an async method
C#
I had read data from an XML file into DataSet by using c # than I want to identify duplicate ( completely the same ) rows in that set.I tried such kind of grouping and that works ! But the number of data columns can be differ , so I can not apply static grouping in query like above . I had to generate the grouping array dynamically ? I do n't want to delete dublicate , I just want to find them !
var d= from r1 in table.AsEnumerable ( ) group r1 by new { t0 = r1 [ 0 ] , t1 = r1 [ 1 ] , t2 = r1 [ 2 ] , t3 = r1 [ 3 ] , t4 = r1 [ 4 ] , t5 = r1 [ 5 ] , t6 = r1 [ 6 ] , t7 = r1 [ 7 ] , t8 = r1 [ 8 ] , } into grp where grp.Count ( ) > 1 select grp ;
Query to detect duplicate rows
C#
Could you please explain me the reason of the following situation.Today I wrote the code ( only variables names are changed ) : Everything was fine until I decided to move the if condition to a variable : Now the compiler underlines firstInteger and secondInteger variables with error `` Local variable might not be initialized before accessing '' .But why ? The only thing I made is refactored the code a bit . And as I see it the logic is the same .
private void Foo ( ) { int firstInteger , secondInteger ; const string firstStringValue = `` 1 '' , secondStringValue = `` 2 '' ; if ( ! string.IsNullOrWhiteSpace ( firstStringValue ) & & int.TryParse ( firstStringValue , out firstInteger ) & & ! string.IsNullOrWhiteSpace ( secondStringValue ) & & int.TryParse ( secondStringValue , out secondInteger ) ) { // Using firstInteger and secondInteger here firstInteger++ ; secondInteger++ ; } } private void Foo ( ) { int firstInteger , secondInteger ; const string firstStringValue = `` 1 '' , secondStringValue = `` 2 '' ; bool firstIntegerAndSecondIntegerAreSpecified = ! string.IsNullOrWhiteSpace ( firstStringValue ) & & int.TryParse ( firstStringValue , out firstInteger ) & & ! string.IsNullOrWhiteSpace ( secondStringValue ) & & int.TryParse ( secondStringValue , out secondInteger ) ; if ( firstIntegerAndSecondIntegerAreSpecified ) { // Use firstInteger and secondInteger here firstInteger++ ; secondInteger++ ; } }
Moving `` if '' statement condition to a local variable makes C # compiler unhappy
C#
I have a business layer class that uses System.IO.File to read information from various files . In order to unit test this class I 've chosen to replace the dependency on the File class with an injected dependency like so : Now I can test my class using a Mock and all is right with the world . Separately , I need a concrete implementation . I have the following : Now my business class is no longer dependent on the System.IO.File class and can be tested using a Mock of IFileWrapper . I see no need to test the System.IO.File class as I assume this has been thoroughly tested by Microsoft and proven in countless uses.How do I test the concrete FileWrapper class ? Though this is a simple class ( low risk ) , I have larger examples that follow the same approach . I can not approach 100 % code coverage ( assuming this is important ) without completing this.The larger question here I suppose is , how to bridge the gap between unit testing and integration testing ? Is it necessary to test this class , or is there some attribute to decorate this class to exlcude this from code coverage calculation .
using System.IO ; public interface IFileWrapper { bool FileExists ( string pathToFile ) ; Stream Open ( string pathToFile ) ; } using System ; using System.IO ; public class FileWrapper : IFileWrapper { public bool FileExists ( string pathToFile ) { return File.Exists ( pathToFile ) ; } public Stream Open ( string pathToFile ) { return File.Open ( pathToFile , FileMode.Open , FileAccess.Read , FileShare.Read ) ; } }
How do I ( or do I ) unit test a concrete dependency
C#
For EF6 , I had a method in my generic repository that I exposed to all service layers in order to retrieve entities from the database with any nested properties as needed : This way , I could use the method in the following way : In EF6 , this would load the Papers navigation property , the People navigation property , and the Addresses navigation property on each person . This , as expected , throws an exception in EFCore . Because of the switch to Include -- > ThenInclude method in EFCore , I 'm not quite sure how to easily replicate this at my service layer which I 'd like to not require any information about EntityFramework .
public IQueryable < T > OldMethod ( params Expression < Func < T , object > > [ ] includeProperties ) { var queryable = set.AsQueryable ( ) ; return includeProperties.Aggregate ( queryable , ( current , includeProperty ) = > current.Include ( includeProperty ) ) ; } var data = repo.OldMethod ( x = > x.Papers , = > x.People.Select ( y = > y.Addresses ) ) .ToList ( ) ;
Translating generic eager load method from EF6 to EF Core
C#
This piece of code caught me out today : clientFile.Review month is a byte ? and its value , in the failing case , is null.The expected result type is string.The exception is in this codeThe right hand side of the evaluation is being evaluated and then implicitly converted to a string.But my question is why is the right hand side being evaluated at all when clearly only the left hand side should be evaluated ? ( The documentation states that `` Only one of the two expressions is evaluated . `` ) The solution incidentally is to cast the null to string - that works but Resharper tells me that the cast is redundant ( and I agree ) Edit : This is different to the `` Why do I need to add a cast before it will compile '' type ternary operator question . The point here is that no cast is required to make it compile - only to make it work correctly .
clientFile.ReviewMonth == null ? null : MonthNames.AllValues [ clientFile.ReviewMonth.Value ] public static implicit operator string ( LookupCode < T > code ) { if ( code ! = null ) return code.Description ; throw new InvalidOperationException ( ) ; }
C # Ternary Operator evaluating when it should n't
C#
I 've just upgraded to VS2015.1 and got a compiler crash when trying to compile one of my projects . If you put the following repo code in a console application ( and add a reference to moq.dll ) the code in line 12 crashes my compiler . It seems to happen during a Roslyn lamdba rewrite call.Anyone know why the crash occurs ?
using System.Collections.Generic ; using System.Linq ; using Moq ; namespace RoslynError { class Program { static void Main ( string [ ] args ) { var mockRepo = new MockRepository ( MockBehavior.Strict ) ; var obj = mockRepo.OneOf < DTO > ( x = > x.Value == ( OptionEnum ? ) null ) ; } } class DTO { public DTO ( OptionEnum ? enumVal ) { Value = enumVal ; } public OptionEnum ? Value ; } enum OptionEnum { NotSpecified } }
Why does Roslyn crash when trying to rewrite this lambda ? ( Visual Studio 2015 update 1 )
C#
Updated with a solution that works for me . See the bottom of this question.Context : I needed a way to evaluate the size of a generic type for the purpose of calculating array lengths to fit within a certain byte size . Basically , sizeof similar to what C/C++ provides.C # 's sizeof and Marshal.SizeOf are not suitable for this , because of their many limitations.With this in mind , I wrote an assembly in IL that enables the functionality I was looking for through the sizeof opcode . I 'm aware that it essentially evaluates to IntPtr.Size with reference types.I duplicated this for .NET Standard & Core , referencing what I believed were the correct equivalents of mscorlib . Note that the IL compiles fine , this question is about another issue.Code : Headers per target framework : .NET : ( Windows\Microsoft.NET\Framework\v4.0.30319\ilasm.exe ) .NET Standard : ( ilasm extracted from nuget ) .NET Core : ( same ilasm as standard , though I 've tested with both ) Source : Problem : When any dll compiled in this manner is referenced by a .NET Core or Xamarin application , I receive the following error : The type 'Object ' is defined in an assembly that is not referenced . You must add a reference to assembly 'System.Runtime , Version=0.0.0.0 , Culture=neutral , PublicKeyToken=null'.This issue does n't occur when such dlls are referenced by .NET projects or .NET standard libraries which are then referenced by a .NET project.I 've read countless articles , posts , and repositories detailing this error with different versions and assemblies . The typical solution seems to be to add an explicit reference to the target framework 's equivalent of mscorlib ( breaking portability ) . There seems to be a lack of information about using IL compiled assemblies for .NET Standard & Core.To my understanding , .NET Standard & Core use facades that forward type definitions so they may be resolved by the target framework 's runtime , enabling portability.I 've tried the following : Explicit versions of System.RuntimeDisassembling .NET Core libraries compiled from C # , using the exact same references . Oddly enough they seem to target explicit versions ( such as System.Runtime 4.2 in .NET Core 2.0 ) .Generating the code dynamically using the Emit API . Compiling to memory appears to work , but is n't an option because I 'm also targeting Xamarin.iOS ( AOT only ) . Referencing such dynamically compiled assemblies from disk results in the same error as if I compiled them manually.Update : I attempted the solution in Jacek 's answer ( following the build instructions here ) , yet could n't configure my system to compile corefx with the build script or VS 2017 . However , after digging through the code of System.Runtime.CompilerServices.Unsafe I discovered a solution . This probably seems obvious , but I was referencing the wrong version of System.Runtime.Headers per target framework ( copied from corefx ) : .NET : .NET Standard : .NET Core : In all source files , use CORELIB to reference types in mscorlib ( i.e . [ CORELIB ] System.Object ) .
.assembly extern mscorlib { } .assembly extern netstandard { .publickeytoken = ( B7 7A 5C 56 19 34 E0 89 ) .ver 0:0:0:0 } .assembly extern System.Runtime { .ver 0:0:0:0 } .assembly extern System.Runtime { .ver 0:0:0:0 } .assembly Company.IL { .ver 0:0:1:0 } .module Company.IL.dll// CORE is a define for mscorlib , netstandard , and System.Runtime.class public abstract sealed auto ansi beforefieldinit Company.IL.Embedded extends [ CORE ] System.Object { .method public hidebysig specialname rtspecialname instance void .ctor ( ) cil managed { .maxstack 8 ldarg.0 call instance void [ CORE ] System.Object : :.ctor ( ) ret } .method public hidebysig static uint32 SizeOf < T > ( ) cil managed { sizeof ! ! 0 ret } } # define CORELIB `` mscorlib '' .assembly extern CORELIB { } # define CORELIB `` System.Runtime '' # define netcoreapp// Metadata version : v4.0.30319.assembly extern CORELIB { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } # define CORELIB `` System.Runtime '' // Metadata version : v4.0.30319.assembly extern CORELIB { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 }
Using assemblies compiled from IL with .NET Core & Xamarin
C#
Ok , consider the following code : trueOrFalse is a compile time constant and as such , the compiler warns correctly that int hash = o.GetHashCode ( ) ; is not reachable.Also , constObject is a compile time constant and as such the compiler warns again correctly that int hash = o.GetHashCode ( ) ; is not reachable as o ! = null will never be true.So why does n't the compiler figure out that : is 100 % sure to be a runtime exception and thus issue out a compile time error ? I know this is probably a stupid corner case , but the compiler seems pretty smart reasoning about compile time constant value types , and as such , I was expecting it could also figure out this small corner case with reference types .
const bool trueOrFalse = false ; const object constObject = null ; void Foo ( ) { if ( trueOrFalse ) { int hash = constObject.GetHashCode ( ) ; } if ( constObject ! = null ) { int hash = constObject.GetHashCode ( ) ; } } if ( true ) { int hash = constObject.GetHashCode ( ) ; }
Compile time constants and reference types
C#
I have these statements and their ' results are near them.Why the last equality gives me false ? The question is why ( x == y ) is true ( k == m ) is false
string a = `` abc '' ; string b = `` abc '' ; Console.Writeline ( a == b ) ; //trueobject x = a ; object y = b ; Console.Writeline ( x == y ) ; // truestring c = new string ( new char [ ] { ' a ' , ' b ' , ' c ' } ) ; string d = new string ( new char [ ] { ' a ' , ' b ' , ' c ' } ) ; Console.Writeline ( c == d ) ; // trueobject k = c ; object m = d ; Console.Writeline ( k.Equals ( m ) ) //trueConsole.Writeline ( k == m ) ; // false
Object equality behaves different in .NET
C#
Hello I want to scan audio-video files and store their metadata in a database using php . I found this Command-line wrapper that uses TagLib.dll compiled by banshee developpers to do the job . It 's works fine but it limited by the functions implemented . I want to access directly to the dll methods via PHP.In PHP we have a function ( DOTNET ) that allows me to instantiate a class from a .Net assembly and call its methods and access its properties like this : Here is the Taglib # project sources in github I saw many questions relatives to PHP-DLL-COM and there is some recommendations : Make the dll comVisible ; Register the dll with regsvr32 ; Use a module definition file similar to ; My question is : How can I build the DLL and use its method via PHP ? My config : OS Windows Server 2012 R2 Standard Edition i586Apache : Apache/2.2.21 ( Win32 ) DAV/2 PHP/5.4.42 mod_ssl/2.2.21 OpenSSL/0.9.8rPHP PHP Version : 5.4.42 Arch : x86 Compiler : MSVC9 ( Visual C++ 2008 ) COM support : enabled DCOM support : disabled .Net support enabledMicrosoft Visual Studio 2013
/* $ obj = new DOTNET ( `` assembly '' , `` classname '' ) ; */ $ stack = new DOTNET ( `` mscorlib '' , `` System.Collections.Stack '' ) ; $ stack- > Push ( `` .Net '' ) ; $ stack- > Push ( `` Hello `` ) ; echo $ stack- > Pop ( ) . $ stack- > Pop ( ) ; //Returns string ( 10 ) `` Hello .Net '' ; ; DESCRIPTION `` Simple COM object '' EXPORTS DllGetClassObject PRIVATE DllCanUnloadNow PRIVATE DllRegisterServer PRIVATE DllUnregisterServer PRIVATE
Build TagLib # DLL from source and make it COM Visible to PHP
C#
The following code : might be optimized toif x gets assigned in another thread only . See Illustrating usage of the volatile keyword in C # . The answer there solves this by setting x to be volatile.However , it looks like that is not the correct way to go about it according to these three contributors ( with a combined reputation of over 1 million : ) ) Hans Passant A reproducable example of volatile usage : `` never assume that it is useful in a multi-threading scenario . `` Marc Gravell Value of volatile variable does n't change in multi-thread : `` volatile is not the semantic I usually use to guarantee the behavior '' Eric Lippert Atomicity , volatility and immutability are different , part three : `` I discourage you from ever making a volatile field . '' Assuming a Backgroundworker is treated like any other multithreading ( as opposed to having some built-in mechanism to prevent optimization ) - How can bad-optimization be prevented ?
while ( x == 1 ) { ... } while ( true ) { ... }
Prevent bad-optimization in Multithreading
C#
Input in my case is a string with a list of elements separated by CommaInput : Expected Output ( a string ) : I 'm looking for a solution in VB.net but i 'm not so familiar with it . So , I tried it in c # . Not sure what i 'm missing . My Attempt : Actual Output : Any help in funding a solution in vb.net is much appreciated : )
var input = `` 123,456,789 '' ; `` '123 ' , '456 ' , '789 ' '' var input = `` 123,456,789 '' ; var temp = input.Split ( new Char [ ] { ' , ' } ) ; Array.ForEach ( temp , a = > a = `` ' '' + a + `` ' '' ) ; Console.WriteLine ( String.Join ( `` , '' , temp ) ) ; `` 123,456,789 ''
Appending a Char to each element in a array
C#
I want to be able to specify something like this : Class FilterControl < > is a base class . I can not know what will be the generic argument for FilterControl < > .
public abstract class ColumnFilter < TCell , TFilterControl > : ColumnFilter where TFilterControl : FilterControl < > , new ( ) where TCell : IView , new ( ) { }
Generic type in generic constraint
C#
I 'm using specifications in this kind of form : Now I can use this specification in the form : But I 'm not sure how to use the specification against an associated object like this : Is there a way to do this , or do I need to rethink my implementation of specifications ?
public static Expression < Func < User , bool > > IsSuperhero { get { return x = > x.CanFly & & x.CanShootLasersFromEyes ; } } var superHeroes = workspace.GetDataSource < User > ( ) .Where ( UserSpecifications.IsSuperhero ) ; var loginsBySuperheroes = workspace.GetDataSource < Login > ( ) .Where ( x = > x.User [ ? ? ? ] ) ;
Linq : how to use specifications against associated objects
C#
Im making a graph program and im stuck at where I need to get mouse coordinates to equal graphic scale . With picturebox I use transform to scale my graphic : Im using MouseMove function . Is there a way to transform mouse coordinates ? When I put my mouse on x=9 I need my mouse coordinate to be 9 .
RectangleF world = new RectangleF ( wxmin , wymin , wwid , whgt ) ; PointF [ ] device_points = { new PointF ( 0 , PictureBox1.ClientSize.Height ) , new PointF ( PictureBox1.ClientSize.Width , PictureBox1.ClientSize.Height ) , new PointF ( 0 , 0 ) , } ; Matrix transform = new Matrix ( world , device_points ) ; gr.Transform = transform ; private void PictureBox1_MouseMove ( object sender , MouseEventArgs e ) { Console.WriteLine ( e.X ) ; }
Transforming mouse coordinates
C#
What is better : to have large code area in lock statementorto have small locks in large area ? ..exchanges in this sample are not changable . or
lock ( padLock ) { foreach ( string ex in exchanges ) { sub.Add ( x.ID , new Subscription ( ch , queue.QueueName , true ) ) ; ... ... ... } foreach ( string ex in exchanges ) { lock ( padLock ) { sub.Add ( x.ID , new Subscription ( ch , queue.QueueName , true ) ) ; } ... ..
What is the proper way to lock code areas
C#
I have an NUnit unit test which I have two collections of different types which I want to assert are equivalent.where Assert.IsPrettySimilar is defined like suchMy question is , is there a more idiomatic way of doing the above with the existing methods in NUnit ? I already looked at CollectionAssert and there 's nothing matching what I want to do.My description of `` equivalent '' in this case is:1 ) Collections must be of same size2 ) Collections must be in same logical order3 ) Some predicate must be used to determine equivalence between matching items .
class A { public int x ; } class B { public string y ; } [ Test ] public void MyUnitTest ( ) { var a = GetABunchOfAs ( ) ; // returns IEnumerable < A > var b = GetABunchOfBs ( ) ; // returns IEnumerable < B > Assert.IsPrettySimilar ( a , b , ( argA , argB ) = > argA.ToString ( ) == argB ) ; } public static void IsPrettySimilar < T1 , T2 > ( IEnumerable < T1 > left , IEnumerable < T2 > right , Func < T1 , T2 , bool > predicate ) { using ( var leftEnumerator = left.GetEnumerator ( ) ) using ( var rightEnumerator = right.GetEnumerator ( ) ) { while ( true ) { var leftMoved = leftEnumerator.MoveNext ( ) ; if ( leftMoved ! = rightEnumerator.MoveNext ( ) ) { Assert.Fail ( `` Enumerators not of equal size '' ) ; } if ( ! leftMoved ) { break ; } var isMatch = predicate ( leftEnumerator.Current , rightEnumerator.Current ) ; Assert.IsTrue ( isMatch ) ; } } }
Assert two different types of enumerations are equivalent
C#
I am a new ASP.NET developer and I am developing a web-based application in which there is a menu bar that has many options . Some of these options will be displayed only to the Admin . There is a logic behind the system to check whether the user is an admin or not . If yes , the options will be displayed . I wrote the method but I have a sql injectiom and I want to remove it.For your information , I have the following database design : Users table : NetID , Name , TitleAdmins table : ID , NetIDHere 's the C # method : I tried to change it by doing the changing the third line to : But I got the following error and I do n't know why : Must declare the scalar variable `` @ NetID '' .Could you please help me in solving this ? **UPDATE : I got the following error : Incorrect syntax near ' ) ' . How to fix this problem ?
private bool isAdmin ( string username ) { string connString = `` Data Source=appSever\\sqlexpress ; Initial Catalog=TestDB ; Integrated Security=True '' ; string cmdText = `` SELECT ID , NetID FROM dbo.Admins WHERE NetID = ' '' + NetID + `` ' ) '' ; using ( SqlConnection conn = new SqlConnection ( connString ) ) { conn.Open ( ) ; // Open DB connection . using ( SqlCommand cmd = new SqlCommand ( cmdText , conn ) ) { SqlDataReader reader = cmd.ExecuteReader ( ) ; if ( reader ! = null ) if ( reader.Read ( ) ) if ( reader [ `` ID '' ] .Equals ( 1 ) ) return true ; return false ; } } } string cmdText = `` SELECT ID , NetID FROM dbo.Admins WHERE NetID = @ NetID ) '' ; After updating the code to the following : private bool isAdmin ( string username ) { string NetID = username ; string connString = `` Data Source=appServer\\sqlexpress ; Initial Catalog=TestDB ; Integrated Security=True '' ; string cmdText = `` SELECT ID , NetID FROM dbo.Admins WHERE NetID = @ NetID '' ; using ( SqlConnection conn = new SqlConnection ( connString ) ) { conn.Open ( ) ; // Open DB connection . using ( SqlCommand cmd = new SqlCommand ( cmdText , conn ) ) { cmd.Parameters.AddWithValue ( `` @ NetID '' , NetID ) ; SqlDataReader reader = cmd.ExecuteReader ( ) ; if ( reader ! = null ) if ( reader.Read ( ) ) if ( reader [ `` NetID '' ] == username ) return true ; return false ; } } }
How to remove the sql injection from this query and make it working well ?
C#
I am stepping through the WPF source code to debug some issue with my own code . I have the source and the pdb 's ( I 'm using dotpeek as a symbol server so I have the full pdbs with source code ) and I can step into the WPF code no problem . The modules I am interested in are PresentationFramework and System.Xaml . The debugging experience is horrible because the framework modules are optimised ( normally a good thing ! ) . My ( very vauge ) understanding is that they are pre-JITed with ngen.exe by VS or whatever , on installation ... and this is causing the obfuscation.Uninstalling .NET Framework elements from Native Image Cache to improve debuggingAs I understand it , I can use ngen.exe ( from the Developer Command Prompt launched from the Visual Studio folder ) to uninstall the native image files . For example ... I 'm lead to believe that this will force the C # compiler to revert to the MSIL versions and JIT compile them at run time . I 'm also assuming that I can then disable the runtime JIT optimization and that 's how I can get a decent debugging experience.However , uninstalling the target native images proves troublesome . Ngen does it but , it has no effect as far as the debugging experience is concerned.When I try to uninstall the same modules again , I am informed that they are not installed - which is encouraging - but I also get a list of files that depend on them , a lot of dll and exe files and also some native image files ( about ten of these ) and the following message ... So , I assume that I will need to find the roots for these ten files and start uninstalling everything from there . This could get out of control fairly quickly if there are a loot of dependencies.Disabling JIT optimisation of particular MSIL modulesAssuming I can get un-optimised modules , in order to supress JIT optimisation , I added ini files to the same folder as the modules that I want to step through , for example , in C : \Windows\Microsoft.NET\assembly\GAC_MSIL\PresentationFramework\v4.0_4.0.0.0__31bf3856ad364e35 I have PresentationFramework.ini In Tools/Options/Debugging/General/ I have Enable source Server support disabled and Suppress JIT optimization on module load enabled.In the Project Options , I have Optimize code disabled in the Build section , I also have Debugging information set to full in Build/Advanced.Am I on the right track ? Is there a config option somewhere in VS where I can just tell it to use the dll files and ignore the aggressively optimised native images ?
ngen uninstall PresentationFrameworkUninstalling assembly PresentationFramework , Version=3.0.0.0 , Culture=Neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=msilUninstalling assembly PresentationFramework , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35Uninstalling assembly PresentationFramework , Version=4.0.0.0 , Culture=Neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=msil You may need to uninstall these assembly roots in order to delete the native image for PresentationFrameworkError : The specified assembly is not installed . [ .NET Framework Debugging Control ] GenerateTrackingInfo=1AllowOptimize=0
How to temporarily stop optimisation of WPF framework elements ?
C#
I have a regex to match date format with comma . yyyy/mm/dd or yyyy/mmFor example : 2016/09/02,2016/08,2016/09/30My code : I use option multiline.If string data have `` \n '' .Any character will match this regex.For example : I find option definition in MSDN . It says : It changes the interpretation of the ^ and $ language elements so that they match the beginning and end of a line , instead of the beginning and end of the input string.I did n't understand why this problem has happened.Anyone can explan it ? Thanks .
string data= '' 21535300/11/11\n '' ; Regex reg = new Regex ( @ '' ^ ( 20\d { 2 } / ( 0 [ 1-9 ] |1 [ 012 ] ) ( / ( 0 [ 1-9 ] | [ 12 ] \d|30|31 ) ) ? , ? ) * $ '' , RegexOptions.Multiline ) ; if ( ! reg.IsMatch ( data ) ) `` Error '' .Dump ( ) ; else `` True '' .Dump ( ) ; string data= '' test\n '' string data= '' 2100/1/1 ''
Regex option `` Multiline ''
C#
I have 5 numbers i.e . : 1 1 1 2 3 ; I have to sum them except the minimum number , but I can remove it only one time ( if the minimum occurs more than one time I have to maintain the rest ) . How can I do it with Linq ? I thought : But it remove all the 1s from the lists . I need a way to go out from the where if there 's more than 1 occurence . All this with Linq if it 's possible .
var min = nums.Min ( ) ; var minSum = nums.Where ( x = > x ! = min ) .Sum ( ) ;
Linq remove only one item if there are duplicate
C#
Is there any way to find a path in C # dynamically without executing `` where '' command prompt command ? For example , if I want to find mspaint exe , I can type this in command promptand it returns the path .
where mspaint
Equivalent of `` where '' command prompt command in C #
C#
I just hit a situation where a method dispatch was ambiguous and wondered if anyone could explain on what basis the compiler ( .NET 4.0.30319 ) chooses what overload to callIn any case , why does the compiler not warn me or even why does it compile ? Thank you very much for any answers .
interface IfaceA { } interface IfaceB < T > { void Add ( IfaceA a ) ; T Add ( T t ) ; } class ConcreteA : IfaceA { } class abstract BaseClassB < T > : IfaceB < T > { public virtual T Add ( T t ) { ... } public virtual void Add ( IfaceA a ) { ... } } class ConcreteB : BaseClassB < IfaceA > { // does not override one of the relevant methods } void code ( ) { var concreteB = new ConcreteB ( ) ; // it will call void Add ( IfaceA a ) concreteB.Add ( new ConcreteA ( ) ) ; }
c # Generic overloaded method dispatching ambiguous
C#
This question is about this code : I answered this question yesterday and if you notice in the comments to the question ( not the answer ) , one of the members @ gertarnold said this : entityEntry.Property ( `` InsertedBy '' ) does n't use reflection , it reads the EF metadata . Sure it uses the EF metadata to figure out if the entity has that property but I am pretty sure somewhere down the line they would have to use reflection to set the property.I tried looking at the source code here , here and here ( line 484 ) and then chickened out.So the questions are : Does it use reflection ? If not , how is the property set then ?
entityEntry.Property ( `` WhateverProperty '' ) .CurrentValue = 1 ;
Does the Entity Framework DbEntityEntry.Property method use reflection ?
C#
I have a Mailchimp RSS campaign that reads an RSS feed on a website and is set to once a day . I would like to send this campaign pro-grammatically after I add an item to the feed.I am using PerceptiveMCAPI and My code for triggering the campaign isThe error I receive looks likeAny ideas on what would be causing this ?
campaignSendNowInput campaignSendNowInput = new campaignSendNowInput ( apiKey , campaignKey ) ; campaignSendNow campaignSendNow = new campaignSendNow ( campaignSendNowInput ) ; campaignSendNowOutput campaignSendNowOutput = campaignSendNow.Execute ( ) ; `` Error Code : 313 , Message : This Campaign has already been sent and can not be sent again . ''
Mailchimp Campaign Send Error - This Campaign has already been sent and can not be sent again
C#
The following code will throw an exception : This seems like strange behavior to me , can someone explain why this is n't a bug ? Or perhaps suggest a workaround ? Instantiating a Regex object in place of the null will of course stop this from throwing an exception.The exception produced is : Newtonsoft.Json.JsonSerializationException : Unexpected token when reading Regex . Path 'RegProp ' , line 1 , position 15 .
class SimpleClassWithRegex { public Regex RegProp { get ; set ; } } [ TestMethod ] public void RegexTest ( ) { string json = JsonConvert.SerializeObject ( new SimpleClassWithRegex { RegProp = null } ) ; // json = { `` RegProp '' : null } SimpleClassWithRegex obj = JsonConvert.DeserializeObject < SimpleClassWithRegex > ( json ) ; //Above line throws a JsonSerializationException }
Deserialize null regex property with json.net
C#
The language I use is C # .Let we have a List of objects of type T , Say that we want to go over each item of collection . That can be done in many ways . Among of them , are the following two : andDoes the second way be better than the first or not and why ? Thanks in advance for your answers .
List < T > collection = new List < T > { ... .. } ; foreach ( var item in collection ) { // code goes here } foreach ( T item in collection ) { // code goes here }
faster way between to ways of iterating through all the elements of a collection in C #
C#
I have this interface that is being used by a handful of concrete types , such as EmailFormatter , TextMessageFormatter etc.The issue I 'm having is that with my EmailNotificationService is that I want to inject EmailFormatter . The constructor signature for this service is public EmailNotificationService ( IFormatter < string > emailFormatter ) .I 'm pretty sure I 've seen this done before but how do I register this with Windsor so that it injects EmailFormatter if the constructor parameter name is emailFormatter ? Here is my Windsor registration code .
public interface IFormatter < T > { T Format ( CompletedItem completedItem ) ; } container.Register ( Component.For < IFormatter < string > > ( ) .ImplementedBy < EmailFormatter > ( ) ) ;
How to inject proper dependency based on constructor parameter name
C#
I am trying to understand how ASP.NET MVC works and I have been recommended to follow the MVC Music Store Tutorial , however I am having problems since I am using different ( more current ) software.According to this page I should add a List of genres to my action method inside my StoreController.cs . However according to Visual studio , this piece of code seems to be incorrect or not recognized . The error says : Identifier expected ; 'new ' is a keyword . Should I use different code or do this in my model class instead in some way ? Should n't something like this do the job ? : And does n't this constantly add the genres everytime I would run through the Index action method ?
public ActionResult Index ( ) { var genres = new List < Genre > { new Genre = { Name = `` Disco '' } , new Genre = { Name = `` Jazz '' } , new Genre = { Name = `` Rock '' } } ; return View ( ) ; } public ActionResult Index ( ) { //var genres = new List < Genre > // { // new Genre = { Name = `` Disco '' } , // new Genre = { Name = `` Jazz '' } , // new Genre = { Name = `` Rock '' } // } ; var genres = new List < Genre > ( ) ; genres.Add ( new Genre ( ) { Name = `` Disco '' } ) ; genres.Add ( new Genre ( ) { Name = `` Jazz '' } ) ; genres.Add ( new Genre ( ) { Name = `` Rock '' } ) ; return View ( ) ; }
Is this deprecated way of coding ? ASP.Net MVC
C#
I 've imported Microsoft.VisualStudio.Threading into .Net Core Web App . I did this specifically to make use of AsyncLazy < T > .I wanted to make sure I did this right , so I imported the appropriate Analyzers.The warnings and the documentation clearly state that a JoinableTaskFactory should be injected into my implementation.My question is , how should I instantiate that JoinableTaskFactory in the configuration of my .Net Core Web App ? Is it as simple as or , is that all wrong ?
public void ConfigureServices ( IServiceCollection services ) { // ... services.AddSingleton ( new JoinableTaskFactory ( ) ) ; // ... }
Do I use a JoinableTaskFactory with AspNetCore ?
C#
So I want to execute PowerShell Calculated Properties ( I hope that 's the correct name ) from C # .My CmdLet in the PS ( Exchange ) Console looks like this : This works just fine , the problem occures when I try to execute it from C # .My Code looks like this : My result then contains the empty ToBeExpandedGuid ( null ) . So I tried the command without the second select and it shows me that it has the column : So my thought was that powershell does n't recognize this renaming ... Now my question how do I use something like this from C # ? Is there any solution ?
Get-Something -ResultSize unlimited |Select-Object DisplayName , @ { name= '' RenamedColumn ; expression= { $ _.Name } } , ToBeExpanded -Expand ToBeExpanded |Select-Object DisplayNameRenamedColumn , ToBeExpandedGuid List < string > parameters = new List < string > ( ) { `` DisplayName '' , '' @ { { name=\ '' RenamedColumn\ '' ; expression= { { $ _.Name } } } } '' , '' ToBeExpanded '' } ; List < string > parameters2 = new List < string > ( ) { `` DisplayName '' , '' RenamedColumn '' , '' ToBeExpanded '' , '' ToBeExpandedGuid '' } ; powershell.AddCommand ( `` Get-Something '' ) ; powershell.AddParameter ( `` ResultSize '' , '' unlimited '' ) ; powershell.AddCommand ( `` Select-Object '' ) ; powershell.AddParameter ( `` Property '' , parameters ) ; powershell.AddParameter ( `` ExpandProperty '' , '' ToBeExpanded '' ) ; powershell.AddCommand ( `` Select-Object '' ) ; powershell.AddParameters ( `` Property '' , parameters2 ) ; result = powershell.Invoke ( ) ; @ { { name=\ '' RenamedColumn\ '' ; expression= { { $ _.Name } } } }
Using PowerShell Calculated Properties from C #
C#
I am confused by some code that should n't be working , but oddly enough , is working and I know I 'm simply overlooking something obvious . I 'm looking at the source code for the Accord.NET framework and I downloaded it and its compiling just fine , but I 'm confused about something . In one of the assemblies , called Accord.Math is a file called Indices.cs . Here is the definition : You can see this on line 35.Over in another assembly , called Accord.Statistics , there is a file called Tools.cs . In that file , there is this line : You can see this on line 329.I am confused on how this line can reference the Accord.Math.Indices class since it is marked as internal . My understanding is that a class marked as internal can only be accessed by classes that reside in the same DLL file . Can someone explain how this is working ?
internal static class Indices { // Lots of code // ... // ... } return Accord.Math.Indices.Random ( k , n ) ;
Accessing an internal class from a different Dll file
C#
From the docs for the TakeUntil operator ( emphasis mine ) : The TakeUntil subscribes and begins mirroring the source Observable . It also monitors a second Observable that you provide . If this second Observable emits an item or sends a termination notification , the Observable returned by TakeUntil stops mirroring the source Observable and terminates.If this is true , then why does this block ? :
Observable.Never < Unit > ( ) .TakeUntil ( Observable.Empty < Unit > ( ) ) .Wait ( ) ;
TakeUntil not working as documented ?
C#
I 'm developing a multi-tenant application in ASP.NET Core 2.1 . I 'm utilizing AspNetCore.Identity.EntityFrameworkCore framework for user management . I want to add a unique index combining NormalizedName with TenantId in Role Table . Also , in the user table NormalizedUserName with TenantId in User table . This does n't let me create that index since identity creates a default unique indexes for Role table RoleNameIndex and UserNameIndex for User table . What is the best way to configure that in OnModelCreating method in EF Core ?
modelBuilder.Entity < User > ( ) .HasIndex ( u = > new { u.NormalizedUserName , u.TenantId } ) .HasName ( `` UserNameIndex '' ) .IsUnique ( true ) ; modelBuilder.Entity < Role > ( ) .HasIndex ( u = > new { u.NormalizedName , u.TenantId } ) .HasName ( `` RoleNameIndex '' ) .IsUnique ( true ) ;
Override default indexes in AspNetCore.Identity tables
C#
FsCheck has some neat default Arbitrary types to generate test data . However what if one of my test dates depends on another ? For instance , consider the property of string.Substring ( ) that a resulting substring can never be longer than the input string : Although the implementation of Substring certainly is correct , this property fails , because eventually a PositiveInt will be generated that is longer than the genereated NonEmptyString resulting in an exception . Shrunk : NonEmptyString `` a '' PositiveInt 2 with exception : System.ArgumentOutOfRangeException : Index and length must refer to a location within the string.I could guard the comparison with an if ( input.Length < length ) return true ; but that way I end up with lots of test runs were the property is n't even checked.How do I tell FsCheck to only generate PositiveInts that do n't exceed the input string ? I presume I have to use the Gen < T > class , but it 's interface is just hella confusing to me ... I tried the following but still got PositiveInts exceeding the string :
[ Fact ] public void SubstringIsNeverLongerThanInputString ( ) { Prop.ForAll ( Arb.Default.NonEmptyString ( ) , Arb.Default.PositiveInt ( ) , ( input , length ) = > input.Get.Substring ( 0 , length.Get ) .Length < = input.Get.Length ) .QuickCheckThrowOnFailure ( ) ; } var inputs = Arb.Default.NonEmptyString ( ) ; // I have no idea what I 'm doing here ... var lengths = inputs.Generator.Select ( s = > s.Get.Length ) .ToArbitrary ( ) ; Prop.ForAll ( inputs , lengths , ( input , length ) = > input.Get.Substring ( 0 , length ) .Length < = input.Get.Length ) .QuickCheckThrowOnFailure ( ) ;
FsCheck : How to generate test data that depends on other test data ?
C#
I am trying to insert millisecond into data type of datetime ( 6 ) in MySQL using c # .here is my code : the createtiming is created withI have read the value of createtiming before it inserts into MySQL , and it does contain milliseconds , however , when I do on MySQL , I only see time like While the time should be like 2015-08-27 15:33:04.123456 something like this.I am trying to Order the table by using this createtiming to the very millisecond.How should I get this done ?
MySqlCommand myCommand4 = new MySqlCommand ( `` Insert into Test_OrderRecord values ( ' '' + OrderID + `` ' , ' '' + customerCode + `` ' , ' '' + customer + `` ' , ' '' + TelComboBox.Text + `` ' , ' '' + LicenseComboBox.Text + `` ' , ' '' + DriverComboBox.Text + `` ' , ' '' + AddressComboBox.Text + `` ' , ' '' + LocationTypeComboBox.Text + `` ' , ' '' + PickupComboBox.Text + `` ' , ' '' + CustomerTypeLabel.Text + `` ' , ' '' + Convert.ToDecimal ( TotalPriceLabel.Text ) + `` ' , ' '' + status + `` ' , ' '' + note + `` ' , ' '' + sandReceiptNo + `` ' , ' '' + createtiming + `` ' , ' '' + DateTime.Now.ToString ( `` yyyy-MM-dd HH : mm : ss '' ) + `` ' ) '' , myConnection ) ; myCommand4.ExecuteNonQuery ( ) ; createtiming = OrderDateTimePicker.Value.ToString ( `` yyyy-MM-dd HH : mm : ss : ffffff '' ) ; SELECT * FROM SaveFundDevelopmentDB.Test_OrderDetails 2015-08-27 15:33:04.000000
inserting millisecond into mysql from c #
C#
I would expect `` 2- '' and `` 22 '' to always compare the same way , but changing the 3rd character changes the sort order . What on earth is happening here ? Our culture is en-US by the way .
string.Compare ( `` 2-1 '' , '' 22- '' , StringComparison.CurrentCulture ) //-1string.Compare ( `` 2-2 '' , '' 22- '' , StringComparison.CurrentCulture ) //1
Character after hyphen affects string.compare
C#
I am using Visual Studio and I am very confused about the best way to store configuration strings . I am creating a Windows Forms Application . I need very basic security -- I do n't want the password to be readable in app.config but I am not concerned about someone disassembling my code in order to figure it out . So , in the Data Source Wizard , I said `` Do n't Save Password '' and then I put the following code in Settings.Designer.CS : I realize that this is n't the best solution but I ca n't think of a better one . I would appreciate anyone 's help and input on this.Thanks -- Missy .
public string MyConnectionString { get { return ( ( string ) ( `` Data Source=SQLSERVER\\ACCOUNTING ; Initial Catalog=ACCOUNTING ; User ID=MyUser ; Password=28947239SKJFKJF '' ) ) ; } }
Proper Storage of Configuration Strings
C#
ProblemProblem shapingImage sequence position and size are fixed and known beforehand ( it 's not scaled ) . It will be quite short , maximum of 20 frames and in a closed loop . I want to verify ( event driven by button click ) , that I have seen it before . Lets say I have some image sequence , like : http : //img514.imageshack.us/img514/5440/60372aeba8595eda.gifIf seen , I want to see the ID associated with it , if not - it will be analyzed and added as new instance of image sequence , that has been seen . I have though about this quite a while , and I admit , this might be a hard problem . I seem to be having hard time of putting this all together , can someone assist ( in C # ) ? Limitations and usesI am not trying to recreate copyright detection system , like content id system Youtube has implemented ( Margaret Gould Stewart at TED ( link ) ) . The image sequence can be thought about like a ( .gif ) file , but it is not and there is no direct way to get binary . Similar method could be used , to avoid duplicates in `` image sharing database '' , but it is not what I am trying to do.My effortGaussian blurMathematica function to generate Gaussian blur kernels : Turns out , that it is much more efficient to use 2 passes of vector kernel , then matrix kernel . Thy are based on Pascal triangle uneven rows : Data input , hashing , grayscaleing and lightboxingExample of source bits , that might be useful : Lightbox around the known rectangle : FrameX Using MD5CryptoServiceProvider to get md5 hash of the content inside known rectangle atm.Using ColorMatrix to grayscale imageSource exampleSource example ( GUI ; code ) : Get current content inside defined rectangle.Get md5 hash of bitmap.Get grayscale of the image .
getKernel [ L_ ] : = Transpose [ { L } ] . { L } / ( Total [ Total [ Transpose [ { L } ] . { L } ] ] ) getVKernel [ L_ ] : = L/Total [ L ] { 1d/4 , 1d/2 , 1d/4 } { 1d/16 , 1d/4 , 3d/8 , 1d/4 , 1d/16 } { 1d/64 , 3d/32 , 15d/64 , 5d/16 , 15d/64 , 3d/32 , 1d/64 } private Bitmap getContentBitmap ( ) { Rectangle r = f.r ; Bitmap hc = new Bitmap ( r.Width , r.Height ) ; using ( Graphics gf = Graphics.FromImage ( hc ) ) { gf.CopyFromScreen ( r.Left , r.Top , 0 , 0 , // new Size ( r.Width , r.Height ) , CopyPixelOperation.SourceCopy ) ; } return hc ; } private byte [ ] getBitmapHash ( Bitmap hc ) { return md5.ComputeHash ( c.ConvertTo ( hc , typeof ( byte [ ] ) ) as byte [ ] ) ; } public static Bitmap getGrayscale ( Bitmap hc ) { Bitmap result = new Bitmap ( hc.Width , hc.Height ) ; ColorMatrix colorMatrix = new ColorMatrix ( new float [ ] [ ] { new float [ ] { 0.5f,0.5f,0.5f,0,0 } , new float [ ] { 0.5f,0.5f,0.5f,0,0 } , new float [ ] { 0.5f,0.5f,0.5f,0,0 } , new float [ ] { 0,0,0,1,0,0 } , new float [ ] { 0,0,0,0,1,0 } , new float [ ] { 0,0,0,0,0,1 } } ) ; using ( Graphics g = Graphics.FromImage ( result ) ) { ImageAttributes attributes = new ImageAttributes ( ) ; attributes.SetColorMatrix ( colorMatrix ) ; g.DrawImage ( hc , new Rectangle ( 0 , 0 , hc.Width , hc.Height ) , 0 , 0 , hc.Width , hc.Height , GraphicsUnit.Pixel , attributes ) ; } return result ; }
Verify image sequence
C#
I been scratching my head trying to figure out why a project I have ( what I did not touch ) was not working anymore.Basically I was trying trying to get some data back from google contacts . When I selected `` allow '' in the oAuth part it would keep giving me a 404 error . This is all done in the windows phone 7 emulator.I then realized that I was on my Windows 8 partition so I went back to my windows 7 partition and it works.Wondering if it is some IE 10 issue or something . Anyone have any theories of why this is happening ? EditHere is some quick sample code I whipped up maybe someone can try it and tell me what is going on.xamlEdit2They released IE 10 for Windows 7 so I installed that and it still works on Windows 7 so I guess it is not an IE issue . Must be something with Windows 8 ? Maybe iis ? Edit3Here is a flow of what is happening in Windows 7Application start up and loads MainPg.xmalNavigated is triggered but if statement is skippedUser Sees Google Login Page and enters in information and hits loginNavigated is triggered but if statement is skippedUser sees `` request page '' and must allow application permissionsUser hit allowNavigated is triggered and goes into `` if '' statementUser sees IIS 7 screen.Here is a flow of what is happening in Windows 8Application start up and loads MainPg.xmalNavigated is triggered but if statement is skippedUser Sees Google Login Page and enters in information and hits loginNavigated is triggered but if statement is skippedUser sees `` request page '' and must allow application permissionsUser hit allowGoes to 404 pages Navigated is not triggered.As you can see it goes all wrong after the allow button is pressed . In windows 7 it goes back to the Navigated method and then shows IIS 7 welcome page but in Windows 8 after the allow button is hit it does not go to the navigated page and shows 404 instead .
string clientId = `` You client id here '' ; public MainPage ( ) { InitializeComponent ( ) ; string url = String.Format ( `` https : //accounts.google.com/o/oauth2/auth ? scope=https : //www.google.com/m8/feeds & redirect_uri=http : //localhost & response_type=code & approval_prompt=auto & client_id= { 0 } '' , clientId ) ; webBrowser1.Navigated += new EventHandler < System.Windows.Navigation.NavigationEventArgs > ( webBrowser1_Navigated ) ; webBrowser1.Navigate ( new Uri ( url , UriKind.Absolute ) ) ; } void webBrowser1_Navigated ( object sender , System.Windows.Navigation.NavigationEventArgs e ) { var queryParmas = e.Uri.ParseQueryString ( ) ; foreach ( var item in queryParmas ) { if ( item.Key == `` code '' ) { string test1 = `` If you got here then it works '' ; string test2 = `` in windows 8 '' ; } } } } < Grid x : Name= '' ContentPanel '' Grid.Row= '' 1 '' Margin= '' 12,0,12,0 '' > < phone : WebBrowser HorizontalAlignment= '' Left '' IsScriptEnabled= '' True '' Name= '' webBrowser1 '' VerticalAlignment= '' Top '' Height= '' 669 '' Width= '' 468 '' / > < /Grid >
Google Api Redirect gives me 404 error on WP7 When using Windows 8 but not Windows 7
C#
I am currently writing a resource manager for my game . This is basically a class that will handle all kinds of other objects of different types , and each object is referred to by name ( a System.String ) . Now this is my current implementation , but since I am using a dictionary of objects I will still need to cast every object . Is there a way to use Generics in this case ? I 'm not very strong on those , I tried reading up on them and it just ended up confusing me more .
public static class ResourceManager { public static Dictionary < string , object > Resources { get ; private set ; } public static void LoadResources ( ) { Resources = new Dictionary < string , object > ( ) ; //Sample resource loading code Resources.Add ( `` number '' , 3 ) ; Resources.Add ( `` string '' , `` bleh '' ) ; Console.Log ( `` Loaded `` + Resources.Count + `` resources . `` ) ; } }
Dictionary using generics
C#
The below code works fine : Whereas the below code wo n't compile : In the second example the compiler says that i am trying to set a property on a variable that has not been instantiated . In either case lstMyControl must be instantiated , but the compilr ca n't seem to follow that code paths through the switch statement to see that . In the above simple example i would just use if/else . But there are a few times when I have wanted to do something like this with 10 different classes that all inherit from the same base class and having a 10 if/elseif statements is annoying when a switch statement is what i should be using .
ListControl lstMyControl ; if ( SomeVariable == SomeEnum.Value1 ) { lstMyControl = new DropDownList ( ) ; } else { lstMyControl = new RadioButtonList ( ) ; } lstMyControl.CssClass = `` SomeClass '' ; ListControl lstMyControl ; switch ( SomeVariable ) { case SomeEnum.Value1 : lstMyControl = new DropDownList ( ) ; break ; case default : lstMyControl = new RadioButtonList ( ) ; break ; } lstMyControl.CssClass = `` SomeClass '' ;
Why ca n't C # compiler follow all code paths through a switch statement
C#
Is there a way to do what classmethod does in Python in C # ? That is , a static function that would get a Type object as an ( implicit ) parameter according to whichever subclass it 's used from.An example of what I want , approximately , isthe expected output being ( same code on codepad here . )
class Base : @ classmethod def get ( cls , id ) : print `` Would instantiate a new % r with ID % d . `` % ( cls , id ) class Puppy ( Base ) : passclass Kitten ( Base ) : passp = Puppy.get ( 1 ) k = Kitten.get ( 1 ) Would instantiate a new < class __main__.Puppy at 0x403533ec > with ID 1.Would instantiate a new < class __main__.Kitten at 0x4035341c > with ID 1 .
Python-style classmethod for C # ?
C#
I want to calculate the mean absolute deviation and I 'm currently using the following class from Stack Overflow ( link here ) , posted by Alex : The person who made that class , did it somehow weirdly and I do n't understand the calculations , because he 's using different formulas . For example , people normally calculate the variance just like this.Can someone explain me how to calculate the mean absolution deviation in that class ? Formulas : Edit : This one is a bit more accurate but not enough . Any ideas ? Output ( should be ) : Output ( what it is ) : Output from another CCI ( should be ) : Output from CommodityChannelIndex.cs ( what it is ) : A working example code : The actual ( broken ) code that I want to fix : The sum for the mean absolute deviation is broken . The question is how to fix it ? Edit : After Alireza 's correction . Still inaccurate.Project repo : https : //github.com/Warrolen/test-project
public class MovingAverageCalculator { private readonly int _period ; private readonly double [ ] _window ; private int _numAdded ; private double _varianceSum ; public MovingAverageCalculator ( int period ) { _period = period ; _window = new double [ period ] ; } public double Average { get ; private set ; } public double StandardDeviation { get { var variance = Variance ; if ( variance > = double.Epsilon ) { var sd = Math.Sqrt ( variance ) ; return double.IsNaN ( sd ) ? 0.0 : sd ; } return 0.0 ; } } public double Variance { get { var n = N ; return n > 1 ? _varianceSum / ( n - 1 ) : 0.0 ; } } public bool HasFullPeriod { get { return _numAdded > = _period ; } } public IEnumerable < double > Observations { get { return _window.Take ( N ) ; } } public int N { get { return Math.Min ( _numAdded , _period ) ; } } public void AddObservation ( double observation ) { // Window is treated as a circular buffer . var ndx = _numAdded % _period ; var old = _window [ ndx ] ; // get value to remove from window _window [ ndx ] = observation ; // add new observation in its place . _numAdded++ ; // Update average and standard deviation using deltas var old_avg = Average ; if ( _numAdded < = _period ) { var delta = observation - old_avg ; Average += delta / _numAdded ; _varianceSum += ( delta * ( observation - Average ) ) ; } else // use delta vs removed observation . { var delta = observation - old ; Average += delta / _period ; _varianceSum += ( delta * ( ( observation - Average ) + ( old - old_avg ) ) ) ; } } } CCI = -29.189669CCI = -57.578105CCI = 1.537557CCI = 46.973803CCI = 68.662979CCI = 78.647204CCI = 52.798310CCI = 84.266845CCI = 104.694912CCI = 99.048428CCI = 58.068118CCI = 57.575758CCI = 68.387309CCI = 127.625967CCI = 128.826508CCI = 124.751608CCI = 112.929293CCI = 165.170449CCI = 141.586505CCI = 114.463325CCI = 155.766418 CCI = -26.630104CCI = -53.295597CCI = 1.476909CCI = 44.829571CCI = 67.857143CCI = 80.059829CCI = 55.447471CCI = 90.681818CCI = 116.030534CCI = 106.314948CCI = 61.242833CCI = 61.664226CCI = 74.962064CCI = 150.864780CCI = 163.034547CCI = 162.636347CCI = 153.194865CCI = 197.583882CCI = 159.622130CCI = 122.744143CCI = 163.325826 Typical Price : 0.010153 | SMA : 0.009989 | Mean Deviation : 0.000139Typical Price : 0.010100 | SMA : 0.009988 | Mean Deviation : 0.000142Typical Price : 0.010180 | SMA : 0.009991 | Mean Deviation : 0.000150Typical Price : 0.010230 | SMA : 0.009990 | Mean Deviation : 0.000153Typical Price : 0.010233 | SMA : 0.010000 | Mean Deviation : 0.000157Typical Price : 0.010147 | SMA : 0.010008 | Mean Deviation : 0.000159Typical Price : 0.010160 | SMA : 0.010027 | Mean Deviation : 0.000154Typical Price : 0.010200 | SMA : 0.010044 | Mean Deviation : 0.000152Typical Price : 0.010380 | SMA : 0.010077 | Mean Deviation : 0.000158Typical Price : 0.010413 | SMA : 0.010107 | Mean Deviation : 0.000159Typical Price : 0.010447 | SMA : 0.010138 | Mean Deviation : 0.000165Typical Price : 0.010450 | SMA : 0.010171 | Mean Deviation : 0.000165Typical Price : 0.010657 | SMA : 0.010199 | Mean Deviation : 0.000185Typical Price : 0.010647 | SMA : 0.010224 | Mean Deviation : 0.000199Typical Price : 0.010623 | SMA : 0.010252 | Mean Deviation : 0.000216Typical Price : 0.010880 | SMA : 0.010308 | Mean Deviation : 0.000245Typical Price : 0.010863 | SMA : 0.010354 | Mean Deviation : 0.000263Typical Price : 0.010853 | SMA : 0.010397 | Mean Deviation : 0.000285Typical Price : 0.010967 | SMA : 0.010442 | Mean Deviation : 0.000307Typical Price : 0.011480 | SMA : 0.010517 | Mean Deviation : 0.000356Typical Price : 0.011750 | SMA : 0.010600 | Mean Deviation : 0.000408Typical Price : 0.011653 | SMA : 0.010674 | Mean Deviation : 0.000448 Typical Price : 0.010153 | SMA : 0.009989 | Mean Deviation : 0.000137Typical Price : 0.010100 | SMA : 0.009988 | Mean Deviation : 0.000135Typical Price : 0.010180 | SMA : 0.009991 | Mean Deviation : 0.000139Typical Price : 0.010230 | SMA : 0.009990 | Mean Deviation : 0.000138Typical Price : 0.010233 | SMA : 0.010000 | Mean Deviation : 0.000146Typical Price : 0.010147 | SMA : 0.010008 | Mean Deviation : 0.000151Typical Price : 0.010160 | SMA : 0.010027 | Mean Deviation : 0.000144Typical Price : 0.010200 | SMA : 0.010044 | Mean Deviation : 0.000139Typical Price : 0.010380 | SMA : 0.010077 | Mean Deviation : 0.000134Typical Price : 0.010413 | SMA : 0.010107 | Mean Deviation : 0.000125Typical Price : 0.010447 | SMA : 0.010138 | Mean Deviation : 0.000127Typical Price : 0.010450 | SMA : 0.010171 | Mean Deviation : 0.000122Typical Price : 0.010657 | SMA : 0.010199 | Mean Deviation : 0.000154Typical Price : 0.010647 | SMA : 0.010224 | Mean Deviation : 0.000177Typical Price : 0.010623 | SMA : 0.010252 | Mean Deviation : 0.000202Typical Price : 0.010880 | SMA : 0.010308 | Mean Deviation : 0.000234Typical Price : 0.010863 | SMA : 0.010354 | Mean Deviation : 0.000244Typical Price : 0.010853 | SMA : 0.010397 | Mean Deviation : 0.000255Typical Price : 0.010967 | SMA : 0.010442 | Mean Deviation : 0.000273Typical Price : 0.011480 | SMA : 0.010517 | Mean Deviation : 0.000329Typical Price : 0.011750 | SMA : 0.010600 | Mean Deviation : 0.000389Typical Price : 0.011653 | SMA : 0.010674 | Mean Deviation : 0.000423 public decimal [ ] Calculate ( IReadOnlyList < ( decimal High , decimal Low , decimal Close ) > candles , int period ) { var ccis = new decimal [ candles.Count ] ; SMA sma = new SMA ( period ) ; var smas = sma.Calculate ( candles.Select ( e = > e.Close ) .ToArray ( ) ) ; for ( int i = 0 ; i < candles.Count ; i++ ) { var typicalPrice = ( candles [ i ] .High + candles [ i ] .Low + candles [ i ] .Close ) / 3m ; decimal total = 0m ; for ( int j = i ; j > = Math.Max ( i - period + 1 , 0 ) ; j -- ) { total += Math.Abs ( smas [ j ] - candles [ j ] .Close ) ; Console.WriteLine ( `` Sum = `` + total.ToString ( `` f6 '' ) ) ; } decimal meanDeviation = total / period ; decimal cci = meanDeviation ! = 0 ? ( typicalPrice - smas [ i ] ) / meanDeviation / 0.015m : 0 ; //Console.WriteLine ( $ '' Typical Price : { typicalPrice.ToString ( `` f6 '' ) } | SMA : { smas [ i ] .ToString ( `` f6 '' ) } | Mean Deviation : { meanDeviation.ToString ( `` f6 '' ) } '' ) ; ccis [ i ] = cci ; } return ccis ; } public class MovingAverageCalculator { private readonly int _period ; private readonly double [ ] _window ; private int _numAdded ; private double _varianceSum ; public MovingAverageCalculator ( int period ) { _period = period ; _window = new double [ period ] ; } public double Average { get ; private set ; } public double StandardDeviation { get { var variance = Variance ; if ( variance > = double.Epsilon ) { var sd = Math.Sqrt ( variance ) ; return double.IsNaN ( sd ) ? 0.0 : sd ; } return 0.0 ; } } public double Variance { get { var n = N ; return n > 1 ? _varianceSum / ( n - 1 ) : 0.0 ; } } public double MeanAbsoluteDeviation { get { //return _window.Average ( e = > Math.Abs ( e - Average ) ) ; // https : //stackoverflow.com/questions/5336457/how-to-calculate-a-standard-deviation-array var n = N ; var sumOfDifferences = _window.Sum ( e = > Math.Abs ( e - Average ) ) ; return n > 1 ? sumOfDifferences / ( n - 1 ) : 0.0 ; } } public bool HasFullPeriod { get { return _numAdded > = _period ; } } public IEnumerable < double > Observations { get { return _window.Take ( N ) ; } } public int N { get { return Math.Min ( _numAdded , _period ) ; } } public void AddObservation ( double observation ) { // Window is treated as a circular buffer . var ndx = _numAdded % _period ; var old = _window [ ndx ] ; // get value to remove from window _window [ ndx ] = observation ; // add new observation in its place . _numAdded++ ; // Update average and standard deviation using deltas var oldAvg = Average ; if ( _numAdded < = _period ) { var delta = observation - oldAvg ; Average += delta / _numAdded ; _varianceSum += ( delta * ( observation - Average ) ) ; } else // use delta vs removed observation . { var delta = observation - old ; Average += delta / _period ; _varianceSum += ( delta * ( ( observation - Average ) + ( old - oldAvg ) ) ) ; } } public void Reset ( ) { _numAdded = 0 ; _varianceSum = 0 ; } } public class CommodityChannelIndex : Indicator < ( decimal High , decimal Low , decimal Close ) , decimal > { private readonly int _period ; private readonly MovingAverageCalculator _movingAvg ; public CommodityChannelIndex ( int period ) { _period = period ; _movingAvg = new MovingAverageCalculator ( _period ) ; } public override decimal ComputeNextValue ( ( decimal High , decimal Low , decimal Close ) input ) { decimal typicalPrice = ( input.High + input.Low + input.Close ) / 3m ; _movingAvg.AddObservation ( ( double ) input.Close ) ; if ( _movingAvg.HasFullPeriod ) { var average = ( decimal ) _movingAvg.Average ; var meanDeviation = ( decimal ) _movingAvg.MeanAbsoluteDeviation ; return meanDeviation ! = 0m ? ( typicalPrice - average ) / meanDeviation / 0.015m : 0m ; } return 0 ; } public override void Reset ( ) { throw new System.NotImplementedException ( ) ; } } // USAGECommodityChannelIndex rsi = new CommodityChannelIndex ( 20 ) ; for ( int i = 0 ; i < candles.Count - 1 ; i++ ) { var result = rsi.ComputeNextValue ( ( candles [ i ] .High , candles [ i ] .Low , candles [ i ] .Close ) ) ; Console.WriteLine ( $ '' CCI = { result.ToString ( `` f6 '' ) } '' ) ; } Correct ( how it should be ) : CCI = -11.554556CCI = 21.045918CCI = 38.828097CCI = 22.566381CCI = 59.149184CCI = 77.075455CCI = 38.104311CCI = 13.746847CCI = -41.996578CCI = -89.997229CCI = -77.630112CCI = 18.273976CCI = 9.525936CCI = -11.306480CCI = 74.880871CCI = 186.070619CCI = 19.839042CCI = -159.106198Incorrect ( n - 1 ) - before Alireza 's answer : CCI = -29.587542CCI = 45.010768CCI = 69.666667CCI = 34.518799CCI = 75.449922CCI = 89.486260CCI = 43.181818CCI = 15.962060CCI = -47.174211CCI = -99.664083CCI = -80.542391CCI = 17.952962CCI = 8.888889CCI = -10.138104CCI = 66.560510CCI = 169.550087CCI = 18.679280CCI = -154.360812Incorrect ( n ) - after Alireza 's answerCCI = -31.144781CCI = 47.379756CCI = 73.333333CCI = 36.335578CCI = 79.420970CCI = 94.196064CCI = 45.454545CCI = 16.802168CCI = -49.657064CCI = -104.909561CCI = -84.781464CCI = 18.897855CCI = 9.356725CCI = -10.671689CCI = 70.063694CCI = 178.473776CCI = 19.662400CCI = -162.485066
Calculating mean absolute deviation
C#
While trying to organize some data access code using EF Core I noticed that the generated queries were worse than before , they now queried columns that were not needed . The basic query is just selecting from one table and mapping a subset of columns to a DTO . But after rewriting it now all columns are fetched , not just the ones in the DTO.I created a minimal example with some queries that show the problem : The objects are defined like this : The first query queries all columns as intended , and the second query with an anonymous object only queries the selected queries , that works all fine . Using my MinimalItem DTO also works as long as it is created directly in the Select method . But the last two queries fetch all columns even though they do exactly the same thing as the third query , just moved to a constructor or an extension method , respectively.Obviously EF Core ca n't follow this code and determine that it only needs the two columns if I move it out of the Select method . But I 'd really like to do that to be able to reuse the mapping code , and make the actual query code easier to read . How can I extract this kind of straightforward mapping code without making EF Core inefficiently fetching all columns all the time ?
ctx.Items.ToList ( ) ; // SELECT i . `` Id '' , i . `` Property1 '' , i . `` Property2 '' , i . `` Property3 '' FROM `` Items '' AS ictx.Items.Select ( x = > new { Id = x.Id , Property1 = x.Property1 } ) .ToList ( ) ; // SELECT i . `` Id '' , i . `` Property1 '' FROM `` Items '' AS ictx.Items.Select ( x = > new MinimalItem { Id = x.Id , Property1 = x.Property1 } ) .ToList ( ) ; // SELECT i . `` Id '' , i . `` Property1 '' FROM `` Items '' AS ictx.Items.Select ( x = > x.MapToMinimalItem ( ) ) .ToList ( ) ; // SELECT i . `` Id '' , i . `` Property1 '' , i . `` Property2 '' , i . `` Property3 '' FROM `` Items '' AS ictx.Items.Select ( x = > new MinimalItem ( x ) ) .ToList ( ) ; // SELECT i . `` Id '' , i . `` Property1 '' , i . `` Property2 '' , i . `` Property3 '' FROM `` Items '' AS i public class Item { public int Id { get ; set ; } public string Property1 { get ; set ; } public string Property2 { get ; set ; } public string Property3 { get ; set ; } } public class MinimalItem { public MinimalItem ( ) { } public MinimalItem ( Item source ) { Id = source.Id ; Property1 = source.Property1 ; } public int Id { get ; set ; } public string Property1 { get ; set ; } } public static class ItemExtensionMethods { public static MinimalItem MapToMinimalItem ( this Item source ) { return new MinimalItem { Id = source.Id , Property1 = source.Property1 } ; } }
EF Core queries all columns in SQL when mapping to object in Select
C#
Probably a silly question , since I may have already answered my question , but I just want to be sure that I 'm not missing something Constant expressions are evaluated at compile time within checked context . I thought the following expression should n't be evaluated at compile time , since I assumed C # considers a particular expression as a constant expression only if all operands on the left-hand side are constants : Instead it appears compiler considers any subexpression where both operands are constants as a constant expression , even if other operands in an expression are non-constants ? Thus compiler may only evaluate a part of an expression at compile time , while the remained of the expression ( which contains non-constant values ) will get evaluated at run-time -- > I assume in the following example only ( 200 +100 ) gets evaluated at compile timeAre my assumptions correct ? thanx
int i= 100 ; long u = ( int.MaxValue + 100 + i ) ; //error int i=100 ; long l = int.MaxValue + i + ( 200 + 100 ) ; // works
It appears some parts of an expression may be evaluated at compile-time , while other parts at run-time
C#
Transparent images are pure evil in Windows Forms , that why I 've created a custom control class to handle them . The designer does n't show my control when it 's empty . I would like to add a subtle border , but only in the design view ( and when no border is added by the user ) . How would I do this ? My class is :
class TransparentImage : Control { public Image Image { get ; set ; } protected Graphics graphics ; public string FilePath { get ; set ; } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams ; cp.ExStyle |= 0x00000020 ; //WS_EX_TRANSPARENT return cp ; } } protected override void OnPaintBackground ( PaintEventArgs pevent ) { // Do n't paint background } protected override void OnPaint ( PaintEventArgs e ) { // Update the private member so we can use it in the OnDraw method this.graphics = e.Graphics ; // Set the best settings possible ( quality-wise ) this.graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias ; this.graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear ; this.graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality ; this.graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality ; if ( Image ! = null ) { // Sets the images ' sizes and positions var width = Image.Size.Width ; var height = Image.Size.Height ; var size = new Rectangle ( 0 , 0 , width , height ) ; // Draws the two images this.graphics.DrawImage ( Image , size ) ; } } }
How to add a border to a custom control in the design view ?
C#
This is not a question about how to change the font size . Rather , why is the size of my font changing by itself as I type ( or paste ) when it 's inside a plain TextBox control which , as you should know , only supports one color , one font , and one font size at any given time.My code : The font is set at 8pt . If I paste plain text into it , the top line will be 9 to 10pt while the bottom line is noticeably smaller ( about 8 pt ) .It does n't matter which font , font style , or font size I choose ; this keeps happening ! UpdateThanks for all your help thus far.To answer your recent questions below : My app is targetting .NET 4.5.There 's no mix up in the code , since I was able to reproduce this problem in a new Windows Forms project with nothing but a Form , a TextBox and a Button that calls the FontDialog.To answer the question about my Video drivers , I did require support for an app I purchased a few weeks ago and they told me to run DXDiag , they got back to me saying my Video Card driver is out of date , however I did n't think it was because I always check every few months . I then went to the manufacturer 's website and it said that I already have the latest drivers installed for my system.Windows Update also says there are no new available updates . I 'll check for a new version of drivers again , though.I also did a test in a new blank project where I display the font being used by the TextBox before calling FontDialog.ShowDialog ( ) , and after it has been shown and after the new font has been set and everything matches - yet there is still the issues after changing font/font size inside the textbox .
using ( FontDialog d = new FontDialog ( ) ) { // The usual properties ... if ( d.ShowDialog ( ) == DialogResult.OK ) { textbox1.Font = d.Font ; } }
Why do multiple font sizes display inside Plain TextBox ?
C#
I would like to create list of data in list of data . I believe this can be difficult to explain but I will try explain my problem very clear . I created list of data but in this list some arguments are also list of data . I have to write using this code because this are restriction ( Our Factory ) . If I take data , which are not list of data , everything working correct . Where is problem ? If I write list in list I get error . Perhaps you can see there my mistake.Program is compile.Problem ( I take data from third table using mapping in NHibernate ) : DestynationName in ModelClass : Important : I have got answer ( Topic Closed )
DestynationName = ( List < dictionaryNewInfoSupportList > x.DictImportantInformationSDestination.Select ( n= > new DictionaryNewInfoSupportList { Id = n.Destination.Id , Name = n.Destination.Desciption } ) .ToList ( ) ; public Ilist < dictionaryNewInfoSupportList > DestynationName ; class dictionaryNewInfoSupportList { public string Name { get ; set ; } public int Id { get ; set ; } } public IEnumerable < DictionaryListModel > OnList ( DictionayDisplayModel dictionary DisplayModel , int jtStartIndex = 0 , int jtPageSize = 0 , string jtSorting = null ) { var displayModel = ( DictionaryNewInfoDisplayModel ) dictionaryDisplayModel ; if ( displayModel == null ) var list = _dictImportantInformation.GetList ( ) .Select ( x= > new DictionaryNewInfoListModel { Id = x.Id Description = x.Description , IsActiveYN = x.IsActive , DestynationName = ( List < DictionaryNewInfoSupportList > ) x.DictImportantInformationXDestination.Select ( n = > new DictionaryNewInfoSupportList { Id = n.Destination.Id , Name = Destination.Description } ) .To.List ( ) } ) .ToList ( ) ; return list ; } var list = _dictImportantInformation.GetList ( ) .ToList ( ) .Select ( x = > new DictionaryNewInfoListModel { Id = x.Id , Description = x.Description , IsActiveYN = x.IsActive , DeestynationName = x.DictImportantInformationXDestination.Select ( n = > new DictionaryNewInfoSupportList { Id = n.Destination.Id , Name = n.Destination.Description } ) .ToList ( ) } ) .ToList ( ) ;
List in list ( Model ) Factory