lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
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 stoppe...
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...
Comparison to null evaluates to true for both expr == null and expr ! = null
C#
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 ?
void Foo ( params string [ ] parameters ) { } void Foo ( string firstParameter , params string [ ] parameters ) { }
More or less equal overloads
C#
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 ...
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 ( ) ;...
Entity Framework - concurrent use of containers
C#
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 ?
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#
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 :
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...
Get and Add/Update multilevel embedded/nested MongoDB document using C #
C#
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...
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...
Why C # using same memory address in this case ?
C#
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 save...
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#
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...
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...
Optimizing an algorithm and/or structure in C #
C#
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 # speci...
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 ...
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#
Let see at this class : why I can access private field ? Can I use this feature or may be it is bad practice ?
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#
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 ...
< 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 : //...
XAML UWA Scrollbar not showing
C#
Is there a better way to do these assignments with LINQ ?
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#
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 Sub...
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#
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...
Window d = new Window ( ) ; //d.ShowDialog ( ) ;
Program does n't stop after new Window
C#
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 unt...
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.T...
EntityFramework update fails randomly on SaveChanges / ASP.NET MVC / postbacks
C#
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 !
//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 requi...
please explain the use of `` default ( ) '' in this code
C#
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 ?
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#
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 > ( ) ;
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#
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 con...
[ 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#
Consider the following code.Calling Task.Run and then Result in the static initializer causes the program to permanently freeze . Why ?
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#
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 ?
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 ...
Why is the base class being called ?
C#
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 vid...
public static IAsyncOperation < IStorageFile > ConcatenateVideoRT ( [ ReadOnlyArray ] IStorageFile [ ] videoFiles , IStorageFolder outputFolder , string outputfileName ) { return Task.Run < IStorageFile > ( async ( ) = > { IStorageFile _OutputFile = await outputFolder.CreateFileAsync ( outputfileName , CreationCollisio...
Windows Phone 8.1 MediaComposition - Audio Too Fast When Stitching Videos
C#
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 ?
# define x 'liaM ' uint m = x ;
Single quoted string to uint in c #
C#
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 t...
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 . `` ) ;...
novice inheritance question
C#
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 .
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 ; } r...
Something similar to sql IN statement within .NET framework ?
C#
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 :
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 .OfT...
How do I retrieve all ( and only ) class variables ?
C#
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 a...
public enum MyButtons { Button1 = 1 , Button2 = 2 , Button3 = 3 , Button4 = 4 , Button5 = 5 , Button6 = 6 }
Use TinyInt to hide/show controls ?
C#
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 eleme...
[ 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 '...
How to make a UI-MarkupExtension
C#
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 ?
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#
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...
MathInputControl mic = new MathInputControlClass ( ) ; mic.EnableExtendedButtons ( true ) ; mic.Show ( ) ;
Is it possible to cast a .NET class into a COM library class ?
C#
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...
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 ...
Is there a `` split list '' method in c # ?
C#
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 y...
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#
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 n...
Console.WriteLine ( `` { 0 } : { 1 } : { 2 } '' , `` foo '' , `` bar '' , `` baz '' ) ;
Which methods in the 3.5 framework have a String.Format-like signature ?
C#
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 ins...
var oneOverNine = 1d / 9d ; var resultTimesNine = oneOverNine * 9d ;
Why does n't 0.9 recurring always equal 1
C#
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...
< ? 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...
How to generate closing nodes in a file that is not a valid xml file ?
C#
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 NullableC...
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 ; inte...
Why Nullable < T > is treated special by PropertyInfo.SetValue
C#
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 ?
< 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 > < /Phr...
Parse number with cortana
C#
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 fo...
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#
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 m...
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 ) ; downloade...
How Can I Use DownloadProgressChangedEventHandler in asp.net mvc ?
C#
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...
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#
I expect the output of 1 and 11 but I 'm getting 1 and 98 . What am I missing ?
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#
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 ?
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 ...
Trouble using the ref keyword . Very newbie question !
C#
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 no...
{ 1,3,4,5,5,6,7,7 }
How to determine duplicates in a collection of ints ?
C#
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 < ...
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 versio...
Wrap T in Nullable < T > via Reflection
C#
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 ...
using ( var context = new AppDbContext ( ) ) { // ... }
How to use DbContext with DI in desktop applications ?
C#
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 ge...
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 ) , hel...
C # Enum in a C++ Library
C#
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 str...
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 = TextBoxPosit...
Casting Error : Inserting data into Custom MembershipUser
C#
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 ?
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#
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 ...
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 [ ...
Need help with algorithm to resolve index through jagged array
C#
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 t...
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 r...
Standardization with Interface in .Net
C#
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...
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 . C...
when is reading and writing to memory legal ?
C#
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 ...
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 dispo...
Creating a simple Async Workflow Activity
C#
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
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 ( ) .ToDictionar...
Linq to Dictionary with key and a list
C#
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 ha...
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#
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 , beca...
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 ...
Is it possible to combine a GroupBy and Select to get a proper named Key ?
C#
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 w...
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#
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 th...
[ 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 ( WizardViewMo...
A created a new CustomModelBinder from one that already worked . Why does the new one never get called to do any binding ?
C#
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 ...
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 v...
How/Why does ref return for instance members
C#
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...
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#
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 sens...
// 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 ] F...
What is the difference between these LINQ queries
C#
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
myContext.Products.AsNoTracking ( ) .Count ( ) ; myContext.Products.Count ( ) ;
Does adding AsNoTracking in Entity Framework impact a Count ?
C#
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 ?
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#
& 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 :
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...
Error Inside Of Visual Studio 2012 - `` ' . ' or ' ( ' expected ``
C#
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 ?
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 ! = nul...
.NET decompiler distinction between `` using '' and `` try ... finally ''
C#
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 e...
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...
Why does ValueMember override an empty DisplayMember
C#
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 i...
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 . Se...
MVC4 RenderViewToString not respecting mobile views
C#
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 r...
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 (...
Combine multiple Linq Where statements
C#
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 ( fro...
< 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...
Why does n't my styled ToggleButton work on the second tab of a TabControl ?
C#
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 wit...
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.ma...
c # to vb.net convsersion
C#
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 t...
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.TargetDate...
Using a variable in the x y sort
C#
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 ?
protected void Page_Load ( object sender , EventArgs e ) { DoIt ( ) ; }
Method names for event handlers S100
C#
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 :
public class PopupFrame : Frame { public PopupFrame ( ) { this.SetDynamicResource ( BackgroundColorProperty , `` PopUpBackgroundColor '' ) ; this.SetDynamicResource ( CornerRadiusProperty , `` PopupCornerRadius '' ) ; HasShadow = true ; HorizontalOptions = LayoutOptions.FillAndExpand ; Padding = 0 ; VerticalOptions = L...
How to override/modify the Content property of Frame to accept multiple Views in Xamarin.Forms ?
C#
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 e...
`` \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#
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 . ...
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#
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
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#
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 ( ) ...
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#
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 .
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#
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
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 : \D...
How to access a C++ function which takes pointers as input argument from a C #
C#
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-o...
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...
Treat visual representation of integer as hexadecimal to place in guid
C#
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 .
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 ( `` # ....
Round 100.11 to 100.15 and 100.16 to 100.20 in c #
C#
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 Sele...
< 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= '' { Bindi...
WPF ComboBox Does n't Display SelectedItem after one DataTrigger but does for another
C#
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 an...
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 ...
Generic Type as a Variable
C#
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 .
< 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#
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 tup...
Tuple < int , string , bool > tuple = new Tuple < int , string , bool > ( 1 , `` cat '' , true ) ;
how is a tuple different from a class ?
C#
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 loade...
> `` 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 '' : `` [ MYCOMP...
Converting Json Post Back Data To XML
C#
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 , t...
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#
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 pu...
//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 > ( ...
Event function not working as expected
C#
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...
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/...
Why is n't my css getting minified ?
C#
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 ...
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 ...
Why do if statements in Unity3d C # allow objects that are not bools ?
C#
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 .
myVar = `` D : \\mainfolder\\subf1\\subf2\\subf3\\file.txt '' ;
What 's the fast way to get the file name ?
C#
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 ? : )
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...
Turn a 2D grid into a 'diamond ' with LINQ - is it possible ?
C#
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 , o...
< 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 app...
How do you fight against all these ways ? -Javascript and its million different ways you can write it
C#
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 p...
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#
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 !
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....
Join a string [ ] Without Using string.Join
C#
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 V...
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 ...
Can I prevent the automatic casting from string to XName ?
C#
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...
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 ( ) { Con...
Why SWIG C # overloads fail ?
C#
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 ...
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 > (...
Can DbContext be composed instead of inherited ?
C#
Why does this go BOOM ?
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.Conta...
Unintended consequences when changing next line of execution in Visual Studio
C#
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 t...
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 ( connectionStrin...
C # constructor to call constructor after executing code
C#
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 ...
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