lang
stringclasses 4
values | desc
stringlengths 2
8.98k
| code
stringlengths 7
36.2k
| title
stringlengths 12
162
|
|---|---|---|---|
C#
|
This is my Table : PupilNutritionMy another table Nutrition : This is one field to store final Rate : Case 1 : Operation field with Value 0 and Batch Id 1Case 2 : Now for operation field with Value 1 and Batch Id 1Case 3 : Now for operation field with Value 0 and Batch Id 2Case 4 : Now for operation field with Value 2 and Batch Id 2My Class file : This is how i have Done : I have tried like this but its a labour process : Similarly for Operation 1 : Similarly for Operation 2 : I think i have done a labour process as this can be done even in better way with linq query only i guess.So can anybody help me to simplify this whole process in linq query or even some better way and provide solution for Operation Value 2 which is left ?
|
Id PupilId NutritionId1 10 100 2 10 101 Id Nutritioncategory BatchId NutritionRate NutritionId Operation1 A 1 9000 100 12 B 1 5000 100 03 C 1 5000 100 14 D 2 6000 101 2 5 E 2 7000 101 2 6 F 2 8000 101 0 decimal Rate= 0 ; Rate= Rate + NutritionRate ( i.e 5000 because for batch id 1 with condition 0 only 1 record is there ) . Here i want to sum up both the value i.e ( 10000 and 5000 ) but during addition if sum of both is greater than 10000 then just take 10000 else take sum like this : if ( 9000 + 5000 > 10000 ) Rate= 10000else Rate=Rate + ( Addition of both if less than 10000 ) . Rate= Rate + NutritionRate ( i.e 8000 because for batch id 1 with condition 0 only 1 record is there ) . Here I will select Maximum value from Nutrition Rate field if there are 2 records : Rate=Rate - ( Maximum value from 6000 and 7000 so will take 7000 ) . public partial class PupilNutrition { public int Id { get ; set ; } public int PupilId { get ; set ; } public int NutritionId { get ; set ; } } public partial class Nutrition { public int Id { get ; set ; } public string Nutritioncategory { get ; set ; } public decimal NutritionRate { get ; set ; } public Nullable < int > NutritionId { get ; set ; } } batchId=1 or 2 ; // List < int > NutritionId = db.PupilNutrition.Where ( x = > PupilId == 10 ) .Select ( c = > c.NutritionId ) .ToList ( ) ; //output 100,101 var data = db.Nutrition.Where ( x = > x.BatchId == batchId & & NutritionId.Contains ( x.NutritionId.Value ) ) .ToList ( ) ; var data1=data.where ( t= > t.Operation==0 ) ; Rate= Rate + data1.Sum ( p = > p.NutritionRate ) ; var data2=data.where ( t= > t.Operation==1 ) ; This is left because here i need to sum up 2 value if two records are there as shown in my above cases and if sum is greater than 10000 than select 10000 else select sum . var data3=data.where ( t= > t.Operation==2 ) ; Rate= Rate - data3.Max ( p = > p.NutritionRate ) ;
|
Simplify process with linq query
|
C#
|
It seems exceptionally heavy handed but going by the rule anything publicly available should be tested should auto-implemented properties be tested ? Customer ClassTested by
|
public class Customer { public string EmailAddr { get ; set ; } } [ TestClass ] public class CustomerTests : TestClassBase { [ TestMethod ] public void CanSetCustomerEmailAddress ( ) { //Arrange Customer customer = new Customer ( ) ; //Act customer.EmailAddr = `` foo @ bar.com '' ; //Assert Assert.AreEqual ( `` foo @ bar.com '' , customer.EmailAddr ) ; } }
|
Is there value in unit testing auto implemented properties
|
C#
|
Today while coding , visual studio notified me that my switch case could be optimized . But the code that I had vs the code that visual studio generated from my switch case does not result in the same outcome.The Enum I Used : After the following code runs the value is equal to 2147483647.But when visual studio optimized the switch case , the value becomes 2147483648.This is just the code with information that reproduced the erroneous output and not actual code that is run in production . What I found weird was that if I comment out the line State.ExampleA in the last code block the correct value is written.My Question is : Is this a bug ? Or am I missing something here ?
|
public enum State { ExampleA , ExampleB , ExampleC } ; State stateExample = State.ExampleB ; double value ; switch ( stateExample ) { case State.ExampleA : value = BitConverter.ToSingle ( BitConverter.GetBytes ( ( long ) 2147483646 ) , 0 ) ; break ; case State.ExampleB : value = BitConverter.ToUInt32 ( BitConverter.GetBytes ( ( long ) 2147483647 ) , 0 ) ; break ; case State.ExampleC : value = BitConverter.ToInt16 ( BitConverter.GetBytes ( ( long ) 2147483648 ) , 0 ) ; break ; default : value = 0 ; break ; } State stateExample = State.ExampleB ; double value = stateExample switch { State.ExampleA = > BitConverter.ToSingle ( BitConverter.GetBytes ( ( long ) 2147483646 ) , 0 ) , //Commenting this line results in correct value State.ExampleB = > BitConverter.ToUInt32 ( BitConverter.GetBytes ( ( long ) 2147483647 ) , 0 ) , State.ExampleC = > BitConverter.ToInt16 ( BitConverter.GetBytes ( ( long ) 2147483648 ) , 0 ) , _ = > throw new InvalidOperationException ( ) } ;
|
Unexpected results after optimizing switch case in Visual Studio with C # 8.0
|
C#
|
I am relatively new to custom controls ( writing control from scratch in code - not merely styling existing controls ) . I am having a go at replicating the YouTube video control , you know the one ... To start with I want to develop the `` timeline '' ( the transparent grey bar , which displays the current position of the video and allows the user to drag to change position ) . With the preview panel and all the rest coming later on ... I currently have the control partially rendered and the hover animations and scale working very well ... However , I am struggling to write the correct code to allow me to drag the `` thumb '' . When I try and handle my left click on the Ellipse that is representing my thumb , the leave event of the containing Canvas fires , in accordance with the WPF documentation , so no complaints , I just don ; t know how to achieve what I want and indeed if what I have done already is the correct approach . The code : The XAML styleMy questions are : Is my approach for drawing the draggable thumb correct ? How can I actually change the code to get the dragging of my `` thumb '' to work ? Thanks for your time.Ps . the GitHub project with the working code is here so you can reproduce the problem I am having . If anyone wants to help me develop this control , that would be awesome ! Pps . I am aware I could override a slider to get my functionality for the `` timeline '' , but this is just the first part of a much more comprehensive control and hence needs to be written from scratch .
|
[ ToolboxItem ( true ) ] [ DisplayName ( `` VideoTimeline '' ) ] [ Description ( `` Controls which allows the user navigate video media . In addition is can display a `` + `` waveform repesenting the audio channels for the loaded video media . `` ) ] // [ TemplatePart ( Name = `` PART_ThumbCanvas '' , Type = typeof ( Canvas ) ) ] [ TemplatePart ( Name = `` PART_TimelineCanvas '' , Type = typeof ( Canvas ) ) ] [ TemplatePart ( Name = `` PART_WaveformCanvas '' , Type = typeof ( Canvas ) ) ] [ TemplatePart ( Name = `` PART_PreviewCanvas '' , Type = typeof ( Canvas ) ) ] [ TemplatePart ( Name = `` PART_Thumb '' , Type = typeof ( Ellipse ) ) ] // Is this the right thing to be doing ? public class VideoTimeline : Control { private Canvas thumbCanvas ; private Canvas timelineCanvas ; private Canvas waveformCanvas ; private Canvas previewCanvas ; private Rectangle timelineOuterBox = new Rectangle ( ) ; private Rectangle timelineProgressBox = new Rectangle ( ) ; private Rectangle timelineSelectionBox = new Rectangle ( ) ; private Ellipse timelineThumb = new Ellipse ( ) ; private Path previewWindow = new Path ( ) ; private Point mouseDownPosition ; private Point currentMousePosition ; private const int TIMELINE_ANIMATION_DURATION = 400 ; private const string HIGHLIGHT_FILL = `` # 878787 '' ; private double __timelineWidth ; # region Initialization . static VideoTimeline ( ) { DefaultStyleKeyProperty.OverrideMetadata ( typeof ( VideoTimeline ) , new FrameworkPropertyMetadata ( typeof ( VideoTimeline ) ) ) ; } public override void OnApplyTemplate ( ) { base.OnApplyTemplate ( ) ; //thumbCanvas = GetTemplateChild ( `` PART_ThumbCanvas '' ) as Canvas ; //thumbCanvas.Background = new SolidColorBrush ( Colors.Transparent ) ; //thumbCanvas.Children.Add ( timelineThumb ) ; timelineThumb = EnforceInstance < Ellipse > ( `` PART_Thumb '' ) ; timelineThumb.MouseLeftButtonDown -= TimelineThumb_MouseLeftButtonDown ; timelineThumb.MouseLeftButtonDown += TimelineThumb_MouseLeftButtonDown ; timelineCanvas = GetTemplateChild ( `` PART_TimelineCanvas '' ) as Canvas ; timelineCanvas.Background = new SolidColorBrush ( Colors.Transparent ) ; timelineCanvas.Children.Add ( timelineOuterBox ) ; timelineCanvas.Children.Add ( timelineSelectionBox ) ; timelineCanvas.Children.Add ( timelineProgressBox ) ; timelineCanvas.Children.Add ( timelineThumb ) ; previewCanvas = GetTemplateChild ( `` PART_PreviewCanvas '' ) as Canvas ; previewCanvas.Background = new SolidColorBrush ( Colors.Transparent ) ; previewCanvas.Children.Add ( previewWindow ) ; } private T EnforceInstance < T > ( string partName ) where T : FrameworkElement , new ( ) { return GetTemplateChild ( partName ) as T ? ? new T ( ) ; } protected override void OnTemplateChanged ( ControlTemplate oldTemplate , ControlTemplate newTemplate ) { base.OnTemplateChanged ( oldTemplate , newTemplate ) ; if ( timelineCanvas ! = null ) timelineCanvas.Children.Clear ( ) ; SetDefaultMeasurements ( ) ; } # endregion // Initialization . # region Event Overrides . protected override void OnRenderSizeChanged ( SizeChangedInfo sizeInfo ) { base.OnRenderSizeChanged ( sizeInfo ) ; //UpdateWaveformCacheScaling ( ) ; SetDefaultMeasurements ( ) ; UpdateAllRegions ( ) ; } protected override void OnMouseLeftButtonDown ( MouseButtonEventArgs e ) { base.OnMouseLeftButtonDown ( e ) ; Canvas c = e.OriginalSource as Canvas ; if ( c == null ) c = Utils.FindParent < Canvas > ( e.OriginalSource as FrameworkElement ) ; if ( c ! = null ) { CaptureMouse ( ) ; mouseDownPosition = e.GetPosition ( c ) ; if ( c.Name == `` PART_TimelineCanvas '' ) { Trace.WriteLine ( `` OnMouseLeftDown over TimeLine '' ) ; } } } protected override void OnMouseLeftButtonUp ( MouseButtonEventArgs e ) { base.OnMouseLeftButtonUp ( e ) ; ReleaseMouseCapture ( ) ; } protected override void OnMouseMove ( MouseEventArgs e ) { base.OnMouseMove ( e ) ; currentMousePosition = e.GetPosition ( thumbCanvas ) ; if ( Mouse.Captured == null ) { Canvas c = e.OriginalSource as Canvas ; if ( c == null ) c = Utils.FindParent < Canvas > ( e.OriginalSource as FrameworkElement ) ; } } # endregion // Event Overrides . # region Drawing Methods and Events . private void UpdateAllRegions ( ) { UpdateTimelineCanvas ( ) ; } private void UpdateTimelineCanvas ( ) { if ( timelineCanvas == null ) return ; SetDefaultMeasurements ( ) ; // Bounding timeline box . timelineOuterBox.Fill = new SolidColorBrush ( ( Color ) ColorConverter.ConvertFromString ( `` # 878787 '' ) ) { Opacity = 0.25 } ; timelineOuterBox.StrokeThickness = 0.0 ; timelineOuterBox.Width = __timelineWidth ; timelineOuterBox.Height = TimelineThickness ; timelineOuterBox.Margin = new Thickness ( TimelineExpansionFactor * TimelineThickness , ( timelineCanvas.RenderSize.Height - TimelineThickness ) / 2 , 0 , 0 ) ; timelineOuterBox.SnapsToDevicePixels = true ; // Selection timeline box . timelineSelectionBox.Fill = TimelineSelectionBrush ; timelineSelectionBox.Width = 0.0 ; timelineSelectionBox.Height = TimelineThickness ; timelineSelectionBox.Margin = new Thickness ( TimelineExpansionFactor * TimelineThickness , ( timelineCanvas.RenderSize.Height - TimelineThickness ) / 2 , 0 , 0 ) ; timelineSelectionBox.SnapsToDevicePixels = true ; // Progress timeline box . timelineProgressBox.Fill = TimelineProgressBrush ; timelineProgressBox.StrokeThickness = 0.0 ; timelineProgressBox.Width = 0.0 ; timelineProgressBox.Height = TimelineThickness ; timelineProgressBox.Margin = new Thickness ( TimelineExpansionFactor * TimelineThickness , ( timelineCanvas.RenderSize.Height - TimelineThickness ) / 2 , 0 , 0 ) ; timelineProgressBox.SnapsToDevicePixels = true ; // Animation and selection . timelineCanvas.MouseEnter -= TimelineCanvas_MouseEnter ; timelineCanvas.MouseEnter += TimelineCanvas_MouseEnter ; timelineCanvas.MouseLeave -= TimelineCanvas_MouseLeave ; timelineCanvas.MouseLeave += TimelineCanvas_MouseLeave ; timelineCanvas.MouseMove -= TimelineCanvas_MouseMove ; timelineCanvas.MouseMove += TimelineCanvas_MouseMove ; timelineCanvas.MouseDown -= TimelineCanvas_MouseDown ; timelineCanvas.MouseDown += TimelineCanvas_MouseDown ; // The draggable thumb . timelineThumb.Fill = TimelineThumbBrush ; //timelineThumb.Stroke = new SolidColorBrush ( Colors.Black ) ; //timelineThumb.StrokeThickness = 0.5 ; timelineThumb.VerticalAlignment = VerticalAlignment.Center ; timelineThumb.Height = timelineThumb.Width = 0.0 ; timelineThumb.Margin = new Thickness ( TimelineExpansionFactor * TimelineThickness , timelineCanvas.RenderSize.Height / 2 , 0 , 0 ) ; timelineThumb.SnapsToDevicePixels = true ; timelineThumb.MouseLeftButtonDown -= TimelineThumb_MouseLeftButtonDown ; timelineThumb.MouseLeftButtonDown += TimelineThumb_MouseLeftButtonDown ; timelineThumb.MouseLeftButtonUp -= TimelineThumb_MouseLeftButtonUp ; timelineThumb.MouseLeftButtonUp += TimelineThumb_MouseLeftButtonUp ; // Preview window . } private void TimelineCanvas_MouseDown ( object sender , MouseButtonEventArgs e ) { Trace.WriteLine ( `` POON '' ) ; } private void SetDefaultMeasurements ( ) { if ( timelineCanvas ! = null ) __timelineWidth = timelineCanvas.RenderSize.Width - 2 * 2 * TimelineThickness ; } private void TimelineCanvas_MouseEnter ( object sender , MouseEventArgs e ) { timelineThumb.ResetAnimation ( Ellipse.WidthProperty , Ellipse.HeightProperty ) ; timelineProgressBox.ResetAnimation ( Rectangle.HeightProperty , Rectangle.MarginProperty ) ; timelineSelectionBox.ResetAnimation ( Rectangle.HeightProperty , Rectangle.MarginProperty ) ; timelineOuterBox.ResetAnimation ( Rectangle.HeightProperty , Rectangle.MarginProperty ) ; CircleEase easing = new CircleEase ( ) ; easing.EasingMode = EasingMode.EaseOut ; // Thumb animation . Thickness margin = new Thickness ( 0 , ( timelineCanvas.RenderSize.Height - 2 * TimelineExpansionFactor * TimelineThickness ) / 2 , 0 , 0 ) ; EllpiseDiameterAnimation ( timelineThumb , TimelineThickness * TimelineExpansionFactor * 2 , margin , easing ) ; // Timeline animation . margin = new Thickness ( TimelineExpansionFactor * TimelineThickness , ( timelineCanvas.RenderSize.Height - ( TimelineThickness * TimelineExpansionFactor ) ) / 2 , 0 , 0 ) ; TimelineHeightAnimation ( timelineProgressBox , TimelineThickness * TimelineExpansionFactor , margin , easing ) ; TimelineHeightAnimation ( timelineSelectionBox , TimelineThickness * TimelineExpansionFactor , margin , easing ) ; TimelineHeightAnimation ( timelineOuterBox , TimelineThickness * TimelineExpansionFactor , margin , easing ) ; double selectionWidth = ( currentMousePosition.X / RenderSize.Width ) * timelineOuterBox.Width ; timelineSelectionBox.Width = selectionWidth ; Trace.WriteLine ( `` MouseENTER Canvas '' ) ; } private void TimelineCanvas_MouseLeave ( object sender , MouseEventArgs e ) { timelineThumb.ResetAnimation ( Ellipse.WidthProperty , Ellipse.HeightProperty ) ; timelineProgressBox.ResetAnimation ( Rectangle.HeightProperty , Rectangle.MarginProperty ) ; timelineSelectionBox.ResetAnimation ( Rectangle.HeightProperty , Rectangle.MarginProperty ) ; timelineOuterBox.ResetAnimation ( Rectangle.HeightProperty , Rectangle.MarginProperty ) ; CircleEase easing = new CircleEase ( ) ; easing.EasingMode = EasingMode.EaseOut ; // Thumb animation . Thickness margin = new Thickness ( TimelineExpansionFactor * TimelineThickness , timelineCanvas.RenderSize.Height / 2 , 0 , 0 ) ; EllpiseDiameterAnimation ( timelineThumb , 0.0 , margin , easing ) ; // Timeline animation . margin = new Thickness ( TimelineExpansionFactor * TimelineThickness , ( timelineCanvas.RenderSize.Height - TimelineThickness ) / 2 , 0 , 0 ) ; TimelineHeightAnimation ( timelineProgressBox , TimelineThickness , margin , easing ) ; TimelineHeightAnimation ( timelineSelectionBox , TimelineThickness , margin , easing ) ; TimelineHeightAnimation ( timelineOuterBox , TimelineThickness , margin , easing ) ; if ( ! isDraggingThumb ) timelineSelectionBox.Width = 0.0 ; Trace.WriteLine ( `` MouseLeave Canvas '' ) ; } private void TimelineCanvas_MouseMove ( object sender , MouseEventArgs e ) { Point relativePosition = e.GetPosition ( timelineOuterBox ) ; double selectionWidth = ( relativePosition.X / timelineOuterBox.Width ) * timelineOuterBox.Width ; timelineSelectionBox.Width = selectionWidth.Clamp ( 0.0 , timelineOuterBox.Width ) ; if ( isDraggingThumb ) { timelineProgressBox.Width = timelineSelectionBox.Width ; Thickness thumbMargin = new Thickness ( TimelineExpansionFactor * TimelineThickness , ( timelineCanvas.RenderSize.Height - ( TimelineThickness * TimelineExpansionFactor ) ) / 2 , 0 , 0 ) ; timelineThumb.Margin = thumbMargin ; } } private bool isDraggingThumb = false ; private void TimelineThumb_MouseLeftButtonDown ( object sender , MouseButtonEventArgs e ) { CaptureMouse ( ) ; isDraggingThumb = true ; Trace.WriteLine ( `` Dragging Thumb '' ) ; } private void TimelineThumb_MouseLeftButtonUp ( object sender , MouseButtonEventArgs e ) { ReleaseMouseCapture ( ) ; isDraggingThumb = false ; Trace.WriteLine ( `` STOPPED Dragging Thumb '' ) ; } # endregion // Drawing Methods and Events . # region Animation Methods . private void EllpiseDiameterAnimation ( Ellipse ellipse , double diameter , Thickness margin , IEasingFunction easing ) { AnimationTimeline widthAnimation = ShapeWidthAnimation ( ellipse , diameter , easing ) ; AnimationTimeline heightAnimation = ShapeHeightAnimation ( ellipse , diameter , easing ) ; AnimationTimeline marginAnimation = ShapeMarginAnimation ( ellipse , margin , easing ) ; Storyboard storyboard = new Storyboard ( ) ; storyboard.Children.Add ( widthAnimation ) ; storyboard.Children.Add ( heightAnimation ) ; storyboard.Children.Add ( marginAnimation ) ; storyboard.Begin ( this ) ; } private void TimelineHeightAnimation ( Rectangle rectangle , double height , Thickness margin , IEasingFunction easing ) { AnimationTimeline heightAnimation = ShapeHeightAnimation ( rectangle , height , easing ) ; AnimationTimeline marginAnimation = ShapeMarginAnimation ( rectangle , margin , easing ) ; Storyboard storyboard = new Storyboard ( ) ; storyboard.Children.Add ( marginAnimation ) ; storyboard.Children.Add ( heightAnimation ) ; storyboard.Begin ( this ) ; } private AnimationTimeline ShapeMarginAnimation ( Shape shape , Thickness margin , IEasingFunction easing ) { ThicknessAnimation marginAnimation = new ThicknessAnimation ( margin , TimeSpan.FromMilliseconds ( ( TIMELINE_ANIMATION_DURATION ) ) ) ; if ( easing ! = null ) marginAnimation.EasingFunction = easing ; Storyboard.SetTarget ( marginAnimation , shape ) ; Storyboard.SetTargetProperty ( marginAnimation , new PropertyPath ( Rectangle.MarginProperty ) ) ; return marginAnimation ; } private AnimationTimeline ShapeWidthAnimation ( Shape shape , double width , IEasingFunction easing ) { DoubleAnimation widthAnimation = new DoubleAnimation ( width , TimeSpan.FromMilliseconds ( TIMELINE_ANIMATION_DURATION ) ) ; if ( easing ! = null ) widthAnimation.EasingFunction = easing ; Storyboard.SetTarget ( widthAnimation , shape ) ; Storyboard.SetTargetProperty ( widthAnimation , new PropertyPath ( Shape.WidthProperty ) ) ; return widthAnimation ; } private AnimationTimeline ShapeHeightAnimation ( Shape shape , double height , IEasingFunction easing ) { DoubleAnimation heightAnimation = new DoubleAnimation ( height , TimeSpan.FromMilliseconds ( TIMELINE_ANIMATION_DURATION ) ) ; if ( easing ! = null ) heightAnimation.EasingFunction = easing ; Storyboard.SetTarget ( heightAnimation , shape ) ; Storyboard.SetTargetProperty ( heightAnimation , new PropertyPath ( Shape.HeightProperty ) ) ; return heightAnimation ; } # endregion // Animation Methods . // Lots of DependencyProperties here ... } < ResourceDictionary xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' clr-namespace : MediaControlBuilder '' > < Style TargetType= '' { x : Type local : VideoTimeline } '' > < Setter Property= '' TimelineProgressBrush '' Value= '' DarkOrange '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type local : VideoTimeline } '' > < Border Background= '' { TemplateBinding Background } '' BorderBrush= '' { TemplateBinding BorderBrush } '' BorderThickness= '' { TemplateBinding BorderThickness } '' > < Grid > < Grid.RowDefinitions > < ! -- < RowDefinition Height= '' * '' / > -- > < ! -- < RowDefinition Height= '' 15 '' / > -- > < RowDefinition Height= '' * '' / > < RowDefinition Height= '' 20 '' / > < ! -- < RowDefinition Height= '' * '' / > -- > < /Grid.RowDefinitions > < Canvas Name= '' PART_PreviewCanvas '' Grid.Row= '' 0 '' ClipToBounds= '' True '' / > < Canvas Name= '' PART_ThumbCanvas '' Grid.Row= '' 1 '' ClipToBounds= '' True '' / > < Canvas Name= '' PART_TimelineCanvas '' Grid.Row= '' 1 '' ClipToBounds= '' True '' / > < Canvas Name= '' PART_WaveformCanvas '' Grid.Row= '' 1 '' ClipToBounds= '' True '' / > < /Grid > < /Border > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > < /ResourceDictionary >
|
WPF Video Transport Control
|
C#
|
I have a method that currently takes a Func < Product , string > as a parameter , but I need it to be an Expression < Func < Product , string > > . Using AdventureWorks , here 's an example of what I 'd like to do using the Func.I would like it to look something like this : However , the problem I 'm running into is that myExpression ( product ) is invalid ( wo n't compile ) . After reading some other posts I understand why . And if it was n't for the fact that I need the product variable for the second part of my key I could probably say something like this : But I do need the product variable because I do need the second part of the key ( ProductNumber ) . So I 'm not really sure what to do now . I ca n't leave it as a Func because that causes problems . I ca n't figure out how to use an Expression because I do n't see how I could pass it the product variable . Any ideas ? EDIT : Here 's an example of how I would call the method :
|
private static void DoSomethingWithFunc ( Func < Product , string > myFunc ) { using ( AdventureWorksDataContext db = new AdventureWorksDataContext ( ) ) { var result = db.Products.GroupBy ( product = > new { SubCategoryName = myFunc ( product ) , ProductNumber = product.ProductNumber } ) ; } } private static void DoSomethingWithExpression ( Expression < Func < Product , string > > myExpression ) { using ( AdventureWorksDataContext db = new AdventureWorksDataContext ( ) ) { var result = db.Products.GroupBy ( product = > new { SubCategoryName = myExpression ( product ) , ProductNumber = product.ProductNumber } ) ; } } var result = db.Products.GroupBy ( myExpression ) ; DoSomethingWithFunc ( product = > product.ProductSubcategory.Name ) ;
|
Refactoring Func < T > into Expression < Func < T > >
|
C#
|
I 'm trying to use SQLXMLBulkLoader4 from C # code into an SQL 2008 DB . But for some reason it does n't insert any rows at all despite not throwing any error . I 've made use of the bulkloads own ErrorLog file , ( to check for any errors that might not cause it to crash ) , but no error is reported.I have a XML file that is downloaded from a supplier ( basically a list of products ) , I wrote an XSD to match the fields to our DB . There is nothing else writing to those specific tables , and nothing else using those files.My BulkLoad code looks as follows ( I X'ed out the actual connection string values ) : The XML looks like this ( stripped down , everything below is just a couple more product-fields and then more products ) : The XSD I wrote looks like this ( again shortened ) : I 've stared myself blind at the namespaces , but they look correct to me . ( Read about a lot of similar errors where different namespaces was the cause ) .The code is running from my computer , both my computer and the one with the DB have access to the network folder with the XML and XSD files.I 've tried deliberately changing some field-names in both files , and the BulkLoader flares up throwing an error on the field I just changed.I 've compared both my BulkLoader code and the XSD to examples I 've found on the net , and I ca n't find any difference that would account for this behaviour.It 's probably something easy I 'm overlooking , but I 'm just not seeing it atm.Any help at all pointing me in the right direction is deeply welcomed.Thank you in advance ! ( P.S . Sorry if the post is off in some way , it 's my first time posting here , I did do my research however and I did try to follow the guidelines on how to post = ) )
|
public void Bulkload ( string schemaFile , string xmlFile , string source ) { SQLXMLBULKLOADLib.SQLXMLBulkLoad4 bulkload = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4 ( ) ; try { bulkload.ConnectionString = `` Provider=sqloledb ; server=X ; database=X ; uid=X ; pwd=X '' ; bulkload.ErrorLogFile = k_ArticleInfoDirectory + source + `` BulkLoadError.log '' ; bulkload.KeepIdentity = false ; bulkload.Execute ( schemaFile , xmlFile ) ; } catch ( Exception e ) { Console.WriteLine ( `` Fel i BL : `` + e ) ; throw ; } finally { bulkload = null ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < GetProductsResult xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' > < Status xmlns= '' http : //schemas.servicestack.net/types '' > < Code > 0 < /Code > < Message > Ok < /Message > < /Status > < NumberOfProducts xmlns= '' http : //schemas.servicestack.net/types '' > 9826 < /NumberOfProducts > < Products xmlns= '' http : //schemas.servicestack.net/types '' > < Product > < ProductID > 1000002 < /ProductID > < CreatedDate > 2011-11-24 15:54 < /CreatedDate > < UpdatedDate > 2011-11-24 15:54 < /UpdatedDate > < Title > Vi tolererar inga förlorare - klanen Kennedy < /Title > < Publisher > Piratförlaget < /Publisher > ... And some more fields per Product < ? xml version= '' 1.0 '' encoding= '' iso-8859-1 '' ? > < xs : schema targetNamespace= '' http : //schemas.servicestack.net/types '' xmlns : xs= '' http : //www.w3.org/2001/XMLSchema '' attributeFormDefault= '' qualified '' elementFormDefault= '' qualified '' xmlns : sql= '' urn : schemas-microsoft-com : mapping-schema '' > < xs : annotation > < xs : appinfo > < sql : relationship name= '' Status '' parent= '' tblElibProduct '' parent-key= '' id '' child= '' tblElibStatus '' child-key= '' product_id '' / > ... + Several other sql : relationships < /xs : appinfo > < /xs : annotation > < xs : element name= '' GetProductsResult '' sql : is-constant= '' 1 '' > < xs : complexType > < xs : sequence > < xs : element name= '' Status '' sql : is-constant= '' 1 '' > < xs : complexType > < xs : sequence > < xs : element name= '' Code '' type= '' xs : integer '' minOccurs= '' 0 '' / > < xs : element name= '' Message '' type= '' xs : string '' minOccurs= '' 0 '' / > < /xs : sequence > < /xs : complexType > < /xs : element > < xs : element name= '' NumberOfProducts '' type= '' xs : string '' sql : is-constant= '' 1 '' / > < xs : element name= '' Products '' sql : is-constant= '' 1 '' > < xs : complexType > < xs : sequence > < xs : element minOccurs= '' 0 '' maxOccurs= '' unbounded '' name= '' Product '' sql : relation= '' tblElibProduct '' > < xs : complexType > < xs : sequence > < xs : element minOccurs= '' 1 '' maxOccurs= '' 1 '' name= '' CreatedDate '' type= '' xs : date '' sql : field= '' created_date '' / > < xs : element minOccurs= '' 1 '' maxOccurs= '' 1 '' name= '' UpdatedDate '' type= '' xs : date '' sql : field= '' updated_date '' / > < xs : element minOccurs= '' 1 '' maxOccurs= '' 1 '' name= '' Title '' type= '' xs : string '' sql : field= '' title '' / >
|
SQLXML BulkLoader not throwing any error but no data is inserted
|
C#
|
I 'm using IdentityServer4 with ASP.NET Core 2.2 . On the Post Login method I have applied the ValidateAntiForgeryToken . Generally after 20 minutes to 2 hours of sitting on the login page and then attempting to login it produces a blank page . If you look at Postman Console you get a 400 Bad Request message . I then set the Cookie Expiration on the AntiForgery options to 90 days . I was able to allow the page to sit for up to 6 hours and still login . However , after around 8 hours ( overnight ) , I received the blank page again after attempting to login.I expect to be able to sit on the login page for 90 days which is the duration of the cookie but that does n't work . How do I get the cookie for the AntiforgeryToken to last the entire 90 days or whatever time I set it to and not timeout or expire ? Is there a way to catch this error and redirect the user back to the login method ?
|
[ HttpPost ] [ ValidateAntiForgeryToken ] public async Task < IActionResult > Login services.AddAntiforgery ( options = > { options.Cookie.Expiration = TimeSpan.FromDays ( 90 ) ; } ) ;
|
AntiForgeryToken Expiration Blank Page
|
C#
|
Update : This is called a de Brujin torus , but I still need to figure out a simple algoritm in C # .http : //en.wikipedia.org/wiki/De_Bruijn_torushttp : //datagenetics.com/blog/october22013/index.htmlI need to combine all values of a 3x3 bit grid as densely as possible . By a 3x3 bit grid , I mean a 3x3 grid where each place is a bit similar to the hole punch concept in this question : Find all combinations of 3x3 holepunch3x3 Bit Grid Examples : GoalI want to pack all 512 ( actually 256 because the center bit is always on ) possible values so that they overlap in a single NxM grid.Incomplete Example : This example packs ~25 of the possible values into a 7x7 grid.Things already known : There are 2^9 ( 512 ) unique values.I only care about 2^8 ( 256 ) values because I need the center bit always on.AttemptsI tried many different techniques by hand , but could not come up with a straightforward algorithm.So , I would like to write a C # program to create this , but I also did not see an easy way . There is not even an obvious brute-force approach that seems possible to me . It seems any brute-force attempt would approach 512 ! combinations in the worse case.ObservationsEach edge only has 8 possible values . PurposeThis is actually going to be used for a 2d tile-based game.The game has N possible ground pieces . Given that the ground can occur in any situation , the designer needs a way to express which tile should be chosen for any given situation.A compact grid that contains every possible situation is the most efficient way to specify which tile to use in each situation and eliminates all redundancy.UpdateExampleThe above is the base pattern that will allow the expression of 4 situations and I will modify this to use other ascii values to represent the result that should be used in each situation : Where A , G , H each represent a specific pattern that should be used for each situation.So , if the following pattern is found : This matches the pattern that results in ' A ' above , so ' A ' will be used in that situation . The purpose is to have an exhaustive expression of what each possible situation would result.In PracticeI was able to attempt this , and found the results too random to work well to achieve the goals . As a human , it was difficult to choose the correct values in each situation because or the disorganization . Manual grouping of similar patterns still works better .
|
XXX .X . ... XXX .X . .X.XXX .X . ... ... ... ..X.XXX ... ... ... X.XXX..X.XXX..X.XXX ... ... .. X ... X.XXX . // ( 8+2 bits ) Exhausts all values in the same problem with 1-Dimension..X.XXX . // ( 5+2 bits ) The above simplifies when the center bit must be on . ... ..XX..XX ... .. ... ..AG..HH ... .. ... .XX.XX ? ? ? ? A ? ? ? ?
|
Find a NxM grid that contains all possible 3x3 bit patterns
|
C#
|
I 'm learning TDD . I know about dependency injection whereby you place the class 's dependencies in the constructor 's parameters and have them passed in , passing in default implementations from the default constructor eg ; RepositoryFactory is a simple static class that returns the chosen implementations for the current buildBut the default ASP.NET MVC web app project does n't do this , instead the DI takes the form of public properties that are assigned in the object initializer in the test class eg ; from AccountController.cs : And in the test class AccountControllerTest.cs : So now my AccountController class has two approaches to dependency injection . Which one should I use ? Constructor injection or public properties ? Am thinking constructor injection ... Is the ASP.NET MVC use of public properties like that because you need to provide a specific way of injecting into the constructor , and the basic `` create new '' web app needs to be generic as a starting point ?
|
public AccountController ( ) : this ( RepositoryFactory.Users ( ) ) { } public AccountController ( IUserRepository oUserRepository ) { m_oUserRepository = oUserRepository ; } protected override void Initialize ( RequestContext requestContext ) { if ( FormsService == null ) { FormsService = new FormsAuthenticationService ( ) ; } if ( MembershipService == null ) { MembershipService = new AccountMembershipService ( ) ; } base.Initialize ( requestContext ) ; } private static AccountController GetAccountController ( ) { AccountController controller = new AccountController ( ) { FormsService = new MockFormsAuthenticationService ( ) , MembershipService = new MockMembershipService ( ) , Url = new UrlHelper ( requestContext ) , } ; //snip }
|
Are the unit test classes in ASP.NET MVC web project a good example ?
|
C#
|
I was astounded to find that the System.Numerics.Complex data type in .NET does n't yield mathematically accurate results.Instead of ( 0 , 1 ) , I get ( 6.12303176911189E-17 , 1 ) , which looks a lot like a rounding error.Now I realize that floating point arithmetic will lead to results like this sometimes , but usually using integers will avoid rounding errors.Why does this seemingly basic operation yield an obviously wrong result ?
|
Complex.Sqrt ( -1 ) ! = Complex.ImaginaryOne
|
Why is .NET 's Complex type broken ?
|
C#
|
To be more specific : will the Linq extension method Any ( IEnumerable collection , Func predicate ) stop checking all the remaining elements of the collections once the predicate has yielded true for an item ? Because I do n't want to spend to much time on figuring out if I need to do the really expensive parts at all : So if Any is always checking all the items in the source this might end up being a waste of time instead of just going with : because I 'm pretty sure that FirstOrDefault does return once it got a result and only keeps going through the whole Enumerable if it does not find a suitable entry in the collection.Does anyonehave information about the internal workings of Any , or could anyone suggest a solution for this kind of decision ? Also , a colleague suggested something along the lines of : since this is supposed to stop once the conditions returns false for the first time but I 'm not sure on that , so if anyone could shed some light on this as well it would be appreciated .
|
if ( lotsOfItems.Any ( x = > x.ID == target.ID ) ) //do expensive calculation here var candidate = lotsOfItems.FirstOrDefault ( x = > x.ID == target.ID ) if ( candicate ! = null ) //do expensive calculation here if ( ! lotsOfItems.All ( x = > x.ID ! = target.ID ) )
|
Does Any ( ) stop on success ?
|
C#
|
I 'm trying to figure out if there 's any way to avoid getting an `` Unreachable code '' warning for something that 's caused by the preprocessor . I do n't want to suppress all such warnings , only those which will be dependent on the preprocessor , e.g.And later on there 's code that goes : One of those two sections will always be detected as `` Unreachable code '' , and we 've got those all over the place . I 'd like to try and get rid of the many warnings it creates , but I still want to get warnings for legitimately unreachable code . ( In reality , there 's more than just two platforms , so each chunk of platform-specific code creates a pile of unnecessary warnings . )
|
# if WINDOWS public const GamePlatform platform = GamePlatform.PC ; # else public const GamePlatform platform = GamePlatform.MAC ; # endif if ( platform == GamePlatform.PC ) { ... } else { ... }
|
Avoid `` Unreachable code '' warning for preprocessor-dependent code
|
C#
|
Using MYSQL , with EF 5.x and MVC3 . I have a table with around 3.2 million rows which has city , country combo . I have a autocomplete textbox on the client side that takes city 's search term and sends back suggestions using jQuery/ajax.The challenge that I am facing is that I cache this table into my memory when its used for first time using : This timeouts even when I set my db-context timeout to 5 mins . When I run this SQL against the DB using MySQL client it takes about 3 min to pull all the rows.What is the best way to read this data into cache or should I be doing something different ? Can I cache the table directly into MySQL cache memory if so how ? Or should I be sending the term search directly to DB instead of doing it using data in cache .
|
CityData = DataContext.Citys.OrderBy ( v = > v.Country ) .ToList ( ) ; if ( CityData.Any ( ) ) { // Put this data into the cache for 30 minutes Cache.Set ( `` Citys '' , CityData , 30 ) ; }
|
Cache Static Tables Mysql
|
C#
|
Many years ago , I was admonished to , whenever possible , release resources in reverse order to how they were allocated . That is : I imagine on a 640K MS-DOS machine , this could minimize heap fragmentation . Is there any practical advantage to doing this in a C # /.NET application , or is this a habit that has outlived its relevance ?
|
block1 = malloc ( ... ) ; block2 = malloc ( ... ) ; ... do stuff ... free ( block2 ) ; free ( block1 ) ;
|
C # : Is there an Advantage to Disposing Resources in Reverse Order of their Allocation ?
|
C#
|
NOTE : Right before posting this question it occurred to me there 's a better way of doing what I was trying to accomplish ( and I feel pretty stupid about it ) : So OK , yes , I already realize this . However , I 'm posting the question anyway , because I still do n't quite get why what I was ( stupidly ) trying to do was n't working.I thought this would be extremely easy . Turns out it is giving me quite a headache.The basic idea : display all the items whose ProductType property value is checked in a CheckedListBox.The implementation : However , say the items `` Equity '' and `` ETF '' are both checked in ProductTypesList ( a CheckedListBox ) . Then for some reason , the following code only returns products of type `` ETF '' : I guessed it might have had something to do with some self-referencing messiness where filter is set to , essentially , itself or something else . And I thought that maybe using ... ... would do the trick , but no such luck . Can anybody see what I am missing here ?
|
IEnumerable < string > checkedItems = ProductTypesList.CheckedItems.Cast < string > ( ) ; filter = p = > checkedItems.Contains ( p.ProductType ) ; private Func < Product , bool > GetProductTypeFilter ( ) { // if nothing is checked , display nothing Func < Product , bool > filter = p = > false ; foreach ( string pt in ProductTypesList.CheckedItems.Cast < string > ( ) ) { Func < Product , bool > prevFilter = filter ; filter = p = > ( prevFilter ( p ) || p.ProductType == pt ) ; } return filter ; } var filter = GetProductTypeFilter ( ) ; IEnumerable < Product > filteredProducts = allProducts.Where ( filter ) ; filter = new Func < Product , bool > ( p = > ( prevFilter ( p ) || p.ProductType == pt ) ) ;
|
What am I missing in this chain of predicates ?
|
C#
|
What ( if any ) is the C # equivalent of Python 's itertools.chain method ? Python Example : Results:1234 Note that I 'm not interested in making a new list that combines my first two and then processing that . I want the memory/time savings that itertools.chain provides by not instantiating this combined list .
|
l1 = [ 1 , 2 ] l2 = [ 3 , 4 ] for v in itertools.chain ( l1 , l2 ) : print ( v )
|
C # Equivalent of Python 's itertools.chain
|
C#
|
Hi I have this code using generic and nullable : Please note the TInput constraint , one is class , the other one is struct . Then I use them in : It cause an Ambiguos error . But I also have the another pair : This one compiles successfullyI got no clues why this happen . The first one seems Ok , but compiles error . The second one ( 'Return ' ) should be error if the first one is , but compiles successfully . Did I miss something ?
|
// The first one is for classpublic static TResult With < TInput , TResult > ( this TInput o , Func < TInput , TResult > evaluator ) where TResult : class where TInput : class// The second one is for struct ( Nullable ) public static TResult With < TInput , TResult > ( this Nullable < TInput > o , Func < TInput , TResult > evaluator ) where TResult : class where TInput : struct string s ; int ? i ; // ... s.With ( o = > `` '' ) ; i.With ( o = > `` '' ) ; // Ambiguos method public static TResult Return < TInput , TResult > ( this TInput o , Func < TInput , TResult > evaluator , TResult failureValue ) where TInput : classpublic static TResult Return < TInput , TResult > ( this Nullable < TInput > o , Func < TInput , TResult > evaluator , TResult failureValue ) where TInput : struct string s ; int ? i ; // ... s.Return ( o = > 1 , 0 ) ; i.Return ( o = > i + 1 , 0 ) ;
|
Generic type parameter and Nullable method overload
|
C#
|
So I 've notice that this code works : In particular , I 'm curious about the using block , since : fails with a compiler error . Obviously , the class that yield return returns is IDisposable while a regular array enumerator is not . So now I 'm curious : what exactly does yield return create ?
|
class Program { public static void Main ( ) { Int32 [ ] numbers = { 1,2,3,4,5 } ; using ( var enumerator = Data ( ) .GetEnumerator ( ) ) { } } public static IEnumerable < String > Data ( ) { yield return `` Something '' ; } } Int32 [ ] numbers = { 1 , 2 , 3 , 4 , 5 , 6 } ; using ( var enumerator = numbers.GetEnumerator ( ) ) { }
|
What kind of class does yield return return
|
C#
|
I have .net core WEB API application with MassTransit ( for implement RabbitMQ message broker ) . RabbitMQ-MassTransit configuration is simple and done in few line code in Startup.cs file.I am using dependency injection in my project solution for better code standard . Publish messages are works fine with controller dependency injection . But when I implement a custom middle ware for log actions , Masstransit failed to publish the message properly , it was created a additional queue with _error in RabbitMQ web console . configure Middleware in startupIs there any additional configuration in startup for MassTransit to work with Middle WareEditIActionLogPublishActionLogPublishEditRabbitMQ Web Console
|
services.AddMassTransit ( x = > { x.AddConsumer < CustomLogConsume > ( ) ; x.AddBus ( provider = > Bus.Factory.CreateUsingRabbitMq ( cfg = > { var host = cfg.Host ( new Uri ( `` rabbitmq : //rabbitmq/ '' ) , h = > { h.Username ( `` guest '' ) ; h.Password ( `` guest '' ) ; } ) ; cfg.ExchangeType = ExchangeType.Fanout ; cfg.ReceiveEndpoint ( host , `` ActionLog_Queue '' , e = > { e.PrefetchCount = 16 ; } ) ; // or , configure the endpoints by convention cfg.ConfigureEndpoints ( provider ) ; } ) ) ; } ) ; public class RequestResponseLoggingMiddleware { # region Private Variables /// < summary > /// RequestDelegate /// < /summary > private readonly RequestDelegate _next ; /// < summary > /// IActionLogPublish /// < /summary > private readonly IActionLogPublish _logPublish ; # endregion # region Constructor public RequestResponseLoggingMiddleware ( RequestDelegate next , IActionLogPublish logPublish ) { _next = next ; _logPublish = logPublish ; } # endregion # region PrivateMethods # region FormatRequest /// < summary > /// FormatRequest /// < /summary > /// < param name= '' request '' > < /param > /// < returns > < /returns > private async Task < ActionLog > FormatRequest ( HttpRequest request ) { ActionLog actionLog = new ActionLog ( ) ; var body = request.Body ; request.EnableRewind ( ) ; var context = request.HttpContext ; var buffer = new byte [ Convert.ToInt32 ( request.ContentLength ) ] ; await request.Body.ReadAsync ( buffer , 0 , buffer.Length ) ; var bodyAsText = Encoding.UTF8.GetString ( buffer ) ; request.Body = body ; var injectedRequestStream = new MemoryStream ( ) ; var requestLog = $ '' REQUEST HttpMethod : { context.Request.Method } , Path : { context.Request.Path } '' ; using ( var bodyReader = new StreamReader ( context.Request.Body ) ) { bodyAsText = bodyReader.ReadToEnd ( ) ; if ( string.IsNullOrWhiteSpace ( bodyAsText ) == false ) { requestLog += $ '' , Body : { bodyAsText } '' ; } var bytesToWrite = Encoding.UTF8.GetBytes ( bodyAsText ) ; injectedRequestStream.Write ( bytesToWrite , 0 , bytesToWrite.Length ) ; injectedRequestStream.Seek ( 0 , SeekOrigin.Begin ) ; context.Request.Body = injectedRequestStream ; } actionLog.Request = $ '' { bodyAsText } '' ; actionLog.RequestURL = $ '' { request.Scheme } { request.Host } { request.Path } { request.QueryString } '' ; return actionLog ; } # endregion # region FormatResponse private async Task < string > FormatResponse ( HttpResponse response ) { response.Body.Seek ( 0 , SeekOrigin.Begin ) ; var text = await new StreamReader ( response.Body ) .ReadToEndAsync ( ) ; response.Body.Seek ( 0 , SeekOrigin.Begin ) ; return $ '' Response { text } '' ; } # endregion # endregion # region PublicMethods # region Invoke /// < summary > /// Invoke - Hits before executing any action . Actions call executes from _next ( context ) /// < /summary > /// < param name= '' context '' > < /param > /// < returns > < /returns > public async Task Invoke ( HttpContext context ) { ActionLog actionLog = new ActionLog ( ) ; actionLog = await FormatRequest ( context.Request ) ; var originalBodyStream = context.Response.Body ; using ( var responseBody = new MemoryStream ( ) ) { context.Response.Body = responseBody ; await _next ( context ) ; actionLog.Response = await FormatResponse ( context.Response ) ; await _logPublish.Publish ( actionLog ) ; await responseBody.CopyToAsync ( originalBodyStream ) ; } } # endregion # endregion } public async void Configure ( IApplicationBuilder app , IHostingEnvironment env , IApplicationLifetime lifetime ) { ... ... ... ... app.UseMiddleware < RequestResponseLoggingMiddleware > ( ) ; ... ... ... ... ... ... .. } public interface IActionLogPublish { Task Publish ( ActionLog model ) ; } public class ActionLogPublish : IActionLogPublish { private readonly IBus _bus ; public ActionLogPublish ( IBus bus ) { _bus = bus ; } public async Task Publish ( ActionLog actionLogData ) { /* Publish values to RabbitMQ Service Bus */ await _bus.Publish ( actionLogData ) ; /* Publish values to RabbitMQ Service Bus */ } }
|
Middleware with Masstransit publish
|
C#
|
I 'm trying to drag one or more files from my application to an outlook mail-message . If I drag to my desktop the files are copied to the desktop as expected , but when dragging into a new outlook 2013 mail message , nothing happens ... Only when I drag explicitly to the 'attachments textbox ' do they appear , this is not helpful because the attachment-textbox is n't shown by default . I do n't understand why when I drag file ( s ) from my desktop to the mail I can just drop them and the attachment-text automatically appears showing the files but when I drag from my app it 's not working ... , here 's my code : '' I 've also added the files to the DataObject by using the 'SetFileDropList ' method but that makes no difference.The must be some magic property I have to set to get this working right with an outlook-message.I hope someone can shed some light on this.thanks , Jurjen .
|
private void Form1_MouseDown ( object sender , MouseEventArgs e ) { var _files = new string [ ] { @ '' E : \Temp\OR_rtftemplates.xml '' , @ '' E : \Temp\Tail.Web_Trace.cmd '' } ; var fileDragData = new DataObject ( DataFormats.FileDrop , _files ) ; ( sender as Form ) .DoDragDrop ( fileDragData , DragDropEffects.All ) ; Console.WriteLine ( `` { 0 } - button1_MouseDown '' , DateTime.Now.TimeOfDay ) ; }
|
How to drag files from c # winforms app to outlook message
|
C#
|
I just created the following method in one of my classesAnd a friend of mine , reviewing my code , said that I should n't create methods that 'extend the List class ' , since that violates the open/closed principle.If I want to extend the class List I should create a new class that inherits from List and implement my `` merge '' method in that new class.Is he right ? Extending the List class violates the Open/Closed principle ?
|
public static bool Assimilate ( this List < Card > first , List < Card > second ) { // Trivial if ( first.Count == 0 || second.Count == 0 ) { return false ; } // Sort the lists , so I can do a binarySearch first.Sort ( ) ; second.Sort ( ) ; // Copia only the new elements int index ; for ( int i = 0 ; i < second.Count ; i++ ) { index = first.BinarySearch ( second [ i ] ) ; if ( index < 0 ) { first.Insert ( ~index , second [ i ] ) ; } } // Edit second = null ; return true ; }
|
Extending List < T > and Violating The Open/Closed Principle
|
C#
|
I recently started to make video games using the XNA game studio 4.0 . I have made a main menu with 4 sprite fonts using a button list . They change color from White to Yellow when I press the up and down arrows.My problem is that when I scroll through it goes from the top font to the bottom font really fast and goes straight to the last one . I am unsure why this is ? Is it because I am putting it in the update method and it is calling it every 60 seconds or so ? Here is my code for when I press the arrow keys.I need someone to help me slow it down to a reasonable speed.If you could help me it would be greatly appreciated .
|
public void Update ( GameTime gameTime ) { keyboard = Keyboard.GetState ( ) ; if ( CheckKeyboard ( Keys.Up ) ) { if ( selected > 0 ) { selected -- ; } } if ( CheckKeyboard ( Keys.Down ) ) { if ( selected < buttonList.Count - 1 ) { selected++ ; } } keyboard = prevKeyboard ; } public bool CheckKeyboard ( Keys key ) { return ( keyboard.IsKeyDown ( key ) & & prevKeyboard.IsKeyUp ( key ) ) ; }
|
Main Menu navigation / keyboard input speed is too fast
|
C#
|
I am working on a class that needs run a different process method based on the type of object I pass in . I thought that overloading might work here , but I have a question . Lets say I have two interfaces : and and a class to process these objects : My question is , being that ISpecialEmail inherits from IEmail , are these method signatures sufficiently different to allow for overloading ? My original thought is that ISpecialEmail emails would also trigger the IEmail signature because technically that interface is implemented also.Thanks for your help .
|
public interface IEmail { Some properties ... } public interface ISpecialEmail : IEmail { Some more properties ... . } public class EmailProcessor { public void ProcessEmail ( IEmail email ) { do stuff ; } public void ProcessEmail ( ISpecialEmail email ) { do different stuff } }
|
C # inheritance and method signatures
|
C#
|
My program have a pluginManager module , it can load a DLL file and run DLL 's methods , but I need read the DLL properties before Assembly.LoadFile ( ) . What should I do ? I readed about Assembly documents , they read properties after Assembly.LoadFile ( ) , you know Assembly no UnLoad ( ) Method , so I must read properties before LoadFile ( )
|
private void ImprotZip ( string path ) { /* 1、create tempDir , uppackage to tempDir 2、Load Plugin DLL , Load plugin dependent lib DLL */ string tempDirectory = CreateRuntimeDirectory ( path ) ; string [ ] dllFiles = Directory.GetFiles ( tempDirectory ) ; ///Load DlL foreach ( string dll in dllFiles ) { ImprotDll ( dll , false ) ; } string libPath = string.Format ( `` { 0 } \\lib\\ '' , tempDirectory ) ; if ( ! Directory.Exists ( libPath ) ) return ; string [ ] dlls = Directory.GetFiles ( libPath ) ; ///Load plugin dependent lib DLL foreach ( string dll in dlls ) { try { //filtering same DLL //if ( Dll.properties.AssemblyProduct ! = `` something '' ) //continue ; Assembly.LoadFile ( dll ) ; } catch ( Exception e ) { e.Log ( ) ; } } }
|
How to read properties from DLL before Assembly.LoadFile ( )
|
C#
|
In my system I have tasks , which can optionally be assigned to contacts . So in my business logic I have the following code : If no contact was specified , the contact variable is null . This is supposed to null out the contact relationship when I submit changes , however I have noticed this is n't happening 99 % of the time I do it ( I have seen it happen once , but not consistently after stepping through this code over and over ) .When I debug , I have verified that _contactChanged is true and the inside code is n't getting hit . However , after I step past task.Contact = contact ; I notice that while contact is null , task.Contact is of type and still has the previous data tied to it.Why is the proxy not being set to null , and how can I get this to work properly ?
|
if ( _contactChanged ) { task.Contact = contact ; } { System.Data.Entity.DynamicProxies.Contact_4DF70AA1AA8A6A94E9377F65D7B1DD3A837851FD3442862716FA7E966FFCBAB9 }
|
Why does my EF4.1 relationship not get set to null upon assignment of a null value ?
|
C#
|
For some of my code I use a method which looks like this : and I want to use it like this ( simple example ) : now , obviously , I know that there is no way MyMethod could never return anything , because it will always ( indirectly ) throw an exception.But of course I get the compiler value `` not all paths return a value '' . That 's why I am asking if there is anything like the C++ [ [ noreturn ] ] attribute that I could use to indicate to the compiler that the code is actually valid ? EDIT : The reason for why I want to use a throwing helper class instead of throwing directly or using an exception builder , is this statement : Members that throw exceptions are not getting inlined . Moving the throw statement inside the builder might allow the member to be inlined.I actually measured the code and I would benefit ( a little ) from inlining , so I would be happy to find ways to achieve this .
|
public static void Throw < TException > ( string message ) where TException : Exception { throw ( TException ) Activator.CreateInstance ( typeof ( TException ) , message ) ; } public int MyMethod ( ) { if ( ... ) { return 42 ; } ThrowHelper.Throw < Exception > ( `` Test '' ) ; // I would have to put `` return -1 ; '' or anything like that here for the code to compile . }
|
Is there something like [ [ noreturn ] ] in C # to indicate the compiler that the method will never return a value ?
|
C#
|
I have the below string I need the output asAs can be make out that it can be easily done by splitting by `` , '' but the problem comes when it is MAV # ( X , , ) or MOV # ( X,12,33 ) type.Please help
|
P , MV , A1ZWR , MAV # ( X , , ) , PV , MOV # ( X,12,33 ) , LO PMVA1ZWRMAV # ( X , , ) PVMOV # ( X,12,33 ) LO
|
String Splitter in .NET
|
C#
|
I 'm profiling some C # code . The method below is one of the most expensive ones . For the purpose of this question , assume that micro-optimization is the right thing to do . Is there an approach to improve performance of this method ? Changing the input parameter to p to ulong [ ] would create a macro inefficiency .
|
static ulong Fetch64 ( byte [ ] p , int ofs = 0 ) { unchecked { ulong result = p [ 0 + ofs ] + ( ( ulong ) p [ 1 + ofs ] < < 8 ) + ( ( ulong ) p [ 2 + ofs ] < < 16 ) + ( ( ulong ) p [ 3 + ofs ] < < 24 ) + ( ( ulong ) p [ 4 + ofs ] < < 32 ) + ( ( ulong ) p [ 5 + ofs ] < < 40 ) + ( ( ulong ) p [ 6 + ofs ] < < 48 ) + ( ( ulong ) p [ 7 + ofs ] < < 56 ) ; return result ; } }
|
Optimize C # Code Fragment
|
C#
|
instead ofAm I correct in thinking that the first line of code will always perform an assignment ? Also , is this a bad use of the null-coalescing operator ?
|
myFoo = myFoo ? ? new Foo ( ) ; if ( myFoo == null ) myFoo = new Foo ( ) ;
|
Bad Use of Null Coalescing Operator ?
|
C#
|
Entity framework has synchronous and asynchronous versions of the same IO-bound methods such as SaveChanges and SaveChangesAsync . How can I create new methods that minimally accomplish the same task without `` duplicating '' code ?
|
public bool SaveChanges ( ) { //Common code calling synchronous methods context.Find ( ... ) ; //Synchronous Save return context.SaveChanges ( ) ; } public async Task < bool > SaveChangesAsync ( ) { //Common code asynchronous methods await context.FindAsync ( ... ) ; //Asynchronous Save return await context.SaveChangesAsync ( ) ; }
|
How can I easily support duplicate async/sync methods ?
|
C#
|
I am creating a C # TBB . I have the XML code as shown below.C # TBB code : In the XML code `` body '' tag is occured multiple times . I need to extract the each and every `` body '' tag content . For that purpose I am using HTML agility pack . To make it work in the C # TBB , How to add the HTML agility pack DLL to the Tridion system ? And also please provide a sample code snippet in html agility to loop through the body tags.If HTML Agility is not going to work with C # TBB then please suggest me a way how to get the `` body '' tag content ? Thanks in advance.Early response is appreciated .
|
< content > < ah > 123 < /ah > < ph > 456 < /ph > < body > < sc > hi < /sc > < value > aa < /value > < value > bb < /value > < value > cc < /value > < value > dd < /value > < value > dd < /value > < /body > < body > < sc > hello < /sc > < value > ee < /value > < value > ddff < /value > < /body > < /content > using ( MemoryStream ms = new MemoryStream ( ) ) { XmlTextWriter securboxXmlWriter = new XmlTextWriter ( ms , new System.Text.UTF8Encoding ( false ) ) ; securboxXmlWriter.Indentation = 4 ; securboxXmlWriter.Formatting = Formatting.Indented ; securboxXmlWriter.WriteStartDocument ( ) ; securboxXmlWriter.WriteStartElement ( `` component '' ) ; securboxXmlWriter.WriteAttributeString ( `` xmlns : xsi '' , `` http : //www.w3.org/2001/XMLSchema-instance '' ) ; securboxXmlWriter.WriteAttributeString ( `` xmlns '' , `` http : //www.w3.org/1999/xhtml '' ) ; securboxXmlWriter.WriteStartElement ( `` content '' ) ; securboxXmlWriter.WriteStartElement ( `` wire : wire '' ) ; securboxXmlWriter.WriteStartElement ( `` wire : si '' ) ; securboxXmlWriter.WriteStartElement ( `` wg : ah '' ) ; securboxXmlWriter.WriteElementString ( `` text '' , package.GetValue ( `` Component.ah '' ) ) ; securboxXmlWriter.WriteEndElement ( ) ; securboxXmlWriter.WriteStartElement ( `` wg : ph '' ) ; securboxXmlWriter.WriteElementString ( `` nlt '' , package.GetValue ( `` Component.ph '' ) ) ; securboxXmlWriter.WriteEndElement ( ) ; securboxXmlWriter.WriteEndElement ( ) ; securboxXmlWriter.WriteEndElement ( ) ; securboxXmlWriter.WriteEndElement ( ) ; securboxXmlWriter.WriteEndElement ( ) ; securboxXmlWriter.WriteEndDocument ( ) ; securboxXmlWriter.Flush ( ) ; securboxXmlWriter.Close ( ) ; Item output = package.GetByName ( `` Output '' ) ; if ( output ! = null ) { package.Remove ( output ) ; } package.PushItem ( `` Output '' , package.CreateStringItem ( ContentType.Xml , Encoding.UTF8.GetString ( ms.ToArray ( ) ) ) ) ; }
|
How to add third party dll in Tridion for C # TBB ?
|
C#
|
Consider the following code : Will the compiler optimize the calls to Test.OptionOne.ToString ( ) or will it call it for each item in the testValues collection ?
|
enum Test { OptionOne , OptionTwo } List < string > testValues = new List < string > { ... } // A huge collection of stringsforeach ( var val in testValues ) { if ( val == Test.OptionOne.ToString ( ) ) // **Here** { // Do something } }
|
Will the C # compiler optimize calls to a same method inside a loop ?
|
C#
|
I remember few weeks ago when I reorgnized our code and created some namespaces in our project I got error and the system did not allow me to create a companyName.projectName.System namespace , I had to change it to companyName.projectName.Systeminfo . I do n't know why . I know there is a System namespace but it is not companyName.projectName.System . I think A.B.C namespace should be different with A.A.C namespace . Right ? EDITThe error I got is like the this :
|
Error 7 The type or namespace name 'Windows ' does not exist in the namespace 'MyCompany.SystemSoftware.System ' ( are you missing an assembly reference ? ) C : \workspace\SystemSoftware\SystemSoftware\obj\Release\src\startup\App.g.cs 39 39 SystemSoftware
|
C # : why can I not create a system namespace ?
|
C#
|
We have developed a WPF Application with C # and are using RestSharp to communicate with a simple Web Service like this : It all worked great until we received calls that on some machines ( most work ) the app ca n't connect to the service.A direct call to the service method with fiddler worked . Then we extracted a small .net console app and tried the service call with RestSharp and directly with a HttpWebRequest and it failed again with 401.Now we enabled System.Net tracing and noticed something . After the first 401 , which is normal , the faulty machine produces this log : System.Net Information : 0 : [ 4480 ] Connection # 3741682 - Received headers { Connection : Keep-Alive Content-Length : 1293 Content-Type : text/html Date : Mon , 10 Aug 2015 12:37:49 GMT Server : Microsoft-IIS/8.0 WWW-Authenticate : Negotiate , NTLM X-Powered-By : ASP.NET } . System.Net Information : 0 : [ 4480 ] ConnectStream # 39451090 : :ConnectStream ( Buffered 1293 bytes . ) System.Net Information : 0 : [ 4480 ] Associating HttpWebRequest # 2383799 with ConnectStream # 39451090 System.Net Information : 0 : [ 4480 ] Associating HttpWebRequest # 2383799 with HttpWebResponse # 19515494 System.Net Information : 0 : [ 4480 ] Enumerating security packages : System.Net Information : 0 : [ 4480 ] Negotiate System.Net Information : 0 : [ 4480 ] NegoExtender System.Net Information : 0 : [ 4480 ] Kerberos System.Net Information : 0 : [ 4480 ] NTLM System.Net Information : 0 : [ 4480 ] Schannel System.Net Information : 0 : [ 4480 ] Microsoft Unified Security Protocol Provider System.Net Information : 0 : [ 4480 ] WDigest System.Net Information : 0 : [ 4480 ] TSSSP System.Net Information : 0 : [ 4480 ] pku2u System.Net Information : 0 : [ 4480 ] CREDSSP System.Net Information : 0 : [ 4480 ] AcquireCredentialsHandle ( package = NTLM , intent = Outbound , authdata = ( string.empty ) \corp\svc_account ) System.Net Information : 0 : [ 4480 ] InitializeSecurityContext ( credential = System.Net.SafeFreeCredential_SECURITY , context = ( null ) , targetName = HTTP/mysvc.mycorp.com , inFlags = Delegate , MutualAuth , Connection ) System.Net Information : 0 : [ 4480 ] InitializeSecurityContext ( In-Buffers count=1 , Out-Buffer length=40 , returned code=ContinueNeeded ) .A working machine produces this output : System.Net Information : 0 : [ 3432 ] Connection # 57733168 - Empfangene Statusleiste : Version = 1.1 , StatusCode = 401 , StatusDescription = Unauthorized . System.Net Information : 0 : [ 3432 ] Connection # 57733168 - Header { Content-Type : text/html Server : Microsoft-IIS/8.0 WWW-Authenticate : Negotiate , NTLM X-Powered-By : ASP.NET Date : Mon , 10 Aug 2015 15:15:11 GMT Content-Length : 1293 } wurden empfangen . System.Net Information : 0 : [ 3432 ] ConnectStream # 35016340 : :ConnectStream ( Es wurden 1293 Bytes gepuffert . ) System.Net Information : 0 : [ 3432 ] Associating HttpWebRequest # 64062224 with ConnectStream # 35016340 System.Net Information : 0 : [ 3432 ] Associating HttpWebRequest # 64062224 with HttpWebResponse # 64254500 System.Net Information : 0 : [ 3432 ] Sicherheitspakete werden enumeriert : System.Net Information : 0 : [ 3432 ] Negotiate System.Net Information : 0 : [ 3432 ] NegoExtender System.Net Information : 0 : [ 3432 ] Kerberos System.Net Information : 0 : [ 3432 ] NTLM System.Net Information : 0 : [ 3432 ] Schannel System.Net Information : 0 : [ 3432 ] Microsoft Unified Security Protocol Provider System.Net Information : 0 : [ 3432 ] WDigest System.Net Information : 0 : [ 3432 ] TSSSP System.Net Information : 0 : [ 3432 ] pku2u System.Net Information : 0 : [ 3432 ] CREDSSP System.Net Information : 0 : [ 3432 ] AcquireCredentialsHandle ( package = Negotiate , intent = Outbound , authdata = System.Net.SafeSspiAuthDataHandle ) System.Net Information : 0 : [ 3432 ] InitializeSecurityContext ( credential = System.Net.SafeFreeCredential_SECURITY , context = ( null ) , targetName = HTTP/mysvc.mycorp.com , inFlags = Delegate , MutualAuth , Connection ) System.Net Information : 0 : [ 3432 ] InitializeSecurityContext ( Anzahl von In-Buffers = 1 , Länge von Out-Buffer = 40 , zurückgegebener Code = ContinueNeeded ) .I wonder if some configuration on the faulty machine would cause this . At the moment I am not sure where to look next.Update : Here is the Code of our simple test tool : Update 2 : We have now confirmed that this Problem only occurs on newly installed win 7 machines that have an updated corporate Image . Almost Looks like some update in the last 2 months is screwing with us .
|
Client = new RestClient ( serviceUri.AbsoluteUri ) ; Client.Authenticator = new NtlmAuthenticator ( SvcUserName , SvcPassword.GetString ( ) ) ; RestClient Client = new RestClient ( `` https : //mysvc.mycorp.com/service.svc '' ) ; Client.Authenticator = new NtlmAuthenticator ( `` corp\\svc_account '' , `` mypassword '' ) ; var request = new RestRequest ( `` api/Method '' , Method.POST ) ; request.RequestFormat = DataFormat.Json ; request.AddBody ( new { Device_Key = `` somestring '' } ) ; request.Timeout = 200000 ; RestResponse response = ( RestResponse ) Client.Execute ( request ) ;
|
401 when calling Web Service only on particular machines
|
C#
|
I 'm wrestling with a weird , at least for me , method overloading resolution of .net . I 've written a small sample to reproduce the issue : Will print : Basically the overload called is different depending on the value ( 0 , 1 ) instead of the given data type.Could someone explain ? UpdateI should have pointed out that there 's a different behaviour between C # 2 and C # 3
|
class Program { static void Main ( string [ ] args ) { var test = new OverloadTest ( ) ; test.Execute ( 0 ) ; test.Execute ( 1 ) ; Console.ReadLine ( ) ; } } public class OverloadTest { public void Execute ( object value ) { Console.WriteLine ( `` object overload : { 0 } '' , value ) ; } public void Execute ( MyEnum value ) { Console.WriteLine ( `` enum overload : { 0 } '' , value ) ; } } public enum MyEnum { First = 1 , Second = 2 , Third = 3 } enum overload : 0object overload : 1 Do ( ( long ) 0 ) = > object overload //C # 2Do ( ( long ) 0 ) = > enum overload //C # 3
|
Method overload resolution unexpected behavior
|
C#
|
I have a pair of libraries that both use the same COM interface . In one library I have a class that implements that interface . The other library requires an object that implements the interface.However both libraries have their own definition of the interface . Both are slightly different but essentially the same interface.So I try to case between them as follows : but this raises as an exception . If I do the following : Then it casts without problem but I am no longer able to pass the class to Library2.I naively assumed that both interfaces having the same GUID would prevent this being a problem but I appear to be wrong on that . Does anyone have any idea how I can convert between the 2 libraries ? Perhaps via a Marshal of some sort ?
|
Library2.Interface intf = ( Library2.Interface ) impl ; Library1.Interface intf = ( Library1.Interface ) impl ;
|
Converting between 2 different libraries using the same COM interface in C #
|
C#
|
Let 's say there 's a class that with one public constructor , which takes one parameter . In addition , there are also multiple public properties I 'd like to set . What would be the syntax for that in F # ? For instance in C # In F # I can get this done using either the constructor or property setters , but not both at the same time as in C # . For example , the following are n't validIt looks like I 'm missing something , but what ? < edit : As pointed out by David , doing it all in F # works , but for some reason , at least for me : ) , it gets difficult when the class to be used in F # is defined in C # . As for an example on such is TopicDescription ( to make up something public enough as for an added example ) . One can write , for instanceand the corresponding compiler error will be Method 'set_IsReadOnly ' is not accessible from this code location .
|
public class SomeClass { public string SomeProperty { get ; set ; } public SomeClass ( string s ) { } } //And associated usage.var sc = new SomeClass ( `` '' ) { SomeProperty = `` '' } ; let sc1 = new SomeClass ( `` '' , SomeProperty = `` '' ) let sc2 = new SomeClass ( s = `` '' , SomeProperty = `` '' ) let sc3 = new SomeClass ( `` '' ) ( SomeProperty = `` '' ) let t = new TopicDescription ( `` '' , IsReadOnly = true )
|
In F # , what is the object initializer syntax with a mandatory constructor parameter ?
|
C#
|
I 've got this code in my App.xaml.cs : I would like to do something similar for the InitializedEvent.Here 's my failed attempt : Is the InitializedEvent somewhere else ? Is this even possible ? I 've tried using the LoadedEvent : It only fired for Windows and not the controls inside the Windows . I did realize though ; that when I added a loaded event to a Label that I had inside my Window ; the global FrameworkElement_LoadedEvent fired for that Label even though my normal loaded event ( That I made for the Label specifically ) was empty . I 've also tried these : But they do n't fire unless I add another empty loaded event on those controls specifically.My goal is to build up a sort of a time log of every control that becomes initialized.How can I achieve this without adding loaded events on every single control I have ? ( I have a lot )
|
protected override void OnStartup ( StartupEventArgs e ) { EventManager.RegisterClassHandler ( typeof ( TextBox ) , TextBox.TextChangedEvent , new RoutedEventHandler ( TextBox_TextChangedEvent ) ) ; } private void TextBox_TextChangedEvent ( object sender , RoutedEventArgs e ) { // Works } protected override void OnStartup ( StartupEventArgs e ) { EventManager.RegisterClassHandler ( typeof ( FrameworkElement ) , FrameworkElement.InitializedEvent , new EventHandler ( FrameworkElement_InitializedEvent ) ) ; } private void FrameworkElement_InitializedEvent ( object sender , EventArgs e ) { } protected override void OnStartup ( StartupEventArgs e ) { EventManager.RegisterClassHandler ( typeof ( FrameworkElement ) , FrameworkElement.LoadedEvent , new RoutedEventHandler ( FrameworkElement_LoadedEvent ) ) ; } private void FrameworkElement_LoadedEvent ( object sender , RoutedEventArgs e ) { // Fires only for Windows } EventManager.RegisterClassHandler ( typeof ( Button ) , Button.LoadedEvent , new RoutedEventHandler ( Button_LoadedEvent ) ) ; EventManager.RegisterClassHandler ( typeof ( Grid ) , Grid.LoadedEvent , new RoutedEventHandler ( Grid_LoadedEvent ) ) ; EventManager.RegisterClassHandler ( typeof ( DataGrid ) , DataGrid.LoadedEvent , new RoutedEventHandler ( DataGrid_LoadedEvent ) ) ;
|
How do I assign a global initialized event ?
|
C#
|
i am reading Accelerated C # i do n't really understand the following code : in the last line what is x referring to ? and there 's another : How do i evaluate this ? ( y ) = > ( x ) = > func ( x , y ) what is passed where ... it does confusing .
|
public static Func < TArg1 , TResult > Bind2nd < TArg1 , TArg2 , TResult > ( this Func < TArg1 , TArg2 , TResult > func , TArg2 constant ) { return ( x ) = > func ( x , constant ) ; } public static Func < TArg2 , Func < TArg1 , TResult > > Bind2nd < TArg1 , TArg2 , TResult > ( this Func < TArg1 , TArg2 , TResult > func ) { return ( y ) = > ( x ) = > func ( x , y ) ; }
|
Need help understanding lambda ( currying )
|
C#
|
I just updated Visual Studio 2013 and I noticed that in the project template for an MVC application the ApplicationDbContext class now has a static method that just calls the constructor : This seems like clutter to me but I imagine that there is some semantic reason that I should now start using ApplicationDbContext.Create ( ) instead of new ApplicationDbContext ( ) . Are there any benefits to doing so ?
|
public static ApplicationDbContext Create ( ) { return new ApplicationDbContext ( ) ; }
|
Is there any benefit ( semantic or other ) to using a static method that calls a constructor ?
|
C#
|
I am trying to use the stack exchange MiniProfiler in my asp MVC project , but getting a really annoying error message in my view , where I am callingandon the RenderIncludes line , VS complains that The type 'MiniProfiler ' exists in both 'MiniProfiler.Shared , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b44f9351044011a3 ' and 'MiniProfiler , Version=3.2.0.157 , Culture=neutral , PublicKeyToken=b44f9351044011a3 ' I already checked the ( .csprroj ) project file , and it only contains one element referencing MiniProfiler : I also checked in packages.config and it also only has 1 reference to MiniProfiler : I cleaned the project and restarted Visual Studio but with no success . What is happening here ?
|
@ using StackExchange.Profiling @ MiniProfiler.RenderIncludes ( ) < Reference Include= '' MiniProfiler , Version=3.2.0.157 , Culture=neutral , PublicKeyToken=b44f9351044011a3 , processorArchitecture=MSIL '' > < HintPath > ..\packages\MiniProfiler.3.2.0.157\lib\net40\MiniProfiler.dll < /HintPath > < /Reference > < package id= '' MiniProfiler '' version= '' 3.2.0.157 '' targetFramework= '' net452 '' / >
|
The type MiniProfiler exists in both Miniprofiler.Shared and MiniProfiler
|
C#
|
I have a fairly complex thing stuffed into a T4 template . Basically I take something like { =foo= } more text ... and convert it into a class ( view ) like so : The code generated is of course much more complicated than this . Anyway , the T4 template is over 600 lines of code right now and really becoming unmanageable fast . I believe the main problem is mixing code and `` content '' ( ie , static code ) . I 'm not really sure how to cleanly fix this problem though ( while of course not affecting the code generated ) . I also do n't see any feasible way to unit test my T4 code , other than simply testing it for T4 execution errors . And of course there seems to be the nearly impossible task of testing it 's generated code . Are there any `` model-view '' type frameworks or techniques I can use to make my T4 template code more clean ?
|
public class MyView { public string foo { get ; set ; } public string Write ( ) { return foo+ @ '' more text ... '' ; } }
|
Is there anything out there to make T4 code more ... clean ?
|
C#
|
Thanks for looking . I 'm kind of new to Ninject and like it so far . I get the part where you bind one thing in debug mode and bind another in release mode . Those are global bindings where you have to declare that every Samurai will have a sword or a dagger , using Ninjects example code . It 's not either/or , it 's one or the other . How do I do something where I can have one Samurai with a sword , and another with a dagger where they could even switch weapons if they like . Is there another way other than creating a bunch of kernels with different binding modules ? Here is the example code from Ninject . If you drop it in a console app it should run : EDITThanks for the replays and suggestions . I figured out how to get pretty much what I wanted . Okay , so here is what I did : Set the default/initial binding to the weakest weapon . Sort of like a new-b would do.Added another weapon ( Dagger ) Expanded IWeapon to include a WeaponHitPoints value to rate the weapons value.Expanded Samurai to include an add and drop weapon method so the Samurai can gain or lose weapons.Modified the Attack method to use the best weapon.Modified the program to make use of the added features.TODO : add try/catch and null checks ... Create a Console project called NinjectConsole , install Ninject and you should be able to just drop this in and run it.Here is the new code :
|
using System ; using Ninject ; namespace NinjectConsole { class Program { //here is where we have to choose which weapon ever samurai must use ... public class BindModule : Ninject.Modules.NinjectModule { public override void Load ( ) { //Bind < IWeapon > ( ) .To < Sword > ( ) ; Bind < IWeapon > ( ) .To < Shuriken > ( ) ; } } class Shuriken : IWeapon { public void Hit ( string target ) { Console.WriteLine ( `` Pierced { 0 } 's armor '' , target ) ; } } class Sword : IWeapon { public void Hit ( string target ) { Console.WriteLine ( `` Chopped { 0 } clean in half '' , target ) ; } } interface IWeapon { void Hit ( string target ) ; } class Samurai { readonly IWeapon weapon ; [ Inject ] public Samurai ( IWeapon weapon ) { if ( weapon == null ) throw new ArgumentNullException ( `` weapon '' ) ; this.weapon = weapon ; } public void Attack ( string target ) { this.weapon.Hit ( target ) ; } } static void Main ( string [ ] args ) { //here is where we bind ... Ninject.IKernel kernel = new StandardKernel ( new BindModule ( ) ) ; var samurai = kernel.Get < Samurai > ( ) ; samurai.Attack ( `` your enemy '' ) ; //here is I would like to do , but with DI and no local newing up ... var warrior1 = new Samurai ( new Shuriken ( ) ) ; var warrior2 = new Samurai ( new Sword ( ) ) ; warrior1.Attack ( `` the evildoers '' ) ; warrior2.Attack ( `` the evildoers '' ) ; Console.ReadKey ( ) ; } } } using System ; using System.Collections.Generic ; using System.Linq ; using Ninject ; namespace NinjectConsole { class Program { public class BindModule : Ninject.Modules.NinjectModule { // default bind to weakest weapon public override void Load ( ) { Bind < IWeapon > ( ) .To < Dagger > ( ) ; } } class Dagger : IWeapon { public int WeaponHitPoints { get { return 5 ; } } public string Hit ( string target ) { return String.Format ( `` Stab { 0 } to death '' , target ) ; } } class Shuriken : IWeapon { public int WeaponHitPoints { get { return 9 ; } } public string Hit ( string target ) { return String.Format ( `` Pierced { 0 } 's armor '' , target ) ; } } class Sword : IWeapon { public int WeaponHitPoints { get { return 11 ; } } public string Hit ( string target ) { return string.Format ( `` Chopped { 0 } clean in half '' , target ) ; } } interface IWeapon { int WeaponHitPoints { get ; } string Hit ( string target ) ; } private class Samurai { private IEnumerable < IWeapon > _allWeapons ; public Samurai ( IWeapon [ ] allWeapons ) { if ( ! allWeapons.Any ( ) ) throw new ArgumentException ( `` Samurai '' ) ; _allWeapons = allWeapons ; } public void AddWeapon ( IWeapon weapon ) { //TODO : check for nulls ... _allWeapons = _allWeapons.Concat ( new [ ] { weapon } ) ; } public void DropWeapon ( IWeapon weapon ) { //TODO : check for nulls ... Console.WriteLine ( `` A Samurai got rid of a `` + weapon.WeaponName ) ; _allWeapons = _allWeapons.Where ( x = > x.WeaponName ! = weapon.WeaponName ) ; } public void Attack ( string target ) { int points = 0 ; try { points = _allWeapons.Max ( x = > x.WeaponHitPoints ) ; } catch ( ) { Console.WriteLine ( `` You just punched `` + target + `` on the nose ! `` ) ; } var attackWeapon = _allWeapons.FirstOrDefault ( i = > i.WeaponHitPoints == points ) ; //TODO : check for nulls ... Console.WriteLine ( attackWeapon.Hit ( target ) ) ; } } static void Main ( string [ ] args ) { Ninject.IKernel kernel = new StandardKernel ( new BindModule ( ) ) ; var samurai1 = kernel.Get < Samurai > ( ) ; var samurai2 = kernel.Get < Samurai > ( ) ; Console.WriteLine ( `` Samurai # 1 '' ) ; samurai1.Attack ( `` your enemy '' ) ; samurai2.AddWeapon ( new Shuriken ( ) ) ; Console.WriteLine ( `` \nSamurai # 2 selects best weapon for attack '' ) ; samurai2.Attack ( `` your enemy '' ) ; Console.WriteLine ( `` \nSamurai # 1 gets new weapon ! `` ) ; samurai1.AddWeapon ( new Sword ( ) ) ; Console.WriteLine ( `` Samurai # 1 selects best weapon for attack '' ) ; samurai1.Attack ( `` your enemy '' ) ; Console.ReadKey ( ) ; } } }
|
One samurai with a sword and one with a dagger
|
C#
|
So I have some code in VB that I am trying to convert to C # . This code was written by someone else and I am trying to understand it but with some difficulty . I have some bitwise operator and enum comparison to do but keep throwing an error out : I can not say that i have used a lot of these syntaxes before and am baffled how to write this code . I have used Google to understand more about it and also used VB to C # online converters in the hopes of getting some basic guidance but nothing . The code belowVB - This is the original code that worksC # -the code I converted which is throwing an errorError - The error that is returned every time Operator ' ! ' can not be applied to operand of type MyEnum'.Any help and some explanation on this will be greatly appreciated .
|
Flags = Flags And Not MyEnum.Value ' Flags is of type int Flags = Flags & ! MyEnum.Value ; // Flags is of type int
|
Operator ' ! ' can not be applied to operand of type x
|
C#
|
I 'm reading Effective C # ( Second Edition ) and it talks about method inlining.I understand the principle , but I do n't see how it would work based on the 2 examples in the book . The book says : Inlining means to substitute the body of a function for the function call.Fair enough , so if I have a method , and its call : the JIT compiler might ( will ? ) inline it to : Now , with these two examples ( verbatim from the book ) : Example 1Example 2The book mentions the code but does n't go any further into how they might be inlined . How would the JIT compiler inline these 2 examples ?
|
public string SayHiTo ( string name ) { return `` Hi `` + name ; } public void Welcome ( ) { var msg = SayHiTo ( `` Sergi '' ) ; } public void Welcome ( ) { var msg = `` Hi `` + `` Sergi '' ; } // readonly name propertypublic string Name { get ; private set ; } // access : string val = Obj.Name ; string val = `` Default Name '' ; if ( Obj ! = null ) val = Obj.Name ;
|
How does method inlining work for auto-properties in C # ?
|
C#
|
Using Entity-Framework 6 I 'm able to set up the configuration through Fluent Api like this : Source from this questionUsing the attribute approach I 'm able to know what 's the property roles by reflection , but I wonder how can I retrieve these configurations , like Key for example , with Fluent Api approach ? There 's no public property from the EntityTypeConfiguration < > class.Is that possible to get the Key and ForeignKey somehow ?
|
public class ApplicationUserConfiguration : EntityTypeConfiguration < ApplicationUser > { public ApplicationUserConfiguration ( ) { this.HasKey ( d = > d.Id ) ; this.Ignore ( d = > d.UserId ) ; } }
|
How to retrieve Entity Configuration from Fluent Api
|
C#
|
Having a list of structs OR maybe an array List each with 3 elements , likeI want to get rid of items that have 2 common subitems in list , in the example I would like to removeSo using structs approach I am thinking in sorting the list by element A , then looping and comparing elements , in a way that If current element has 2 values equal to other element in list I do not add it to a result List , however I got stuck and do not know if there is a better approach Is there a more efficient way to get the list without having item with 2 same items so I would get , instead of hardcoding the solution ?
|
12 8 75 1 07 3 210 6 56 2 18 4 36 1 57 2 68 3 79 4 811 7 613 9 811 6 1012 7 1113 8 1214 9 13 5 1 06 2 16 1 57 3 27 2 68 4 38 3 7 has 2 same items as row 7,3,29 4 8 has 2 same items as row 8,4,310 6 511 7 611 6 10 has 2 same items as row 11,7,612 7 11 has 2 same items as row 11,7,1012 8 713 8 1213 9 814 9 13 has 2 same items as row 13,9,8 struct S { public int A ; public int B ; public int C ; } public void test ( ) { List < S > DataItems = new List < S > ( ) ; DataItems.Add ( new S { A = 1 , B = 2 , C=3 } ) ; DataItems.Add ( new S { A = 12 , B = 8 , C = 7 } ) ; DataItems.Add ( new S { A = 5 , B = 1 , C = 0 } ) ; DataItems.Add ( new S { A = 7 , B = 3 , C = 2 } ) ; DataItems.Add ( new S { A = 10 , B = 6 , C = 5 } ) ; DataItems.Add ( new S { A = 6 , B = 2 , C = 1 } ) ; DataItems.Add ( new S { A = 8 , B = 4 , C = 3 } ) ; DataItems.Add ( new S { A = 6 , B = 1 , C = 5 } ) ; DataItems.Add ( new S { A = 7 , B = 2 , C = 6 } ) ; DataItems.Add ( new S { A = 8 , B = 3 , C = 7 } ) ; DataItems.Add ( new S { A = 9 , B = 4 , C = 8 } ) ; DataItems.Add ( new S { A = 11 , B = 7 , C = 6 } ) ; DataItems.Add ( new S { A = 13 , B = 9 , C = 8 } ) ; DataItems.Add ( new S { A = 11 , B = 6 , C = 10 } ) ; DataItems.Add ( new S { A = 12 , B = 7 , C = 11 } ) ; DataItems.Add ( new S { A = 13 , B = 8 , C = 12 } ) ; DataItems.Add ( new S { A = 14 , B = 9 , C = 13 } ) ; var sortedList = DataItems.OrderBy ( x = > x.A ) ; List < S > resultList = new List < S > ( ) ; for ( int i = 0 ; i < sortedList.Count ( ) ; i++ ) { for ( int j = i+1 ; j < sortedList.Count ( ) ; j++ ) { if ( sortedList.ElementAt ( i ) .A == sortedList.ElementAt ( j ) .A || sortedList.ElementAt ( i ) .A == sortedList.ElementAt ( j ) .B || sortedList.ElementAt ( i ) .A == sortedList.ElementAt ( j ) .C ) { //ONE HIT , WAIT OTHER } } } } 5 1 06 2 16 1 57 3 27 2 68 4 310 6 511 7 612 8 713 8 1213 9 8
|
How to remove elements of list of array/structs that have 2 common elements
|
C#
|
When the C # compiler interprets a method invocation it must use ( static ) argument types to determine which overload is actually being invoked . I want to be able to do this programmatically.If I have the name of a method ( a string ) , the type that declares it ( an instance of System.Type ) , and a list of argument types I want to be able to call a standard library function and get back a MethodInfo object representing the method the C # compiler would choose to invoke.For instance if I haveThen I want something like this fictional function GetOverloadedMethod on System.TypeIn this case methodToInvoke should be public void myFunc ( BaseClass bc ) .NOTE : Neither of the methods GetMethod and GetMethods will serve my purpose . Neither of them do any overload resolution . In the case of GetMethod it only returns exact matches . If you give it more derived arguments it will simply return nothing . Or you might be lucky enough to get an ambiguity exception which provides no useful information .
|
class MyClass { public void myFunc ( BaseClass bc ) { } ; public void myFunc ( DerivedClass dc ) { } ; } MethodInfo methodToInvoke = typeof ( MyClass ) .GetOverloadedMethod ( `` myFunc '' , new System.Type [ ] { typeof ( BaseClass ) } ) ;
|
How can I programmatically do method overload resolution in C # ?
|
C#
|
I 'm trying to obfuscate a string , but need to preserve a couple patterns . Basically , all alphanumeric characters need to be replaced with a single character ( say ' X ' ) , but the following ( example ) patterns need to be preserved ( note that each pattern has a single space at the beginning ) QQQ '' RRR '' I 've looked through a few samples on negative lookahead/behinds , but still not have n't any luck with this ( only testing QQQ ) .The correct result should be : This works for an exact match , but will fail with something like ' QQR '' ' , which returns
|
var test = @ '' '' '' SOME TEXT AB123 12XYZ QQQ '' '' '' '' empty '' '' '' '' empty '' '' 1A2BCDEF '' ; var regex = new Regex ( @ '' ( ( ? ! QQQ ) ( ? < ! \sQ { 1,3 } ) ) [ 0-9a-zA-Z ] '' ) ; var result = regex.Replace ( test , `` X '' ) ; `` XXXX XXXX XXXXX XXXXX QQQ '' '' XXXXX '' '' XXXXX '' XXXXXXXX `` XXXX XXXX XXXXX XXXXX XQR '' '' XXXXX '' '' XXXXX '' XXXXXXXX
|
Replace all alphanumeric characters in a string except pattern
|
C#
|
What should IEquatable < T > .Equals ( T obj ) do when this == null and obj == null ? 1 ) This code is generated by F # compiler when implementing IEquatable < T > . You can see that it returns true when both objects are null:2 ) Similar code can be found in the question `` in IEquatable implementation is reference check necessary '' or in the question `` Is there a complete IEquatable implementation reference ? '' . This code returns false when both objects are null.3 ) The last option is to say that the behaviour of the method is not defined when this == null .
|
public sealed override bool Equals ( T obj ) { if ( this == null ) { return obj == null ; } if ( obj == null ) { return false ; } // Code when both this and obj are not null . } public sealed override bool Equals ( T obj ) { if ( obj == null ) { return false ; } // Code when obj is not null . }
|
Result of calling IEquatable < T > .Equals ( T obj ) when this == null and obj == null ?
|
C#
|
Let 's say I have these two methods : The following were the results I got : I understand that PLINQ has some overhead because of the threads setup , but with such a big n I was expecting PLINQ to be faster.Here is another result :
|
public BigInteger PFactorial ( int n ) { return Enumerable.Range ( 1 , n ) .AsParallel ( ) .Select ( i = > ( BigInteger ) i ) .Aggregate ( BigInteger.One , BigInteger.Multiply ) ; } public BigInteger Factorial ( int n ) { BigInteger result = BigInteger.One ; for ( int i = 1 ; i < = n ; i++ ) result *= i ; return result ; } PFactorial ( 25000 ) - > 0,9897 secondsFactorial ( 25000 ) - > 0,9252 seconds PFactorial ( 50000 ) - > 4,91035 secondsFactorial ( 50000 ) - > 4,40056 seconds
|
Why is PLINQ slower than for loop ?
|
C#
|
This is my C # Code : HTML Code : Javascript Code : I want show 'username ' in text field but when form will be post I want to send 'ID ' . Instead of that I am getting username .
|
public JsonResult FillUsers ( string term ) { var Retailers = from us in db.Users join pi in db.UserPersonalInfoes on us.ID equals pi.UserID into t from rt in t.DefaultIfEmpty ( ) where us.Status == true select new { ID = us.ID , Username = us.Username + `` : ( `` + ( rt == null ? String.Empty : rt.FirstName ) + `` ) '' } ; List < string > UsersList ; UsersList = Retailers.Where ( x = > x.Username.Contains ( term ) ) .Select ( y = > y.Username ) .Take ( 10 ) .ToList ( ) ; return Json ( UsersList , JsonRequestBehavior.AllowGet ) ; } < div class= '' col-md-3 '' > @ Html.TextBox ( `` ddlUser '' , null , new { @ id = `` ddlUser '' , @ class = `` form-control '' } ) < /div > < script type= '' text/javascript '' > $ ( function ( ) { $ ( `` # ddlUser '' ) .autocomplete ( { source : ' @ Url.Action ( `` FillUsers '' , `` FirebaseNotification '' ) ' , select : function ( event , ui ) { var id = ui.item.ID ; var name = ui.item.Username ; } } ) ; } ) ;
|
How to post value from autocomplete instead of text ?
|
C#
|
I have on my winform two panels : on the first panel I have an usercontrol that can be multiplied dynamically . I want , on the second panel , to be displayed the usercontrol that is selected by the user . The idea is that , I want , if I change the text at runtime of my usercontrol , these changes to be displayed on the second panel too . I need an idea how can I do that . I am trying now to create properties for each object of my usercontrol and events , but I think is too much to do for this . . Thanks.My code , what I have tried so far : On my usercontrol I have created properties for each object that this contains . Code on usercontrol.cs :
|
public string TextName { get { return textname.Text ; } set { textname.Text = value ; } } public string Task { get { return checkboxTip.Text ; } set { checkboxTip.Text = value ; } } ... ... . and on my winform.cs I created an event for all properties : private void PropertiesChange_Click ( object sender , EventArgs e ) { textname1.Text=textname.Text ; //textname1 is the textbox from usercontrol , and textname is from the second panel ; checkboxTip1.Text-checkbox.Text ; ... ..// I am doing this for each object , but I have 10 objects .
|
Display control on another panel
|
C#
|
Given a function async Task < ( Boolean result , MyObject value ) > TryGetAsync ( ) , I can doBut if I try to use declare the types or use deconstruction get an error `` a declaration is not allowed in this context '' : How can I avoid using the first option var ret in this scenario ? My issue with this is that the types are not evident ( which is a separate discussion ) .
|
if ( ( await TryGetAsync ( ) ) is var ret & & ret.result ) { //use ret.value } //declaration . errorif ( ( await TryGetAsync ( ) ) is ( Boolean result , MyObject value ) ret & & ret.result ) { //use ret.value } //deconstruction , also error.if ( ( await TryGetAsync ( ) ) is ( Boolean result , MyObject value ) & & result ) { //use value }
|
Deconstruct tuple for pattern matching
|
C#
|
I have to unit test my BlogController 's CreatePost action method . I am passing SavePostViewModel without some fields like Author , Subject , and Postdate which are required field to test CreatePost action method should returns `` Invalid Input '' which is in ( ! ModelState.IsValid ) logic . But it 's always return true even when I am passing a null object.My View Model : My Controller Action Method : My Test Method :
|
public class SavePostViewModel : ISavePostDto { public SavePostViewModel ( ) { PostDate = Helper.LocalDateToday ; CategoryIds = new List < int > ( ) ; } [ DisplayName ( `` Post ID '' ) ] public int ? Id { get ; set ; } [ DisplayName ( `` Post Date '' ) ] [ Required ( ErrorMessage = `` { 0 } is required '' ) ] public DateTime PostDate { get ; set ; } [ DisplayName ( `` Mata Title '' ) ] public string MetaTitle { get ; set ; } [ DisplayName ( `` Mata Keywords '' ) ] public string MetaKeywords { get ; set ; } [ DisplayName ( `` Mata Description '' ) ] public string MetaDescription { get ; set ; } [ DisplayName ( `` Author '' ) ] [ Required ( ErrorMessage = `` { 0 } is required '' ) ] [ StringLength ( 100 , ErrorMessage = `` { 0 } can be maximum of { 1 } characters '' ) ] public string Author { get ; set ; } [ DisplayName ( `` Subject '' ) ] [ Required ( ErrorMessage = `` { 0 } is required '' ) ] [ StringLength ( 100 , ErrorMessage = `` { 0 } can be maximum of { 1 } characters '' ) ] public string Subject { get ; set ; } [ DisplayName ( `` Short Description '' ) ] [ Required ( ErrorMessage = `` { 0 } is required '' ) ] [ StringLength ( 500 , ErrorMessage = `` { 0 } can be maximum of { 1 } characters '' ) ] public string ShortDesc { get ; set ; } [ DisplayName ( `` Content '' ) ] public string Content { get ; set ; } [ DisplayName ( `` Categories '' ) ] public List < int > CategoryIds { get ; set ; } [ DisplayName ( `` URL Key '' ) ] public string UrlKey { get ; set ; } public bool IsPublished { get ; set ; } public string PhotoPath { get ; set ; } public string PhotoVersion { get ; set ; } } [ HttpPost ] public async Task < IActionResult > CreatePost ( SavePostViewModel model ) { if ( ! ModelState.IsValid ) { ViewData [ MESSAGE_KEY_ERROR ] = `` Invalid input '' ; return View ( model ) ; } var result = await _blogService.CreatePostAsync ( model ) ; if ( result.Status ! = TaskResult.StatusCodes.SUCCESS ) { ViewData [ MESSAGE_KEY_ERROR ] = result.Message ; return View ( model ) ; } TempData [ `` PROMPT_PHOTO_UPLOAD '' ] = `` TRUE '' ; return Redirect ( `` /Blog/EditPost/ '' + result.Post.Id ) ; } [ Test ] public async Task HttpPost_CreatePost_When_Model_Is_Invalid_Returns_Error ( ) { // Arrange var expectedErrorMessage = `` Invalid input '' ; var model = new SavePostViewModel ( ) { //Author = `` Tamim Iqbal '' , Content = `` New Content '' , IsPublished = true , //Subject = `` New Subject '' , //PostDate = Helper.LocalDateToday , } ; // Act var result = await _blogController.CreatePost ( model ) as ViewResult ; var actualErrorMessage = result.ViewData [ `` ERROR_MESSAGE '' ] ; // Assert Assert.AreEqual ( expectedErrorMessage , actualErrorMessage ) ; }
|
Why ModelState.IsValid always return true ?
|
C#
|
My colleague was getting an error with a more complex query using LINQ to SQL in .NET 4.0 , but it seems to be easily reproducible in more simpler circumstances . Consider a table named TransferJob with a synthetic id and a bit field.If we make the following queryAn invalid cast exception is thrown where noted . But strangely , we have type equality when viewing in a debugger.Simply changing the second to last line to move from IQueryable 's to using linq-to-objectsthen everything work fine as expected.After some initial digging , I see that it looks like the programmers of LINQ to SQL were considering performance and are not actually having the generated SQL pull the constant value in the case with the explicit setting of true in the withConstant version . Finally , if I switch order everything seems to work : However , I 'd still like to know if better detail what is really going on . I find it rather odd that these would be considered equal types but cause an invalid cast exception . What 's actually happening under the covers ? How could I go about proving it to myself ? Stack Trace : Generated SQL is the following : With the order reversed ( which does n't crash ) the SQL is : To my earlier comment , the constant is n't pulled when doing
|
using ( var ctx = DBDataContext.Create ( ) ) { var withOutConstant = ctx.TransferJobs.Select ( x = > new { Id = x.TransferJobID , IsAuto = x.IsFromAutoRebalance } ) ; var withConstant = ctx.TransferJobs.Select ( x = > new { Id = x.TransferJobID , IsAuto = true } ) ; //note we 're putting a constant value in this one var typeA = withOutConstant.GetType ( ) ; var typeB = withConstant.GetType ( ) ; bool same = typeA == typeB ; //this is true ! var together = withOutConstant.Concat ( withConstant ) ; var realized = together.ToList ( ) ; //invalid cast exception } var together = withOutConstant.ToList ( ) .Concat ( withConstant.ToList ( ) ) ; var realized = together.ToList ( ) ; //no problem here var together = withConstant.Concat ( withOutConstant ) ; //no problem this way at System.Data.SqlClient.SqlBuffer.get_Boolean ( ) at Read_ < > f__AnonymousType2 ` 2 ( ObjectMaterializer ` 1 ) at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader ` 2.MoveNext ( ) at System.Collections.Generic.List ` 1..ctor ( IEnumerable ` 1 collection ) at System.Linq.Enumerable.ToList [ TSource ] ( IEnumerable ` 1 source ) at KBA.GenericTestRunner.Program.Main ( String [ ] args ) in c : \Users\nick\Source\Workspaces\KBA\Main\KBA\KBA.GenericTestRunner\Program.cs : line 59 at System.AppDomain._nExecuteAssembly ( RuntimeAssembly assembly , String [ ] args ) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ( ) at System.Threading.ExecutionContext.RunInternal ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( ) SELECT [ t2 ] . [ TransferJobID ] AS [ Id ] , [ t2 ] . [ IsFromAutoRebalance ] AS [ IsAuto ] FROM ( SELECT [ t0 ] . [ TransferJobID ] , [ t0 ] . [ IsFromAutoRebalance ] FROM [ dbo ] . [ TransferJob ] AS [ t0 ] UNION ALL SELECT [ t1 ] . [ TransferJobID ] , @ p0 AS [ value ] FROM [ dbo ] . [ TransferJob ] AS [ t1 ] ) AS [ t2 ] -- @ p0 : Input Int ( Size = -1 ; Prec = 0 ; Scale = 0 ) [ 1 ] -- Context : SqlProvider ( Sql2008 ) Model : AttributedMetaModel Build : 4.0.30319.34209 SELECT [ t2 ] . [ TransferJobID ] AS [ Id ] , [ t2 ] . [ value ] AS [ IsAuto ] FROM ( SELECT [ t0 ] . [ TransferJobID ] , @ p0 AS [ value ] FROM [ dbo ] . [ TransferJob ] AS [ t0 ] UNION ALL SELECT [ t1 ] . [ TransferJobID ] , [ t1 ] . [ IsFromAutoRebalance ] FROM [ dbo ] . [ TransferJob ] AS [ t1 ] ) AS [ t2 ] -- @ p0 : Input Int ( Size = -1 ; Prec = 0 ; Scale = 0 ) [ 1 ] -- Context : SqlProvider ( Sql2008 ) Model : AttributedMetaModel Build : 4.0.30319.34209 withConstant.ToList ( ) SELECT [ t0 ] . [ TransferJobID ] AS [ Id ] FROM [ dbo ] . [ TransferJob ] AS [ t0 ] -- Context : SqlProvider ( Sql2008 ) Model : AttributedMetaModel Build : 4.0.30319.34209
|
Odd behavior in LINQ to SQL with anonymous objects and constant columns
|
C#
|
I 'm using automatic globalization on an ASP MVC website . It works fine until it reached a parallel block : What is the best way to make the parallel block inherit the culture ? apart from this solution :
|
public ActionResult Index ( ) { // Thread.CurrentThread.CurrentCulture is automatically set to `` fr-FR '' // according to the requested `` Accept-Language '' header Parallel.Foreach ( ids , id = > { // Not every thread in this block has the correct culture . // Some of them still have the default culture `` en-GB '' } ) ; return View ( ) } public ActionResult Index ( ) { var currentCulture = Thread.CurrentThread.CurrentCulture ; Parallel.Foreach ( ids , id = > { // I do n't know if it 's threadsafe or not . Thread.CurrentThread.CurrentCulture = currentCulture ; } ) ; return View ( ) }
|
How to correctly inherit thread culture in a parallel block ?
|
C#
|
In MVC 6 source code I saw some code lines that has strings leading with $ signs.As I never saw it before , I think it is new in C # 6.0 . I 'm not sure . ( I hope I 'm right , otherwise I 'd be shocked as I never crossed it before.It was like :
|
var path = $ '' ' { pathRelative } ' '' ;
|
What does ' $ ' sign do in C # 6.0 ?
|
C#
|
I am writing a small application that prints some stickers to a special printer.When I use MS Word to print some text to that printer ( and to an XPS file ) , the result looks excellent . When I print from C # code with the Graphics object , the text appears to be over-pixelized or over-smoothed.I tried the following hints , but none produced the same result as MS Word : And some others.Can you advice which hints are applied by MS Word , so I could create it programatically ?
|
System.Drawing.Drawing2D.SmoothingMode.AntiAliasSystem.Drawing.Text.TextRenderingHint.AntiAliasGridFitSystem.Drawing.Text.TextRenderingHint.AntiAliasSystem.Drawing.Text.TextRenderingHint.ClearTypeGridFitInterpolationMode.NearestNeighborCompositingQuality.HighQuality
|
Achieving MS Word print quality in C #
|
C#
|
Sorry if this sounds simple , but I 'm looking for some help to improve my code : ) So I currently have the following implementation ( which I also wrote ) : Then I have technology-specific concrete classes : Now I 'm trying to add a generic optimizer , one that optimizes for conditions other than priority , so my attempt : and I also need technology-specific implementation just like the priority optimizer : Q1 . TechnologyXPriorityOptimizer and TechnologyXGenericOptimizer have the same exact `` extra '' methods because they involve the same technology . Is there a way to keep this method common to both inheritance branches ? Q2 . For AbstractGenericOptimizer , the optimizer has a special name for special values of the int param , so would it be a good idea to extend the base generic optimizer class ( where param is hardcoded ) and then for every division , have a technology-specific implementation : What would be the best way to refactor this scenario ? I feel that there is a smarter way of reducing the number of inheritance levels.Thanks !
|
public interface IOptimizer { void Optimize ( ) ; string OptimizerName { get ; } } public abstract AbstractOptimizer : IOptimizer { public void Optimize ( ) { // General implementation here with few calls to abstract methods } } public abstract AbstractPriorityOptimizer : AbstractOptimizer { // Optimize according to priority criteria . string Name { get { return `` Priority Optimizer '' ; } } } TechnologyXPriorityOptimizer : AbstractPriorityOptimizer TechnologyYPriorityOptimizer : AbstractPriorityOptimizer public abstract AbstractGenericOptimizer : AbstractOptimizer { // Optimize according to a generic criteria . private readonly int param ; public AbstractGenericOptimizer ( int param ) : base ( ) { // param affects the optimization this.param = param ; } } TechnologyXGenericOptimizer : AbstractGenericOptimizer TechnologyYGenericOptimizer : AbstractGenericOptimizer AbstractSpecialName1Optimizer : AbstractGenericOptimizerTechnologyXSpecialName1Optimizer : AbstractSpecialName1OptimizerTechnologyYSpecialName1Optimizer : AbstractSpecialName1OptimizerAbstractSpecialName2Optimizer : AbstractGenericOptimizer ... .
|
Refactoring abstract class in C #
|
C#
|
For testing purposes , I need to mock a Task-returning method on an interface handing back a task that never runs the continuation . Here 's the code I have so far : Here , I 've created a custom awaitable type that simply ignores the continuation handed to it -- await new StopAwaitable ( ) has essentially the same effect as a return from a sync method . Then , I await it in an async Task method , creating a Task object that will never run the continuation.My question is , is this the most concise/clear way to do this ? Is there any other way to create such a task that does n't involve a custom awaitable , which will confuse people unfamiliar w/ how async works ?
|
// FooTests.cs [ Test ] public void Foo ( ) { var yielder = Substitute.For < IYielder > ( ) ; yielder.YieldAsync ( ) .Returns ( ThreadingUtilities.NeverReturningTask ) ; ... } // ThreadingUtilities.csusing System.Diagnostics ; using System.Threading.Tasks ; namespace Repository.Editor.Android.UnitTests.TestInternal.Threading { internal static class ThreadingUtilities { public static Task NeverReturningTask { get ; } = CreateNeverReturningTask ( ) ; private async static Task CreateNeverReturningTask ( ) { await new StopAwaitable ( ) ; Debug.Fail ( `` Execution should n't reach here . `` ) ; } } } // StopAwaitable.csusing System ; using System.Diagnostics ; using System.Runtime.CompilerServices ; namespace Repository.Editor.Android.UnitTests.TestInternal.Threading { internal struct StopAwaitable : INotifyCompletion { public bool IsCompleted = > false ; public StopAwaitable GetAwaiter ( ) = > this ; public void GetResult ( ) { Debug.Fail ( `` The continuation should n't have been posted ! `` ) ; } public void OnCompleted ( Action continuation ) { // Ignore the continuation . } } }
|
What 's the most concise way to create a Task that never returns ?
|
C#
|
I made a form and extended the glass in it like in the image below . But when I move the window so not all of it is visible on screen , the glass rendering is wrong after I move it back : How can I handle this so the window is rendered correctly ? This is my code :
|
[ DllImport ( `` dwmapi.dll '' ) ] private static extern void DwmExtendFrameIntoClientArea ( IntPtr hWnd , ref Margins mg ) ; [ DllImport ( `` dwmapi.dll '' ) ] private static extern void DwmIsCompositionEnabled ( out bool enabled ) ; public struct Margins { public int Left ; public int Right ; public int Top ; public int Bottom ; } private void Form1_Shown ( object sender , EventArgs e ) { this.CreateGraphics ( ) .FillRectangle ( new SolidBrush ( Color.Black ) , new Rectangle ( 0 , this.ClientSize.Height - 32 , this.ClientSize.Width , 32 ) ) ; bool isGlassEnabled = false ; Margins margin ; margin.Top = 0 ; margin.Left = 0 ; margin.Bottom = 32 ; margin.Right = 0 ; DwmIsCompositionEnabled ( out isGlassEnabled ) ; if ( isGlassEnabled ) { DwmExtendFrameIntoClientArea ( this.Handle , ref margin ) ; } }
|
Glass is not rendered right
|
C#
|
I 've this code : I want to have the same name for my two methods . Is this even possible ? My problems : I have to write two different methods because of the return type ( I want it to be null if the request failed or a value if the request succeed ) which is Nullable < T > if T is a value type , and an instance of T if T is a reference type . async does n't allow ref/out , so without a method argument of type T , T is n't inferred and my two methods can not have the same name ( signature conflict , as generic constraints does n't works for signature conflict resolution if T is n't inferred ) Currently this code works but I do n't like this strange function calls between `` RequestValue1 '' and `` RequestValue2 '' .
|
public async static Task < T ? > RequestValue1 < T > ( Command requestCommand ) where T : struct { // Whatever } public async static Task < T > RequestValue2 < T > ( Command requestCommand ) where T : class { // Whatever }
|
Generics , Nullable , Type inference and function signature conflict
|
C#
|
I am using the MVVM Light library . From this library I use RelayCommand < T > to define commands with an argument of type T. Now I have defined a RelayCommand that requires an argument of type Nullable < bool > : How can I assign the CommandParameter from my XAML code ? I 've tried to pass a boolean value , but that causes the following exception : System.InvalidCastException : Invalid cast from 'System.Boolean ' to 'System.Nullable ` 1 [ [ System.Boolean , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] '.I 've also tried to define static properties containing the bool ? values and reference them from XAML : XAML : But this causes the same exception to be thrown . I 've also tried to return new Nullable < bool > ( true ) , but as expected , this has the same result .
|
private RelayCommand < bool ? > _cmdSomeCommand ; public RelayCommand < bool ? > CmdSomeCommand { get { if ( _cmdSomeCommand == null ) { _cmdSomeCommand = new RelayCommand < bool ? > ( new Action < bool ? > ( ( val ) = > { /* do work */ } ) ) ; } return _cmdSomeCommand ; } } public static class BooleanHelper { public static bool True { get { return true ; } } public static bool False { get { return false ; } } public static bool ? NullableTrue { get { return true ; } } public static bool ? NullableFalse { get { return false ; } } } < Button Command= '' { Binding CmdSomeCommand } '' CommandParameter= '' { x : Static my : BooleanHelper.NullableTrue } '' / >
|
How do I pass Nullable < Boolean > value to CommandParameter ?
|
C#
|
I have 2 classes , each returns itself in all of the function : I want to enable this kind of API : SetName can not be accessed since SetId returns Parent and SetName is on the Child.How ?
|
public class Parent { public Parent SetId ( string id ) { ... return this } } public class Child : Parent { public Child SetName ( string id ) { ... return this } } new Child ( ) .SetId ( `` id '' ) .SetName ( `` name '' ) ;
|
C # Object oriented return type `` this '' on child call
|
C#
|
I 'm trying to figure out what 's the difference between these two rules ? MergeSequentialChecksMergeSequentialChecksWhenPossibleThe documentation does n't say anything about the second one.https : //www.jetbrains.com/help/resharper/2016.1/MergeSequentialChecks.htmlAnd it 's not quire clear for me what does it mean WhenPossible ? If ReSharper suggests to apply the first rule and merge my sequential checks , then it IS possible indeed . How it could be not possible ? Here is a code example to check .
|
public class Person { public string Name { get ; set ; } public IList < Person > Descendants { get ; set ; } } public static class TestReSharper { // Here ` MergeSequentialChecks ` rule is triggered for both ` & & ` operands . public static bool MergeSequentialChecks ( Person person ) { return person ! = null & & person.Descendants ! = null & & person.Descendants.FirstOrDefault ( ) ! = null ; } // Here ` MergeSequentialChecksWhenPossible ` rule is triggered . public static bool MergeSequentialChecksWhenPossible1 ( Person person ) { return person ! = null & & person.Descendants.Any ( ) ; } // Here ` MergeSequentialChecksWhenPossible ` rule is triggered . public static bool MergeSequentialChecksWhenPossible2 ( Person person ) { return person.Descendants ! = null & & person.Descendants.Any ( ) ; } }
|
What 's the difference between ReSharper ` MergeSequentialChecks ` and ` MergeSequentialChecksWhenPossible ` ?
|
C#
|
I 'm in the process of converting my Microsoft SDK Beta code to the Microsoft SDK Official Release that was released February 2012 . I added a generic PauseKinect ( ) to pause the Kinect . My pause will really only remove the event handler that updated the image Pros : No Reinitialization ( 30+ second wait time ) Cons : Kinect still processing imagesPause Method ( Color Only ) PROBLEM : Even though I 'm removing the event why is it still getting triggered ? NOTE : Also when I pause the color image I 'm also pausing the depth and skeleton in their object.SIDE NOTE : If I uncomment my code it works fine , but then it 'll take forever to reinitialize which is not what I want to do.MS in Reflector
|
internal void PauseColorImage ( bool isPaused ) { if ( isPaused ) { _Kinect.ColorFrameReady -= ColorFrameReadyEventHandler ; //_Kinect.ColorStream.Disable ( ) ; } else { _Kinect.ColorFrameReady += ColorFrameReadyEventHandler ; //_Kinect.ColorStream.Enable ( ColorImageFormat.RgbResolution640x480Fps30 ) ; } } public void AddHandler ( EventHandler < T > originalHandler ) { if ( originalHandler ! = null ) { this._actualHandlers.Add ( new ContextHandlerPair < T , T > ( originalHandler , SynchronizationContext.Current ) ) ; } } public void RemoveHandler ( EventHandler < T > originalHandler ) { SynchronizationContext current = SynchronizationContext.Current ; ContextHandlerPair < T , T > item = null ; foreach ( ContextHandlerPair < T , T > pair2 in this._actualHandlers ) { EventHandler < T > handler = pair2.Handler ; SynchronizationContext context = pair2.Context ; if ( ( current == context ) & & ( handler == originalHandler ) ) { item = pair2 ; break ; } } if ( item ! = null ) { this._actualHandlers.Remove ( item ) ; } } public void Invoke ( object sender , T e ) { if ( this.HasHandlers ) { ContextHandlerPair < T , T > [ ] array = new ContextHandlerPair < T , T > [ this._actualHandlers.Count ] ; this._actualHandlers.CopyTo ( array ) ; foreach ( ContextHandlerPair < T , T > pair in array ) { EventHandler < T > handler = pair.Handler ; SynchronizationContext context = pair.Context ; if ( context == null ) { handler ( sender , e ) ; } else if ( this._method == ContextSynchronizationMethod < T > .Post ) { context.Post ( new SendOrPostCallback ( this.SendOrPostDelegate ) , new ContextEventHandlerArgsWrapper < T , T > ( handler , sender , e ) ) ; } else if ( this._method == ContextSynchronizationMethod < T > .Send ) { context.Send ( new SendOrPostCallback ( this.SendOrPostDelegate ) , new ContextEventHandlerArgsWrapper < T , T > ( handler , sender , e ) ) ; } } } }
|
Pause Kinect Camera - Possible error in SDK reguarding event handler
|
C#
|
Here 's a simple test demonstrating the problem : I need a comparing method which will determine that these two properties are actually represent the same property . What is the correct way of doing this ? In particular I want to check if property actually comes from base class and not altered in any way like overriden ( with override int Foo ) , hidden ( with new int Foo ) properties , interface properties ( i.e . explicit implementation in derived class ISome.Foo ) or any other way that lead to not calling MyBase.Foo when instanceOfDerived.Foo is used .
|
class MyBase { public int Foo { get ; set ; } } class MyClass : MyBase { } [ TestMethod ] public void TestPropertyCompare ( ) { var prop1 = typeof ( MyBase ) .GetProperty ( `` Foo '' ) ; var prop2 = typeof ( MyClass ) .GetProperty ( `` Foo '' ) ; Assert.IsTrue ( prop1 == prop2 ) ; // fails //Assert.IsTrue ( prop1.Equals ( prop2 ) ) ; // also fails }
|
How to compare same PropertyInfo with different ReflectedType values ?
|
C#
|
When a method has two overloads , one accepting IDictionary and another accepting IDictionary < TKey , TValue > , passing new Dictionary < string , int > ( ) to it is considered ambigous . However , if the two overloads are changed to accept IEnumerable and IEnumerable < KeyValuePair < TKey , TValue > > , the call is no longer ambigous.As Dictionary < TKey , TValue > implements all of the above interfaces ( to be precise , IDictionary < TKey , TValue > , ICollection < KeyValuePair < TKey , TValue > > , IDictionary , ICollection , IReadOnlyDictionary < TKey , TValue > , IReadOnlyCollection < KeyValuePair < TKey , TValue > > , IEnumerable < KeyValuePair < TKey , TValue > > , IEnumerable , ISerializable , IDeserializationCallback in .NET 4.5 ) ; as IDictionary is inherited from IEnumerable and IDictionary < TKey , TValue > is inherited from IEnumerable < KeyValuePair < TKey , TValue > > , I ca n't understand why it happens.Sample console application : The error I get is : The call is ambiguous between the following methods or properties : 'AmbigousCall.Program.FooDic ( System.Collections.IDictionary ) ' and 'AmbigousCall.Program.FooDic ( System.Collections.Generic.IDictionary ) 'Question 1 : Why does it happen ? Question 2 : How to accept both generic and non-generic arguments without causing ambiguity if a class implements both ?
|
using System ; using System.Collections ; using System.Collections.Generic ; namespace AmbigousCall { internal class Program { static void Main ( string [ ] args ) { var dic = new Dictionary < string , int > ( ) ; FooDic ( dic ) ; // Error : The call is ambiguous FooEnum ( dic ) ; // OK : The generic method is called Console.ReadKey ( ) ; } static void FooDic ( IDictionary dic ) { } static void FooDic < TKey , TValue > ( IDictionary < TKey , TValue > dic ) { } static void FooEnum ( IEnumerable dic ) { } static void FooEnum < TKey , TValue > ( IEnumerable < KeyValuePair < TKey , TValue > > dic ) { } } }
|
Ambiguous call when a method has overloads for IDictionary and IDictionary < TKey , TValue >
|
C#
|
Using c # HttpClient to POST data , hypothetically I 'm also concerned with the returned content . I 'm optimizing my app and trying to understand the performance impact of two await calls in the same method . The question popped up from the following code snippet , Assume I have error handling in there : ) I know await calls are expensive so the double await caught my attention.After the first await completes the POST response is in memory would it be more efficient to return the result directly , like var response = post.Content.ReadAsStringAsync ( ) .Result ; What are the performance considerations when making two await/async calls in the same method ? Will the above code result in a thread per await ( 2 threads ) , or 1 thread for the returned Task that will handle both await calls ?
|
public static async Task < string > AsyncRequest ( string URL , string data = null ) { using ( var client = new HttpClient ( ) ) { var post = await client.PostAsync ( URL , new StringContent ( data , Encoding.UTF8 , `` application/json '' ) ) .ConfigureAwait ( false ) ; post.EnsureSuccessStatusCode ( ) ; var response = await post.Content.ReadAsStringAsync ( ) ; return response ; } }
|
Double await operations during POST
|
C#
|
Does the line fixed ( int* pArray = & array [ 0 ] ) from the example below pin the whole array , or just array [ 0 ] ?
|
int array = new int [ 10 ] ; unsafe { fixed ( int* pArray = & array [ 0 ] ) { } // or just 'array ' }
|
How to pin the whole array in C # using the keyword fixed
|
C#
|
I just relfected over WindowsBase.dll > > System.Windows.UncommonField < T > and I wondered about the usage of this class ... E.g . it 's used in the Button-class : So what is the use of this `` wrapper '' ?
|
public class Button : ButtonBase { private static readonly UncommonField < KeyboardFocusChangedEventHandler > FocusChangedEventHandlerField = new UncommonField < KeyboardFocusChangedEventHandler > ( ) ; }
|
The use of UncommonField < T > in WPF
|
C#
|
Is there a way to have a common logic to retrieve the file size on disk regardless of the underlying operating system ? The following code works for windows but obviously does n't for Linux.Alternatively , I 'm looking for a similar implementation that would work on Linux . Can anyone point me in the right direction ? Thanks for your help !
|
public static long GetFileSizeOnDisk ( string file ) { FileInfo info = new FileInfo ( file ) ; uint dummy , sectorsPerCluster , bytesPerSector ; int result = GetDiskFreeSpaceW ( info.Directory.Root.FullName , out sectorsPerCluster , out bytesPerSector , out dummy , out dummy ) ; if ( result == 0 ) throw new Win32Exception ( ) ; uint clusterSize = sectorsPerCluster * bytesPerSector ; uint hosize ; uint losize = GetCompressedFileSizeW ( file , out hosize ) ; long size ; size = ( long ) hosize < < 32 | losize ; return ( ( size + clusterSize - 1 ) / clusterSize ) * clusterSize ; } [ DllImport ( `` kernel32.dll '' ) ] static extern uint GetCompressedFileSizeW ( [ In , MarshalAs ( UnmanagedType.LPWStr ) ] string lpFileName , [ Out , MarshalAs ( UnmanagedType.U4 ) ] out uint lpFileSizeHigh ) ; [ DllImport ( `` kernel32.dll '' , SetLastError = true , PreserveSig = true ) ] static extern int GetDiskFreeSpaceW ( [ In , MarshalAs ( UnmanagedType.LPWStr ) ] string lpRootPathName , out uint lpSectorsPerCluster , out uint lpBytesPerSector , out uint lpNumberOfFreeClusters , out uint lpTotalNumberOfClusters ) ;
|
C # .net Core - Get file size on disk - Cross platform solution
|
C#
|
I 'm using method overloading in Assembly A : When I try to call the second overload from Assembly B , VS produces the following compile-time error : The type 'System.Data.Entity.DbContext ' is defined in an assembly that is not referenced . You must add a reference to assembly 'EntityFramework , Version=6.0.0.0 , Culture=neutral , PublicKeyToken= ... '.Assembly B references Assembly A . Entity Framework is referenced only in Assembly A as Assembly B does n't use it . The call from Assembly B looks like this : What I do n't understand is that the error goes away if I change the method signature in Assembly A to e.g . : and change the call to : Why is my code not compiling in the first case ? It does n't seem to be related to Entity Framework as the error indicates . I have always thought that C # allows method overloading where method signatures differ only in parameter types . E.g . I can run the following code without problems as expected : So why am I getting the error in my situation despite the apparently legal overloads ? Note that from Assembly B I have no problems calling other methods that internally use EntityDataContext , the only difference is that these methods do n't have overloads.BackgroundEntityDataContext inherits EF 's DbContext : I 'm using .NET 4.0 with EF 6 code first to an existing database with some custom ctor overloads added .
|
public static int GetPersonId ( EntityDataContext context , string name ) { var id = from ... in context ... where ... select ... ; return id.First ( ) ; } public static int GetPersonId ( SqlConnection connection , string name ) { using ( var context = new EntityDataContext ( connection , false ) ) { return GetPersonId ( context , name ) ; } } using ( SqlConnection connection = new SqlConnection ( connectionString ) ) { connection.Open ( ) ; var id = AssemblyA.GetPersonId ( connection , name ) ; // compiler error ... } public static int GetPersonId ( SqlConnection connection , string name , bool empty ) var id = AssemblyA.GetPersonId ( connection , name , true ) ; // no error static void DoStuff ( int a , int b ) { ... } static void DoStuff ( int a , float b ) { ... } DoStuff ( 10 , 5 ) ; DoStuff ( 10 , 5.0f ) ; public partial class EntityDataContext : DbContext { public EntityDataContext ( ) : base ( `` name=EntityDataContext '' ) { } public EntityDataContext ( DbConnection connection , bool contextOwnsConnection ) : base ( connection , contextOwnsConnection ) { } ... }
|
Weird `` assembly not referenced '' error when trying to call a valid method overload
|
C#
|
hi everybody I want used shortcut key ( using left and right key ) in wpf and tabcontrol to navigation between tabitem I set code in Window_KeyDown ( object sender , System.Windows.Input.KeyEventArgs e ) like this : but it 's not do anything I want navigation between tabitem with left and right keythanks
|
switch ( e.Key ) { case Key.Right : if ( tbControl.TabIndex == 0 ) tbControl.TabIndex = 1 ; break ; case Key.Left : if ( tbControl.TabIndex == 0 ) tbControl.TabIndex = 1 ; break ; }
|
how to navigate between tabitem with Left and Right Key in WPF
|
C#
|
First of all , this will not be a post about Database Transactions . I want to know more about the TransactionModel in .NET 2.0 and higher . Since I am developing against .NET 3.5 newer models are apprechiated.Now , what I would like to acheive is something like the followingWhich would mean that when the Money is less than 0 , everything inside the TransactionScope should be RolledBack , however , it 's not.A simple test as followedProvided that the Stadard Money amount is 100.Did I miss something here or is this not how the transactions should work ? And what are the performance losses using this model ?
|
public void Withdraw ( double amount ) { using ( TransactionScope scope = new TransactionScope ( ) ) { Money -= amount ; if ( Money > 0 ) scope.Complete ( ) ; } } ImportantObject obj = new ImportantObject ( 1 ) ; Console.WriteLine ( obj.Money ) ; obj.Withdraw ( 101 ) ; Console.WriteLine ( obj.Money ) ;
|
Transactions in C #
|
C#
|
If I have an IOrderedEnumberable < Car > , I sort it and then do a projecting query ... is the order preserved in the projection ? For example , does this scenario work ? Does the name of the top3FastestCarManufacturers variable convey the meaning of what has really happened in the code ?
|
IOrderedEnumberable < Car > allCarsOrderedFastestToSlowest = GetAllCars ( ) .OrderByDescending ( car= > car.TopSpeed ) ; var top3FastestCarManufacturers = allCarsOrderedFastestToSlowest .Select ( car= > car.Manufacturer ) .Distinct ( ) .Take ( 3 ) ;
|
In LINQ , do projections off an IOrderedEnumerable < T > preserve the order ?
|
C#
|
I know that 's not possible as written , and as far as I understand it 's just simply not allowed ( although I would love nothing more than to be wrong about that ) . The first solution that comes to mind is to use an object initializer , but let 's suppose that 's a last resort because it would conflict with other oop goals in this case.My next inclination would be to use reflection , but before I do that I 'd like to know if I am overlooking any easier way to do this or perhaps a different design pattern that would work better ?
|
class MyClass < T > where T : new ( ) { public Test ( ) { var t = new T ( ) ; var t = new T ( `` blah '' ) ; // < - How to do this ? } }
|
Instantiating a generic type with an overloaded constructor
|
C#
|
I was reading `` CLR via C # '' and it seems that in this example , the object that was initially assigned to 'obj ' will be eligible for Garbage Collection after line 1 is executed , not after line 2.That 's because local variable lifespan defined not by scope in which it was defined , but by last time you read it.So my question is : what about Java ? I have written this program to check such behavior , and it looks like object stays alive . I do n't think that it 's possible for the JVM to limit variable lifetime while interpreting bytecode , so I tried to run program with 'java -Xcomp ' to force method compilation , but 'finalize ' is not called anyway . Looks like that 's not true for Java , but I hope I can get a more accurate answer here . Also , what about Android 's Dalvik VM ? Added : Jeffrey Richter gives code example in `` CLR via C # '' , something like this : TimerCallback called only once on MS .Net if projects target is 'Release ' ( timer destroyed after GC.Collect ( ) call ) , and called every second if target is 'Debug ' ( variables lifespan increased because programmer can try to access object with debugger ) . But on Mono callback called every second no matter how you compile it . Looks like Mono 's 'Timer ' implementation stores reference to instance somewhere in thread pool . MS implementation does n't do this .
|
void Foo ( ) { Object obj = new Object ( ) ; obj = null ; } class TestProgram { public static void main ( String [ ] args ) { TestProgram ref = new TestProgram ( ) ; System.gc ( ) ; } @ Override protected void finalize ( ) { System.out.println ( `` finalized '' ) ; } } public static void Main ( string [ ] args ) { var timer = new Timer ( TimerCallback , null , 0 , 1000 ) ; // call every second Console.ReadLine ( ) ; } public static void TimerCallback ( Object o ) { Console.WriteLine ( `` Callback ! `` ) ; GC.Collect ( ) ; }
|
Objects lifespan in Java vs .Net
|
C#
|
I am trying to learn ASP.NET 5 . I am using it on Mac OS X . At this time , I have a config.json file that looks like the following : config.jsonI am trying to figure out how to load these settings into a configuration file in Startup.cs . Currently , I have a file that looks like this : Configuration.csThen , in Startup.cs , I have the following : However , this approach does n't work . Basically , its like it does n't know how to map between the .json and the Config classes . How do I do this ? I would really like to stay with the DI approach so I can test my app more effectively.Thank you
|
{ `` AppSettings '' : { `` Environment '' : '' dev '' } , `` DbSettings '' : { `` AppConnectionString '' : `` ... '' } , `` EmailSettings '' : { `` EmailApiKey '' : `` ... '' } , } public class AppConfiguration { public AppSettings AppSettings { get ; set ; } public DbSettings DbSettings { get ; set ; } public EmailSettings EmailSettings { get ; set ; } } public class AppSettings { public string Environment { get ; set ; } } public class DbSettings { public string AppConnectionString { get ; set ; } } public class EmailSettings { public string MandrillApiKey { get ; set ; } } public IConfiguration Configuration { get ; set ; } public Startup ( IHostingEnvironment environment ) { var configuration = new Configuration ( ) .AddJsonFile ( `` config.json '' ) ; Configuration = configuration ; } public void ConfigureServices ( IServiceCollection services ) { services.Configure < AppConfiguration > ( Configuration ) ; }
|
ASP.NET 5 ( vNext ) - Configuration
|
C#
|
Why does new List < string > ( ) .ToString ( ) ; return the following : ? Why would n't it just bring back System.Collections.Generic.List < System.String > . What 's with the strange non C # syntax ?
|
System.Collections.Generic.List ` 1 [ System.String ]
|
Why does ToString ( ) on generic types have square brackets ?
|
C#
|
I found this link to make full-text search work through linq . However , the code seems to be targeting database first approach . How to make it work with Database First Approach ? Relevant part of code : As seen above the function OnModelCreating is only called in Code First Approach . I wonder what needs to change to make the code in link work for Database First approach
|
public class NoteMap : EntityTypeConfiguration < Note > { public NoteMap ( ) { // Primary Key HasKey ( t = > t.Id ) ; } } public class MyContext : DbContext { static MyContext ( ) { DbInterception.Add ( new FtsInterceptor ( ) ) ; } public MyContext ( string nameOrConnectionString ) : base ( nameOrConnectionString ) { } public DbSet < Note > Notes { get ; set ; } protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { modelBuilder.Configurations.Add ( new NoteMap ( ) ) ; } }
|
EF6 : Full-text Search with Database First Approach
|
C#
|
Error : The type arguments for method GraphMLExtensions.SerializeToGraphML < TVertex , TEdge , TGraph > ( TGraph , XmlWriter ) can not be inferred from the usage.The code is copied from QuickGraph 's documentation . However when I write it explicitly it works : Edit : I saw some related questions , but they are too advanced for me . I 'm just concerned about using it . Am I doing something wrong or it 's the documentation ?
|
using System.Xml ; using QuickGraph ; using QuickGraph.Serialization ; var g = new AdjacencyGraph < string , Edge < string > > ( ) ; ... . add some vertices and edges ... .using ( var xwriter = XmlWriter.Create ( `` somefile.xml '' ) ) g.SerializeToGraphML ( xwriter ) ; using ( var xwriter = XmlWriter.Create ( `` somefile.xml '' ) ) GraphMLExtensions.SerializeToGraphML < string , Edge < string > , AdjacencyGraph < string , Edge < string > > > ( g , xwriter ) ;
|
Extension method does n't work ( Quick Graph Serialization )
|
C#
|
I 'm creating a service that will monitor a specific folder and print any file that is put in this folder . I 'm having difficulties with the various file types that could be sent to the folder to be printed.My first attempt is with Microsoft Office files . What I 'm trying to do is start the office to print the file . It 's more like a catch , I 'm not really using a library or anything like it.So far this approach would work , but when no Office application has ever started on the machine the Office asks for the user initials . So , in this case my application would just not work , since I 'm doing this programatically.Right now I am trying with Microsoft Office files , but I will apply the same approach for other types as well.There is anyway to get around the Initials required by the first Office run ? Or any better approach to my problem ? Any help is appreciated , thanks in advance .
|
ProcessStartInfo info = new ProcessStartInfo ( myDocumentsPath ) ; info.Verb = `` Print '' ; info.CreateNoWindow = true ; info.WindowStyle = ProcessWindowStyle.Hidden ; Process.Start ( info ) ;
|
Printing any file type
|
C#
|
If one of the strings is n't 10 characters long I 'd get an ArgumentOutOfRangeException . In this case its fairly trivial to find out and I know I can do With more complex object construction errors like this are n't always easy to see though . Is there a way to see what string was n't long enough via exception handling ?
|
var trimmed = myStringArray.Select ( s = > s.Substring ( 0 , 10 ) ) ; s.Substring ( 0 , Math.Min ( 10 , s.Length ) )
|
LINQ Iterator Exception Handling
|
C#
|
I try to write System Tests in NUnit and I want to Invoke the UI using the UI Automation from ms.For some reason my Invokes fail - I found some hints online that got me to a state where I can write a compiling test but my assertion fails.Here is a compileable minimal example . My problem is the failing test in the example.Application XAMLApplication CSWindow XAMLWindow CSEDIT # 1 : @ Nkosi pointed out that there was a binding failure in my xamlEDIT # 2 : Added a bit of boiler to enable manual testing and also added a usecase that shows behaviour without uiautomation . That is just a sidenote , uiautomation is the core of this question .
|
< Application x : Class= '' InvokeTest.App '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' clr-namespace : InvokeTest '' Startup= '' Application_Startup '' / > using System.Windows ; namespace InvokeTest { public partial class App : Application { private void Application_Startup ( object sender , StartupEventArgs e ) { var view = new MainWindow ( ) ; var viewmodel = new MainWindowViewModel ( ) ; view.DataContext = viewmodel ; view.Show ( ) ; } } } < Window x : Class= '' InvokeTest.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : local= '' clr-namespace : InvokeTest '' mc : Ignorable= '' d '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' > < TextBox x : Name= '' MyTextBox '' x : FieldModifier= '' public '' Text= '' { Binding TextProperty , UpdateSourceTrigger=PropertyChanged } '' / > < /Window > using NUnit.Framework ; using System.Diagnostics ; using System.Threading ; using System.Windows ; using System.Windows.Automation.Peers ; using System.Windows.Automation.Provider ; using System.Windows.Controls ; namespace InvokeTest { public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; } } public class MainWindowViewModel { string textfield ; public string TextProperty { get { DebugLog ( `` getter '' ) ; return textfield ; } set { textfield = value ; DebugLog ( `` setter '' ) ; } } private void DebugLog ( string function ) { Debug.WriteLine ( ToString ( ) + `` `` + nameof ( TextProperty ) + `` `` + function + `` was called . value : ' '' + textfield ? ? `` < null > '' + `` ' '' ) ; } [ TestFixture , Apartment ( ApartmentState.STA ) ] public class WPFTest { MainWindow view ; MainWindowViewModel viewmodel ; [ SetUp ] public void SetUp ( ) { view = new MainWindow ( ) ; viewmodel = new MainWindowViewModel ( ) ; view.DataContext = viewmodel ; } [ Test ] public void SetTextBox_NoAutomation ( ) { string expected = `` I want to set this '' ; view.MyTextBox.Text = expected ; Assert.AreEqual ( expected , viewmodel.TextProperty ) ; /* Test Name : SetTextBox_NoAutomation Test Outcome : Failed Result Message : Expected : `` I want to set this '' But was : null */ } [ Test ] public void SetTextBox_UIAutomation ( ) { string expected = `` I want to set this '' ; SetValue ( view.MyTextBox , expected ) ; Assert.AreEqual ( expected , viewmodel.TextProperty ) ; /* Test Name : SetTextBox_UIAutomation Test Outcome : Failed Result Message : Expected : `` I want to set this '' But was : null */ } private static void SetValue ( TextBox textbox , string value ) { TextBoxAutomationPeer peer = new TextBoxAutomationPeer ( textbox ) ; IValueProvider provider = peer.GetPattern ( PatternInterface.Value ) as IValueProvider ; provider.SetValue ( value ) ; } } } }
|
How to Invoke a setter for a WPF Textbox in an NUnit Test
|
C#
|
I have a co-worker who uses a C # refactoring tool . The tool for some reason perfers : overNow we 've asked him to turn it off simply because it 's annoying to have all the code re-written automatically , but that 's not the point.Am I missing something , or is this just wrong ? Why on earth would I want this.Foo ( ) ?
|
this.Foo ( ) Foo ( )
|
Foo ( ) vs this.Foo ( )
|
C#
|
As described in my previous question : Asp.net web API 2 separation Of Web client and web server development In order to get full separation of client and server , I want to set a variable to hold the end point for client requests . When client side is developed , the requests will be sent to a `` stub server '' that returns default values so that client side can be developed without depending on the server side development . That stub server runs on one port different that the real server port , and when running integration between server and client , in a branch integration , the variable will hold the real server port.For that matter , I learned that a build tool such as Gulp could help me . I 'm working with Tfs source control.What I want is for example , write a task that will function like this : Is there a way to get the current branch that task is running in ? Thanks for helpers
|
gulp.task ( 'setEndPoint ' , function ( ) { var branchName = // How do I get it ? if ( branchName == `` Project.Testing '' ) endPoint = `` localhost/2234 '' if ( branchName == `` Project.Production '' ) endPoint = `` localhost/2235 '' } ) ;
|
Web api - Use Gulp task to dynamically set end point address
|
C#
|
I 've found a difference in overload resolution between the C # and the VB-compiler . I 'm not sure if it 's an error or by design : Note that it does n't matter if the overloaded Foo-methods are defined in VB or not . The only thing that matters is that the call site is in VB.The VB-compiler will report an error : Overload resolution failed because no accessible 'Foo ' is most specific for these arguments : 'Public Sub Foo ( Of String ) ( expression As System.Linq.Expressions.Expression ( Of System.Func ( Of String ) ) ) ' : Not most specific . 'Public Sub Foo ( Of ) ( value As ) ' : Not most specific.Adding the C # code which works for comparison :
|
Public Class Class1 Public Sub ThisBreaks ( ) ' These work ' Foo ( Of String ) ( Function ( ) String.Empty ) 'Expression overload ' Foo ( String.Empty ) 'T overload ' ' This breaks ' Foo ( Function ( ) String.Empty ) End Sub Public Sub Foo ( Of T ) ( ByVal value As T ) End Sub Public Sub Foo ( Of T ) ( ByVal expression As Expression ( Of Func ( Of T ) ) ) End SubEnd Class class Class1 { public void ThisDoesntBreakInCSharp ( ) { Foo < string > ( ( ) = > string.Empty ) ; Foo ( string.Empty ) ; Foo ( ( ) = > string.Empty ) ; } public void Foo < T > ( T value ) { } public void Foo < T > ( Expression < Func < T > > expression ) { } }
|
Is this an error in the VB.NET compiler or by design ?
|
C#
|
What is happening below ? i is being converted to string in both cases . I am confusing myself with the idea of operator precedence ( although this example does n't show much of that ) and evaluation direction . Sometimes evaluation happens from left-to-right or vice versa . I do n't exactly know the science of how the expression is evaluated ... Why is i converted to string in the above example , and not actually giving a compilation error ?
|
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; public class DotNetPad { public static void Main ( string [ ] args ) { int i = 10 ; string k = `` Test '' ; Console.WriteLine ( i+k ) ; Console.WriteLine ( k+i ) ; } }
|
Why is the integer converted to string in this case ?
|
C#
|
I have a little C # app that is extracting text from a Microsoft Publisher file via the COM Interop API.This works fine , but I 'm struggling if I have multiple styles in one section . Potentially every character in a word could have a different font , format , etc.Do I really have to compare character after character ? Or is there something that returns me the different style sections ? Kinda like I can get the different Paragraphs ? Or is there in general a better way to extract the text from a Publisher file ? But I have to be able to actually write it back with the same formatting . It 's for a translation .
|
foreach ( Microsoft.Office.Interop.Publisher.Shape shp in pg.Shapes ) { if ( shp.HasTextFrame == MsoTriState.msoTrue ) { text.Append ( shp.TextFrame.TextRange.Text ) ; for ( int i = 0 ; i < shp.TextFrame.TextRange.WordsCount ; i++ ) { TextRange range = shp.TextFrame.TextRange.Words ( i+1 , 1 ) ; string test = range.Text ; } } }
|
Get different style sections in Microsoft Publisher via Interop
|
C#
|
I 'm working on an MVC page that requires conditional validation.When a user selects a country from a dropdownlist , if they select one of two specific countries , then a box is displayed containing two text boxes which are required . I would like validation to activate in this case , and if they select any other country , then the box is hidden and validation will be deactivated.Currently on the site , which I did n't build , there is a separate validation class ( which inherits from ValidationSet ) that handles all validation for that controller , and they validate with commands like ValidatePresence , ValidateDecimal , and ValidateExpression , so I would like to stick to that format for consistency . e.g . Anyone got any ideas ? Thanks
|
new ValidatePresence ( `` countryId '' ) { ErrorMessageFormat = `` Please supply a country for delivery to '' }
|
ASP.net MVC conditional validation
|
C#
|
1 ) If one operand is of type ulong , while the other operand is of type sbyte/short/int/long , then compile-time error occurs . I fail to see the logic in this . Thus , why would it be bad idea for both operands to instead be promoted to type double or float ? b ) Compiler implicitly converts int literal into byte type and assigns resulting value to b : But if we try to assign a literal of type ulong to type long ( or to types int , byte etc ) , then compiler reports an error : I would think compiler would be able to figure out whether result of constant expression could fit into variable of type long ? ! thank you
|
long L = 100 ; ulong UL = 1000 ; double d = L + UL ; // error saying + operator ca n't be applied to operands of type ulong and long byte b = 1 ; long L = 1000UL ;
|
Instead of error , why do n't both operands get promoted to float or double ?
|
C#
|
Sorry about the stupid title , had no idea how to word thisI 'm creating a class that has two lists of the same type . It 's used to copy a reference to a object in the first list to the second list.While both lists will be of the same type ( hold the same type of object ) it can be different each time this class is initialized.So I 'm guessing I should make the List types as some kind of abstract list . I would like to ensure they will be strongly typed when instanced ( but not neccesary if problematic ) . The problem is inside the method that moves selected items from list1 to list2 abstract list types normally do n't have methods for that.I guess the normal solution would be to make the class generic ( className < T > thingy ) but I 'm not sure I can do that ( at least I do n't know how ) because this class inherits a WPF UserControl.Here is the Code : EDIT : SolutionSome answers pointed me towards the optimal solution of creating a Generic Class . However this can be problematic in WPF . You would have to skip the XAML on the top level generic class.This would mean that you could do the XAML in the type specific child classes which is n't something you would like to do ( unless only the code is something you would re-use but the look is variable ) . You could also have designed the control using code I guess but I 'm not sure how effective that would be.I was pointed towards the IList object which is a abstract list that many others inherit from and I 'm gon na use . It 's a bit of a hack but as this will not be used in a open library I 'm ok with it . Otherwise I would use the Generic Route .
|
public partial class SubsetSelectionLists : UserControl { public static DependencyProperty SetCollectionProperty = DependencyProperty.Register ( `` SetCollection '' , typeof ( `` Need a abstract list type here '' ) , typeof ( SubsetSelectionLists ) ) ; public static DependencyProperty SubsetCollectionProperty = DependencyProperty.Register ( `` SubsetCollection '' , typeof ( `` Need a abstract list type here '' ) , typeof ( SubsetSelectionLists ) ) ; public `` Need a abstract list type here '' SetCollection { get { return ( `` Need a abstract list type here '' ) GetValue ( SetCollectionProperty ) ; } set { SetValue ( SetCollectionProperty , value ) ; } } public `` Need a abstract list type here '' SubsetCollection { get { return ( `` Need a abstract list type here '' ) GetValue ( SubsetCollectionProperty ) ; } set { SetValue ( SubsetCollectionProperty , value ) ; } } public SubsetSelectionLists ( ) { InitializeComponent ( ) ; SubsetSelectiongrid.DataContext = this ; } private void selectionBtnClick ( object sender , RoutedEventArgs e ) { SubsetCollection.AddTheseItems ( SET.SelecctedItems ) } private void removeBtnClick ( object sender , RoutedEventArgs e ) { SUBSET.RemoveTheseItems ( SUBSET.SelectedItem ) ; } }
|
C # : Implementation of two abstract lists within a non-generic class ?
|
C#
|
I 've noticed that static methods seem more popular in F # than C # . In C # , you 'd always add an element to a collection by calling an instance method : But in F # there is usually an equivalent static method : And I 've seen the latter form quite often in samples . Both appear to me completely identical both semantically and functionally , but coming from a C # background , using the instance method feels more natural . Which is better style in F # and why ?
|
mySet.Add ( elem ) ; mySet.Add ( elem ) // ORSet.Add elem mySet
|
F # coding style - static vs instance methods
|
C#
|
Here 's a code reproducing the behavior I 'm expecting to get : The behavior is the same for any VS starting from VS2008 ( did not check on earlier versions ) .If you run it under debug ( using a standard debugging settings ) you 're not allowed to continue until you fix the code ( using the EnC ) . Hitting F5 will just rerun assertion due to [ DebuggerHidden ] and `` Unwind stack on unhandled exception '' setting combo ( setting is enabled by default ) . To fix the code , just replace the # 1 line with object x = `` '' , set the next statement to it and hit F5 again.Now , enable `` break when thrown '' for the ArgumentNullException and uncomment the lines marked with # 2.The behavior changes : you 're stopped on assertion again , but the stack does not unwind ( easy to check with CallStack window ) . F5 will continue from the place the exception was thrown.Ok , so ... now the question is : Is there any way to enable auto stack unwinding when breaking on handled exceptions ? Hidden VS option , existing extension or ( maybe ) API that can be used from my own extension ? UPD : To clarify the question : I want to break at the line with failed assertion , edit the code with edit and continue , set next statement to the fixed code and continue the execution.As it works if the exception is not caught down the stack.UPD2 As proposed by Hans Passant : Posted an suggestion on UserVoice . Feel free to vote : )
|
static void Main ( string [ ] args ) { // try // # 2 { string x = null ; // # 1 AssertNotNull ( x , nameof ( x ) ) ; } // catch ( ArgumentNullException ) { } // # 2 Console.WriteLine ( `` Passed . `` ) ; Console.ReadKey ( ) ; } [ DebuggerHidden ] public static void AssertNotNull < T > ( T arg , string argName ) where T : class { if ( arg == null ) throw new ArgumentNullException ( argName ) ; }
|
Visual Studio : edit-and-continue on handled exceptions ?
|
C#
|
After installing Visual Studio 2015 Update 1 on my machine I saw that some of my unit tests failed . After doing some investigation I was able to reduce the problem to this line of code : When hovering over the expression variable the results were different in the versions of Visual Studio : VS 2015 : VS 2015 Update 1 : The logic that was doing the comparison for the enums ( somewhere in ServiceStack.OrmLite code ) now acted differently which then eventually resulted in the enum not being recognized as an enum , resulting in the failing unit test.I was able to reproduce the problem using the following code : On VS 2015 it will go into the UnaryExpression path , and in VS 2015 Update 1 it will go into the ConstantExpression path.If you compile the solution on VS 2015 and then copy the compiled .exe file to a VS 2015 Update 1 system it will run the same as the VS 2015 version ( So also the UnaryExpression path ) . This suggests it is not JIT related but instead build related.My question would be if this is intended ? ( Since it could break existing code when simply recompiling the solution )
|
Expression < Func < GameObject , bool > > expression = t = > t.X == 0 & & t.Y == 0 & & t.GameObjectType == GameObjectType.WindMill ; class Program { static void Main ( string [ ] args ) { var gameObjects = new List < GameObject > { new GameObject { X = 0 , Y = 0 , GameObjectType = GameObjectType.WindMill } , new GameObject { X = 0 , Y = 1 , GameObjectType = GameObjectType.Pipe } , new GameObject { X = 0 , Y = 2 , GameObjectType = GameObjectType.Factory } } ; var gameObjectsQueryable = gameObjects.AsQueryable ( ) ; Expression < Func < GameObject , bool > > expression = t = > t.X == 0 & & t.Y == 0 & & t.GameObjectType == GameObjectType.WindMill ; var result = gameObjectsQueryable.Where ( expression ) ; var resultAsList = result.ToList ( ) ; foreach ( var item in resultAsList ) { Console.WriteLine ( item ) ; } //Obtain the t.GameObjectType == GameObjectType.WindMill part var binaryExpression = expression.Body as BinaryExpression ; var right = binaryExpression.Right ; var binaryExpression2 = right as BinaryExpression ; var right2 = binaryExpression2.Right ; if ( right2 is UnaryExpression ) { Console.WriteLine ( `` Found UnaryExpression ( This happens when the solution is build with VS2015 ) ... '' ) ; var right2Unary = binaryExpression2.Right as UnaryExpression ; var right2Constant = right2Unary.Operand as ConstantExpression ; CheckIfConsantIsAsExpected ( right2Constant ) ; } else { Console.WriteLine ( `` Found ConstantExpression ( This happens when the solution is build with VS2015 Update 1 ) ... '' ) ; var right2Constant = binaryExpression2.Right as ConstantExpression ; CheckIfConsantIsAsExpected ( right2Constant ) ; } Console.ReadKey ( ) ; } public static void CheckIfConsantIsAsExpected ( ConstantExpression expression ) { if ( expression.Value.Equals ( GameObjectType.WindMill ) ) { Console.WriteLine ( $ '' The value is the enum we expected : ) , : { expression.Value } '' ) ; } else { Console.WriteLine ( $ '' The value is not the enum we expected : ( , : { expression.Value } '' ) ; } } } public class GameObject { public int X { get ; set ; } public int Y { get ; set ; } public GameObjectType GameObjectType { get ; set ; } public override string ToString ( ) { return $ '' { X } , { Y } : { GameObjectType } '' ; } } public enum GameObjectType { WindMill = 100 , Pipe = 200 , Factory = 300 }
|
Expressions breaking code when compiled using VS2015 Update 1
|
C#
|
I 'm getting recurring word counts in StringBuilder ( sb ) with this code which i 've found on internet and according to writer it 's really consistent like Word 's word counter.This is my sample text : The green algae ( singular : green alga ) are a large , informal grouping of algae consisting of the Chlorophyte and Charophyte algae , which are now placed in separate Divisions . The land plants or Embryophytes ( higher plants ) are thought to have emerged from the Charophytes . [ 1 ] As the embryophytes are not algae , and are therefore excluded , green algae are a paraphyletic group . However , the clade that includes both green algae and embryophytes is monophyletic and is referred to as the clade Viridiplantae and as the kingdom Plantae . The green algae include unicellular and colonial flagellates , most with two flagella per cell , as well as various colonial , coccoid and filamentous forms , and macroscopic , multicellular seaweeds . In the Charales , the closest relatives of higher plants , full cellular differentiation of tissues occurs . There are about 8,000 species of green algae . [ 2 ] Many species live most of their lives as single cells , while other species form coenobia ( colonies ) , long filaments , or highly differentiated macroscopic seaweeds . A few other organisms rely on green algae to conduct photosynthesis for them . The chloroplasts in euglenids and chlorarachniophytes were acquired from ingested green algae , [ 1 ] and in the latter retain a nucleomorph ( vestigial nucleus ) . Green algae are also found symbiotically in the ciliate Paramecium , and in Hydra viridissima and in flatworms . Some species of green algae , particularly of genera Trebouxia of the class Trebouxiophyceae and Trentepohlia ( class Ulvophyceae ) , can be found in symbiotic associations with fungi to form lichens . In general the fungal species that partner in lichens can not live on their own , while the algal species is often found living in nature without the fungus . Trentepohlia is a filamentous green alga that can live independently on humid soil , rocks or tree bark or form the photosymbiont in lichens of the family Graphidaceae.With my sample text , I 'm getting green and algae words in the first lines as expected.Problem is , I do n't need only single words , I need word groups too . With this example text , I want green algae words too , together with green and algae words . And my optional problem is : I need to do it with high performance , because texts can be very long . As i researched it 's not high performance to use RegEx with this case , but I 'm not sure about if there is a second way to make it possible . Thanks in advance.UPDATE If you got what I 'm asking about , you do n't need to read these lines.As I see too many comments about my `` group '' definiton is not clear , I think I need to state my point with more detail and I wished write these lines on comments section but it 's a little narrow area for this update . Firstly , I know StackOverflow is not a coding service . I 'm trying to find the most used word groups in an article and trying to decide what 's article about , we can call it tag generator too . For this purpose I tried to find most used words and it was okay at the beginning . Then i realized it 's not a good way to decide about topic because I ca n't assume the article is about only first or second word . In my example I ca n't say this article is only about green or algae because they mean something together here , not alone . If i try this with an article about a three named celebrity like `` Helena Bonham Carter '' ( if I assume it 's written full name along article , not only surname ) , I want to take these words together not one by one . I 'm trying to achieve more clever algorithm which is guessing the topic in most accurate way and with one shot . I do n't want to limit the word count because article may be about `` United Nations Industrial Development Organization '' ( again I assume it 's now written like `` UNIDO '' in article ) . And I can achieve this by trying to get every word group starting from any index to the end of text with any length . Okay it 's not a good way really , especially with long texts but it 's not impossible right ? But i was looking for a better way to do this and I just asked about a better algorithm idea and best tool to use , I can write the code by myself . I hope I stated my goal clear finally .
|
StringBuilder wordBuffer = new StringBuilder ( ) ; int wordCount = 0 ; // 1 . Build the list of words used . Consider `` ' ( apostrophe ) and '- ' ( hyphen ) a word continuation character . Dictionary < string , int > wordList = new Dictionary < string , int > ( ) ; foreach ( char c in sb.ToString ( ) ) { if ( char.IsLetter ( c ) || c == '\ '' || c == '- ' ) { wordBuffer.Append ( char.ToLower ( c ) ) ; } else { if ( wordBuffer.Length > 3 ) { int count = 0 ; string word = wordBuffer.ToString ( ) ; wordList.TryGetValue ( word , out count ) ; wordList [ word ] = ++count ; wordBuffer.Clear ( ) ; wordCount++ ; } } }
|
How to find recurring word groups in text with C # ?
|
C#
|
I 'm new to LINQ . I understand it 's purpose . But I ca n't quite figure it out . I have an XML set that looks like the following : I have loaded this XML into an XDocument as such : Now , I 'm trying to get the results into POCO format . In an effort to do this , I 'm currently using : How do I get a collection of Result elements via LINQ ? I 'm particularly confused about navigating the XML structure at this point in my code.Thank you !
|
< Results > < Result > < ID > 1 < /ID > < Name > John Smith < /Name > < EmailAddress > john @ example.com < /EmailAddress > < /Result > < Result > < ID > 2 < /ID > < Name > Bill Young < /Name > < EmailAddress > bill @ example.com < /EmailAddress > < /Result > < /Results > string xmlText = GetXML ( ) ; XDocument xml = XDocument.Parse ( xmlText ) ; var objects = from results in xml.Descendants ( `` Results '' ) select new Results // I 'm stuck
|
LINQ to XML via C #
|
C#
|
This is a bit difficult to describe , but I need to mock/stub a method to return an instance of T based on inputs.The message signature looks like : Here is the code within the SUT : Here is what the setup should look like in my unit test : This does n't compile because x is an Action.Is what I 'm trying to do possible ?
|
T DoSomething < T > ( Action < T > action ) ; var myEvent = _service.DoSomething < IMyEvent > ( y = > { y.Property1 = localProperty1 ; y.Property2 = localProperty2 ; } ) ; service.Setup ( x = > x.DoSomething < IMyEvent > ( It.IsAny < Action < IMyEvent > > ( ) ) ) .Returns ( ( ( Action < IMyEvent > x ) = > { return new MyEventFake //derives from IMyEvent { Property1 = x.Property1 , Property2 = x.Property2 } ; } ) ) ;
|
Mocking Action < T > to Return Value Based on Parameters
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 6