text
stringlengths 46
37.3k
| title
stringlengths 12
162
|
|---|---|
C_sharp : Suppose I have var lst = List < Foobar > that I populated in loop . I can not modify the Foobar object.What would be the best way to effectively do an OrderBy on one property in an IEnumerable , but preserve the original order in case they are equal ? For example , if I had this : I would want to ensure I 'd get back the following after lst.OrderByWithPreserveOrder ( x = > x.Foo ) .ToList : <code> var lst = new List < Foobar > { new Foobar { Foo = `` b '' , Bar=3 } , new Foobar { Foo = `` b '' , Bar=1 } , new Foobar { Foo = `` a '' , Bar=2 } } List < Foobar > { new Foobar { Foo = `` a '' , Bar=2 } new Foobar { Foo = `` b '' , Bar=3 } , new Foobar { Foo = `` b '' , Bar=1 } , }
|
Linq order by property , then by original order
|
C_sharp : I have two extension methods : Now I write some code which uses it : Second overload is chosen only if I explicitly specify IEnumerable type . Is there any way to make second overload to be chosen in both cases ? <code> public static IPropertyAssertions < T > ShouldHave < T > ( this T subject ) { return new PropertyAssertions < T > ( subject ) ; } public static IPropertyAssertions < T > ShouldHave < T > ( this IEnumerable < T > subject ) { return new CollectionPropertyAssertions < T > ( subject ) ; } List < Customer > collection2 = new List < Customer > ( ) ; collection2.ShouldHave ( ) ; //first overload is chosenIEnumerable < Customer > collection3 = new List < Customer > ( ) ; collection3.ShouldHave ( ) ; //second overload is chosen
|
Extension methods overload choice
|
C_sharp : I have this project , and one of the tasks I need to do is find what page a specific object appears on . The object has a predefined ID , and the ID 's appear in order from 0 to N , but they could potentially skip values.Which means , obviously , that using the ID of the element I 'm looking for wo n't work , as if it 's 25 , and there are supposed to be 10 items per page , but 8 of those items are missing , it would try to fit on page 3 , but could only fit on page 2.Here 's what I have now , I was wondering if there was a better way : If there 's no better way to do this , that 's fine . I just hope that there is , because I 'm sure the TakeWhile can take , well , a while when I have thousands of Items in the database.Do note : this method currently works it seems . <code> int itemsPerPage = Convert.ToInt32 ( masterDbContext.Settings.First ( x = > x.Name == `` ItemsPerPage '' ) .Value ) ; int itemCount = masterDbContext.Items.OrderBy ( x = > x.Id ) .TakeWhile ( x = > x.Id < currentItemId ) .Count ( ) ; int pageNumber = ( int ) Math.Ceiling ( ( double ) itemCount / itemsPerPage ) ; Response.Redirect ( `` ~/View/ '' + rootItem.Id + ( pageNumber > 1 ? `` /Page/ '' + pageNumber : `` '' ) ) ;
|
Count how many items appear before an item with a specific ID
|
C_sharp : I have an OWIN-based ASP.NET Web API hosted in a Windows Service . Most of my ApiController actions are async , and accept CancellationToken parameters : Using the built-in request-cancellation features of Web API , if the client cancels the request , token is signaled and _dataSource handles it appropriately and throws the OperationCanceledException.So far , so great.But when my host process terminates ( that is , the Windows Service stops ) , token is n't signaled and the cancellation-and-bail-out process is n't graceful.I 'm aware of the OWIN environment dictionary 's host.onAppDisposing property , and I 've dug into the source for the Microsoft.Owin [ . * ] and Microsoft.AspNet.WebApi . * packages to try and figure out where GetSomeDataAsync 's token argument is coming from , but I 'm not sure how to connect the pieces together.I 'd like to do something likeBut I 'm not sure how to get _cts to be the source of the CancellationTokens that get fed to my actions , while not breaking the request-cancellation feature that 's working well.I 'm thinking that CancellationTokenSource.CreateLinkedTokenSource ( ) might be useful , but I 'm not seeing how to put the pieces together.Can you help ? Thanks ! <code> [ Route ( `` data/ { id } '' ) ] public async Task < IHttpActionResult > GetSomeDataAsync ( int id , CancellationToken token ) { try { using ( var _dataSource = ... ) { return Ok ( await _dataSource.GetDataAsync ( id , token ) ) ; } } catch ( OperationCanceledException ex ) { return StatusCode ( HttpStatusCode.NoContent ) ; } } class WebServiceInAWindowsService : ServiceBase { private readonly CancellationTokenSource _cts = new CancellationTokenSource ( ) ; ... protected override void OnStop ( ) { _cts.Cancel ( ) ; } }
|
How can I signal cancellation to Web API actions when the self-hosted OWIN server shuts down ?
|
C_sharp : I have a TCP server windows service developed in .net 4.0 with asynchronous server sockets.It works , but about 90 % of the time I simply can not stop it : after pressing stop button in Windows Service console , it hangs and stops after about a minute , but its process goes on and TCP communication continues . It hangs at _listener.Close ( ) . Only thing I can do to close the communication is to restart Windows . There can be something with closing sockets . I tried to figure out but I simply can not find the root of the problem.Client side is not under my control , they are some 100 gadgets sending data via TCP.Here is my code ( updated ) .Thanks a lot , any suggestions are highly appreciated ! <code> public class DeviceTCPServer { public readonly IPAddress IPAddress ; public readonly int Port ; public readonly int InputBufferSize ; public readonly ConcurrentDictionary < Guid , StateObject > Connections ; public event EventHandler OnStarted ; public event EventHandler OnStopped ; public event ServerEventHandler OnConnected ; public event ServerEventHandler OnDisconnected ; public event RecievedEventHandler OnRecieved ; public event DroppedEventHandler OnDropped ; public event ExceptionEventHandler OnException ; public event ServerLogEventHandler ServerLog ; private volatile bool _iAmListening ; private Socket _listener ; private Thread _listenerThread ; private readonly ManualResetEvent _allDone = new ManualResetEvent ( false ) ; public bool Listening { get { return _iAmListening ; } } public DeviceTCPServer ( IPAddress ipAddress , int port , int inputBufferSize ) { IPAddress = ipAddress ; Port = port ; InputBufferSize = inputBufferSize ; Connections = new ConcurrentDictionary < Guid , StateObject > ( ) ; } public void ThreadedStart ( ) { _listenerThread = new Thread ( Start ) { CurrentUICulture = Thread.CurrentThread.CurrentUICulture , IsBackground = true } ; _listenerThread.Start ( ) ; } private void Start ( ) { try { var localEP = new IPEndPoint ( IPAddress , Port ) ; _listener = new Socket ( localEP.Address.AddressFamily , SocketType.Stream , ProtocolType.Tcp ) ; _listener.Bind ( localEP ) ; _listener.Listen ( 10000 ) ; if ( OnStarted ! = null ) OnStarted ( this , new EventArgs ( ) ) ; _iAmListening = true ; var listenerWithCultureInfo = new Tuple < Socket , CultureInfo > ( _listener , Thread.CurrentThread.CurrentUICulture ) ; while ( _iAmListening ) { _allDone.Reset ( ) ; _listener.BeginAccept ( AcceptCallback , listenerWithCultureInfo ) ; _allDone.WaitOne ( ) ; } } catch ( Exception exc ) { Debug.Assert ( false , exc.Message ) ; if ( OnException ! = null ) OnException ( this , new ExceptionEventArgs ( exc , `` Start '' ) ) ; } } public void StopListening ( ) { try { _iAmListening = false ; _allDone.Set ( ) ; } catch ( Exception exc ) { Debug.Assert ( false , exc.Message ) ; if ( OnException ! = null ) OnException ( this , new ExceptionEventArgs ( exc , `` StopListening '' ) ) ; } } public void Stop ( ) { try { _listener.Close ( 0 ) ; CloseAllConnections ( ) ; _listenerThread.Abort ( ) ; } catch ( Exception exc ) { Debug.Assert ( false , exc.Message ) ; if ( OnException ! = null ) OnException ( this , new ExceptionEventArgs ( exc , `` Stop '' ) ) ; } } private void AcceptCallback ( IAsyncResult ar ) { var arTuple = ( Tuple < Socket , CultureInfo > ) ar.AsyncState ; var state = new StateObject ( arTuple.Item2 , InputBufferSize ) ; try { Connections.AddOrUpdate ( state.Guid , state , ( k , v ) = > v ) ; Thread.CurrentThread.CurrentUICulture = state.CurrentUICulture ; var listener = arTuple.Item1 ; var handler = listener.EndAccept ( ar ) ; _allDone.Set ( ) ; if ( ! _iAmListening ) return ; state.WorkSocket = handler ; handler.BeginReceive ( state.Buffer , 0 , state.InputBufferSize , 0 , RecieveCallBack , state ) ; if ( OnConnected ! = null ) OnConnected ( this , new ServerEventArgs ( state ) ) ; } catch ( ObjectDisposedException ) { _allDone.Set ( ) ; return ; } catch ( Exception exc ) { Debug.Assert ( false , exc.Message ) ; if ( OnException ! = null ) OnException ( this , new ExceptionEventArgs ( exc , state , `` AcceptCallback '' ) ) ; } } public void RecieveCallBack ( IAsyncResult ar ) { var state = ( StateObject ) ar.AsyncState ; try { Thread.CurrentThread.CurrentUICulture = state.CurrentUICulture ; var handler = state.WorkSocket ; var read = handler.EndReceive ( ar ) ; var pBinayDataPocketCodecStore = new BinayDataPocketCodecStore ( ) ; if ( read > 0 ) { state.LastDataReceive = DateTime.Now ; var data = new byte [ read ] ; Array.Copy ( state.Buffer , 0 , data , 0 , read ) ; state.AddBytesToInputDataCollector ( data ) ; //check , if pocket is complete var allData = state.InputDataCollector.ToArray ( ) ; var codecInitRes = pBinayDataPocketCodecStore.Check ( allData ) ; if ( codecInitRes.Generic.Complete ) { if ( ! codecInitRes.Generic.Drop ) { if ( OnRecieved ! = null ) OnRecieved ( this , new RecievedEventArgs ( state , allData ) ) ; } else { if ( OnDropped ! = null ) OnDropped ( this , new DroppedEventArgs ( state , codecInitRes.Generic ) ) ; //get new data state.ResetInputDataCollector ( ) ; handler.BeginReceive ( state.Buffer , 0 , state.InputBufferSize , 0 , RecieveCallBack , state ) ; } } else { //get more data handler.BeginReceive ( state.Buffer , 0 , state.InputBufferSize , 0 , RecieveCallBack , state ) ; } } else { if ( ( handler.Connected == false ) || ( handler.Available == 0 ) ) { Close ( state ) ; } } } catch ( Exception exc ) { Debug.Assert ( false , exc.Message ) ; if ( OnException ! = null ) OnException ( this , new ExceptionEventArgs ( exc , state , `` RecieveCallBack '' ) ) ; } } public void Send ( StateObject state , byte [ ] data ) { try { var handler = state.WorkSocket ; handler.BeginSend ( data , 0 , data.Length , 0 , SendCallback , state ) ; } catch ( Exception exc ) { Debug.Assert ( false , exc.Message ) ; if ( OnException ! = null ) OnException ( this , new ExceptionEventArgs ( exc , state , `` Send '' ) ) ; } } private void SendCallback ( IAsyncResult ar ) { var state = ( StateObject ) ar.AsyncState ; try { Thread.CurrentThread.CurrentUICulture = state.CurrentUICulture ; var handler = state.WorkSocket ; handler.EndSend ( ar ) ; handler.BeginReceive ( state.Buffer , 0 , state.InputBufferSize , 0 , RecieveCallBack , state ) ; } catch ( Exception exc ) { Debug.Assert ( false , exc.Message ) ; if ( OnException ! = null ) OnException ( this , new ExceptionEventArgs ( exc , state , `` SendCallback '' ) ) ; } } public void Close ( StateObject state ) { try { if ( state == null ) return ; var handler = state.WorkSocket ; if ( handler == null ) return ; if ( ! handler.Connected ) return ; if ( handler.Available > 0 ) { var data = new byte [ handler.Available ] ; handler.Receive ( data ) ; } handler.Shutdown ( SocketShutdown.Both ) ; handler.Close ( 0 ) ; if ( OnDisconnected ! = null ) OnDisconnected ( this , new ServerEventArgs ( state ) ) ; StateObject removed ; var removeResult = Connections.TryRemove ( state.Guid , out removed ) ; } catch ( Exception exc ) { Debug.Assert ( false , exc.Message ) ; if ( OnException ! = null ) OnException ( this , new ExceptionEventArgs ( exc , `` Close '' ) ) ; } } private void CloseAllConnections ( ) { try { var connections = Connections.Select ( c = > c.Value ) ; foreach ( var connection in connections ) { Close ( connection ) ; } } catch ( Exception exc ) { Debug.Assert ( false , exc.Message ) ; if ( OnException ! = null ) OnException ( this , new ExceptionEventArgs ( exc , `` CloseAllConnections '' ) ) ; } } public override string ToString ( ) { return string.Format ( `` { 0 } : { 1 } '' , IPAddress , Port ) ; } }
|
Can not stop async TCP sever Windows service
|
C_sharp : I have a UserScope class which functions similarly to TransactionScope , i.e. , it stores the current state in a thread local . This of course does n't work across calls to await , and neither did TransactionScope until TransactionScopeAsyncFlowOption was added in .NET 4.5.1 . What alternative to thread local can I use so that UserScope can be used the same in single-threaded and multi-threaded scenarios ? ( If I had 4.5.1 installed I 'd decompile to see how TransactionScope does it . ) This is a simplified version of what I have : And this is a test I 'd expect to work : <code> class User { readonly string name ; public User ( string name ) { this.name = name ; } public string Name { get { return this.name ; } } } class UserScope : IDisposable { readonly User user ; [ ThreadStatic ] static UserScope currentScope ; public UserScope ( User user ) { this.user = user ; currentScope = this ; } public static User User { get { return currentScope ! = null ? currentScope.user : null ; } } public void Dispose ( ) { /// ... } } static async Task Test ( ) { var user = new User ( `` Thread Flintstone '' ) ; using ( new UserScope ( user ) ) { await Task.Run ( delegate { Console.WriteLine ( `` Crashing with NRE ... '' ) ; Console.WriteLine ( `` The current user is : { 0 } '' , UserScope.User.Name ) ; } ) ; } } static void Main ( string [ ] args ) { Test ( ) .Wait ( ) ; Console.ReadLine ( ) ; }
|
Sharing scope across awaits
|
C_sharp : I have a following situation . Some .Net runtime method does n't work very well and I need to craft a workaround . Like there 's SqlCommand.ExecuteReader ( ) which sometimes returns a closed reader object and I want to have code like this : This would be just fine except I now need to change all the code that calls ExecuteReader ( ) so that it now calls MyExecuteReader ( ) and it makes maintenance harder.Is there a way to somehow declare that whenever any of my code wants SqlCommand.ExecuteReader ( ) called MyExecuteReader ( ) is called instead ? Effectively is it possible to replace an existing method with another one having exactly the same signature and the same name ? <code> SqlDataReader MyExecuteReader ( this SqlCommand command ) { var reader = command.ExecuteReader ( ) ; if ( reader.IsClosed ( ) ) { throw new ClosedReaderReturnedException ( ) ; } return reader ; }
|
Can I replace a C # method with another with the same name and signature ?
|
C_sharp : Perhaps I am missing something trivial . I have a couple of List < T > s and I need one big list from them which is a union of all the other lists . But I do want their references in that big list and not just the values/copies ( unlike many questions I typically find on SO ) .For example I have this , Suppose I get the list I want in unionList , then this should happen : To make it clear , this typically happens with But how do I go about with the second list , list2 to add to unionList ? I tried Add and AddRange but they obviously clone and not copy.and Update : I think I am asking something that makes no sense , and something that inherently is not possible in the language.. <code> List < string > list1 = new List < string > { `` a '' , `` b '' , `` c '' } ; List < string > list2 = new List < string > { `` 1 '' , `` 2 '' , `` 3 '' } ; var unionList = GetThatList ( list1 , list2 ) ; unionList.Remove ( `` a '' ) ; = > list1.Remove ( `` a '' ) ; unionList.Remove ( `` 1 '' ) ; = > list2.Remove ( `` 1 '' ) ; //in other words////unionList.Count = 4 ; //list1.Count = 2 ; //list2.Count = 2 ; unionList = list1 ; //got the reference copy . unionList = list1 ; unionList.AddRange ( list2 ) ; // -- error , clones , not copies here . foreach ( var item in list2 ) { unionList.Add ( item ) ; // -- error , clones , not copies here . }
|
How to copy a List < T > without cloning
|
C_sharp : I was reading about the ValueType class and I am wondering if , when something gets casted to a ValueType , whether it is getting boxed ? Example : Did the int represented by the literal 5 get boxed when received by DoSomething method ? <code> void DoSomething ( ValueType valueType ) { } DoSomething ( 5 ) ;
|
C # boxing when casting to ValueType
|
C_sharp : I have exceptionI 'm using unit tests to test class Parser which on specific input should throw exception above . I 'm using code like this : Is there any smart simple way to check if SyntaxError.line == 1 ? Best I come up with is : I do n't like it very much , is there better way ? <code> class SyntaxError : Exception { public SyntaxError ( int l ) { line = l ; } public int line ; } [ TestMethod ] [ ExpectedException ( typeof ( Parser.SyntaxError ) ) ] public void eolSyntaxError ( ) { parser.reader = new StringReader ( `` ; alfa\n ; beta\n\n\n\na '' ) ; parser.eol ( ) ; } [ TestMethod ] public void eolSyntaxError ( ) { try { parser.reader = new StringReader ( `` ; alfa\n ; beta\n\n\n\na '' ) ; parser.eol ( ) ; Assert.Fail ( ) ; } catch ( SyntaxError e ) { Assert.AreEqual ( 1 , e.line ) ; } }
|
Unit testing exception property
|
C_sharp : For purposes of automatically translating code from C++ to C # , I would like to have a C # class ( psuedo-code ) This would be useful in cases such asFor certain reasons , programmatically disambiguating the above type is not in general possible . E.g.But if I had the Null class above , I could programmatically add in and generateThe trick would be to use new Null ( ) in place of every generated null such that evencompiles with x == null.Is it possible to write such a class ? <code> class Null { public static implicit operator T ( Null unused ) { return null ; } } foo ( T1 x ) { ... } foo ( T2 x ) { ... } foo ( null ) ; // ambiguous foo ( ( T1 ) null ) ; // Discovering T1 over T2 is not possible or really hard to do foo ( Null x ) { ... } foo ( new Null ( ) ) ; // not ambiguous T1 x = new Null ( ) ;
|
C # generic implicit operator return type
|
C_sharp : I have the SQL queryand I want to convert it to LINQ to SQL , yet my LINQ skills are not there yet . Could someone please help me convert this . It 's the with and union statements that are making this a bit more complex for me.Any help appreciated . <code> with c as ( select categoryId , parentId , name,0 as [ level ] from task_Category b where b.parentId is null union all select b.categoryId , b.parentId , b.name , [ level ] + 1 from task_Category b join c on b.parentId = c.categoryId ) select name , [ level ] , categoryId , parentId as item from c
|
Convert SQL to LINQ to SQL
|
C_sharp : Possible Duplicate : C # if/then directives for debug vs release I am working on a C # project and I like to know how to add special cases while I am running the program in the debugger in the Debug Mode I have access to certain resources that I would not normally have in the release version.Here is what keeps happening , I have admin tools built into the program , that are just for debugging , like a button that says test and put what ever code I want to into it . What keeps happening I forget to hide that button and I release it to the clients . I would love to have that test button there only while it 's running in the debug mode but not any other time.This turns on my admin toolsThis turns off my admin toolsIs there a simple way to do this ? or maybe while it 's running in visual studio it'sbut when it 's running on it 's ownI am running on Visual Studio 2010Thanks . <code> rpg_Admin.Visible = true ; rpg_Admin.Visible = false ; if Debug Mode rpg_Admin.Visible = true rpg_Admin.Visible = true rpg_Admin.Visible = false
|
In Visual Studio how to add special cases for debug and release versions ?
|
C_sharp : Possible Duplicate : Cast int to Enum in C # I fetch a int value from the database and want to cast the value to an enum variable . In 99.9 % of the cases , the int will match one of the values in the enum declarationIn the edge case , the value will not match ( whether it 's corruption of data or someone manually going in and messing with the data ) .I could use a switch statement and catch the default and fix the situation , but it feels wrong . There has to be a more elegant solution.Any ideas ? <code> public enum eOrderType { Submitted = 1 , Ordered = 2 , InReview = 3 , Sold = 4 , ... } eOrderType orderType = ( eOrderType ) FetchIntFromDb ( ) ;
|
The correct way of casting an int to an enum
|
C_sharp : Is there an Android preprocessor macros that Mono for Android defines ? I mean very useful things for cross-platform development like : and <code> # if WINDOWS ... # endif # if WINDOWS_PHONE ... # endif
|
Mono for Android preprocessor macros
|
C_sharp : I have a Windows form with a datagridview.The ideal situation : User clicks on any of the nine columns , and the program sorts all the data , if the clicked column contains numbers , I would like the lowest number on the top . If the clicked column contains a string I would like it to be sorted Alphabetically ( A-Z ) .What I have right now : I saw an old question on Stack Overflow where the OP how to sort the datagridview when clicking `` a '' header . The difference with mine is that I want my datagridview to be sortable by any of the nine columns.I have this code , stolen from the question I found : This only lets the user order by `` Achternaam '' when he clicks one of the nine columns . What I want is when the user clicks on the Nationaliteit column , the data gets sorted with the An on top . And so on for every columnThis is the listplayers list : And in the main class : Some dummy data : <code> dataGridView2.DataSource = listPlayers.Select ( s = > new { voornaam = s.Voornaam , Achternaam = s.Achternaam , positie = s.Positie , Nationaltieit = s.Nationaliteit , Leeftijd = s.Age , Aanval = s.Aanval , Verdediging = s.Verdediging , Gemiddeld = s.Gemiddeld , waarde = s.TransferWaarde } ) .OrderBy ( s = > s.Achternaam ) .ToList ( ) ; foreach ( DataGridViewColumn column in dataGridView2.Columns ) { dataGridView2.Columns [ column.Name ] .SortMode = DataGridViewColumnSortMode.Automatic ; } namespace SimulatorSimulator { class SpelerData { public string Voornaam { get ; set ; } public string Achternaam { get ; set ; } public string Positie { get ; set ; } public string Nationaliteit { get ; set ; } public int Age { get ; set ; } public int Aanval { get ; set ; } public int Verdediging { get ; set ; } public int Gemiddeld { get ; set ; } public string TransferWaarde { get ; set ; } } } List < SpelerData > listPlayers = new List < SpelerData > ( ) ; Romelu ; Lukaku ; Aanvaller ; Belgie ; 22 ; 87 ; 12 ; 50 ; 41.000.000,00 Raheem ; Sterling ; Aanvaller ; Engeland ; 21 ; 84 ; 30 ; 57 ; 35.000.000,00 Zlatan ; Ibrahimovic ; Aanvaller ; Zweden ; 34 ; 87 ; 21 ; 54 ; 34.500.000,00
|
Make all datagridview columns sortable
|
C_sharp : Tough question but I could use any help on it.I 'm using System.Security.Cryptography.Xml on my end to encrypt an XML SAML blob.The encryption is working fine , however when it hits the java library on the other side they are getting error : How can I continue to use my encryption method : While getting around this error ? Is there a parameter on EncryptedKey to set the padding size ? Or do I have to use Bouncy Castle to specify the size of the encrypted data ? <code> java.lang.ArrayIndexOutOfBoundsException : too much data for RSA block at org.bouncycastle.jce.provider.JCERSACipher.engineDoFinal ( Unknown Source ) at org.bouncycastle.jce.provider.WrapCipherSpi.engineUnwrap ( Unknown Source ) at javax.crypto.Cipher.unwrap ( Unknown Source ) at org.apache.xml.security.encryption.XMLCipher.decryptKey ( Unknown Source ) at org.opensaml.xml.encryption.Decrypter.decryptKey ( Decrypter.java:680 ) at org.opensaml.xml.encryption.Decrypter.decryptKey ( Decrypter.java:611 ) at org.opensaml.xml.encryption.Decrypter.decryptUsingResolvedEncryptedKey ( Decrypter.java:761 ) at org.opensaml.xml.encryption.Decrypter.decryptDataToDOM ( Decrypter.java:512 ) at org.opensaml.xml.encryption.Decrypter.decryptDataToList ( Decrypter.java:439 ) at org.opensaml.xml.encryption.Decrypter.decryptData ( Decrypter.java:400 ) at org.opensaml.saml2.encryption.Decrypter.decryptData ( Decrypter.java:141 ) at org.opensaml.saml2.encryption.Decrypter.decrypt ( Decrypter.java:69 ) public XmlElement EncryptXml ( XmlElement assertion , X509Certificate2 cert ) { //cert = new X509Certificate2 ( @ '' C : \temp\SEI.cer '' ) ; XmlElement returnElement ; EncryptedData message = new EncryptedData ( ) ; message.Type = `` http : //www.w3.org/2001/04/xmlenc # Element '' ; message.EncryptionMethod = new EncryptionMethod ( EncryptedXml.XmlEncAES128KeyWrapUrl ) ; //message.EncryptionMethod = new EncryptionMethod ( EncryptedXml.XmlEncAES128KeyWrapUrl ) ; EncryptedKey key = new EncryptedKey ( ) ; key.EncryptionMethod = new EncryptionMethod ( EncryptedXml.XmlEncRSA15Url ) ; key.KeyInfo.AddClause ( new KeyInfoX509Data ( cert ) ) ; var rKey = new RijndaelManaged ( ) ; rKey.BlockSize = 128 ; rKey.KeySize = 128 ; rKey.Padding = PaddingMode.PKCS7 ; rKey.Mode = CipherMode.CBC ; key.CipherData.CipherValue = EncryptedXml.EncryptKey ( rKey.Key , ( RSA ) cert.PublicKey.Key , false ) ; KeyInfoEncryptedKey keyInfo = new KeyInfoEncryptedKey ( key ) ; message.KeyInfo.AddClause ( keyInfo ) ; message.CipherData.CipherValue = new EncryptedXml ( ) .EncryptData ( assertion , rKey , false ) ; returnElement = message.GetXml ( ) ; Logger ( `` Cert Size : `` + System.Text.ASCIIEncoding.Unicode.GetByteCount ( cert.ToString ( ) ) ) ; GetBytesKeyAndData ( rKey , assertion.InnerText ) ; return returnElement ; }
|
.NET System Encryption to Bouncy Castle Java Decryption Throws Error
|
C_sharp : I am trying to use the ActionTypes.OpenUrl type on a CardAction in a hero card on kik . all it does is echo back the message . It does not actually open a URL . I have the same code working on multiple channels , but can not get it working on kik . Has anyone been able to find a work around for this ? Here is the code I am using : <code> Activity reply = activity.CreateReply ( ) ; var card = new HeroCard { Title = `` title '' , Text = `` text '' , Buttons = new List < CardAction > { new CardAction ( ActionTypes.OpenUrl , '' url 1 '' , text : `` open url 1 '' , value : @ '' https : //www.google.com/ '' ) , new CardAction ( ActionTypes.OpenUrl , title : '' url 2 '' , text : `` open url 2 '' , value : @ '' https : //www.google.com/ '' ) , new CardAction ( ActionTypes.OpenUrl , title : '' url 3 '' , text : `` open url 3 '' , value : @ '' https : //www.google.com/ '' ) } } ; reply.Attachments.Add ( card.ToAttachment ( ) ) ; await context.PostAsync ( reply ) ;
|
Bot Framework : How to make an OpenUrl button on a herocard in Kik
|
C_sharp : I am working on a math library for my DirectX 3D engine in C # . I am using SlimDX , which is a wonderfuly put together and powerful library . SlimDX provides quite a few math classes , but they are actually wrappers around native D3DX objects , so while the objects themselves are very , very fast , the interop is not I presume , because my managed C # code outperforms them.My specific question has to do with floating-point comparison . The sort-of canonical way is to define an epsilon value , and compare the value to the difference between the floating-point values to determine closeness , like so : The function call overhead would swamp the actual comparison , so this trivial function would be inlined in C++ , will the C # compiler do this ? Is there a way to tell the C # compiler that I want a method inlined ? <code> float Epsilon = 1.0e-6f ; bool FloatEq ( float a , float b ) { return Math.Abs ( a - b ) < Epsilon }
|
Inline expansion in C #
|
C_sharp : Regex.Replace says : In a specified input string , replaces all strings that match a specified regular expression with a specified replacement string.In my case : Output : but I was expectingWhy is it replacing my non-matching groups ( group 1 and 3 ) ? And how do I fix this in order to get the expected output ? Demo <code> string w_name = `` 0x010102_default_prg_L2_E2_LDep1_LLC '' ; string regex_exp = @ '' ( ? : E\d ) ( [ \w\d_ ] + ) ( ? : _LLC ) '' ; w_name = Regex.Replace ( w_name , regex_exp , string.Empty ) ; 0x010102_default_prg_L2_ 0x010102_default_prg_L2_E2_LLC
|
Regex replace only matching groups and ignore non-matching groups ?
|
C_sharp : i 've got this structnow i 'm failing this : with System.InvalidCastException : Specified cast is not valid . at System.Linq.Enumerable.d__aa ` 1.MoveNext ( ) at System.Collections.Generic.List ` 1..ctor ( IEnumerable ` 1 collection ) at System.Linq.Enumerable.ToList [ TSource ] ( IEnumerable ` 1 source ) ... <code> [ Serializable ] public struct Foo : IConvertible , IXmlSerializable , IComparable , IComparable < Foo > { private readonly int _value ; private Foo ( int id ) { this._value = id ; } private IConvertible ConvertibleValue { get { return this._value ; } } public int CompareTo ( object obj ) { if ( obj is Foo ) { var foo = ( Foo ) obj ; return this.CompareTo ( foo ) ; } return -1 ; } public int CompareTo ( Foo other ) { return this._value.CompareTo ( other._value ) ; } public TypeCode GetTypeCode ( ) { return this._value.GetTypeCode ( ) ; } bool IConvertible.ToBoolean ( IFormatProvider provider ) { return this.ConvertibleValue.ToBoolean ( provider ) ; } char IConvertible.ToChar ( IFormatProvider provider ) { return this.ConvertibleValue.ToChar ( provider ) ; } sbyte IConvertible.ToSByte ( IFormatProvider provider ) { return this.ConvertibleValue.ToSByte ( provider ) ; } byte IConvertible.ToByte ( IFormatProvider provider ) { return this.ConvertibleValue.ToByte ( provider ) ; } short IConvertible.ToInt16 ( IFormatProvider provider ) { return this.ConvertibleValue.ToInt16 ( provider ) ; } ushort IConvertible.ToUInt16 ( IFormatProvider provider ) { return this.ConvertibleValue.ToUInt16 ( provider ) ; } int IConvertible.ToInt32 ( IFormatProvider provider ) { return this.ConvertibleValue.ToInt32 ( provider ) ; } uint IConvertible.ToUInt32 ( IFormatProvider provider ) { return this.ConvertibleValue.ToUInt32 ( provider ) ; } long IConvertible.ToInt64 ( IFormatProvider provider ) { return this.ConvertibleValue.ToInt64 ( provider ) ; } ulong IConvertible.ToUInt64 ( IFormatProvider provider ) { return this.ConvertibleValue.ToUInt64 ( provider ) ; } float IConvertible.ToSingle ( IFormatProvider provider ) { return this.ConvertibleValue.ToSingle ( provider ) ; } double IConvertible.ToDouble ( IFormatProvider provider ) { return this.ConvertibleValue.ToDouble ( provider ) ; } decimal IConvertible.ToDecimal ( IFormatProvider provider ) { return this.ConvertibleValue.ToDecimal ( provider ) ; } DateTime IConvertible.ToDateTime ( IFormatProvider provider ) { return this.ConvertibleValue.ToDateTime ( provider ) ; } string IConvertible.ToString ( IFormatProvider provider ) { return this.ConvertibleValue.ToString ( provider ) ; } object IConvertible.ToType ( Type conversionType , IFormatProvider provider ) { return this.ConvertibleValue.ToType ( conversionType , provider ) ; } XmlSchema IXmlSerializable.GetSchema ( ) { return null ; } void IXmlSerializable.ReadXml ( XmlReader reader ) { var stringId = reader.ReadElementContentAsString ( ) ; if ( string.IsNullOrEmpty ( stringId ) ) { return ; } this = int.Parse ( stringId ) ; } void IXmlSerializable.WriteXml ( XmlWriter writer ) { writer.WriteValue ( this ) ; } public static implicit operator int ( Foo value ) { return value._value ; } public static implicit operator Foo ( int value ) { Foo foo ; if ( value > 0 ) { foo = new Foo ( value ) ; } else { foo = new Foo ( ) ; } return foo ; } public override string ToString ( ) { return this._value.ToString ( ) ; } } var intList = new List < int > { 1 , 2 , 3 , 4 } ; var fooList = intList.Cast < Foo > ( ) .ToList ( ) ;
|
Why does this cast-operation fail
|
C_sharp : In the code below , I 'm checking the equality of object references.Here : x and z refers to same object ; I can say that x is interned and z is used taht version . Well , I 'm not sure about this ; Please correct me , if I am wrong.I changed the value of y by assigning it the same value as x. I thought it is going to create a new object here ; but I was wrong , it used the same reference.My questions are : Does .net uses string interns for every string that I use ? If so , is n't it hurts the performance ? If not , how the references became same in above example ? <code> string x = `` Some Text '' ; string y = `` Some Other Text '' ; string z = `` Some Text '' ; Console.WriteLine ( object.ReferenceEquals ( x , y ) ) ; // FalseConsole.WriteLine ( object.ReferenceEquals ( x , z ) ) ; // TrueConsole.WriteLine ( object.ReferenceEquals ( y , z ) ) ; // Falsey = `` Some Text '' ; Console.WriteLine ( object.ReferenceEquals ( x , y ) ) ; // TrueConsole.WriteLine ( object.ReferenceEquals ( x , z ) ) ; // TrueConsole.WriteLine ( object.ReferenceEquals ( y , z ) ) ; // True
|
String Interning
|
C_sharp : I have an ASP.NET application that is accessed by 120-140 users at the same time on average . I use Session to get and set user specific info . To make things easy I 've got a static a class called CurrentSession and it has a property called UserInfo : And whenever I needed current user 's info I just used to do : Recently I 've come across situations when wrong user info is retrieved . Is there a problem in my approach that can cause Session conflicts ? <code> public static class CurrentSession { public static UserInfo { get { return HttpContext.Current.Session [ `` userInfo '' ] ! =null ? ( UserInfo ) HttpContext.Current.Session [ `` userInfo '' ] : null ; } set { HttpContext.Current.Session [ `` userInfo '' ] =value ; } } //And other properties } CurrentSession.UserInfo ;
|
Can Sessions conflict when encapsulated in a static class static property ?
|
C_sharp : I know how to force a type parameter to be a subtype of another type : Is there a way to force a type parameter to be a supertype of another type ? Currently , I 'm having to compare T1 and T2 at runtime using IsSubclassOf inside IncludeMappingOf . A compile-safe solution would be preferable . Any ideas ? EDIT : Changed the example to be less design-smelly.NOTE : The linked question is quite similar , but no suitable answer is given . Hopefully this question will shed some light on that one as well.EDIT # 2 : Simpler example : Compiler : Argument type 'T2 ' is not assignable to parameter type 'T1 ' . Yes I know that , I 'm trying to get the compiler to allow only cases where T2 IS assignable to parameter type T1 ! <code> public interface IMapping < T2 > { public void Serialize < T3 > ( T3 obj ) where T3 : T2 ; } ... var mapping = MapManager.Find < Truck > ( ) ; mapping.Serialize ( new TonkaTruck ( ) ) ; public interface IMapping < T2 > { public void IncludeMappingOf < T1 > ( ) where T2 : T1 ; // < == does n't work } ... var mapping = MapManager.Find < Truck > ( ) ; // Truck inherits Vehicle // Would like compiler safety here : mapping.IncludeMappingOf < Vehicle > ( ) ; mapping.Serialize ( new TonkaTruck ( ) ) ; public class Holder < T2 > { public T2 Data { get ; set ; } public void AddDataTo < T1 > ( ICollection < T1 > coll ) //where T2 : T1 // < == does n't work { coll.Add ( Data ) ; // error } } ... var holder = new Holder < Truck > { Data = new TonkaTruck ( ) } ; var list = new List < Vehicle > ( ) ; holder.AddDataTo ( list ) ;
|
Constrain type parameter to a base type
|
C_sharp : What will happen if two threads read this property at the same time ? My object is read only and it 's not critical if two instances are created . Should I add locks in any case ? <code> public static HugeType HugeType { get { if ( tenderCache == null ) { tenderCache = Config.Get < HugeType > ( `` HugeType '' , null ) ; } return tenderCache ; } }
|
Lazy loading without locks in multithread application
|
C_sharp : I wanted to know how to word-wrap in C # when I came across a very good solution to my problem on word-wrapping text in a line in this URL . Unfortunately , I do not have enough reputations to ask the OP directly about one specific problem I am having ( and most likely people dealing with this will be having indefinitely ) Problem Description : I can word-wrap a string if it needs to be word-wrapped with this code : However , I could not find the place to receive a trigger whenever the word-length overflows from a single line.for example : In LINE-2 of that code , whenever the wordlength exceeds 700px , it moves to the next line . It does that by following the RectangleF to wordwrap . It is doing so automatically , which is a problem since that makes it difficult to know whether it has crossed 700px or not.This is the format in which information is displayed whenever I tried to print PAddressLength : { Width=633.1881 , Height=47.14897 } I am thinking that If I can extract the value of width from that using PAddressLength.Width , then I can partially solve this problem . But with that , I will need to calculate if the remaining space ( i.e 700px - 633.1881px ) will accommodate the next word or not ( if there is one ) BREAKING DOWN THE PROBLEM : I already know how to word-wrap when there is a string longer than what specify by using Graphics.MeasureString as given in this solution in another question.But that^ process happens automatically , so I want to know how to detect if the word-wrap has occured ( and how may lines it has wrapped with each line being 700px width maximum ) I need to know the number of lines that have been wrapped in order to know the number of times to execute newline ( ) function that I wrote , which gives appropriate line spacing upon executing each time.ADDITIONALLY , ( bonus question ; may or maynot solve ) Is there some way to extract the value 633.1881 and then calculate whether the next word fits in ( 700 - 633.1881 ) px space or not ? <code> Graphics PAddress = e.Graphics ; SizeF PAddressLength = PAddress.MeasureString ( `` Residential Address : `` + RAddressTextBox.Text , new Font ( fontface , fontsize , FontStyle.Regular ) ,700 ) ; PAddress.DrawString ( `` Residential Address : `` +PAddressLength + RAddressTextBox.Text , new Font ( fontface , fontsize , FontStyle.Regular ) , Brushes.Black , new RectangleF ( new Point ( pagemarginX , newline ( ) ) , PAddressLength ) , StringFormat.GenericTypographic ) ;
|
How to detect a string-overflow from a line in C # ?
|
C_sharp : Somehow I can not believe that I am the first one to run into that problem ( and I do n't want to believe that I am the only one stupid enough not to see a solution directly ) , but my search-fu was not strong enough.I regularly run into a situation , when I need to do a few time-consuming steps one after the other . The workflow looks likeI do n't want to block the UI during each step , so every method does return immediately , and raises an event once it has finished . Now hilarity ensues , since the above code block mutates intoThis reads too much like Continuation-passing style for my taste , and there has to be a better way to structure this code . But how ? <code> var data = DataGetter.GetData ( ) ; var processedData = DataProcessor.Process ( data ) ; var userDecision = DialogService.AskUserAbout ( processedData ) ; // ... DataGetter.Finished += ( data ) = > { DataProcessor.Finished += ( processedData ) = > { DialogService.Finished ( userDecision ) = > { // ... . } DialogService.AskUserAbout ( processedData ) ; } DataProcessor.Process ( data ) ; } ; DataGetter.GetData ( ) ;
|
How to avoid spaghetti code when using completion events ?
|
C_sharp : Imagine I have a function calledMy C # declaration could beIs this functionally and technically equivalent toOr will there be a difference in how they are marshalled.I 'm asking this because the library I 'm calling is all void * , typedef 'd to other names , and in C # I 'd like to get type safety , for what it 's worth . <code> Myfunction ( const void * x ) ; MyFunction ( IntPtr x ) ; struct MyStruct { IntPtr P ; } MyFunction ( MyStruct x ) ;
|
PInvoke with a void * versus a struct with an IntPtr
|
C_sharp : I 'm trying to use SOAP headers to allow for SQL Authentication while accessing a webservice published on my SQL 2005 box via HTTP Endpoint . On the endpoint , I 've set Authentication = ( Basic ) , Ports = ( SSL ) , and LOGIN_TYPE = MIXED . I 'm able to generate the WSDL and consume it just fine in VS utilizing domain credentials . However , when I try to implement SOAP headers to allow for SQL Authentication , i 'm running into problems . I 've followed MS BOL to the letter ( http : //msdn.microsoft.com/en-us/library/ms189619 ( SQL.90 ) .aspx ) , but for some reason , i 'm not sending the SOAP header . I 've verified this by using fiddler ( http : //www.fiddler2.com/fiddler2/ ) to trap my https messages and look at them . Any help would be greatly appreciated . Included is the code I 've been using ( the names have been changed to protect the innocent ) This code utilizes the SqlSoapHeader class as documented in the BOL reference from above.I error at calling ws.SelectUserAccountByUserName ( ) with an `` Execute permission denied '' due to the fact that the `` netaccount '' user does n't have rights to execute the stored proc . But again , this is because according to the soap message , no header with the sqluser info is being passed . <code> namespace ConsoleApplication.WebService { class Program { static void Main ( string [ ] args ) { //Prevents error due to self signed cert ServicePointManager.ServerCertificateValidationCallback = delegate { return true ; } ; Stuff stuff = new Stuff ( ) ; stuff.DoSomthing ( ) ; } } public class Stuff { [ System.Web.Services.Protocols.SoapHeaderAttribute ( `` sqlSecurity '' ) ] public int DoSomthing ( ) { Webservice ws = new Webservice ( ) ; CredentialCache myCreds = new CredentialCache ( ) ; myCreds.Add ( new Uri ( ws.Url ) , `` Basic '' , new NetworkCredential ( `` netaccount '' , `` netpass '' , `` domain '' ) ) ; ws.Credentials = myCreds ; ws.sqlSecurity = new SqlSoapHeader.Security ( ) ; ws.sqlSecurity.Username = `` sqluser '' ; ws.sqlSecurity.Password = `` sqlpass '' ; try { ws.SelectUserAccountByUserName ( `` someuser '' ) ; } catch ( SoapException ex ) { string txterror = ex.Detail.InnerText ; return 0 ; } return 1 ; } } public partial class Webservice { public SqlSoapHeader.Security sqlSecurity ; } }
|
Adding SOAP Headers for SQL 2005 HTTP Endpoint web service in Visual Studio 2008
|
C_sharp : Context : There 2 main classes that look something like this : And the sub / collection / Enum types : Currently my Map looks like this : Where MapAttribute gets the item from the Dictionary and using the AttributeType I 've provided , adds it to the target collection as a ( name & value ) object ( using a try get and returning an empty if the key does not exist ) ... After all of this my Target set end 's up looking like this : Question : How do I go about mapping the rest of the items to the target class , but I need to be able to exclude specific keys ( like , title or description ) . E.G . Source.Attribute items that have a defined place in target gets excluded from the Target.Attributes collection , and `` left-over '' properties still go to Target.Attributes.For even more clarity ( if my source looks like this ) : it would map to a target like this : I 've attempted this , but it does not compile , stating the following : Custom configuration for members is only supported for top-level individual members on a type . <code> public class Source { public Dictionary < AttributeType , object > Attributes { get ; set ; } } public class Target { public string Title { get ; set ; } public string Description { get ; set ; } public List < Attribute > Attributes { get ; set ; } } public class Attribute { public string Name { get ; set ; } public string Value { get ; set ; } } public enum AttributeType { Title , Description , SomethingElse , Foobar } CreateMap < Source , Target > ( ) .ForMember ( dest = > dest.Description , opt = > opt.MapAttribute ( AttributeType.Description ) ) .ForMember ( dest = > dest.Title , opt = > opt.MapAttribute ( AttributeType.Title ) ) ; { title : `` Foo '' , attributes : [ { name : `` SomethingElse '' , value : `` Bar '' } , { name : `` Title '' , value : `` Foo '' } ] } { attributes : { title : `` Foo '' , somethingelse : `` Bar '' } } { title : `` Foo '' , attributes : [ { name : `` SomethingElse '' , value : `` Bar '' } ] } CreateMap < KeyValuePair < AttributeType , object > , Attribute > ( ) .ForSourceMember ( x = > x.Key == AttributeType.CompanyName , y = > y.Ignore ( ) )
|
AutoMapper : Ignore specific dictionary item ( s ) during mapping
|
C_sharp : In c # I can use default ( T ) to get the default value of a type . I need to get the default type at run time from a System.Type . How can I do this ? E.g . Something along the lines of this ( which does n't work ) <code> var type = typeof ( int ) ; var defaultValue = default ( type ) ;
|
How can I call default ( T ) with a type ?
|
C_sharp : The application I am working on is relying on Autofac as DI container and one of the reasons that made me decide to use it , among others , was the delegate factory feature ( see here ) This works fine for all cases where I need to recreate the same elements several times as is the case of some reports and related screens . Some reports ( even those of the same type ) are executed concurrently but they change only by their user-defined parameters so it makes sense ( I think ) to inject factories in order to create instances , passing the free parameters and leave the rest to the application.The problem comes with the fact that each report is made of a variable number of sub reports ( tasks ) and each task implements an ITask interface . Each report may have up to 50 different tasks to use and each task encapsulates a precise business operation . One option I have is to inject delegate factories for and create them when needed.These tasks have to be dynamically generated by factories and something like : requires a lot of manual wiring ( delegates , constructor , backing fields etc ) while something like would be incredibly less work especially if the _taskFactory wraps the container as shown in this other post , but also it would basically mean I am using a service locator to create my tasks.What other options do I have that may be suitable to solve this ? ( NOTE : there is a good chance I am completely off track and that I have to read a lot more about DI , in which case any contribution would be even more important ) <code> var myTaskA = _taskFactoryConcreteTaskA ( ) ; var myTaskB = _taskFactoryConcreteTaskB ( ) ; var myTaskC = _taskFactoryConcreteTaskC ( ) ; ... var myTaskZZ = = _taskFactoryConcreteTaskZZ ( ) ; var myTaskA = _taskFactory.Create < ConcreteTaskA > ( ) ; var myTaskB = _taskFactory.Create < ConcreteTaskB > ( ) ; var myTaskC = _taskFactory.Create < ConcreteTaskC > ( ) ; ... var myTaskZZ = _taskFactory.Create < ConcreteTaskZZ > ( ) ;
|
Service Locator easier to use than dependency Injection ?
|
C_sharp : I 'm testing what sort of speedup I can get from using SIMD instructions with RyuJIT and I 'm seeing some disassembly instructions that I do n't expect . I 'm basing the code on this blog post from the RyuJIT team 's Kevin Frei , and a related post here . Here 's the function : The section of disassembly I 'm querying copies the array values into the Vector < float > . Most of the disassembly is similar to that in Kevin and Sasha 's posts , but I 've highlighted some extra instructions ( along with my confused annotations ) that do n't appear in their disassemblies : Note the loop range check is as expected : so I do n't know why there are extra comparisons to eax . Can anyone explain why I 'm seeing these extra instructions and if it 's possible to get rid of them.In case it 's related to the project settings I 've got a very similar project that shows the same issue here on github ( see FloatSimdProcessor.HwAcceleratedSumInPlace ( ) or UShortSimdProcessor.HwAcceleratedSumInPlaceUnchecked ( ) ) . <code> static void AddPointwiseSimd ( float [ ] a , float [ ] b ) { int simdLength = Vector < float > .Count ; int i = 0 ; for ( i = 0 ; i < a.Length - simdLength ; i += simdLength ) { Vector < float > va = new Vector < float > ( a , i ) ; Vector < float > vb = new Vector < float > ( b , i ) ; va += vb ; va.CopyTo ( a , i ) ; } } ; // Vector < float > va = new Vector < float > ( a , i ) ; cmp eax , r8d ; < -- Unexpected - Compare a.Length to i ? jae 00007FFB17DB6D5F ; < -- Unexpected - Jump to range check failure lea r10d , [ rax+3 ] cmp r10d , r8d jae 00007FFB17DB6D5F mov r11 , rcx ; < -- Unexpected - Extra register copy ? movups xmm0 , xmmword ptr [ r11+rax*4+10h ] ; // Vector < float > vb = new Vector < float > ( b , i ) ; cmp eax , r9d ; < -- Unexpected - Compare b.Length to i ? jae 00007FFB17DB6D5F ; < -- Unexpected - Jump to range check failure cmp r10d , r9d jae 00007FFB17DB6D5F movups xmm1 , xmmword ptr [ rdx+rax*4+10h ] ; // for ( i = 0 ; i < a.Length - simdLength ; i += simdLength ) { add eax,4 cmp r9d , eax jg loop
|
What are these extra disassembly instructions when using SIMD intrinsics ?
|
C_sharp : I 'm reading Clean Code : A Handbook of Agile Software Craftsmanship and one of the examples involves a Portfolio class and a TokyoStockExchange class . However , Portfolio is not very testable because it depends on TokyoStockExchange as an external API to determine the value of the portfolio and such is quite a volatile lookup and not conducive to testing.So , they solve this by creating a common StockExchange interface and have TokyoStockExchange and DummyStockExchange both implement the base class . Thus , dependency inversion principle is attained and in the PortfolioTest class one can instantiate a DummyStockExchange , fix a stock price to a corporation , assign the DummyStockExchange instance to the portfolio , and add some stocks from that company to the portfolio , and then assert if the expected value is indeed the proper value . Here 's the code : My question , simply , is why ? We were trying test if the TokyoStockExchange class worked in tandem with the Portfolio class . Obviously if we create another class with a new method that sets a stock price and then give the portfolio five of those stocks then everything will work . It just seems.. useless to test . I understand that TokyoStockExchange is basically impossible to test with Portfolio because of the changing stock prices but I do n't understand how subbing in a rather useless test helps the situation.It all just seems akin to not knowing if our adder programs works but the only numbers available are randomly generated so we create a dummy class that gives us a 2 and test if 2 + 2 = 4 . Well yeah , obviously that is true . We can still break TokyoStockExchange and the test will still succeed because it 's testing another class . If anything this all seems deceptive and it also results in having to write additional code just to test something we know is going to work.I think this is the biggest problem I have with understanding Unit Testing at this point . I know that I 'm wrong I just have failed to see the light I guess . Hopefully someone can help me out . <code> public class PortfolioTest { private DummyStockExchange exchange ; private Portfolio portfolio ; protected void setUp ( ) { exchange = new DummyStockExchange ( ) ; exchange.fix ( `` MSFT '' , 100 ) ; portfolio = new Portfolio ( exchange ) ; } public void GivenFiveMSFTTotalShouldBe500 ( ) { portfolio.add ( 5 , `` MSFT '' ) ; Assert.assertEquals ( 500 , portfolio.value ( ) ) ; } }
|
Confused about why it 's useful to unit test dummy objects
|
C_sharp : Creating a simple list ( UniqueList ) of items with a Name property that must only contains unique items ( defined as having different Names ) . The constraint on the UniqueList type can be an interface : or an abstract class : So the UniqueList can be : orThe class function , AddUnique : If the class type constraint is based on the interface , compiling results inat the lineAll is well if I base UniqueList on the abstract class . Any thoughts ? <code> interface INamed { string Name { get ; } } public abstract class NamedItem { public abstract string Name { get ; } } class UniqueList < T > : List < T > where T : INamed class UniqueList < T > : List < T > where T : NamedItem public T AddUnique ( T item ) { T result = Find ( x = > x.Name == item.Name ) ; if ( result == default ( T ) ) { Add ( item ) ; return item ; } return result ; } Error : Operator '== ' can not be applied to operands of type 'T ' and 'T ' if ( result == default ( T ) )
|
Constraints on type parameters : interface vs. abstract class
|
C_sharp : I 've noticed a performance hit of iterating over a primitive collection ( T [ ] ) that has been cast to a generic interface collection ( IList or IEnumberable ) .For example : The above code executes significantly faster than the code below , where the parameter is changed to type IList ( or IEnumerable ) : The performance hit still occurs if the object passed is a primitive array , and if I try changing the loop to a for loop instead of a foreach loop.I can get around the performance hit by coding it like such : Is there a more elegant way of solving this issue ? Thank you for your time.Edit : My benchmark code : <code> private static int Sum ( int [ ] array ) { int sum = 0 ; foreach ( int i in array ) sum += i ; return sum ; } private static int Sum ( IList < int > array ) { int sum = 0 ; foreach ( int i in array ) sum += i ; return sum ; } private static int Sum ( IList < int > array ) { int sum = 0 ; if ( array is int [ ] ) foreach ( int i in ( int [ ] ) array ) sum += i ; else foreach ( int i in array ) sum += i ; return sum ; } static void Main ( string [ ] args ) { int [ ] values = Enumerable.Range ( 0 , 10000000 ) .ToArray < int > ( ) ; Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; Sum ( values ) ; //Sum ( ( IList < int > ) values ) ; sw.Stop ( ) ; Console.WriteLine ( `` Elasped : { 0 } ms '' , sw.ElapsedMilliseconds ) ; Console.Read ( ) ; }
|
Overhead of Iterating T [ ] cast to IList < T >
|
C_sharp : I 'm working on a WordSearch puzzle program ( also called WordFind ) where you have to find certain words in a mass of letters . I 'm using C # WinForms.My problem is when I want to click and hold 1 letter ( Label ) , then drag over to other letters to change their ForeColor . I 've tried googling but to no avail.Here is what I have : However , the MouseHover event never fires unless the mouse is not being held down . Also no luck swapping MouseHover with MouseEnter . So , I kept the MouseDown and MouseUp events and tried using MouseHover within the form itself : This event does not fire either and I 'm at a loss as to why it 's not firing and what some alternative solutions are . Any advice is appreciated . <code> foreach ( Letter a in game.GetLetters ( ) ) { this.Controls.Add ( a ) ; a.MouseDown += ( s , e2 ) = > { isDown = true ; a.ForeColor = Color.Yellow ; } ; a.MouseUp += ( s , e2 ) = > { isDown = false ; } ; a.MouseHover += ( s , e2 ) = > { if ( isDown ) a.ForeColor = Color.Yellow ; } ; } private void frmMain_MouseHover ( object sender , MouseEventArgs e ) { if ( isDown ) { foreach ( Letter l in game.GetLetters ( ) ) if ( l.ClientRectangle.Contains ( l.PointToClient ( Control.MousePosition ) ) ) l.ForeColor = Color.Purple ; } }
|
MouseHover not firing when mouse is down
|
C_sharp : Possible Duplicate : Can ’ t operator == be applied to generic types in C # ? I have a DatabaseLookup { } class where the parameter T will be used by the lookup methods in the class . Before lookup , I want to see if T was already looked up with something likeThis does n't compile at all . What is preventing me from making a simple comparison like this ? <code> if ( T == previousLookupObject ) ...
|
Applying '== ' operator to generic parameter
|
C_sharp : I have a dynamic COM object as a private field in my class . I 'm not sure whether it is considered managed resource ( GC cleans it up ) , or not ... .When implementing IDispose , should I clean it up as a managed resource ( only when Dispose ( ) is called explicitly ) , or as a native resource ( when Dispose ( false ) is called from the finalizer too ) ? <code> private dynamic _comConnector = null ; _comConnector = Activator.CreateInstance ( Type.GetTypeFromProgID ( `` SomeProgId '' ) ) ; private void Dispose ( bool disposing ) { if ( disposing ) { // Free managed resources // // -- > Should I call Marshal.FinalReleaseComObject ( _comConnector ) here ? } // Free unmanaged resources // // -- > Or maybe here ? }
|
Are dynamic COM objects considered managed resources ?
|
C_sharp : I have a method like so : However , I 'm wanting to write another method , very similar but it calls WriteAsync instead , such as : However I do n't like having two methods with practically duplicate code . How can I avoid this ? The right approach feels like I should use an Action/Delegate , but the signatures are different ... .Thoughts ? <code> public void Encrypt ( IFile file ) { if ( file == null ) throw new ArgumentNullException ( nameof ( file ) ) ; string tempFilename = GetFilename ( file ) ; using ( var stream = new FileStream ( tempFilename , FileMode.OpenOrCreate ) ) { this.EncryptToStream ( file , stream ) ; file.Write ( stream ) ; } File.Delete ( tempFilename ) ; } public async Task EncryptAsync ( IFile file ) { if ( file == null ) throw new ArgumentNullException ( nameof ( file ) ) ; string tempFilename = GetFilename ( file ) ; using ( var stream = new FileStream ( tempFilename , FileMode.OpenOrCreate ) ) { this.EncryptToStream ( file , stream ) ; await file.WriteAsync ( stream ) ; } File.Delete ( tempFilename ) ; }
|
Refactoring a library to be async , how can I avoid repeating myself ?
|
C_sharp : I have a native DLL , written in Delphi , actively using callback mechanism : a callback function is `` registered '' and later called from inside of the DLL : Most of the callback functions are passing plain structures by reference , like the following : where PStructType is declared asThis DLL is consumed by a .NET application , written in C # . The C # code is written very negligently and the application as a whole behaves unreliably , showing hard-to-identify exceptions , raised in different places from run to run.I do not have reasons to suspect the DLL , because it had already proved itself as a quite robust piece of software , used in many other applications . What I am currently concerned about is the way how those structures are used in C # .Let 's assume , that the record from above is re-declared in C # as follows : and the callback is declared asNow something interesting begins . Let 's assume , that in the DLL , the registered callbacks are called in this way : But what I see in the C # application , and what I do not like at all , that the marshaled structure is saved aside as a pointer for future use : As I understand , Struct variable is that created on Delphi 's stack deep inside in the DLL , and storing pointer to it on heap in client application - is a sheer adventure . I am not a big fan/expert of C # , so please excuse my naive question , does the marshaller do something behind the scene , like copy structures onto heap or something like that , or the fact that the application sometimes works is a matter of pure chance ? Thank you in advance . <code> function RegisterCallback ( CallbackProc : TCallbackProc ) : Integer ; stdcall ; TCallbackProc = procedure ( Struct : PStructType ) ; stdcall ; TStructType = packed record Parameter1 : array [ 0..9 ] of AnsiChar ; Parameter2 : array [ 0..19 ] of AnsiChar ; Parameter3 : array [ 0..29 ] of AnsiChar ; end ; PStructType = ^TStructType ; [ StructLayout ( LayoutKind.Sequential , CharSet = CharSet.Ansi , Pack = 1 ) ] public struct TStructType { [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 10 ) ] public string Parameter1 ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 20 ) ] public string Parameter2 ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 30 ) ] public string Parameter3 ; } [ UnmanagedFunctionPointer ( CallingConvention.StdCall ) ] public delegate void CallbackProc ( ref TStructType Struct ) ; var Struct : TStructType ; begin // Struct is initialized and filled with values CallbackProc ( @ Struct ) ; end ; private void CallbackProc ( ref TStructType Struct ) { SomeObjectList.Add ( Struct ) ; // ! ! ! WTF ? }
|
Marshalling plain structures : does C # copy them onto heap ?
|
C_sharp : I have two text boxes and I want skip a block of code only when both are empty : If either of the text boxes has something , I want the //Do something part to execute . Only when both are empty do I want to skip.However the above code fragment does n't work . Why ? <code> if ( txtBox1.Text.Trim ( ) ! = string.Empty & & txtBox2.Text.Trim ( ) ! = string.Empty ) { // Do something }
|
Why does this IF statement return false ?
|
C_sharp : I have a string like this : When I parse it to JObject like thatMy jObject looks like this : I need to get rid of scientific notation so that resulting JObject would look like original json.I managed to do that using later version of Newtonsoft.Json like that : But I need to achieve the same result using Newtonsoft.Json version 3.5 which does not have a FloatParseHandling property . I guess I need to implement a JsonConverter somehow , but I have no idea how to do that , since my real json is much more complex than the one in example and I need to handle all the float values in it the right way.So , what would be the right way to get a JObject without a scientific notation for float values using Newtonsoft 3.5 ? <code> var str = `` { 'data ' : { 'someProperty ' : 0.00001 } } '' ; var jObject = JObject.Parse ( str ) ; { `` data '' : { `` someProperty '' : 1E-05 } } var serializer = new JsonSerializer { FloatParseHandling = FloatParseHandling.Decimal } ; using ( System.IO.TextReader tr = new System.IO.StringReader ( str ) using ( var jsonReader = new JsonTextReader ( tr ) ) { var jp = serializer.Deserialize ( jsonReader ) ; var jObject = JObject.FromObject ( jp ) ; }
|
How to deserialize string to JObject without scientific notation in C #
|
C_sharp : I contribute to an open source library that currently supports MVC 2 - MVC 5 , and I would like to support MVC 6 ( and beyond ) as well . To support each version of MVC , we take advantage of the Condition feature of MSBuild to include the correct version of MVC and its dependencies when doing a build ( depending on the value of DefineConstants ) . This makes it possible to use a single project file for all supported versions of MVC , by creating an individual DLL for each MVC version using the same project file and source code.I have looked at the project structure of ASP.NET 5/MVC 6 and have already resigned to use a project.json file rather than a .csproj file for MVC 6 . However , I read the project.json documentation and there does n't appear to be a way to support multiple versions of MVC with a single project.json file.Ideally , I would like to ditch MSBuild and use Roslyn for every MVC version ( including MVC 2 - MVC 5 ) going forward . But is there a way to support multiple MVC versions without having to create a project file ( and project directory since all of them would have to be named project.json ) for every MVC version ? If not , is there another way to not have to duplicate all of the project.json configuration 5 times ? <code> < ItemGroup Condition= '' $ ( DefineConstants.Contains ( 'MVC2 ' ) ) `` > < Reference Include= '' System.Web.Mvc , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' / > < /ItemGroup > < ItemGroup Condition= '' $ ( DefineConstants.Contains ( 'MVC3 ' ) ) `` > < ! -- Due to the windows update MS14-059 , we need this hack to ensure we can build MVC3 both on machines that have the update and those that do n't -- > < Reference Condition= '' Exists ( ' $ ( windir ) \Microsoft.NET\assembly\GAC_MSIL\System.Web.Mvc\v4.0_3.0.0.0__31bf3856ad364e35\System.Web.Mvc.dll ' ) `` Include= '' System.Web.Mvc , Version=3.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' / > < Reference Condition= '' ! Exists ( ' $ ( windir ) \Microsoft.NET\assembly\GAC_MSIL\System.Web.Mvc\v4.0_3.0.0.0__31bf3856ad364e35\System.Web.Mvc.dll ' ) `` Include= '' System.Web.Mvc , Version=3.0.0.1 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < Private > True < /Private > < HintPath > ..\packages\Microsoft.AspNet.Mvc.3.0.20105.1\lib\net40\System.Web.Mvc.dll < /HintPath > < /Reference > < Reference Include= '' System.Web.Razor , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < Private > True < /Private > < HintPath > ..\packages\Microsoft.AspNet.Razor.1.0.20105.408\lib\net40\System.Web.Razor.dll < /HintPath > < /Reference > < Reference Include= '' System.Web.WebPages.Razor , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < Private > True < /Private > < HintPath > ..\packages\Microsoft.AspNet.WebPages.1.0.20105.408\lib\net40\System.Web.WebPages.Razor.dll < /HintPath > < /Reference > < /ItemGroup > < ItemGroup Condition= '' $ ( DefineConstants.Contains ( 'MVC4 ' ) ) `` > < Reference Include= '' System.Web.Mvc , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < Private > True < /Private > < HintPath > ..\packages\Microsoft.AspNet.Mvc.4.0.20710.0\lib\net40\System.Web.Mvc.dll < /HintPath > < /Reference > < Reference Include= '' System.Web.Razor , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < Private > True < /Private > < HintPath > ..\packages\Microsoft.AspNet.Razor.4.0.20715.0\lib\net40\System.Web.Razor.dll < /HintPath > < /Reference > < Reference Include= '' System.Web.WebPages.Razor , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < Private > True < /Private > < HintPath > ..\packages\Microsoft.AspNet.WebPages.4.0.20710.0\lib\net40\System.Web.WebPages.Razor.dll < /HintPath > < /Reference > < /ItemGroup > < ItemGroup Condition= '' $ ( DefineConstants.Contains ( 'MVC5 ' ) ) `` > < Reference Include= '' System.Web.Mvc , Version=5.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < Private > True < /Private > < HintPath > ..\packages\Microsoft.AspNet.Mvc.5.0.0\lib\net45\System.Web.Mvc.dll < /HintPath > < /Reference > < Reference Include= '' System.Web.Razor , Version=3.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < Private > True < /Private > < HintPath > ..\packages\Microsoft.AspNet.Razor.3.0.0\lib\net45\System.Web.Razor.dll < /HintPath > < /Reference > < Reference Include= '' System.Web.WebPages , Version=3.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < Private > True < /Private > < HintPath > ..\packages\Microsoft.AspNet.WebPages.3.0.0\lib\net45\System.Web.WebPages.dll < /HintPath > < /Reference > < Reference Include= '' System.Web.WebPages.Razor , Version=3.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < Private > True < /Private > < HintPath > ..\packages\Microsoft.AspNet.WebPages.3.0.0\lib\net45\System.Web.WebPages.Razor.dll < /HintPath > < /Reference > < /ItemGroup >
|
Supporting Multiple Versions of a Compilation Dependency ( vNext )
|
C_sharp : The autofac documentation states : when Autofac is injecting a constructor parameter of type IEnumerable < ITask > it will not look for a component that supplies IEnumerable < ITask > . Instead , the container will find all implementations of ITask and inject all of them.But actually , it adds each registered type as many times as it has been registered . So , if you register a class twice as following : Then you get two items in the enumeration ! ! Within a single module , it is not a problem , as you obviously take care to register only once your types . But if you have a shared module registered by multiple modules ( typical diamond module dependency diagram ) , then you get as many items in the enumeration as the shared module has been registered by others ... Is it a bug ? Is there any way to force the enumeration to provide a single item for each implementation , as stated in the documentation , no more ? <code> builder.RegisterType < A > ( ) ; builder.RegisterType < A > ( ) ;
|
Autofac Enumeration not working with multiple registrations of types or modules
|
C_sharp : How does Skip ( ) and Take ( ) work in Entity Framework when calling a stored procedure ? I ca n't access sql profiler to check , but I want to make sure I optimize the amount of data sent between servers.Say I have the following code , where MyStoredProcedure returns 1000+ rows . Will the Take ( 10 ) make sure that only 10 of those rows are sent from the database server to the web server , or will all 1000+ rows be sent ( though only 10 would be sent to the client ) ? <code> List < MyComplex_Result > myComplexList = db.MyStoredProcedure ( ) .Skip ( 50 ) .Take ( 10 ) ;
|
EF using skip and take on stored procedure
|
C_sharp : I already searched the forum but no asked question fits to my problem I think ... I use a BackgroundWorker to handle a very time consuming operation . After this operation finishes a button should be set to enabled so that the user can perform another operation . I 'm using WPF and I 'm following the MVVM pattern , so I have no direct access to this button . I have to call a method in the BackgroundWorker_RunWorkerCompleted event handler which sets a Property , representing the buttons enabled-state , to true . That all works fine except one thing : The button is only redrawn after I e.g . click into the window ( or maximize the window , ... ) . Thats very annoying and took me the whole day to get rid of this behaviour but I ca n't find a solution ... The BackgroundWorker_RunWorkerCompleted event handler looks like this : Has anyone any idea how to fix this issue ? Edit : The button is bound to a command : This command is a RelayCommand as Smith stated in his blog ( http : //msdn.microsoft.com/en-us/magazine/dd419663.aspx ) and looks like this : this.CanLoadTarget is set to true by the SetButtonToEnabled ( ) ; methodEdit 2 : the following code 'works ' : but that is some sort of really dangerous and ugly code ... <code> void fileLoadBackgroundWorker_RunWorkerCompleted ( object sender , RunWorkerCompletedEventArgs e ) { SetButtonToEnabled ( ) ; } < Button Name= '' btnLoadTargetFile '' Command= '' { Binding Path=LoadTargetCommand } '' ... / > public RelayCommand LoadTargetCommand { get { if ( loadTargetCommand == null ) { loadTargetCommand = new RelayCommand ( param = > this.OnRequestLoadFile ( BusinessLogic.CustomTypes.TreeType.Target ) , param = > this.CanLoadTarget ) ; } return loadTargetCommand ; } set { loadTargetCommand = value ; } } fileLoadBackgroundWorker.RunWorkerAsync ( argumentList ) ; while ( fileLoadBackgroundWorker.IsBusy ) System.Windows.Forms.Application.DoEvents ( ) ; SetButtonToEnabled ( ) ;
|
Why does BackgroundWorker_RunWorkerCompleted not update GUI ?
|
C_sharp : I 'm making a sound synthesis program in which the user can create his own sounds doing node-base compositing , creating oscillators , filters , etc.The program compiles the nodes onto an intermediary language which is then converted onto an MSIL via the ILGenerator and DynamicMethod.It works with an array in which all operations and data are stored , but it will be faster if I was able to use pointers to allow me to do some bit-level operations later.PD : Speed is very important ! I noticed that one DynamicMethod constructor override has a method attribute , which one is UnsafeExport , but I ca n't use it , because the only valid combination is Public+StaticThis is what I 'm trying to do which throws me a VerificationException : ( Just to assign a value to a pointer ) <code> //Testing delegateunsafe delegate float TestDelegate ( float* data ) ; //Inside the test method ( which is marked as unsafe ) Type ReturnType = typeof ( float ) ; Type [ ] Args = new Type [ ] { typeof ( float* ) } ; //Ca n't use UnamangedExport as method attribute : DynamicMethod M = new DynamicMethod ( `` HiThere '' , ReturnType , Args ) ; ILGenerator Gen = M.GetILGenerator ( ) ; //Set the pointer value to 7.0 : Gen.Emit ( OpCodes.Ldarg_0 ) ; Gen.Emit ( OpCodes.Ldc_R4 , 7F ) ; Gen.Emit ( OpCodes.Stind_R4 ) ; //Just return a dummy value : Gen.Emit ( OpCodes.Ldc_R4 , 20F ) ; Gen.Emit ( OpCodes.Ret ) ; var del = ( TestDelegate ) M.CreateDelegate ( typeof ( TestDelegate ) ) ; float* data = ( float* ) Marshal.AllocHGlobal ( 4 ) ; //VerificationException thrown here : float result = del ( data ) ;
|
ILGenerator : How to use unmanaged pointers ? ( I get a VerificationException )
|
C_sharp : If you forward to approximately 13 minutes into this video by Eric Lippert he describes a change that was made to the C # compiler that renders the following code invalid ( Apparently prior to and including .NET 2 this code would have compiled ) .Now I understand that clearly any execution of the above code actually evaluates to But what I dont understand is why it is considered `` desirable '' to make the following code in-compilable ? IE : What are the risks with allowing such inferences to run their course ? <code> int y ; int x = 10 ; if ( x * 0 == 0 ) y = 123 ; Console.Write ( y ) ; int y ; int x = 10 ; y = 123 ; Console.Write ( y ) ;
|
Constants and compile time evaluation - Why change this behaviour
|
C_sharp : I 've already looked around , and since i 'm no security or encryption expert , I am still confused on how to implement encryption in my program . I need a server to login to its gitHub account to update code files with special headers . The only hang-up I have right now is how to store/retrieve the server 's credentials . How would I encrypt these credentials for storage ? I know its a bad idea to store them in the code like the example is , and it would be a bad idea as well to store them in any file unencrypted.Also , the only user interaction I want occurs when they compile and setup the program on the server . It 's as a cronjob on a linux server , in-case that makes a difference . Another detail to note , I 'm using libgit2sharp , but previously was using a bash script and ssh to authenticate for testing . <code> PushOptions push = new PushOptions { Credentials = new UsernamePasswordCredentials { Password = `` password '' , Username = `` Username '' } } ;
|
Storing credentials for automated use
|
C_sharp : Why does the following code : render as : Where is that `` Length=4 '' coming from ? UpdateIf I remove the new { @ class = `` more '' } , I do n't get that Length=4 parameter . <code> < % = Html.ActionLink ( `` [ Click Here For More + ] '' , `` Work '' , `` Home '' , new { @ class = `` more '' } ) % > < a class= '' more '' href= '' /Home/Work ? Length=4 '' > [ Click Here For More + ] < /a >
|
Puzzling ... why do most of my links , in ASP.NET MVC , have Length=4 appended to them ?
|
C_sharp : I have this code : When I try to compile it I get an error : A deconstruction can not mix declarations and expressions on the left I do n't understand why . Any suggestions ? <code> public static ( int a , int b ) f12 ( ) { return ( 1 , 2 ) ; } public static void test ( ) { int a ; ( a , int b ) = f12 ( ) ; //here is the error }
|
Why a deconstruction can not mix declarations and expressions on the left
|
C_sharp : I have a rather simple problem , but there seems to be no solution within C # .I have around 100 Foo classes where each implement a static FromBytes ( ) method . There are also some generic classes which shall use these methods for its own FromBytes ( ) . BUT the generic classes can not use the static FromBytes ( ) methods , because T.FromBytes ( ... ) is illegal.Do I miss something or is there no way to implement this functionality ? I think it would be unfair to choose an answer as accepted answer , after all answers and comments have contributed in different ways with their different views . It would be nice if someone writes a good overview about the different approaches with their pros and cons . That should be accepted after it helps future developers best . <code> public class Foo1 { public static Foo1 FromBytes ( byte [ ] bytes , ref int index ) { // build Foo1 instance return new Foo1 ( ) { Property1 = bytes [ index++ ] , Property2 = bytes [ index++ ] , // [ ... ] Property10 = bytes [ index++ ] } ; } public int Property1 { get ; set ; } public int Property2 { get ; set ; } // [ ... ] public int Property10 { get ; set ; } } //public class Foo2 { ... } // [ ... ] //public class Foo100 { ... } // Generic class which needs the static method of T to workpublic class ListOfFoo < T > : System.Collections.Generic.List < T > { public static ListOfFoo < T > FromBytes ( byte [ ] bytes , ref int index ) { var count = bytes [ index++ ] ; var listOfFoo = new ListOfFoo < T > ( ) ; for ( var i = 0 ; i < count ; i++ ) { listOfFoo.Add ( T.FromBytes ( bytes , ref index ) ) ; // T.FromBytes ( ... ) is illegal } return listOfFoo ; } }
|
Is there a workaround to use static methods by a generic class ?
|
C_sharp : In ASP.NET MVC 2 asynchronous controllers , we can do something like this : My question is , does the action filter `` Blurb '' in this case execute asynchronously ? In other words , is its synchronous nature automatically wrapped into an asynchronous call ? <code> public class SomeController : AsyncController { [ Blurb ] public void FooAsync ( ) { this.AsyncManager.OutstandingOperations.Increment ( ) ; Task.Factory.StartNew ( ( ) = > { this.AsyncManager.Parameters [ `` result '' ] = new BazResult ( ) ; this.AsyncManager.OutstandingOperations.Decrement ( ) ; } ) ; } public ActionResult FooCompleted ( ActionResult result ) { return result ; } }
|
In ASP.NET MVC 2 asynchronous controllers , do Action Filters execute asynchronously ?
|
C_sharp : I am looking at the Roslyn September 2012 CTP with Reflector , and I noticed that the SlidingTextWindow class has the following : I believe the purpose of this class is to provide fast access to substrings of the input text , by using char [ ] characterWindow , starting with 2048 characters at a time ( although the characterWindow may grow ) . I believe this is because it is faster to take substrings of character arrays than of strings , as Eric Lippert seems to indicate on his blog.The SlidingTextWindow class is instantiated each time the Lexer class is instantiated , which happens each call to SyntaxTree.ParseText.I do not understand the purpose of the arrayPool field . Its only usage in this class is in the constructor and Dispose methods . When calling SyntaxTree.ParseText , there seems to be only one instance of the Lexer class and of the SlidingTextWindow class created . What advantage is gained by enqueuing the characterWindow when an instance is disposed and by trying to dequeue a characterWindow when an instance is created ? Perhaps somebody from the Roslyn team could help me understand this ? <code> internal sealed class SlidingTextWindow : IDisposable { private static readonly ConcurrentQueue < char [ ] > arrayPool = new ConcurrentQueue < char [ ] > ( ) ; private int basis ; private readonly LexerBaseCache cache ; private char [ ] characterWindow ; private int characterWindowCount ; private int characterWindowStart ; private int offset ; private readonly IText text ; private readonly int textEnd ; public SlidingTextWindow ( IText text , LexerBaseCache cache ) { this.text = text ; this.basis = 0 ; this.characterWindowStart = 0 ; this.offset = 0 ; this.textEnd = text.Length ; this.cache = cache ; if ( ! arrayPool.TryDequeue ( out this.characterWindow ) ) { this.characterWindow = new char [ 2048 ] ; } } public void Dispose ( ) { arrayPool.Enqueue ( this.characterWindow ) ; this.characterWindow = null ; } // ... }
|
Why use a ConcurrentQueue in this case ?
|
C_sharp : So I have a client who is going to upgrade to ssl , but they currently use just plain http.I want to change the endpoint for the service . To use https.The question is will their connection to the web service using http still work until they change the address to https ? Do I need two endpoints to pull this off ? <code> < binding name= '' basicHttpSSLBinding '' closeTimeout= '' 00:02:00 '' openTimeout= '' 00:02:00 '' receiveTimeout= '' 00:20:00 '' sendTimeout= '' 00:20:00 '' > < security mode= '' Transport '' > < /security > < /binding >
|
Can I use normal http and https for the same endpoint
|
C_sharp : Trying to do some business logic in C # by overriding the EF SaveChanges method.The idea is to have some advanced calculations on things like if this field has changed update this field . And this field is the sum of the subclass minus some other fields , you know advanced business junk . Since it 's really complicated we want to test the stuffing out of it . Adding tests work great but the updating ones we ca n't seem to test as we have written an interface where the method in question is passed Signature looks like this When calling it in full EF it works beautifully We just ca n't figure out how to pass in the DbPropertyValues original or updated for our tests . Please help us figure out how to test that method . <code> void Update ( object entity , DbPropertyValues currentValues , DbPropertyValues originalValues ) ; public override int SaveChanges ( ) { var added = ChangeTracker.Entries ( ) .Where ( p = > p.State == EntityState.Added ) .Select ( p = > p.Entity ) ; var updated = ChangeTracker.Entries ( ) .Where ( p = > p.State == EntityState.Modified ) .Select ( p = > p ) ; var context = new ChangeAndValidationContext ( ) ; foreach ( var item in added ) { var strategy = context.SelectStrategy ( item ) ; strategy.Add ( item ) ; } foreach ( var item in updated ) { var strategy = context.SelectStrategy ( item ) ; strategy.Update ( item.Entity , item.CurrentValues , item.OriginalValues ) ; } return base.SaveChanges ( ) ; }
|
Testing EF Save Changes Modifiers . Passing in DbPropertyValues
|
C_sharp : I am aware that Linq provides capability to determine if a collection has any items . Such asThis is very efficient because if it finds at least one item then the iteration stops . Now what if I want to know if a collection has at least 2 items . Here is the code i have currently : This one will go through the whole collection then if the count is bigger than one . I think this is very inefficient . Does Linq or .NET provide a better way to do this ? <code> var anyCategories= categories.Any ( ) ; var atLeastTwoCategories= categories.Count ( ) > 1 ;
|
Efficient way to determine collection has at least 2 items
|
C_sharp : I 'd like to create a method that returns a type ( or IEnumerable of types ) that implement a specific interface that takes a type parameter -- however I want to search by that generic type parameter itself . This is easier demonstrated as an example : Method signature that I want : And then if I have the below objectsI then want to be able to do : and get an IEnumerable containing the types FooRepo and DifferentFooRepo.This is very similar to this question , however using that example I would like to search by both IRepository < > and by User . <code> public IEnumerable < Type > GetByInterfaceAndGeneric ( Type interfaceWithParam , Type specificTypeParameter ) public interface IRepository < T > { } ; public class FooRepo : IRepository < Foo > { } ; public class DifferentFooRepo : IRepository < Foo > { } ; var repos = GetByInterfaceAndGeneric ( typeof ( IRepository < > ) , typeof ( Foo ) ) ;
|
Get type that implements generic interface by searching for a specific generic interface parameter
|
C_sharp : In the projects I worked on I have classes that query/update database , like this one , as I keep creating more and more classes of this sort , I realize that maybe I should make this type of class static . By doing so the obvious benefit is avoid the need to create class instances every time I need to query the database . But since for the static class , there is only one copy of the class , will this result in hundreds of requests contend for only one copy of static class ? Thanks , <code> public class CompanyInfoManager { public List < string > GetCompanyNames ( ) { //Query database and return list of company names } }
|
should I make this class static ?
|
C_sharp : I 'm experimenting with parsing expression trees and have written the following code : The idea of the code is to parse the expression tree and write details about the nodes into the string variable output . However , when this variable is written to the page ( using the Output ( ) method ) , I 'm finding it 's empty.When I use the debugger to step through the code , I find that output is correctly set to ' x ' when the code executes HandleParameterExpression ( ) for the first time , but as soon as control returns from HandleParameterExpression ( ) back to the switch block in HandleExpression ( ) , the variable is mysteriously empty again.Since strings are reference types , I should simply be able to pass the reference between the methods and changes to its value made by the methods should be retained , right ? Is there some subtlety of parameter passing in C # that I 'm not aware of ? <code> private void TestExpressionTree ( ) { Expression < Func < int , bool > > expression = x = > x == 1 || x == 2 ; string output = String.Empty ; HandleExpression ( expression.Body , output ) ; Output ( `` Output '' , output ) ; } private void HandleExpression ( Expression expression , string output ) { switch ( expression.NodeType ) { case ExpressionType.Conditional : HandleConditionalExpression ( expression , output ) ; break ; case ExpressionType.OrElse : HandleOrElseExpression ( expression , output ) ; break ; case ExpressionType.Equal : HandleEqualExpression ( expression , output ) ; break ; case ExpressionType.Parameter : HandleParameterExpression ( expression , output ) ; break ; case ExpressionType.Constant : HandleConstantExpression ( expression , output ) ; break ; } } private void HandleConditionalExpression ( Expression expression , string output ) { ConditionalExpression conditionalExpression = ( ConditionalExpression ) expression ; HandleExpression ( conditionalExpression.Test , output ) ; } private void HandleOrElseExpression ( Expression expression , string output ) { BinaryExpression binaryExpression = ( BinaryExpression ) expression ; HandleExpression ( binaryExpression.Left , output ) ; output += `` || '' ; HandleExpression ( binaryExpression.Right , output ) ; } private void HandleEqualExpression ( Expression expression , string output ) { BinaryExpression binaryExpression = ( BinaryExpression ) expression ; HandleExpression ( binaryExpression.Left , output ) ; output += `` = '' ; HandleExpression ( binaryExpression.Right , output ) ; } private void HandleParameterExpression ( Expression expression , string output ) { ParameterExpression parameterExpression = ( ParameterExpression ) expression ; output += parameterExpression.Name ; } private void HandleConstantExpression ( Expression expression , string output ) { ConstantExpression constantExpression = ( ConstantExpression ) expression ; output += constantExpression.Value.ToString ( ) ; }
|
C # : String parameter being mysteriously reset to empty - please help !
|
C_sharp : In my codebehind file I call this function : Then in webservice I do this : What I want to do now is when an exception is thrown , show a messagebox . And when I got a status 200 I navigate to the next page in de code behind file.My question is now , how do i 'm going to know this in my code behind file ? Many thanks in advance ! EDITI also have these helper methods : <code> private void loginAction ( object sender , TappedRoutedEventArgs e ) { Webservice webservice = new Webservice ( ) ; webservice.getUser ( txtLogin.Text , txtPass.Text ) ; } public void getUser ( String user , String password ) { String strUrl = String.Format ( `` http : //*******/nl/webservice/abc123/members/login ? email= { 0 } & password= { 1 } '' , user , password ) ; startWebRequest ( strUrl , loginCallback ) ; } private async void loginCallback ( IAsyncResult asyncResult ) { try { ReceiveContext received = GetReceiveContextFromAsyncResult ( asyncResult , `` User '' ) ; if ( received ! = null & & received.Status == 200 ) { await UserDataSource.AddUser ( received.Data ) ; } else { throw new Exception ( `` failedddd '' ) ; } } catch ( Exception e ) { } } # region HELPERSprivate void startWebRequest ( string url , AsyncCallback callback ) { // HttpWebRequest.RegisterPrefix ( `` http : // '' , WebRequestCreator.ClientHttp ) ; HttpWebRequest httpWebRequest = ( HttpWebRequest ) HttpWebRequest.Create ( new Uri ( url ) ) ; // start the stream immediately httpWebRequest.AllowReadStreamBuffering = false ; // asynchronously get a response httpWebRequest.BeginGetResponse ( callback , httpWebRequest ) ; } private ReceiveContext GetReceiveContextFromAsyncResult ( IAsyncResult asyncResult , string context ) { // Request afleiding van de AsyncState uit het ontvangen AsyncResult HttpWebRequest httpWebRequest = ( HttpWebRequest ) asyncResult.AsyncState ; HttpWebResponse httpWebResponse = null ; try { // Response afleiden uit de Resuest via de methode EndGetResponse ( ) ; httpWebResponse = ( HttpWebResponse ) httpWebRequest.EndGetResponse ( asyncResult ) ; string responseString ; // using == IDisposable ( automatische GC ) using ( StreamReader readStream = new StreamReader ( httpWebResponse.GetResponseStream ( ) ) ) { //Stream van de response gebruiken om een readstream te maken . responseString = readStream.ReadToEnd ( ) ; } // Release the HttpWebResponse //httpWebResponse.Dispose ( ) ; return new ReceiveContext ( int.Parse ( responseString.Substring ( 10 , 3 ) ) , responseString ) ; } catch ( WebException wex ) { Debug.WriteLine ( String.Format ( `` { 0 } kon niet opgehaald worden : { 1 } '' , context , wex.Message ) ) ; } catch ( JsonReaderException jrex ) { Debug.WriteLine ( String.Format ( `` { 0 } opgehaald van server , maar de json kon niet geparsed worden : { 1 } '' , context , jrex.Message ) ) ; } catch ( FormatException fex ) { Debug.WriteLine ( String.Format ( `` { 0 } opgehaald van server , maar de gegevens kloppen niet : { 1 } '' , context , fex.Message ) ) ; } catch ( ArgumentOutOfRangeException arex ) { Debug.WriteLine ( String.Format ( `` { 0 } opgehaald van server , maar de context is leeg : { 1 } '' , context , arex.Message ) ) ; } return null ; } public sealed class ReceiveContext { public ReceiveContext ( int status , string data ) { this.Status = status ; this.Data = data ; } public int Status { get ; private set ; } public string Data { get ; private set ; } } # endregion
|
returning a false when got 400 status of webservice in JSON
|
C_sharp : In a C # 8 project with nullable reference types enabled , I have the following code which I think should give me a warning about a possible null dereference , but does n't : When instance is initialized with the default constructor , instance.Member is set to the default value of ExampleClassMember , which is null . Thus , instance.Member.Value will throw a NullReferenceException at runtime . As I understand C # 8 's nullability detection , I should get a compiler warning about this possibility , but I do n't ; why is that ? <code> public class ExampleClassMember { public int Value { get ; } } public struct ExampleStruct { public ExampleClassMember Member { get ; } } public class Program { public static void Main ( string [ ] args ) { var instance = new ExampleStruct ( ) ; Console.WriteLine ( instance.Member.Value ) ; // expected warning here about possible null dereference } }
|
Why do n't I get a warning about possible dereference of a null in C # 8 with a class member of a struct ?
|
C_sharp : I 'm trying to bring a listing to frontEnd.I 'm using mongoDb . My mongodb has a colletion called Employee . Employee has the following attributeIn this Model , I have an attribute called : public List < DocumentsImagesViewModel > DependentsDocuments { get ; set ; } : I 'm trying to bring benefits that contain the depedentID equal of the parameter . When I use this method , it has an error that can not be converted . IEnumerable to List C # What is the best way to get this data ? this filter ? I used this question as a reference : Mongodb C # driver return only matching sub documents in array <code> public class EmployeeViewModel { [ BsonId ( IdGenerator = typeof ( StringObjectIdGenerator ) ) ] public string ownerId { get ; set ; } public string atributeChange { get ; set ; } public PersonalDataViewModel personalData { get ; set ; } public AddressViewModel address { get ; set ; } public List < EmailsViewModel > emails { get ; set ; } public SyndicateViewModel syndicate { get ; set ; } public List < DependentsViewModel > dependents { get ; set ; } public List < PhoneViewModel > phone { get ; set ; } public List < BankViewModel > bank { get ; set ; } public AttributesViewModel attributes { get ; set ; } public List < BenefitsViewModel > benefits { get ; set ; } public TransportViewModel transport { get ; set ; } public List < AttachmentsViewModel > attachments { get ; set ; } public List < DocumentsViewModel > documents { get ; set ; } public List < DocumentsImagesViewModel > DependentsDocuments { get ; set ; } public List < AttachmentsViewModel > DependentsAttachments { get ; set ; } public List < BenefitsViewModel > DependentsBenefits { get ; set ; } } public class DocumentsViewModel { [ BsonId ] public string ownerId { get ; set ; } public string id { get ; set ; } public string dependentId { get ; set ; } public string number { get ; set ; } public DateTime expiration { get ; set ; } public List < DocumentsImagesViewModel > images { get ; set ; } public List < DocumentPropertiesViewModel > properties { get ; set ; } public DocumentTypeViewModel type { get ; set ; } } public async Task < List < Documents > > GetDocument ( string ownerId , string dependentId ) { var query = from employee in _employee.AsQueryable ( ) where employee.ownerId == ownerId select new Employee ( ) { DependentsDocuments = employee.DependentsDocuments.Where ( x = > x.dependentId == dependentId ) } ; return query.ToList ( ) ; }
|
Can not convert type IEnumerable to List C #
|
C_sharp : I am working with asp.net mvc and creating a form . I want to add a class attribute to the form tag.I found an example here of adding a enctype attribute and tried to swap out with class . I got a compile error when accessing the view.I then found an example of someone adding a @ symbol to the beginning of the property name and that worked . Great that it works , but I am one that needs to know why and a quick Google search was not helpful . I understand that C # allows one to prepend the @ to a string to ignore escaping chars . Why does it work in this case ? What does the @ tell the compiler ? Code that produces a compile error ? Code that does work : <code> < % Html.BeginForm ( `` Results '' , `` Search '' , FormMethod.Get , new { class= '' search_form '' } ) ; % > < % Html.BeginForm ( `` Results '' , `` Search '' , FormMethod.Get , new { @ class= '' search_form '' } ) ; % >
|
Why does adding the @ symbol make this work ?
|
C_sharp : Given the following code : Is it possible that the cast from char to int could fail ( and under what circumstances ) ? <code> string source = `` Some Unicode String '' ; foreach ( char value in source ) { int y = ( int ) value ; }
|
Is casting char to int a safe operation in C # ?
|
C_sharp : I have a controller running on Azure App Service - Mobile . The trace shows that the below code runs fine until db.SaveChanges ( ) this fails.The stacktrace from the diagnostic on the appservice ( which I unfortunately do not understand ) gives : UpdateSo I will be trying this , which will give more detailed error message : AlsoI will go through all the the settings to ensure that the a field that must not be null is null as according to this answer on stackoverflow.Testing the aboveThe exception hides that the Id Field is required , is the exception.The database I have uses EntityData ( described here on msdn ) where the Id comes from . My use on MobileService was that the Id was created when I executed the line , which fails db.SaveChanges ( ) . Can somebody clarify this ? The class looks like this : <code> var telemetry = new Microsoft.ApplicationInsights.TelemetryClient ( ) ; telemetry.TrackTrace ( `` Create User '' ) ; using ( BCMobileAppContext db = new BCMobileAppContext ( ) ) { string Username_NoSpaces = username.Username.Replace ( `` `` , `` '' ) ; var user = db.Users.FirstOrDefault ( u = > u.Username_NoSpaces == Username_NoSpaces || u.MicrosoftToken == this.User.Identity.Name ) ; telemetry.TrackTrace ( `` 1 '' ) ; if ( user == null & & ! Username_NoSpaces.Contains ( `` , '' ) ) { telemetry.TrackTrace ( `` 2 '' ) ; DateTime now = DateTime.UtcNow ; telemetry.TrackTrace ( `` 3 '' ) ; string username_noSpaces = username.Username.Replace ( `` `` , `` '' ) ; DataObjects.User userItem = new DataObjects.User ( ) { Created = now , UserId = this.User.Identity.Name , MicrosoftToken = this.User.Identity.Name , Username_NoSpaces = username_noSpaces , Update = now , Username = username.Username , Gold = 1 , Level = 1 , Title = `` Sir '' , InGameCrest = `` '' , ReceiveNotifications = true } ; telemetry.TrackTrace ( `` 4 '' ) ; UserDTO returnObject1 = new UserDTO ( ) { Created = userItem.Created , isCreated = true , MicrosoftId = userItem.MicrosoftToken , Username = userItem.Username } ; telemetry.TrackTrace ( `` 5 '' ) ; db.Users.Add ( userItem ) ; telemetry.TrackTrace ( `` 6 '' ) ; db.SaveChanges ( ) ; //Trace and code fails telemetry.TrackTrace ( `` 7 '' ) ; UserDTO returnObject = new UserDTO ( ) { Created = userItem.Created , isCreated = true , MicrosoftId = userItem.MicrosoftToken , Username = userItem.Username } ; telemetry.TrackTrace ( `` 8 '' ) ; return Ok ( returnObject ) ; } } 2016-04-07T17:29:19 PID [ 5008 ] Error Operation=ReflectedHttpActionDescriptor.ExecuteAsync , Exception=System.Data.Entity.Validation.DbEntityValidationException : Validation failed for one or more entities . See 'EntityValidationErrors ' property for more details . at System.Data.Entity.Internal.InternalContext.SaveChanges ( ) at System.Data.Entity.Internal.LazyInternalContext.SaveChanges ( ) at System.Data.Entity.DbContext.SaveChanges ( ) at BCMobileAppService.Controllers.Test2Controller.Post ( UserDTO username ) in C : \Users\johann\Desktop\BCMobileApp_Runtime\BCMobileAppService\Controllers\TestController.cs : line 78 at lambda_method ( Closure , Object , Object [ ] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor. < > c__DisplayClass10. < GetExecutor > b__9 ( Object instance , Object [ ] methodParameters ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute ( Object instance , Object [ ] arguments ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync ( HttpControllerContext controllerContext , IDictionary 2 arguments , CancellationToken cancellationToken ) -- - 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.Web.Http.Tracing.ITraceWriterExtensions. < TraceBeginEndAsyncCore > d__18 1.MoveNext ( ) 2016-04-07T17:29:19 PID [ 5008 ] Error Operation=ApiControllerActionInvoker.InvokeActionAsync , Exception=System.Data.Entity.Validation.DbEntityValidationException : Validation failed for one or more entities . See 'EntityValidationErrors ' property for more details . at System.Data.Entity.Internal.InternalContext.SaveChanges ( ) at System.Data.Entity.Internal.LazyInternalContext.SaveChanges ( ) at System.Data.Entity.DbContext.SaveChanges ( ) at BCMobileAppService.Controllers.Test2Controller.Post ( UserDTO username ) in C : \Users\johann\Desktop\BCMobileApp_Runtime\BCMobileAppService\Controllers\TestController.cs : line 78 at lambda_method ( Closure , Object , Object [ ] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor. < > c__DisplayClass10. < GetExecutor > b__9 ( Object instance , Object [ ] methodParameters ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute ( Object instance , Object [ ] arguments ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync ( HttpControllerContext controllerContext , IDictionary 2 arguments , CancellationToken cancellationToken ) -- - 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.Web.Http.Tracing.ITraceWriterExtensions. < TraceBeginEndAsyncCore > d__18 1.MoveNext ( ) -- - 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.Web.Http.Controllers.ApiControllerActionInvoker. < InvokeActionAsyncCore > d__0.MoveNext ( ) -- - 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.Web.Http.Tracing.ITraceWriterExtensions. < TraceBeginEndAsyncCore > d__18 1.MoveNext ( ) 2016-04-07T17:29:19 PID [ 5008 ] Error Operation=Test2Controller.ExecuteAsync , Exception=System.Data.Entity.Validation.DbEntityValidationException : Validation failed for one or more entities . See 'EntityValidationErrors ' property for more details . at System.Data.Entity.Internal.InternalContext.SaveChanges ( ) at System.Data.Entity.Internal.LazyInternalContext.SaveChanges ( ) at System.Data.Entity.DbContext.SaveChanges ( ) at BCMobileAppService.Controllers.Test2Controller.Post ( UserDTO username ) in C : \Users\johann\Desktop\BCMobileApp_Runtime\BCMobileAppService\Controllers\TestController.cs : line 78 at lambda_method ( Closure , Object , Object [ ] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor. < > c__DisplayClass10. < GetExecutor > b__9 ( Object instance , Object [ ] methodParameters ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute ( Object instance , Object [ ] arguments ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync ( HttpControllerContext controllerContext , IDictionary 2 arguments , CancellationToken cancellationToken ) -- - 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.Web.Http.Tracing.ITraceWriterExtensions. < TraceBeginEndAsyncCore > d__18 1.MoveNext ( ) -- - 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.Web.Http.Controllers.ApiControllerActionInvoker. < InvokeActionAsyncCore > d__0.MoveNext ( ) -- - 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.Web.Http.Tracing.ITraceWriterExtensions. < TraceBeginEndAsyncCore > d__18 1.MoveNext ( ) -- - 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.Web.Http.Filters.ActionFilterAttribute. < CallOnActionExecutedAsync > d__5.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Web.Http.Filters.ActionFilterAttribute. < CallOnActionExecutedAsync > d__5.MoveNext ( ) -- - 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.Web.Http.Filters.ActionFilterAttribute. < ExecuteActionFilterAsyncCore > d__0.MoveNext ( ) -- - 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.Web.Http.Controllers.ActionFilterResult. < ExecuteAsync > d__2.MoveNext ( ) -- - 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.Web.Http.Tracing.Tracers.HttpControllerTracer. < ExecuteAsyncCore > d__5.MoveNext ( ) -- - 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.Web.Http.Tracing.ITraceWriterExtensions. < TraceBeginEndAsyncCore > d__18 1.MoveNext ( ) catch ( DbEntityValidationException dbEx ) { foreach ( var validationErrors in dbEx.EntityValidationErrors ) { foreach ( var validationError in validationErrors.ValidationErrors ) { Trace.TraceInformation ( `` Property : { 0 } Error : { 1 } '' , validationError.PropertyName , validationError.ErrorMessage ) ; } } } public abstract class EntityData : ITableData { protected EntityData ( ) ; [ Index ( IsClustered = true ) ] [ TableColumn ( TableColumnType.CreatedAt ) ] public DateTimeOffset ? CreatedAt { get ; set ; } [ TableColumn ( TableColumnType.Deleted ) ] public bool Deleted { get ; set ; } [ TableColumn ( TableColumnType.Id ) ] public string Id { get ; set ; } [ TableColumn ( TableColumnType.UpdatedAt ) ] public DateTimeOffset ? UpdatedAt { get ; set ; } [ TableColumn ( TableColumnType.Version ) ] public byte [ ] Version { get ; set ; } }
|
Db context on azure app service ( mobile ) fails
|
C_sharp : Just Asking : Why 'withOffset ' variable is inferred as dynamic as Parse method returns Struct ? and after explicit cast its back to Struct ? since the return type of DateTimeOffset.Parse is DateTimeOffset , and the compiler must know that . keeping that in mind , what ever method it invoke at runtime , the return is always DateTimeOffset.The specs tells Since your method takes dynamic as an argument , it qualifies for `` dynamic binding '' bit fishy.What 's point in having such specification ? OR in which circumstance DateTimeOffset.Parse will not return STRUCT ( forgetting DLR for moment.. ) ? Compiler need to be clever , if all methods/overload in the class have same return type to gain performance benefit in long run . <code> dynamic str = `` 22/11/2013 10:31:45 +00:01 '' ; var withOffset = DateTimeOffset.Parse ( str ) ; dynamic str = `` 22/11/2013 10:31:45 +00:01 '' ; var withOffset = DateTimeOffset.Parse ( ( string ) str ) ;
|
C # DLR , Datatype inference with Dynamic keyword
|
C_sharp : I am trying to query data from Azure WadPerformanceCountersTable.I am trying to get the last 5 minutes of data.The problem is that I only get data from instances nr . 4,5 and 6 , but not from 0,1,2 and 3.The script I am using to pull de data is this : My diagnostics.wadcfg file is this : EDIT : Also , I have this code deployed on a test environment in azure , and it works just fine.EDIT 2 : Update to include Service Definitions XML : After I have read user @ Igorek 's answer I have included my ServiceDefinition.csdef configuration XML . I am still unaware of how I must configure the LocalResources > LocalStorage part of the configuration . The configuration must be set for `` MyApp.Website '' .EDIT 3 : I have made these changes to the test azure account.I have set this in ServiceDefinitions.csdefAnd I have lowered the OverallQuota and BufferQuota in diagnostics.wadcfgIn the end , in the WAD-control-container I have this configuration per instance : http : //pastebin.com/aUywLUfEI will have to put this on the live account to see the results.FINAL EDIT : Apparently the overall Quota was the problem , even though I can not guarantee it.In the end , after a new publish I noticed this : a role instance had the configuration XML in wad-control-container with an overall quota of 1024MB and BufferQuotaInMB of 1024MB -- > this was correct , another 2 role instances had an overall quota of 4080MB and BufferQuotaInMB of 500MB -- > this was incorrect , they were not writing in WADPerformanceCounters table.both of the XML configuration files ( that were in wad-control-container ) belonging to each role instance were deleted prior to the new publish.the configuration file diagnostics.wadcfg was configured correctly : 1024MB everywereSo I think there is a problem with their publisher.Two solutions were tried : I deleted 1 incorrect XML from 'wad-control-container ' and rebooted the machine . The XML was rewritten and the role instance started to write in the WADPerfCountTable.I used the script below on the other incorrect instance and the incorrect role instance started to write in the WADPerfCountTable.Also , I keep receiving this error from time to time The configuration file is missing a diagnostic connection string for one or more roles.In the end I will choose the current response as the answer , because I have found the problem . Unfortunately , I have not found the cause of the problem . At every publish I risk getting a changed confguration XML . <code> Microsoft.WindowsAzure.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.CloudStorageAccount.Parse ( AppDefs.CloudStorageAccountConnectionString ) ; CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient ( ) ; TableServiceContext serviceContext = cloudTableClient.GetDataServiceContext ( ) ; IQueryable < PerformanceCountersEntity > traceLogsTable = serviceContext.CreateQuery < PerformanceCountersEntity > ( `` WADPerformanceCountersTable '' ) ; var selection = from row in traceLogsTable where row.PartitionKey.CompareTo ( `` 0 '' + DateTime.UtcNow.AddMinutes ( -timespanInMinutes ) .Ticks ) > = 0 & & row.DeploymentId == deploymentId & & row.CounterName == @ '' \Processor ( _Total ) \ % Processor Time '' select row ; CloudTableQuery < PerformanceCountersEntity > query = selection.AsTableServiceQuery < PerformanceCountersEntity > ( ) ; IEnumerable < PerformanceCountersEntity > result = query.Execute ( ) ; return result ; < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < DiagnosticMonitorConfiguration xmlns= '' http : //schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration '' configurationChangePollInterval= '' PT1M '' overallQuotaInMB= '' 4096 '' > < PerformanceCounters bufferQuotaInMB= '' 0 '' scheduledTransferPeriod= '' PT5M '' > < PerformanceCounterConfiguration counterSpecifier= '' \Memory\Available Bytes '' sampleRate= '' PT60S '' / > < PerformanceCounterConfiguration counterSpecifier= '' \Processor ( _Total ) \ % Processor Time '' sampleRate= '' PT60S '' / > < /PerformanceCounters > < /DiagnosticMonitorConfiguration > < ServiceDefinition name= '' MyApp.Azure '' xmlns= '' http : //schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition '' schemaVersion= '' 2012-05.1.7 '' > < WebRole name= '' MyApp.Website '' vmsize= '' ExtraSmall '' > < Sites > < Site name= '' Web '' > < Bindings > < Binding name= '' Endpoint1 '' endpointName= '' Endpoint1 '' / > < /Bindings > < /Site > < /Sites > < Endpoints > < InputEndpoint name= '' Endpoint1 '' protocol= '' http '' port= '' 80 '' / > < /Endpoints > < Imports > < Import moduleName= '' Diagnostics '' / > < /Imports > < /WebRole > < WorkerRole name= '' MyApp.Cache '' vmsize= '' ExtraSmall '' > < Imports > < Import moduleName= '' Diagnostics '' / > < Import moduleName= '' Caching '' / > < /Imports > < LocalResources > < LocalStorage name= '' Microsoft.WindowsAzure.Plugins.Caching.FileStore '' sizeInMB= '' 1000 '' cleanOnRoleRecycle= '' false '' / > < /LocalResources > < /WorkerRole > < /ServiceDefinition > < LocalResources > < LocalStorage name= '' DiagnosticStore '' sizeInMB= '' 4096 '' cleanOnRoleRecycle= '' false '' / > < /LocalResources > var storageAccount = CloudStorageAccount.Parse ( AppDefs.CloudStorageAccountConnectionString ) ; DeploymentDiagnosticManager diagManager = new DeploymentDiagnosticManager ( storageAccount , deploymentId ) ; IEnumerable < RoleInstanceDiagnosticManager > instanceManagers = diagManager.GetRoleInstanceDiagnosticManagersForRole ( roleName ) ; foreach ( var roleInstance in instanceManagers ) { DiagnosticMonitorConfiguration currentConfiguration = roleInstance.GetCurrentConfiguration ( ) ; TimeSpan configurationChangePollInterval = TimeSpan.FromSeconds ( 60 ) ; if ( ! IsCurrentConfigurationCorrect ( currentConfiguration , overallQuotaInMb , TimeSpan.FromMinutes ( 1 ) , TimeSpan.FromMinutes ( 1 ) ) ) { // Add a performance counter for processor time . PerformanceCounterConfiguration pccCPU = new PerformanceCounterConfiguration ( ) ; pccCPU.CounterSpecifier = @ '' \Processor ( _Total ) \ % Processor Time '' ; pccCPU.SampleRate = TimeSpan.FromSeconds ( 60 ) ; // Add a performance counter for available memory . PerformanceCounterConfiguration pccMemory = new PerformanceCounterConfiguration ( ) ; pccMemory.CounterSpecifier = @ '' \Memory\Available Bytes '' ; pccMemory.SampleRate = TimeSpan.FromSeconds ( 60 ) ; currentConfiguration.ConfigurationChangePollInterval = TimeSpan.FromSeconds ( 60 ) ; currentConfiguration.OverallQuotaInMB = overallQuotaInMb ; currentConfiguration.PerformanceCounters.BufferQuotaInMB = overallQuotaInMb ; currentConfiguration.PerformanceCounters.DataSources.Add ( pccCPU ) ; currentConfiguration.PerformanceCounters.DataSources.Add ( pccMemory ) ; roleInstance.SetCurrentConfiguration ( currentConfiguration ) ; } }
|
Azure instances from 0 to 3 not writing diagnostics data in WadPerformanceCountersTable
|
C_sharp : Basically I just want to check if one time period overlaps with another.Null end date means till infinity . Can anyone shorten this for me as its quite hard to read at times . Cheers <code> public class TimePeriod { public DateTime StartDate { get ; set ; } public DateTime ? EndDate { get ; set ; } public bool Overlaps ( TimePeriod other ) { // Means it overlaps if ( other.StartDate == this.StartDate || other.EndDate == this.StartDate || other.StartDate == this.EndDate || other.EndDate == this.EndDate ) return true ; if ( this.StartDate > other.StartDate ) { // Negative if ( this.EndDate.HasValue ) { if ( this.EndDate.Value < other.StartDate ) return true ; if ( other.EndDate.HasValue & & this.EndDate.Value < other.EndDate.Value ) return true ; } // Negative if ( other.EndDate.HasValue ) { if ( other.EndDate.Value > this.StartDate ) return true ; if ( this.EndDate.HasValue & & other.EndDate.Value > this.EndDate.Value ) return true ; } else return true ; } else if ( this.StartDate < other.StartDate ) { // Negative if ( this.EndDate.HasValue ) { if ( this.EndDate.Value > other.StartDate ) return true ; if ( other.EndDate.HasValue & & this.EndDate.Value > other.EndDate.Value ) return true ; } else return true ; // Negative if ( other.EndDate.HasValue ) { if ( other.EndDate.Value < this.StartDate ) return true ; if ( this.EndDate.HasValue & & other.EndDate.Value < this.EndDate.Value ) return true ; } } return false ; } }
|
Can anyone simplify this Algorithm for me ?
|
C_sharp : Ok , So I have the following situation . I originally had some code like this : Now , I decided to refactor that code so the classes ' dependencies are injected , instead : My question is what to do about Board Size ? I mean , in the first case , I just passed the class the desired board size , and it would do everything to create the other kinds of boards with the correct size . In the dependency injection case , that might not be more the case . What do you guys do in this situation ? Do you put any kind of checking on the MainBoard 's constructor so to make sure that the correct sizes are being passed in ? Do you just assume the class ' client will be responsible enough to pass the 3 kinds of boards with the same size , so there is no trouble ? EditWhy am I doing this ? Because I need to Unit-Test MainBoard . I need to be able to set the 3 sub-boards in certain states so I can test that my MainBoard is doing what I expect it to.Thanks <code> public class MainBoard { private BoardType1 bt1 ; private BoardType2 bt2 ; private BoardType3 bt3 ; ... private readonly Size boardSize ; public MainBoard ( Size boardSize ) { this.boardSize = boardSize ; bt1 = new BoardType1 ( boardSize ) ; bt2 = new BoardType2 ( boardSize ) ; bt3 = new BoardType3 ( boardSize ) ; } } public class MainBoard { private IBoardType1 bt1 ; private IBoardType2 bt2 ; private IBoardType3 bt3 ; ... private Size boardSize ; public MainBoard ( Size boardSize , IBoardType1 bt1 , IBoardType2 bt2 , IBoardType3 bt3 ) { this.bt1 = bt1 ; this.bt2 = bt2 ; this.bt3 = bt3 ; } }
|
How to convert this code so it now uses the Dependency Injection pattern ?
|
C_sharp : I have a python script : It 's so easy to achieve multiple return values in python.And now I want to achieve the same result in C # . I tried several ways , like return int [ ] or KeyValuePair . But both ways looked not elegant . I wonder a exciting solution . thanks a lot . <code> def f ( ) : a = None b = None return ( a , b ) a , b = f ( )
|
How to achieve multiple return values in C # like python style
|
C_sharp : I 've created an website available in three languages : english , portuguese and spanish.It 's everything working fine except for one thing : it was not updating a BoundField when an accentuated word is loaded into it.Below is the field which does n't update in the gridview at MEMGridView.ascx : At App_LocalResources are three files with this values : MEMGridView.ascx.resx ( english is default ) -BoundFieldResource9.HeaderText - `` Fill Rate '' MEMGridView.ascx.pt-BR.resx - BoundFieldResource9.HeaderText - '' Ocupação '' MEMGridView.ascx.es.resx - BoundFieldResource9.HeaderText - '' Ocupación '' When the page loads for the first time it exhibits `` Fill Rate '' . Then I change the language to spanish and it exhibits `` Ocupación '' . If I return to load the page in english it updates all fields , except for the accentuated ones . So it continues to show `` Ocupación '' instead of `` Fill Rate '' .I have no clues of what can be happening. -- Update - Additional Info -- MEMGridView is a UserControl inside of DashBoard.aspx . Everytime someone changes the language value in ddlLanguage ( dropdownlist ) or clicks on Update button a postback is generated.This is the MEMGridView event suposed to update the fields ( actually , it updates all fields except the accentuated ones ) . <code> < asp : BoundField DataField= '' Ocupacao '' HeaderText= '' Ocupação '' SortExpression= '' Ocupação '' meta : resourcekey= '' BoundFieldResource9 '' > < ItemStyle HorizontalAlign= '' Center '' / > < /asp : BoundField > public partial class MEMGridView : UserControl { ... protected override void FrameworkInitialize ( ) { if ( ! string.IsNullOrEmpty ( Request [ `` ddlLanguage '' ] ) ) { string str = Request [ `` ddlLanguage '' ] ; //Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture ( str ) ; Thread.CurrentThread.CurrentUICulture = new CultureInfo ( str ) ; } else { string preferredLanguage ; if ( Request.QueryString [ `` Language '' ] ! = null ) preferredLanguage = Request.QueryString [ `` Language '' ] ; else preferredLanguage = Request.UserLanguages [ 0 ] ; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture ( preferredLanguage ) ; Thread.CurrentThread.CurrentUICulture = new CultureInfo ( preferredLanguage ) ; } base.FrameworkInitialize ( ) ; }
|
Globalization issue on asp.net : it 's not updating accentuated words
|
C_sharp : I 've been looking for a way to extract slices from a 2D matrix without having to actually reallocate-copy the contents , and I 've checked this method with this simple Unit tests and apparently it works : This does n't seem right to me though . I mean , I 'd like to understand what 's exactly happening behind the scenes here , as that ref m [ x , y ] part does n't convince me.How is the runtime getting the actual reference to the value at that location inside the matrix , since the this [ int x , int y ] method in the 2D array is just returning a value and not a reference ? Should n't the ref modifier only get a reference to the local copy of that float value returned to the method , and not a reference to the actual value stored within the matrix ? I mean , otherwise having methods/parameters with ref returns would be pointless , and that 's not the case.I took a peek into the IL for the test method and noticed this : Now , I 'm not 100 % sure since I 'm not so great at reading IL , but is n't the ref m [ x , y ] call being translated to a call to that other Address method , which I suppose just returns a ref value on its own ? If that 's the case , is there a way to directly use that method from C # code ? And is there a way to discover methods like this one , when available ? I mean , I just noticed that by looking at the IL and I had no idea it existed or why was the code working before , at this point I wonder how much great stuff is there in the default libs without a hint it 's there for the average dev.Thanks ! <code> public static Span < float > Slice ( [ NotNull ] this float [ , ] m , int row ) { if ( row < 0 || row > m.GetLength ( 0 ) - 1 ) throw new ArgumentOutOfRangeException ( nameof ( row ) , `` The row index is n't valid '' ) ; return Span < float > .DangerousCreate ( m , ref m [ row , 0 ] , m.GetLength ( 1 ) ) ; } [ TestMethod ] public void Foo ( ) { float [ , ] m = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 9.5f , 10 , 11 } , { 12 , 13 , 14.3f , 15 } } ; Span < float > s = m.Slice ( 2 ) ; var copy = s.ToArray ( ) ; var check = new [ ] { 9 , 9.5f , 10 , 11 } ; Assert.IsTrue ( copy.Select ( ( n , i ) = > Math.Abs ( n - check [ i ] ) < 1e-6f ) .All ( b = > b ) ) ; }
|
Slicing a Span < T > row from a 2D matrix - not sure why this works
|
C_sharp : I got an old solution and I am trying to build a newer one using the current projects in it . One of the projects is SQLUtils that contains only .cs files and the Target framework of it is .NET Framework 2.0.In the old solution it is a regular C # Class Library project but when I add it to my new solution it becomes .sqlproj and I get errors while building it.I tried to edit the new .sln like the old one , but that did n't make any difference.I looked at https : //social.msdn.microsoft.com/Forums/sqlserver/en-US/38113dcd-caaa-4704-ad69-d7ce774d2916/sql-server-data-tools-september-edition-migration-issues-vs2010 ? forum=ssdtand at https : //social.msdn.microsoft.com/Forums/sqlserver/en-US/0f537da4-9d61-45bf-8778-102eae9d4b83/csproj-to-sqlproj-migration-in-vs2012-with-ssdt ? forum=ssdtbut they did n't exactly solved it , you know MSDN ... Additional information : solution file : .csproj : Each time I add the project a file named `` UpgradeLog.htm '' is created.This is how it looks like : <code> Microsoft Visual Studio Solution File , Format Version 12.00 # Visual Studio 14VisualStudioVersion = 14.0.25420.1MinimumVisualStudioVersion = 10.0.40219.1Project ( `` { E24C65DC-7377-472B-9ABA-BC803B73C61A } '' ) = `` BO 25.7.17 '' , `` BO 25.7.17 '' , `` { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } '' ProjectSection ( WebsiteProperties ) = preProject SccProjectName = `` SAK '' SccAuxPath = `` SAK '' SccLocalPath = `` SAK '' SccProvider = `` SAK '' TargetFrameworkMoniker = `` .NETFramework , Version % 3Dv2.0 '' ProjectReferences = `` { f977dcec-ed6c-485f-ab12-1fe31b7cbc5c } |Logic.dll ; '' Debug.AspNetCompiler.VirtualPath = `` /localhost_61694 '' Debug.AspNetCompiler.PhysicalPath = `` ..\..\..\..\..\..\TFS\StyleRiver\BO\BO 25.7.17\ '' Debug.AspNetCompiler.TargetPath = `` PrecompiledWeb\localhost_61694\ '' Debug.AspNetCompiler.Updateable = `` true '' Debug.AspNetCompiler.ForceOverwrite = `` true '' Debug.AspNetCompiler.FixedNames = `` false '' Debug.AspNetCompiler.Debug = `` True '' Release.AspNetCompiler.VirtualPath = `` /localhost_61694 '' Release.AspNetCompiler.PhysicalPath = `` ..\..\..\..\..\..\TFS\StyleRiver\BO\BO 25.7.17\ '' Release.AspNetCompiler.TargetPath = `` PrecompiledWeb\localhost_61694\ '' Release.AspNetCompiler.Updateable = `` true '' Release.AspNetCompiler.ForceOverwrite = `` true '' Release.AspNetCompiler.FixedNames = `` false '' Release.AspNetCompiler.Debug = `` False '' VWDPort = `` 61694 '' SlnRelativePath = `` ..\..\..\..\..\..\TFS\StyleRiver\BO\BO 25.7.17\ '' EndProjectSectionEndProjectProject ( `` { FAE04EC0-301F-11D3-BF4B-00C04F79EFBC } '' ) = `` Logic '' , `` Logic\Logic.csproj '' , `` { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } '' EndProjectGlobal GlobalSection ( SolutionConfigurationPlatforms ) = preSolution Debug|Any CPU = Debug|Any CPU Debug|Mixed Platforms = Debug|Mixed Platforms Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|Mixed Platforms = Release|Mixed Platforms Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection ( ProjectConfigurationPlatforms ) = postSolution { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } .Debug|Any CPU.ActiveCfg = Debug|Any CPU { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } .Debug|Any CPU.Build.0 = Debug|Any CPU { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } .Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } .Debug|x64.ActiveCfg = Debug|Any CPU { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } .Debug|x64.Build.0 = Debug|Any CPU { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } .Debug|x86.ActiveCfg = Debug|Any CPU { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } .Release|Any CPU.ActiveCfg = Debug|Any CPU { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } .Release|Any CPU.Build.0 = Debug|Any CPU { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } .Release|Mixed Platforms.ActiveCfg = Debug|Any CPU { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } .Release|x64.ActiveCfg = Debug|Any CPU { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } .Release|x64.Build.0 = Debug|Any CPU { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } .Release|x86.ActiveCfg = Debug|Any CPU { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } .Debug|Any CPU.ActiveCfg = Debug|Any CPU { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } .Debug|Any CPU.Build.0 = Debug|Any CPU { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } .Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } .Debug|x64.ActiveCfg = Debug|x64 { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } .Debug|x64.Build.0 = Debug|x64 { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } .Debug|x86.ActiveCfg = Debug|Any CPU { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } .Release|Any CPU.ActiveCfg = Release|Any CPU { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } .Release|Any CPU.Build.0 = Release|Any CPU { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } .Release|Mixed Platforms.ActiveCfg = Release|Any CPU { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } .Release|x64.ActiveCfg = Release|x64 { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } .Release|x64.Build.0 = Release|x64 { F977DCEC-ED6C-485F-AB12-1FE31B7CBC5C } .Release|x86.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection ( SolutionProperties ) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection ( TeamFoundationVersionControl ) = preSolution SccNumberOfProjects = 2 SccEnterpriseProvider = { 4CA58AB2-18FA-4F8D-95D4-32DDF27D184C } SccTeamFoundationServer = http : //gpnt049:8080/tfs/zap % 20market % 20- % 20zap % 20travel SccWebProject0 = true SccProjectUniqueName0 = BO\u002025.7.17 SccProjectName0 = BO\u002025.7.17 SccAuxPath0 = http : //gpnt049:8080/tfs/zap % 20market % 20- % 20zap % 20travel SccLocalPath0 = BO\u002025.7.17 SccProvider0 = { 4CA58AB2-18FA-4F8D-95D4-32DDF27D184C } SccProjectEnlistmentChoice0 = 2 SccProjectUniqueName1 = Logic\\Logic.csproj SccProjectName1 = Logic SccAuxPath1 = http : //gpnt049:8080/tfs/zap % 20market % 20- % 20zap % 20travel SccLocalPath1 = Logic SccProvider1 = { 4CA58AB2-18FA-4F8D-95D4-32DDF27D184C } EndGlobalSectionEndGlobal < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Project DefaultTargets= '' Build '' xmlns= '' http : //schemas.microsoft.com/developer/msbuild/2003 '' ToolsVersion= '' 4.0 '' > < PropertyGroup > < Configuration Condition= '' ' $ ( Configuration ) ' == `` `` > Debug < /Configuration > < Platform Condition= '' ' $ ( Platform ) ' == `` `` > AnyCPU < /Platform > < ProjectTypeGuids > { c252feb5-a946-4202-b1d4-9916a0590387 } ; { FAE04EC0-301F-11D3-BF4B-00C04F79EFBC } < /ProjectTypeGuids > < ProductVersion > 8.0.50727 < /ProductVersion > < SchemaVersion > 2.0 < /SchemaVersion > < ProjectGuid > { 80A3D07F-863D-4E34-A5D4-8587A201629E } < /ProjectGuid > < OutputType > Library < /OutputType > < NoStandardLibraries > false < /NoStandardLibraries > < AssemblyName > SQLUtils < /AssemblyName > < RootNamespace > SQLUtils < /RootNamespace > < TargetFrameworkVersion > v2.0 < /TargetFrameworkVersion > < FileUpgradeFlags > 40 < /FileUpgradeFlags > < OldToolsVersion > 4.0 < /OldToolsVersion > < UpgradeBackupLocation > C : \TFS\StyleRiver\StyleRiver 24.7.17\Backup1\ < /UpgradeBackupLocation > < ConnectionString / > < PublishUrl > publish\ < /PublishUrl > < Install > true < /Install > < InstallFrom > Disk < /InstallFrom > < UpdateEnabled > false < /UpdateEnabled > < UpdateMode > Foreground < /UpdateMode > < UpdateInterval > 7 < /UpdateInterval > < UpdateIntervalUnits > Days < /UpdateIntervalUnits > < UpdatePeriodically > false < /UpdatePeriodically > < UpdateRequired > false < /UpdateRequired > < MapFileExtensions > true < /MapFileExtensions > < ApplicationRevision > 0 < /ApplicationRevision > < ApplicationVersion > 1.0.0. % 2a < /ApplicationVersion > < IsWebBootstrapper > false < /IsWebBootstrapper > < UseApplicationTrust > false < /UseApplicationTrust > < BootstrapperEnabled > true < /BootstrapperEnabled > < SccProjectName > < /SccProjectName > < SccLocalPath > < /SccLocalPath > < SccAuxPath > < /SccAuxPath > < SccProvider > < /SccProvider > < TargetFrameworkProfile / > < /PropertyGroup > < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Debug|AnyCPU ' `` > < DebugSymbols > true < /DebugSymbols > < DebugType > full < /DebugType > < Optimize > false < /Optimize > < OutputPath > bin\Debug\ < /OutputPath > < EnableUnmanagedDebugging > false < /EnableUnmanagedDebugging > < DefineConstants > DEBUG ; TRACE < /DefineConstants > < WarningLevel > 4 < /WarningLevel > < DeployCode > true < /DeployCode > < /PropertyGroup > < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Release|AnyCPU ' `` > < DebugSymbols > false < /DebugSymbols > < Optimize > true < /Optimize > < OutputPath > bin\Release\ < /OutputPath > < EnableUnmanagedDebugging > false < /EnableUnmanagedDebugging > < DefineConstants > TRACE < /DefineConstants > < WarningLevel > 4 < /WarningLevel > < /PropertyGroup > < Import Project= '' $ ( MSBuildBinPath ) \Microsoft.CSharp.targets '' / > < Import Project= '' $ ( MSBuildBinPath ) \SqlServer.targets '' / > < ItemGroup > < Reference Include= '' System '' / > < Reference Include= '' System.Data '' / > < Reference Include= '' System.XML '' / > < /ItemGroup > < ItemGroup > < Compile Include= '' Concat.cs '' / > < Compile Include= '' ConcatDistinct.cs '' / > < Compile Include= '' Encryption.cs '' / > < Compile Include= '' Properties\AssemblyInfo.cs '' / > < Compile Include= '' SqlRegEx.cs '' / > < Compile Include= '' ToUrlCompatible.cs '' / > < /ItemGroup > < ! -- To modify your build process , add your task inside one of the targets below and uncomment it . Other similar extension points exist , see Microsoft.Common.targets . < Target Name= '' BeforeBuild '' > < /Target > < Target Name= '' AfterBuild '' > < /Target > -- > < ItemGroup > < None Include= '' Test Scripts\Test1.sql '' / > < /ItemGroup > < ItemGroup > < BootstrapperPackage Include= '' Microsoft.Net.Client.3.5 '' > < Visible > False < /Visible > < ProductName > .NET Framework 3.5 SP1 Client Profile < /ProductName > < Install > false < /Install > < /BootstrapperPackage > < BootstrapperPackage Include= '' Microsoft.Net.Framework.3.5.SP1 '' > < Visible > False < /Visible > < ProductName > .NET Framework 3.5 SP1 < /ProductName > < Install > true < /Install > < /BootstrapperPackage > < BootstrapperPackage Include= '' Microsoft.Windows.Installer.3.1 '' > < Visible > False < /Visible > < ProductName > Windows Installer 3.1 < /ProductName > < Install > true < /Install > < /BootstrapperPackage > < /ItemGroup > < /Project >
|
How to stop VS2015 from converting my.csproj into .sqlproj ?
|
C_sharp : The following simple code will yield an `` invariant unproven '' warning by the static checker of Code Contracts , although there is no way _foo can be null . The warning is for the return statement inside UncalledMethod.Apart from the fact , that the warning is simply invalid , it only occures in certain specific circumstances . Changing any of the following will make the warning go away : Inline GetNode so the return statement looks like this : Remove any of the parameters s1 to s5 from the constructor of Node.Change the type of any of the parameters s1 to s5 from the constructor of Node to object.Use a temporary variable for the result of GetNode : Changing the order of the parameters of the constructor of Node.Checking the option `` Show assumptions '' in the code contracts settings pane in the project settings.Am I missing something obvious here or is this simply a bug in the static checker ? My settings : My output : <code> public class Node { public Node ( string s1 , string s2 , string s3 , string s4 , object o , string s5 ) { } } public class Bar { private readonly string _foo ; public Bar ( ) { _foo = `` foo '' ; } private object UncalledMethod ( ) { return new Node ( string.Empty , string.Empty , string.Empty , string.Empty , GetNode ( ) , string.Empty ) ; } private Node GetNode ( ) { return null ; } public string Foo { get { Contract.Ensures ( Contract.Result < string > ( ) ! = null ) ; return _foo ; } } [ ContractInvariantMethod ] private void Invariants ( ) { Contract.Invariant ( _foo ! = null ) ; } } return new Node ( string.Empty , string.Empty , string.Empty , string.Empty , null , string.Empty ) ; var node = GetNode ( ) ; return new Node ( string.Empty , string.Empty , string.Empty , string.Empty , node , string.Empty ) ; C : \ { path } \Program.cs ( 20,9 ) : message : CodeContracts : Suggested ensures : Contract.Ensures ( this._foo ! = null ) ; C : \ { path } \Program.cs ( 41,17 ) : message : CodeContracts : Suggested ensures : Contract.Ensures ( Contract.Result < System.String > ( ) == this._foo ) ; C : \ { path } \Program.cs ( 33,13 ) : message : CodeContracts : Suggested ensures : Contract.Ensures ( Contract.Result < ConsoleApplication3.Program+Node > ( ) == null ) ; C : \ { path } \Program.cs ( 27,13 ) : message : CodeContracts : Suggested ensures : Contract.Ensures ( Contract.Result < System.Object > ( ) ! = null ) ; C : \ { path } \Program.cs ( 55,13 ) : message : CodeContracts : Suggested ensures : Contract.Ensures ( Contract.ForAll ( 0 , args.Length , __k__ = > args [ __k__ ] ! = 0 ) ) ; CodeContracts : ConsoleApplication3 : Validated : 92,3 % CodeContracts : ConsoleApplication3 : Contract density : 1,81CodeContracts : ConsoleApplication3 : Total methods analyzed 8CodeContracts : ConsoleApplication3 : Methods with 0 warnings 7CodeContracts : ConsoleApplication3 : Total method analysis read from the cache 8CodeContracts : ConsoleApplication3 : Total time 2,522sec . 315ms/methodCodeContracts : ConsoleApplication3 : Retained 0 preconditions after filteringCodeContracts : ConsoleApplication3 : Inferred 0 object invariantsCodeContracts : ConsoleApplication3 : Retained 0 object invariants after filteringCodeContracts : ConsoleApplication3 : Detected 0 code fixesCodeContracts : ConsoleApplication3 : Proof obligations with a code fix : 0C : \ { path } \Program.cs ( 27,13 ) : warning : CodeContracts : invariant unproven : _foo ! = nullC : \ { path } \Program.cs ( 49,13 ) : warning : + location related to previous warningC : \windows\system32\ConsoleApplication3.exe ( 1,1 ) : message : CodeContracts : Checked 13 assertions : 12 correct 1 unknownCodeContracts : ConsoleApplication3 : CodeContracts : ConsoleApplication3 : Background contract analysis done .
|
`` Invariant unproven '' when using method that creates a specific new object in its return statement
|
C_sharp : I have a themed page whereby the theme is chosen inside a http module.Now when I request the elmah.axd the following exception is thrown : Using themed css files requires a header control on the page . ( e.g . ) .When I disable the http theme module everything is fine and elmah.axd page is shown . I think this is a small bug inside the ErrorLogPage . The ErrorLogPage should cope with the fact that a theme can be given to the page OR should ignore the given theme at all.For now I use the workaround : private const string ELMAH_ERROR_PAGE = `` Elmah.ErrorLogPage '' ; Do you have any better ideas or thoughts ? GrMartijnThe Netherlands <code> public void context_PreRequestHandlerExecute ( object sender , EventArgs e ) { Page p = HttpContext.Current.Handler as Page ; if ( p ! = null ) { //get theme string theme = GetTheme ( HttpContext.Current.Request.Url.Host ) ; Debug.WriteLine ( String.Format ( `` Loading theme { 0 } '' , theme ) ) ; //set theme of page p.Theme = theme ; } } if ( p.GetType ( ) .FullName ! = ELMAH_ERROR_PAGE ) { p.Theme = theme ; }
|
ELMAH within a themed page error
|
C_sharp : When I trying to define a class which inherits from System.ValueType or System.Enum class , I 'm getting an error : I understand that error but what I could n't understand is what makes ValueType class special ? I mean there is no keyword ( like sealed ) or attribute to specify that this class can not be inherited.ValueType has two attributes , Serializable and ComVisible but none of them is relevant with that case.The documentation says : Although ValueType is the implicit base class for value types , you can not create a class that inherits from ValueType directly . Instead , individual compilers provide a language keyword or construct ( such as struct in C # and Structure…End Structure in Visual Basic ) to support the creation of value types.But it does n't answer my question.So my question is how the compiler is informed in this case ? Does the compiler directly check whether the class is ValueType or Enum when I try to create a class that inherit from a class ? Edit : Also all structs implicitly inherit from ValueType , but Enum class Explicitly inherit from ValueType , so how is that working ? How the compiler figure out this situation , all of this are hard coded by compiler ? <code> Can not derive from special class System.ValueType
|
What makes ValueType class Special ?
|
C_sharp : Im having some trouble getting this generic constraint to work.I have two interfaces below . I want to be able to constrain the ICommandHandlers TResult type to only use types that implement ICommandResult , but ICommandResult has its own constraints that need to be supplied . ICommandResult could potentially return a value or reference type from its Result property . Am I missing something obvious ? Thanks . <code> public interface ICommandResult < out TResult > { TResult Result { get ; } } public interface ICommandHandler < in TCommand , TResult > where TCommand : ICommand where TResult : ICommandResult < ? ? ? ? > { TResult Execute ( TCommand command ) ; }
|
Defining generic interface type constraint for value and reference types
|
C_sharp : Is it possible to write methods , which are only callable by unit tests ? My problem is that our framework contains a lot of Singleton classes , which makes unit testing quite hard some time . My idea was to create a simple interface like this : This method will be called for `` resetting '' singleton instances for better handling of unit tests . But this method should only be callable from unit test classes/instances . Is this possible ? <code> public interface IUnitTestClearable { void ClearForUnitTest ( ) ; }
|
Make method only callable from unit test
|
C_sharp : I 'm using an AutoFixture customization to test a repository which access to a SQL Compact DB.Would be very helpful to me to delete this database as soon as the test is completed . Because the db is created in the customization constructor I think that the best place to delete it is in the dispose method.The code which I 'm thinking is : Is possible to do something similar ? <code> internal class ProjectRepositoryCustomization : ICustomization { private readonly String _dbLocation ; public ProjectRepositoryCustomization ( ) { var tempDbLocation = Path.Combine ( Path.GetTempPath ( ) , `` TempDbToDelete '' ) ; if ( ! Directory.Exists ( tempDbLocation ) ) { Directory.CreateDirectory ( tempDbLocation ) ; } _dbLocation = Path.Combine ( tempDbLocation , Guid.NewGuid ( ) .ToString ( `` N '' ) + `` .sdf '' ) ; } public void Customize ( IFixture fixture ) { DataContextConfiguration.database = _dbLocation ; var dataContextFactory = new BaseDataContextFactory ( ) ; var projRepository = new ProjectRepository ( dataContextFactory ) ; fixture.Register ( ( ) = > projRepository ) ; } public void Dispose ( ) { if ( File.Exists ( _dbLocation ) ) { File.Delete ( _dbLocation ) ; } } }
|
Invoke Dispose method on AutoFixture customization
|
C_sharp : I am just starting to learn about the code contracts library that comes standard with VS2010 . One thing I am running into right away is what some of the contract clauses really mean.For example , how are these two statements different ? In other words , what does Contract.Exists do in practical purposes , either for a developer using my function , or for the static code analysis system ? <code> Contract.Requires ( ! mycollection.Any ( a = > a.ID == newID ) ) ; Contract.Requires ( ! Contract.Exists ( mycollection , a = > a.ID == newID ) ) ;
|
How does Contract.Exists add value ?
|
C_sharp : I have a list of Button , and I add an event handler for each button : Then I clear the list : <code> List < Button > buttons = new List < Button > ( ) ; for ( int i = 0 ; i < 10 ; i++ ) { Button btn = new Button ( ) ; btn.Click = new RoutedEventHandler ( OnbtnClick ) ; buttons.Add ( btn ) ; } /* Have I to remove all events here ( before cleaning the list ) , or not ? foreach ( Button btn in buttons ) btn.Click -= new RoutedEventHandler ( OnbtnClick ) ; */buttons.Clear ( ) ;
|
Should I remove an event handler ?
|
C_sharp : I know various questions have been asked that resembles this question , but as far as I can tell ( and test ) , none of the provided solutions seems to fit , so here goes.I am wondering if it is possible to flatten/denormalise an object hierarchy so that an instance with a list of nested properties is mapped to a list of some destination type using AutoMapper.I have a source class that looks something likeSources : Destination : So I want to map the two sources to a list of the denormalised destination DenormDistributionInfo.I.e : Is that possible/feasible using AutoMapper , or should I give in and denormalise it `` manually '' ? <code> public class DistributionInformation { public string Streetname ; public RouteInformation [ ] Routes ; } public class RouteInformation { public int RouteNumber ; public string RouteDescription ; } public class DenormDistributionInfo { public string Streetname ; public int RouteNumber ; public string RouteDescription ; } IEnumerable < DenormDistributionInfo > result = Mapper.Map ( distributionInformationInstance ) ;
|
Denormalise object hierarchy with automapper
|
C_sharp : I seem to be having a problem with retrieving XML values with C # , which I know it is due to my very limited knowledge of C # and .XML.I was given the following XML fileI am to process the XML file and make sure that each of the files in the exist in the folder ( that 's the easy part ) . It 's the processing of the XML file that I have having a hard time with . Here is what I have done thus far : My issue is that the String List is only ever populated with one value , `` EasySoap110.dll '' , and everything else is ignored . Can someone please help me , as I am at a loss . <code> < PowerBuilderRunTimes > < PowerBuilderRunTime > < Version > 12 < /Version > < Files > < File > EasySoap110.dll < /File > < File > exPat110.dll < /File > < File > pbacc110.dll < /File > < /File > < /PowerBuilderRunTime > < /PowerBuilderRunTimes > var runtimeXml = File.ReadAllText ( string.Format ( `` { 0 } \\ { 1 } '' , configPath , Resource.PBRuntimes ) ) ; var doc = XDocument.Parse ( runtimeXml ) ; var topElement = doc.Element ( `` PowerBuilderRunTimes '' ) ; var elements = topElement.Elements ( `` PowerBuilderRunTime '' ) ; foreach ( XElement section in elements ) { //pbVersion is grabbed earlier . It is the version of PowerBuilder if ( section.Element ( `` Version '' ) .Value.Equals ( string.Format ( `` { 0 } '' , pbVersion ) ) ) { var files = section.Elements ( `` Files '' ) ; var fileList = new List < string > ( ) ; foreach ( XElement area in files ) { fileList.Add ( area.Element ( `` File '' ) .Value ) ; } } }
|
Retrieving Data From XML File
|
C_sharp : I 've set up a little example where I loaded an assembly into a new AppDomain without any Permission . This works fine , the assembly ca n't access the file system and ca n't listen to sockets.But there is another thing i want to prevent : Thread creation . Why ? Cause theoreticly this assembly can create a thread which creates even more threads and flood my memory.I thought of the ( in my opinion ) best way : Limiting the memory of an AppDomain . Is this possible ? And if not , what can i do to avoid thread creation ? Used this code to create the threadAnd this code for the AppDomain ( Ok , i gave access to the file system in the folder where i want to load the assembly , this is just because StrongName fullTrustAssembly = typeof ( SecureInstance ) .Assembly.Evidence.GetHostEvidence < StrongName > ( ) ; do n't work for me either.Hope s/o can help . ( : <code> Thread t = new Thread ( this.DoWork ) ; t.Start ( ) ; PermissionSet set = new PermissionSet ( PermissionState.None ) ; set.AddPermission ( new SecurityPermission ( SecurityPermissionFlag.Execution ) ) ; set.AddPermission ( new FileIOPermission ( FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery , this.path ) ) ; AppDomainSetup info = new AppDomainSetup { ApplicationBase = this.path } ; this.domain = AppDomain.CreateDomain ( `` Sandbox '' , null , info , set , null ) ;
|
Prevent thread creation in AppDomain
|
C_sharp : The question is very straightforward , if I have a following class : and change it to : can it break a legay client dll ? <code> public class ExportReservationsToFtpRequestOld { public int A { get ; set ; } public long B { get ; set ; } } public class ExportReservationsToFtpRequestOld { public virtual int A { get ; set ; } public virtual long B { get ; set ; } }
|
Does adding virtual to a C # method may break legacy clients ?
|
C_sharp : In the following WPF code , once button is clicked , a new foreground thread is started . Then I close the WPF window , I could see that in Windows task manager , the process wo n't be terminated until Thread.Sleep ( 100000 ) ends . I could understand it because foreground threads could prevent process from terminating as MSDN doc says.But when I try almost the same thing in a console program , the process terminates immediately after I close the console window . Anybody could help to explain the differences ? <code> public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; } private void Button_Click ( object sender , RoutedEventArgs e ) { new Thread ( Go ) .Start ( ) ; } private void Go ( object obj ) { Thread.Sleep ( 100000 ) ; } } class Program { static void Main ( string [ ] args ) { new Thread ( Go ) .Start ( ) ; } private static void Go ( ) { Thread.Sleep ( 100000 ) ; } }
|
Foreground thread do n't stop a console process from terminating ?
|
C_sharp : I wonder if it is possible to get MatchCollection with all matches even if there 's intersection among them.This code returns 1 , but I want it to return 2 . How to achive it ? Thank you for your help . <code> string input = `` a a a '' ; Regex regex = new Regex ( `` a a '' ) ; MatchCollection matches = regex.Matches ( input ) ; Console.WriteLine ( matches.Count ) ;
|
regex matches with intersection in C #
|
C_sharp : I have two interfaces : An example of a closed implementation of IQueryHandler : I can register and resolve closed generic implementations of IQueryHandler < , > with this component registration : However what I would like to do is resolve an open generic implementation that is `` half closed '' ( ie specifies a generic TQuery type parameter ) : When I tried to resolve IQueryHandler < GetById < Event > , Event > I got this exception : An exception of type 'Castle.MicroKernel.Handlers.GenericHandlerTypeMismatchException ' occurred in Castle.Windsor.dll but was not handled in user codeAdditional information : Types Queries.GetById ' 1 [ [ Models.Event , Domain , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=null ] ] , Models.Event do n't satisfy generic constraints of implementation type Queries.GetByIdHandler ' 1 of component 'Queries.GetByIdHandler ' 1 ' . This is most likely a bug in your code.It looks like the type has successfully registered , and the constraints are satisfied as far as I can tell ( Event is a class and implements IIdentity ) . What am I missing here ? Am I trying to do something that Windsor ca n't cope with ? <code> public interface IQuery < TResult > { } public interface IQueryHandler < in TQuery , out TResult > where TQuery : IQuery < TResult > { TResult Handle ( TQuery q ) ; } public class EventBookingsHandler : IQueryHandler < EventBookings , IEnumerable < EventBooking > > { private readonly DbContext _context ; public EventBookingsHandler ( DbContext context ) { _context = context ; } public IEnumerable < EventBooking > Handle ( EventBookings q ) { return _context.Set < MemberEvent > ( ) .OfEvent ( q.EventId ) .AsEnumerable ( ) .Select ( EventBooking.FromMemberEvent ) ; } } Classes.FromAssemblyContaining ( typeof ( IQueryHandler < , > ) ) .BasedOn ( typeof ( IQueryHandler < , > ) ) .WithServiceAllInterfaces ( ) public class GetById < TEntity > : IQuery < TEntity > where TEntity : class , IIdentity { public int Id { get ; private set ; } public GetById ( int id ) { Id = id ; } } public class GetByIdHandler < TEntity > : IQueryHandler < GetById < TEntity > , TEntity > where TEntity : class , IIdentity { private readonly DbContext _context ; public GetByIdHandler ( DbContext context ) { _context = context ; } public TEntity Handle ( GetById < TEntity > q ) { return _context.Set < TEntity > ( ) .Find ( q.Id ) ; } }
|
Registering 'half-closed ' generic component
|
C_sharp : Currently trying to create a wrapper for an iOS framework on Unity.I made a .bundle , containing basic objective-c code : sample.h : sample.mm : The SDK is included in the bundle as a .framework ( references in `` Linked Frameworks and libraries '' ) . The bundle target is iOS.The bundle builds successfully.The bundle is placed in Unity under `` Assets/Plugins/iOS '' , marked as `` iOS '' and `` Add to Embedded Binaries '' Then , in Unity , there is a simple C # script calling SDK functions : sample.csWhen I test this code in the editor I get the following error : EntryPointNotFoundException : SampleFunctionIf I build the generated project on iOS , I get a similar issue : ld : symbol ( s ) not found for architecture arm64Note : I used the following tutorial as guideline : http : //blog.mousta.ch/post/140780061168Why is SampleFunction ( ) not found in __Internal ? <code> # import < Foundation/Foundation.h > extern `` C '' { void SampleFunction ( ) ; // this is going to call already bridged swift or objc code } # import `` Sample.h '' # import < SDK/SDKFunctions.h > void SampleFunction ( ) { // my sweet functions calls } public class BundleImportSample : MonoBehaviour { # if UNITY_IOS [ DllImport ( `` __Internal '' ) ] private static extern void SampleFunction ( ) ; # endif void Start ( ) { # if UNITY_IOS SampleFunction ( ) ; # endif } }
|
Unity iOS - Can not import functions from .Bundle
|
C_sharp : If I 'm explaining the following ForEach feature to someone , is it accurate to say that # 2 is the `` LINQ foreach approach '' or is it simply a `` List < T > extension method '' that is not officially associated with LINQ ? <code> var youngCustomers = from c in customers where c.Age < 30 select c ; //1 . traditional foreach approachforeach ( var c in youngCustomers ) { Console.WriteLine ( c.Display ( ) ) ; } //2 . LINQ foreach approach ? youngCustomers.ToList ( ) .ForEach ( c = > Console.WriteLine ( c.Display ( ) ) ) ;
|
What part of the C # language is .ForEach ( ) ?
|
C_sharp : Possible Duplicate : Collection < T > versus List < T > what should you use on your interfaces ? Consider this method—the returned variable myVar is a List < T > , but the return type of the method MyMethod ( ) is an IEnumerable < T > : Essentially , what I want to know is if returning myVar as a different type is OK.Specifically , with respect to my situation , the 'do stuff ' goes through a DataRow and assigns the items in that DataRow to a list of objects . I also have similar situations with ICollection and IList return types in other places.The reason I want to return either IEnumerable or ICollection is so that I 'm not returning more than needed . But at the same time , this allows the caller to convert the returned value to a List if it needs to do so.However , it seems weird that my return statement is returning a List , instead of what the method 's return type is . Is this normal practice ? Is there anything wrong with doing this ? Clarification ( in response to the dupe comments ) : Just to clarify , what I 'm curious about is if it is okay that my return statement in the body is returning a List < T > , but the method header has a return-type of IEnumerable , or possibly ICollection , Collection , etc ... Something different than than bodies return statement . <code> public IEnumerable < T > MyMethod ( string stuff ) { var myVar = new List < T > ( ) ; //do stuff return myVar ; }
|
OK to return an internal List < T > as an IEnumerable < T > or ICollection < T > ?
|
C_sharp : A control can only be accessed by the thread that created it - this much I know . I have a DataGridView with aDataSource based on a BindingList < > .I have a worker thread ( non-GUI ) that runs some fancycalculations/comparisons/etc andthen adds/edits an object to/in the BindingList < > .On a timer , the GUI thread refreshes itself against the BindingList < > .This code works flawlessly - as long as I 'm not running in the environment . In the environment when the .Add ( ) method is called on the BindingList < > I get this handy little error : Notice how the name of the control being violated is blank ... I would think that if the problem was with updating the BindingList < > it would n't matter if I was running in the environment or not . Notwithstanding , that 's what I 'm seeing . Moreover , the .Add ( ) completes successfully even though the exception is thrown ! ! Obviously , it 's not a big deal in my production environment ( yet ? ) since it only happens in Studio ; and yes I could Invoke the GUI thread to perform the Add , or store the adds in a place for the GUI thread to retrieve them later ... I 'm not looking for a work-around but more so am interested in the answer to this question : Why does the error only appear in studio ? <code> An Exception has occurredEXCEPTION : Cross-thread operation not valid : Control `` accessed from a thread other than the thread it was created on.IN METHOD : get_HandleAT LINE : 0CLASS : System.Windows.Forms.Control
|
Cross-Thread Exception - Environment Only
|
C_sharp : Consider the following code : With the following output : Why is it false and null ? A has n't been collected yet.EDIT : Oh ye of little faith.I added the following lines : See the updated output . <code> class Program { static void Main ( string [ ] args ) { A a = new A ( ) ; CreateB ( a ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Console.WriteLine ( `` And here 's : '' + a ) ; GC.KeepAlive ( a ) ; } private static void CreateB ( A a ) { B b = new B ( a ) ; } } class A { } class B { private WeakReference a ; public B ( A a ) { this.a = new WeakReference ( a ) ; } ~B ( ) { Console.WriteLine ( `` a.IsAlive : `` + a.IsAlive ) ; Console.WriteLine ( `` a.Target : `` + a.Target ) ; } } a.IsAlive : Falsea.Target : And here 's : ConsoleApp.A Console.WriteLine ( `` And here 's : '' + a ) ; GC.KeepAlive ( a ) ;
|
Why is a WeakReference useless in a destructor ?
|
C_sharp : As shown here , attribute constructors are not called until you reflect to get the attribute values . However , as you may also know , you can only pass compile-time constant values to attribute constructors . Why is this ? I think many people would much prefer to do something like this : than passing a string ( causing stringly typed code too ! ) with those values , turned into strings , and then relying on Regex to try and get the value instead of just using the actual value , and instead of using compile-time warnings/errors depending on exceptions that might be thrown somewhere that has nothing to do with the class except that a method that it called uses some attributes that were typed wrong.What limitation caused this ? <code> [ MyAttribute ( new MyClass ( foo , bar , baz , jQuery ) ]
|
If attributes are only constructed when they are reflected into , why are attribute constructors so limited ?
|
C_sharp : In the Microsoft.VisualStudio.TestTools.UnitTesting namespace , there is the handy static class Assert to handle the assertions going on in your tests.Something that has got me bugged is that most methods are extremely overloaded , and on top of that , they have a generic version . One specific example is Assert.AreEqual which has 18 overloads , among them : What is the use of this generic method ? Originally , I thought this was a way to directly call the IEquatable < T > Equals ( T t ) method , but that is not the case ; it will always call the non-generic version object.Equals ( object other ) . I found out the hard way after coding quite a few unit tests expecting that behavior ( instead of examining the Assert class definition beforehand like I should have ) .In order to call the generic version of Equals , the generic method would had to be defined as : Is there a good reason why it was n't done this way ? Yes , you loose the generic method for all those types that do n't implement IEquatable < T > , but it 's not a great loss anyway as equality would be checked through object.Equals ( object other ) , so Assert.AreEqual ( object o1 , object o2 ) is already good enough.Does the current generic method offer advantages I 'm not considering , or is it just the case that no one stopped to think about it as it 's not that much of a deal ? The only advantage I see is argument type safety , but that seems kind of poor.Edit : fixed an error where I kept referring to IComparable when I meant IEquatable . <code> Assert.AreEqual < T > ( T t1 , T t2 ) Assert.AreEqual < T > ( T t1 , T t2 ) where T : IEquatable < T >
|
Microsoft.VisualStudio.TestTools.UnitTesting.Assert generic method overloads behavior
|
C_sharp : I am trying to build an interface for a game . The game runs for 1 minute . The GetStop method stops after 60 sec game . The play method starts the game and the quit method quit the game . Now ideally what I want is when I quit the game after 30 seconds , the timer should get reset and on click of the Play button , the timer should again run for 1 minute . So that the next game gets to run for 1 minute . If I press Quit button then again , the timer should be reset for the next game.However , there seems to be a certain issue in my code . Whenever I execute quit method the timer seems to be saved at that state . So , If I quit a race in 30 seconds then the next race will last for only 30 seconds . If I quit a race in 50 seconds , the next race will last only 10 seconds . Ideally , the timer should get reset but it is not getting reset.I am out of ideas here . Can anyone please provide some suggestions ? ? <code> private async Task GetStop ( CancellationToken token ) { await Task.Run ( async ( ) = > { token.ThrowIfCancellationRequested ( ) ; await Task.Delay ( TimeSpan.FromSeconds ( 60 ) , token ) ; token.ThrowIfCancellationRequested ( ) ; if ( ! token.IsCancellationRequested ) { sendMessage ( ( byte ) ACMessage.AC_ESCAPE ) ; } } , token ) ; } public async void Play ( ) { sendMessage ( ( byte ) ACMessage.AC_START_RACE ) ; _cts.Cancel ( ) ; if ( _cts ! = null ) { _cts.Dispose ( ) ; _cts = null ; } _cts = new CancellationTokenSource ( ) ; await GetStop ( _cts.Token ) ; } public void Quit ( ) { _cts.Cancel ( ) ; if ( _cts ! = null ) { _cts.Dispose ( ) ; _cts = null ; } // }
|
Task.Delay didn ’ t get canceled ?
|
C_sharp : The code below shows a generic class with a type constraint ( Pub < T > ) . The class has an event that it can raise allowing us to pass a message to subscribers . The constraint is that the message must implement IMsg ( or inherit from IMsg when it 's is an abstract class ) .Pub < T > also provides a Subscribe method to allow objects to subscribe to the notify event if and only if the object implements IHandler < IMsg > .Using .NET 4 , the code below shows an error on baseImplementer.NotifyEventHandler stating that : '' No overload for 'IHandler < IMsg > .NotifyEventHandler ( IMsg ) ' matches delegate 'System.Action < T > ' '' Question : ( with updated Subscribe method ) Why does the error go away as soon as I change ` IMsg ` to an abstract class instead of an interface ? Code below here is not necessary to reproduce the issue ... but shows how the code above might be used . Obviously IMsg ( and the derived Msg ) classes would define or implement methods that could be called in a handler . <code> public interface IMsg { } // Does n't work//public abstract class IMsg { } // Does workpublic class Msg : IMsg { } public class Pub < T > where T : IMsg { public event Action < T > notify ; public void Subscribe ( object subscriber ) { // Subscriber subscribes if it implements IHandler of the exact same type as T // This always compiles and works IHandler < T > implementer = subscriber as IHandler < T > ; if ( implementer ! = null ) this.notify += implementer.NotifyEventHandler ; // If subscriber implements IHandler < IMsg > subscribe to notify ( even if T is Msg because Msg implements IMsg ) // This does not compile if IMsg is an interface , only if IMsg is an abstract class IHandler < IMsg > baseImplementer = subscriber as IHandler < IMsg > ; if ( baseImplementer ! = null ) this.notify += baseImplementer.NotifyEventHandler ; } } public interface IHandler < T > where T : IMsg { void NotifyEventHandler ( T data ) ; } public class SubA : IHandler < Msg > { void IHandler < Msg > .NotifyEventHandler ( Msg data ) { } } public class SubB : IHandler < IMsg > { void IHandler < IMsg > .NotifyEventHandler ( IMsg data ) { } } class MyClass { Pub < Msg > pub = new Pub < Msg > ( ) ; SubA subA = new SubA ( ) ; SubB subB = new SubB ( ) ; public MyClass ( ) { //Instead of calling ... this.pub.notify += ( this.subA as IHandler < Msg > ) .NotifyEventHandler ; this.pub.notify += ( this.subB as IHandler < IMsg > ) .NotifyEventHandler ; //I want to call ... this.pub.Subscribe ( this.subA ) ; this.pub.Subscribe ( this.subB ) ; // ... except that the Subscribe method wont build when IMsg is an interface } }
|
Why does n't an interface work but an abstract class does with a generic class constraint ?
|
C_sharp : According to MSDN the .NET XmlDocument.Load ( String ) method requires write access to the underlying file . The exceptions list saysMy question boils down toIs it even true that read-write access is needed , or is this just a documentation error ? Does it mean that the file is kept open during the lifetime of the object ? Does it mean that modifications to the the XmlDocument and its sub-nodes can result in live modifications to the file on disk ? Even without an explicit save . <code> UnauthorizedAccessException : filename specified a file that is read-only ... .
|
Why does XmlDocument.Load ( String ) seem to want read-write access ?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.