text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : I am seeing something very strange , which I can not explain . I am guessing some edge case of C # which I am not familiar with , or a bug in the runtime / emitter ? I have the following method : While testing my app , I see it is misbehaving - it is returning true for objects I know do not exist in my db . So I stopped at the method and in Immediate , I ran the following : GetObject is defined like so : Interestingly , when casting the expression to object , the comparison is evaluated correctly : There is no equality operator overriding.Edit : It turns out there is an operator overload , which was incorrect . But then why would the equality evaluate correctly in the internal method generic GetObject , where rv is of type HistoryMessage in this case.What is going on here ? <code> public static bool HistoryMessageExists ( DBContext context , string id ) { return null ! = context.GetObject < HistoryMessage > ( id ) ; } context.GetObject < HistoryMessage > ( id ) nullnull == context.GetObject < HistoryMessage > ( id ) truenull ! = context.GetObject < HistoryMessage > ( id ) true public T GetObject < T > ( object pk ) where T : DBObject , new ( ) { T rv = Connection.Get < T > ( pk ) ; if ( rv ! = null ) { rv.AttachToContext ( this ) ; rv.IsInserted = true ; } return rv ; } null == ( object ) context.GetObject < HistoryMessage > ( id ) truenull ! = ( object ) context.GetObject < HistoryMessage > ( id ) false public class HistoryMessage : EquatableIdentifiableObject { public static bool HistoryMessageExists ( DBContext context , string id ) { var rv = context.GetObject < HistoryMessage > ( id ) ; bool b = rv ! = null ; return b ; } public static void AddHistoryMessage ( DBContext context , string id ) { context.InsertObject ( new HistoryMessage { Id = id } ) ; } } public abstract partial class EquatableIdentifiableObject : DBObject , IObservableObject { public event PropertyChangedEventHandler PropertyChanged ; [ PrimaryKey ] public string Id { get ; set ; } // ... } public abstract partial class EquatableIdentifiableObject { // ... public static bool operator == ( EquatableIdentifiableObject self , EquatableIdentifiableObject other ) { if ( ReferenceEquals ( self , null ) ) { return ReferenceEquals ( other , null ) ; } return self.Equals ( other ) ; } public static bool operator ! = ( EquatableIdentifiableObject self , EquatableIdentifiableObject other ) { if ( ReferenceEquals ( self , null ) ) { return ! ReferenceEquals ( other , null ) ; } return ! self.Equals ( other ) ; } } public abstract class DBObject { [ Ignore ] protected DBContext Context { get ; set ; } [ Ignore ] internal bool IsInserted { get ; set ; } // ... } | Comparison to null evaluates to true for both expr == null and expr ! = null |
C_sharp : The following code compiles in C # 4.0 : How does the compiler know which overload you 're calling ? And if it ca n't , why does the code still compile ? <code> void Foo ( params string [ ] parameters ) { } void Foo ( string firstParameter , params string [ ] parameters ) { } | More or less equal overloads |
C_sharp : In the Business Logic Layer of an Entity Framework-based application , all methods acting on DB should ( as I 've heard ) be included within : Of course , for my own convenience often times those methods use each other , for the sake of not repeating myself . The risk I see here is the following : I does n't look good to me , when the container fc2 is created , while fc is still open and has not been saved yet . So this leads to my question number one : Is having multiple containers open at the same time and acting on them carelessly an acceptable practice ? I came to a conclusion , that I could write a simple guard-styled object like this : Now the usage would be as following : When the HelperMethod is called by MainMethod , the GlobalContainer is already created , and its used by both methods , so there is no conflict . Moreover , HelperMethod can be also used separately , and then it creates its own container.However , this seems like a massive overkill to me ; so : Has this problem been already solved in form of some class ( IoC ? ) or at least some nice design pattern ? Thank you . <code> using ( FunkyContainer fc = new FunkyContainer ( ) ) { // do the thing fc.SaveChanges ( ) ; } public void MainMethod ( ) { using ( FunkyContainer fc = new FunkyContainer ( ) ) { // perform some operations on fc // modify a few objects downloaded from DB int x = HelperMethod ( ) ; // act on fc again fc.SaveChanges ( ) ; } } public int HelperMethod ( ) { using ( FunkyContainer fc2 = new FunkyContainer ( ) ) { // act on fc2 an then : fc2.SaveChanges ( ) ; return 42 ; } } public sealed class FunkyContainerAccessGuard : IDisposable { private static FunkyContainer GlobalContainer { get ; private set ; } public FunkyContainer Container // simply a non-static adapter for syntactic convenience { get { return GlobalContainer ; } } private bool IsRootOfHierarchy { get ; set ; } public FunkyContainerAccessGuard ( ) { IsRootOfHierarchy = ( GlobalContainer == null ) ; if ( IsRootOfHierarchy ) GlobalContainer = new FunkyContainer ( ) ; } public void Dispose ( ) { if ( IsRootOfHierarchy ) { GlobalContainer.Dispose ( ) ; GlobalContainer = null ; } } } public void MainMethod ( ) { using ( FunkyContainerAccessGuard guard = new FunkyContainerAccessGuard ( ) ) { FunkyContainer fc = guard.Container ; // do anything with fc int x = HelperMethod ( ) ; fc.SaveChanges ( ) ; } } public int HelperMethod ( ) { using ( FunkyContainerAccessGuard guard = new FunkyContainerAccessGuard ( ) ) { FunkyContainer fc2 = guard.Container ; // do anything with fc2 fc2.SaveChanges ( ) ; } } | Entity Framework - concurrent use of containers |
C_sharp : I want to use using statement purely for scope management . Can I omit holding an explicit reference to the underlying object that implements IDisposable ? For example , giving this declaraions : Can I do the following : Is TransactionGuard instance alive during using statement ? <code> class ITransactionScope : IDisposable { } class TransactionGuard : ITransactionScope { ... } class DbContext { public IDisposable ITransactionScope ( ) { return new TransactionGuard ( ) ; } } void main ( ) { var dbContext = new DbContext ( ) ; using ( dbContext.TransactionScope ( ) ) { // the guard is not accessed here } } | Can I use using statement with RHV ( right hand value ) ? |
C_sharp : How can i make filter and add/update third , fourth level child of a mongodb document using C # .I can add/Update till second level but not further . Please provide me a solution or any kind reference from where can get help . Is there any other way to do it except builders..Elemmatch . Here is my classes and code : <code> namespace CrudWithMultilvelNestedDoc { public class Channel { [ BsonId ] [ BsonRepresentation ( BsonType.String ) ] public string Id { get ; set ; } public string Name { get ; set ; } public Episode [ ] Episodes { get ; set ; } } public class Episode { [ BsonId ] [ BsonRepresentation ( BsonType.String ) ] public string Id { get ; set ; } public string Name { get ; set ; } public Track [ ] Tracks { get ; set ; } } public class Track { [ BsonId ] [ BsonRepresentation ( BsonType.String ) ] public string Id { get ; set ; } public string Name { get ; set ; } public Like [ ] Likes { get ; set ; } } public class Like { [ BsonId ] [ BsonRepresentation ( BsonType.String ) ] public string Id { get ; set ; } public string Name { get ; set ; } } } //First Method //var filter = Builders < Channel > .Filter.And ( Builders < Channel > // .Filter.Where ( x = > x.Id == `` 5e4606e6ae7b090688671416 '' ) , // OR & // Builders < Channel > .Filter.ElemMatch ( e = > e.Episodes , Builders < Episode > // .Filter.Eq ( e = > e.Id , `` 5e460851d29c1b3df4d27b7d '' ) ) ) ; //Second Method //var filter = Builders < Channel > .Filter.Eq ( e = > e.Id , `` 5e4606e6ae7b090688671416 '' ) // & Builders < Channel > .Filter.ElemMatch ( e = > e.Episodes , Builders < Episode > .Filter.Eq ( e = > e.Id , `` 5e46071d385a672b0cea0f86 '' ) ) ; //Third Method var filter = channelFilter.ElemMatch ( e = > e.Episodes , episodeFilter.ElemMatch ( e= > e.Tracks , trackFilter.Eq ( e = > e.Id , `` 5e460dbe2bc5e70c9cfeac21 '' ) ) ) ; var data = collection.Find ( filter ) ; //Update Filter var update = Builders < Channel > .Update.Push ( `` Episodes [ -1 ] .Tracks [ -1 ] .Likes '' , like ) ; var result = collection.UpdateOne ( filter , update ) ; //Data { `` _id '' : '' 5e4606e6ae7b090688671416 '' , '' Name '' : '' Channel 1 '' , '' Episodes '' : [ { `` _id '' : '' 5e46071d385a672b0cea0f86 '' , '' Name '' : '' Episode 1 '' , '' Tracks '' : [ { `` _id '' : '' 5e460dbe2bc5e70c9cfeac21 '' , '' Name '' : '' Trak 1 '' , '' Likes '' : [ ] } , { `` _id '' : '' 5e4612d60747a2121870c815 '' , '' Name '' : '' Trak 2 '' , '' Likes '' : [ ] } ] } , { `` _id '' : '' 5e460851d29c1b3df4d27b7d '' , '' Name '' : '' Episode 2 '' , '' Tracks '' : [ { `` _id '' : '' 5e460e307ca6843758ce814e '' , '' Name '' : '' Trak 1 '' , '' Likes '' : [ ] } ] } ] } | Get and Add/Update multilevel embedded/nested MongoDB document using C # |
C_sharp : When I executing this code the output is : When I separate this 2 scopes in methods like this : the output is : EditedI also try this way : and the output is : **Environment which I used is MacOS and .net core 2.2 ( Rider ) **I expect to have same output in all cases , but the output is different . As we know interning is that all strings you hardcoded are put into assembly and reused globally in the whole application to reuse same memory space . But in case of this code we see that hardcoded strings reused only in function scope and not in global scope.Is this a .NET Core bug or this have explanation ? <code> class Program { static void Main ( string [ ] args ) { //scope 1 { string x = `` shark '' ; string y = x.Substring ( 0 ) ; unsafe { fixed ( char* c = y ) { c [ 4 ] = ' p ' ; } } Console.WriteLine ( x ) ; } //scope 2 { string x = `` shark '' ; //Why output in this line `` sharp '' and not `` shark '' ? Console.WriteLine ( x ) ; } } } sharpsharp class Program { static void Main ( string [ ] args ) { func1 ( ) ; func2 ( ) ; } private static void func2 ( ) { { string x = `` shark '' ; Console.WriteLine ( x ) ; } } private static void func1 ( ) { { string x = `` shark '' ; string y = x.Substring ( 0 ) ; unsafe { fixed ( char* c = y ) { c [ 4 ] = ' p ' ; } } Console.WriteLine ( x ) ; } } } sharpshark class Program { static void Main ( string [ ] args ) { { string x = `` shark '' ; string y = x.Substring ( 0 ) ; unsafe { fixed ( char* c = y ) { c [ 4 ] = ' p ' ; } } Console.WriteLine ( x ) ; } void Test ( ) { { string x = `` shark '' ; Console.WriteLine ( x ) ; } } Test ( ) ; } } sharp shark | Why C # using same memory address in this case ? |
C_sharp : I have defined models based on the tables in the database . Now there are some models whose data hardly changes . For example , the categories of the products that an e-comm site sells , the cities in which it ships the products etc . These do n't change often and thus to avoid hitting the db , these are currently saved as static variables . The question is where in code should these static variables be located . Currently , in ProductCategory class ( which is also the model representation ) a static List is defined which if empty calls the db and loads the Product Categories . Similarly , the City class has a similar static List and so on . These static Lists are then used across the application . I was thinking of creating a class called StaticData and then keeping all the static Lists within this class . That is now instead of I shall have Which do you think is a better approach ? I am also aiming for testability and decoupled code . Also , is there a better way to achieve these ? How do you do something similar in your code ? <code> ProductCategory.AllCategories.Find ( p = > p.Id = 2 ) StaticData.AllProductCategories.Find ( p = > p.Id = 2 ) | Where in code should one keep data that does n't change ? |
C_sharp : I 'm working on an application where you 're able to subscribe to a newsletter and choose which categories you want to subscribe to . There 's two different sets of categories : cities and categories.Upon sending emails ( which is a scheduled tast ) , I have to look at which cities and which categories a subscriber has subscribed to , before sending the email . I.e. , if I have subscribed to `` London '' and `` Manchester '' as my cities of choice and have chosen `` Food '' , `` Cloth '' and `` Electronics '' as my categories , I will only get the newsletters that relates to these.The structure is as follows : On every newsitem in Umbraco CMS there is a commaseparated string of cities and categories ( effectively , these are stored as node ids since cities and categories are nodes in Umbraco aswell ) When I subscribe to one or more city and one or more category , I store the city and category nodeids in the database in custom tables . My relational mapping looks like this : And the whole structure looks like this : To me , this seems like two sets of 1 - 1..* relations ( one subscriber to one or many cities and one subscriber to one or many categories ) To find which emails to send who which subscriber , my code looks like this : While this works , I 'm a bit concerned about performance when a certain amount of subscribers is reached since we 're into three nested foreach loops . Also , remembering my old teachers preaches : `` for every for loop there is a better structure '' So , I would like your oppinion on the above solution , is there anything that can be improved here with the given structure ? And will it cause performance problems over time ? Any help/hint is greatly appreciated ! : - ) Thanks in advance.SolutionSo after a few good hours of debugging and fumblin ' around I finally came up with something that works ( initially , it looked like my original code worked , but it did n't ) Sadly , I could n't get it to work with any LINQ queries I tried , so I went back to the `` ol ' school ' way of iterating ; - ) The final algorithm looks like this : <code> private bool shouldBeAdded = false ; // Dictionary containing the subscribers e-mail address and a list of news nodes which should be sentDictionary < string , List < Node > > result = new Dictionary < string , List < Node > > ( ) ; foreach ( var subscriber in subscribers ) { // List of Umbraco CMS nodes to store which nodes the html should come from List < Node > nodesToSend = new List < Node > nodesToSend ( ) ; // Loop through the news foreach ( var newsItem in news ) { // The news item has a comma-separated string of related cities foreach ( string cityNodeId in newsItem.GetProperty ( `` cities '' ) .Value.Split ( ' , ' ) ) { // Check if the subscriber has subscribed to the city if ( subscriber.CityNodeIds.Contains ( Convert.ToInt32 ( cityNodeId ) ) ) { shouldBeAdded = true ; } } // The news item has a comma-separated string of related categories foreach ( string categoryNodeId in newsItem.GetProperty ( `` categories '' ) .Value.Split ( ' , ' ) ) { // Check if the subscriber has subscribed to the category if ( subscriber.CategoryNodeIds.Contains ( Convert.ToInt32 ( categoryNodeId ) ) ) { shouldBeAdded = true ; } } } // Store in list if ( shouldBeAdded ) { nodesToSend.Add ( newsItem ) ; } // Add it to the dictionary if ( nodesToSend.Count > 0 ) { result.Add ( subscriber.Email , nodesToSend ) ; } } // Ensure that we process the request only if there are any subscribers to send mails toif ( result.Count > 0 ) { foreach ( var res in result ) { // Finally , create/merge the markup for the newsletter and send it as an email . } } private bool shouldBeAdded = false ; // Dictionary containing the subscribers e-mail address and a list of news nodes which should be sentDictionary < string , List < Node > > result = new Dictionary < string , List < Node > > ( ) ; foreach ( var subscriber in subscribers ) { // List of Umbraco CMS nodes to store which nodes the html should come from List < Node > nodesToSend = new List < Node > nodesToSend ( ) ; // Loop through the news foreach ( var newsItem in news ) { foreach ( string cityNodeId in newsItem.GetProperty ( `` cities '' ) .Value.Split ( ' , ' ) ) { // Check if the subscriber has subscribed to the city if ( subscriber.CityNodeIds.Contains ( Convert.ToInt32 ( cityNodeId ) ) ) { // If a city matches , we have a base case nodesToSend.Add ( newsItem ) ; } } foreach ( string categoryNodeId in newsItem.GetProperty ( `` categories '' ) .Value.Split ( ' , ' ) ) { // Check if the subscriber has subscribed to the category if ( subscriber.CategoryNodeIds.Contains ( Convert.ToInt32 ( categoryNodeId ) ) ) { shouldBeAdded = true ; // News item matched and will be sent . Stop the loop . break ; } else { shouldBeAdded = false ; } } if ( ! shouldBeAdded ) { // The news item did not match both a city and a category and should not be sent nodesToSend.Remove ( newsItem ) ; } } if ( nodesToSend.Count > 0 ) { result.Add ( subscriber.Email , nodesToSend ) ; } } // Ensure that we process the request only if there are any subscribers to send mails toif ( result.Count > 0 ) { foreach ( var res in result ) { // StringBuilder to build markup for newsletter StringBuilder sb = new StringBuilder ( ) ; // Build markup foreach ( var newsItem in res.Value ) { // build the markup here } // Email logic here } } | Optimizing an algorithm and/or structure in C # |
C_sharp : Consider the following example program : The first one works as expected — the conversion to MyDelegateType succeeds . The second one , however , throws a RuntimeBinderException with the error message : Can not implicitly convert type 'System.Func < int , string > ' to 'MyDelegateType'Is there anything in the C # specification that allows for this behaviour , or is this a bug in Microsoft ’ s C # compiler ? <code> using System ; public delegate string MyDelegateType ( int integer ) ; partial class Program { static string MyMethod ( int integer ) { return integer.ToString ( ) ; } static void Main ( ) { Func < int , string > func = MyMethod ; // Scenario 1 : works var newDelegate1 = new MyDelegateType ( func ) ; newDelegate1 ( 47 ) ; // Scenario 2 : doesn ’ t work dynamic dyn = func ; var newDelegate2 = new MyDelegateType ( dyn ) ; newDelegate2 ( 47 ) ; } } | Should an expression of type ‘ dynamic ’ behave the same way at run-time as a non-dynamic one of the same run-type time ? |
C_sharp : Let see at this class : why I can access private field ? Can I use this feature or may be it is bad practice ? <code> public class Cluster { private List < Point > points ; //private field public float ComputeDistanceToOtherClusterCLINK ( Cluster cluster ) { var max = 0f ; foreach ( var point in cluster.points ) // here points field are accessible { ... ... . } return max ; } } | Why private field of the class are visible when passing same type as a parameter of method C # ? |
C_sharp : In the following code the Scrollbar control does not display but the Slider control does . If I change the Scrollbar control to a Slider control simply by changing Scrollbar to Slider it works perfectly , however I would prefer the look of the scrollbar control over the slider for the application.I 'm manually drawing a large 1000 cell x 1000 cell grid using Win2D into the animated canvas , but only displaying the part scrolled into by using the scrollbar ( slider ) positions.Works perfectly when using the Slider controls . <code> < Pagex : Class= '' TrappedEditor.MainPage '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' using : TrappedEditor '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : canvas= '' using : Microsoft.Graphics.Canvas.UI.Xaml '' Unloaded= '' Page_Unloaded '' mc : Ignorable= '' d '' > < Grid Background= '' { ThemeResource ApplicationPageBackgroundThemeBrush } '' SizeChanged= '' Grid_SizeChanged '' > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' 1* '' / > < ColumnDefinition Width= '' 50 '' / > < /Grid.ColumnDefinitions > < Grid.RowDefinitions > < RowDefinition Height= '' * '' / > < RowDefinition Height= '' 50 '' / > < /Grid.RowDefinitions > < ScrollBar x : Name= '' scrollBarVertical '' Visibility= '' Visible '' Grid.Row= '' 0 '' Grid.Column= '' 1 '' ValueChanged= '' scrollBarVertical_ValueChanged '' Orientation= '' Vertical '' Minimum= '' 0 '' Maximum= '' 1000 '' / > < Slider x : Name= '' scrollBarHorizontal '' Grid.Column= '' 0 '' Grid.ColumnSpan= '' 2 '' Grid.Row= '' 1 '' Orientation= '' Horizontal '' ValueChanged= '' scrollBarHorizontal_ValueChanged '' Minimum= '' 0 '' Maximum= '' 1000 '' / > < canvas : CanvasAnimatedControl Grid.Row= '' 0 '' Grid.Column= '' 0 '' x : Name= '' canvas '' Draw= '' canvas_Draw '' CreateResources= '' canvas_CreateResources '' / > < /Grid > | XAML UWA Scrollbar not showing |
C_sharp : Is there a better way to do these assignments with LINQ ? <code> IEnumerable < SideBarUnit > sulist1 = newlist.Where ( c = > c.StatusID == EmergencyCV.ID ) ; foreach ( SideBarUnit su in sulist1 ) su.color = `` Red '' ; | Is there a way to set values in LINQ ? |
C_sharp : More specifically , why does this work : but this not ? In the latter case , I get a compiler warning saying : The given expression is never of the provided type . I can understand that , as changeRow is a ChangeSetEntry not a RouteStage , so why does it work inside the foreach block ? This is in my override of the Submit method in an RIA Services DomainService . RouteStage is an entity I have defined to be returned by the DomainService . <code> foreach ( ChangeSetEntry changeRow in changeSet.ChangeSetEntries ) if ( changeRow is RouteStage ) { ... } ChangeSetEntry changeRow = changeSet.ChangeSetEntries [ 0 ] ; if ( changeRow is RouteStage ) { ... } | How does the `` is '' keyword work ? |
C_sharp : Maybe a stupid question for C # , WPF , .NET 4.0 : If I do a new on a window derived class and do n't call ShowDialog on this window , my program does n't shut down anymore on close.Example : Why is this so ? I do n't want to show the window , I just want to use this object for some purpose . So what do I have to do in order to allow my program to shut down afterwards ? <code> Window d = new Window ( ) ; //d.ShowDialog ( ) ; | Program does n't stop after new Window |
C_sharp : I 'm doing an entity update from a Postback in MVC : The update method looks like this : The weird thing is first time I run it it usually works fine ; if i do a second post back it does not work and fails on an EntityValidation error of a foreign key ; however examining the entity the foreign key looks fine and is untouched.Do I need to somehow synchronize the Context somewhere ? I 've been trying to find the differences in when it succeeds or when it does not succeed.I 'm using Injection for the repositories : -- update : In the ControlChartMap we have the following : <code> ControlChartPeriod period = _controlChartPeriodService.Get ( request.PeriodId ) ; if ( period ! = null ) { SerializableStringDictionary dict = new SerializableStringDictionary ( ) ; dict.Add ( `` lambda '' , request.Lambda.ToString ( ) ) ; dict.Add ( `` h '' , request.h.ToString ( ) ) ; dict.Add ( `` k '' , request.k.ToString ( ) ) ; period.Parameters = dict.ToXmlString ( ) ; // ToDo : fails on save every now and then when one of the values changes ; fails on Foreign Key being null try { _controlChartPeriodService.Update ( period , request.PeriodId ) ; return Ok ( request ) ; } public TObject Update ( TObject updated , TKey key ) { if ( updated == null ) return null ; TObject existing = _context.Set < TObject > ( ) .Find ( key ) ; if ( existing ! = null ) { _context.Entry ( existing ) .CurrentValues.SetValues ( updated ) ; _context.SaveChanges ( ) ; } return existing ; } public TObject Get ( TKey id ) { return _context.Set < TObject > ( ) .Find ( id ) ; } public void ConfigureServices ( IServiceCollection services ) { services.AddScoped ( ( _ ) = > new DataContext ( ConfigSettings.Database.ConnectionString ) ) ; services.AddScoped < ControlChartPeriodService , ControlChartPeriodService > ( ) ; } [ Key ] [ DatabaseGenerated ( DatabaseGeneratedOption.Identity ) ] public int Id { get ; set ; } public DateTime StartDate { get ; set ; } public DateTime ? EndDate { get ; set ; } public virtual ICollection < ControlChartPoint > ControlChartPoints { get ; set ; } [ Required ] public virtual ControlChart ControlChart { get ; set ; } public string Parameters { get ; set ; } HasMany ( x = > x.Periods ) .WithRequired ( c = > c.ControlChart ) ; | EntityFramework update fails randomly on SaveChanges / ASP.NET MVC / postbacks |
C_sharp : sourcehttp : //technet.microsoft.com/en-us/library/ms162234 % 28SQL.100 % 29.aspxcodewhy to use default ( Server ) , ? -even if its like server asd = new asd ( ) ; it will still connect to the default instance ! why to use default ( linkedserver ) -whats the point ? we still specify the srv and provider and product ! <code> //Connect to the local , default instance of SQL Server . { Server srv = default ( Server ) ; srv = new Server ( ) ; //Create a linked server . LinkedServer lsrv = default ( LinkedServer ) ; lsrv = new LinkedServer ( srv , `` OLEDBSRV '' ) ; //When the product name is SQL Server the remaining properties are //not required to be set . lsrv.ProductName = `` SQL Server '' ; lsrv.Create ( ) ; } | please explain the use of `` default ( ) '' in this code |
C_sharp : What I mean is ... get the time , run the code , get the time , compare the time and get the seconds out : am I doing this right ? <code> DateTime timestamp = DateTime.Now ; // ... do the code ... DateTime endstamp = DateTime.Now ; string results = ( ( endstamp.ticks - timestamp.ticks ) /10000000 ) .ToString ( ) ; | Is this a good way of checking the amount of time it took to run some code in C # ? |
C_sharp : I have some generic interfaces and classes that implement those intefaces like so : I know it seems like a very messy way of doing things , but I sort of need it for my application . My question is how come I ca n't do this : A < X < Y > , Y > variable = new B < X1 < Y1 > , Y1 > ( ) ; <code> interface A < M , N > where M : X < N > where N : Y { } class B < M , N > : A < M , N > where M : X < N > where N : Y { } interface X < M > where M : Y { } interface Y { } class X1 < M > : X < M > where M : Y { } class Y1 : Y { } | C # casting with generics that use interfaces |
C_sharp : I 'm working on a C # dll bind to UDK , in which you have to return a unsigned 32 bit integer for bool values - hence 0 is false , anything greater is true . The UDK gets the value and converts it to either true or false ... I was doing some code and found this : gave me the error of : `` Error , Can not implicitly convert type 'int ' to 'uint ' . An explicit conversion exists ( are you missing a cast ? ) '' While I understand the error , I didnt have this issue before doing From the way it looks like C # 's issue with string typecasting , where if you have this : The first console.writeline will give an error because C # wo n't autotype cast to a stringI understand that there are logical reasons behind these errors ( as they occur in these situations ) , but is there a fix for this other than doing Convert.ToUInt32 ( 1 ) and Convert.ToUInt32 ( 0 ) ? ( I 'm hoping for a fix akin to how you can go 0.f for floats , but for unsigned intergers ) <code> [ DllExport ( `` CheckCaps '' , CallingConvention = CallingConvention.StdCall ) ] public static UInt32 CheckCaps ( ) { return ( Console.CapsLock ? 1 : 0 ) ; } if ( File.Exists ( filepath ) ) return 1 ; else return 0 ; int example = 5 ; Console.Writeline ( example ) ; Console.Writeline ( example + `` '' ) ; | C # returning UInt32 vs Int32 - C # thinking 0 and 1 are Int32 |
C_sharp : Consider the following code.Calling Task.Run and then Result in the static initializer causes the program to permanently freeze . Why ? <code> static class X { public static int Value = Task.Run ( ( ) = > 0 ) .Result ; } class Program { static void Main ( string [ ] args ) { var value = X.Value ; } } | Task.Run in Static Initializer |
C_sharp : Here 's my situation : When I run my code as described above the output is simply `` Fuzzy Container '' . What am i missing here ? Is there a better way to get the desired results ? <code> interface Icontainer { string name ( ) ; } abstract class fuzzyContainer : Icontainer { string name ( ) { return `` Fuzzy Container '' ; } } class specialContainer : fuzzyContainer { string name ( ) { return base.name ( ) + `` Special Container '' ; } } Icontainer cont = new SpecialContainer ( ) ; cont.name ( ) ; // I expected `` Fuzzy Container Special Container '' as the output . | Why is the base class being called ? |
C_sharp : I am having a problem when trying to concatenate multiple videos together . Whenever I combine 2 or more videos , the audio is played at double speed , while the video plays out normally.Below is the code . Am I missing something ? I get the same results when testing but cloning a single video or selecting multiple videos.I have compared to the code example here ( I am not trimming ) . <code> public static IAsyncOperation < IStorageFile > ConcatenateVideoRT ( [ ReadOnlyArray ] IStorageFile [ ] videoFiles , IStorageFolder outputFolder , string outputfileName ) { return Task.Run < IStorageFile > ( async ( ) = > { IStorageFile _OutputFile = await outputFolder.CreateFileAsync ( outputfileName , CreationCollisionOption.GenerateUniqueName ) ; MediaComposition _MediaComposition = new MediaComposition ( ) ; foreach ( IStorageFile _VideoFile in videoFiles ) { MediaClip _MediaClip = await MediaClip.CreateFromFileAsync ( _VideoFile ) ; _MediaComposition.Clips.Add ( _MediaClip ) ; _MediaComposition.Clips.Add ( _MediaClip.Clone ( ) ) ; } TranscodeFailureReason _TranscodeFailureReason = await _MediaComposition.RenderToFileAsync ( _OutputFile ) ; if ( _TranscodeFailureReason ! = TranscodeFailureReason.None ) { throw new Exception ( `` Video Concatenation Failed : `` + _TranscodeFailureReason.ToString ( ) ) ; } return _OutputFile ; } ) .AsAsyncOperation ( ) ; } | Windows Phone 8.1 MediaComposition - Audio Too Fast When Stitching Videos |
C_sharp : I was translating some C++ to C # code and I saw the below definiton : First , what does this single quoted constant mean ? Do I make it a string constant in c # ? Second , this constant is assigned as value to a uint variable in C++ . How does that work ? <code> # define x 'liaM ' uint m = x ; | Single quoted string to uint in c # |
C_sharp : I do n't understand why my output is not how I think it should be . I think that it should be Dog barks line break Cat meows . But there is nothing there.Code : I have tried to go through the c # programming guide on MSDN but I find it very difficult to understand some of the examples on there . If someone could link to a good `` inheritance for dummies '' site , it would be much appreciated . <code> namespace ConsoleApplication2 { class Program { static void Main ( string [ ] args ) { Pets pet1 = new Dog ( ) ; Pets pet2 = new Cat ( ) ; pet1.Say ( ) ; pet2.Say ( ) ; Console.ReadKey ( ) ; } } class Pets { public void Say ( ) { } } class Dog : Pets { new public void Say ( ) { Console.WriteLine ( `` Dog barks . `` ) ; } } class Cat : Pets { new public void Say ( ) { Console.WriteLine ( `` Cat meows . `` ) ; } } } | novice inheritance question |
C_sharp : I have this function : but I 'm wondering if there 's an easier way to write it , such as : I know I could write an extension method to handle this , I 'm just curious if there 's already something out there or if there 's a better way to write it . <code> public bool IsValidProduct ( int productTypeId ) { bool isValid = false ; if ( productTypeId == 10 || productTypeId == 11 || productTypeId == 12 ) { isValid = true ; } return isValid ; } public bool IsValidProduct ( int productTypeId ) { bool isValid = false ; if ( productTypeId.In ( 10,11,12 ) ) { isValid = true ; } return isValid ; } | Something similar to sql IN statement within .NET framework ? |
C_sharp : I need to extract all class variables . But my code returns all variables , including variables declared in methods ( locals ) . For example : I need to get only x and y but I get x , y , and z.My code so far : <code> class MyClass { private int x ; private int y ; public void MyMethod ( ) { int z = 0 ; } } SyntaxTree tree = CSharpSyntaxTree.ParseText ( content ) ; IEnumerable < SyntaxNode > nodes = ( ( CompilationUnitSyntax ) tree.GetRoot ( ) ) .DescendantNodes ( ) ; List < ClassDeclarationSyntax > classDeclarationList = nodes .OfType < ClassDeclarationSyntax > ( ) .ToList ( ) ; classDeclarationList.ForEach ( cls = > { List < MemberDeclarationSyntax > memberDeclarationSyntax = cls.Members.ToList ( ) ; memberDeclarationSyntax.ForEach ( x = > { //contains all variables List < VariableDeclarationSyntax > variables = x.DescendantNodes ( ) .OfType < VariableDeclarationSyntax > ( ) .ToList ( ) ; } ) ; } ) ; | How do I retrieve all ( and only ) class variables ? |
C_sharp : I have 6 buttons on my GUI . The visibility of the buttons can be configured via checkboxes . Checking the checkbox and saving means the correpsonding button should be shown . I am wondering if it is somehow possible to have one TinyInt column in the database which represents the visibility of all 6 buttons.I created an enum for the buttons , it looks like that : Now I am wondering how to say that for example only button1 , button5 and button6 are checked using this one column . Possible at all ? Thanks : - ) <code> public enum MyButtons { Button1 = 1 , Button2 = 2 , Button3 = 3 , Button4 = 4 , Button5 = 5 , Button6 = 6 } | Use TinyInt to hide/show controls ? |
C_sharp : I have a simple UIElement that I would like to turn into a MarkupExtension : It works really well in most cases . The only exception is in lists : In Collection Syntax , it says : If the type of a property is a collection , then the inferred collection type does not need to be specified in the markup as an object element . Instead , the elements that are intended to become the items in the collection are specified as one or more child elements of the property element . Each such item is evaluated to an object during loading and added to the collection by calling the Add method of the implied collection.However , xaml interprets the syntax above as MyList = PinkRectangle rather than MyList.Add ( PinkRectangle ) But if I put in a Grid first , it calls MyList.Add ( ) for both correctly . What is the correct syntax for telling xaml to call MyList.Add ( ) for both situations ? Here 's the rest of the code to create a Minimal , Reproducable Example : - Edit -I found that if I removed the set { } from MyList , the problem went away because xaml no longer thought there was a setter , but ultimately I need to be able to set MyList ... . <code> [ MarkupExtensionReturnType ( typeof ( FrameworkElement ) ) ] public class PinkRectangle : MarkupExtension { public override object ProvideValue ( IServiceProvider serviceProvider ) { return new Rectangle { Height = 100 , Width = 300 , Fill = Brushes.HotPink } ; } } < local : WindowEx x : Class= '' WpfApp1.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.winfx/200x/xaml '' xmlns : local= '' clr-namespace : WpfApp1 '' DataContext= '' { Binding RelativeSource= { RelativeSource Self } } '' MyProperty= '' { Binding local : PinkRectangle } '' > < ! -- this one works. -- > < local : WindowsEx.MyList > < ! -- < Grid/ > If I comment this line in , it works -- > < local : PinkRectangle/ > < /local : WindowsEx.MyList > < ContentPresenter Content= '' { Binding MyProperty } '' / > < /local : WindowEx > namespace WpfApp1 { // I use this class to directly set a few unusual properties directly in xaml . public class WindowEx : Window { //If I remove the set property , the error goes away , but I need the setter . public ObservableCollection < object > MyList { get ; set ; } = new ObservableCollection ( ) ; public object MyProperty { get { return GetValue ( MyPropertyProperty ) ; } set { SetValue ( MyPropertyProperty , value ) ; } } public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register ( nameof ( MyProperty ) , typeof ( object ) , typeof ( MainWindow ) , new PropertyMetaData ( 0 ) ) ; } public partial class MainWindow : WindowEx { public MainWindow ( ) { InitializeComponent ( ) ; } } } | How to make a UI-MarkupExtension |
C_sharp : I am thinking about a re-factor , but I do n't know if the end result is just overkill.Currently I haveWould it be overkill and/or less efficient to use linq for the ForEachWould the cast be a significant overhead here ? <code> IList < myobjecttypebase > m_items ; public int GetIncrementTotal ( ) { int incrementTot ; foreach ( myobjecttypebase x in m_items ) { incrementTot += x.GetIncrement ( ) ; } } m_items.ToList ( ) .ForEach ( x = > incrementTot += x.GetIncrement ( ) ) ; | Is using linq in this situation overkill |
C_sharp : I am using the MathInputControl class in C # through the micautLib COM library . Example : I am using Microsoft.Ink and I would like to be able to send an Ink object to the MathInputControl object through the MathInputControl.LoadInk ( IInkDisp ink ) ; method . However , the IInkDisp interface is an unmanaged interface and none of the managed Microsoft.Ink classes implement it . How can I send it a managed Ink object ? <code> MathInputControl mic = new MathInputControlClass ( ) ; mic.EnableExtendedButtons ( true ) ; mic.Show ( ) ; | Is it possible to cast a .NET class into a COM library class ? |
C_sharp : In C # , calling the .Split method will split a string into an array of strings based on some character or string.Is there an equivalent method for lists or arrays ? For example : This is what I have so far -- is there a cleaner or more eloquent way of accomplishing the same task ? Edit : It just occurred to me that my version will split the list only by a single element , whereas string.Split can split using either a single character , or an arbitrary string.Just for the sake of completeness , what would be the best way to implement that ? <code> var foo = new List < int > ( ) { 1 , 2 , 3 , 0 , 4 , 5 , 0 , 6 } ; var output = Split ( foo , 0 ) ; // produces { { 1 , 2 , 3 } , { 4 , 5 } , { 6 } } IEnumerable < IEnumerable < T > > Split < T > ( IEnumerable < T > list , T divider ) { var output = new List < List < T > > ( ) ; var temp = new List < T > ( ) ; foreach ( var item in list ) { if ( item.Equals ( divider ) ) { output.Add ( temp ) ; temp = new List < T > ( ) ; } else { temp.Add ( item ) ; } } output.Add ( temp ) ; return output ; } | Is there a `` split list '' method in c # ? |
C_sharp : If I have a class like this : - I know that in this example it 's unnecessary to use T since all Types have ToString ( ) on them etc . - it 's simply a contrived example . What I 'm more interested in is what happens under the bonnet in terms of the following : -I broadly ( think ! ) I understand reification i.e . if you make different types of a generic class e.g.etc . then at compile-time ( or runtime ? ) we end up with three actual concrete types , one for each generic argument specified . Does the same apply to method calls in my first example i.e . would we still have a single class Foo but three reified Bar methods , one for String , Int32 and Employee ? <code> static class Foo { public static void Bar < T > ( T item ) { Console.WriteLine ( item.ToString ( ) ; } } Foo.Bar ( `` Hello '' ) ; Foo.Bar ( 123 ) ; Foo.Bar ( new Employee ( `` Isaac '' ) ) ; List < Int32 > List < String > List < Employee > | What do C # generic methods on a non-generic class boil down to ? |
C_sharp : I just noticed that I can do the following , which came as a complete surprise to me : This works for the Write method too . What other methods have signatures supporting this , without requiring the use of String.Format ? Debug.WriteLine does n't ... HttpResponse.WriteLine does n't ... ( And on a side note , I could not find a quick way of searching for this with Reflector . What is a good way to search for specific signatures ? ) Edit : Specifically for the 3.5 framework . <code> Console.WriteLine ( `` { 0 } : { 1 } : { 2 } '' , `` foo '' , `` bar '' , `` baz '' ) ; | Which methods in the 3.5 framework have a String.Format-like signature ? |
C_sharp : Mathematically , 0.9 recurring can be shown to be equal to 1 . This question however , is not about infinity , convergence , or the maths behind this.The above assumption can be represented using doubles in C # with the following.Using the code above , ( resultTimesNine == 1d ) evaluates to true.When using decimals instead , the evaluation yields false , yet , my question is not about the disparate precision of double and decimal.Since no type has infinite precision , how and why does double maintain such an equality where decimal does not ? What is happening literally 'between the lines ' of code above , with regards to the manner in which the oneOverNine variable is stored in memory ? <code> var oneOverNine = 1d / 9d ; var resultTimesNine = oneOverNine * 9d ; | Why does n't 0.9 recurring always equal 1 |
C_sharp : How do I add closing nodes of a given node ( < sec > ) in certain positions in a text file which is not a valid xml file . I know its a bit confusing but here is sample input text and here is its desired outputBasically the program should generate < /sec > node before the next < sec > node and how many < /sec > 's will it add to the required place depend on the attribute id of the node < sec > using the digits separated by a . as follows : if the next < sec > node after say , < sec id= '' 4.5 '' > is < sec id= '' 5 '' > then 2 < /sec > should be added before < sec id= '' 5 '' > if the next < sec > node after say , < sec id= '' 3.2.1.2 '' > is < sec id= '' 3.4 '' > then 3 < /sec > nodes should be added before < sec id= '' 3.4 '' > I can not use any xml parsing methods to do this obviously , what other way can this be done ... .I 'm clueless at this point ... Can anyone help ? sample inputDesired output <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < body > < sec id= '' sec1 '' > < title > Introduction < /title > < p > Tuberculosis is associated with high mortality rate although according to the clinical trials that have been documented < /p > < sec id= '' sec1.2 '' > < title > Related Work < /title > < p > The main contributions in this study are : < list list-type= '' ordered '' > < list-item > < label > I. < /label > < p > Introducing SURF features descriptors for TB detection which for our knowledge has not been used in this problem before. < /p > < /list-item > < list-item > < label > II. < /label > < p > Providing an extensive study of the effect of grid size on the accuracy of the SURF. < /p > < /list-item > < /list > < /p > < /sec > < sec id= '' sec1.3 '' > < title > Dataset < /title > < p > The dataset used in this work is a standard computerized images database for tuberculosis gathered and organized by National Library of Medicine in collaboration with the Department of Health and Human Services , Montgomery County , Maryland ; USA < xref ref-type= '' bibr '' rid= '' ref15 '' > [ 15 ] < /xref > . The set contains 138 x-rays , 80 for normal cases and 58 with TB infections . The images are annotated with clinical readings comes in text notes with the database describing age , gender , and diagnoses . The images comes in 12 bits gray levels , PNG format , and size of 4020*4892 . The set contains x-ray images information gathered under Montgomery County & # x0027 ; s Tuberculosis screening program. < /p > < sec id= '' sec1.3.5 '' > < sec id= '' sec1.3.5.2 '' > < title > Methodologies < /title > < sec id= '' sec2 '' > < p > The majority of TB and death cases are in developing countries. < /p > < sec id= '' sec2.5 '' > < p > The disordered physiological manifestations associated with TB is diverse and leads to a complex pathological changes in the organs like the lungs. < /p > < sec id= '' sec2.5.3 '' > < sec id= '' sec2.5.3.1 '' > < p > The complexity and diversity in the pulmonary manifestations are reported to be caused by age. < /p > < sec id= '' sec2.5.3.1.1 '' > < /sec > < /sec > < /body > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < body > < sec id= '' sec1 '' > < title > Introduction < /title > < p > Tuberculosis is associated with high mortality rate although according to the clinical trials that have been documented < /p > < sec id= '' sec1.2 '' > < title > Related Work < /title > < p > The main contributions in this study are : < list list-type= '' ordered '' > < list-item > < label > I. < /label > < p > Introducing SURF features descriptors for TB detection which for our knowledge has not been used in this problem before. < /p > < /list-item > < list-item > < label > II. < /label > < p > Providing an extensive study of the effect of grid size on the accuracy of the SURF. < /p > < /list-item > < /list > < /p > < /sec > < sec id= '' sec1.3 '' > < title > Dataset < /title > < p > The dataset used in this work is a standard computerized images database for tuberculosis gathered and organized by National Library of Medicine in collaboration with the Department of Health and Human Services , Montgomery County , Maryland ; USA < xref ref-type= '' bibr '' rid= '' ref15 '' > [ 15 ] < /xref > . The set contains 138 x-rays , 80 for normal cases and 58 with TB infections . The images are annotated with clinical readings comes in text notes with the database describing age , gender , and diagnoses . The images comes in 12 bits gray levels , PNG format , and size of 4020*4892 . The set contains x-ray images information gathered under Montgomery County & # x0027 ; s Tuberculosis screening program. < /p > < sec id= '' sec1.3.5 '' > < sec id= '' sec1.3.5.2 '' > < title > Methodologies < /title > < /sec > < /sec > < /sec > < /sec > < sec id= '' sec2 '' > < p > The majority of TB and death cases are in developing countries. < /p > < sec id= '' sec2.5 '' > < p > The disordered physiological manifestations associated with TB is diverse and leads to a complex pathological changes in the organs like the lungs. < /p > < sec id= '' sec2.5.3 '' > < sec id= '' sec2.5.3.1 '' > < p > The complexity and diversity in the pulmonary manifestations are reported to be caused by age. < /p > < sec id= '' sec2.5.3.1.1 '' > < /sec > < /sec > < /sec > < /sec > < /sec > < /body > | How to generate closing nodes in a file that is not a valid xml file ? |
C_sharp : While implementing a struct similar to Nullable < T > I 've found that PropertyInfo.SetValue treats Nullable type differently then others . For Nullable property it can set value of underlying type but for custom type it throws System.ArgumentException : Object of type 'SomeType ' can not be converted to type NullableCase.CopyOfNullable 1 [ SomeType ] even if all conversion operators are overridden same way as in original Nullable < T > Code to reproduce : Why does PropertyInfo.SetValue fails for CopyOfNullable type and passes for Nullable < T > ? <code> foo.GetType ( ) .GetProperty ( `` NullableBool '' ) .SetValue ( foo , true ) ; using System ; namespace NullableCase { /// < summary > /// Copy of Nullable from .Net source code /// without unrelated methodts for brevity /// < /summary > public struct CopyOfNullable < T > where T : struct { private bool hasValue ; internal T value ; public CopyOfNullable ( T value ) { this.value = value ; this.hasValue = true ; } public bool HasValue { get { return hasValue ; } } public T Value { get { if ( ! hasValue ) { throw new InvalidOperationException ( ) ; } return value ; } } public static implicit operator CopyOfNullable < T > ( T value ) { return new CopyOfNullable < T > ( value ) ; } public static explicit operator T ( CopyOfNullable < T > value ) { return value.Value ; } } class Foo { public Nullable < bool > NullableBool { get ; set ; } public CopyOfNullable < bool > CopyOfNullablBool { get ; set ; } } class Program { static void Main ( string [ ] args ) { Foo foo = new Foo ( ) ; foo.GetType ( ) .GetProperty ( `` NullableBool '' ) .SetValue ( foo , true ) ; foo.GetType ( ) .GetProperty ( `` CopyOfNullablBool '' ) .SetValue ( foo , true ) ; //here we get ArgumentException } } } | Why Nullable < T > is treated special by PropertyInfo.SetValue |
C_sharp : I have a Cortana XML file and I need to input a number . What should I do to ensure I can convert it to a number ? <code> < Command Name= '' AddMoney '' > < Example > Add 10 dollars < /Example > < ListenFor > add { amount } { currency } < /ListenFor > < Feedback > Adding some money < /Feedback > < Navigate/ > < /Command > < PhraseList Label= '' currency '' > < item > dollar < /item > < item > euro < /item > < item > pound < /item > < /PhraseList > < PhraseList Label= '' amount '' > < /PhraseList > | Parse number with cortana |
C_sharp : I have this : But I could have this : If I convert to 'new way of writing things ' , what do I gain besides unreadability ? Will it make me closer to lambda functions ( = > ) ? Does it have something to do with RAII ? ADDITION : Some answered that normal initialization could left the object in 'invalid ' state after for example setting only a Directory property - my observation here is that is someone who was designing the object probably designed it in a way that only values that MUST be really entered are entered through real constructor , and all other could be freely modified later . <code> AudioPlayer player = new AudioPlayer ( ) ; player.Directory = vc.Directory ; player.StartTime = vc.StarTime ; player.EndTime = vc.EndTime ; AudioPlayer player = new AudioPlayer { Directory = vc.Directory , StartTime = vc.StarTime , EndTime = vc.EndTime } ; | Why bother with initializers ? ( .net ) |
C_sharp : I have website that I want download file with WebClient Class . For example I have url that I want download it . in console application this methods and code work correctly . This is sample code in Console application : this sample code work correctly in console application . how can i use this sample code in asp.net mvc application . for asp.net mvc it should like this ( i think ) for me the event handler method ( Downloader_DownloadProgressChanged ) it very important to work because i want create progress bar in client side .As i think this is best way to do that . but how can ? <code> public void DownloadFile ( string sourceUrl , string targetFolder ) { WebClient downloader = new WebClient ( ) ; downloader.Headers.Add ( `` User-Agent '' , `` Mozilla/4.0 ( compatible ; MSIE 8.0 ) '' ) ; downloader.DownloadFileCompleted += new AsyncCompletedEventHandler ( Downloader_DownloadFileCompleted ) ; downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler ( Downloader_DownloadProgressChanged ) ; downloader.DownloadFileAsync ( new Uri ( sourceUrl.Replace ( @ '' \ '' , '' '' ) ) , targetFolder ) ; while ( downloader.IsBusy ) { } } private void Downloader_DownloadProgressChanged ( object sender , DownloadProgressChangedEventArgs e ) { //Console.Write ( e.BytesReceived + `` `` + e.ProgressPercentage ) ; Console.Write ( `` % '' + e.ProgressPercentage ) ; } public ActionResult DownloadPage ( ) { string url = `` https : //rjmediamusic.com/media/mp3/mp3-256/Mostafa-Yeganeh-Jadeh.mp3 '' ; var downld = new DownloadManager ( ) ; downld.DownloadFile ( url , @ '' c : \\temp\1.mp3 '' ) ; return View ( ) ; } | How Can I Use DownloadProgressChangedEventHandler in asp.net mvc ? |
C_sharp : I am relatively new to binding in win forms . In order to learn the subject I setup the following test application . A basic winform with a ListBox and a Button.The string `` First '' shows in listBox1 on application launch . However , when I push the button which adds a new string to the stringList the new item is not shown in listBox1 . Could anyone help me understand the basics of collection data binding ? <code> public partial class Form1 : Form { public List < String > stringList = new List < String > ( ) ; public Form1 ( ) { InitializeComponent ( ) ; stringList.Add ( `` First '' ) ; listBox1.DataSource = stringList ; } private void button1_Click ( object sender , EventArgs e ) { stringList.Add ( `` Second '' ) ; } } | Winforms binding question |
C_sharp : I expect the output of 1 and 11 but I 'm getting 1 and 98 . What am I missing ? <code> public static void Main ( string [ ] args ) { int num = 1 ; string number = num.ToString ( ) ; Console.WriteLine ( number [ 0 ] ) ; Console.WriteLine ( number [ 0 ] + number [ 0 ] ) ; } | Why does string addition result is so weird ? |
C_sharp : Here 's my class : I 'm under the impression that the ref keyword tells the computer to use the same variable and not create a new one . Am I using it correctly ? Do I have to use ref on both the calling code line and the actual method implementation ? <code> public class UserInformation { public string Username { get ; set ; } public string ComputerName { get ; set ; } public string Workgroup { get ; set ; } public string OperatingSystem { get ; set ; } public string Processor { get ; set ; } public string RAM { get ; set ; } public string IPAddress { get ; set ; } public UserInformation GetUserInformation ( ) { var CompleteInformation = new UserInformation ( ) ; GetPersonalDetails ( ref CompleteInformation ) ; GetMachineDetails ( ref CompleteInformation ) ; return CompleteInformation ; } private void GetPersonalDetails ( ref UserInformation CompleteInformation ) { } private void GetMachineDetails ( ref UserInformation CompleteInformation ) { } } | Trouble using the ref keyword . Very newbie question ! |
C_sharp : Let 's say I 've got the following values in a collection of integers : The result I 'd expect is { 5,7 } .How can I do that ? Maybe using LINQ ? EDIT : The input collection is unsorted , so the algorithm should not rely on duplicates being consecutive . Also , whether the resulting duplicate collection is sorted or not does n't matter . <code> { 1,3,4,5,5,6,7,7 } | How to determine duplicates in a collection of ints ? |
C_sharp : So I have a custom generic model binder , that handle both T and Nullable < T > .But I automatically create the bindigs via reflection . I search trhough the entire appdomain for enumeration flagged with specific attribute and I want to bind theese enums like this : But here is the catch . I ca n't bind the Nullable < T > to CommandModelBinder.I 'm thinking the runtime code generation , but I never do this , and maybe there is other options on the market.Any idea to achieve this ? Thanks , Péter <code> AppDomain .CurrentDomain .GetAssemblies ( ) .SelectMany ( asm = > asm.GetTypes ( ) ) .Where ( t = > t.IsEnum & & t.IsDefined ( commandAttributeType , true ) & & ! ModelBinders.Binders.ContainsKey ( t ) ) .ToList ( ) .ForEach ( t = > { ModelBinders.Binders.Add ( t , new CommandModelBinder ( t ) ) ; //the nullable version should go here } ) ; | Wrap T in Nullable < T > via Reflection |
C_sharp : I 've been working on several non-web applications with Entity Framework and always it was struggling for me to find a correct approach for implementing Generic Repository with DbContext.I 've searched a lot , many of articles are about web applications which have short-living contexts . In desktop approaches I ca n't find suitable method.One approach is DbContext per ViewModel but I do n't agree with coupling View with Repository layers.Another one is using using clause this way : but this way we will not have Unit of Work and also ca n't use IoC Containers.So what is the best practice for using DbContext in desktop applications ? <code> using ( var context = new AppDbContext ( ) ) { // ... } | How to use DbContext with DI in desktop applications ? |
C_sharp : I 'm having issues using a public enum defined in C # within a C++ Interface . The .NET project is exposed to COM to be used within C++ and VB legacy software.C # Code : C++ Code : Edit : In the idl for the project I imported the tlb . ( importlib ( `` \..\ACME.XXX.XXX.XXX.Interfaces.tlb '' ) ) In MethodTwo , I keep getting errors stating Excepting Type Specification near TestEnumI 'm assuming there 's something I 'm not doing correctly . MethodOne seems to be finding the reference correctly.Is there some magic to referencing .NET enum object in C++ interface ? <code> namespace ACME.XXX.XXX.XXX.Interfaces.Object { [ Guid ( `` ... .. '' ) ] [ InterfaceType ( ComInterfaceType.InterfaceIsDual ) ] [ ComVisible ( true ) ] public interface TestInterface { void Stub ( ) ; } [ ComVisible ( true ) ] public enum TestEnum { a = 1 , b = 2 } } interface ITestObject : IDispatch { [ id ( 1 ) , helpstring ( `` one '' ) ] HRESULT MethodOne ( [ in ] TestInterface *a ) ; [ id ( 2 ) , helpstring ( `` two '' ) ] HRESULT MethodTwo ( [ in ] TestEnum a ) ; } | C # Enum in a C++ Library |
C_sharp : I 'm attempting to fill in data to my NCCMembershipUser with the following code : I am getting an error `` An object reference is required for the non-static field , method , or property 'System.Web.Security.MembershipProvider.GetUser ( string , bool ) ' '' If I instead use Membership.GetUser ( ) ( without the name string ) to access the current user , it gives me a casting error , and GetUser ( ) appears it can not be overridden.Edit : The casting error I get is `` [ A ] NCC.App_Code.NCCMembershipProvider can not be cast to [ B ] NCC.App_Code.NCCMembershipProvider . '' <code> string name = User.Identity.Name ; NCCMembershipUser currentUser = ( NCCMembershipUser ) NCCMembershipProvider.GetUser ( name , true ) ; currentUser.Salutation = GenderSelect.SelectedValue ; currentUser.FirstName = TextBoxFirstName.Text ; currentUser.LastName = TextBoxLastName.Text ; currentUser.Position = TextBoxPosition.Text ; ... try { NCCMembershipProvider u = ( NCCMembershipProvider ) Membership.Provider ; u.UpdateUser ( currentUser ) ; } | Casting Error : Inserting data into Custom MembershipUser |
C_sharp : Say I have the following code : Will this clear out the subscribers , replacing it with new empty default ? And , will the event notify all subscribers before they get cleared out ? I.E . Is there a chance for a race condition ? <code> public event EventHandler DatabaseInitialized = delegate { } ; //a intederminant amount of subscribers have subscribed to this event ... // sometime later fire the event , then create a new event handler ... DatabaseInitialized ( null , EventArgs.Empty ) ; //THIS LINE IS IN QUESTION DatabaseInitialized = delegate { } ; | Clearing C # Events after execution ? |
C_sharp : Argh ! I know I will get this eventually but at this point I 'm almost 2 hours into it and still stuck.I need to resolve the individual indexes for each `` level '' of a jagged array for a specific location . It 's hard to explain , but if you imagine a 3 level jagged array with [ 2,3,4 ] lengths . If you then were to flatten that out into a single array it would have a size of 24 . Now , let 's say you needed to find the the indexes ( one for each level of the jagged array ) that would be equal to the single array index 22 . It would be 1,2,1 . It 's not hard to figure out a single scenario , but I 'm trying to figure out what the algorithm is to resolve these values for a variable depth jagged array.Here is a simple code sample of my current attempt : It does n't work correctly , although it ALMOST gets me what I need but I think that just may be luck . I suspect this is a common problem that has been solved before , I just do n't have the experience to figure it out . : ( Also , before anyone tells me that using arrays like this is terrible or `` why do n't you store your data like this '' - The above description and code is simulating the layout of some decoder chips on our hardware and I need to work out a way to resolve a path to a specific graph of cascading chips ; the above example exactly matches the layout of the chips . I 'm stuck with it . <code> using System ; class Program { static void Main ( string [ ] args ) { // Build up the data and info about level depth int [ ] levelDepth = new [ ] { 2 , 3 , 4 } ; int [ ] [ ] [ ] data = new int [ ] [ ] [ ] { new int [ ] [ ] { new int [ 4 ] , new int [ 4 ] , new int [ 4 ] } , new int [ ] [ ] { new int [ 4 ] , new int [ 4 ] , new int [ 4 ] } } ; int requestedValue = 22 ; float temp = requestedValue ; // Store the index of each level array to get to the index // for the requested value int [ ] levelIndexes = new int [ 3 ] { 0 , 0 , 0 } ; // The following does not work ! int i = levelDepth.Length ; while ( i > 0 ) { temp = temp / levelDepth [ i - 1 ] ; levelIndexes [ i - 1 ] = ( int ) Math.Round ( temp ) ; i -- ; } } } | Need help with algorithm to resolve index through jagged array |
C_sharp : I have a weird question about OOP and interfaces which messed up my mind while trying to find best design.There are two different classes which make same work ( for example sending message ) at different environments . These two environments use different parameters to define recipient ; one is using mail address and the other one is using user name . So both the classes have same but slightly different methods for sending message.MessageSenderViaMailManager.csMessageSenderViaUsernameManager.csThere are other similar methods in both classes , responsible for same work but may require different parameters.To make usable these managers with an interface , i created one which name is IMessageSenderManager and contains a definition like this.So both SendMessage methods in my classes were changed to this : With this new SendMessage method , i can use appropriate parameter to use as recipient ( mail address or username ) . This seems ok , but implemantation looks like weird . Because i have to send all parameters , without knowing which will be used at runtime while coding . For example : Like code above , sending message by mail address looks similar.In my opinion this is not a good design so i started to think for a better solution . Bacause if i want to implement another MessageSender provider which uses different descriptor for recipient , i have to add another parameter to my interface , so to all classes . I thought , i could change two recipient parameters with one general recipient parameter and send appropriate value for context . But i am trying to use this in dynamic enviroment and the way ( via user name or mail ) will be determined in runtime , so i could n't use this.I am planing to make this , a flexible library which can be used decoupled or unit test friendly for other developers and i do n't want to confuse them with meaningless parameters or with bad design . Is there any better design for a situation like this ? EDIT : Actually by my mistake , i forgot very big and important part of my question , i am sorry for this . As you can see from answers there are some alternatives to solve my first problem which described above . But then ? I mentioned in code , interface is returned from MessageSenderFactory ( ) method but i do n't know which message sender manager returned . So i have two options , Write if condition to check which manager is returned from method and send mandatory parameters for that manager with proper values and send others empty.Send all parameters with proper values regardless of manager , so both of them can work without problem . But in future , if another manager is added than i will need to send extra parameters for that manager , everytime.Is there another way which i could n't think yet ? Also other methods than SendMessage may require different parameters according to manager which is unknown at runtime . For example : MessageSenderViaMailManager 's AddContact method may require parameters below : Contact NameContact MailContact Phone NumberContact MailType ( rich , plain ) or MessageSenderViaUserNameManager 's AddContact method may require parameters below : Contact NameContact MailContact User NameContact Message Platform ( Twitter , facebook , vs ) Contact Sender NameSo this makes everything very complicated . How my IMessageSenderManger 's AddMethod should be ? Should it contain all parameters ? Should i overload it ? Or should i put common parameters in method and make other parameters which vary by manager anonymous ( like HtmlHelper in MVC ) I know this is question is n't very solid and i am not good at describing in English.GitHub EDIT : I created a small example and uploaded to github , i hope this can help me to explain my question betterhttps : //github.com/bahadirarslan/InterfaceDesign <code> public bool SendMessage ( string recipientMailAddress , string message ) { .. } public bool SendMessage ( string recipientUserName , string message ) { .. } public bool SendMessage ( string recipientUserName , string recipientMailAddress , string message ) ; public bool SendMessage ( string recipientUserName , string recipientMailAddress , string message ) { .. } // Sending message via username implementationstring userName = GetUserNameFromSomeWhere ( ) ; string mailAddress = GetUserMailFromSomeWhere ( ) ; IMessageSenderManager manager = MessageSenderFactory ( ) ; manager.SendManager ( userName , mailAddress , `` This messaged sent by your user name '' ) ; | Standardization with Interface in .Net |
C_sharp : Please correct me if I am wrong . I am asking this question to clarify some ideas that I have.Today in school I learned that when a process ( program ) executes , then the operating systems gives it a space in memory . So take for instance this two programs : Program1 : Program 2So I understand that in program 2 I will get an error . I will be accessing restricted memory . So far what I have learned makes sense . Ok know here is where things do not make sense.There is a very nice program called AutoIt used to automate tasks . For example it can send mouse clicks , move the mouse , send key strokes etc.Anyways autoit comes with a program called AutoIt Window Info where that program enables you to get the handles ( pointers ) of controls on windows . For example I could see the handle of the window 's control by draging the finder tool to the control that I wish on getting information : int this picture I am dragging the finder tool to the calculator 's input control . I could also drag it to button 7 for instance . So if you see in the picture I now have the address of that control . I could then be able to access it from my program ! ! Yet another example of how you can access memory that does not belong to my programStep 1 ) Get the pointer of any window with autoit window infoStep 2 ) In my computer that pointer is : That is the window of google chrome the place where I am typing this question.This class will send a window to the back : and then if I call the method with the poniter that I just got with the help of autoit and call it as : then I will send that window to the backI post some examples in order to ilustrate my point . But my question is when are you allowed to access other parts of the memory ? If I make my variable public other programs will be able to access it ? Why can I access some controls of windows from my own program ? <code> static void Main ( string [ ] args ) { unsafe // in debug options on the properties enable unsafe code { int a = 2 ; int* pointer_1 = & a ; // create pointer1 to point to the address of variable a // breakpoint in here ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! // in the debug I should be able to see the address of pointer1 . Copy it and // type it in the console string hexValue = Console.ReadLine ( ) ; // convert the hex value to base 10 int decValue = int.Parse ( hexValue , System.Globalization.NumberStyles.HexNumber ) ; // create a new pointer that point to the address that I typed in the console IntPtr pointer_2 = new IntPtr ( decValue ) ; Console.WriteLine ( `` The address of a : { 0 } Value { 1 } '' , ( ( int ) & a ) , a ) ; try { Console.WriteLine ( `` The address of { 0 } points to value { 1 } '' , ( int ) & pointer_1 , ( int ) pointer_2 ) ; // different approach of acomplishing the same Console.WriteLine ( Marshal.ReadInt32 ( pointer_2 ) ) ; } catch { Console.WriteLine ( @ '' you are supposed to be debuging this program . `` ) ; } } static void Main ( string [ ] args ) { unsafe { IntPtr pointer_0 = new IntPtr ( 95151860 ) ; // see address of variable from program1 int* pointer_1 = ( int* ) pointer_0 ; // try to access program 's 1 object Console.WriteLine ( `` addrees of { 0 } points to value { 1 } `` , ( int ) & pointer_1 , *pointer_1 ) ; } } public static class SendWndToBack { [ DllImport ( `` user32.dll '' ) ] static extern bool SetWindowPos ( IntPtr hWnd , IntPtr hWndInsertAfter , int X , int Y , int cx , int cy , uint uFlags ) ; const UInt32 SWP_NOSIZE = 0x0001 ; const UInt32 SWP_NOMOVE = 0x0002 ; const UInt32 SWP_NOACTIVATE = 0x0010 ; static readonly IntPtr HWND_BOTTOM = new IntPtr ( 1 ) ; static readonly IntPtr k = new IntPtr ( 12 ) ; public static void WindowHandle ( IntPtr windowHandle ) { SetWindowPos ( windowHandle , HWND_BOTTOM , 0 , 0 , 0 , 0 , SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE ) ; } } SendWndToBack.WindowHandle ( new IntPtr ( 0x00000000000510B2 ) ) ; | when is reading and writing to memory legal ? |
C_sharp : I 'm trying to get in to workflow foundation but apparently i ca n't seem to get even the most basic implementation of an async activity working.Could anyone point me in the right direction with this activity I have put together in order to make an async OData request using HttpClient ... Firstly I created a base type extending from AsyncCodeActivity ... Next I inherit that to provide my implementation ... ... the idea being that this activity can do only get requests , i could then implement a post , put and delete to get full crud in the same manner on top of my base type above.The problem comes when i add this to a workflow and try to execute the flow using a re-hosted designer in a new wpf app resulting in the following exception ... Edit : So I did a little bit more tinkering and have something that appears to not complain but i 'm not convinced this is a `` good '' way to handle this as Task implements IAsyncResult directly and it feels like i 'm jumping through a bunch of hoops I perhaps do n't need to.This appears to compile and run but i ca n't help but feel like there 's a cleaner way to handle this . <code> public abstract class ODataActivity < TResult > : AsyncCodeActivity < TResult > , IDisposable { protected HttpClient Api = new HttpClient ( new HttpClientHandler ( ) { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate } ) { BaseAddress = new Uri ( new Config ( ) .ApiRoot ) } ; bool disposed = false ; public void Dispose ( ) { Dispose ( disposed ) ; } public virtual void Dispose ( bool disposed ) { if ( ! disposed ) { Api.Dispose ( ) ; Api = null ; } } } public class ODataFetchActivity < TResult > : ODataActivity < TResult > { public string Query { get ; set ; } protected override IAsyncResult BeginExecute ( AsyncCodeActivityContext context , AsyncCallback callback , object state ) { var task = Api.GetAsync ( Query ) .ContinueWith ( t = > t.Result.Content.ReadAsAsync < TResult > ( ) ) .ContinueWith ( t = > callback ( t ) ) ; context.UserState = task ; return task ; } protected override TResult EndExecute ( AsyncCodeActivityContext context , IAsyncResult result ) { var response = ( ( Task < TResult > ) result ) .Result ; context.SetValue ( Result , response ) ; return response ; } } public class ODataFetchActivity < TResult > : ODataActivity < TResult > { public string Query { get ; set ; } Func < TResult > work ; protected override IAsyncResult BeginExecute ( AsyncCodeActivityContext context , AsyncCallback callback , object state ) { work = ( ) = > Api.Get < TResult > ( Query ) .Result ; context.UserState = work ; return work.BeginInvoke ( callback , state ) ; } protected override TResult EndExecute ( AsyncCodeActivityContext context , IAsyncResult result ) { TResult response = work.EndInvoke ( result ) ; Result.Set ( context , response ) ; return response ; } } | Creating a simple Async Workflow Activity |
C_sharp : My data is as under in two tablesMyDatetime column in above has unique indexI want to populate this in a dictionary . I have triedI expect two rows in the dictionaryI get an error where it complains about the key of the dictionary entered twice . The key would be the datetime which is unique in the master <code> Master Columns ID MyDateTime 1 07 Sept2 08 Sept Detail ColumnsID Data1 Data2 Data31 a b c 1 x y z1 f g h2 a b c Dictionary < DateTime , List < Detail > > result = ( from master in db.master from details in db.detail where ( master.ID == detail.ID ) select new { master.MyDateTime , details } ) .Distinct ( ) .ToDictionary ( key = > key.MyDateTime , value = > new List < Detail > { value.details } ) ; 1 , List of 3 rows as details2 , List of 1 row as details | Linq to Dictionary with key and a list |
C_sharp : So if I have something like this : and I decide later that I want to change it to this : Is there a quicker way to have the existing code under the if statement go directly into the newly made curly braces ? Because currently if I were to add the curly braces after creating the if statement in the first example I 'd have to cut the `` return true '' from under the new braces and paste it between the newly made curly braces . This is what it looks like : and it 's pretty annoying . Is there a fix to this or do we have to manually copy and paste the existing line in between the brackets ? P.S . I 'm using Microsoft Visual Studio 2015 ver 3 and programming in c # but I think this problem occurs in other languages too like c++ . <code> if ( a > b ) return true ; if ( a > b ) { a++ ; return true ; } if ( a > b ) { } return true ; | Visual Studio 2015 How to quickly move existing code after if statement into newly placed curly braces ? |
C_sharp : I really love the GroupBy LINQ method in C # . One thing that I do n't like though is that the Key is always called Key . When I loop through the groups , Key does n't say me anything . So I have to look at the rest of the context to understand what Key actually is . Of course you could argue it 's a small thing , because you only have to look at the outer loop . In my opinion it still eats 'braincycles ' when you 're reading it though . So if there are good alternatives that need little boilerplate I would like to use it.There are some alternatives , but they all add boilerplate code or depend on comments - both I try to omit.Option 1 - Extra variable inside loopThis solution adds unnecessary boilerplate code.Option 2 - Extra SelectThis solution adds unnecessary boilerplate code.Option 3 - Add comment close to the use of KeyI rather have expressive code then comments that get outdated.SummaryIs it theoretically possible to design an extension method that somehow works similar like the anonymous class functionaliy ? So we get : <code> var grouped_by_competition = all_events .GroupBy ( e = > e.Competition ) ; foreach ( var group in grouped_by_competition ) { [ ... ] // ok what is Key for kind of object ? I have to look at the outer loop to understand group.Key.DoSomething ( ) ; } var grouped_by_competition = all_events .GroupBy ( e = > e.Competition ) foreach ( var group in grouped_by_competition ) { var competition = group.Key ; [ ... ] competition.DoSomething ( ) ; } var grouped_by_competition = all_events .GroupBy ( e = > e.Competition ) .Select ( x = > new { Competition = x.Key , Items = x } ) ; foreach ( var group in grouped_by_competition ) { [ ... ] group.Competition.DoSomething ( ) ; } var example = new { e.Competition } ; example.Competition.DoSomething ( ) ; // property name deduced var grouped_by_competition = all_events .NamedGroupBy ( e = > e.Competition ) ; foreach ( var group in grouped_by_competition ) { [ ... ] group.Competition.DoSomething ( ) ; } | Is it possible to combine a GroupBy and Select to get a proper named Key ? |
C_sharp : suppose I have x.dll in C++ which looks like thisNow , suppose I want to use this in C # Is there any way to tell CLR to take strong ownership of the string returned from f2 , but not f1 ? The thing is that the fact that the string returned from f1 will eventually be freed , deleted , or whatever by GC is equally bad with the fact that the string returned from f2 wo n't . Hope the question was clear . Thanks in advance <code> MYDLLEXPORTconst char* f1 ( ) { return `` Hello '' ; } MYDLLEXPORTconst char* f2 ( ) { char* p = new char [ 20 ] ; strcpy ( p , `` Hello '' ) ; return p ; } [ DllImport ( `` x.dll '' ) ] public static extern string f1 ( ) ; [ DllImport ( `` x.dll '' ) ] public static extern string f2 ( ) ; | How to specify whether to take ownership of the marshalled string or not ? |
C_sharp : Can I do something like this ? Where I have the following in my global.asax.cs application_startUpdateSo , I tried to see what is wrong . Here is my new code . It seems that the problem is with this WizardViewModel and it 's binder . What `` tells '' the application to expect and incoming Wizard model ? Where I have the following in my global.asax.cs application_startComplete Binder Code <code> [ HttpPost ] public ActionResult Index ( WizardViewModel wizard , IStepViewModel step ) { ModelBinders.Binders.Add ( typeof ( IStepViewModel ) , new StepViewModelBinder ( ) ) ; ModelBinders.Binders.Add ( typeof ( WizardViewModel ) , new WizardViewModelBinder ( ) ) ; [ HttpPost ] public ActionResult Index ( WizardViewModel wizard ) { ModelBinders.Binders.Add ( typeof ( WizardViewModel ) , new WizardViewModelBinder ( ) ) ; namespace Tangible.Binders { public class StepViewModelBinder : DefaultModelBinder { protected override object CreateModel ( ControllerContext controllerContext , ModelBindingContext bindingContext , Type modelType ) { var stepTypeValue = bindingContext.ValueProvider.GetValue ( `` StepType '' ) ; var stepType = Type.GetType ( ( string ) stepTypeValue.ConvertTo ( typeof ( string ) ) , true ) ; var step = Activator.CreateInstance ( stepType ) ; bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType ( ( ) = > step , stepType ) ; return step ; } } public class WizardViewModelBinder : DefaultModelBinder { protected override object CreateModel ( ControllerContext controllerContext , ModelBindingContext bindingContext , Type modelType ) { var wizardValue = bindingContext.ValueProvider.GetValue ( `` wizard '' ) ; if ( wizardValue ! = null ) { var wizardType = Type.GetType ( ( string ) wizardValue.ConvertTo ( typeof ( string ) ) , true ) ; var wizard = Activator.CreateInstance ( wizardType ) ; bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType ( ( ) = > wizard , wizardType ) ; return wizard ; } else { var wizard = new Tangible.Models.WizardViewModel ( ) ; wizard.Initialize ( ) ; return wizard ; } } } } | A created a new CustomModelBinder from one that already worked . Why does the new one never get called to do any binding ? |
C_sharp : I 'm trying to understand why/how does ref-return for the case of returning refs to members of a class.In other words , I want to understand the internal workings of the runtime that guarantee why ref-return of a instance member works , from the memory safety aspect of the CLR.The specific feature I 'm referring to is mentioned in the ref-return documentation which specifically states : The return value can not be a local variable in the method that returns it ; it must have a scope that is outside the method that returns it . It can be an instance or static field of a class , or it can be an argument passed to the method . Attempting to return a local variable generates compiler error CS8168 , `` Can not return local 'obj ' by reference because it is not a ref local . `` Here 's a code snippet that cleanly compiles and runs and demonstrates returning an instance field as ref return : My question for this code is : What is the underlying mechanism in the GC that ensures that it keeps tracking the SomeClass instance after that last refernce to it had supposedly been set to null ? More precisely ... : Given that the local s stores a direct pointer to the _s member of the SomeClass instance ( disassembly from windbg below ) whose last `` explicit '' reference is overwritten with null in the following line ( x = null ) , How does the GC keep track of the live-root to the SomeClass instance which would prevent this program from crashing ... ? Windbg Disassembly : <code> using System ; using System.Diagnostics ; namespace refreturn { public struct SomeStruct { public int X1 ; } public class SomeClass { SomeStruct _s ; public ref SomeStruct S = > ref _s ; } class Program { static void Main ( string [ ] args ) { var x = new SomeClass ( ) ; // This will store a direct pointer to x.S ref var s = ref x.S ; // And now the GC will be free to re-use this memory x = null ; // Why should s.X1 be considered safe ? Console.WriteLine ( s.X1 + 0x666 ) ; } } } 007ff9 ` e01504dc e8affbffff call 00007ff9 ` e0150090 ( refreturn.SomeClass.get_S ( ) , mdToken : 0000000006000001 ) //rbp-30h stores the pointer to the struct00007ff9 ` e01504e1 488945d0 mov qword ptr [ rbp-30h ] , rax // Now it 's copied to rcx00007ff9 ` e01504e5 488b4dd0 mov rcx , qword ptr [ rbp-30h ] // And now copied to rbp-20h00007ff9 ` e01504e9 48894de0 mov qword ptr [ rbp-20h ] , rcx00007ff9 ` e01504ed 33c9 xor ecx , ecx // The last reference is overwritten with null00007ff9 ` e01504ef 48894de8 mov qword ptr [ rbp-18h ] , rcx // rbp-20h is copied to rcx again00007ff9 ` e01504f3 488b4de0 mov rcx , qword ptr [ rbp-20h ] // Is n't this a possible boom ? ! ? ! ? 00007ff9 ` e01504f7 8b09 mov ecx , dword ptr [ rcx ] 00007ff9 ` e01504f9 81c19a020000 add ecx,29Ah00007ff9 ` e01504ff e85c634c5d call mscorlib_ni+0xd56860 ( 00007ffa ` 3d616860 ) ( System.Console.WriteLine ( Int32 ) , mdToken : 0000000006000b5b ) 00007ff9 ` e0150504 90 nop | How/Why does ref return for instance members |
C_sharp : Is is possible to make the following compile without : Making IFooCollection genericExplicitly implementing IFooCollection.Items on FooCollection and performing an explicit cast.I 'm happy enough with the second solution ( implementing the interface explicitly ) but would like to understand why I need to cast T as IFoo when we have a generic constraint specifying that T must implement IFoo . <code> public interface IFoo { } public interface IFooCollection { IEnumerable < IFoo > Items { get ; } } public class FooCollection < T > : IFooCollection where T : IFoo { public IEnumerable < T > Items { get ; set ; } } | Cast generic type to interface type constraint |
C_sharp : I 've been fooling around with some LINQ over Entities and I 'm getting strange results and I would like to get an explanation ... Given the following LINQ query , I get the following SQL query ( taken from SQL Profiler ) : So far so good.If I change my LINQ query to : it yields to the exact same SQL query . Makes sense to me.Here comes the interesting part ... If I change my LINQ query to : the following SQL is executed ( I stripped a few of the fields from the actual query , but all the fields from the table ( ~ 15 fields ) were included in the query , twice ) : Why are the SQLs generated are so different ? After all , the exact same code is executed , it 's just that sample # 3 is using intermediate variables to get the same job done ! Also , if I do : for sample # 1 and sample # 2 , I get the exact same query that was captured by SQL Profiler , but for sample # 3 , I get : What is the difference ? Why ca n't I get the SQL Query generated by LINQ if I split the LINQ query in multiple instructions ? The ulitmate goal is to be able to add operators to the query ( Where , OrderBy , etc . ) at run-time.BTW , I 've seen this behavior in EF 4.0 and EF 6.0.Thank you for your help . <code> // Sample # 1IEnumerable < GroupInformation > groupingInfo ; groupingInfo = from a in context.AccountingTransaction group a by a.Type into grp select new GroupInformation ( ) { GroupName = grp.Key , GroupCount = grp.Count ( ) } ; SELECT 1 AS [ C1 ] , [ GroupBy1 ] . [ K1 ] AS [ Type ] , [ GroupBy1 ] . [ A1 ] AS [ C2 ] FROM ( SELECT [ Extent1 ] . [ Type ] AS [ K1 ] , COUNT ( 1 ) AS [ A1 ] FROM [ dbo ] . [ AccountingTransaction ] AS [ Extent1 ] GROUP BY [ Extent1 ] . [ Type ] ) AS [ GroupBy1 ] // Sample # 2groupingInfo = context.AccountingTransaction . GroupBy ( a = > a.Type ) . Select ( grp = > new GroupInformation ( ) { GroupName = grp.Key , GroupCount = grp.Count ( ) } ) ; // Sample # 3IEnumerable < AccountingTransaction > accounts ; IEnumerable < IGrouping < object , AccountingTransaction > > groups ; IEnumerable < GroupInformation > groupingInfo ; accounts = context.AccountingTransaction ; groups = accounts.GroupBy ( a = > a.Type ) ; groupingInfo = groups.Select ( grp = > new GroupInformation ( ) { GroupName = grp.Key , GroupCount = grp.Count ( ) } ) ; SELECT [ Project2 ] . [ C1 ] AS [ C1 ] , [ Project2 ] . [ Type ] AS [ Type ] , [ Project2 ] . [ C2 ] AS [ C2 ] , [ Project2 ] . [ Id ] AS [ Id ] , [ Project2 ] . [ TimeStamp ] AS [ TimeStamp ] , -- < snip > FROM ( SELECT [ Distinct1 ] . [ Type ] AS [ Type ] , 1 AS [ C1 ] , [ Extent2 ] . [ Id ] AS [ Id ] , [ Extent2 ] . [ TimeStamp ] AS [ TimeStamp ] , -- < snip > CASE WHEN ( [ Extent2 ] . [ Id ] IS NULL ) THEN CAST ( NULL AS int ) ELSE 1 END AS [ C2 ] FROM ( SELECT DISTINCT [ Extent1 ] . [ Type ] AS [ Type ] FROM [ dbo ] . [ AccountingTransaction ] AS [ Extent1 ] ) AS [ Distinct1 ] LEFT OUTER JOIN [ dbo ] . [ AccountingTransaction ] AS [ Extent2 ] ON [ Distinct1 ] . [ Type ] = [ Extent2 ] . [ Type ] ) AS [ Project2 ] ORDER BY [ Project2 ] . [ Type ] ASC , [ Project2 ] . [ C2 ] ASC Console.WriteLine ( groupingInfo.ToString ( ) ) ; System.Linq.Enumerable+WhereSelectEnumerableIterator ` 2 [ System.Linq.IGrouping ` 2 [ System.Object , TestLinq.AccountingTransaction ] , TestLinq.GroupInformation ] | What is the difference between these LINQ queries |
C_sharp : Does adding AsNotracking function to a count in Entity Framework 6 has an impact on a count ? More specifically does it improve or decrease performance or will the count result get cached ? With AsNoTrackingWithout AsNoTracking <code> myContext.Products.AsNoTracking ( ) .Count ( ) ; myContext.Products.Count ( ) ; | Does adding AsNoTracking in Entity Framework impact a Count ? |
C_sharp : I am having a problem sorting Swedish strings.I am having problems with the following characters : v , w , å , ä , ö.Expected : a , va , vb , wa , wb , å , ä , ö Actual : a , va , wa , vb , wb , å , ä , öIs the there any option to make it sort the strings as expected ? <code> new [ ] { `` ö '' , `` ä '' , `` å '' , `` wa '' , `` va '' , `` wb '' , `` vb '' , `` a '' } .OrderBy ( x = > x , new CultureInfo ( `` sv-SE '' ) .CompareInfo.GetStringComparer ( CompareOptions.None ) ) | How to get Swedish sort order for strings |
C_sharp : & Design : http : //i40.tinypic.com/2ufvshz.pngYa i deleted everything else , if someone has any idea what the guy who posted an answer refers to in reference to my tables column name design and structure please feel free to answer.Class definition ( That is inside of the Model1.Context.CS ( .edmx ) ) : Dim_Audit : <code> SELECT TOP 1000 [ GUID ] , [ Ticket_Number ] , [ Created_At ] , [ Changed_At ] , [ Priority ] , [ Department ] , [ Ticket_Type ] , [ Category ] , [ SubCategory ] , [ Second_Category ] , [ Third_Category ] , [ ZZARN ] , [ Categorization_Hash_Key ] , [ ZZAID ] , [ Work_Order ] , [ Contact_Type ] , [ Action ] , [ BPartner_Key ] , [ PFT ] , [ Ticket_Status_Code ] , [ Ticket_Status ] , [ Audit_Key ] FROM [ CorporateDWTest ] . [ dbo ] . [ SRS_Ticket_Transaction_Stage_Cleaned ] public DbSet < SRS_Ticket_Transaction_Stage_Cleaned > SRS_Ticket_Transaction_Stage_Cleaned { get ; set ; } namespace CorporateDWTesting { using System ; using System.Collections.Generic ; public partial class CRM_Ticket_Transaction_Stage_Cleaned { public byte [ ] GUID { get ; set ; } public string Ticket_Number { get ; set ; } public decimal Created_At_UTC { get ; set ; } public decimal Changed_At_UTC { get ; set ; } public string Priority { get ; set ; } public string Department { get ; set ; } public string Municipality { get ; set ; } public string Ticket_Type { get ; set ; } public string Category { get ; set ; } public string SubCategory { get ; set ; } public string Address_Number { get ; set ; } public string Street1 { get ; set ; } public string Street2 { get ; set ; } public string Contact_Type { get ; set ; } public string Action { get ; set ; } public string BPartner_Key { get ; set ; } public Nullable < int > PFT { get ; set ; } public string Ticket_Status_Code { get ; set ; } public string Ticket_Status { get ; set ; } public Nullable < decimal > Due_Date_UTC { get ; set ; } public int Audit_Key { get ; set ; } public virtual Dim_Audit Dim_Audit { get ; set ; } } } namespace CorporateDWTesting { using System ; using System.Collections.Generic ; public partial class Dim_Audit { public Dim_Audit ( ) { this.Business_Partner_Stage = new HashSet < Business_Partner_Stage > ( ) ; this.CRM_Ticket_Transaction_Stage = new HashSet < CRM_Ticket_Transaction_Stage > ( ) ; this.CRM_Ticket_Transaction_Stage_Cleaned = new HashSet < CRM_Ticket_Transaction_Stage_Cleaned > ( ) ; this.Dim_Audit1 = new HashSet < Dim_Audit > ( ) ; this.Dim_Categorization = new HashSet < Dim_Categorization > ( ) ; this.Dim_Collection_Type = new HashSet < Dim_Collection_Type > ( ) ; this.Dim_Municipality = new HashSet < Dim_Municipality > ( ) ; this.Dim_Response_Team = new HashSet < Dim_Response_Team > ( ) ; this.Dim_Ticket = new HashSet < Dim_Ticket > ( ) ; this.Fact_Service_Units = new HashSet < Fact_Service_Units > ( ) ; this.Fact_Service_Units1 = new HashSet < Fact_Service_Units > ( ) ; this.Fact_Ticket_Processing = new HashSet < Fact_Ticket_Processing > ( ) ; this.Fact_Ticket_Processing1 = new HashSet < Fact_Ticket_Processing > ( ) ; this.Initial_Categories = new HashSet < Initial_Categories > ( ) ; } public int Audit_Key { get ; set ; } public Nullable < int > Parent_Audit_Key { get ; set ; } public string Table_Name { get ; set ; } public string Package_Name { get ; set ; } public Nullable < System.Guid > Package_GUID { get ; set ; } public Nullable < int > Package_Version_Major { get ; set ; } public Nullable < int > Package_Version_Minor { get ; set ; } public Nullable < System.DateTime > Execution_Start_Time { get ; set ; } public Nullable < System.DateTime > Execution_End_Time { get ; set ; } public Nullable < int > Extract_Row_Count { get ; set ; } public Nullable < int > Insert_Row_Count { get ; set ; } public Nullable < int > Update_Row_Count { get ; set ; } public Nullable < int > Error_Row_Count { get ; set ; } public Nullable < int > Table_Initial_Row_Count { get ; set ; } public Nullable < int > Table_Final_Row_Count { get ; set ; } public Nullable < int > Table_Max_Surrogate_Key { get ; set ; } public string Table_Max_Business_Key { get ; set ; } public Nullable < bool > Processing_Successful { get ; set ; } public string Error_Code { get ; set ; } public virtual ICollection < Business_Partner_Stage > Business_Partner_Stage { get ; set ; } public virtual ICollection < CRM_Ticket_Transaction_Stage > CRM_Ticket_Transaction_Stage { get ; set ; } public virtual ICollection < CRM_Ticket_Transaction_Stage_Cleaned > CRM_Ticket_Transaction_Stage_Cleaned { get ; set ; } public virtual ICollection < Dim_Audit > Dim_Audit1 { get ; set ; } public virtual Dim_Audit Dim_Audit2 { get ; set ; } public virtual ICollection < Dim_Categorization > Dim_Categorization { get ; set ; } public virtual ICollection < Dim_Collection_Type > Dim_Collection_Type { get ; set ; } public virtual ICollection < Dim_Municipality > Dim_Municipality { get ; set ; } public virtual ICollection < Dim_Response_Team > Dim_Response_Team { get ; set ; } public virtual ICollection < Dim_Ticket > Dim_Ticket { get ; set ; } public virtual ICollection < Fact_Service_Units > Fact_Service_Units { get ; set ; } public virtual ICollection < Fact_Service_Units > Fact_Service_Units1 { get ; set ; } public virtual ICollection < Fact_Ticket_Processing > Fact_Ticket_Processing { get ; set ; } public virtual ICollection < Fact_Ticket_Processing > Fact_Ticket_Processing1 { get ; set ; } public virtual GIS_Collection_Stage GIS_Collection_Stage { get ; set ; } public virtual ICollection < Initial_Categories > Initial_Categories { get ; set ; } } } | Error Inside Of Visual Studio 2012 - `` ' . ' or ' ( ' expected `` |
C_sharp : Given the following C # code in which the Dispose method is called in two different ways : Once compiled using release configuration then disassembled with ildasm , the MSIL looks like this : How does a .NET decompiler such as DotPeek or JustDecompile make the difference between using and try ... finally ? <code> class Disposable : IDisposable { public void Dispose ( ) { } } class Program { static void Main ( string [ ] args ) { using ( var disposable1 = new Disposable ( ) ) { Console.WriteLine ( `` using '' ) ; } var disposable2 = new Disposable ( ) ; try { Console.WriteLine ( `` try '' ) ; } finally { if ( disposable2 ! = null ) ( ( IDisposable ) disposable2 ) .Dispose ( ) ; } } } .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 57 ( 0x39 ) .maxstack 1 .locals init ( [ 0 ] class ConsoleApplication9.Disposable disposable2 , [ 1 ] class ConsoleApplication9.Disposable disposable1 ) IL_0000 : newobj instance void ConsoleApplication9.Disposable : :.ctor ( ) IL_0005 : stloc.1 .try { IL_0006 : ldstr `` using '' IL_000b : call void [ mscorlib ] System.Console : :WriteLine ( string ) IL_0010 : leave.s IL_001c } // end .try finally { IL_0012 : ldloc.1 IL_0013 : brfalse.s IL_001b IL_0015 : ldloc.1 IL_0016 : callvirt instance void [ mscorlib ] System.IDisposable : :Dispose ( ) IL_001b : endfinally } // end handler IL_001c : newobj instance void ConsoleApplication9.Disposable : :.ctor ( ) IL_0021 : stloc.0 .try { IL_0022 : ldstr `` try '' IL_0027 : call void [ mscorlib ] System.Console : :WriteLine ( string ) IL_002c : leave.s IL_0038 } // end .try finally { IL_002e : ldloc.0 IL_002f : brfalse.s IL_0037 IL_0031 : ldloc.0 IL_0032 : callvirt instance void [ mscorlib ] System.IDisposable : :Dispose ( ) IL_0037 : endfinally } // end handler IL_0038 : ret } // end of method Program : :Main | .NET decompiler distinction between `` using '' and `` try ... finally '' |
C_sharp : When I set a DataSource on a control and want to use .ToString ( ) as DisplayMember , I need to set the DisplayMember last or the ValueMember will override it . MSDN on empty string as display member : The controls that inherit from ListControl can display diverse types of objects . If the specified property does not exist on the object or the value of DisplayMember is an empty string ( `` '' ) , the results of the object 's ToString method are displayed instead.Code to reproduce : Class : Form : You can try it by making a new form and adding 2 combobox's.Result : Conclusion and question : This can be easily fixed by setting them in the correct order however this is prone to errors , it also does not show this behavior if I use an actual property as DisplayMember instead of `` '' /ToString.I would really like to know why it displays this behavior and if I could possibly set .ToString ( ) explicitly as DisplayMember ( for code clarity ) . <code> class SomeClass { public string PartA { get ; set ; } public string PartB { get ; set ; } public string WrongPart { get { return `` WRONG '' ; } } public override string ToString ( ) { return $ '' { PartA } - { PartB } '' ; } } var testObj = new SomeClass ( ) { PartA = `` A '' , PartB = `` B '' } ; comboBox1.DataSource = new [ ] { testObj } ; comboBox1.DisplayMember = `` '' ; comboBox1.ValueMember = `` WrongPart '' ; comboBox2.DataSource = new [ ] { testObj } ; comboBox2.ValueMember = `` WrongPart '' ; comboBox2.DisplayMember = `` '' ; | Why does ValueMember override an empty DisplayMember |
C_sharp : I 'm building mobile views for an asp.net MVC4 site and have encountered a problem . We have quite a bit of places where we have a method to convert a view into a string but this method does n't seem to work with displaymodes thus always finding the default view . E.g . index.cshtml instead of index.mobile.cshtml.Any ideas to what is missing to make this code respect mobile display modes ? <code> public string RenderViewToString ( string viewName , object model ) { ViewData.Model = model ; using ( var sw = new StringWriter ( ) ) { var viewResult = ViewEngines.Engines.FindPartialView ( ControllerContext , viewName ) ; if ( viewResult.View == null ) { var message = String.Format ( `` View ' { 0 } ' not found . Searched in the following locations { 1 } . `` , viewName , String.Join ( `` , `` , viewResult.SearchedLocations ) ) ; throw new Exception ( message ) ; } var viewContext = new ViewContext ( ControllerContext , viewResult.View , ViewData , TempData , sw ) ; viewResult.View.Render ( viewContext , sw ) ; viewResult.ViewEngine.ReleaseView ( ControllerContext , viewResult.View ) ; return stripWhitespaceRx.Replace ( sw.GetStringBuilder ( ) .ToString ( ) , `` `` ) .Trim ( ) ; } } | MVC4 RenderViewToString not respecting mobile views |
C_sharp : I 've created a function to filter and sort the content of a list.It 's seems a bit 'bitty ' , however Linq is n't strong point . I 'm wondering if the function can be streamlined , either from a performance perspective or even asthetic perspective.Here 's the code : // Deserialise the XML to create a class of active rows// First - get 'direct ' agents and order them// Second - get indirect agents and order them// Bolt the 2 sublists together , retaining the orderAny thoughts on how this could be improved ? <code> var agents = XmlHelper .Deserialise < AgentConfigs > ( `` ~/Pingtree.xml '' ) .Agents .Where ( x = > x.IsActive == true ) ; var direct = agents .Where ( x = > x.IsDirect ) .OrderByDescending ( x = > x.MinPrice ) ; var agency = agents .Where ( x = > ! x.IsDirect ) .OrderBy ( x = > x.Priority ) ; Agents = direct.Concat ( agency ) .ToList ( ) ; | Combine multiple Linq Where statements |
C_sharp : I encountered a problem when I was developing a WPF application with a TabControl object . I tried to debug and find the problem and finally I 've got it , but I did n't find any workaround to it . Here is some explanation : I used this data grid filtering library ( here is a codeproject url ) , which is the best ( from my viewpoint ) . I want to customize it with the google material design theme and change some graphical features , such as using a toggle button in the first tab header of data gird to hide/show the filtering option.I created a user control and placed my custom datagrid in it . Then I embedded that control into the tabItem . When I set this control to the first tabItem , everything works correctly . But when I change the user control to the other tabItem , the toggle button does not work . Here is my main window xaml code that did n't work : Note that if I change the order of TabItems , it works well . Does anyone have a suggestion how to solve this problem ? Here is my sample project code on GithubEdit : Today , I test my application with `` WPF Inspector '' to find the structure of visual and logical tree . The behavior was too strange because when I attached `` WPF Inspector '' to my application , everything started to work . The below GIF is what I did : <code> < TabControl x : Name= '' tabControl '' > < TabItem Header= '' 1'st Tab '' > < ContentControl DataContext= '' { Binding Path=DataContext , RelativeSource= { RelativeSource AncestorType= { x : Type Window } } } '' > < Button Content= '' Do no thing '' > < /Button > < /ContentControl > < /TabItem > < TabItem Header= '' 2'nd Tab '' > < ContentControl DataContext= '' { Binding Path=DataContext , RelativeSource= { RelativeSource AncestorType= { x : Type Window } } } '' > < local : UserControl1/ > < /ContentControl > < /TabItem > < /TabControl > | Why does n't my styled ToggleButton work on the second tab of a TabControl ? |
C_sharp : I am trying to convert a block of c # to vb . I used the service at developerfusion.com to do the conversion , but when I paste it into Visual Studio , it is complaing about the `` Key '' statements ( `` Name of field or property being initialized in an object initializer must start with ' . ' `` ) .I played around with the code for a few hours trying to get around that , but everything I did only led to more errors.So I started to wonder if the conversion at developerfusion was ever correct . Here is the c # to vb.net . I am not sure where `` Key '' is coming from and was wondering if someone could enlighten me.Thanks ! FromTo <code> var combinedResults = cars.Select ( c= > new carTruckCombo { ID=c.ID , make=c.make , model=c.model } ) .Union ( tracks.Select ( t= > new carTruckCombo { ID=t.ID , make=t.make , model=t.model } ) ) ; Dim combinedResults = cars . [ Select ] ( Function ( c ) New carTruckCombo ( ) With { _Key .ID = c.ID , _Key .make = c.make , _Key .model = c.model _ } ) .Union ( tracks . [ Select ] ( Function ( t ) New carTruckCombo ( ) With { _Key .ID = t.ID , _Key .make = t.make , _Key .model = t.model _ } ) ) | c # to vb.net convsersion |
C_sharp : I have the following right now : I want to get rid of the case statement and just do something like : The case statement is HUGE and it will really cut down on readability . But because MySort is not contained in lstDMV it 's not working . Is there another way I can substitute it in ? I will of course change the text to make sure MySort variable values match exactly to the lstDMV property names.i 've also tried the following with no luck : ( <code> switch ( Mysort ) { case `` reqDate '' : lstDMV.Sort ( ( x , y ) = > DateTime.Compare ( x.RequestDate , y.RequestDate ) ) ; break ; case `` notifDate '' : lstDMV.Sort ( ( x , y ) = > DateTime.Compare ( x.NotifDate , y.NotifDate ) ) ; break ; case `` dueDate '' : lstDMV.Sort ( ( x , y ) = > String.Compare ( x.TargetDateShort , y.TargetDateShort ) ) ; break ; case `` days '' : lstDMV.Sort ( ( x , y ) = > x.DaysLapsed.CompareTo ( y.DaysLapsed ) ) ; break ; } lstDMV.Sort ( ( x , y ) = > String.Compare ( x.MySort , y.MySort ) ) ; if ( sort ! = `` '' ) { string xsort , ysort ; xsort = `` x . '' + sort ; ysort = `` y . '' + sort ; lstDMV.Sort ( ( x , y ) = > String.Compare ( xsort , ysort ) ) ; } | Using a variable in the x y sort |
C_sharp : The Sonar rule csharpsquid : S100 ( Method name should comply with a naming convention ) is thrown also for event handlers that are generated by Visual Studio , something like : Is it possible to ignore this rule for event handlers as they are auto-generated ? <code> protected void Page_Load ( object sender , EventArgs e ) { DoIt ( ) ; } | Method names for event handlers S100 |
C_sharp : Here 's the C # template code I have : I am using it like this : Is there some way that I can code PopupFrame so that the StackLayout is part of it and it takes content.Here 's what I would like to code : <code> public class PopupFrame : Frame { public PopupFrame ( ) { this.SetDynamicResource ( BackgroundColorProperty , `` PopUpBackgroundColor '' ) ; this.SetDynamicResource ( CornerRadiusProperty , `` PopupCornerRadius '' ) ; HasShadow = true ; HorizontalOptions = LayoutOptions.FillAndExpand ; Padding = 0 ; VerticalOptions = LayoutOptions.Center ; } } < t : PopupFrame > < StackLayout HorizontalOptions= '' FillAndExpand '' VerticalOptions= '' FillAndExpand '' > < t : PopupHeader Text= '' Copy Deck '' / > < t : PopupEntryHeader Text= '' New Deck Name '' / > More XAML here < /StackLayout > < /t : PopupFrame > < t : PopupFrame > < t : PopupHeader Text= '' Copy Deck '' / > < t : PopupEntryHeader Text= '' New Deck Name '' / > More XAML here < /t : PopupFrame > | How to override/modify the Content property of Frame to accept multiple Views in Xamarin.Forms ? |
C_sharp : The string `` \u1FFF : foo '' starts with \u1FFF ( or `` '' ) , right ? So how can these both be true ? Does .NET claim that this string starts with two different characters ? And while I find this very surprising and would like to understand the `` why '' , I 'm equally interested in how I can force .NET to search exclusively by codepoints instead ( using InvariantCulture does n't seem to do a thing ) ? And for comparison , one characters below that , `` \u1FFE : foo '' .StartsWith ( `` : '' ) returns false . <code> `` \u1FFF : foo '' .StartsWith ( `` : '' ) // equals true '' \u1FFF : foo '' .StartsWith ( `` \u1FFF '' ) // equals true// alternatively , the same : '' : foo '' .StartsWith ( `` : '' ) // equals true '' : foo '' .StartsWith ( `` '' ) // equals true | Why does `` \u1FFF : foo '' .StartsWith ( `` : '' ) return true ? |
C_sharp : Basically I have an entity like : and a class like : What I want to accomplish is to have vertical join two classes and have a table with row : Why I want this approach is , in my real project , I have same kind of data structure pattern occurring on multiple entries , in such case example would be the address class . It might easily appear in another entity.Is it that much hard that I can not find how to do this for days ? Closest I can get is the complex types but they do n't allow navigational properties in such case . I want to access and have my row data kind of structured and object oriented , thought EF would have a go . Any help is appreciated . <code> public class Person { public int PersonId { get ; set ; } public string Name { get ; set ; } public Address Hometown { get ; set ; } } public class Address { public City City { get ; set ; } public string Province { get ; set ; } } TB_PERSON : PersonId PK Name City_id FK Province | How do I have class properties ( with navigational props ) as entity properties ? Complex types wo n't do |
C_sharp : I am experimenting with applying Code Contracts to my code and I 've hit a perplexing problem.This code is failing to meet the contract but unless I 'm being really thick I would expect it to be able to easily analyse that id must have a value at the point of return <code> if ( id == null ) throw new InvalidOperationException ( string.Format ( `` { 0 } ' { 1 } ' does not yet have an identity '' , typeof ( T ) .Name , entity ) ) ; return id.Value ; | Is Code Contracts failing to spot obvious relationship between Nullable < T > .HasValue and null ? |
C_sharp : What is the proper way to ensure that only the 'last-in ' thread is given access to a mutex/locked region while intermediary threads do not acquire the lock ? Example sequence : *B should fail to acquire the lock either via an exception ( as in SemaphoreSlim.Wait ( CancellationToken ) or a boolean Monitor.TryEnter ( ) type construct.I can think of several similar schemes to achieve this ( such as using a CancellationTokenSource and SemaphoreSlim ) , but none of them seem particularly elegant . Is there a common practice for this scenario ? <code> A acquires lockB waitsC waitsB fails to acquire lock*A releases lockC acquires lock | Thread synchronization ( locking ) that only releases to the last-in thread |
C_sharp : Is it possible in c # to do something similar to the following ? I 'm doing some XML apis and the request objects coming in are similar to the response objects that need to go out . The above would be incredibly convenient if it were possible ; much more so than auto-mapper . <code> var tigerlist = new List < Tigers > ( ) { Tail = 10 , Teeth = 20 } ; var tigers_to_cats_approximation = new List < Cat > ( ) { foreach ( var tiger in tigerlist ) { new Cat ( ) { Tail = tiger.Tail / 2 , Teeth = tiger.Teeth / 3 , HousePet = true , Owner = new Owner ( ) { name= '' Tim '' } } } } | c # collection initializer foreach |
C_sharp : It throws an Error Pointers and fixed size buffers may only be used in an unsafe context . How do I pass pointers to the C++ dll ? I am new to C # , please help me <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Runtime.InteropServices ; namespace PatternSequencer { class Version { public string majorVersion ; public string minorVersion ; ushort* pmajorVersion ; ushort* pminorVersion ; ulong status ; [ DllImport ( @ '' c : \DOcuments\Myapp.dll '' , CallingConvention = CallingConvention.Cdecl , EntryPoint = `` SRX_DllVersion '' ) ] public static extern ulong SRX_DllVersion ( ushort* pmajorVersion , ushort* pminorVersion ) ; public Version ( ) { status = SRX_DllVersion ( & pmajorVersion , & pminorVersion ) ; if ( status ) { majorVersion = `` 1 - `` + *pmajorVersion ; minorVersion = `` 1 - `` + *pminorVersion ; } else { majorVersion = `` 0 - `` + *pmajorVersion ; minorVersion = `` 0 - `` + *pminorVersion ; } } } } | How to access a C++ function which takes pointers as input argument from a C # |
C_sharp : We have a legacy requirement to store what are now newly migrated int ID values into a guid type for use on ID-agnostic data types ( basically old code that took advantage of the `` globally unique '' part of guid in order to contain all possible IDs in one column/field ) .Due to this requirement , there was a follow-on requirement to embed the integer ID of entites into guid in a human-readable manner . This is important and is currently what is stopping me from working against the byte values directly.Currently , I have the following : It treats the visual representation of the int as a hex value ( value.ToString ( ) ) , converts that to a long ( Convert.ToInt64 ( value.ToString ( ) , 16 ) ) and the grabs the bytes from the long into a flattened byte [ ] for creating a guid in a particular structure.So given an int of 42 , when you treat 42 as a hex and convert that to an long you get 66 , and on to the bytes of 66 gives , placing into a guid gives : And an int of 379932126 gives : So the end result is to place the integer into the guid in the last 12 digits so it visually looks like the integer 42 ( even though the underlying integer value was 66 ) .This is roughly 30 % -40 % faster than constructing a string using concatenation in order to feed into the new Guid ( string ) constructor , but I feel I 'm missing the solution that avoids having to do anything with strings in the first place.The actual timings involved are quite small so as a performance improvement it probably wo n't justify the effort . This is purely for the sake of my own curiosity to see if there are faster ways of tackling this problem . I posted here as I 'm a long-standing SO user , but I 'm torn as to whether this is a code-review-ish question , though I 'm not asking for anything against my code directly , it just demonstrates what I want as output.The integer range being supplied is 0 to int.MaxValue.Update : For completeness , this is what we currently have and what I 'm testing against : My other code above is faster than this by around 30 % . <code> public static byte [ ] IntAsHexBytes ( int value ) { return BitConverter.GetBytes ( Convert.ToInt64 ( value.ToString ( ) , 16 ) ) ; } public static Guid EmbedInteger ( int id ) { var ib = IntAsHexBytes ( id ) ; return new Guid ( new byte [ ] { 0,0,0,0,0,0,1,64 , ib [ 7 ] , ib [ 6 ] , ib [ 5 ] , ib [ 4 ] , ib [ 3 ] , ib [ 2 ] , ib [ 1 ] , ib [ 0 ] } ) ; } `` 00000000-0000-4001-0000-000000000042 '' `` 00000000-0000-4001-0000-000379932126 '' string s = string.Format ( `` 00000000-0000-4001-0000- { 0 : D12 } '' , id ) ; return new Guid ( s ) ; | Treat visual representation of integer as hexadecimal to place in guid |
C_sharp : Round 100.11 to 100.15 and 100.16 to 100.20 in c # I have tried all these things but none of these helps me . <code> Math.Round ( 100.11 , 2 , MidpointRounding.AwayFromZero ) ; //gives 100.11Math.Round ( 100.11 , 2 , MidpointRounding.ToEven ) ; //gives 100.11Math.Round ( ( Decimal ) 100.11 , 2 ) //gives 100.11 ( 100.11 ) .ToString ( `` N2 '' ) ; //gives `` 100.11 '' Math.Floor ( 100.11 ) ; // gives 100.0 ( 100.11 ) .ToString ( `` # . # # '' ) ; //gives `` 100.11 '' Math.Truncate ( 100.11 ) ; // gives 100.0Math.Ceiling ( 100.11 ) ; //gives 101.0 ( 100.11 ) .ToString ( `` F4 '' ) ; // gives `` 100.1100 '' | Round 100.11 to 100.15 and 100.16 to 100.20 in c # |
C_sharp : So I have a combobox I 'd like to reuse for multiple sets of data rather than having 3 separate comboboxes . Maybe this is bad and someone can tell me so . I 'm open to all ideas and suggestions . I 'm just trying to clean up some code and thought one combobox rather than 3 was cleaner . Anyway the ItemsSource and SelectedItem all should change when another ComboBox'svalue is changed which Raises the Property Changed value for the ComboBox that is n't working . The worst part is when CurSetpoint.ActLowerModeIsTimerConditionis true it always loads the SelectedItem correctly but when going from that to CurSetpoint.ActLowerGseMode being True the combobox does n't have the SelectedItem loaded.Here is the XAML for the ComboBox with issues.Here is an image of the two combo boxes . When the Mode is change from Timer to Variable it does n't load anything despite its binding not being null and its instance and itemssource instance data not having changed . But If I go from Variable to Timer the Timer : 1 is displayed correctly.Here is the Model Code behind the Mode ComboBox 's value being changed . Along with the other two Properties that are the SelectedItems for the ComboBox in question . Along with the Properties of the ItemsSourceI 'm sure I 've probably overlooked some important info so I will update it with any questions you guys have or details you need.Update : Just wanted to add as stated in the bounty . That if what I 'm doing here is n't a good idea and there is a better way of doing it , someone with experience please just tell me why and how I should . If there are better ways and what I 'm doing is bad I just need to know . <code> < ComboBox Grid.Row= '' 1 '' Grid.Column= '' 1 '' Margin= '' 5,2 '' VerticalAlignment= '' Center '' Name= '' cmbActTimersSetpointsGseVars '' > < ComboBox.Style > < Style BasedOn= '' { StaticResource { x : Type ComboBox } } '' TargetType= '' { x : Type ComboBox } '' > < Style.Triggers > < DataTrigger Binding= '' { Binding Path=CurSetpoint.ActLowerModeIsTimerCondition } '' Value= '' True '' > < Setter Property= '' ItemsSource '' Value= '' { Binding TimerInstances } '' / > < Setter Property= '' SelectedItem '' Value= '' { Binding CurSetpoint.ActLowerTimerInstance , Mode=TwoWay } '' / > < Setter Property= '' DisplayMemberPath '' Value= '' DisplayName '' > < /Setter > < Setter Property= '' Visibility '' Value= '' Visible '' / > < /DataTrigger > < DataTrigger Binding= '' { Binding Path=CurSetpoint.ActLowerGseMode } '' Value= '' True '' > < Setter Property= '' ItemsSource '' Value= '' { Binding EnabledGseVars } '' / > < Setter Property= '' SelectedItem '' Value= '' { Binding CurSetpoint.ActLowerGseVar , Mode=TwoWay } '' / > < Setter Property= '' DisplayMemberPath '' Value= '' DisplayName '' > < /Setter > < Setter Property= '' Visibility '' Value= '' Visible '' / > < /DataTrigger > < DataTrigger Binding= '' { Binding Path=CurSetpoint.ActModeIsLogicCondition } '' Value= '' True '' > < Setter Property= '' ItemsSource '' Value= '' { Binding SetpointStates } '' / > < Setter Property= '' SelectedItem '' Value= '' { Binding CurSetpoint.ActSetpoint1State , Mode=TwoWay } '' / > < Setter Property= '' DisplayMemberPath '' Value= '' Value '' > < /Setter > < Setter Property= '' Visibility '' Value= '' Visible '' / > < /DataTrigger > < DataTrigger Binding= '' { Binding Path=CurSetpoint.ShowActLowerCmbBox } '' Value= '' False '' > < Setter Property= '' Visibility '' Value= '' Collapsed '' / > < /DataTrigger > < /Style.Triggers > < /Style > < /ComboBox.Style > < /ComboBox > private VarItem actLowerMode ; public VarItem ActLowerMode { get { return this.actLowerMode ; } set { if ( value ! = null ) { var oldValue = this.actLowerMode ; this.actLowerMode = value ; config.ActLowerMode.Value = value.ID ; //if they were n't the same we need to reset the variable name //Note : 5/21/19 Needs to be this way instead of before because when changing from Timer- > GseVariable it would n't change the config value because it //thought it was still a timer condition because the value had n't been changed yet . if ( oldValue ! = null & & ( oldValue.CheckAttribute ( `` timer '' ) ! = value.CheckAttribute ( `` timer '' ) ) ) { if ( value.CheckAttribute ( `` timer '' ) ) { ActLowerTimerInstance = model.TimerInstances.First ( ) ; } else { ActLowerVarName = `` '' ; if ( GseMode ) { ActLowerGseVar = model.EnabledGseVars.FirstOrDefault ( ) ; } } } RaisePropertyChanged ( `` ActLowerMode '' ) ; RaisePropertyChanged ( `` HasActLowerScale '' ) ; RaisePropertyChanged ( `` ActLowerGseMode '' ) ; RaisePropertyChanged ( `` HasActLowerVarName '' ) ; RaisePropertyChanged ( `` ActLowerModeIsConstant '' ) ; RaisePropertyChanged ( `` ActLowerRow1Label '' ) ; RaisePropertyChanged ( `` ActLowerModeIsTimerCondition '' ) ; RaisePropertyChanged ( `` ShowActLowerConstTextBox '' ) ; RaisePropertyChanged ( `` ShowActLowerCmbBox '' ) ; RaisePropertyChanged ( `` ShowActLowerRow1Label '' ) ; if ( GseMode ) { RaisePropertyChanged ( `` ActLowerGseMode '' ) ; } } } } private GseVariableModel actLowerGseVar ; public GseVariableModel ActLowerGseVar { get { return this.actLowerGseVar ; } set { if ( value ! = null ) { this.actLowerGseVar = value ; if ( ! ActLowerModeIsTimerCondition ) //only changing the config value if its not set to timer { config.ActLowerVarName.Value = value.Number.ToString ( ) ; } RaisePropertyChanged ( `` ActLowerGseVar '' ) ; } } } private INumberedSelection actLowerTimerInstance ; public INumberedSelection ActLowerTimerInstance { get { return this.actLowerTimerInstance ; } set { if ( value ! = null ) { this.actLowerTimerInstance = value ; config.ActLowerVarName.Value = value.Number.ToString ( ) ; RaisePropertyChanged ( `` ActLowerTimerInstance '' ) ; } } } public ObservableCollection < INumberedSelection > TimerInstances { get { return this.timerInstances ; } } public ObservableCollection < GseVariableModel > EnabledGseVars { get { return enabledGseVariables ; } } | WPF ComboBox Does n't Display SelectedItem after one DataTrigger but does for another |
C_sharp : I have a Method which accepts a Generic T classI have more than 50 types for which this method needs to be called Like thisAlthough I can do like this , but i prefer to create maybe array of Types and use for loop to call this methodSomething like this Is there a way around this ? that can also save me a lot of code and refactor things effectively ? EDIT1 : From the answers , indeed Parameters like CreateTables ( Type T ) can work , however for the second method above , is there also a possibility ? In the second it 's important that T is mentioned of type EntityData as the code in the method depends on it . <code> public void CreateTables < T > ( ) { string name = typeof ( T ) .Name ; var fields = typeof ( T ) .GetProperties ( ) .Select ( t = > new { key = t.Name.ToLower ( CultureInfo.InvariantCulture ) , value = SqLiteUtility.GetSQLiteTypeString ( t.PropertyType ) } ) .ToDictionary ( t = > t.key , t = > t.value ) ; CreateTable ( name , fields ) ; } and public void PushData < T > ( ) where T : EntityData { var data = _context.Set < T > ( ) .Where ( p = > p.Deleted == false ) .ToList ( ) ; } CreateTables < Class1 > ( ) ; PushData < Class1 > ( ) ; Type [ ] types=new Types [ ] { typeof ( Class1 ) , typeof ( Class2 ) } foreach ( var type in types ) { //call create table method CreateTables < type > ( ) ; - - this doesnt work as `` type '' is a variable used as a type } | Generic Type as a Variable |
C_sharp : For example in the following label I want to use SmallCaps , but they only show up on Windows 8 and higher . On Windows 7 , there are just normal letters.I 'm using .NET Framework 4.5 and the font is Segoe UI Medium ( and in some other labels Segoe UI Light ) , which is installed on both systems . <code> < Label x : Name= '' servername '' Typography.Capitals= '' SmallCaps '' Content= '' Server xy '' VerticalAlignment= '' Bottom '' FontSize= '' 15 '' Margin= '' 10,0,10,31 '' Padding= '' 5,0 '' FontWeight= '' Light '' Height= '' 19 '' HorizontalAlignment= '' Left '' SizeChanged= '' servername_SizeChanged '' / > | Typography.Capitals not working on Windows 7 |
C_sharp : how is a tuple different from a class ? instead of the following code , we can make a class with 3 fields and make objects from it . How is this Tuple different from that ? Is it only reducing the code we write or does it have something to do with speed as well , given the fact that you ca n't change the items in a tuple . <code> Tuple < int , string , bool > tuple = new Tuple < int , string , bool > ( 1 , `` cat '' , true ) ; | how is a tuple different from a class ? |
C_sharp : This is my first web app project . I am using VS community , asp.net , bootstrap 4 , C # and JS knockout for my view model , the server side data is coming from the company ERP SQL database using Entity Framework.The idea is that the user receives a list of items to approve from the Company ERP system , which are loaded into the View Model . The View Model is structured as a JS Knockout observable array and that each item is a JS knockout item of observables ( see full code below ) Once the user has processed the items as desired , I want the web app to post back the whole View Modal as a Json object and for the server Post Controller to take this Json object convert it to xml to send into a SQL stored procedure for insertion into the SQL database , from the SQL database the data will be handled and inserted into the ERP databaseWhen I try to action the Post I get a 405 `` Method Not Allowed '' I think that I am not receiving the Json Date from the client correctly . My thinking is because I am sending the whole model back , which is a Json list , which but My controller does not receiver a List rather a string.Can any one explain how my controller should receive the client side dataHere is my call to my Controller from the client and the server Post controller and full code listing is belowThanks View Model CodeModel ClassController Code <code> > `` tags '' : { `` ai.cloud.roleInstance '' : `` [ MYCOMPUTER ] .local '' , `` ai.operation.id '' : `` c07680cd8c845240a9e3791018c39521 '' , `` ai.operation.name '' : `` POST ReqsTests '' , `` ai.location.ip '' : `` : :1 '' , `` ai.internal.sdkVersion '' : `` web:2.8.0-241 '' , `` ai.internal.nodeName '' : `` [ MYCOMPUTER ] .local '' } , `` data '' : { `` baseType '' : `` RequestData '' , `` baseData '' : { `` ver '' : 2 , `` id '' : `` |c07680cd8c845240a9e3791018c39521.66f8d951_ '' , `` name '' : `` POST ReqsTests '' , `` duration '' : `` 00:00:00.0279394 '' , `` success '' : false , `` responseCode '' : `` 405 '' , `` url '' : `` http : //localhost:64234/api/ReqsTests/ '' , `` properties '' : { `` DeveloperMode '' : `` true '' , `` _MS.ProcessedByMetricExtractors '' : `` ( Name : 'Requests ' , Ver : ' 1.1 ' ) '' } } } } self.postAllReqs = function ( self ) { self.error ( `` ) ; // Clear error message var data = ko.toJSON ( self.Reqs ) ; // convert to json console.log ( data ) ; ajaxHelper ( reqsUri , 'POST ' , data ) .fail ( function ( jqXHR , textStatus , errorThrown ) { self.error ( errorThrown ) ; } ) ; } // POST : api/ReqsTests public IHttpActionResult PostReqsTest ( string json ) { if ( ! ModelState.IsValid ) { return BadRequest ( ModelState ) ; } XmlDocument doc = JsonConvert.DeserializeXmlNode ( json ) ; try { //SQL store procedure SqlParameter param1 = new SqlParameter ( `` @ XmlIn '' , doc ) ; db.Database.ExecuteSqlCommand ( `` exec [ CHC_Web ] . [ TestWebHandShake ] , @ XmlIn '' , param1 ) ; } catch ( Exception e ) { string message = e.Message ; return ResponseMessage ( Request.CreateErrorResponse ( HttpStatusCode.InternalServerError , message ) ) ; } return Ok ( ) ; } function ReqsTest ( rt ) { rt = rt || { } ; var self = this ; self.id = ko.observable ( rt.ID || 0 ) ; self.requisition = ko.observable ( rt.Requisition || `` '' ) ; self.reqnStatus = ko.observable ( rt.ReqnStatus || `` '' ) ; self.dateReqnRaised = ko.observable ( rt.DateReqnRaised|| null ) ; self.reqnValue = ko.observable ( rt.ReqnValue || null ) ; self.approvedValue = ko.observable ( rt.ApprovedValue || null ) ; self.originator = ko.observable ( rt.Originator || `` '' ) ; self.origName = ko.observable ( rt.OrigName || `` '' ) ; self.origEmail = ko.observable ( rt.OrigEmail || `` '' ) ; self.line = ko.observable ( rt.Line || 0.00 ) ; self.indx = ko.observable ( rt.INDX || 0 ) ; self.dateReqnRaisedL = ko.observable ( rt.DateReqnRaisedL || null ) ; self.reqStatus = ko.observable ( rt.ReqStatus || `` '' ) ; //self.reqBackground = ko.observable ( rt.ReqBackground || `` '' ) ; //Computed observables self.reqBackground = ko.computed ( function ( ) { // get variable var status = self.reqStatus ( ) ; if ( status == `` A '' ) { return `` card-heading bg-success text-white '' ; } else if ( status == `` D '' ) { return `` card heading bg-secondary '' ; } else if ( status == `` R '' ) { return `` card heading bg-warning '' ; } else if ( status == `` E '' ) { return `` card heading bg-danger '' ; } else { return `` card-heading bg-primary text-white '' ; } } ) self.reqStatusLabel = ko.computed ( function ( ) { // get variable var status = self.reqStatus ( ) ; if ( status == `` A '' ) { return `` Approved '' ; } else if ( status == `` D '' ) { return `` Declined - put on hold '' ; } else if ( status == `` R '' ) { return `` Routing On '' ; } else if ( status == `` E '' ) { return `` Erase On Syspro '' ; } else { return `` Awaiting Approval '' ; } } ) self.approvalBtn = ko.computed ( function ( ) { // get variable var status = self.reqStatus ( ) ; if ( status == `` A '' ) { return `` css : button btn-secondary `` ; } else { return `` btn btn-success `` ; } } ) self.approvalBtnLbl = ko.computed ( function ( ) { // get variable var status = self.reqStatus ( ) ; if ( status == `` W '' ) { return `` Approve '' ; } else { return `` UnApprove '' ; } } ) self.declineBtnLbl = ko.computed ( function ( ) { // get variable var status = self.reqStatus ( ) ; if ( status == `` D '' ) { return `` UnDecline '' ; } else { return `` Decline '' ; } } ) self.deleteBtnLbl = ko.computed ( function ( ) { // get variable var status = self.reqStatus ( ) ; if ( status == `` E '' ) { return `` Restore '' ; } else { return `` Erase '' ; } } ) // Functions //show details alert $ ( `` .btn '' ) .on ( `` click '' , function ( ) { $ ( `` .alert '' ) .removeClass ( `` in '' ) .show ( ) ; $ ( `` .alert '' ) .delay ( 200 ) .addClass ( `` in '' ) .fadeOut ( 2000 ) ; } ) ; } function ReqsViewModel ( ) { var self = this ; self.Reqs = ko.observableArray ( [ ] ) ; self.error = ko.observable ( ) ; var reqsUri = '/api/ReqsTests/ ' ; function ajaxHelper ( uri , method , data ) { self.error ( `` ) ; // Clear error message return $ .ajax ( { type : method , url : uri , dataType : 'json ' , contentType : 'application/json ' , data : data ? JSON.stringify ( data ) : null } ) .fail ( function ( jqXHR , textStatus , errorThrown ) { self.error ( errorThrown ) ; } ) ; } function getAllReqs ( ) { ajaxHelper ( reqsUri , 'GET ' ) .done ( function ( data ) { // Build the ReqsTest objects var reqs = ko.utils.arrayMap ( data , function ( rt ) { return new ReqsTest ( rt ) ; } ) ; self.Reqs ( reqs ) ; } ) ; } self.postAllReqs = function ( self ) { self.error ( `` ) ; // Clear error message var data = ko.toJSON ( self.Reqs ) ; // convert to json console.log ( data ) ; ajaxHelper ( reqsUri , 'POST ' , data ) .fail ( function ( jqXHR , textStatus , errorThrown ) { self.error ( errorThrown ) ; } ) ; } // Details self.detail = ko.observable ( ) ; self.getReqDetail = function ( item ) { //var url = reqsUri + item.indx ( ) ; //ajaxHelper ( url , 'GET ' ) .done ( function ( data ) { // self.detail ( data ) ; // } // ) ; self.detail ( item ) } //Approval function self.Approval = function ( item ) { var status = item.reqStatus ( ) ; if ( status == `` W '' ) { item.reqStatus ( `` A '' ) ; } else { item.reqStatus ( `` W '' ) ; } self.getReqDetail ( item ) ; } //Decline function self.Decline = function ( item ) { var status = item.reqStatus ( ) ; if ( status == `` D '' ) { item.reqStatus ( `` W '' ) ; } else { item.reqStatus ( `` D '' ) ; } self.getReqDetail ( item ) ; } //Delete function self.Delete = function ( item ) { var status = item.reqStatus ( ) ; if ( status == `` E '' ) { item.reqStatus ( `` W '' ) ; } else { item.reqStatus ( `` E '' ) ; } self.getReqDetail ( item ) ; } // Load the reqs - Take this out if you do n't want it getAllReqs ( ) ; } ko.applyBindings ( new ReqsViewModel ( ) ) ; namespace POC_Reqs_v1.Models { using System ; using System.Collections.Generic ; public partial class ReqsTest { public string ID { get ; set ; } public string Requisition { get ; set ; } public string ReqnStatus { get ; set ; } public Nullable < System.DateTime > DateReqnRaised { get ; set ; } public Nullable < decimal > ReqnValue { get ; set ; } public Nullable < decimal > ApprovedValue { get ; set ; } public string Originator { get ; set ; } public string OrigName { get ; set ; } public string OrigEmail { get ; set ; } public decimal Line { get ; set ; } public long INDX { get ; set ; } public string DateReqnRaisedL { get ; set ; } public string ReqStatus { get ; set ; } public string ReqBackground { get ; set ; } } } using System ; using System.Collections.Generic ; using System.Data ; using System.Data.Entity ; using System.Data.Entity.Infrastructure ; using System.Linq ; using System.Net ; using System.Net.Http ; using System.Threading.Tasks ; using System.Web.Http ; using System.Web.Http.Description ; using System.Xml ; using Newtonsoft.Json ; using POC_Reqs_v1.Models ; namespace POC_Reqs_v1.Controllers { public class ReqsTestsController : ApiController { private ChamberlinWebEntities db = new ChamberlinWebEntities ( ) ; // GET : api/ReqsTests public IQueryable < ReqsTest > GetReqsTests ( ) { return db.ReqsTests ; } // GET : api/ReqsTests/5 [ ResponseType ( typeof ( ReqsTest ) ) ] public async Task < IHttpActionResult > GetReqsTest ( string id ) { var ID = Convert.ToInt64 ( id ) ; ReqsTest reqsTest = await db.ReqsTests.FindAsync ( ID ) ; if ( reqsTest == null ) { return NotFound ( ) ; } return Ok ( reqsTest ) ; } // PUT : api/ReqsTests/5 [ ResponseType ( typeof ( void ) ) ] public async Task < IHttpActionResult > PutReqsTest ( string id , ReqsTest reqsTest ) { if ( ! ModelState.IsValid ) { return BadRequest ( ModelState ) ; } if ( id ! = reqsTest.ID ) { return BadRequest ( ) ; } db.Entry ( reqsTest ) .State = EntityState.Modified ; try { await db.SaveChangesAsync ( ) ; } catch ( DbUpdateConcurrencyException ) { if ( ! ReqsTestExists ( id ) ) { return NotFound ( ) ; } else { throw ; } } return StatusCode ( HttpStatusCode.NoContent ) ; } // POST : api/ReqsTests public IHttpActionResult PostReqsTest ( string json ) { if ( ! ModelState.IsValid ) { return BadRequest ( ModelState ) ; } XmlDocument doc = JsonConvert.DeserializeXmlNode ( json ) ; try { //SQL store procedure SqlParameter param1 = new SqlParameter ( `` @ XmlIn '' , doc ) ; db.Database.ExecuteSqlCommand ( `` exec [ CHC_Web ] . [ TestWebHandShake ] , @ XmlIn '' , param1 ) ; } catch ( Exception e ) { string message = e.Message ; return ResponseMessage ( Request.CreateErrorResponse ( HttpStatusCode.InternalServerError , message ) ) ; } return Ok ( ) ; } // DELETE : api/ReqsTests/5 [ ResponseType ( typeof ( ReqsTest ) ) ] public async Task < IHttpActionResult > DeleteReqsTest ( string id ) { ReqsTest reqsTest = await db.ReqsTests.FindAsync ( id ) ; if ( reqsTest == null ) { return NotFound ( ) ; } db.ReqsTests.Remove ( reqsTest ) ; await db.SaveChangesAsync ( ) ; return Ok ( reqsTest ) ; } protected override void Dispose ( bool disposing ) { if ( disposing ) { db.Dispose ( ) ; } base.Dispose ( disposing ) ; } private bool ReqsTestExists ( string id ) { return db.ReqsTests.Count ( e = > e.ID == id ) > 0 ; } } } | Converting Json Post Back Data To XML |
C_sharp : I 'm trying to understand why a specific behavior regarding variant and generics in c # does not compile.I ca n't understand why this does not work as : _lines , being of type TLine [ ] , implements IReadOnlyList < TLine > IReadOnlyList < out T > is a variant generic interface , which means , as far as I understand , that anything implementing IReadOnlyList < TLine > can be used as a IReadOnlyList < ILine > I feel that it must be because the type constraint is not taken into account , but I doubt it . <code> class Matrix < TLine > where TLine : ILine { TLine [ ] _lines ; IReadOnlyList < ILine > Lines { get { return _lines ; } } //does not compile IReadOnlyList < TLine > Lines { get { return _lines ; } } //compile } | Variant and open generics IReadOnlyList |
C_sharp : First I will explain whats happening , then what I am expecting to happen , and finally the code behind itSo whats happening is when I press enter the color of the text is greenWhat I expect to happen is the color turn redThis is based on if i type `` Bad '' into the fieldEDITI edited the code with comments to kinda put my thinking into perspective <code> //Please note I have edited uni9mportant code out//Event ListenerinputField.onEndEdit.AddListener ( delegate { VerifyWords ( ) ; } ) ; //Clss that handles the dictionarypublic abstract class WordDictionary : MonoBehaviour { public static Dictionary < string , bool > _wordDictionary = new Dictionary < string , bool > ( ) ; private void Start ( ) { _wordDictionary.Add ( `` Bad '' , true ) ; } } //Function that handles the word verificationprivate void VerifyWords ( ) { if ( openChat == false ) { //If we done have open chat bool hasBadWords = false ; //Reset boolean string [ ] stringSplit = inputField.text.Split ( ' ' ) ; //Split text string for ( int i = 0 ; i < stringSplit.Length ; i++ ) { // Go through each word in the string array if ( WordDictionary._wordDictionary.ContainsKey ( stringSplit [ i ] ) ) { //If the word is in the dictionary hasBadWords = true ; //Then there is a bad word } } if ( hasBadWords == true ) { //If a bad word was found inputField.textComponent.color = Color.red ; //Then the text should be red } else { inputField.textComponent.color = Color.green ; //The text should be green } } } | Event function not working as expected |
C_sharp : I 'm not clear what I 'm missing here . As far as I can tell I 've followed the instruction here . But my css bundle is still not getting minified.Here 's my RegisterBundles code : I 've disabled debugging in my web.config by removing the < compilation debug= '' true '' > . I can see the js getting bundled and minified : but the css is getting bundled but not minified : What am I missing here ? <code> public static void RegisterBundles ( BundleCollection bundles ) { bundles.UseCdn = true ; BundleTable.EnableOptimizations = true ; bundles.Add ( new ScriptBundle ( `` ~/bundles/otherjquery '' ) .Include ( `` ~/App_Themes/Travel2/Script/jquery-ui.min.js '' , `` ~/Scripts/jquery.validate.unobtrusive.js '' , `` ~/Scripts/jquery.unobtrusive-ajax.js '' ) ) ; Bundle availabiltyResult = new StyleBundle ( `` ~/bundles/css/availabiltyResult '' ) .Include ( `` ~/CSS/Travel2/Air.css '' , `` ~/CSS/Travel2/Air/AvailabiltyResults.css '' ) ; availabiltyResult.Transforms.Add ( new CssMinify ( ) ) ; bundles.Add ( availabiltyResult ) ; } | Why is n't my css getting minified ? |
C_sharp : In the standard .NET 4.6 compiler , the following if statement is not legal , you will get the compiler error : CS0029 Can not implicitly convert type 'UserQuery.TestClass ' to 'bool ' . This is all well and good , and I understand this.However , in Unity3d this code is perfectly legal and I have seen several examples even encouraging this Javascript style of null checking . What 's going on here and is it possible to leverage this in my non-Unity3d work in .NET ? Here is an example of legal code in Unity3D : The plot thickens ! If I attempt to compare an object that does n't derive from mono behavior , I get the expected compiler warning.Thanks to Programmer , I dug down all the way to Unity3D 's Object ( I overlooked it because I mistakenly assumed it was .NET 's actual object . ) Relevant code for the curious ( in UnityEngine.Object ) : <code> void Main ( ) { TestClass foo = new TestClass ( ) ; if ( foo ) { `` Huh . Who knew ? `` .Dump ( ) ; } } public class TestClass : Object { } using UnityEngine ; public class SampleIfBehavior : MonoBehaviour { // Use this for initialization void Start ( ) { var obj = new SampleIfBehavior ( ) ; if ( obj ) { Console.Write ( `` It was n't null . `` ) ; } } } public class TestClass { } void Start ( ) { var obj2 = new TestClass ( ) ; if ( obj2 ) // cast from TestClass to bool compiler error { } } public static implicit operator bool ( Object exists ) { return ! Object.CompareBaseObjects ( exists , ( Object ) null ) ; } public static bool operator == ( Object x , Object y ) { return Object.CompareBaseObjects ( x , y ) ; } public static bool operator ! = ( Object x , Object y ) { return ! Object.CompareBaseObjects ( x , y ) ; } | Why do if statements in Unity3d C # allow objects that are not bools ? |
C_sharp : How can I get file.txt conveniently in .NET 2.0 with C # ? What I know is split with \\ and try to get the last member.Thanks . <code> myVar = `` D : \\mainfolder\\subf1\\subf2\\subf3\\file.txt '' ; | What 's the fast way to get the file name ? |
C_sharp : The other day I needed an algorithm to turn a 2D grid into a diamond ( by effectively rotating 45 degrees ) , so I could deal with diagonal sequences as flat enumerables , like so : My algorithm is as follows : Can this be achieved in a more concise format using LINQ ? .. or even just a more concise format ? : ) <code> 1 2 3 1 4 5 6 = > 4 2 7 8 9 7 5 3 8 6 9 public static IEnumerable < IEnumerable < T > > RotateGrid < T > ( IEnumerable < IEnumerable < T > > grid ) { int bound = grid.Count ( ) - 1 ; int upperLimit = 0 ; int lowerLimit = 0 ; Collection < Collection < T > > rotated = new Collection < Collection < T > > ( ) ; for ( int i = 0 ; i < = ( bound * 2 ) ; i++ ) { Collection < T > row = new Collection < T > ( ) ; for ( int j = upperLimit , k = lowerLimit ; j > = lowerLimit || k < = upperLimit ; j -- , k++ ) { row.Add ( grid.ElementAt ( j ) .ElementAt ( k ) ) ; } rotated.Add ( row ) ; if ( upperLimit == bound ) lowerLimit++ ; if ( upperLimit < bound ) upperLimit++ ; } return rotated ; } | Turn a 2D grid into a 'diamond ' with LINQ - is it possible ? |
C_sharp : I just do n't know what to think anymore . It seems like the people who made javascript went out of their way to allow it to be written a million different ways so hackers can have a field day.I finally got my white list up by using html agility pack . It should remove As it is not in my white list plus any onclick , onmouse and etc.However now it seems you can write javascript in the attribute tags.and since I allow SRC attributes my white list ca n't help me on this . So I came up with the idea to go through all valid attributes at the end and look inside them.So it would find all my allowed attributes for every html tag ( so src , href and etc ) .I then found the innertext and put it to lowercase . I then did a index check on this string for `` javascript '' .If an index was found I started at that index and removed every character from that index on . So in the above case the attribute would be left with Src= '' '' .Now it seems that is not good enough since you can do something likejava script jav ascriptand probably a space between every letter.So I do n't know how to stop it . If it was just a space between java and script then I could just write a simple regex that did not care how many spaces between . But if it is really that you can put a space or tab or whatever after each letter then I have no clue.Then to top it off you can do all these other great ways toohttp : //ha.ckers.org/xss.htmlI know this is for some cross scripting attack ( I am not making an XSS asp.net mvc does a good job of this already ) but I do n't see why it ca n't be use for other things like like in all those examples it makes alerts so it could be used for something else.So I have no clue how to check and remove any of these.I am using C # but I do n't know how to stop any of these and do n't know of anything in C # that could help me out . <code> < scrpit > < /script > < IMG SRC= '' javascript : alert ( 'hi ' ) ; '' > < IMG SRC= & # 106 ; & # 97 ; & # 118 ; & # 97 ; & # 115 ; & # 99 ; & # 114 ; & # 105 ; & # 112 ; & # 116 ; & # 58 ; & # 97 ; & # 108 ; & # 101 ; & # 114 ; & # 116 ; & # 40 ; & # 39 ; & # 88 ; & # 83 ; & # 83 ; & # 39 ; & # 41 ; > // will work apparently < IMG SRC= & # 0000106 & # 0000097 & # 0000118 & # 0000097 & # 0000115 & # 0000099 & # 0000114 & # 0000105 & # 0000112 & # 0000116 & # 0000058 & # 0000097 & # 0000108 & # 0000101 & # 0000114 & # 0000116 & # 0000040 & # 0000039 & # 0000088 & # 0000083 & # 0000083 & # 0000039 & # 0000041 > // will work apparently < IMG SRC= '' jav ascript : alert ( 'XSS ' ) ; '' > // will work apparently < IMG SRC= '' jav & # x09 ; ascript : alert ( 'XSS ' ) ; '' > // will work apparently < IMG SRC= '' jav & # x0A ; ascript : alert ( 'XSS ' ) ; '' > // will work apparently < IMG SRC= '' jav & # x0D ; ascript : alert ( 'XSS ' ) ; '' > // will work apparently | How do you fight against all these ways ? -Javascript and its million different ways you can write it |
C_sharp : Project A ( .NET Standard 2.0 ) has a method that uses TestServer , so it has a reference to Microsoft.AspNetCore.TestHost . It is built into a NuGet package.Project B ( .NET Standard 2.0 ) has a reference to the NuGet package from A . It is also built into a NuGet package.Project C ( .NET Core 2.2 ) is an XUnit test project , that has a reference to NuGet package B . It has a single test that calls the method from A.All these projects compile successfully . But when the test from C is run , it fails with the following : If I manually add a reference to Microsoft.AspNetCore.TestHost to C , the test executes successfully . But from my understanding of .NET and how it handles transitive dependencies , this should n't be necessary.Am I wrong , or is something broken here ? <code> System.IO.FileNotFoundException : Could not load file or assembly'Microsoft.AspNetCore.TestHost , Version=2.2.0.0 , Culture=neutral , PublicKeyToken=adb9793829ddae60 ' . The system can not find the file specified . | Transitive runtime dependencies are discarded , causing runtime failure |
C_sharp : This question is for academic purposes only.Let 's assume I have the following code ... And I would like the line with the arrow to produce the same result as this ... ... without using string.Join.Is that possible ? I ca n't seem to find a LINQ statement to do it ... hopefully y'all already know ! <code> var split = line.Split ( new [ ] { ' , ' } , System.StringSplitOptions.RemoveEmptyEntries ) ; var elem = new XElement ( `` shop '' ) ; elem.SetAttributeValue ( `` name '' , split.Take ( split.Length - 1 ) ) ; < =====elem.SetAttributeValue ( `` tin '' , split.Last ( ) ) ; string.Join ( string.Empty , split.Take ( split.Length - 1 ) ) ; | Join a string [ ] Without Using string.Join |
C_sharp : Being a bit of a purist , I hate seeing string constants spread through out my code : I like to have the them stored as a single referenced constant , and I like the approach I first saw in Eric White 's XmlPowerTools : and use : The beauty of this is that I can easily find all references to these static fields using Visual Studio or Resharper and not have to wade through each found instance of the string `` Key '' , which one can imagine is used in many unrelated places.So , I have a legacy project that I want to convert to using the XName approach and need to find all occurrences of where a string has been used instead of an XName . I figure that if I could stop the automatic conversion of string to XName , the compiler would pick up all these occurrences for me.I used a regex in the find : which picked up those constructs , but then I found : and wondered what else I was going to miss.The question is , how do I stop the automatic conversion of string to XName , or what other approach is there to locating all occurrences of string that should be XName ? <code> var x = element.Attribute ( `` Key '' ) ; public class MyNamespace { public static readonly XNamespace Namespace = `` http : //tempuri.org/schema '' ; public static readonly XName Key = Namespace + `` Key '' ; } var x = element.Attribute ( MyNamespace.Key ) ; ( Element|Attribute|Ancestor ) s ? \ ( `` if ( element.Name == `` key '' ) | Can I prevent the automatic casting from string to XName ? |
C_sharp : So having a simple code in C++ . Having a C++ library with : And a swig file : After calling SWIG generator , including generated C++ and C # files into related projects and rebuilding all projects . swig.exe -c++ -csharp -namespace TestSWIG -outdir ./Sharp/TestSWIG -o ./TestSWIG.cxx TestSWIG.iWe want a simple C # .Net code to work : Yet we see that C++ implementation is the one that gets calledNow the question is : what do I do wrong so that inheritance and virtual functions do not work ? <code> class A { public : virtual void Call ( ) ; virtual void CallCall ( ) ; virtual ~A ( ) ; } ; % { # include `` A.h '' % } % include `` A.h '' % module ( directors= '' 1 '' ) TestSWIG ; % feature ( `` director '' ) A ; using System ; using TestSWIG ; namespace ASharp { class Cassa : A { public override void Call ( ) { Console.WriteLine ( `` Hello from C # '' ) ; } } class Program { private static void Main ( string [ ] args ) { var c = new Cassa ( ) ; c.CallCall ( ) ; Console.ReadLine ( ) ; } } } void A : :Call ( ) { std : :cout < < `` Hello from C++ World ! '' < < std : :endl ; } | Why SWIG C # overloads fail ? |
C_sharp : Let 's say I am doing a code-first development for a school and I have a SchoolDbContext . Most documentation on Entity Framework suggest you derive from DbContext : But my argument is SchoolDbContext is never a specialisation of DbContext , it is instead just making use of DbContext so in my opinion , SchoolDbContext should be composed of DbContext : In my composition root of an ASP.NET MVC application , I tried this composition approach by setting up my dependencies like this ( using Simple Injector as an example ) : Web.config : This fails when I try to load Students with : The entity type Student is not part of the model for the current context.When I change it back to the inheritance approach ( i.e . invoking the default constructor new SchoolDbContext ( ) ) everything works perfectly.Is my composition approach not supported by Entity Framework ? <code> public class SchoolDbContext : DbContext { public IDbSet < Student > Students = > Set < Student > ( ) ; } public class SchoolDbContext { private readonly DbContext _dbContext ; public SchoolDbContext ( DbContext dbContext ) { _dbContext = dbContext ; } public IDbSet < Student > Students = > _dbContext.Set < Student > ( ) ; } private static void RegisterDependencies ( Container container ) { // Assume I have a connection string SchoolDbContext container.Register ( ( ) = > new DbContext ( `` SchoolDbContext '' ) , Lifestyle.Scoped ) ; container.Register < SchoolDbContext > ( Lifestyle.Scoped ) ; } < connectionStrings > < add name= '' SchoolDbContext '' providerName= '' System.Data.SqlClient '' connectionString= '' Server= ( localdb ) \MSSQLLocalDB ; Integrated Security=true '' / > < /connectionStrings > | Can DbContext be composed instead of inherited ? |
C_sharp : Why does this go BOOM ? <code> using System ; using System.Linq ; namespace Test { internal class Program { private static void Main ( string [ ] args ) { try { // 1 . Hit F10 to step into debugging . string [ ] one = { `` 1 '' } ; //2 . Drag arrow to make this next statement executed // 3 . Hit f5 . Enumerable.Range ( 1,1 ) .Where ( x = > one.Contains ( x.ToString ( ) ) ) ; } catch ( Exception exception ) { Console.Write ( `` BOOM ! `` ) ; } } } } | Unintended consequences when changing next line of execution in Visual Studio |
C_sharp : I 've seen answers on constructor chaining but they do n't apply for my problem.I have a the following constructor that requires a couple of parameters : One particular client of this constructor wo n't have the values required for the parameters so I 'd like to be able to call this simple constructor which would get the required values then call the 1st constructor : Problem is , I get a red squiggly on the call to the 2nd constructor with the message SerilogHelper is a 'type ' but used like a 'variable ' <code> public SerilogHelper ( string conString , int minLevel ) { var levelSwitch = new LoggingLevelSwitch ( ) ; levelSwitch.MinimumLevel = ( Serilog.Events.LogEventLevel ) ( Convert.ToInt32 ( minLevel ) ) ; _logger = new LoggerConfiguration ( ) .MinimumLevel.ControlledBy ( levelSwitch ) .WriteTo.MSSqlServer ( connectionString : conString , tableName : `` Logs '' , autoCreateSqlTable : true ) .CreateLogger ( ) ; } public SerilogHelper ( ) { string minLevel = SSOSettingsFileManager.SSOSettingsFileReader.ReadString ( `` LCC.Common '' , `` serilog.level '' ) ; string conString = SSOSettingsFileManager.SSOSettingsFileReader.ReadString ( `` LCC.Common '' , `` serilog.connectionstring '' ) ; SerilogHelper ( conString , minLevel ) ; } | C # constructor to call constructor after executing code |
C_sharp : For example if in a textbox that is full of many different part numbers from a material list for computer parts , I only want one type of cat5 cable at any given time , and if two different types are seen , to warn the user . The cat5 cable part numbers could be : cat5PART # 1 , cat5PART # 2 , and cat5PART # 3 . So if only one cat5 part number is seen no worries , but as soon as two different types or more are seen , to warn . I could easily write it out manually three different times for each variation , but on a larger list of parts , it would take longer and risk mistakes . Plus I 'd just love to know how programmers handle this type of function . I also do n't know what it is called so I 'm not sure how to google for it , despite knowing there are going to be many solutions for this exact situation out there so it is frustrating to have to bug people on a forum for something so simple . An example of my code which obviously does n't work because it would only warn if all three parts were detected not just if two were detected is below . I assume I 'd use some variation of & and | or maybe it 's something completely different ? Basically I do n't want to have to write out on a larger scale if contains part 1 and part 2if contains part 1 and part 3if contains part 2 and part 3Thank you . <code> if ( ( textBox2.Text.Contains ( `` PART # 1 '' ) ) & & ( textBox2.Text.Contains ( `` PART # 2 '' ) ) & & ( textBox2.Text.Contains ( `` PART # 3 '' ) ) ) { MessageBox.Show ( `` 2 types of cat5 part numbers seen at the same time '' ) ; } | How to avoid writing every variation of a simple `` if contains '' statement for different strings |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.