text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : Overloading the comparison operator , how to compare if the two variables points to the same object ( i.e . not value ) <code> public static bool operator == ( Landscape a , Landscape b ) { return a.Width == b.Width & & a.Height == b.Height ; } public static bool operator ! = ( Landscape a , Landscape b ) { return ! ( a.Width == b.Width & & a.Height == b.Height ) ; } | After overloading the operator== , how to compare if two variables points at the same object ? |
C_sharp : Pretty basic question , but I ca n't seem to find the answer anywhere.How do you specify a new instance of a Dictionary < string , string > in SOAP ? Basically I have this envelope ( ommitted envelope top level tag for readability ) : RequestInfo is the property in question , but it 's always null . I assumed that just the presence of the property in the envelope would be deserialized into an empty Dictionary < string , string > , however this is not the case . <code> < soapenv : Body > < tem : LogInWithCredentials > < tem : Request > < ttf1 : Password > password < /ttf1 : Password > < ttf1 : UserName > username < /ttf1 : UserName > < ttf1 : RequestInfo > < /ttf1 : RequestInfo > < /tem : Request > < /tem : LogInWithCredentials > < /soapenv : Body > | Creating a new Dictionary in a SOAP Envelope |
C_sharp : Why is it necessary to use the new keyword when a method shall be hidden ? I have two classes : Following code produces the given output : Output : ParentOutput : ChildI understand that this might be a problem if it the hiding was not intended but is there any other reason to use `` new '' ( excepted avoding of warnings ) ? Edit : May be I was not clear . It is the same situation like : which is called : <code> public class Parent { public void Print ( ) { Console.WriteLine ( `` Parent '' ) ; } } public class Child : Parent { public void Print ( ) { Console.WriteLine ( `` Child '' ) ; } } Parent sut = new Child ( ) ; sut.Print ( ) ; Child sut = new Child ( ) ; sut.Print ( ) ; public void foo ( Parent p ) { p.Print ( ) ; } Child c = new Child ; foo ( c ) ; c | Why using `` new '' when hiding methods ? |
C_sharp : With this code : ... I 'm stopped dead in my tracks with So how do I accomplish this ? <code> private bool AtLeastOnePlatypusChecked ( ) { return ( ( ckbx1.IsChecked ) || ( ckbx2.IsChecked ) || ( ckbx3.IsChecked ) || ( ckbx4.IsChecked ) ) ; } Operator '|| ' can not be applied to operands of type 'bool ? ' and 'bool ? | How can I return a bool value from a plethora of nullable bools ? |
C_sharp : I am working on trying to close a specific MessageBox if it shows up based on the caption and text . I have it working when the MessageBox does n't have an icon.The above code works just fine when the MessageBox is shown without an icon like the following.However , if it includes an icon ( from MessageBoxIcon ) like the following , it does n't work ; GetWindowTextLength returns 0 and nothing happens.My best guess is that the 3rd and/or 4th paramters of FindWindowEx need to change but I 'm not sure what to pass instead . Or maybe the 2nd parameter needs to change to skip the icon ? I 'm not really sure . <code> IntPtr handle = FindWindowByCaption ( IntPtr.Zero , `` Caption '' ) ; if ( handle == IntPtr.Zero ) return ; //Get the Text window handleIntPtr txtHandle = FindWindowEx ( handle , IntPtr.Zero , `` Static '' , null ) ; int len = GetWindowTextLength ( txtHandle ) ; //Get the textStringBuilder sb = new StringBuilder ( len + 1 ) ; GetWindowText ( txtHandle , sb , len + 1 ) ; //close the messageboxif ( sb.ToString ( ) == `` Original message '' ) { SendMessage ( new HandleRef ( null , handle ) , WM_CLOSE , IntPtr.Zero , IntPtr.Zero ) ; } MessageBox.Show ( `` Original message '' , `` Caption '' ) ; MessageBox.Show ( `` Original message '' , `` Caption '' , MessageBoxButtons.OK , MessageBoxIcon.Information ) ; | How to get the text of a MessageBox when it has an icon ? |
C_sharp : On the form called `` Dev '' I have the following OnFormClosing function to make sure a thread is closed properly when a user closes the form.Works fine if I close the `` Dev '' form directly . But if the `` Dev '' form closes because the main form ( `` Form1 '' ) was closed ( which causes the program to exit ) the OnFormClosing ( ) function in `` Dev '' is never called , so the thread keeps on running and the program ' process needs to be killed via task manager.How do I fix this ? I realise I could add an OnFormClosing ( ) function to `` Form1 '' which then calls the OnFormClosing ( ) function in `` Dev '' , but I was hoping for something a bit more clean.Update : Dev form is opened from the main form : The main form is really called `` programname.UI.Main '' ( I know right.. ) and it is opened in `` Program.cs '' ( so the program 's entry point ) : <code> protected override void OnFormClosing ( FormClosingEventArgs e ) { base.OnFormClosing ( e ) ; dev.stopMultipleColorsWatcher ( ) ; } private void btn_opendev_Click ( object sender , EventArgs e ) { Dev frm = new Dev ( ) ; frm.Show ( ) ; } static void Main ( ) { Application.EnableVisualStyles ( ) ; Application.SetCompatibleTextRenderingDefault ( false ) ; Application.Run ( new programname.UI.Main ( ) ) ; } | Forms not closing properly if terminated due to program exit / main form close |
C_sharp : I have an action method like this below.I have a model with the following classes , which I 'd like to load the data from the ajax JSON data . Here is the JSON data . DefaultModelBinder is handling the nested object structure but it ca n't resolve the different sub classes . What would be the best way to load List with the respective sub-classes ? <code> [ AcceptVerbs ( HttpVerbs.Post ) ] public ActionResult Create ( Form newForm ) { ... } public class Form { public string title { get ; set ; } public List < FormElement > Controls { get ; set ; } } public class FormElement { public string ControlType { get ; set ; } public string FieldSize { get ; set ; } } public class TextBox : FormElement { public string DefaultValue { get ; set ; } } public class Combo : FormElement { public string SelectedValue { get ; set ; } } { `` title '' : `` FORM1 '' , `` Controls '' : [ { `` ControlType '' : `` TextBox '' , `` FieldSize '' : `` Small '' , '' DefaultValue '' : '' test '' } , { `` ControlType '' : `` Combo '' , `` FieldSize '' : `` Large '' , `` SelectedValue '' : '' Option1 '' } ] } $ .ajax ( { url : ' @ Url.Action ( `` Create '' , `` Form '' ) ' , type : 'POST ' , dataType : 'json ' , data : newForm , contentType : 'application/json ; charset=utf-8 ' , success : function ( data ) { var msg = data.Message ; } } ) ; | DefaultModelBinder and collection of inherited objects |
C_sharp : I 'm trying to implement something like the idea I 'm trying to show with the following diagram ( end of the question ) .Everything is coded from the abstract class Base till the DoSomething classes.My `` Service '' needs to provide to the consumer `` actions '' of the type `` DoSomethings '' that the service has `` registered '' , at this point I am seeing my self as repeating ( copy/paste ) the following logic on the service class : I would like to know if there is anyway in C # to `` register '' all the `` DoSomething '' I want in a different way ? Something more dynamic and less `` copy/paste '' and at the same time provide me the `` intellisense '' in my consumer class ? Somekind of `` injecting '' a list of accepted `` DoSomething '' for that service.Update # 1After reading the sugestion that PanagiotisKanavos said about MEF and checking other options of IoC , I was not able to find exactly what I am looking for . My objective is to have my Service1 class ( and all similar ones ) to behave like a DynamicObject but where the accepted methods are defined on its own constructor ( where I specify exactly which DoSomethingX I am offering as a method call . Example : I have several actions ( DoSomethingX ) as `` BuyCar '' , `` SellCar '' , `` ChangeOil '' , `` StartEngine '' , etc ... . Now , I want to create a service `` CarService '' that only should offer the actions `` StartEngine '' and `` SellCar '' , while I might have other `` Services '' with other combination of `` actions '' . I want to define this logic inside the constructor of each service . Then , in the consumer class , I just want to do something like : And I want to offer intellisense when I use the `` CarService '' ... .In conclusion : The objective is how to `` register '' in each Service which methods are provided by him , by giving a list of `` DoSomethingX '' , and automatically offer them as a `` method '' ... I hope I was able to explain my objective/wish.In other words : I just want to be able to say that my class Service1 is `` offering '' the actions DoSomething1 , DoSomething2 and DoSomething3 , but with the minimum lines as possible . Somehow the concept of the use of class attributes , where I could do something similar to this : <code> public async Task < Obj1 < XXXX > > DoSomething1 ( ... .params ... . ) { var action = new DoSomething1 ( contructParams ) ; return await action.Go ( ... .params ... . ) ; } var myCarService = new CarService ( ... paramsX ... ) ; var res1 = myCarService.StartEngine ( ... paramsY ... ) ; var res2 = myCarService.SellCar ( ... paramsZ ... ) ; // THEORETICAL CODE [ RegisterAction ( typeOf ( DoSomething1 ) ) ] [ RegisterAction ( typeOf ( DoSomething2 ) ) ] [ RegisterAction ( typeOf ( DoSomething3 ) ) ] public class Service1 { // NO NEED OF EXTRA LINES ... . } | C # how to `` register '' class `` plug-ins '' into a service class ? |
C_sharp : I 'm writing custom security attribute and got strange compiler behaviour ... When I 'm using the attribute at the same file , default parameter values works fine : But when I 'm separating the code above into two files like that - file 1 : And file 2 : I 've got an compiler error : Error : 'FooAttribute ' does not contain a constructor that takes 0 argumentsThis occurs only with the CodeAccessSecurityAttribute inheritors , looks very strange ... <code> using System.Security.Permissions ; [ System.Serializable ] sealed class FooAttribute : CodeAccessSecurityAttribute { public FooAttribute ( SecurityAction action = SecurityAction.Demand ) : base ( action ) { } public override System.Security.IPermission CreatePermission ( ) { return null ; } } [ Foo ] class Program { static void Main ( string [ ] args ) { } } using System.Security.Permissions ; [ System.Serializable ] sealed class FooAttribute : CodeAccessSecurityAttribute { public FooAttribute ( SecurityAction action = SecurityAction.Demand ) : base ( action ) { } public override System.Security.IPermission CreatePermission ( ) { return null ; } } [ Foo ] class Program { static void Main ( string [ ] args ) { } } | Is this an C # 4.0 compiler optional parameters bug ? |
C_sharp : Why is n't it possible to cast an instance of : ... to this interface : ... even though Foo has the signature of IBar ? How can I turn an instance of Foo into an IBar ? Assume I have no control over Foo . <code> sealed class Foo { public void Go ( ) { } } interface IBar { void Go ( ) ; } | Possible to cast to interface that is n't inherited ? |
C_sharp : i have a stupid question , but i want to hear the community here.So here is my code : My question , is it any different than : Which one is better in general ? which one in terms of GC and why ? <code> using ( FtpWebResponse response = ( FtpWebResponse ) request.GetResponse ( ) ) { return true ; } ( FtpWebResponse ) request.GetResponse ( ) ; return true ; | Do I need to dispose of a resource which is not actually used ? |
C_sharp : Consider the following piece of code : As you can see we are on line 28 . Is there any way to see the return value of the function at this point , without letting the code return to the caller function ? Foo.Bar ( ) is a function call which generates a unique path ( for example ) . So it 's NOT constant.Entering ? Foo.Bar ( ) in the immidiate window does n't work either , since that reevaluates the code : In VB.NET it 's possible by entering the function 's name in the Watch , which will then threat it as a variable.But in C # this is not possible , any other tips ? PS : rewriting is not an option . <code> ? Foo.Bar ( ) '' 80857466 '' ? Foo.Bar ( ) '' 2146375101 '' ? Foo.Bar ( ) '' 1106609407 '' ? Foo.Bar ( ) '' 792759112 '' | See return value in C # |
C_sharp : I happened upon this in an NHibernate class definition : So this class inherits from a base class that is parameterized by ... the derived class ? My head just exploded . Can someone explain what this means and how this pattern is useful ? ( This is NOT an NHibernate-specific question , by the way . ) <code> public class SQLiteConfiguration : PersistenceConfiguration < SQLiteConfiguration > | C # unusual inheritance syntax w/ generics |
C_sharp : Say I have the following : Two Questions:1.I 'm a little confused on when my IDisposable members would actually get called . Would they get called when an instance of CdsUpperAlarmLimit goes out of scope ? 2.How would I handle disposing of objects created in the CdsUpperAlarmLimit class ? Should this also derive from IDisposable ? <code> public abstract class ControlLimitBase : IDisposable { } public abstract class UpperAlarmLimit : ControlLimitBase { } public class CdsUpperAlarmLimit : UpperAlarmLimit { } | IDisposable Question |
C_sharp : Consider this code : Results : Why are the results different between List < T > and Array ? I guess this is by design , but why ? Looking at the code of List < T > .IndexOf makes me wonder even more , since it 's porting to Array.IndexOf . <code> public static void Main ( ) { var item = new Item { Id = 1 } ; IList list = new List < Item > { item } ; IList array = new [ ] { item } ; var newItem = new Item { Id = 1 } ; var lIndex = list.IndexOf ( newItem ) ; var aIndex = array.IndexOf ( newItem ) ; Console.WriteLine ( lIndex ) ; Console.WriteLine ( aIndex ) ; } public class Item : IEquatable < Item > { public int Id { get ; set ; } public bool Equals ( Item other ) = > other ! = null & & other.Id == Id ; } 0-1 | Why is Array.IndexOf not checking for IEquatable like List < T > does ? |
C_sharp : I wanted to create an observableCollection that is sortableso i started creating a class that inherit observable with some methods to sort it , then i wanted that class to persist the index into the childs , so i created an interface that expose an index property where i can write to , and i costrainted the T of my collection class to be of my Interface , then i wanted to be able from avery item to access the parentCollection and here the problems started because the type of the parent collection is generic ... i 've tried many solutions , and i think covariance or invariance is the way , but i ca n't get it working ... this is more or less the setup.I 'd like to be able to create a SortableCollection < DerivedClass > but the types mismatch ... wich is the correct way of doing it ? exact error is Error 1 The type 'ClassLibrary1.DerivedClass ' can not be used as type parameter 'T ' in the generic type or method 'ClassLibrary1.SortableCollection < T > ' . There is no implicit reference conversion from 'ClassLibrary1.DerivedClass ' to 'ClassLibrary1.ISortable < ClassLibrary1.DerivedClass > ' . c : \users\luigi.trabacchin\documents\visual studio 2013\Projects\ClassLibrary1\ClassLibrary1\Class1.cs 48 89 ClassLibrary1 <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace ClassLibrary1 { public class SortableCollection < T > : System.Collections.ObjectModel.ObservableCollection < T > , ISortableCollection < T > where T : ISortable < T > { public void Sort ( ) { //We all know how to sort something throw new NotImplementedException ( ) ; } protected override void InsertItem ( int index , T item ) { item.Index = index ; item.ParentCollection = this ; base.InsertItem ( index , item ) ; } } public interface ISortableCollection < T > : IList < T > { void Sort ( ) ; } public interface ISortable < T > { Int32 Index { get ; set ; } ISortableCollection < T > ParentCollection { get ; set ; } } public class BaseClass : ISortable < BaseClass > { public int Index { get ; set ; } public ISortableCollection < BaseClass > ParentCollection { get ; set ; } } public class DerivedClass : BaseClass { } public class Controller { SortableCollection < BaseClass > MyBaseSortableList = new SortableCollection < BaseClass > ( ) ; SortableCollection < DerivedClass > MyDerivedSortableList = new SortableCollection < DerivedClass > ( ) ; public Controller ( ) { //do things } } } | Covariance in generic interfaces |
C_sharp : I 'm trying to use a Microsoft.Toolkit.Wpf.UI.Controls.WebView control in a wpf desktop application . It seems to use substantially less resouces than the webbrowser control and is much more up to date , being based on edge . However , unlike the webbrowser control , it wo n't scroll unless selected . i.e . When the mouse is over the webbrowser I can scroll up and down without selecting first but webview ignores the mouse wheel if it is n't the current selected control.Using VS2019 the following code demonstrates the problem.On running , both browser controls will scroll when the mouse cursor is over . After clicking the button ( removing the focus from either of the browsers ) , only the webbrowser control scrolls on mouseover.Is there any workaround to fix this ? Using : .NET Framework 4.7.2 and Microsoft.Toolkit.Wpf.UI.Controls.WebView 5.1.1 <code> < Window x : Class= '' test0.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : WPF= '' clr-namespace : Microsoft.Toolkit.Wpf.UI.Controls ; assembly=Microsoft.Toolkit.Wpf.UI.Controls.WebView '' Title= '' MainWindow '' Height= '' 600 '' Width= '' 1024 '' > < Grid > < StackPanel > < Button Content= '' hello world '' Height= '' 100 '' / > < WPF : WebView Source= '' https : //bing.com '' Height= '' 250 '' / > < WebBrowser Source= '' https : //bing.com '' Height= '' 250 '' / > < /StackPanel > < /Grid > < /Window > | how to make wpf webview scroll like webbrowser ? |
C_sharp : Why is it not possible to use implicit conversion when calling an extension method ? Here is the sample code : Error i get : 'int ' does not contain a definition for 'ToNumberString ' and the best extension method overload 'Ext.ToNumberString ( decimal ) ' requires a receiver of type 'decimal'As we can see . An implicit conversion from int to decimal exists and works just fine when we do not use it as an extension method . I know what I can do to get things working , But what is the technical reason that there is no implicit cast possible when working with extension methods ? <code> using System ; namespace IntDecimal { class Program { static void Main ( string [ ] args ) { decimal d = 1000m ; int i = 1000 ; d = i ; // implicid conversion works just fine Console.WriteLine ( d.ToNumberString ( ) ) ; // Works as expected Console.WriteLine ( i.ToNumberString ( ) ) ; // Error Console.WriteLine ( ToNumberString2 ( i ) ) ; // Implicid conversion here works just fine } static string ToNumberString2 ( decimal d ) { return d.ToString ( `` N0 '' ) ; } } public static class Ext { public static string ToNumberString ( this decimal d ) { return d.ToString ( `` N0 '' ) ; } } } | Implicit conversion when calling an extension method not possible |
C_sharp : Often I have a bit of code I want to execute from time to time , for example seed the database , drop the database , download some data from the database and collate it in some funny way . All of these tasks can be represented as independent functions in C # . Ala a console app : Here , I comment out the function I do n't want to call , and run the function I do want to call . Compile and wait for results.I 'm looking for a way to streamline this process . For example in unit testing you can right click a function and through some magic execute just that function directly from Visual Studio . Maybe there is an extension that does just this , but I have n't been able to find it . Best way I know of cleaning this so far , is to make snippets in LinqPad . But I feel like I should be able to do this directly from Visual Studio . <code> class Program { static void Task1 ( ) { } static void Task2 ( ) { } static void Main ( ) { //Task1 ( ) ; //Task2 ( ) ; } } | Is there any extension to visual studio that allows to run functions as tasks ? |
C_sharp : I have a partial view that is using a different model than the view that I 'm rendering it in . I keep getting the error message . The model item passed into the dictionary is of type 'JHelpWebTest2.Models.CombinedModels ' , but this dictionary requires a model item of type 'JHelpWebTest2.Models.PagedStudentModel'.I 'm not sure how to fix this here is some of my code.My Index view : Here is my _Grid partial viewThis is the CombinedModel : This is my model for PagedStudentModelCan anyone tell me what I 'm doing wrong ? <code> @ using System.Activities.Expressions @ using JHelpWebTest2.Models @ model JHelpWebTest2.Models.CombinedModels @ using ( Html.BeginForm ( `` _Grid '' , `` Sort '' ) ) { @ Html.Partial ( `` ~/Views/Sort/_Grid.cshtml '' ) } @ model JHelpWebTest2.Models.PagedStudentModel @ using JHelpWebTest2.Models ; < div id= '' grid '' > @ { var grid1 = new WebGrid ( rowsPerPage : Model.PageSize , defaultSort : `` YR_CDE '' , ajaxUpdateContainerId : `` grid '' ) ; grid1.Bind ( Model.Studentcrshist , autoSortAndPage : false , rowCount : Model.TotalRows ) ; grid1.Pager ( WebGridPagerModes.All ) ; } @ grid1.GetHtml ( tableStyle : `` webGrid '' , headerStyle : `` header '' , alternatingRowStyle : `` alt '' , mode : WebGridPagerModes.All , firstText : `` < < First '' , previousText : `` < Prev '' , nextText : `` Next > '' , lastText : `` Last > > '' , columns : grid1.Columns ( grid1.Column ( `` YR_CDE '' , `` YR_CDE '' ) , grid1.Column ( `` TRM_CDE '' , `` TRM_CDE '' ) , grid1.Column ( `` SUBTERM_CDE '' , `` SUBTERM_CDE '' ) , grid1.Column ( `` CRS_CDE '' , `` CRS_CDE '' ) , grid1.Column ( `` CRS_DIV '' , `` CRS_DIV '' ) , grid1.Column ( `` CREDIT_HRS '' , `` CREDIT_HRS '' ) , grid1.Column ( `` CRS_TITLE '' , `` CRS_TITLE '' ) , grid1.Column ( `` ADD_FLAG '' , `` ADD_FLAG '' ) , grid1.Column ( `` ADD_DTE '' , `` ADD_DTE '' , format : ( model = > model.ADD_DTE ! = null ? model.ADD_DTE.ToString ( `` MM/dd/yyyy '' ) : `` '' ) ) , grid1.Column ( `` DROP_FLAG '' , `` DROP_FLAG '' ) , grid1.Column ( `` DROP_DTE '' , `` DROP_DTE '' , format : ( model = > model.DROP_DTE ! = null ? model.DROP_DTE.ToString ( `` MM/dd/yyyy '' ) : `` '' ) ) ) ) < /div > namespace JHelpWebTest2.Models { public class CombinedModels { public NAME_MASTER NAME_MASTER { get ; set ; } public AddressModel DefaultAddressModel { get ; set ; } public IEnumerable < AddressModel > AllAddressModels { get ; set ; } public STUDENT_MASTER STUDENT_MASTER { get ; set ; } public STUDENT_DIV_MAST STUDENT_DIV_MAST { get ; set ; } public BIOGRAPH_MASTER BiographMaster { get ; set ; } public TW_WEB_SECURITY Security { get ; set ; } public ADVISOR_STUD_TABLE Advisor { get ; set ; } public CANDIDACY Candidacy { get ; set ; } public IEnumerable < STUDENT_CRS_HIST > StudentCrsHist { get ; set ; } public STUDENT_CRS_HIST StudentCrsHist1 { get ; set ; } public IEnumerable < TERM_DEF > TermDef { get ; set ; } public IEnumerable < SUBTERM_DEF > SubtermDef { get ; set ; } public IEnumerable < YEAR_DEF > YearDef { get ; set ; } public NAME_AND_ADDRESS NameAndAddress { get ; set ; } public PagedStudentModel PagedStudentModel { get ; set ; } } } namespace JHelpWebTest2.Models { public static class SortModel { public static IOrderedEnumerable < TSource > OrderByWithDirection < TSource , TKey > ( this IEnumerable < TSource > source , Func < TSource , TKey > keySelector , bool descending ) { return descending ? source.OrderByDescending ( keySelector ) : source.OrderBy ( keySelector ) ; } public static IOrderedQueryable < TSource > OrderByWithDirection < TSource , TKey > ( this IQueryable < TSource > source , Expression < Func < TSource , TKey > > keySelector , bool descending ) { return descending ? source.OrderByDescending ( keySelector ) : source.OrderBy ( keySelector ) ; } } public class ModelServices : IDisposable { private readonly TmsEPrdEntities entities = new TmsEPrdEntities ( ) ; public IEnumerable < STUDENT_CRS_HIST > GetStudentHistory ( int pageNumber , int pageSize , string sort , bool Dir ) { if ( pageNumber < 1 ) pageNumber = 1 ; if ( sort == `` YR_CDE '' ) return entities.STUDENT_CRS_HIST.OrderByWithDirection ( x = > x.YR_CDE , Dir ) .Skip ( ( pageNumber - 1 ) * pageSize ) .Take ( pageSize ) .ToList ( ) ; else if ( sort == `` TRM_CDE '' ) return entities.STUDENT_CRS_HIST.OrderByWithDirection ( x = > x.TRM_CDE , Dir ) .Skip ( ( pageNumber - 1 ) * pageSize ) .Take ( pageSize ) .ToList ( ) ; else if ( sort == `` SUBTERM_CDE '' ) return entities.STUDENT_CRS_HIST.OrderByWithDirection ( x = > x.SUBTERM_CDE , Dir ) .Skip ( ( pageNumber - 1 ) * pageSize ) .Take ( pageSize ) .ToList ( ) ; else if ( sort == `` CRS_CDE '' ) return entities.STUDENT_CRS_HIST.OrderByWithDirection ( x = > x.CRS_CDE , Dir ) .Skip ( ( pageNumber - 1 ) * pageSize ) .Take ( pageSize ) .ToList ( ) ; else if ( sort == `` CRS_DIV '' ) return entities.STUDENT_CRS_HIST.OrderByWithDirection ( x = > x.CRS_DIV , Dir ) .Skip ( ( pageNumber - 1 ) * pageSize ) .Take ( pageSize ) .ToList ( ) ; else if ( sort == `` CREDIT_HRS '' ) return entities.STUDENT_CRS_HIST.OrderByWithDirection ( x = > x.CREDIT_HRS , Dir ) .Skip ( ( pageNumber - 1 ) * pageSize ) .Take ( pageSize ) .ToList ( ) ; else if ( sort == `` CRS_TITLE '' ) return entities.STUDENT_CRS_HIST.OrderByWithDirection ( x = > x.CRS_TITLE , Dir ) .Skip ( ( pageNumber - 1 ) * pageSize ) .Take ( pageSize ) .ToList ( ) ; else if ( sort == `` ADD_FLAG '' ) return entities.STUDENT_CRS_HIST.OrderByWithDirection ( x = > x.ADD_FLAG , Dir ) .Skip ( ( pageNumber - 1 ) * pageSize ) .Take ( pageSize ) .ToList ( ) ; else if ( sort == `` ADD_DTE '' ) return entities.STUDENT_CRS_HIST.OrderByWithDirection ( x = > x.ADD_DTE , Dir ) .Skip ( ( pageNumber - 1 ) * pageSize ) .Take ( pageSize ) .ToList ( ) ; else if ( sort == `` DROP_FLAG '' ) return entities.STUDENT_CRS_HIST.OrderByWithDirection ( x = > x.DROP_FLAG , Dir ) .Skip ( ( pageNumber - 1 ) * pageSize ) .Take ( pageSize ) .ToList ( ) ; else return entities.STUDENT_CRS_HIST.OrderByWithDirection ( x = > x.ID_NUM , Dir ) .Skip ( ( pageNumber - 1 ) * pageSize ) .Take ( pageSize ) .ToList ( ) ; } public int CountStudent ( ) { return entities.STUDENT_CRS_HIST.Count ( ) ; } public void Dispose ( ) { entities.Dispose ( ) ; } } public class PagedStudentModel { public int TotalRows { get ; set ; } public IEnumerable < STUDENT_CRS_HIST > Studentcrshist { get ; set ; } public int PageSize { get ; set ; } } } | Different Model in Partial View |
C_sharp : I fixed all the problems described here ( and one additional ) , and posted the modifiedcsharp-mode.el ( v0.7.1 ) at emacswikiThe csharp-mode I use is almost really good . It works for most things , but has a few problems : # if / # endif tags break indentation , but only within the scope of a method.attributes applied to fields within a struct , break indentation . ( sometimes , see example ) within classes that implement interfaces , the indenting is broken . from that point forward.Literal strings ( prefixed with @ ) do not fontify correctly , and in fact break fontification from that point forward in the source file , if the last character in the literal string is a slash . I think there are some other problems , too . I 'm not a mode writer.Has anyone got improvements on that mode ? anyone want to volunteer to fix these few things ? example code <code> using System ; using System.IO ; using System.Linq ; using System.Collections.Generic ; using System.Runtime.InteropServices ; using System.Xml.Serialization ; namespace Cheeso.Says.TreyIsTheBest { public class Class1 { private void Method1 ( ) { // Problem 1 : the following if / endif pair causes indenting to break . // This occurs only within the scope of a method . If the # if/ # endif is // outside of a method , then the indenting does not break . # if DIAGS // this first line of code within the conditional scope // is indented String StringNumber1 ; // the second line of code within the conditional scope // is un-indented public String StringNumber2 ; # endif // The endif is where I expect it to be , I guess . // It 's in-line with the matched # if . But the comments here // are weirdly indented still further . ? ? } // The prior close-curly is indented 2 units more than I would expect . } // the close-curly for the class is indented correctly . // ================================================================== // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ StructLayout ( LayoutKind.Sequential , CharSet = CharSet.Unicode ) ] public struct Class2 { // Problem 2 : when there is an attribute applied to a field // within a struct , and the attribute include a newline , then // the field indents strangely . See also `` Note 1 '' , and `` Note 2 '' // below . [ MarshalAs ( UnmanagedType.ByValArray , SizeConst = 128 ) ] public int Value1 ; // Note 1 : this indents fine . [ MarshalAs ( UnmanagedType.ByValArray , SizeConst = 128 ) ] public int Value2 ; } [ StructLayout ( LayoutKind.Sequential , CharSet = CharSet.Unicode ) ] public class Class3 { public short PrintNameLength ; [ MarshalAs ( UnmanagedType.ByValArray , SizeConst = 128 ) ] // Note 2 : this indents just fine public int Value1 ; } // ================================================================== // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // Linq Syntax is not a problem as I had originally thought public class Class4 { # region eee # endregion private void Method1 ( ) { var files = Directory.GetFiles ( `` Something '' ) ; var selection = from f in files where System.IO.Path.GetFileName ( f ) .StartsWith ( `` C '' ) select f ; foreach ( var e in selection ) Console.WriteLine ( e ) ; } } // ================================================================== // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- public interface IGuess { } public class Class5 : IGuess { // Problem 3 : When a # region tag is used inside a class that // implements an interface ( or derives from a class ) the line // following the region tag gets indented one extra unit . # region utility private static System.Random rnd= new System.Random ( ) ; private string FigureCategory ( ) { return `` unknown '' ; } # endregion // You can also see artifacts of the same confusion in // methods that have multiple attributes . Again , this only // occurs when the containing class implements a particular // interface or derives from a parent class . [ System.Web.Services.WebMethodAttribute ( ) ] [ return : System.Xml.Serialization.XmlElementAttribute ( `` getContainerObjectsReturn '' ) ] public String Method1 ( ) { return `` Hello . `` ; } } // ================================================================== // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- public class Pippo { // Problem 4 : when the final char in an `` escaped '' string literal is a // slash , indenting and fontification breaks . List < string > directories = new List < string > { @ '' C : \Temp\sub1\ '' , // The emacs parser thinks the string has not ended . // This comment is fontified and indented as if it is in // the middle of a string literal . @ '' C : \Temp\sub2\ '' , // Because we have another \ '' at the end of a string , // emacs now thinks we 're `` out '' of the string literal . // This comment is now indented and fontified correctly . @ '' C : \Home\ '' // A third \ '' , and now emacs thinks we 're back inside the string literal . // The rest of the code will be treated as if it were inside the string literal . } ; protected void Page_Load ( object sender , EventArgs e ) { Console.WriteLine ( `` Hello { 0 } '' , `` world '' ) ; } } } | How can I fix csharp-mode.el ? |
C_sharp : I need to recover JSON stored in RavenDb database knowing its Id . What 's tricky here , I need to get it before it is deserialized into an actual object . Reason for that is , I need it in exact same form it was first stored in , regardless what happens to the CLR class ( it can drastically change or even be removed ) , because it is an audit of previous state ( it 's only going to be displayed at this point , I wo n't use it for anything else ) .If I go withI get JSON reflecting current state of underlying type , probably because it 's stored in @ metadata.Raven-Clr-Type . So I do n't see removed properties , and I do see empty properties that did n't exist when it was first stored.I wanted to use DocumentStore.DatabaseCommands.Get ( ) to get RavenJObject , but it is already removed in 4.1 in favor of Advanced.DocumentQuery and I could n't find a way to do what I want using it.I 've also tried using own AbstractIndexCreationTask like this : But session.Load does n't accept TIndexCreator , and in session.Query I ca n't get Id because I do n't have any properties of an object to make query from.Example : If I have this class : And I store a new document new Person { FullName = `` John Samson '' , Age = 42 } , under Id person/A-1 , yet half year later I decide to modify this class to : Now I want to see how JSON of person/A-1 looks like , but an attempt to load it maps it to current state of Person , so I will get : And I want to get I can see my desired result in RavenDb Studio GUI , but I need to get it in my code to display it in my application.Does anyone have any idea how to handle that ? Just a hint in right direction would be appreciated . <code> using ( var session = Store.OpenSession ( ) ) { return JsonConvert.SerializeObject ( session.Load < object > ( id ) ) ; } class Object_AsJson : AbstractIndexCreationTask < JsonObject > { public Configuration_AsJson ( ) { Map = configuration = > configuration.Select ( x = > AsJson ( x ) .Select ( y = > y.Value ) ) ; } } public class Person { string FullName { get ; set ; } int Age { get ; set ; } } public class Person { string FirstName { get ; set ; } string LastName { get ; set ; } int Age { get ; set ; } } { `` FirstName '' : null , `` LastName '' : null , `` Age '' : 42 } { `` FullName '' : `` John Samson '' , `` Age '' : 42 } | RavenDb get raw JSON without deserialization |
C_sharp : I have around 6 WCF services that I want to host in an MVC application , routing requests to /services/foo to WcfFooService and /services/bar to WcfBarServiceI can accomplish IoC with StructureMap within the services and inject my constructor dependencies by using the example that Jimmy Bogard blogged about here : Jimmy 's article is great , but I 'm trying to extend it to work with multiple services hosted within the same MVC application . Essentially , the part at the bottom is the part that is causing me a few headaches : With a single WCF service - routing MVC requests to a specific url via the StructureMapServiceHostFactory shown above works brilliantly - but - If ( for example ) I create a StructureMapServiceHostFactory2 for the /services/bar call , to allow for a different Registry to be used , when the MVC app spins up , it appears to call each factory in turn as it runs through RouteConfig.cs and adds the routes , so ultimately I do n't get configured instances that the first ServiceHostFactory should provide.It does n't make a difference if I call Initialize ( ) ; or attempt to grab the Container property and call Configure on it , either.Am I on a hiding to nothing with this ? The major reason for requiring registry isolation is due to different NHibernate configuration , but I could configure Named instances of SessionFactory and Session for NHibernate purposes and then use a single registry to get around this . In my mind I wanted the WCF service and MVC-hosting to be capable of using their own IoC containers in isolation , which is why I went down this route.Is there any way that I can accomplish this ? <code> public class StructureMapServiceHostFactory : ServiceHostFactory { public StructureMapServiceHostFactory ( ) { ObjectFactory.Initialize ( x = > x.AddRegistry < FooRegistry > ( ) ) ; //var iTriedThisToo = ObjectFactory.Container ; //container.Configure ( x = > x . [ etc ] ) ; } protected override ServiceHost CreateServiceHost ( Type serviceType , Uri [ ] baseAddresses ) { return new StructureMapServiceHost ( serviceType , baseAddresses ) ; } } | How can I host multiple IoC-driven WCF services in MVC ? |
C_sharp : I have a bunch of systems , lets call them A , B , C , D , E , F , G , H , I , J.They all have similar methods and properties . Some contain the exact same method and properties , some may vary slightly and some may vary a lot . Right now , I have a lot of duplicated code for each system . For example , I have a method called GetPropertyInformation ( ) that is defined for each system . I am trying to figure out which method would be the best approach to reduce duplicate code or maybe one of the methods below is not the way to go : InterfaceAbstractVirtual Methods in a Super Base classOne question , although it may be stupid , is let 's assume I went with the abstract approach and I wanted to override the GetPropertyInformation , but I needed to pass it an extra parameter , is this possible or would I have to create another method in the abstract class ? For example , GetPropertyInformation ( x ) <code> public Interface ISystem { public void GetPropertyInformation ( ) ; //Other methods to implement } public class A : ISystem { public void GetPropertyInformation ( ) { //Code here } } public abstract class System { public virtual void GetPropertyInformation ( ) { //Standard Code here } } public class B : System { public override void GetPropertyInformation ( ) { //B specific code here } } public class System { public virtual void GetPropertyInformation ( ) { //System Code } } public class C : System { public override void GetPropertyInformation ( ) { //C Code } } | Interface , Abstract , or just virtual methods ? |
C_sharp : I have a datagrid which is bound to a datatable . I would like to know - How can we show the Cursor as blinking in the first cell of an empty row of this datagrid which is bound to the datatable . Also , when a user adds a new empty row to this datatable/datagrid by hitting the enter key , The cursor should blink on the first cell of the new added empty row.Here 's the UI that 's shown at the moment , but the user may not know where to insert a value since there 's no cursor blinking on the last empty row.Here 's the code : View.xamlViewModel.cs <code> < DataGrid x : Name= '' MyGrid '' ItemsSource= '' { Binding MyDataTable , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged } '' VerticalAlignment= '' Top '' Height= '' 400 '' Width= '' Auto '' SelectionMode= '' Single '' AutoGenerateColumns= '' True '' GridLinesVisibility = '' Vertical '' Background= '' Transparent '' CanUserResizeColumns= '' True '' CanUserReorderColumns= '' False '' CanUserResizeRows= '' False '' BorderThickness= '' 0 '' CanUserAddRows= '' True '' RowHeaderWidth= '' 0 '' > < /DataGrid > private DataTable _MyDataTable ; public DataTable MyDataTable { get { return _MyDataTable ; } set { SetProperty ( ref _MyDataTable , value ) ; } } | How to set the cursor on the first cell of an empty row in datagrid which is bound to a data table |
C_sharp : I 'm still a beginner to programming in high-level programming languages , so I do n't know if this is an easy solution , but I 'm happy to learn anyway . I 've programmed a little alarm program in C # that let 's the user input in how many seconds the alarm needs to go off . It works perfectly , but the input that the user needs to give has to be a number . When the user inputs any form of text , the program crashes . Now , how can I prevent that users input text , and call a function or do something else when the user does , instead of the program just crashing ? This is the code I have now : <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace Test { class Alarm { public static void play ( ) { int sec ; sec = Convert.ToInt16 ( Console.ReadLine ( ) ) ; for ( int i = 0 ; i < seconds ; ++i ) { System.Threading.Thread.Sleep ( 1000 ) ; } for ( int i = 0 ; i < 10 ; i++ ) { Console.Beep ( ) ; } } } } | How to prevent certain forms of input when writing methods ? |
C_sharp : I got this idea while thinking of ways to recycling objects . I am doing this as an experiment to see how memory pooling works and I realize that in 99 % of scenario this is very unnecessary . However , I have a question . Is there a way to force the GC to keep the object ? In other words , can I tell the GC not to destroy an object and say instead have new reference created in a list that holds available to use objects ? The issue , though I have not tested this , is that if I add something like this to a list : it will add a pointer to this object into the list , but if the object is destroyed I will get a null pointer exception because the object is no longer there . However , maybe I could tell the GC not to collect this item and thus keeping the object ? I know this is the type of stuff that most programmers would go `` why the hell would you do this ? '' . But on the other hand programming is about trying new and learning new things . Any suggestions , thoughts , implementatons ? Any help would be greatly appreciated ! <code> ~myObject ( ) { ( ( List < myObject > ) HttpContext.Current.Items [ typeof ( T ) .ToString ( ) ] ) .add ( this ) ; //Lets assume this is ASP } | Keep object on GC destruction attempt |
C_sharp : After two questions and much confusion - I wonder if I finally got it right . This is my understanding : async/await serves only one purpose - to allow code to be executed after an already asynchronous task is finished.e.g.allows AnotherMethod to be executed after the asynchronous AsyncMethod is finished instead of immediately after AsyncMethod is started.async/await NEVER makes anything asynchronous . It does n't start a separate thread ( unless the awaited method does that anyway , of course ) , etc.Is my understanding ( finally ) correct ? <code> async Task CallerMethod ( ) { await AsyncMethod ( ) ; AnotherMethod ( ) ; } | async/await - Is this understanding correct ? |
C_sharp : Does taking address of a C # struct cause default constructor call ? For example , I got such structs : Then , of course , I ca n't do this : But once I obtain pointer to the struct , I can read its fields even without using the pointer , and even embedded struct 's fields : So , does it call the default constructor somehow , or - once I take the address - C # stops caring about the memory ? PS : The memory seems to be zero-initialized anyway . <code> [ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] public struct HEADER { public byte OPCODE ; public byte LENGTH ; } [ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] public struct S { public HEADER Header ; public int Value ; } S s ; // no constructor call , so ... var v = s.Value ; // compiler error : use of possibly unassigned field 'Value ' S s ; S* ps = & s ; var v1 = ps- > Value ; // OK , expectedvar v2 = s.Value ; // OK ! var len = s.Header.LENGTH ; // OK ! | Struct pointer ( address ) , and default constructor |
C_sharp : My code is ... Resharper is recommending ... <code> public static void AssertNotNull < T > ( string name , T val ) { if ( val == null ) throw new ArgumentNullException ( String.Format ( `` { 0 } must not be null '' , name ) ) ; } public static void AssertNotNull < T > ( string name , T val ) { if ( Equals ( val , default ( T ) ) ) throw new ArgumentNullException ( String.Format ( `` { 0 } must not be null '' , name ) ) ; } | Why is resharper making the following recommendation ? |
C_sharp : I am a newbie to Cassandra and created a generic repository for my Cassandra database using linq . For my Single ( ) method , I am passing the where criteria as a parameter . This is my Single method : This is the linq code I am using to query the cassandra databaseThis is the method calling the single methodI keep getting a `` System.AggregateException '' of `` Argument types do not match '' and I am confused about where this could be coming from.The database table columns : and the c # poco : and the exception : What am I missing . I reveiwed the docs . and the mapping rules between Cassandra and c # and everything seems correct . <code> Single ( Expression < Func < T , bool > > exp ) public async Task < T > Single ( Expression < Func < T , bool > > exp ) { return await GetTable.Where < T > ( exp ) .FirstOrDefault ( ) .ExecuteAsync ( ) ; } public override Task OnConnected ( ) { if ( Context.User ! = null ) { string userName = Context.User.Identity.Name ; this.Groups.Add ( userName , Context.ConnectionId ) ; ***** this is the line with the issue ****** Notification notification = Task.Run ( ( ) = > _notificationRepository.Single ( x = > x.UserName.Equals ( userName ) ) ) .Result ; if ( notification == null ) { _notificationRepository.CreateInstance ( new NotificationUserMapping { Connections = new string [ ] { Context.ConnectionId } , UserName = Context.User.Identity.Name } ) ; } else if ( ! notification.Connections.Contains ( Context.ConnectionId ) ) { notification.Connections.Add ( Context.ConnectionId ) ; _notificationRepository.Save ( notification ) ; } } return base.OnConnected ( ) ; } id uuid PRIMARY KEY , connections list < text > , username text [ Table ( ExplicitColumns = true ) ] public class ConnectionMapping { [ Column ( `` id '' ) ] public Guid Id { get ; set ; } [ Column ( `` connections '' ) ] public IList < string > Connections { get ; set ; } [ Column ( `` username '' ) ] public string UserName { get ; set ; } } at System.Linq.Expressions.Expression.Condition ( Expression test , Expression ifTrue , Expression ifFalse ) at Cassandra.Mapping.MapperFactory.GetExpressionToGetColumnValueFromRow ( ParameterExpression row , CqlColumn dbColumn , Type pocoDestType ) at Cassandra.Mapping.MapperFactory.CreateMapperForPoco [ T ] ( RowSet rows , PocoData pocoData ) at Cassandra.Mapping.MapperFactory.CreateMapper [ T ] ( RowSet rows ) at Cassandra.Mapping.MapperFactory. < > c__DisplayClass1 ` 1. < GetMapper > b__0 ( Tuple ` 2 _ ) at System.Collections.Concurrent.ConcurrentDictionary ` 2.GetOrAdd ( TKey key , Func ` 2 valueFactory ) at Cassandra.Mapping.MapperFactory.GetMapper [ T ] ( String cql , RowSet rows ) at Cassandra.Mapping.Mapper. < > c__DisplayClass7 ` 1. < FetchAsync > b__6 ( Statement s , RowSet rs ) at Cassandra.Mapping.Mapper. < > c__DisplayClass2 ` 1. < > c__DisplayClass4. < ExecuteAsyncAndAdapt > b__1 ( Task ` 1 t2 ) at Cassandra.Tasks.TaskHelper.DoNext [ TIn , TOut ] ( Task ` 1 task , Func ` 2 next ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter ` 1.GetResult ( ) at CompanyNamespace.CompanyDomain.NotificationRepository. < SingleByUserName > d__0.MoveNext ( ) | Cassandra : Argument types do not match |
C_sharp : Why does PHP return INF ( infinity ) for the following piece of code : The expected result was 4321 , but PHP returned INF , float type : I wrote the same code in Python and C # and got the expected output - 4321PythonC # <code> < ? php $ n = 1234 ; $ m = 0 ; while ( $ n > 0 ) { $ m = ( $ m * 10 ) + ( $ n % 10 ) ; $ n = $ n / 10 ; } var_dump ( $ m ) ; ? > float INF n = 1234m = 0while ( n > 0 ) : m = ( m * 10 ) + ( n % 10 ) n = n / 10print m static void Main ( string [ ] args ) { int n = 1234 ; int m = 0 ; while ( n > 0 ) { m = ( m * 10 ) + ( n % 10 ) ; n = n / 10 ; } Console.WriteLine ( m ) ; Console.ReadLine ( ) ; } | Unexpected behavior in PHP - Same code gives correct results in C # and Python |
C_sharp : Possible Duplicate : .NET Enumeration allows comma in the last field Since both compile , is there any differences between these declarations ? <code> public enum SubPackageBackupModes { Required , NotRequired //no comma } public enum SubPackageBackupModes { Required , NotRequired , //extra unnecessary comma } | Unnecessary comma in enum declaration |
C_sharp : I read a book `` CLR via C # Fourth Edition '' . And I can not understand one statement : So , for example , if you have the following line of code : then when the CLR creates the FileStream [ ] type , it will cause this type to automatically implement the IEnumerable < FileStream > , ICollection < FileStream > , and IList < FileStream > interfaces . Furthermore , the FileStream [ ] type will also implement the interfaces for the base types : IEnumerable < Stream > , IEnumerable < Object > , ICollection < Stream > , ICollection < Object > , IList < Stream > , and IList < Object > .I tested this statement with this code : and as a result , I have this : There is no implementation of IEnumerable < Stream > and others ! Did I make mistake somewhere ? Or did Jeffrey Richter make mistake ? Furthermore , I think it is mean-less . Because Arrays support co-variance . <code> FileStream [ ] fsArray ; FileStream [ ] fsArray = new FileStream [ 0 ] ; string s = null ; foreach ( var m in fsArray.GetType ( ) .GetInterfaces ( ) ) s += m.ToString ( ) + Environment.NewLine ; System.ICloneableSystem.Collections.IListSystem.Collections.ICollectionSystem.Collections.IEnumerableSystem.Collections.IStructuralComparableSystem.Collections.IStructuralEquatableSystem.Collections.Generic.IList ` 1 [ System.IO.FileStream ] System.Collections.Generic.ICollection ` 1 [ System.IO.FileStream ] System.Collections.Generic.IEnumerable ` 1 [ System.IO.FileStream ] System.Collections.Generic.IReadOnlyList ` 1 [ System.IO.FileStream ] System.Collections.Generic.IReadOnlyCollection ` 1 [ System.IO.FileStream ] | Auto implemented interfaces in Arrays |
C_sharp : For convenience and safety reasons i 'd like to use the using statement for allocation and release of objects from/to a pool and the access the pool likeI found some topics on abusing using and Dispose ( ) for scope handling but all of them incorporate using ( Blah b = _NEW_ Blah ( ) ) .Here the objects are not to be freed after leaving the using scope but kept in the pool.If the using statement simply expands to a plain try finally Dispose ( ) this should work fine but is there something more happening behind the scenes or a chance this wo n't work in future .Net versions ? <code> public class Resource : IDisposable { public void Dispose ( ) { ResourcePool.ReleaseResource ( this ) ; } } public class ResourcePool { static Stack < Resource > pool = new Stack < Resource > ( ) ; public static Resource GetResource ( ) { return pool.Pop ( ) ; } public static void ReleaseResource ( Resource r ) { pool.Push ( r ) ; } } using ( Resource r = ResourcePool.GetResource ( ) ) { r.DoSomething ( ) ; } | Abuse using and Dispose ( ) for scope handling of not to be released objects ? |
C_sharp : I am launching these two console applications on Windows OS.Here is my C # codeAnd here is my C code . I am assuming it is C because I included cstdio and used standard fopen and fprintf functions.When I start C # program I immediately see the message `` Done ! '' . When I start C++ program ( which uses standard C functions ) it waits at least 2 seconds to complete and show me the message `` Done ! '' . I was just playing around to test their speeds , but now I think I do n't know lots of things . Can somebody explain it to me ? NOTE : Not a possible duplicate of `` Why is C # running faster than C++ ? `` , because I am not giving any console output such as `` cout '' or `` Console.Writeline ( ) '' . I am only comparing filestream mechanism which does n't include any interference of any kind that can interrupt the main task of the program . <code> int lineCount = 0 ; StreamWriter writer = new StreamWriter ( `` txt1.txt '' , true ) ; for ( int i = 0 ; i < 900 ; i++ ) { for ( int k = 0 ; k < 900 ; k++ ) { writer.WriteLine ( `` This is a new line '' + lineCount ) ; lineCount++ ; } } writer.Close ( ) ; Console.WriteLine ( `` Done ! `` ) ; Console.ReadLine ( ) ; FILE *file = fopen ( `` text1.txt '' , '' a '' ) ; for ( size_t i = 0 ; i < 900 ; i++ ) { for ( size_t k = 0 ; k < 900 ; k++ ) { fprintf ( file , `` This is a line\n '' ) ; } } fclose ( file ) ; cout < < `` Done ! `` ; | Why my C # code is faster than my C code ? |
C_sharp : I can easily start a process with it 's STD I/O redirected but how can I redirect the STD I/O of an existing process.Exception : StandardOut has not been redirected or the process has n't started yet.Side note : If you know how to do this in C/C++ I 'd be happy to re-tag and accept . I just need to know if it 's even possible . <code> Process process = Process.GetProcessById ( _RunningApplication.AttachProcessId ) ; process.StartInfo.RedirectStandardOutput = true ; process.StartInfo.RedirectStandardError = true ; string text = process.StandardOutput.ReadToEnd ( ) ; //This line blows up . | How to redirect the STD-Out of an **existing** process in C # |
C_sharp : I have a C # function with following signature : I call it from C++ . I was informed by compiler that 2-nd param must have SAFEARRAY* type . So I call it in this way : But safeArray is not updated , it still contains zores . But I tested Get1251Bytes function in C # unit-test . It works properly and updates result array . What am I doing wrong ? <code> int Get1251Bytes ( string source , byte [ ] result , Int32 lengthOfResult ) SAFEARRAY* safeArray = SafeArrayCreateVector ( VT_UI1 , 0 , arrayLength ) ; char str [ ] = { 's ' , 't ' , ' a ' , ' c ' , ' k ' , '\0 ' } ; converter- > Get1251Bytes ( str , safeArray , arrayLength ) ; | C # function does n't update SAFEARRAY |
C_sharp : I started out programming with C # a few days ago.Now an confusing error arised when playing around with operator overloading.The following code produces a StackOverflowException when running : I tried to write an own example after reading the chapter about operater overloading from the book `` Microsoft Visual C # 2008 '' from Dirk Louis and Shinja Strasser.Maybe someone has a clue what 's going wrong.Thanks . <code> using System ; namespace OperatorOverloading { public class Operators { // Properties public string text { get { return text ; } set { if ( value ! = null ) text = value ; else text = `` '' ; } } // Constructors public Operators ( ) : this ( `` '' ) { } public Operators ( string text ) { // Use `` set '' property . this.text = text ; } // Methods public override string ToString ( ) { return text ; } // Operator Overloading public static string operator + ( Operators lhs , Operators rhs ) { // Uses properties of the passed arguments . return lhs.text + rhs.text ; } public static void Main ( string [ ] args ) { Operators o1 = new Operators ( ) ; Operators o2 = new Operators ( `` a '' ) ; Operators o3 = new Operators ( `` b '' ) ; Console.WriteLine ( `` o1 : `` + o1 ) ; Console.WriteLine ( `` o2 : `` + o2 ) ; Console.WriteLine ( `` o3 : `` + o3 ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` o1 + o2 : `` + ( o1 + o2 ) ) ; Console.WriteLine ( `` o2 + o3 : `` + ( o2 + o3 ) ) ; } } } | Operator Overloading causes a stack overflow |
C_sharp : I 'm developing a simple lambda function with .net core . For this , I 'm using the AWS tookit . My project have a three resources file , one with default message , and two with italian and french greetings.For this , my function receive a query string parameter , and depending on this value , I set the culture for the current thread.If I run this project with the unit test project , all works fine , but when is run on amazon infraestructure , it shown the default message . It 's like if never changes the default culture of the main thread.I 'm changing the current culture like this : You can also test from this url , that point to an api gateway endpoint , that utilize my lambda function ; where language 1 is french , 2 is italian and another value is unsuported language.I created an example project on github to reproduce this behaviorAny idea on how to fix thit ? I want to send localized message from my API , Maybe another approach ? Thanks a lot ! UPDATEIn AWS Forum , says that resources is not supported yet ! I created an issue in github AWS repo . <code> CultureInfo.CurrentCulture = new CultureInfo ( `` fr '' ) ; CultureInfo.CurrentUICulture = new CultureInfo ( `` fr '' ) ; | AWS Lambda is not recognizing the culture on .net core |
C_sharp : At work I just installed a brand new copy of my OS and a brand new copy of VS2015 . When I clone my solution for the first time , I can not build it anymore , even if I 've generated the C # files like I always do , by opening the .edmx file first , and clicking on `` save '' icon.When building it throws the error : CS0150 : A constant value is expectedBecause the enums that it has generated are incomplete ! An example of one : I also had this compiler error at the time , but after fixing it my C # enums are still being generated wrongly : The ADO.NET provider with invariant name 'MySql.Data.MySqlClient ' is either not registered in the machine or application config file , or could not be loaded . See the inner exception for detailsHow the hell should I fix this problem ? <code> public enum DocumentType : int { Identity = 1 , ResidenceProof = 2 , RegisterDoc = , } | EntityFramework not generating C # files properly ( some enums are incomplete , so build fails ) |
C_sharp : I found this code snippet on a blog as a `` Convert Binary data to text '' And this provides a output of AAAAAQAB .. What is not clear is that how 000101 - > is mapped to AAAAAQAB , and will I able to use this to all a-z characters as a binary equivalent and how ? or is there a any other method ? <code> Byte [ ] arrByte = { 0,0,0,1,0,1 } ; string x = Convert.ToBase64String ( arrByte ) ; System : Console.WriteLine ( x ) ; | C # byte array problem |
C_sharp : I have a query that looks something like this : MultiframeModule and Frame have an many-to-many relation.With that query I want to find a MultiframeModule that contains all frames inside the frames collection I sent as a parameter , for that I check the ShaHash parameter.If frames contains 2 frames , then the generated SQL would be something like that : But , if I have more frames , say 200 for example , then the call would throw an exception : With stacktrace : So , is there some obvious reason why my query is failing ? And how can I improve it to be able to do the query successfully ? <code> private static IQueryable < MultiframeModule > WhereAllFramesProperties ( this IQueryable < MultiframeModule > query , ICollection < Frame > frames ) { return frames.Aggregate ( query , ( q , frame ) = > { return q.Where ( p = > p.Frames.Any ( i = > i.FrameData.ShaHash == frame.FrameData.ShaHash ) ) ; } ) ; } SELECT `` Extent1 '' . `` MultiframeModuleId '' , `` Extent1 '' . `` FrameIncrementPointer '' , `` Extent1 '' . `` PageNumberVector '' FROM `` public '' . `` MultiframeModule '' AS `` Extent1 '' WHERE EXISTS ( SELECT 1 AS `` C1 '' FROM `` public '' . `` Frame '' AS `` Extent2 '' INNER JOIN `` public '' . `` FrameData '' AS `` Extent3 '' ON `` Extent2 '' . `` FrameData_FrameDataId '' = `` Extent3 '' . `` FrameDataId '' WHERE `` Extent1 '' . `` MultiframeModuleId '' = `` Extent2 '' . `` MultiframeModule_MultiframeModuleId '' AND `` Extent3 '' . `` ShaHash '' = @ p__linq__0 ) AND EXISTS ( SELECT 1 AS `` C1 '' FROM `` public '' . `` Frame '' AS `` Extent4 '' INNER JOIN `` public '' . `` FrameData '' AS `` Extent5 '' ON `` Extent4 '' . `` FrameData_FrameDataId '' = `` Extent5 '' . `` FrameDataId '' WHERE `` Extent1 '' . `` MultiframeModuleId '' = `` Extent4 '' . `` MultiframeModule_MultiframeModuleId '' AND `` Extent5 '' . `` ShaHash '' = @ p__linq__1 ) LIMIT 2 -- p__linq__0 : ' 0 ' ( Type = Int32 , IsNullable = false ) -- p__linq__1 : ' 0 ' ( Type = Int32 , IsNullable = false ) Unable to read data from the transport connection : A connection attempt failed because the connected party did not properly respond after a period of time , or established connection failed because connected host has failed to respond . at Npgsql.ReadBuffer. < Ensure > d__27.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Npgsql.NpgsqlConnector. < DoReadMessage > d__157.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Runtime.CompilerServices.ValueTaskAwaiter ` 1.GetResult ( ) at Npgsql.NpgsqlConnector. < ReadMessage > d__156.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Runtime.CompilerServices.ValueTaskAwaiter ` 1.GetResult ( ) at Npgsql.NpgsqlConnector. < ReadExpecting > d__163 ` 1.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Runtime.CompilerServices.ValueTaskAwaiter ` 1.GetResult ( ) at Npgsql.NpgsqlDataReader. < NextResult > d__32.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Npgsql.NpgsqlDataReader.NextResult ( ) at Npgsql.NpgsqlCommand. < Execute > d__71.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Runtime.CompilerServices.ValueTaskAwaiter ` 1.GetResult ( ) at Npgsql.NpgsqlCommand. < ExecuteDbDataReader > d__92.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Runtime.CompilerServices.ValueTaskAwaiter ` 1.GetResult ( ) at Npgsql.NpgsqlCommand.ExecuteDbDataReader ( CommandBehavior behavior ) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher ` 1.Dispatch [ TTarget , TInterceptionContext , TResult ] ( TTarget target , Func ` 3 operation , TInterceptionContext interceptionContext , Action ` 3 executing , Action ` 3 executed ) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader ( DbCommand command , DbCommandInterceptionContext interceptionContext ) at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands ( EntityCommand entityCommand , CommandBehavior behavior ) | Query with large WHERE clause causes timeout exception in EF6 with npgsql |
C_sharp : So heres my question . I have a Asp.net application with a form based authentication . I have users in my database but the users also has to be in the active directory.The following code is for me to check if user is in the domain AThis code work fine . The problem is client is requesting that domain B should also be able to connect to the application . So created the following code : Since my server is in domainA this does not work . Is there a way for me to query domainB knowing that the server is in domainA ? I found an article saying trust needs to be setup for domainA and B but this domains shouldnt be linked . Its only for this application that they need this functionality.P.S . I might forgot to explain an important detail . domainA and B are not on the same network . But domainA can ping domainB <code> DirectoryEntry de = new DirectoryEntry ( ) ; de.Path = `` LDAP : //domainA.com '' ; de.AuthenticationType = AuthenticationTypes.None ; DirectorySearcher search = new DirectorySearcher ( de ) ; search.Filter = `` ( SAMAccountName= '' + account + `` ) '' ; search.PropertiesToLoad.Add ( `` displayName '' ) ; SearchResult result = search.FindOne ( ) ; DirectoryEntry de = new DirectoryEntry ( ) ; de.Path = `` LDAP : //domainB.com '' ; de.AuthenticationType = AuthenticationTypes.None ; DirectorySearcher search = new DirectorySearcher ( de ) ; search.Filter = `` ( SAMAccountName= '' + account + `` ) '' ; search.PropertiesToLoad.Add ( `` displayName '' ) ; SearchResult result = search.FindOne ( ) ; | How to query Active Directory B if application server is in Active Directory A |
C_sharp : Given the following test : I want to encapsulate fixture creation in its own class , something akin to : The problem is that I 'm using PropertyData and the latter is supplying two input parameters . The fact that I 'm then trying to automatically create my fixture as a parameter is causing an exception . Here is the CustomPropertyData : What are the options to resolve this ? <code> [ Theory ] [ PropertyData ( `` GetValidInputForDb '' ) ] public void GivenValidInputShouldOutputCorrectResult ( string patientId , string patientFirstName ) { var fixture = new Fixture ( ) ; var sut = fixture.Create < HtmlOutputBuilder > ( ) ; sut.DoSomething ( ) ; // More code } [ Theory ] [ CustomPropertyData ( `` GetValidInputForDb '' ) ] public void GivenValidInputShouldOutputCorrectResult ( string patientId , string patientFirstName , HtmlOutputBuilder sut ) { sut.DoSomething ( ) ; // More code } public class CustomPropertyDataAttribute : CompositeDataAttribute { public CustomPropertyDataAttribute ( string validInput ) : base ( new DataAttribute [ ] { new PropertyDataAttribute ( validInput ) , new AutoDataAttribute ( new Fixture ( ) .Customize ( new HtmlOutpuBuilderTestConvention ( ) ) ) , } ) { } } | AutoFixture : PropertyData and heterogeneous parameters |
C_sharp : Is it possible to publish an build artifact to Azure Devops/TFS through build.cake script ? Where should the responsibility for publishing the build artifact be configured when converting to cake scripts , in the build.cake script or in the Azure DevOps pipeline ? To achieve versioning in our build and release pipelines we decided to move our ( gitversion , clean , build , tests , ... ) tasks to be handled by a cake script stored in each repository instead . Is there a way to replace the publish build artifact ( Azure DevOps ) task with a task in the cake.build ? I have searched the official documentation of both Azure and cake but can not seem to find a solution . The first task , copying the build artifacts to a staging directory is possible , however , publishing the artifact - is where it gets complicated.Currently , a snippet of our build.cake.SolutionA snippet of an updated build.cake . <code> Task ( `` Copy-Bin '' ) .WithCriteria ( ! isLocalBuild ) .Does ( ( ) = > { Information ( $ '' Creating directory { artifactStagingDir } /drop '' ) ; CreateDirectory ( $ '' { artifactStagingDir } /drop '' ) ; Information ( $ '' Copying all files from { solutionDir } / { moduleName } .ServiceHost/bin to { artifactStagingDir } /drop/bin '' ) ; CopyDirectory ( $ '' { solutionDir } / { moduleName } .ServiceHost/bin '' , $ '' { artifactStagingDir } /drop/bin '' ) ; // Now we should publish the artifact to TFS/Azure Devops } ) ; Task ( `` Copy-And-Publish-Artifacts '' ) .WithCriteria ( BuildSystem.IsRunningOnAzurePipelinesHosted ) .Does ( ( ) = > { Information ( $ '' Creating directory { artifactStagingDir } /drop '' ) ; CreateDirectory ( $ '' { artifactStagingDir } /drop '' ) ; Information ( $ '' Copying all files from { solutionDir } / { moduleName } .ServiceHost/bin to { artifactStagingDir } /drop/bin '' ) ; CopyDirectory ( $ '' { solutionDir } / { moduleName } .ServiceHost/bin '' , $ '' { artifactStagingDir } /drop/bin '' ) ; Information ( $ '' Uploading files from artifact directory : { artifactStagingDir } /drop to TFS '' ) ; TFBuild.Commands.UploadArtifactDirectory ( $ '' { artifactStagingDir } /drop '' ) ; } ) ; | Publish build artifact through build.cake instead of Azure Devops |
C_sharp : BriefI 've created a beautiful WindowChrome style to apply to my windows . When I add ContentControl to my style , however , the application enters break mode.I 've pieced together code from this youtube video , this article , this SO question and Microsoft 's documentation and I 've come up with the following code.Note : The code below is all considered relevant since the application can not run with either of these parts ( yes I know it can run without the code-behind , but it 's annoying having to stop the application from Visual Studio instead of the close button - which is also what I 'm trying to accomplish ) . I 've actually slimmed down the code below so that it 's easier to work with.CodeWindow.xamlIcons.xamlWindow.xaml makes reference to this file for the ContentControl Template attribute values through App.xaml.Window.xaml.csIssueWhen the line < ContentControl Template= '' { StaticResource Icon_Close } '' Height= '' 10 '' / > is present ( line 38 ) , the following message is received . When the same line is removed/commented out the application runs without entering break mode.Looking at the Output window I 'm getting the following messages : QuestionsThis code worked when placed directly in the XAML code for the Window , but the moment I try to place it in the template it fails.My questions are : Why does my application enter break mode when ContentControl is placed in the Window 's template ? How can I resolve this problem ? Please note that I must use my ControlTemplate from the Icons.xaml file and that the call to this content must remain in the window 's Style ( and not the window 's actual xaml ) . <code> < Style x : Key= '' TestWindow '' TargetType= '' { x : Type Window } '' > < Setter Property= '' Background '' Value= '' # FF222222 '' / > < Setter Property= '' BorderBrush '' Value= '' WhiteSmoke '' / > < Setter Property= '' BorderThickness '' Value= '' 5,30,5,5 '' / > < Setter Property= '' WindowChrome.WindowChrome '' > < Setter.Value > < WindowChrome CaptionHeight= '' 20 '' CornerRadius= '' 0 '' GlassFrameThickness= '' 0,0,0 , -1 '' NonClientFrameEdges= '' None '' ResizeBorderThickness= '' 5 '' UseAeroCaptionButtons= '' True '' / > < /Setter.Value > < /Setter > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type Window } '' > < Grid > < Border Background= '' { TemplateBinding Background } '' BorderBrush= '' { TemplateBinding BorderBrush } '' BorderThickness= '' { TemplateBinding BorderThickness } '' > < AdornerDecorator > < ContentPresenter/ > < /AdornerDecorator > < /Border > < DockPanel LastChildFill= '' True '' VerticalAlignment= '' Top '' Height= '' 30 '' > < StackPanel DockPanel.Dock= '' Right '' Orientation= '' Horizontal '' VerticalAlignment= '' Center '' > < Button x : Name= '' Button_Close '' WindowChrome.IsHitTestVisibleInChrome= '' True '' Width= '' { Binding ActualHeight , RelativeSource= { RelativeSource Self } } '' Click= '' CloseClick '' > < ContentControl Template= '' { StaticResource Icon_Close } '' Height= '' 10 '' / > < /Button > < /StackPanel > < StackPanel DockPanel.Dock= '' Left '' Orientation= '' Horizontal '' VerticalAlignment= '' Center '' > < Image x : Name= '' PART_WindowCaptionIcon '' Width= '' 16 '' Height= '' 16 '' Margin= '' 0,0,6,0 '' Source= '' { TemplateBinding Icon } '' / > < TextBlock x : Name= '' PART_WindowCaptionText '' Margin= '' 6,0,0,0 '' Padding= '' 0 '' > < Run BaselineAlignment= '' Center '' Text= '' { TemplateBinding Title } '' Foreground= '' Black '' / > < /TextBlock > < /StackPanel > < /DockPanel > < /Grid > < ControlTemplate.Triggers > < Trigger SourceName= '' PART_WindowCaptionIcon '' Property= '' Source '' Value= '' { x : Null } '' > < Setter TargetName= '' PART_WindowCaptionIcon '' Property= '' Visibility '' Value= '' Collapsed '' / > < Setter TargetName= '' PART_WindowCaptionText '' Property= '' Margin '' Value= '' 5,0,0,0 '' / > < /Trigger > < /ControlTemplate.Triggers > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > < ControlTemplate x : Key= '' Icon_Close '' > < Viewbox > < Polygon Points= '' 357,35.7 321.3,0 178.5,142.8 35.7,0 0,35.7 142.8,178.5 0,321.3 35.7,357 178.5,214.2 321.3,357 357,321.3 214.2,178.5 '' Fill= '' Black '' / > < /Viewbox > < /ControlTemplate > public partial class Window : ResourceDictionary { public Window ( ) { InitializeComponent ( ) ; } private void CloseClick ( object sender , RoutedEventArgs e ) { var window = ( System.Windows.Window ) ( ( FrameworkElement ) sender ) .TemplatedParent ; window.Close ( ) ; } } An unhandled exception of type 'System.Windows.Markup.XamlParseException ' occurred in PresentationFramework.dllProvide value on 'System.Windows.Markup.StaticResourceHolder ' threw an exception . | Why does adding ContentControl cause my application to enter break mode ? |
C_sharp : What I understand unboxing is when I take a object and unbox it to valuetype like the MSDN example : So I just was thinking , can a string be unboxed ? I think , No it ca n't because there is no valuetype that can represent a string . Am I right ? <code> int i = 123 ; object o = i ; o = 123 ; i = ( int ) o ; // unboxing | Can I unbox a string ? |
C_sharp : I have a array of data : I 'd like it to be sorted from Alphanumeric to Non-Alphanumeric.Example : A B E N ! $ How would I go about accomplishing this ? <code> ! ABE $ N | Sorting from Alphanumeric to nonAlphnumeric |
C_sharp : Trying to get a custom CoreLib in .NET Core project to load in VS 2017 . This was super easy in .NET Framework as all you needed was `` NoStdLib '' but with .NET Core seems like a lot more parts are needed.I keep getting : `` Project file is incomplete . Expected imports are missing . `` Going off what System.Private.CoreLib.csproj is doing and not sure what the missing part is ? Removing `` Sdk= '' Microsoft.NET.Sdk '' '' causes part of the issue as I do n't think I can have that for a custom corelibWhat I 'm basing this off of : https : //github.com/dotnet/coreclr/blob/master/src/System.Private.CoreLib/System.Private.CoreLib.csprojDoes anyone know what the csproj settings are to get this working ? I ca n't seem to find any good info on this . <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < ! -- < Project Sdk= '' Microsoft.NET.Sdk '' > -- > < Project ToolsVersion= '' 14.0 '' DefaultTargets= '' Build '' xmlns= '' http : //schemas.microsoft.com/developer/msbuild/2003 '' > < PropertyGroup > < ProjectGuid > { 3DA06C3A-2E7B-4CB7-80ED-9B12916013F9 } < /ProjectGuid > < OutputType > Library < /OutputType > < AllowUnsafeBlocks > true < /AllowUnsafeBlocks > < ! -- < TargetFramework > netcoreapp2.2 < /TargetFramework > -- > < GenerateTargetFrameworkAttribute > false < /GenerateTargetFrameworkAttribute > < AddAdditionalExplicitAssemblyReferences > false < /AddAdditionalExplicitAssemblyReferences > < ExcludeMscorlibFacade > true < /ExcludeMscorlibFacade > < NoStdLib > true < /NoStdLib > < NoCompilerStandardLib > true < /NoCompilerStandardLib > < LangVersion > latest < /LangVersion > < RootNamespace > System < /RootNamespace > < /PropertyGroup > < PropertyGroup > < AssemblyName > System.Private.CoreLib < /AssemblyName > < AssemblyVersion > 4.0.0.0 < /AssemblyVersion > < MajorVersion > 4 < /MajorVersion > < MinorVersion > 6 < /MinorVersion > < ExcludeAssemblyInfoPartialFile > true < /ExcludeAssemblyInfoPartialFile > < /PropertyGroup > < /Project > | Custom `` CoreLib '' In .NET Core ? |
C_sharp : My Regex is removing all numeric ( 0-9 ) in my string.I do n't get why all numbers are replaced by _ EDIT : I understand that my `` _ '' regex pattern changes the characters into underscores . But not why numbers ! Can anyone help me out ? I only need to remove like all special characters.See regex here : <code> string symbolPattern = `` [ ! @ # $ % ^ & * ( ) -=+ ` ~ { } '| ] '' ; Regex.Replace ( `` input here 12341234 '' , symbolPattern , `` _ '' ) ; Output : `` input here ________ '' | regex issue c # numbers are underscores now |
C_sharp : I 'm seeing an inconstancy with how the CRM SDK treats searching for entities by an OptionSetValue attribute , and creating an entity with an OptionSetValue Attribute.Back Ground : I have a method with this signaturewhere the columnNameAndValuePairs is a list of pairs that look like this : ( string name of the column , value of the column ) ie . `` name '' , '' John Doe '' goes to entity.name = `` John Doe '' . It could be used like this : Which would create and execute a query expression for a SystemUser entity with the username jdoe . If it is n't found , it would create one , populating the username attribute with `` jdoe '' , and then creating the object . Problem : This works great in most instances , unless I 'm searching/creating an OptionSetValue attribute . So say something like this : If I pass in OptionSetValue ( 1 ) the query expression search fails , but if I pass in 1 the query expression executes without error , but the service.Create ( entity ) fails because it expects an OptionSetValue . It would be easy for me to check for an OptionSetValue value , and send the int value into the QueryExpression , but am I just want to make sure I 'm not doing something wrong . Did Microsoft really expect you to create the entity populating the attribute as an OptionSetValue but searching for it as an int ? <code> GetOrCreateEntity < T > ( IOrganizationService service , params object [ ] columnNameAndValuePairs ) var user = GetOrCreateEntity < SystemUser > ( `` username '' , `` jdoe '' ) ; var user = GetOrCreateEntity < SystemUser > ( `` username '' , `` jdoe '' , `` Sex '' , new OptionSetValue ( 1 ) ) ; var user = GetOrCreateEntity < SystemUser > ( `` username '' , `` jdoe '' , `` Sex '' , 1 ) ; | Why must I use an int when searching for an entity with an OptionSetValue attribute , but use an OptionSetValue object when creating an entity ? |
C_sharp : I have the following table in SQL Server : ProductAttributeName : nvarchar ( 100 ) Value : nvarchar ( 200 ) This is mapped via Entity Framework into my class : Some rows of ProductAttributes have the following form : { Name : `` RAM '' , Value : `` 8 GB '' } , { Name : `` Cache '' , Value : `` 3000KB '' } I need to construct dynamically an ExpressionTree that is convertible to SQL that can does the following : If the Value starts with a number followed or not by an alphanumeric string , extract the number and compare it with a given valueThe really nasty thing is that I need to construct this expression tree dynamically . So far I 've managed this ( this considers the value as a decimal not as a string , so it does n't even try to do the whole regex stuff ) : EDIT : With the help provided below , this works : But I also need a cast to double and then a numeric comparison that is : Obviously this is not convertible to SQL : double.Parse ( ) . How could I construct the cast so it can be parsed into SQL from my Expression ? <code> public class ProductAttribute { public string Name { get ; set ; } public string Value { get ; set ; } } double value = ... ; Expression < Func < ProductAttribute , bool > > expression = p = > { Regex regex = new Regex ( @ '' \d+ '' ) ; Match match = regex.Match ( value ) ; if ( match.Success & & match.Index == 0 ) { matchExpression = value.Contains ( _parserConfig.TokenSeparator ) ? value.Substring ( 0 , value.IndexOf ( _parserConfig.TokenSeparator ) ) : value ; string comparand = match.Value ; if ( double.Parse ( comparand ) > value ) return true ; } return false ; } private Expression GenerateAnyNumericPredicate ( Type type , string valueProperty , string keyValue , double value ) { ParameterExpression param = Expression.Parameter ( type , `` s '' ) ; MemberExpression source = Expression.Property ( param , valueProperty ) ; ConstantExpression targetValue = GetConstantExpression ( value , value.GetType ( ) ) ; BinaryExpression comparisonExpression = Expression.GreaterThan ( source , targetValue ) ; return Expression.Lambda ( comparisonExpression , param ) ; } Expression < Func < ProductSpecification , bool > > expo = ps= > ps.Value.Substring ( 0 , ( SqlFunctions.PatIndex ( `` % [ ^0-9 ] % '' , ps.Value + `` . '' ) ? ? 0 ) - 1 ) == `` 1000 '' ; Expression < Func < ProductSpecification , bool > > expo = ps= > double.Parse ( ps.Value.Substring ( 0 , ( SqlFunctions.PatIndex ( `` % [ ^0-9 ] % '' , ps.Value + `` . '' ) ? ? 0 ) - 1 ) ) > 1000 ; | Build Expression Tree convertible to valid SQL dynamically that can compare string with doubles |
C_sharp : I 've just `` earned '' the privilege to maintain a legacy library coded in C # at my current work.This dll : Exposes methods for a big legacy system made with Uniface , that has no choice but calling COM objects.Serves as a link between this legacy system , and another system 's API.Uses WinForm for its UI in some cases.More visually , as I understand the components : * [ Big legacy system in Uniface ] * == [ COM ] == > [ C # Library ] == [ Managed API ] == > * [ Big EDM Management System ] *The question is : One of the methods in this C # Library takes too long to run and I `` should '' make it asynchronous ! I 'm used to C # , but not to COM at all . I 've already done concurrent programming , but COM seems to add a lot of complexity to it and all my trials so far end in either : A crash with no error message at allMy Dll only partially working ( displaying only part of its UI , and then closing ) , and still not giving me any error at allI 'm out of ideas and resources about how to handle threads within a COM dll , and I would appreciate any hint or help.So far , the biggest part of the code I 've changed to make my method asynchronous : Any hint or useful resource would be appreciated.Thank you.UPDATE 1 : Following answers and clues below ( especially about the SynchronizationContext , and with the help of this example ) I was able to refactor my code and making it to work , but only when called from another Window application in C # , and not through COM.The legacy system encounters a quite obscure error when I call the function and does n't give any details about the crash.UPDATE 2 : Latest updates in my trials : I managed to make the multithreading work when the calls are made from a test project , and not from the Uniface system.After multiple trials , we tend to think that our legacy system does n't support well multithreading in its current config . But that 's not the point of the question any more : ) Here is a exerpt of the code that seems to work : We are now considering other solutions than modifying this COM assembly , like encapsulating this library in a Windows Service and creating an interface between the system and the service . It should be more sustainable.. <code> // my public method called by the external systempublic int ComparedSearch ( string application , out string errMsg ) { errMsg = `` '' ; try { Action < string > asyncOp = AsyncComparedSearch ; asyncOp.BeginInvoke ( application , null , null ) ; } catch ( ex ) { // ... } return 0 ; } private int AsyncComparedSearch ( string application ) { // my actual method doing the work , that was the called method before } string application ; SynchronizationContext context ; // my public method called by the external systempublic int ComparedSearch ( string application , out string errMsg ) { this.application = application ; context = WindowsFormsSynchronizationContext.Current ; Thread t = new Thread ( new ThreadStart ( AsyncComparedSearchAndShowDocs ) ) ; t.Start ( ) ; errMsg = `` '' ; return 0 ; } private void AsyncComparedSearch ( ) { // ANY WORK THAT AS NOTHING TO DO WITH UI context.Send ( new SendOrPostCallback ( delegate ( object state ) { // METHODS THAT MANAGE UI SOMEHOW } ) , null ) ; } | Make my COM assembly call asynchronous |
C_sharp : After instantiating a list ( so ignoring the overhead associated with creating a list ) , what is the memory cost of adding the same object to a list over and over ? I believe that the following is just adding the same pointer to memory to the list over and over , and therefore this list is actually not taking up a lot of memory at all . Can somebody confirm that to be the case ? ( Let 's assume that a new newType takes up a considerable amount more of memory than a pointer does ) EDITnewType is a class . Sorry for not clarifying that . <code> List < newType > list = new List < newType > ( ) ; newType example = new newType ( ) ; for ( int i = 0 ; i < 10000 ; i++ ) { list.Add ( example ) ; } | List with repeat objects - What is the memory cost ? |
C_sharp : Possible Duplicate : Should I Create a New Delegate Instance ? Hi , I 've tried searching for the answer to this , but do n't really know what terms to search for , and none of the site-suggested questions are relevant . I 'm sure this must have been answered before though.Basically , can somebody tell me what 's the difference between these two lines in C # : For example : They both seem to do the same thing . <code> SomeEvent += SomeMethodSomeEvent += new SomeDelegate ( SomeMethod ) DataContextChanged += App_DataContextChanged ; DataContextChanged += new DependencyPropertyChangedEventHandler ( App_DataContextChanged ) ; | C # : what 's the difference between SomeEvent += Method and SomeEvent += new Delegate ( Method ) |
C_sharp : I have a data table with the following details.I want to merge values of Column ENTITY as below.is there any way we can achieve it using Linq ? <code> ID | VERSION | ENTITY1 | 01 | A011 | 01 | A022 | 01 | A012 | 01 | A02 ID | VERSION | ENTITY1 | 01 | A01/A022 | 01 | A01/A02 | C # : Merge Datarows in the datatable |
C_sharp : In my MVC controller , i have an action that will populate a stream which i will use later : I had this problem because ReSharper is giving out a warning : access on disposed closure on the line PopulateFile ( fileParams , stream ) and pointing out stream.I have searched for the meaning of it and it seems that it warns that i could possibly use an already disposed stream.I want to await the population of the stream because the task could take long . Is there a way that I can wait the population of the stream without ReSharper giving this warning ? Moreover , i am calling stream inside the using clause , the stream should not yet be disposed until i call flush or the last line of the using clause is executed right ? So why does ReSharper warn about accessing a disposed stream ? <code> [ HttpPost ] public async Task < HttpResponseMessage > BuildFileContent ( FileParameters fileParams ) { byte [ ] output ; if ( fileParams ! = null ) { using ( var stream = new MemoryStream ( ) ) { await Task.Run ( ( ) = > PopulateFile ( fileParams , stream ) ) ; // Here i populate the stream stream.Flush ( ) ; output = stream.ToArray ( ) ; } var guid = Guid.NewGuid ( ) .ToString ( ) ; FileContents.Add ( guid , output ) ; // just save the content for later use return this.Request.CreateResponse ( HttpStatusCode.OK , new { Value = guid } ) ; } return this.Request.CreateErrorResponse ( HttpStatusCode.BadRequest , `` Invalid parameters '' ) ; } | await population of a stream |
C_sharp : I have a simple wrapper for a Unity IoC container ( a temporary use of Service Locator [ anti- ] Pattern to introduce DI to a legacy codebase ) , and since the IUnityContainer in Unity implements IDisposable I wanted to expose that through the wrapper as well.The wrapper is simple enough : IIoCContainer is the domain interface which has nothing but T Resolve < T > ( ) on it , and of course IDisposable . So everything below that one method is simply the implementation of IDisposable as I found it on MSDN.However , when .Dispose ( ) is called on this object ( such as when exiting a using block ) , a StackOverflowException is raised . Debugging , it looks like the call stack repeats between : Dispose ( ) is called on this classWhich calls Dispose ( true ) on this classWhich calls Dispose ( ) on IUnityContainerWhich calls Dispose ( ) on this classI can resolve this in this case by putting a bool flag on the class , setting it on the first line of Dispose ( ) , and checking for it in Dispose ( bool ) , so the recursion ends at its second iteration . But why does this happen in the first place ? I can only assume I 've either missed something obvious or misunderstood something about resource disposal . But what ? <code> public class IoCContainer : IIoCContainer { private IUnityContainer _container ; public IoCContainer ( IUnityContainer container ) { _container = container ; } public T Resolve < T > ( ) { return _container.Resolve < T > ( ) ; } public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } ~IoCContainer ( ) { Dispose ( false ) ; } protected virtual void Dispose ( bool disposing ) { if ( disposing ) if ( _container ! = null ) { _container.Dispose ( ) ; _container = null ; } } } | Stack Overflow when Disposing a Managed Resource |
C_sharp : I 've made a class ( code below ) that handles the creation of a `` matching '' quiz item on a test , this is the output : It works fine.However , in order to get it completely random , I have to put the thread to sleep for at least 300 counts between the random shuffling of the two columns , anything lower than 300 returns both columns sorted in the same order , as if it is using the same seed for randomness : What do I have to do to make the shuffling of the two columns completely random without this time wait ? full code : <code> LeftDisplayIndexes.Shuffle ( ) ; Thread.Sleep ( 300 ) ; RightDisplayIndexes.Shuffle ( ) ; using System.Collections.Generic ; using System ; using System.Threading ; namespace TestSort727272 { class Program { static void Main ( string [ ] args ) { MatchingItems matchingItems = new MatchingItems ( ) ; matchingItems.Add ( `` one '' , `` 111 '' ) ; matchingItems.Add ( `` two '' , `` 222 '' ) ; matchingItems.Add ( `` three '' , `` 333 '' ) ; matchingItems.Add ( `` four '' , `` 444 '' ) ; matchingItems.Setup ( ) ; matchingItems.DisplayTest ( ) ; matchingItems.DisplayAnswers ( ) ; Console.ReadLine ( ) ; } } public class MatchingItems { public List < MatchingItem > Collection { get ; set ; } public List < int > LeftDisplayIndexes { get ; set ; } public List < int > RightDisplayIndexes { get ; set ; } private char [ ] _numbers = { ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' } ; private char [ ] _letters = { ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' , ' g ' , ' h ' } ; public MatchingItems ( ) { Collection = new List < MatchingItem > ( ) ; LeftDisplayIndexes = new List < int > ( ) ; RightDisplayIndexes = new List < int > ( ) ; } public void Add ( string leftText , string rightText ) { MatchingItem matchingItem = new MatchingItem ( leftText , rightText ) ; Collection.Add ( matchingItem ) ; LeftDisplayIndexes.Add ( Collection.Count - 1 ) ; RightDisplayIndexes.Add ( Collection.Count - 1 ) ; } public void DisplayTest ( ) { Console.WriteLine ( `` '' ) ; Console.WriteLine ( `` -- TEST : -- -- -- -- -- -- -- -- -- -- -- -- - '' ) ; for ( int i = 0 ; i < Collection.Count ; i++ ) { int leftIndex = LeftDisplayIndexes [ i ] ; int rightIndex = RightDisplayIndexes [ i ] ; Console.WriteLine ( `` { 0 } . { 1 , -12 } { 2 } . { 3 } '' , _numbers [ i ] , Collection [ leftIndex ] .LeftText , _letters [ i ] , Collection [ rightIndex ] .RightText ) ; } } public void DisplayAnswers ( ) { Console.WriteLine ( `` '' ) ; Console.WriteLine ( `` -- ANSWERS : -- -- -- -- -- -- -- -- -- -- -- -- - '' ) ; for ( int i = 0 ; i < Collection.Count ; i++ ) { string leftLabel = _numbers [ i ] .ToString ( ) ; int leftIndex = LeftDisplayIndexes [ i ] ; int rightIndex = RightDisplayIndexes.IndexOf ( leftIndex ) ; string answerLabel = _letters [ rightIndex ] .ToString ( ) ; Console.WriteLine ( `` { 0 } . { 1 } '' , leftLabel , answerLabel ) ; } } public void Setup ( ) { do { LeftDisplayIndexes.Shuffle ( ) ; Thread.Sleep ( 300 ) ; RightDisplayIndexes.Shuffle ( ) ; } while ( SomeLinesAreMatched ( ) ) ; } private bool SomeLinesAreMatched ( ) { for ( int i = 0 ; i < LeftDisplayIndexes.Count ; i++ ) { int leftIndex = LeftDisplayIndexes [ i ] ; int rightIndex = RightDisplayIndexes [ i ] ; if ( leftIndex == rightIndex ) return true ; } return false ; } public void DisplayAsAnswer ( int numberedIndex ) { Console.WriteLine ( `` '' ) ; Console.WriteLine ( `` -- ANSWER TO { 0 } : -- -- -- -- -- -- -- -- -- -- -- -- - '' , _numbers [ numberedIndex ] ) ; for ( int i = 0 ; i < Collection.Count ; i++ ) { int leftIndex = LeftDisplayIndexes [ i ] ; int rightIndex = RightDisplayIndexes [ i ] ; Console.WriteLine ( `` { 0 } . { 1 , -12 } { 2 } . { 3 } '' , _numbers [ i ] , Collection [ leftIndex ] .LeftText , _letters [ i ] , Collection [ rightIndex ] .RightText ) ; } } } public class MatchingItem { public string LeftText { get ; set ; } public string RightText { get ; set ; } public MatchingItem ( string leftText , string rightText ) { LeftText = leftText ; RightText = rightText ; } } public static class Helpers { public static void Shuffle < T > ( this IList < T > list ) { Random rng = new Random ( ) ; int n = list.Count ; while ( n > 1 ) { n -- ; int k = rng.Next ( n + 1 ) ; T value = list [ k ] ; list [ k ] = list [ n ] ; list [ n ] = value ; } } } } | How can I get true randomness in this class without Thread.Sleep ( 300 ) ? |
C_sharp : I suppose this is more of a public rant , but why ca n't I get c # to infer my Id 's type ? and a defined EntityObject with a Guid as an Id as follows : Inheriting from the abstract EntityObject class defined as follows : Usage of the get method would be as follows : edited to provide further clarification . <code> public EntityT Get < EntityT > ( IdT id ) where EntityT : EntityObject < IdT > public Foo : EntityObject < Guid > public abstract class EntityObject < IdT > { public IdT id { get ; set ; } } IRepository repository = new Repository ( ) ; var hydratedFoo = repository.Get < Foo > ( someGuidId ) ; | Inference from Generic Type Question |
C_sharp : What I am looking for is a way to call a method after another method has been invoked but before it is entered . Example : In the example above I would like to have Tracer ( ) called after SomeFunction ( ) has been invoked by TestFun ( ) but before SomeFunction ( ) is entered . I 'd also like to get reflection data on SomeFunction ( ) .I found something interesting in everyone 's answers . The best answer to the question is to use Castle 's DynamicProxy ; however , this is not that I 'm going to use to solve my problem because it requires adding a library to my project . I have only a few methods that I need to `` trace '' so I 've chosen to go with a modified `` core '' methodology mixed with the way Dynamic Proxy is implemented . I explain this in my answer to my own question below.Just as a note I 'm going to be looking into AOP and the ContextBoundObject class for some other applications . <code> public class Test { public void Tracer ( ... ) { } public int SomeFunction ( string str ) { return 0 ; } public void TestFun ( ) { SomeFunction ( `` '' ) ; } } | Is there a way in .NET to have a method called automatically after another method has been invoked but before it is entered |
C_sharp : Not return value optimization in the traditional sense , but I was wondering when you have a situation like this : This could obviously be written more optimally : I just wondered whether anyone knew if the ( MS ) compiler was clever enough not to generate state machines for Method1 ( ) and Method2 ( ) in the first instance ? <code> private async Task Method1 ( ) { await Method2 ( ) ; } private async Task Method2 ( ) { await Method3 ( ) ; } private async Task Method3 ( ) { //do something async } private Task Method1 ( ) { return Method2 ( ) ; } private Task Method2 ( ) { return Method3 ( ) ; } private async Task Method3 ( ) { //do something async } | Does compiler perform `` return value optimization '' on chains of async methods |
C_sharp : This question stems from a bug where I iterated over a collection of Int64 and accidentally did foreach ( int i in myCollection ) . I was trying to debug the baffling problem of how when I did a linq query , i was not part of the myCollection.Here 's some code that surprised me : I expected the compiler to give me an error . The usual one is that an implicit cast does not exist . But no , it did n't mind this at all . Not even a warning ! The outputted value of ( int ) a incidentally is 1942903641.I 'm curious to know why the cast is permitted without any warnings and also how it comes up with that value . Any ideas ? <code> Int64 a = 12345678912345 ; Console.Write ( ( int ) a ) ; | Why does C # let me overflow without any error or warning when casting an Int64 to an Int32 and how does it do the cast ? |
C_sharp : I am trying to get the data from database by using the below code ... ..if there is no data in the table it will always goes to this statementI am using mysql.net connector for getting the data and i am doing winforms applicationsusing c # and the below code is for return sqlexceution ... function..even if there is no data the process flow will goes to this line table = ds.Tables [ 0 ] ; how can i reduce this ... ..would any one pls help on this ... . <code> public DataTable sales ( DateTime startdate , DateTime enddate ) { const string sql = @ '' SELECT memberAccTran_Source as Category , sum ( memberAccTran_Value ) as Value FROM memberacctrans WHERE memberAccTran_DateTime BETWEEN @ startdate AND @ enddate GROUP BY memberAccTran_Source '' ; return sqlexecution ( startdate , enddate , sql ) ; } private static DataTable sqlexecution ( DateTime startdate , DateTime enddate , string sql ) { var table = new DataTable ( ) ; using ( var conn = new MySql.Data.MySqlClient.MySqlConnection ( connectionstring ) ) { conn.Open ( ) ; var cmd = new MySql.Data.MySqlClient.MySqlCommand ( sql , conn ) ; var ds = new DataSet ( ) ; var parameter = new MySql.Data.MySqlClient.MySqlParameter ( `` @ startdate '' , MySql.Data.MySqlClient.MySqlDbType.DateTime ) ; parameter.Direction = ParameterDirection.Input ; parameter.Value = startdate.ToString ( dateformat ) ; cmd.Parameters.Add ( parameter ) ; var parameter2 = new MySql.Data.MySqlClient.MySqlParameter ( `` @ enddate '' , MySql.Data.MySqlClient.MySqlDbType.DateTime ) ; parameter2.Direction = ParameterDirection.Input ; parameter2.Value = enddate.ToString ( dateformat ) ; cmd.Parameters.Add ( parameter2 ) ; var da = new MySql.Data.MySqlClient.MySqlDataAdapter ( cmd ) ; da.Fill ( ds ) ; try { table = ds.Tables [ 0 ] ; } catch { table = null ; } } return table ; } | problem with getting data from database |
C_sharp : I 'm having some trouble finding answers to a question I have about some code specific to what i 'm working on and I can not seem to find some documentation on how Union works at it 's core mechanics in C # . So the problem is this.I have a set of data that works similar to this example : Is it more efficient to let Union do all the work ? Or is it better to compare each element using Contains ? If No for both , what is the best way to populate unique lists using the least amount of processing time possible ? Efficiency is key for this . Also , this is not homework , or anything work related , just learning related.The lists are continuous at runtime in the way that they are eventually wiped clean and repopulated . The changes in the lists are used to make decisions based on whether or not the final result lists which are all similar to this example , are used to come up with a final list and if that list is empty , its a fail condition , and if that list is not empty , its a success condition.Here 's a snippet of the code in question for one of the lists created : <code> object [ ] someMainTypeArray = new object [ n ] ; List < object > objList2 = new List < object > ( ) ; foreach ( object obj in someMainTypeArray ) { List < object > objList1 = new List < object > ( ) { `` 1 '' , '' 2 '' , '' 3 '' } ; //each obj has a property that will generate a list of data //objList1 is the result of the data specific to obj //some of this data could be duplicates //Which is better , this : foreach ( object test in objList1 ) { if ( ! objList2.Contains ( test ) ) { objList2.Add ( test ) ; } } //or this : objList2 = objList2.Union ( objList1 ) .ToList ( ) ; //Also , assume this has to happen anywhere from 0 to 60 times per second } Player.ClearMoves ( ) ; List < Pair < BoardLocation , BoardLocation > > attacking = new List < Pair < BoardLocation , BoardLocation > > ( ) ; foreach ( ChessPiece p in Board [ this.Player.Opponent ] ) { if ( p.TheoryMove ( this.Location ) ) { foreach ( Pair < BoardLocation , BoardLocation > l in Utility.GetLocations ( p.Location , this.Location ) ) { if ( ! attacking.Contains ( l ) ) { attacking.Add ( l ) ; } } } } if ( attacking.Count < 1 ) { return false ; } | C # Union vs Contains for lists of continuous data |
C_sharp : I am unable to view the debug information when using a Task of Tuple . E.G . When a breakpoint his hit , I can not view any variables on hover , in the local window , or in the watch window.The repro is just to create a new WPF app , add System.ValueTuple , add this code to MainWindow.xaml.cs , and then set breakpoints at both lines with `` return '' .Edit : If I add the un-viewable local variable to watch , I get : error CS8182 : Predefined type 'ValueTuple ` 2 ' must be a struct . <code> using System.Threading.Tasks ; using System.Windows ; namespace WpfApp2 { public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; } private async void Button_Click ( object sender , RoutedEventArgs e ) { var task1 = TaskWithLocalDebugInfo ( ) ; var task2 = TaskWithoutLocalDebugInfo ( ) ; } private async Task < bool > TaskWithLocalDebugInfo ( ) { var viewableInLocalWindowAndHover = true ; return viewableInLocalWindowAndHover ; } private async Task < ( bool , bool ) > TaskWithoutLocalDebugInfo ( ) { var notViewableInLocalWindowAndHover = true ; return ( notViewableInLocalWindowAndHover , notViewableInLocalWindowAndHover ) ; } } } | VS2017 Error debugging Task of Tuple |
C_sharp : I 'm trying to set up a TLS connection to an application running in a ( local ) VM using C # 's HttpClient on Windows . However , it results in a RemoteCertificateNameMismatch error every time . This piece of code : Results in this error : However , my certificate is valid according to Google Chrome and Mozilla Firefox , but not for Internet Explorer.See the screenshot taken from Chrome . The certificate seems valid . I 've created my own Certificate Authority certificate ( self signed certificate ) , then I used that to create my server certificate . I filled in the subject name . As Subject Alternative Name ( SAN ) I 've added the IP address . Is an IP address field inside the SAN field not supported in IE and HttpClient ? If so , is there some other way of validating a server certificate using an IP address ? I 'm using dotnet core 2.0 . <code> HttpClientHandler handler = new HttpClientHandler ( ) ; handler.ServerCertificateCustomValidationCallback = ( request , cert , chain , policyErrors ) = > { Console.WriteLine ( $ '' Policy Errors : { policyErrors } '' ) ; return policyErrors == SslPolicyErrors.None ; } ; HttpClient httpClient = new HttpClient ( handler ) { BaseAddress = new Uri ( `` https : //192.168.99.100/engine-rest '' ) } ; var result = httpClient.GetAsync ( `` /engine '' ) .Result ; Policy Errors : RemoteCertificateNameMismatchUnhandled Exception : System.AggregateException : One or more errors occurred . ( An error occurred while sending the request . ) -- - > System.Net.Http.HttpRequestException : An error occurred while sending the request . -- - > System.Net.Http.WinHttpxception : A security error occurred at System.Net.Http.WinHttpRequestCallback.OnRequestSendingRequest ( WinHttpRequestState state ) at System.Net.Http.WinHttpRequestCallback.RequestCallback ( IntPtr handle , WinHttpRequestState state , UInt32 internetStatus , IntPtr statusInformation , UInt32 statusInformationLength ) | How to start a trusted TLS connection with a server by IP address using HttpClient in C # ? |
C_sharp : Using the Entity-Component-System pattern I want to connect some systems with events . So some systems should n't run in a loop , they should just run on demand.Given the example of a Health system a Death system should only run when a component gets below 1 health.I thought about having two types of systems . The first type is a periodic system . This runs once per frame , for example a Render or Movement System . The other type is an event based system . As mentioned before a connection between Health and Death.First I created a basic interface used by both system types.Further I created the interfaces andbut I 'm not sure if they will be necessary . There is no problem usingbut I do n't want to run a system if not needed.There are two types of Events , a ChangeEvent and a ExecuteEvent . The first gets triggered when a value from a component has changed . The second one gets triggered when something should be done with a specific entity.If you Need or want to you can have a look at the EntityManagerhttps : //pastebin.com/NnfBc0N9the ComponentRequirementshttps : //pastebin.com/xt3YGVSvand the usage of the ECShttps : //pastebin.com/Yuze72xfAn example System would be something like thisHow can I create ChangeEvents and ExecuteEvents for the different systems ? EDITIs there a way to add event delegates to the components to run a specific system for this entity on change if a change event is listening or on demand if an execute event is listening ? By mentioning ChangeEvent and ExecuteEvent I just mean event delegates.Currently I could do something like thisBut I was hoping to achieve a better architecture by using event delegates to make systems communicate and share data between each other . <code> internal interface ISystem { List < Guid > EntityCache { get ; } // Only relevant entities get stored in there ComponentRequirements ComponentRequirements { get ; } // the required components for this system void InitComponentRequirements ( ) ; void InitComponentPools ( EntityManager entityManager ) ; void UpdateCacheEntities ( ) ; // update all entities from the cache void UpdateCacheEntity ( Guid cacheEntityId ) ; // update a single entity from the cache } internal interface IReactiveSystem : ISystem { // event based } internal interface IPeriodicSystem : ISystem { // runs in a loop } foreach ( ISystem system in entityManager.Systems ) { system.UpdateCacheEntities ( ) ; } internal class HealthSystem : IReactiveSystem { public HealthSystem ( EntityManager entityManager ) { InitComponentRequirements ( ) ; InitComponentPools ( entityManager ) ; } private Dictionary < Guid , HealthComponent > healthComponentPool ; public List < Guid > EntityCache { get ; } = new List < Guid > ( ) ; public ComponentRequirements ComponentRequirements { get ; } = new ComponentRequirements ( ) ; public void InitComponentRequirements ( ) { ComponentRequirements.AddRequiredType < HealthComponent > ( ) ; } public void InitComponentPools ( EntityManager entityManager ) { healthComponentPool = entityManager.GetComponentPoolByType < HealthComponent > ( ) ; } public void UpdateCacheEntities ( ) { for ( int i = 0 ; i < EntityCache.Count ; i++ ) { UpdateCacheEntity ( EntityCache [ i ] ) ; } } public void UpdateCacheEntity ( Guid cacheEntityId ) { Health healthComponent = healthComponentPool [ cacheEntityId ] ; healthComponent.Value += 10 ; // just some tests // update UI } } internal class HealthSystem : IReactiveSystem { //… other stuff IReactiveSystem deathSystem = entityManager.GetSystem < Death > ( ) ; // Get a system by its type public void UpdateCacheEntity ( Guid cacheEntityId ) { // Change Health component // Update UI if ( currentHealth < 1 ) // call the death system if the entity will be dead { deathSystem.UpdateCacheEntity ( cacheEntityId ) ; } } } | connect systems with events |
C_sharp : I 'm looking at customising the various pieces of text in an application for different customers . It seems like .resx resources would be a sensible way to do this . However , all the literature for resx I come across seems to be about localising for language differences ( as in English , French , Spanish , etc . ) , so just want to check it is the best thing simply for customer differences in text as well.And , hypothetically , could it also deal with different languages for different customers , e.g . : Is resx the way to go for customer differences ? <code> CustomerA.resxCustomerA.en-US.resxCustomerA.de-DE.resxCustomerB.resxCustomerB.en-US.resxCustomerB.de-DE.resx ... etc | Are resx files a suitable way to customise for different customers ? |
C_sharp : In my services all exposed methods have : It 's boring and ugly to repeat it over and over again . Is there any way to avoid that ? Is there a better way to keep the service working even if exceptions occur and keep sending the exception details to the Log class ? <code> try { // the method core is written here } catch ( Exception ex ) { Log.Append ( ex ) ; } | How to refactor logging in C # ? |
C_sharp : I have an industrial computer with some Digital I/O pins . The manufacturer provides some C++ libraries and examples to handle pin status change.I need to integrate this events onto a C # application . AFAIK the most simple way to perform this is : Make a managed C++/CLI wrapper for the manufacturer libraries that fires events when interruptions are issued from the DIO pins.Reference that wrapper and handle the events in the C # part as it they were normal C # events.I have tried to make this work with some mock objects with no luck . From the docs , the function EventHandler should do most of the `` dirty work '' in my case . Following info available in old threads and the EventHandler example in the MSDN docs I ended up with this test code : C++/CLIC # What am I doing wrong ? Is it something I am missing ? <code> using namespace System ; public ref class ThresholdReachedEventArgs : public EventArgs { public : property int Threshold ; property DateTime TimeReached ; } ; public ref class CppCounter { private : int threshold ; int total ; public : CppCounter ( ) { } ; CppCounter ( int passedThreshold ) { threshold = passedThreshold ; } void Add ( int x ) { total += x ; if ( total > = threshold ) { ThresholdReachedEventArgs^ args = gcnew ThresholdReachedEventArgs ( ) ; args- > Threshold = threshold ; args- > TimeReached = DateTime : :Now ; OnThresholdReached ( args ) ; } } event EventHandler < ThresholdReachedEventArgs^ > ^ ThresholdReached ; protected : virtual void OnThresholdReached ( ThresholdReachedEventArgs^ e ) { ThresholdReached ( this , e ) ; } } ; public ref class SampleHandler { public : static void c_ThresholdReached ( Object^ sender , ThresholdReachedEventArgs^ e ) { Console : :WriteLine ( `` The threshold of { 0 } was reached at { 1 } . `` , e- > Threshold , e- > TimeReached ) ; Environment : :Exit ( 0 ) ; } } ; void main ( ) { return ; CppCounter^ c = gcnew CppCounter ( 20 ) ; c- > ThresholdReached += gcnew EventHandler < ThresholdReachedEventArgs^ > ( SampleHandler : :c_ThresholdReached ) ; Console : :WriteLine ( `` press ' a ' key to increase total '' ) ; while ( Console : :ReadKey ( true ) .KeyChar == ' a ' ) { Console : :WriteLine ( `` adding one '' ) ; c- > Add ( 1 ) ; } } using System ; namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { CppCounter cc = new CppCounter ( 5 ) ; //cc.ThresholdReached += cs_ThresholdReached ; // < -- This is the offending line Console.WriteLine ( `` press ' a ' key to increase total '' ) ; while ( Console.ReadKey ( true ) .KeyChar == ' a ' ) { Console.WriteLine ( `` adding one '' ) ; cc.Add ( 1 ) ; } } static void cs_ThresholdReached ( object sender , ThresholdReachedEventArgs e ) { Console.WriteLine ( `` The threshold of { 0 } was reached at { 1 } . `` , e.Threshold , e.TimeReached ) ; Environment.Exit ( 0 ) ; } } class Counter { private int threshold ; private int total ; public Counter ( int passedThreshold ) { threshold = passedThreshold ; } public void Add ( int x ) { total += x ; if ( total > = threshold ) { ThresholdReachedEventArgs args = new ThresholdReachedEventArgs ( ) ; args.Threshold = threshold ; args.TimeReached = DateTime.Now ; OnThresholdReached ( args ) ; } } protected virtual void OnThresholdReached ( ThresholdReachedEventArgs e ) { EventHandler < ThresholdReachedEventArgs > handler = ThresholdReached ; if ( handler ! = null ) { handler ( this , e ) ; } } public event EventHandler < ThresholdReachedEventArgs > ThresholdReached ; } public class ThresholdReachedEventArgs : EventArgs { public int Threshold { get ; set ; } public DateTime TimeReached { get ; set ; } } } | Firing events in C++ and handling them in C # |
C_sharp : I have such constructionCan I get all unique value from propIDs with LINQ.For example I have list of ( 1,2 ) ( 4,5 ) ( 1,5 ) ( 1,2 ) ( 1,5 ) and I must get ( 1,2 ) ( 4,5 ) ( 1,5 ) <code> List < int [ ] > propIDs = new List < int [ ] > ( ) ; | How can I retrieve a set of unique arrays from a list of arrays using LINQ ? |
C_sharp : What is the correct way for a application to restart another copy of itself with the same arguments ? My current method is to do the followingHowever it seems like there is a lot of busy work in there . Ignoring the striping of the vshost , I still need to wrap arguments that have spaces with `` and combine the array of arguments in to a single string.Is there a better way to launch a new copy of the program ( including the same arguments ) , perhaps a way just needing to pass in Enviroment.CommandLine or takes a string array for the arguments ? <code> static void Main ( ) { Console.WriteLine ( `` Start New Copy '' ) ; Console.ReadLine ( ) ; string [ ] args = Environment.GetCommandLineArgs ( ) ; //Will not work if using vshost , uncomment the next line to fix that issue . //args [ 0 ] = Regex.Replace ( args [ 0 ] , `` \\.vshost\\.exe $ '' , `` .exe '' ) ; //Put quotes around arguments that contain spaces . for ( int i = 1 ; i < args.Length ; i++ ) { if ( args [ i ] .Contains ( ' ' ) ) args [ i ] = String.Concat ( ' '' ' , args [ i ] , ' '' ' ) ; } //Combine the arguments in to one string string joinedArgs = string.Empty ; if ( args.Length > 1 ) joinedArgs = string.Join ( `` `` , args , 1 , args.Length - 1 ) ; //Start the new process Process.Start ( args [ 0 ] , joinedArgs ) ; } | Start a second copy of the program with the same arguments |
C_sharp : I 'm developing an app and I 'd like when the user is in Tablet Mode and switches from one app to other to show a black screen when you press `` alt + tab '' and the opened apps are being shown . I 'd like instead of showing the `` myTrip '' screenshot of the app to show a black screen.I know for WPF we had ShowInTaskbar = false but nothing like that in Windows 10 Universal App Platform.I tried so far : Window.Current.CoreWindow.VisibilityChanged += CoreWindow_VisibilityChanged ; But the snapshot image of the app is taken before those events are being called . Any idea on how to do it ? Regards . <code> private void Current_VisibilityChanged ( object sender , VisibilityChangedEventArgs e ) { var parentGrid = RootPanel ( ) ; parentGrid.Visibility = e.Visible ? Visibility.Visible : Visibility.Collapsed ; } | Hide app preview from Alt-tab taskbar in Windows 10 Universal App Platform |
C_sharp : I want to learn how can I add to my controller some SQL query but I do n't know how to do it properly.My controller isBy default page is giving me the next data . I want to add the next SQL query to the controller which will give me data that I want it on page to display . <code> public ActionResult Index ( ) { return View ( db.Student.ToList ( ) ) ; } ID , NAME , STATUS 1 Bella , 5 2 Bella , 5 3 Bella , 7 ( select distinct id , name , max ( status ) from students group by id , name ) ID , NAME , STATUS 3 Bella , 7 | ASP.net.MVC 5 create a page which will display sql query |
C_sharp : I have a situation where I 'd like the behaviour of the compiler explained . Given a little code : The following compiles and runs : If we make a change to the signature of the Foo class and add the sealed keyword : Then I get a compiler error on the following line : Of : Can not convert type 'MyNamespace.FooGetter ' to 'MyNamespace.IFoo < T > 'Can someone explain what is happening here with regards to the sealed keyword ? This is C # 4 against a .NET 4 project in Visual Studio 2010.Update : interestingly enough I stumbled on that part of the behaviour when I was wondering why the following code fixes it when sealed is applied : Update : just for clarification , it all runs fine when the type of T requested is the same as the type of T used by the concrete type . If the types differ , the cast fails at runtime with something like : Unable to cast object of type 'MyNamespace.StringFoo ' to type 'MyNamespace.IFoo ` 1 [ System.Int32 ] 'In the above example , StringFoo : IFoo < string > and the caller asks to get an int . <code> interface IFoo < T > { T Get ( ) ; } class FooGetter : IFoo < int > { public int Get ( ) { return 42 ; } } static class FooGetterGetter { public static IFoo < T > Get < T > ( ) { return ( IFoo < T > ) new FooGetter ( ) ; } } sealed class FooGetter : IFoo < int > // etc return ( IFoo < T > ) new FooGetter ( ) ; return ( IFoo < T > ) ( IFoo < int > ) new FooGetter ( ) ; | Sealed keyword affects the compiler 's opinion on a cast |
C_sharp : I 'm using Lidgren and for every new type of message I make , I end up writing the same kind of code . I 'm creating an instance of NetOutgoingMessage , running various assignment calls on it , then sending it when I 'm done . Creation and send are the same , so I want to write a wrapper to do this for me , but it 's a sealed class and it 's not IDisposable . What I 'm doing is something like : And I want to do something like : Obviously I ca n't do using so is there another common way if implementing functionality like this ? I 'm not looking for an incredibly complicated solution , as this is just about maintainability for me , so I do n't have a problem repeating my code for every message . But I am curious if there 's a fun C # trick I do n't know about for this . <code> NetOutgoingMessage om = server.CreateMessage ( ) ; om.Write ( messageType ) ; om.Write ( data1 ) ; om.Write ( data2 ) ; server.SendMessage ( om , server.Connections , NetDeliveryMethod.UnreliableSequenced , 0 ) ; using ( AutoNetOutgoingMessage om ( server , messageType , NetDeliveryMethod.UnreliableSequenced ) ) { om.Write ( data1 ) ; om.Write ( data2 ) ; } | Something similar to `` using '' that will create an object and call a method on it when done , but let me do what I want in between |
C_sharp : Is this code even complex enough to deserve a higher level of abstraction ? <code> public static JsonStructure Parse ( string jsonText ) { var result = default ( JsonStructure ) ; var structureStack = new Stack < JsonStructure > ( ) ; var keyStack = new Stack < string > ( ) ; var current = default ( JsonStructure ) ; var currentState = ParserState.Begin ; var key = default ( string ) ; var value = default ( object ) ; foreach ( var token in Lexer.Tokenize ( jsonText ) ) { switch ( currentState ) { case ParserState.Begin : switch ( token.Type ) { case TokenType.BeginObject : currentState = ParserState.Name ; current = result = new JsonObject ( ) ; break ; case TokenType.BeginArray : currentState = ParserState.Value ; current = result = new JsonArray ( ) ; break ; default : throw new JsonException ( token , currentState ) ; } break ; case ParserState.Name : switch ( token.Type ) { case TokenType.String : currentState = ParserState.NameSeparator ; key = ( string ) token.Value ; break ; default : throw new JsonException ( token , currentState ) ; } break ; case ParserState.NameSeparator : switch ( token.Type ) { case TokenType.NameSeparator : currentState = ParserState.Value ; break ; default : throw new JsonException ( token , currentState ) ; } break ; case ParserState.Value : switch ( token.Type ) { case TokenType.Number : case TokenType.String : case TokenType.True : case TokenType.False : case TokenType.Null : currentState = ParserState.ValueSeparator ; value = token.Value ; break ; case TokenType.BeginObject : structureStack.Push ( current ) ; keyStack.Push ( key ) ; currentState = ParserState.Name ; current = new JsonObject ( ) ; break ; case TokenType.BeginArray : structureStack.Push ( current ) ; currentState = ParserState.Value ; current = new JsonArray ( ) ; break ; default : throw new JsonException ( token , currentState ) ; } break ; case ParserState.ValueSeparator : var jsonObject = ( current as JsonObject ) ; var jsonArray = ( current as JsonArray ) ; if ( jsonObject ! = null ) { jsonObject.Add ( key , value ) ; currentState = ParserState.Name ; } if ( jsonArray ! = null ) { jsonArray.Add ( value ) ; currentState = ParserState.Value ; } switch ( token.Type ) { case TokenType.EndObject : case TokenType.EndArray : currentState = ParserState.End ; break ; case TokenType.ValueSeparator : break ; default : throw new JsonException ( token , currentState ) ; } break ; case ParserState.End : switch ( token.Type ) { case TokenType.EndObject : case TokenType.EndArray : case TokenType.ValueSeparator : var previous = structureStack.Pop ( ) ; var previousJsonObject = ( previous as JsonObject ) ; var previousJsonArray = ( previous as JsonArray ) ; if ( previousJsonObject ! = null ) { previousJsonObject.Add ( keyStack.Pop ( ) , current ) ; currentState = ParserState.Name ; } if ( previousJsonArray ! = null ) { previousJsonArray.Add ( current ) ; currentState = ParserState.Value ; } if ( token.Type ! = TokenType.ValueSeparator ) { currentState = ParserState.End ; } current = previous ; break ; default : throw new JsonException ( token , currentState ) ; } break ; default : break ; } } return result ; } | How could I refactor this into more manageable code ? |
C_sharp : Let 's say I have a method as follows : But the above code has two lookups in the dictionary : The test for the existance of the keyThe actual retrieval of the valueIs there a more optimal way to phrase such a function , so that only one lookup is performed , but the case of `` not found '' is still handled via a null return ( i.e. , not via a not found exception ) ? For example , it would have been nice if the lookup for the key returned some sort of iterator that could be used to retrieve the value or an invalid iterator if the value was not found as is done in C++ . Perhaps C # has a better way of doing this given its language features . <code> internal MyClass GetValue ( long key ) { if ( _myDictionary.ContainsKey ( key ) ) return _myDictionary [ key ] ; return null ; // Not found } IDictionary < long , MyClass > _myDictionary= ... | C # optimal IDictionary usage for lookup with possibility of not found |
C_sharp : I 'm using ProtoBuf.NET to serialize/deserialize some classes . I 'm finding that on deserializing , I 'm getting a corrupt byte [ ] ( extra 0 's ) . Before you ask , yes , I need the *WithLengthPrefix ( ) versions of the ProtoBuf API since the ProtoBuf portion is at the starts of a custom stream : ) Anyway , I seeThe extra AAA*A in the ByteArray member are basically hex 0x00 's in base64.The app logic is similar to The DTO classes areI do see that when I move ByteArray = new byte [ 12 ] out form the Parent constructor into it 's Init ( ) method , ProtoBuf works fine . However we have app logic that prevents that in the real version ( vs the SO trim down code you see above ) . Are we doing something wrong or is this a bug in ProtoBuf ? <code> Original object is ( JSON depiction ) : { `` ByteArray '' : '' M+B6q+PXNuF8P5hl '' , '' ByteArray2 '' : '' DmErxVQ2y87IypSRcfxcWA== '' , '' K '' :2 , '' V '' :1.0 } Protobuf : Raw Hex ( 42 bytes ) :29-2A-20-0A-0C-33-E0-7A-AB-E3-D7-36-E1-7C-3F-98-65-12-10-0E-61-2B-C5-54-36-CB-CE-C8-CA-94-91-71-FC-5C-58-08-02-15-00-00-80-3FRegenerated object is ( JSON depiction ) : { `` ByteArray '' : '' AAAAAAAAAAAAAAAAM+B6q+PXNuF8P5hl '' , '' ByteArray2 '' : '' DmErxVQ2y87IypSRcfxcWA== '' , '' K '' :2 , '' V '' :1.0 } static void Main ( string [ ] args ) { var parent = new Parent ( ) ; parent.Init ( ) ; Console.WriteLine ( `` \nOriginal object is ( JSON depiction ) : '' ) ; Console.WriteLine ( JsonConvert.SerializeObject ( parent ) ) ; using ( var ms = new MemoryStream ( ) ) { Serializer.SerializeWithLengthPrefix ( ms , parent , PrefixStyle.Base128 ) ; byte [ ] bytes2 = ms.ToArray ( ) ; var hex2 = BitConverter.ToString ( bytes2 ) ; Console.WriteLine ( `` \nProtobuf : Hex ( { 0 } bytes ) : \n { 1 } '' , bytes2.Length , hex2 ) ; ms.Seek ( 0 , SeekOrigin.Begin ) ; var backFirst = Serializer.DeserializeWithLengthPrefix < Parent > ( ms , PrefixStyle.Base128 ) ; Console.WriteLine ( `` \nRegenerated object is ( JSON depiction ) : '' ) ; Console.WriteLine ( JsonConvert.SerializeObject ( backFirst ) ) ; } } [ DataContract ] [ ProtoContract ] internal class Parent : Child { [ DataMember ( Name = `` ByteArray '' , Order = 10 ) ] [ ProtoMember ( 1 ) ] public byte [ ] ByteArray { get ; set ; } [ DataMember ( Name = `` ByteArray2 '' , Order = 30 , EmitDefaultValue = false ) ] [ ProtoMember ( 2 ) ] public byte [ ] ByteArray2 { get ; set ; } public Parent ( ) { ByteArray = new byte [ 12 ] ; } internal void Init ( bool bindRow = false ) { base.Init ( ) ; var rng = new RNGCryptoServiceProvider ( ) ; rng.GetBytes ( ByteArray ) ; ByteArray2 = new byte [ 16 ] ; rng.GetBytes ( ByteArray2 ) ; } } [ DataContract ] [ ProtoContract ] [ ProtoInclude ( 5 , typeof ( Parent ) ) ] public class Child { [ DataMember ( Name = `` K '' , Order = 100 ) ] [ ProtoMember ( 1 ) ] public Int32 K { get ; set ; } [ DataMember ( Name = `` V '' , Order = 110 ) ] [ ProtoMember ( 2 ) ] public float V { get ; set ; } internal void Init ( ) { K = 2 ; V = 1.0f ; } } | ProtoBuf corrupts byte array during deserialization ( extra 0 's added ) |
C_sharp : If you are coding C # inside visual studio , and you have a multiline comment , thusly : Then if you are inside the comment , like after the word `` comment '' in my example , and you hit enter , Visual Studio adds a `` * `` on the new line and places your cursor even with the `` * '' that started the comment.I hate this behavior . It is never what I want . Any way to turn it off ? I wandered through the editor options but I could n't find it . <code> /*This is a very interesting commentthat consists of multiple lines*/ | Prevent Visual Studio from adding extra asterisks when hitting enter inside a multiline comment |
C_sharp : I want to achieve that I can subdivide a Bezier Curve with a given distance . Now it works if the Bezier is a straight line , but if I change a Controll-Point ( B & C ) so the Bezier get 's curved , the gap between the calculated Points are no more like the given Distance ! I 've look through the web , but did n't crash in to a similar Problem . <code> float t = Distance between subdividedParts / bezier length ; //A , B , C , D = ControllPoints of BezierGetPoint ( A , B , C , D , t ) ; //GetPoint equation : public static Vector3 GetPoint ( Vector3 p0 , Vector3 p1 , Vector3 p2 , Vector3 p3 , float t ) { t = Mathf.Clamp01 ( t ) ; float OneMinusT = 1f - t ; return OneMinusT * OneMinusT * OneMinusT * p0 + 3f * OneMinusT * OneMinusT * t * p1 + 3f * OneMinusT * t * t * p2 + t * t * t * p3 ; } | Subdivide Bezier Curves |
C_sharp : Based on my understanding , given a C # array , the act of iterating over the array concurrently from multiple threads is a thread safe operation.By iterating over the array I mean reading all the positions inside the array by means of a plain old for loop . Each thread is simply reading the content of a memory location inside the array , no one is writing anything so all the threads read the same thing in a consistent manner . This is a piece of code doing what I wrote above : So , my understanding is that the method DoSomethingUseless is thread safe and that there is no need to replace the string [ ] with a thread safe type ( like ImmutableArray < string > for instance ) .Am I correct ? Now let 's suppose that we have an instance of IEnumerable < T > . We do n't know what the underlying object is , we just know that we have an object implementing IEnumerable < T > , so we are able to iterate over it by using the foreach loop . Based on my understanding , in this scenario there is no guarantee that iterating over this object from multiple threads concurrently is a thread safe operation . Put another way , it is entirely possible that iterating over the IEnumerable < T > instance from different threads at the same time breaks the internal state of the object , so that it becomes corrupted . Am I correct on this point ? What about the IEnumerable < T > implementation of the Array class ? Is it thread safe ? Put another way , is the following code thread safe ? ( this is exactly the same code as above , but now the array is iterated by using a foreach loop instead of a for loop ) Is there any reference stating which IEnumerable < T > implementations in the .NET base class library are actually thread safe ? <code> public class UselessService { private static readonly string [ ] Names = new [ ] { `` bob '' , `` alice '' } ; public List < int > DoSomethingUseless ( ) { var temp = new List < int > ( ) ; for ( int i = 0 ; i < Names.Length ; i++ ) { temp.Add ( Names [ i ] .Length * 2 ) ; } return temp ; } } public class UselessService { private static readonly string [ ] Names = new [ ] { `` bob '' , `` alice '' } ; public List < int > DoSomethingUseless ( ) { var temp = new List < int > ( ) ; foreach ( var name in Names ) { temp.Add ( name.Length * 2 ) ; } return temp ; } } | Is iterating over an array with a for loop a thread safe operation in C # ? What about iterating an IEnumerable < T > with a foreach loop ? |
C_sharp : I thought T ? is just a compiler shorthand for Nullable < T > . According to MSDN : The syntax T ? is shorthand for Nullable < T > , where T is a value type . The two forms are interchangeable.However , there is a little ( insignificant ) difference : Visual Studio does n't allow me to call static methods on shorthands : Why ? Is there any reason for this limitation ? <code> bool b1 = Nullable < int > .Equals ( 1 , 2 ) ; //no errorbool b2 = int ? .Equals ( 1 , 2 ) ; //syntax error `` Invalid expression term 'int ' '' | Why is it impossible to call static methods on Nullable < T > shorthands ? |
C_sharp : I have existing ap.net c # website is working with mysql database . now i am planning to create mobile app for that website for that API needs to be ready.I am creating an API into PHP Laravel Framework . for RegistrationAPI needs to generate password.Asp.net using its inbuilt library for generating password like it automatically generates password in table called `` webpages_membership '' Note : I am using same database which is used by aps.net working website . so my website will be in asp.net and api will be now in php.I found MembershipModel class in php which is used to compare two password but it can not generate password.I have successfully created Login APi in PHP which is working fine using above class . <code> WebSecurity.CreateUserAndAccount ( `` username '' , `` password '' ) ; < ? php/* * Author : Mr. Juned Ansari * Date : 15/02/2017 * Purpose : It Handles Login Encryption And Decryption Related Activities */class MembershipModel { function bytearraysequal ( $ source , $ target ) { if ( $ source == null || $ target == null || ( strlen ( $ source ) ! = strlen ( $ target ) ) ) return false ; for ( $ ctr = 0 ; $ ctr < strlen ( $ target ) ; $ ctr++ ) { if ( $ target [ $ ctr ] ! = $ source [ $ ctr ] ) return false ; } return true ; } //This Function is Used to verifypassword function verifypassword ( $ hashedPassword , $ password ) { $ PBKDF2IterCount = 1000 ; // default for Rfc2898DeriveBytes $ PBKDF2SubkeyLength = 32 ; // 256 bits $ SaltSize = 16 ; // 128 bits if ( $ hashedPassword == null ) { return false ; //show_error ( `` hashedPassword is null '' ) ; } if ( $ password == null ) { return false ; //show_error ( `` Password is null '' ) ; } $ hashedPasswordBytes = base64_decode ( $ hashedPassword ) ; if ( strlen ( $ hashedPasswordBytes ) ! = 48 ) { return false ; } $ salt = substr ( $ hashedPasswordBytes , 0 , $ SaltSize ) ; $ storedSubkey = substr ( $ hashedPasswordBytes , $ SaltSize , $ PBKDF2SubkeyLength ) ; $ generatedSubkey = $ this- > encript ( 'sha1 ' , $ password , $ salt , $ PBKDF2IterCount , $ PBKDF2SubkeyLength , true ) ; return $ this- > bytearraysequal ( $ storedSubkey , $ generatedSubkey ) ; } function encript ( $ algorithm , $ password , $ salt , $ count , $ key_length , $ raw_output = false ) { $ algorithm = strtolower ( $ algorithm ) ; if ( ! in_array ( $ algorithm , hash_algos ( ) , true ) ) return false ; //show_error ( 'PBKDF2 ERROR : Invalid hash algorithm . ' ) ; if ( $ count < = 0 || $ key_length < = 0 ) return false ; //show_error ( 'PBKDF2 ERROR : Invalid parameters . ' ) ; $ hash_length = strlen ( hash ( $ algorithm , `` '' , true ) ) ; $ block_count = ceil ( $ key_length / $ hash_length ) ; $ output = `` '' ; for ( $ i = 1 ; $ i < = $ block_count ; $ i++ ) { $ last = $ salt . pack ( `` N '' , $ i ) ; $ last = $ xorsum = hash_hmac ( $ algorithm , $ last , $ password , true ) ; for ( $ j = 1 ; $ j < $ count ; $ j++ ) { $ xorsum ^= ( $ last = hash_hmac ( $ algorithm , $ last , $ password , true ) ) ; } $ output .= $ xorsum ; } return substr ( $ output , 0 , $ key_length ) ; } } | How to Generate ASP.NET Password using PHP |
C_sharp : All , I have a method that is currently used to invoke DLLs of return type bool , this works great . This method isNow , I want to extend this method so that I can retrieve return values from a DLL of any type . I planned to do this using generics but immediately have gone into territory unknown to me . How do I return T when it is unknown at compile time , I have looked at reflection but I am unsure how it would be used in this case . Take the first check in the above codeHow can I achieve what I want , or shall I just overload the method ? Thanks very much for your help . <code> public static bool InvokeDLL ( string strDllName , string strNameSpace , string strClassName , string strMethodName , ref object [ ] parameters , ref string strInformation , bool bWarnings = false ) { try { // Check if user has access to requested .dll . if ( ! File.Exists ( Path.GetFullPath ( strDllName ) ) ) { strInformation = String.Format ( `` Can not locate file ' { 0 } ' ! `` , Path.GetFullPath ( strDllName ) ) ; return false ; } else { // Execute the method from the requested .dll using reflection . Assembly DLL = Assembly.LoadFrom ( Path.GetFullPath ( strDllName ) ) ; Type classType = DLL.GetType ( String.Format ( `` { 0 } . { 1 } '' , strNameSpace , strClassName ) ) ; if ( classType ! = null ) { object classInstance = Activator.CreateInstance ( classType ) ; MethodInfo methodInfo = classType.GetMethod ( strMethodName ) ; if ( methodInfo ! = null ) { object result = null ; result = methodInfo.Invoke ( classInstance , new object [ ] { parameters } ) ; return Convert.ToBoolean ( result ) ; } } // Invocation failed fatally . strInformation = String.Format ( `` Could not invoke the requested DLL ' { 0 } ' ! `` + `` Please insure that you have specified the namespace , class name `` + `` method and respective parameters correctly ! `` , Path.GetFullPath ( strDllName ) ) ; return false ; } } catch ( Exception eX ) { strInformation = String.Format ( `` DLL Error : { 0 } ! `` , eX.Message ) ; if ( bWarnings ) Utils.ErrMsg ( eX.Message ) ; return false ; } } public static T InvokeDLL < T > ( string strDllName , string strNameSpace , string strClassName , string strMethodName , ref object [ ] parameters , ref string strInformation , bool bWarnings = false ) { try { // Check if user has access to requested .dll . if ( ! File.Exists ( Path.GetFullPath ( strDllName ) ) ) { strInformation = String.Format ( `` Can not locate file ' { 0 } ' ! `` , Path.GetFullPath ( strDllName ) ) ; return `` WHAT/HOW ? ? `` ; ... | Defining Generic Methods |
C_sharp : I have a class called ConfigurationElementCollection < T > It 's a generic implementation of System.Configuration.ConfigurationElementCollectionIt 's stored in our solutions ' , Project.Utility.dll but I 've defined it as being part of the System.Configuration namespaceIs putting classes in the System . * namespaces considered bad practice when they are n't part of the System . * Base Class Libraries ? On the face of it , it seems to make sense , as it keeps similar classes with similar functionality in the same place . However it could cause confusion for someone who did n't realise it was actually part of a non .net BCL as they would n't know where to go hunting for the reference . <code> namespace System.Configuration { [ ConfigurationCollection ( typeof ( ConfigurationElement ) ) ] public class ConfigurationElementCollection < T > : ConfigurationElementCollection where T : ConfigurationElement , new ( ) { ... } } | Is using System . * Namespaces on your own classes considered Bad Practice ? |
C_sharp : We 're using the Stream functionality in RavenDB to load , transform and migrate data between 2 databases like so : The problem is that one of the collections has millions of rows , and we keep receiving an IOException in the following format : This happens quite a long way into streaming and of course transient connection issues will occur over this sort of period ( It takes hours to complete ) .However , when we retry , as we are using a Query we have to start from scratch . So ultimately if there is a connection failure during the whole Stream then we have to try it again , and again until it works end to end.I know you can use ETag with stream to effectively restart at a certain point , however there is no overload to do this with a Query which we need to filter the results being migrated and specify the correct collection.So , in RavenDB , is there a way to either improve the internal resilience of the connection ( connection string property , internal settings etc ) or effectively `` recover '' a stream on an error ? <code> var query = originSession.Query < T > ( IndexForQuery ) ; using ( var stream = originSession.Advanced.Stream ( query ) ) { while ( stream.MoveNext ( ) ) { var streamedDocument = stream.Current.Document ; OpenSessionAndMigrateSingleDocument ( streamedDocument ) ; } } Application : MigrateToNewSchema.exeFramework Version : v4.0.30319Description : The process was terminated due to an unhandled exception.Exception Info : System.IO.IOExceptionStack : at System.Net.ConnectStream.Read ( Byte [ ] , Int32 , Int32 ) at System.IO.Compression.DeflateStream.Read ( Byte [ ] , Int32 , Int32 ) at System.IO.Compression.GZipStream.Read ( Byte [ ] , Int32 , Int32 ) at System.IO.StreamReader.ReadBuffer ( Char [ ] , Int32 , Int32 , Boolean ByRef ) at System.IO.StreamReader.Read ( Char [ ] , Int32 , Int32 ) at Raven.Imports.Newtonsoft.Json.JsonTextReader.ReadData ( Boolean , Int32 ) at Raven.Imports.Newtonsoft.Json.JsonTextReader.ReadStringIntoBuffer ( Char ) at Raven.Imports.Newtonsoft.Json.JsonTextReader.ParseString ( Char ) at Raven.Imports.Newtonsoft.Json.JsonTextReader.ParseValue ( ) at Raven.Imports.Newtonsoft.Json.JsonTextReader.ReadInternal ( ) at Raven.Imports.Newtonsoft.Json.JsonTextReader.Read ( ) at Raven.Json.Linq.RavenJObject.Load ( Raven.Imports.Newtonsoft.Json.JsonReader ) at Raven.Json.Linq.RavenJObject.Load ( Raven.Imports.Newtonsoft.Json.JsonReader ) at Raven.Json.Linq.RavenJToken.ReadFrom ( Raven.Imports.Newtonsoft.Json.JsonReader ) at Raven.Client.Connection.ServerClient+ < YieldStreamResults > d__6b.MoveNext ( ) at Raven.Client.Document.DocumentSession+ < YieldQuery > d__c ` 1 [ [ System.__Canon , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] .MoveNext ( ) at MigrateToNewSchema.Migrator.DataMigratorBase ` 1 [ [ System.__Canon , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] .MigrateCollection ( ) at MigrateToNewSchema.Program.MigrateData ( MigrateToNewSchema.Enums.CollectionToMigrate , Raven.Client.IDocumentStore , Raven.Client.IDocumentStore ) at MigrateToNewSchema.Program.Main ( System.String [ ] ) | RavenDB Stream for Unbounded Results - Connection Resilience |
C_sharp : In an effort to explore how the C # compiler optimizes code , I 've created a simple test application . With each test change , I 've compiled the application and then opened the binary in ILSpy.I just noticed something that , to me , is weird . Obviously this is intentional , however , I ca n't think of a good reason why the compiler would do this.Consider the following code : Pointless code , but I had written this to see how ILSpy would interpret the if statements . However , when I compiled/decompiled this code , I did notice something that had me scratching my head . My first variable test_1 was optimized to test_ ! Is there a good reason why the C # compiler would do this ? For full inspection this is the output of Main ( ) that I 'm seeing in ILSpy.UPDATEApparently after inspecting the IL , this is an issue with ILSpy , not the C # compiler . Eugene Podskal has given a good answer to my initial comments and observations . However , I am interested in knowing if this is rather a bug within ILSpy or if this is intentional functionality . <code> static void Main ( string [ ] args ) { int test_1 = 1 ; int test_2 = 0 ; int test_3 = 0 ; if ( test_1 == 1 ) Console.Write ( 1 ) ; else if ( test_2 == 1 ) Console.Write ( 1 ) ; else if ( test_3 == 1 ) Console.Write ( 2 ) ; else Console.Write ( `` x '' ) ; } private static void Main ( string [ ] args ) { int test_ = 1 ; //Where did the `` 1 '' go at the end of the variable name ? ? ? int test_2 = 0 ; int test_3 = 0 ; if ( test_ == 1 ) { Console.Write ( 1 ) ; } else { if ( test_2 == 1 ) { Console.Write ( 1 ) ; } else { if ( test_3 == 1 ) { Console.Write ( 2 ) ; } else { Console.Write ( `` x '' ) ; } } } } | Variables ending with `` 1 '' have the `` 1 '' removed within ILSpy . Why ? |
C_sharp : While investigating the new features in C # 7.x , I created the following class : And the following test code : If the Person class includes only the SECOND Deconstruct overload , the code compiles and runs fine ( `` Dennis was born a Friday '' ) . But as soon as the first overload is added to Person , the compiler starts complaining , the error message being : The call is ambiguous between the following methods or properties : 'Person.Deconstruct ( out string , out int , out int , out int ) ' and 'Person.Deconstruct ( out string , out int , out int , out ( int DayNumber , DayOfWeek DayOfWeek ) ) ' ( CS0121 ) ( ValueTuples ) I 've read the MSDN and GitHub documentation , but it is not clear to me why the compiler can not determine that the only applicable overload is the second , given the inner tuple pattern on the left side of the assignment . Any clarification will be appreciated . <code> using System ; namespace ValueTuples { public class Person { public string Name { get ; } public DateTime BirthDate { get ; } public Person ( string name , DateTime birthDate ) { Name = name ; BirthDate = birthDate ; } public void Deconstruct ( out string name , out int year , out int month , out int day ) { name = Name ; year = BirthDate.Year ; month = BirthDate.Month ; day = BirthDate.Day ; } public void Deconstruct ( out string name , out int year , out int month , out ( int DayNumber , DayOfWeek DayOfWeek ) day ) { name = Name ; year = BirthDate.Year ; month = BirthDate.Month ; day.DayNumber = BirthDate.Day ; day.DayOfWeek = BirthDate.DayOfWeek ; } } } using System ; namespace ValueTuples { class MainClass { static void Main ( ) { var dh = new Person ( `` Dennis '' , new DateTime ( 1985 , 12 , 27 ) ) ; // DECONSTRUCTION : ( string name , _ , _ , ( _ , DayOfWeek dow ) ) = dh ; Console.WriteLine ( $ '' { name } was born a { dow } '' ) ; } } } | C # deconstruction and overloads |
C_sharp : I have an IEnumerable parameter that is required to be non-empty . If there 's a precondition like the one below then the collection will be enumerated during it . But it will be enumerated again the next time I reference it , thereby causing a `` Possible multiple enumeration of IEnumerable '' warning in Resharper.These workarounds made Resharper happy but would n't compile : There are other workarounds that would be valid but maybe not always ideal like using ICollection or IList , or performing a typical if-null-throw-exception.Is there a solution that works with code contracts and IEnumerables like in the original example ? If not then has someone developed a good pattern for working around it ? <code> void ProcessOrders ( IEnumerable < int > orderIds ) { Contract.Requires ( ( orderIds ! = null ) & & orderIds.Any ( ) ) ; // enumerates the collection // BAD : collection enumerated again foreach ( var i in orderIds ) { /* ... */ } } // enumerating before the precondition causes error `` Malformed contract . Found Requires orderIds = orderIds.ToList ( ) ; Contract.Requires ( ( orderIds ! = null ) & & orderIds.Any ( ) ) ; -- -// enumerating during the precondition causes the same errorContract.Requires ( ( orderIds ! = null ) & & ( orderIds = orderIds.ToList ( ) ) .Any ( ) ) ; | IEnumerable multiple enumeration caused by contract precondition |
C_sharp : I have often wanted to create a list of objects where each object must implement a number of interfaces . For example , I 'd like to do something similar to the following : Another option I considered was to create a third interface that implements these two so that any object that implements these two interfaces inherently implements mine.With this I would be able to add any object that implements both IConvertible and IComparable , including double and int , as well as my own objects . Explicitly implementing IConvertibleAndComparable is not required since it does not add any new functionality beyond the interfaces in inherits.I understand that the first snippet is illegal and the second , while legal , does not do what I want . Is it possible to achieve what I am trying to do ? If not , would either of these be a candidate for a future C # feature ? ( Note : This would be legitimate application for empty interfaces . ) EditIn a more general sense , I 'd like to perform one of the following : where I can declare all of the restrictions on T that I need , orwhere any type that implements IA , IB , and ... inherently ( or implicitly ) implements IMyCombinedInterface ( only when IMyCombinedInterface does n't explicitly declare new functionality ) . <code> List < T > where T : IConvertible , IComparable _myList ; public interface IConvertibleAndComparable : IConvertible , IComparable { } List < IConvertibleAndComparable > _myList ; private MyGenericClass < T > where T : IA , IB , ... _myClass ; public interface IMyCombinedInterface : IA , IB , ... { } private MyGenericClass < IMyCombinedInterface > _myClass ; | Inherently-Implemented Interfaces |
C_sharp : In .NET 4.5 this cipher worked perfectly on 32 and 64 bit architecture . Switching the project to .NET 4.6 breaks this cipher completely in 64-bit , and in 32-bit there 's an odd patch for the issue.In my method `` DecodeSkill '' , SkillLevel is the only part that breaks on .NET 4.6.The variables used here are read from a network stream and are encoded.DecodeSkill ( Always returns the proper decoded value for SkillLevel ) ExchangeShortBitsDecodeSkill ( Patched for .NET 4.6 32-bit , notice `` var patch = SkillLevel '' ) Assigning the variable as SkillLevel , in 32-bit only , will cause SkillLevel to always be the correct value . Remove this patch , and the value is always incorrect . In 64-bit , this is always incorrect even with the patch.I 've tried using MethodImplOptions.NoOptimization and MethodImplOptions.NoInlining on the decode method thinking it would make a difference.Any ideas to what would cause this ? Edit : I was asked to give an example of input , good output , and bad output.This is from an actual usage scenario , values were sent from the client and properly decoded by the server using the `` patch '' on .NET 4.6.Input : Good OutputBad OutputEdit # 2 : I should include this part , definitely an important part to this.EncodeSkill ( Timestamp is Environment.TickCount ) BitFold32ExchangeLongBits <code> private void DecodeSkill ( ) { SkillId = ( ushort ) ( ExchangeShortBits ( ( SkillId ^ ObjectId ^ 0x915d ) , 13 ) + 0x14be ) ; SkillLevel = ( ( ushort ) ( ( byte ) SkillLevel ^ 0x21 ) ) ; TargetObjectId = ( ExchangeLongBits ( TargetObjectId , 13 ) ^ ObjectId ^ 0x5f2d2463 ) + 0x8b90b51a ; PositionX = ( ushort ) ( ExchangeShortBits ( ( PositionX ^ ObjectId ^ 0x2ed6 ) , 15 ) + 0xdd12 ) ; PositionY = ( ushort ) ( ExchangeShortBits ( ( PositionY ^ ObjectId ^ 0xb99b ) , 11 ) + 0x76de ) ; } private static uint ExchangeShortBits ( uint data , int bits ) { data & = 0xffff ; return ( data > > bits | data < < ( 16 - bits ) ) & 65535 ; } private void DecodeSkill ( ) { SkillId = ( ushort ) ( ExchangeShortBits ( ( SkillId ^ ObjectId ^ 0x915d ) , 13 ) + 0x14be ) ; var patch = SkillLevel = ( ( ushort ) ( ( byte ) SkillLevel ^ 0x21 ) ) ; TargetObjectId = ( ExchangeLongBits ( TargetObjectId , 13 ) ^ ObjectId ^ 0x5f2d2463 ) + 0x8b90b51a ; PositionX = ( ushort ) ( ExchangeShortBits ( ( PositionX ^ ObjectId ^ 0x2ed6 ) , 15 ) + 0xdd12 ) ; PositionY = ( ushort ) ( ExchangeShortBits ( ( PositionY ^ ObjectId ^ 0xb99b ) , 11 ) + 0x76de ) ; } ObjectId = 1000001TargetObjectId = 2778236265PositionX = 32409PositionY = 16267SkillId = 28399SkillLevel = 8481 TargetObjectId = 0PositionX = 302PositionY = 278SkillId = 1115SkillLevel = 0 TargetObjectId = 0PositionX = 302PositionY = 278SkillId = 1115SkillLevel = 34545 private void EncodeSkill ( ) { SkillId = ( ushort ) ( ExchangeShortBits ( ObjectId - 0x14be , 3 ) ^ ObjectId ^ 0x915d ) ; SkillLevel = ( ushort ) ( ( SkillLevel + 0x100* ( Timestamp % 0x100 ) ) ^ 0x3721 ) ; Arg1 = MathUtils.BitFold32 ( SkillId , SkillLevel ) ; TargetObjectId = ExchangeLongBits ( ( ( TargetObjectId - 0x8b90b51a ) ^ ObjectId ^ 0x5f2d2463u ) , 19 ) ; PositionX = ( ushort ) ( ExchangeShortBits ( ( uint ) PositionX - 0xdd12 , 1 ) ^ ObjectId ^ 0x2ed6 ) ; PositionY = ( ushort ) ( ExchangeShortBits ( ( uint ) PositionY - 0x76de , 5 ) ^ ObjectId ^ 0xb99b ) ; } public static int BitFold32 ( int lower16 , int higher16 ) { return ( lower16 ) | ( higher16 < < 16 ) ; } private static uint ExchangeLongBits ( uint data , int bits ) { return data > > bits | data < < ( 32 - bits ) ; } | .Net 4.6 breaks XOR cipher pattern ? |
C_sharp : how to check for duplicate entry on a form using php ? my front end is c # windows applicationI am adding a new user to database using c # and php file.I have created the following : my project in c # ( form1 ) : c # coding : my PHP file : response.phpit add data successfully but when i enter the same userid in textbox and click create button i need to get an error message in txtmessage as userid already exists.i search through googling but i did not got any thing about duplicate entry please refer me some coding <code> private void btncreate_Click ( object sender , EventArgs e ) { var request = ( HttpWebRequest ) WebRequest.Create ( `` http : //***.**.*** . ***/response.php '' ) ; request.Method = WebRequestMethods.Http.Post ; request.ContentType = `` application/x-www-form-urlencoded '' ; using ( var stream = request.GetRequestStream ( ) ) { var buffer = Encoding.UTF8.GetBytes ( `` userid= `` + txtUserid.Text + `` & password= '' + txtConformpassword.Text + `` & first_name= '' + txtFirstname.Text + `` & last_name= '' + txtLastName.Text + `` & role= `` + cmbRole.Text + `` & active= '' + cmbActive.Text + `` '' ) ; stream.Write ( buffer , 0 , buffer.Length ) ; } var response = ( HttpWebResponse ) request.GetResponse ( ) ; string result = String.Empty ; using ( var reader = new StreamReader ( response.GetResponseStream ( ) ) ) { result = reader.ReadToEnd ( ) ; } txtMessage.Text = result ; } < ? php $ uid = $ _POST [ 'userid ' ] ; $ pass = $ _POST [ 'password ' ] ; $ fname = $ _POST [ 'first_name ' ] ; $ lname = $ _POST [ 'last_name ' ] ; $ rol = $ _POST [ 'role ' ] ; $ act = $ _POST [ 'active ' ] ; $ conn = new mysqli ( $ servername , $ username , $ password , $ dbname ) ; if ( $ conn- > connect_error ) { die ( `` Connection failed : `` . $ conn- > connect_error ) ; } $ sql= `` INSERT INTO aster ( userid , password , first_name , last_name , role , active ) VALUES ( ' $ uid ' , ' $ pass ' , ' $ fname ' , ' $ lname ' , ' $ rol ' , ' $ act ' ) ; '' ; if ( $ conn- > query ( $ sql ) ) { echo `` New record created successfully '' ; } else { echo `` Error : `` . $ sql . `` < br > '' . $ conn- > error ; } $ conn- > close ( ) ; ? > | duplicate entry on database using php |
C_sharp : I 'm making user changeable settings for my media player and I 'm struggling to find an elegant solution to the problem.One of my settings for example - pauses the video at it 's last frame , if not checked it will either continue through the playlist or if it 's only 1 file , reset it and pause it at the start.This is how I 've implemented it : This is contained inside the ViewModel of the main window , where the media element is and GeneralSettings.PauseOnLastFrame is a boolean property.This command is binded as follows : It works but it 's awful , how should I go about implementing such setting system in an elegant way ? Some settings might not be boolean , they might have multiple options , some might be applied only on startup and others , as the one illustrated above , event based . <code> private void OnMediaEndedCommand ( ) { if ( GeneralSettings.PauseOnLastFrame ) { MediaPlayer.SetMediaState ( MediaPlayerStates.Pause ) ; return ; } if ( PlayListViewModel.FilesCollection.Last ( ) .Equals ( PlayListViewModel.FilesCollection.Current ) & & ! Repeat ) { ChangeMediaPlayerSource ( PlayListViewModel.ChangeCurrent ( ( ) = > PlayListViewModel.FilesCollection.MoveNext ( ) ) ) ; MediaPlayer.SetMediaState ( MediaPlayerStates.Stop ) ; return ; } ChangeMediaPlayerSource ( PlayListViewModel.ChangeCurrent ( ( ) = > PlayListViewModel.FilesCollection.MoveNext ( ) ) ) ; } < MediaElement ... . > < ia : Interaction.Triggers > < ia : EventTrigger EventName= '' MediaEnded '' > < ia : InvokeCommandAction Command= '' { Binding MediaEndedCommand } '' / > < /ia : EventTrigger > < /ia : Interaction.Triggers > < /MediaElement > | Conditional settings in WPF application |
C_sharp : Let 's assume that our system can perform actions , and that an action requires some parameters to do its work . I have defined the following base class for all actions ( simplified for your reading pleasure ) : Only a concrete implementation of BaseBusinessAction knows how to validate that the parameters passed to it are valid , and therefore theParametersAreValid is an abstract function . However , I want the base class constructor to enforce that the parameters passed are always valid , so I 've added acall to ParametersAreValid to the constructor and I throw an exception when the function returns false . So far so good , right ? Well , no.Code analysis is telling me to `` not call overridable methods in constructors '' which actually makes a lot of sense because when the base class 's constructor is called the child class 's constructor has not yet been called , and therefore the ParametersAreValid method may not have access to some critical member variable that the child class 's constructor would set.So the question is this : How do I improve this design ? Do I add a Func < bool , TActionParameters > parameter to the base class constructor ? If I did : This would work because ValidateIt is static , but I do n't know ... Is there a better way ? Comments are very welcome . <code> public abstract class BaseBusinessAction < TActionParameters > : where TActionParameters : IActionParameters { protected BaseBusinessAction ( TActionParameters actionParameters ) { if ( actionParameters == null ) throw new ArgumentNullException ( `` actionParameters '' ) ; this.Parameters = actionParameters ; if ( ! ParametersAreValid ( ) ) throw new ArgumentException ( `` Valid parameters must be supplied '' , `` actionParameters '' ) ; } protected TActionParameters Parameters { get ; private set ; } protected abstract bool ParametersAreValid ( ) ; public void CommonMethod ( ) { ... } } public class MyAction < MyParameters > { public MyAction ( MyParameters actionParameters , bool something ) : base ( actionParameters , ValidateIt ) { this.something = something ; } private bool something ; public static bool ValidateIt ( ) { return something ; } } | How can I improve this design ? |
C_sharp : I was doing tutorial from this page : http : //msdn.microsoft.com/en-us/library/gg185927.aspxI think I did everything ok but I 'm getting this exception : What I did wrong ? I used certificate from sample . Maybe I should create my own certificate ? Is there any difference ? I noticed that hard coded credentials slighty differs from this passed in tutorial , so I changed them in Services Identites . Before I did that , I was getting authentication exception , so I think it was ok to change it.I 'm not experienced in any kind of security but I want to finally learn it , so I wish you guys can help me : ) EDIT : I 'm not sure if this Realm is ok . I passed http : //localhost:7100/Service/Default.aspx there.I 'm running it on my local machine and I 'm not sure is it the way I should do it.EDIT 2 : This is the StackTrace : I have this error at line : <code> ` An error occurred when processing the security tokens in the message. ` Server stack trace : at System.ServiceModel.Channels.SecurityChannelFactory ` 1.SecurityRequestChannel.ProcessReply ( Message reply , SecurityProtocolCorrelationState correlationState , TimeSpan timeout ) at System.ServiceModel.Channels.SecurityChannelFactory ` 1.SecurityRequestChannel.Request ( Message message , TimeSpan timeout ) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request ( Message message , TimeSpan timeout ) at System.ServiceModel.Channels.ServiceChannel.Call ( String action , Boolean oneway , ProxyOperationRuntime operation , Object [ ] ins , Object [ ] outs , TimeSpan timeout ) at System.ServiceModel.Channels.ServiceChannel.Call ( String action , Boolean oneway , ProxyOperationRuntime operation , Object [ ] ins , Object [ ] outs ) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService ( IMethodCallMessage methodCall , ProxyOperationRuntime operation ) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke ( IMessage message ) Exception rethrown at [ 0 ] : at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage ( IMessage reqMsg , IMessage retMsg ) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke ( MessageData & msgData , Int32 type ) at WcfService.IStringService.Reverse ( String value ) at WcfClient.Program.Main ( String [ ] args ) in c : \Users\Hador\Downloads\Windows Azure AD Access Control ( ACS ) Code Samples\C # \Webservice\Acs2UsernameBindingSample\WcfClient\Program.cs : line 53 string outputString = stringService.Reverse ( userInputString ) ; | WCF Username Authentication - exception in tutorial |
C_sharp : Why the following program prints ( as it should ) but if we remove keyword 'public ' in class B like so : it starts printing ? <code> BB public class A { public void Print ( ) { Console.WriteLine ( `` A '' ) ; } } public class B : A { public new void Print ( ) { Console.WriteLine ( `` B '' ) ; } public void Print2 ( ) { Print ( ) ; } } class Program { static void Main ( string [ ] args ) { var b = new B ( ) ; b.Print ( ) ; b.Print2 ( ) ; } } new void Print ( ) { Console.WriteLine ( `` B '' ) ; } AB | How method hiding works in C # ? |
C_sharp : The following is a typical implementation of SynchronizationContext.CreateCopy : The MSDN docs are scarce about this method . My questions are : Under what circumstances does it get called by the Framework ? When to implement the actual copy logic , rather than just returning a reference to thesource instance ? <code> public class CustomSynchronizationContext : SynchronizationContext { // ... public override SynchronizationContext CreateCopy ( ) { return this ; } } | The purpose of SynchronizationContext.CreateCopy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.