text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : I have an import operation I 'd like to execute on another thread , desiring the UI to respond right away . So , I started down the path and created an action like this : The ImportManager now serves two purposes : Handle the import.Notify all clients of the status of the import via SignalR.The StartImport method looks like this : What 's Happening ? Debugging we find that when I hit the await Task.Run ( ( ) = > it runs synchronously ( for a while anyway ) because the UI does n't get the request to redirect to Index until say 30K+ lines have been read.How can I get this to simply execute and forget it ? Do I need to use a different approach ? <code> [ HttpPost ] public async Task < RedirectToRouteResult > ImportAsync ( HttpPostedFileBase file ) { var importsRoot = Server.MapPath ( `` ~/App_Data/Imports '' ) ; var path = Path.ChangeExtension ( Path.Combine ( importsRoot , Guid.NewGuid ( ) .ToString ( ) ) , `` txt '' ) ; if ( ! Directory.Exists ( importsRoot ) ) { Directory.CreateDirectory ( importsRoot ) ; } file.SaveAs ( path ) ; // start the import process await ImportManager.Instance.StartImport ( User.Identity.Name ) ; return RedirectToAction ( `` Index '' ) ; } public async Task StartImport ( string user ) { string [ ] files ; var importRoot = HttpContext.Current.Server.MapPath ( `` ~/App_Data/Imports '' ) ; var processingRoot = HttpContext.Current.Server.MapPath ( `` ~/App_Data/Processing '' ) ; var processedRoot = HttpContext.Current.Server.MapPath ( `` ~/App_Data/Processed '' ) ; lock ( lockObj ) { // make sure the `` Processing '' folder exists if ( ! Directory.Exists ( processingRoot ) ) { Directory.CreateDirectory ( processingRoot ) ; } // find all of the files available and move them to the `` Processing '' folder files = Directory.GetFiles ( importRoot ) ; foreach ( var file in files ) { var fileName = Path.GetFileName ( file ) ; if ( fileName == null ) { continue ; } File.Move ( file , Path.Combine ( processingRoot , fileName ) ) ; } // make sure the `` Processed '' directory exists if ( ! Directory.Exists ( processedRoot ) ) { Directory.CreateDirectory ( processedRoot ) ; } } await Task.Run ( ( ) = > { // start processing the files foreach ( var file in files ) { var fileName = Path.GetFileName ( file ) ; if ( fileName == null ) { continue ; } var processingFileName = Path.Combine ( processingRoot , fileName ) ; var processedFileName = Path.Combine ( processedRoot , fileName ) ; var recognizer = new Recognizer ( processingFileName ) ; recognizer.ProgressChanged += ( s , e ) = > Clients.All.updateImportStatus ( e.ProgressPercentage , user ) ; recognizer.Recognize ( DataManager.GetExclusionPatterns ( ) ) ; // move the file to the `` Processed '' folder File.Move ( processingFileName , processedFileName ) ; } Clients.All.importComplete ( ) ; } ) ; } | Task.Run is n't running asynchronously like I had thought it would ? |
C_sharp : This error is so weird I Just ca n't really figure out what is really wrong ! In UserController I haveMy view is of type @ model IEnumerable < UserViewModel > on the top.This is what happens : Where and what exactly IS null ! ? I create the users from a fake repository with moq . I also wrote unit tests , which pass , to ensure the right amount of mocked users are returned . Maybe someone can point me in the right direction here ? Top of the stack trace is : Is it something to do with linq here ? Tell me If I should include the full stack trace.Edit < BangsHeadOnWall / > Wow , I can not believe it was u.UserGroupMain.GroupName thanks @ Lunivore.It was a mockup repo , and I had a unit test to check if the mock repo user had a mock instance of UserGroupMain but I did n't Assert if the wee property GroupName had been set ! Thanks @ RPM1984 you 're suggestion got the code to break in the controller itself . Plus I learnt something new.Thanks @ Mikael , first time I used the immediate window wow its cool ! =DGuess you live , code and learn ! <code> public virtual ActionResult Index ( ) { var usersmdl = from u in RepositoryFactory.GetUserRepo ( ) .GetAll ( ) select new UserViewModel { ID = u.ID , UserName = u.Username , UserGroupName = u.UserGroupMain.GroupName , BranchName = u.Branch.BranchName , Password = u.Password , Ace = u.ACE , CIF = u.CIF , PF = u.PF } ; if ( usersmdl ! = null ) { return View ( usersmdl.AsEnumerable ( ) ) ; } return View ( ) ; } at lambda_method ( Closure , User ) at System.Linq.Enumerable.WhereSelectArrayIterator ` 2.MoveNext ( ) at ASP.Index_cshtml.Execute ( ) | odd nullreference error at foreach when rendering view |
C_sharp : I created an extension method to encapsule some where logic like this ( this is a very simplified version ) : So I can use it like this : Which works nicely , this is translated to SQL and executed by Entity Framework . Now , I have another place I need cargos which are not ready to carry , which means I need exactly the opposite.My idea was something like this : I did n't want to recreate the reverse logic from scratch , so if I needed to change it one day , I 'd change in one unique place.I 'm accepting alternatives to this approach , since it 's a new project . <code> public static IQueryable < Cargo > ReadyToCarry ( this IQueryable < Cargo > q ) { VehicleType [ ] dontNeedCouple = new VehicleType [ ] { VehicleType.Sprinter , VehicleType.Van , VehicleType.Truck } ; return q.Where ( c = > c.DriverId > 0 & & c.VehicleId > 0 ) .Where ( c = > c.CoupleId > 0 || dontNeedCouple.Contains ( c.Vehicle.Type ) ) ; } using ( var ctx = new MyNiceContext ( ) ) { var readyCargo = ctx.Cargos.ReadyToCarry ( ) .OrderBy ( c = > c.Id ) .ToList ( ) ; // ... more code } public static IQueryable < Cargo > NotReadyToCarry ( this IQueryable < Cargo > q ) { return ! q.ReadyToCarry ( ) ; // ofc this does n't work ... } using ( var ctx = new MyNiceContext ( ) ) { var readyCargo = ctx.Cargos.NotReadyToCarry ( ) .OrderBy ( c = > c.Id ) .ToList ( ) ; // OR maybe var readyCargo = ctx.Cargos.ReadyToCarry ( false ) .OrderBy ( c = > c.Id ) .ToList ( ) ; // somehow use that bool param to reverse the logic when false } | How to negate a Where clause of an IQueryable |
C_sharp : I 'm creating a model for an existing database . How do I use nvarchar ( max ) as an attribute to my property ? Do I use an extension to my attribute ? Or is it entirely different . The SQL Server database is using a datatype of nvarchar ( max ) . <code> [ MaxLength + ? ? ? ] public string Bucket { get ; set ; } | Using NVarChar in asp.net core |
C_sharp : Need to validate the Azure Virtual machine username and password . Now used the following code to validate the Virtual machine username and password.But can not able to validate the Virtual machine credentials while Virtual machines are in shutdown state . Is there any way to validate Virtual machine credentials even when the Virtual machines are in shutdown state ? <code> $ SecureVmPassword = ConvertTo-SecureString -string $ VmPassword -AsPlainText -Force $ VmCredential = New-Object -typename System.Management.Automation.PSCredential -argumentlist $ Fqdn '' \ '' $ VmUsername , $ SecureVmPasswordInvoke-Command -ConnectionUri $ RemoteConnectionUri.ToString ( ) -Credential $ VmCredential -ScriptBlock { } | How to validate Azure Virtual machine username and password ? |
C_sharp : I am trying out Resharper and i notice that it is recommending to set instance level fields to readonly . For example : What is the benefit of marking fields like this readonly ? <code> private readonly IConnection _connection ; public RetrieveCommand ( IConnection connection ) { _connection = connection ; } | Resharper changing fields to readonly |
C_sharp : Here is a small demo of a SQL database , where one can add , update delete members from a SQL server . There are two tables in a single SQL Server DB , one is “ members ” second is “ overview ” . In members there is distinct ID column and members personal info like name , address telephone etc . In overview there are only three columns which are dID , year & amount.There is one single windows form , language is c # and project is built in Visual Studio 2010 , and of course data base in SQL Server 2010 . The windows form has a “ reset , insert , update & delete ” buttons . There is one more button besides the dID text box where a distinct ID can be inserted and after clicking Search button the last entry made about the member shows by filling all the text boxes where name address telephone appear . This serves the function that member full info can be seen and changes can be made or can be removed from dB . There are two text boxes in particular , which are Year & Amount , which shows that the member has paid a certain amount for the certain year . But as I mentioned in the text boxes you can only see the last entry made . What function I want to achieve is that after inserting dID of person x I could only in the year text box able to insert lets say any previous year and the press search which should like normally fill all the text boxes with info , and in the amount text box should show me the entry from the dB that according to the year I entered how much amount is there or there is nothing which means that may be member has not paid for a certain year . I need help in achieving this logic programmatically therefore I would like to request assistance.The present program is as follows : <code> using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Data.SqlClient ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Windows.Forms ; namespace SQLDatabase { public partial class SQLDBDisplay : Form { SqlConnection con = new SqlConnection ( `` Data Source=JG-PC\\SQLEXPRESS ; Initial Catalog=TEST ; Integrated Security=True '' ) ; public SQLDBDisplay ( ) { InitializeComponent ( ) ; } SqlDataAdapter da ; DataSet ds = new DataSet ( ) ; private void btnSearch_Click ( object sender , EventArgs e ) { SqlDataReader reader ; SqlCommand cmd = new SqlCommand ( ) ; try { string sql = `` SELECT * FROM members where dID = ' '' + txtdID.Text + `` ' `` ; txtYear.Text = sql ; cmd.Connection = con ; cmd.CommandText = sql ; con.Open ( ) ; reader = cmd.ExecuteReader ( ) ; while ( reader.Read ( ) ) { txtID.Text = reader [ `` ID '' ] .ToString ( ) ; txtName.Text = reader [ `` Name '' ] .ToString ( ) ; txtAddress.Text = reader [ `` Address '' ] .ToString ( ) ; txtMobile.Text = reader [ `` Mobile '' ] .ToString ( ) ; txtEmail.Text = reader [ `` Email '' ] .ToString ( ) ; txtdID.Text = reader [ `` dID '' ] .ToString ( ) ; } con.Close ( ) ; sql = `` SELECT * FROM Overview where dID = ' '' + txtdID.Text + `` ' `` ; txtYear.Text = txtYear.Text + `` : `` + sql ; cmd.Connection = con ; cmd.CommandText = sql ; con.Open ( ) ; reader = cmd.ExecuteReader ( ) ; while ( reader.Read ( ) ) { txtYear.Text = reader [ `` Year '' ] .ToString ( ) ; txtAmount.Text = reader [ `` Amount '' ] .ToString ( ) ; txtdID.Text = reader [ `` dID '' ] .ToString ( ) ; } con.Close ( ) ; } catch ( Exception ex ) { MessageBox.Show ( ex.Message.ToString ( ) ) ; } } private void btnReset_Click ( object sender , EventArgs e ) { txtdID.Text = `` '' ; txtName.Text = `` '' ; txtAddress.Text = `` '' ; txtMobile.Text = `` '' ; txtEmail.Text = `` '' ; txtYear.Text = `` '' ; txtAmount.Text = `` '' ; } private void btnInsert_Click ( object sender , EventArgs e ) { SqlCommand cmd = new SqlCommand ( ) ; string Sql = `` INSERT INTO members ( dID , Name , Address , Email , Mobile ) VALUES ( ' '' + txtdID.Text+ `` ' , ' '' + txtName.Text + `` ' , ' '' + txtAddress.Text + `` ' , ' '' + txtEmail.Text + `` ' , ' '' + txtMobile.Text + `` ' ) '' ; cmd.CommandText = Sql ; cmd.Connection = con ; con.Open ( ) ; cmd.ExecuteNonQuery ( ) ; con.Close ( ) ; Sql = `` INSERT INTO Overview ( dID , Year , Amount ) VALUES ( ' '' + txtdID.Text + '' ' , ' '' + txtYear.Text + `` ' , ' '' + txtAmount.Text + '' ' ) '' ; cmd.CommandText = Sql ; cmd.Connection = con ; con.Open ( ) ; cmd.ExecuteNonQuery ( ) ; con.Close ( ) ; MessageBox.Show ( `` Record Inserted Scuessfully ! ! ! `` ) ; for ( int i = 0 ; i < this.Controls.Count ; i++ ) { if ( this.Controls [ i ] is TextBox ) { this.Controls [ i ] .Text = `` '' ; } } } private void btnUpdate_Click ( object sender , EventArgs e ) { try { SqlCommand cmd = new SqlCommand ( ) ; string Sql = `` Update members set Name = ' '' + txtName.Text + `` ' , Address = ' '' + txtAddress.Text + `` ' , Email = ' '' +txtEmail.Text + `` ' , Mobile = ' '' + txtMobile.Text + `` ' WHERE dID = ' '' + txtdID.Text + `` ' '' ; cmd.CommandText = Sql ; cmd.Connection = con ; con.Open ( ) ; cmd.ExecuteNonQuery ( ) ; con.Close ( ) ; Sql = `` Update overview set Year = ' '' + txtYear.Text + `` ' , Amount = ' '' + txtAmount.Text + `` ' WHERE dID = ' '' + txtdID.Text+ '' ' '' ; cmd.CommandText = Sql ; cmd.Connection = con ; con.Open ( ) ; cmd.ExecuteNonQuery ( ) ; MessageBox.Show ( `` Data Scuessfully Updated '' ) ; con.Close ( ) ; } catch ( Exception error ) { MessageBox.Show ( error.ToString ( ) ) ; } for ( int i = 0 ; i < this.Controls.Count ; i++ ) { if ( this.Controls [ i ] is TextBox ) { this.Controls [ i ] .Text = `` '' ; } } } private void btnDelete_Click ( object sender , EventArgs e ) { SqlCommand cmd = con.CreateCommand ( ) ; cmd.CommandType = CommandType.Text ; cmd.CommandText = `` DELETE FROM members WHERE dID = ' '' + txtdID.Text + '' ' '' ; con.Open ( ) ; cmd.ExecuteNonQuery ( ) ; cmd.CommandText = `` DELETE FROM overview WHERE dID = ' '' + txtdID.Text + `` ' '' ; cmd.ExecuteNonQuery ( ) ; da = new SqlDataAdapter ( cmd ) ; MessageBox.Show ( `` Record Scuessfully Deleted ! `` ) ; con.Close ( ) ; for ( int i = 0 ; i < this.Controls.Count ; i++ ) { if ( this.Controls [ i ] is TextBox ) { this.Controls [ i ] .Text = `` '' ; } } } private void btnClose_Click ( object sender , EventArgs e ) { Application.Exit ( ) ; } } } | How to achieve a search for a certain year & amount using C # |
C_sharp : I have a case there I need to execute set of validation rules for different companies . There will be multiple validation rules against one Company.So I have following table StructureCompany ValidationRule CompanyValidationRuleMapping I have separate stored procedures for every validation rule.So from my c # code , I will find all validation rule corresponding to a company and need to execute the validation stored procedure associated with that rule.So I am planning to keep one Interface 'IValidation ' which is having different validation methods.OrCan i have to create different classes for each validation which implements an interface Can anyone please suggest a better approach on this . <code> ID CompanyName 1 ABC 2 DEF RuleID Name 1 Rule1 2 Rule2 MappingID CompanyId RuleID1 1 12 1 23 2 2 | Execute Set of ValidationRule-C # Class Design - Better Approach |
C_sharp : When I run this bit of code , Equation ( 10 , 20 ) is output to the console : I 'd like to support Equation instances being used in the test of an if so I allowed for implicit conversion to Boolean : However , the trouble is , now when I use WriteLine on an Equation , it get 's converted to a Boolean instead of printing using ToString.How can I allow for implicit conversion to Boolean and still have WriteLine display using ToString ? updateThis question is inspired by the Equation class in SymbolicC++ . The code below illustrates that an Equation can be displayed via cout as well as used in the test of an if : So this is somehow possible in C++ . <code> public class Equation { public int a ; public int b ; public override string ToString ( ) { return `` Equation ( `` + a + `` , `` + b + `` ) '' ; } } class Program { static void Main ( string [ ] args ) { Console.WriteLine ( new Equation ( ) { a = 10 , b = 20 } ) ; Console.ReadLine ( ) ; } } public class Equation { public int a ; public int b ; public override string ToString ( ) { return `` Equation ( `` + a + `` , `` + b + `` ) '' ; } public static implicit operator Boolean ( Equation eq ) { return eq.a == eq.b ; } } class Program { static void Main ( string [ ] args ) { if ( new Equation ( ) { a = 10 , b = 10 } ) Console.WriteLine ( `` equal '' ) ; Console.WriteLine ( new Equation ( ) { a = 10 , b = 20 } ) ; Console.ReadLine ( ) ; } } auto eq = x == y ; cout < < eq < < endl ; if ( eq ) cout < < `` equal '' < < endl ; else cout < < `` not equal '' < < endl ; | Support conversion to Boolean but still have WriteLine display using ToString |
C_sharp : Say that I have a list of valid scheduling days . Something like : 23 , 27 , 29I want to modify a given date to it 's next valid day-month based on the above list.If your given date was `` 23/11/2013 '' the next valid date would be `` 27/11/2013 '' But If your given date was `` 30/11/2013 '' it has to return `` 23/12/2013 '' And if the given date is `` 30/12/2013 '' it has to return `` 23/01/2014 '' I 've done that in SQL , but now I 'm translating it to C # and it 's a bit tricky.I 'm trying to do it using LINQ over the list for SQL similarity , but it gets confusing.The SQL statement was ( yes , i know it does n't swift year ) : @ DAYS was a working table . <code> SELECT TOP 1 @ DATE = ISNULL ( DateAdd ( yy , YEAR ( @ DATE ) -1900 , DateAdd ( m , ( MONTH ( @ DATE ) +CASE WHEN DATEPART ( day , @ DATE ) > [ DAY ] THEN 1 ELSE 0 END ) - 1 , [ DAY ] - 1 ) ) , @ DATE ) FROM @ DAYS WHERE DateAdd ( yy , YEAR ( @ DATE ) -1900 , DateAdd ( m , ( MONTH ( @ DATE ) +CASE WHEN DATEPART ( day , @ DATE ) > [ DAY ] THEN 1 ELSE 0 END ) - 1 , [ DAY ] - 1 ) ) > = @ DATEORDER BY [ DAY ] | DateTime shift to next predefined date |
C_sharp : I have a simple method to compare an array of FileInfo objects against a list of filenames to check what files have been already been processed . The unprocessed list is then returned.The loop of this method iterates for about 250,000 FileInfo objects . This is taking an obscene amount of time to compete.The inefficiency is obviously the Contains method call on the processedFiles collection.First how can I check to make sure my suspicion is true about the cause and secondly , how can I improve the method to speed the process up ? <code> public static List < FileInfo > GetUnprocessedFiles ( FileInfo [ ] allFiles , List < string > processedFiles ) { List < FileInfo > unprocessedFiles = new List < FileInfo > ( ) ; foreach ( FileInfo fileInfo in allFiles ) { if ( ! processedFiles.Contains ( fileInfo.Name ) ) { unprocessedFiles.Add ( fileInfo ) ; } } return unprocessedFiles ; } | I have a non-performant method , how can I improve its efficiency ? |
C_sharp : Possible Duplicate : Why does Enumerable.All return true for an empty sequence ? Code : How it is possible ? it should not return false ? after : is an empty string . <code> var line = `` name : '' ; Console.Write ( line.Split ( new char [ ] { ' : ' } ) [ 1 ] .All ( char.IsDigit ) ) ; | why this condition returns true ? |
C_sharp : If I create a binary add expression ( addExpression ) of two int literals like this : . . and then a binary multiply expression , where left is addExpression and right is an int literal Calling multExpression.ToString ( ) outputs 10+100*5 . I would expect it to output ( 10+100 ) *5.Is this correct behavior ? <code> BinaryExpressionSyntax addExpression = SyntaxFactory.BinaryExpression ( SyntaxKind.AddExpression , SyntaxFactory.LiteralExpression ( SyntaxKind.NumericLiteralExpression , SyntaxFactory.Literal ( 10 ) ) , SyntaxFactory.LiteralExpression ( SyntaxKind.NumericLiteralExpression , SyntaxFactory.Literal ( 100 ) ) ) ; BinaryExpressionSyntax multExpression = SyntaxFactory.BinaryExpression ( SyntaxKind.MultiplyExpression , addExpression , SyntaxFactory.LiteralExpression ( SyntaxKind.NumericLiteralExpression , SyntaxFactory.Literal ( 5 ) ) ) ; | Roslyn - Calling ToString on SyntaxNode not preserving precedence |
C_sharp : I have written a regex to parse a BibTex entry , but I think I used something that is not allowed in .net as I am getting a Unrecognized grouping construct exception.Can anyone spot my mistake ? Can be seen at https : //regex101.com/r/uM0mV1/1 <code> ( ? < entry > @ ( \w+ ) \ { ( \w+ ) , ( ? < kvp > \W* ( [ a-zA-Z ] + ) = \ { ( .+ ) \ } , ) ( ? & kvp ) * ( \W* ( [ a-zA-Z ] + ) = \ { ( .+ ) \ } ) \W*\ } , ? \s* ) ( ? & entry ) * | Recursive regex : Unrecognized grouping construct |
C_sharp : Possible Duplicate : C # , int or Int32 ? Should I care ? Please any one let me know MSIL of System.Int32 and int will be same or different , If different then which one we should use.Edit : this wo n't compilebut this will <code> public enum MyEnum : Int32 { AEnum = 0 } public enum MyEnum : int { AEnum = 0 } | MSIL of System.Int32 and int will be same ? |
C_sharp : I am using EnumerateFiles to get all *.md in the directory : I have three test files a.md , b.md and c.md.Now when I rename a.md to a1.md , EnumerateFiles returns both old and new filename.. The result from PowerShell says I have 3 files , while EnumerateFiles returns 4 files.I read somewhere EnumerateFiles does some kind of caching , with lazy loading ? But should n't it invalidate cache when the file is renamed ? GetFiles / EnumerateFiles Output : <code> foreach ( var mdName in Directory.EnumerateFiles ( Path.Combine ( BaseDirectory , `` assets/markdowns '' ) , `` *.md '' , SearchOption.AllDirectories ) ) { // async md parser call goes here } [ 0 ] : `` C : \\Repos\\KiddiesBlog\\Tests\\bin\\Debug\\assets/less\\a.md '' [ 1 ] : `` C : \\Repos\\KiddiesBlog\\Tests\\bin\\Debug\\assets/less\\b.md '' [ 2 ] : `` C : \\Repos\\KiddiesBlog\\Tests\\bin\\Debug\\assets/less\\c.md '' [ 3 ] : `` C : \\Repos\\KiddiesBlog\\Tests\\bin\\Debug\\assets/less\\_a.md '' [ 4 ] : `` C : \\Repos\\KiddiesBlog\\Tests\\bin\\Debug\\assets/less\\_a1.md '' [ 5 ] : `` C : \\Repos\\KiddiesBlog\\Tests\\bin\\Debug\\assets/less\\_a2.md '' [ 6 ] : `` C : \\Repos\\KiddiesBlog\\Tests\\bin\\Debug\\assets/less\\_a3.md '' | EnumerateFiles to avoid caching |
C_sharp : I am about to undertake a conversion of Identity 's Microsoft.AspNet.Identity.EntityFramework project ( v 2.0.0.0 ) to one that uses NHibernate as its persistence machine . My first 'stumbling block ' is this set of repositories in the UserStore class : Type parameter TUser is constrained to IdentityUser < TKey , TUserLogin , TUserRole , TUserClaim > , and this type has its own similar set of collections : My life would be much easier if I had to manage just one repository , of TUser , as each of these users already take care of their own stuff . Is there any important reason I ca n't just do away with these ( in order to do away with any dependencies on Entity Framework , like DbSet ? I could contrive my own repository class in place of DbSet to conform to this design of UserStore , but I would much prefer to just lose them and let each user instance take care of its own claims etc . <code> private readonly IDbSet < TUserLogin > _logins ; private readonly EntityStore < TRole > _roleStore ; private readonly IDbSet < TUserClaim > _userClaims ; private readonly IDbSet < TUserRole > _userRoles ; private EntityStore < TUser > _userStore ; public virtual ICollection < TRole > Roles { get ; private set ; } public virtual ICollection < TClaim > Claims { get ; private set ; } public virtual ICollection < TLogin > Logins { get ; private set ; } | Why so many repositories in ASP.NET Identity 's ` UserStore ` ? |
C_sharp : If I have something like this : Now can you please tell me how can I create a unit test that will ensure that the method generates correct xml ? How can I mock XDocument ( I am using Moq ) , without adding additional parameters to the method call <code> static class ManifestGenerator { public static void GenerateManifestFile ( ) { var doc = new XDocument ( ) ; ... ... xml stuff added to doc ... doc.Save ( manifestFilePath ) } | How do you mock object in a static method |
C_sharp : it has a property : string Codeand 10 other.common codes is list of strings ( string [ ] ) cars a list of cars ( Car [ ] ) filteredListOfCars is List.Unfortunately this piece of methodexecutes too long.I have about 50k recordsHow can I lower execution time ? ? <code> for ( int index = 0 ; index < cars.Length ; index++ ) { Car car = cars [ index ] ; if ( commonCodes.Contains ( car.Code ) ) { filteredListOfCars.Add ( car ) ; } } | How to optimize this code |
C_sharp : In a web project , I 'm trying to execute the following query : With breakpoints , I can see I attached to @ value0 the value , 2.Despite this , I get the following error : No value given for one or more required parameters.I understood this error is usually generated due to bad SQL syntax . Is there anything wrong with what I did ? EDIT : Attachment code : And later on : I 'm pretty sure items [ ii ] .ID is fine , breakpoints show that it equals 2 and the attachment goes well.EDIT 2 : I 've editted the code as Krish and Hans advised me , and I get the following query without any attachments : I still get the same error , if it changes anything.EDIT 3 : Executing the query in Access asks me to give a value to the parameter `` ItemPicture '' ... Odd ; ItemPicture is a column , is n't it ? <code> SELECT ItemName as Name , ItemPicture as Picture , ItemHeroModif as Assistance , ItemTroopModif as Charisma , HerbCost as Herbs , GemCost as GemsFROM Item WHERE ItemId = @ value0 var madeForCommand = `` SELECT ItemName as Name , ItemPicture as [ Picture ] , ItemHeroModif as Assistance , ItemTroopModif as Charisma , HerbCost as Herbs , GemCost as Gems FROM Item WHERE `` ; OleDbCommand command = new OleDbCommand ( ) ; for ( int ii = 0 ; ii < items.Count ; ii++ ) // items is a list of items with IDs I want to get from the query . { madeForCommand += `` ItemId = @ value '' +ii+ '' OR `` ; } madeForCommand = madeForCommand.Substring ( 0 , madeForCommand.Length - 4 ) ; // making sure I trim the final or ; In the case I shown , it 's just one item , so there are none at all . OleDbCommand forOperations = new OleDbCommand ( madeForCommand , _dbConnection ) ; //_dbConnection is the connection to the database , it seems to work pretty well.for ( int ii = 0 ; ii < items.Count ; ii++ ) { string attach = `` @ value '' + ii ; command.Parameters.AddWithValue ( attach , items [ ii ] .ID ) ; } SELECT ItemName as [ Name ] , ItemPicture as Picture , ItemHeroModif as Assistance , ItemTroopModif as Charisma , HerbCost as Herbs , GemCost as Gems FROM [ Item ] WHERE ( ItemID in ( 2 ) ) ; | Access SQL query missing more required parameters |
C_sharp : Consider this silly program that does nothing : This shows that A2 and C2 implement both I < A1 > and I < A2 > , and that B2 implements both I < B1 > and I < B2 > .However , modifying this toshows that on the first and third lines , f 's generic type argument can not be inferred from the passed argument , yet on the second line , it can be.I understand what it is that the compiler is doing here , so that does n't need explaining . But how can I work around this ? Is there some way to modify this so that I can define the interface on both the base and the derived class , yet have type inference work when passing the derived class ? What I had in mind was to look for a way to `` hide '' a base class 's implemented interfaces , so that the compiler does n't see them and use them , even though they do exist . However , C # does n't seem to provide an option to do so.Clarification : in my silly example program , A1 implements I with itself as the generic type argument . I do have that in my real code , but I also have classes that implement I with a different generic type argument , and have added C1 and C2 to my example code for that reason . <code> interface I < out T > { } class A1 : I < A1 > { } class A2 : A1 , I < A2 > { } class B1 { } class B2 : B1 , I < B2 > { } class C1 : I < A1 > { } class C2 : C1 , I < A2 > { } static class Program { static void f < T > ( I < T > obj ) { } static void Main ( ) { f < A1 > ( new A2 ( ) ) ; f < A2 > ( new A2 ( ) ) ; f < B1 > ( new B2 ( ) ) ; f < B2 > ( new B2 ( ) ) ; f < A1 > ( new C2 ( ) ) ; f < A2 > ( new C2 ( ) ) ; } } static void Main ( ) { f ( new A2 ( ) ) ; f ( new B2 ( ) ) ; f ( new C2 ( ) ) ; } | Generic type inference with multiply-implemented covariant interfaces , how to work around it ? |
C_sharp : The following code compiles : However , when switching to an aliased using , there is a problem with the Include function , which is an extension method : The Include function can still be used , but not as an extension method . Is there any way to use it as an extension method without un-aliasing the using directive ? <code> using Microsoft.SharePoint.Clientclass Dummy ( ) { void DummyFunction ( ClientContext ctx , ListCollection lists ) { Context.Load ( lists , lc = > lc.Include ( l = > l.DefaultViewUrl ) ; } } using SP = Microsoft.SharePoint.Clientclass DummyAliased ( ) { void DummyFunction ( SP.ClientContext ctx , SP.ListCollection lists ) { /* Does not compile : */ Context.Load ( lists , lc = > lc.Include ( l = > l.DefaultViewUrl ) ; /* Compiles ( not using function as generic ) */ Context.Load ( lists , lc = > SP.ClientObjectQueryableExtension.Include ( lc , l = > l.DefaultViewUrl ) ) ; } } | C # : Extension Methods not accessible with aliased using directive |
C_sharp : Let 's say I have these bytes : And I want to turn it into the six-character string hex representation you see in CSS ( e.g . `` # 0000ff '' ) : How can I do this ? <code> byte red = 0 ; byte green = 0 ; byte blue = 255 ; | C # /CSS : Convert bytes to CSS hex string |
C_sharp : I am creating a generic class to hold widgets and I am having trouble implementing the contains method : Error : Operator '== ' can not be applied to operands of type ' V ' and ' V'If I can not compare types , how am I to implement contains ? How do dictionaries , lists , and all of the other generic containers do it ? ? <code> public class WidgetBox < A , B , C > { public bool ContainsB ( B b ) { // Iterating thru a collection of B 's if ( b == iteratorB ) // Compiler error . ... } } | Can Not Compare Generic Values |
C_sharp : I 'm basically wondering how I should , in C # , catch exceptions from asynchronous methods that are waited on through the await keyword . Consider for example the following small console program , which most importantly contains a method called AwaitSync . AwaitSync calls TestAsync , which returns a Task that when executed throws an exception . I try to catch the exception in AwaitAsync , but it goes unhandled.How am I supposed to go about catching the exception from the Task returned by TestAsync ? While this example is a console program , my real life problem is within the context of of ASP.NET MVC / Web API.EDIT : Turns out the exception is getting caught , for technical reasons I just did n't notice the 'Exception caught ' message before the terminal closed . In any case , Jon Skeet 's answer was very valuable to my understanding of await and exception handling . <code> class Program { static void Main ( string [ ] args ) { AwaitAsync ( ) ; Console.ReadKey ( ) ; } static async Task AwaitAsync ( ) { try { await TestAsync ( ) ; } catch ( Exception ) { Console.WriteLine ( `` Exception caught '' ) ; } } static Task TestAsync ( ) { return Task.Factory.StartNew ( ( ) = > { throw new Exception ( `` Test '' ) ; } ) ; } } | How do I catch in C # an exception from an asynchronous method that is awaited ? |
C_sharp : I 've been programming in JAVA and C all my years at Uni , but now I 'm learning C # and building a small application , and I 've found troubles with this : I get a red underline for this conditional , and I do n't really know why , because according to what I 've seen that should be ok , but it is not . Is there something I 'm missing ? thank you all in advance , VictorThank you all ! ! ! I was getting mad about this . The thing is that I 'm Spanish and I 'm used to have the pipe key | exactly in the same place where ¦ is in the American configuration ... I was seeing this ¦ strange , but I thought it was the same ... Thanks for the fast reply ! ! Victor <code> if ( taxonType.Equals ( null ) ¦¦ taxonID == -1 ) | Conditional or in C # |
C_sharp : Since immutable data strucutures are first-class values we can compare them for equality or order as we do with any other values . But things became complicated in BCL immutable collections preview because every immutable collection can be parameterized by IEqualityComparer < T > /IComparer < T > instances . Looks like immutable collections with different comparers should not be allowed to compare ( since equality is not defined for comparers itself ) , because it makes equality relation non-symmetric : Will this behavior be fixed somehow ? <code> var xs = ImmutableList < string > .Empty.Add ( `` AAA '' ) .WithComparer ( StringComparer.OrdinalIgnoreCase ) ; var ys = ImmutableList < string > .Empty.Add ( `` aaa '' ) .WithComparer ( StringComparer.Ordinal ) ; Console.WriteLine ( xs.Equals ( ys ) ) ; // trueConsole.WriteLine ( ys.Equals ( xs ) ) ; // false | BCL Immutable Collections : equality is non-symmetric |
C_sharp : Ok ! I have same code written in Java and C # but the output is different ! Output : Class A . It is in C # .But when same code was ran in Java , the output was Class B . Here is the Java Code : So , why this is showing different results ? I do know that , in Java , all methods are virtual by default that 's why Java outputs Class B.Another thing is that , both languages claim that they are emerged or inspired by C++ then why they are showing different results while both have same base language ( Say ) . And what does this line A a = new B ( ) ; actually doing ? Is n't a holding object of class B ? If it is so , then why C # displays Class A and Java shows Class B ? NOTE This question was asked in interview with the same code provided above . And I answered with output Class B ( with respect to Java ) but he said Class A will be right output.Thank you ! <code> class A { public void print ( ) { Console.WriteLine ( `` Class A '' ) ; } } class B : A { public void print ( ) { Console.WriteLine ( `` Class B '' ) ; } } class Program { static void Main ( string [ ] args ) { A a = new B ( ) ; a.print ( ) ; Console.Read ( ) ; } } class A { public void print ( ) { System.out.println ( `` Class A '' ) ; } } class B extends A { public void print ( ) { System.out.println ( `` Class B '' ) ; } } public class Program { public static void main ( String [ ] args ) { A a = new B ( ) ; a.print ( ) ; } } | Java Vs C # : Java and C # subclasses with method overrides output different results in same scenario |
C_sharp : My question is how to return a list of MergeObj when joining the two tables . I tried : But QueryJoin ( ) gives Exception : System.NotSupportedException , Joins are not supported . please note I 'm using sqlite.net not ADO.net . <code> class TableObj1 { public string Id { get ; set ; } public string Name { get ; set ; } } class TableObj2 { public string Id { get ; set ; } public string Email { get ; set ; } } class MergeObj { public TableObj1 Obj1 { get ; set ; } public TableObj2 Obj2 { get ; set ; } } public IEnumerable < MergeObj > QueryJoin ( ) { return ( from obj1 in conn.Table < TableObj1 > ( ) join obj2 in conn.Table < TableObj2 > ( ) on obj1.Id equals obj2.Id select new MergeObj { Obj1 = obj1 , Obj2 = obj2 } ) ; } void main ( ) { IEnumerable < MergeObj > mergeObjs = QueryJoin ( ) ; } | How to return Wrapper obj of TableOjb1 and TableObj2 using linq |
C_sharp : I was working with bit shift operators ( see my question Bit Array Equality ) and a SO user pointed out a bug in my calculation of my shift operand -- I was calculating a range of [ 1,32 ] instead of [ 0,31 ] for an int . ( Hurrah for the SO community ! ) In fixing the problem , I was surprised to find the following behavior : In fact , it would seem that n < < s is compiled ( or interpreted by the CLR -- I did n't check the IL ) as n < < s % bs ( n ) where bs ( n ) = size , in bits , of n.I would have expected : It would seem that the compiler is realizing that you are shifting beyond the size of the target and correcting your mistake.This is purely an academic question , but does anyone know if this is defined in the spec ( I could not find anything at 7.8 Shift operators ) , just a fortuitous fact of undefined behavior , or is there a case where this might produce a bug ? <code> -1 < < 32 == -1 -1 < < 32 == 0 | C # bit shift : is this behavior in the spec , a bug , or fortuitous ? |
C_sharp : I have a model : and a View Model : My view has an instance of ProductViewModel as the DataContext . The view has the field : By default , validation occurs on the IDataErrorProvider of the bound object ( Product ) , not the DataContext ( ProductViewModel ) . So in the above instance , ProductViewModel validation is never called . This is just a simple example but illustrates the problem . The model does n't ( and should n't ) know about Temperature , so the design dictates that the VM should perform the validation on that field.Yes , I could hack it and replicate the bound properties of the model directly in the ViewModel , but I would have thought there must be an easier way to redirect the call to the VM rather than the model ? <code> public class Product { public int Rating { get ; set ; } ... } public class ProductViewModel : IDataErrorProvider { public int Temperature { get ; set ; } public Product CurrentProduct { get ; set ; } public string this [ string columnName ] { get { if ( columnName == `` Rating '' ) { if ( CurrentProduct.Rating > Temperature ) return `` Rating is too high for current temperature '' ; } return null ; } } } < TextBox Text= { Binding Path=CurrentProduct.Rating , ValidatesOnDataErrors=True } ... / > | IDataErrorInfo calling bound object rather than DataContext |
C_sharp : I have a Visual Studio extension that adds an property to the property grid of a project item . It is done by registering an extender provider like this : It works fine for C # and VB projects , but only for those ... Is it possible to make it work for all project types ? If not , where can I find the CATIDs of other project types ? <code> void RegisterExtenderProvider ( ) { var provider = new PropertyExtenderProvider ( _dte , this ) ; string name = PropertyExtenderProvider.ExtenderName ; RegisterExtenderProvider ( VSConstants.CATID.CSharpFileProperties_string , name , provider ) ; RegisterExtenderProvider ( VSConstants.CATID.VBFileProperties_string , name , provider ) ; } void RegisterExtenderProvider ( string extenderCatId , string name , IExtenderProvider extenderProvider ) { int cookie = _dte.ObjectExtenders.RegisterExtenderProvider ( extenderCatId , name , extenderProvider ) ; _registerExtenderProviders.Add ( cookie , extenderProvider ) ; } | Register an extender provider for all project types |
C_sharp : I have the below code and I 'm expecting a different result.I have excepted that following result : 100 ,110 ,120 , 200 , 500Console output ( real result ) I 'm wondering now about this +1 from where came ? <code> using System ; using System.Collections.Generic ; using System.Linq ; namespace ConsoleApplication11 { public class Program { static void Main ( string [ ] args ) { var values = new List < int > { 100 , 110 , 120 , 200 , 500 } ; // In my mind the result shall be like ( 100,0 ) = > 100 + 0 = 100 // In my mind the result shall be like ( 110,0 ) = > 110 + 0 = 110 etc . var sumLinqFunction = new Func < int , int , int > ( ( x , y ) = > x + y ) ; var outputs = values.Select ( sumLinqFunction ) ; foreach ( var o in outputs ) Console.WriteLine ( o ) ; } } } 100111122203504 | Unexpected results in Linq query always + 1 |
C_sharp : C # can not infer a type argument in this pretty obvious case : The JObject type clearly implements IEnumerable < KeyValuePair < string , JToken > > , but I get the following error : Why does this happen ? UPD : To the editor who marked this question as duplicate : please note how my method 's signature accepts not IEnumerable < T > , but IEnumerable < KeyValuePair < string , T > > . The JObject type implements IEnumerable twice , but only one of the implementations matches this constraint - so there should be no ambiguity.UPD : Here 's a complete self-contained repro without JObject : https : //gist.github.com/impworks/2eee2cd0364815ab8245b81963934642 <code> public void Test < T > ( IEnumerable < KeyValuePair < string , T > > kvp ) { Console.WriteLine ( kvp.GetType ( ) .Name + `` : KeyValues '' ) ; } Test ( new Newtonsoft.Json.Linq.JObject ( ) ) ; CS0411 : The type arguments for method can not be inferred from the usage . | Generic interface type inference weirdness in c # |
C_sharp : Because this is my first attempt at an extension method that seems quite useful to me , I just want to make sure I 'm going down the right route Called byEDIT : Some excellent suggestions coming through , exactly the sort of thing I was looking for . ThanksEDIT : I have decided on the following implementationI preferred using params over IEnumerable because it simplified the calling codeA far cry on the previousThank you again ! <code> public static bool EqualsAny ( this string s , string [ ] tokens , StringComparison comparisonType ) { foreach ( string token in tokens ) { if ( s.Equals ( token , comparisonType ) ) { return true ; } } return false ; } if ( queryString [ `` secure '' ] .EqualsAny ( new string [ ] { `` true '' , '' 1 '' } , StringComparison.InvariantCultureIgnoreCase ) ) { parameters.Protocol = Protocol.https ; } public static bool EqualsAny ( this string s , StringComparison comparisonType , params string [ ] tokens ) { // for the scenario it is more suitable for the code to continue if ( s == null ) return false ; return tokens.Any ( x = > s.Equals ( x , comparisonType ) ) ; } public static bool EqualsAny ( this string s , params string [ ] tokens ) { return EqualsAny ( s , StringComparison.OrdinalIgnoreCase , tokens ) ; } if ( queryString [ `` secure '' ] .EqualsAny ( `` true '' , '' 1 '' ) ) { parameters.Protocol = Protocol.https ; } if ( queryString [ `` secure '' ] ! = null ) { if ( queryString [ `` secure '' ] == `` true '' || queryString [ `` secure '' ] == `` 1 '' ) { parameters.Protocal = Protocal.https ; } } | My first extension method , could it be written better ? |
C_sharp : I am trying to print some information in a column-oriented way . Everything works well for Latin characters , but when Chinese characters are printed , the columns stop being aligned . Let 's consider an example : Output : As one can see , the Chinese is not aligned to columns.Important note : this is just a presentation of the problem ; it wo n't be used in a console app . Can anyone help me with this ? <code> var latinPresentation1 = `` some text '' .PadRight ( 30 ) + `` | `` + 23 ; var latinPresentation2 = `` some longer text '' .PadRight ( 30 ) + `` | `` + 23 ; Console.WriteLine ( latinPresentation1 ) ; Console.WriteLine ( latinPresentation2 ) ; Console.WriteLine ( `` ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... . '' ) ; var chinesePresentation1 = `` 一些文字 '' .PadRight ( 30 ) + `` | `` + 23 ; var chinesePresentation2 = `` 一些較長的文字 '' .PadRight ( 30 ) + `` | `` + 23 ; Console.WriteLine ( chinesePresentation1 ) ; Console.WriteLine ( chinesePresentation2 ) ; some text | 23some longer text | 23 ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... .一些文字 | 23一些較長的文字 | 23 | How do I format Chinese characters so they fit the columns ? |
C_sharp : What is wrong with this code : I compile this piece of code using this command : When I double click on the exe , it does n't seem to throw the exception ( StackOverFlowException ) , and keep running forever.Using visual studio command prompt 2010 , but I also have vs 2012 installed on the system , all up to date . <code> using System ; namespace app1 { static class Program { static int x = 0 ; static void Main ( ) { fn1 ( ) ; } static void fn1 ( ) { Console.WriteLine ( x++ ) ; fn1 ( ) ; } } } csc /warn:0 /out : app4noex.exe app4.cs | Why does n't this recursion produce a StackOverFlowException ? |
C_sharp : Hello I have an unusual date format that I would like to parse into a DateTime objectI would like to use DateTime.Tryparse ( ) but I cant seem to get started on this.Thanks for any help . <code> string date = '' 20101121 '' ; // 2010-11-21string time = '' 13:11:41 : //HH : mm : ss | How do I parse an unusual date string |
C_sharp : Consider this code : when I call emu.ElementAt ( size-10 ) and arr.ElementAt ( size-10 ) and measure the time the arr is much faster ( the array is 0.0002s compared to IEnumerable 0.59s ) . As I understand it , the extention method ElementAt ( ) have the signature and since the 'source ' is a IEnumerable the logic carried out would be similar - opposed to what I see where the array is accessed directly.Could someone please explain this : ) <code> int size = 100 * 1000 * 1000 ; var emu = Enumerable.Range ( 0 , size ) ; var arr = Enumerable.Range ( 0 , size ) .ToArray ( ) ; public static TSource ElementAt < TSource > ( this IEnumerable < TSource > source , int index ) | Understanding the extension ElementAt ( index ) |
C_sharp : Looking at the code : Looking at the `` Do stuff here '' section : What type of objects can I write in there so they can be Transactionable ? . I already know that I can write ADO commands and they will be rollback/commited when neccesary . But via C # POV : what implementation should a Class has to have in order to be Transactionable ( implementing some interface or something ? ) If it is a TransactionScope as it called , inside a using clause ( which is try + finally ) , The logic says that if there is a rollback : MyClass.g should get BACK its value of 1. however . this is not happening.So I guess it is related to the first question . How can I make MyClass Transactionable ? <code> class MyClass { public static int g=1 ; } using ( TransactionScope tsTransScope = new TransactionScope ( ) ) { //Do stuff here MyClass.g=999 ; tsTransScope.Complete ( ) ; } | Transactionable objects in C # ? |
C_sharp : I am using a Parallel.ForEach in this way : I am wondering if when paramIeCollection is empty , the Parallel.ForEach starts anyway and take threads from Thread Pool and consumes resources or if it first checks if there are items in the collection.If it does n't check , to avoid that , I am thinking in this code : So the question is , is it a good practice to check if the collection has items before calling Parallel.ForEach or if it is n't needed ? <code> public void myMethod ( IEnumerable < MyType > paramIeCollection ) { Parallel.Foreach ( paramIeCollection , ( iterator ) = > { //Do something } ) ; } if ( paramIeCollection.count > 0 ) { //run Parallel.Foreach } | Does Parallel.ForEach start threads if the source is empty ? |
C_sharp : I have been wondering whether it would be worth implementing weak events ( where they are appropriate ) using something like the following ( rough proof of concept code ) : Allowing other classes to subscribe and unsubscribe from events with the more conventional C # syntax whilst under the hood actually being implemented with weak references : Where the WeakEvent < TEventArgs > helper class is defined as follows : Is this a good approach ? are there any undesirable side effects to this approach ? <code> class Foo { private WeakEvent < EventArgs > _explodedEvent = new WeakEvent < EventArgs > ( ) ; public event WeakEvent < EventArgs > .EventHandler Exploded { add { _explodedEvent += value ; } remove { _explodedEvent -= value ; } } private void OnExploded ( ) { _explodedEvent.Invoke ( this , EventArgs.Empty ) ; } public void Explode ( ) { OnExploded ( ) ; } } static void Main ( string [ ] args ) { var foo = new Foo ( ) ; foo.Exploded += ( sender , e ) = > Console.WriteLine ( `` Exploded ! `` ) ; foo.Explode ( ) ; foo.Explode ( ) ; foo.Explode ( ) ; Console.ReadKey ( ) ; } public class WeakEvent < TEventArgs > where TEventArgs : EventArgs { public delegate void EventHandler ( object sender , TEventArgs e ) ; private List < WeakReference > _handlers = new List < WeakReference > ( ) ; public void Invoke ( object sender , TEventArgs e ) { foreach ( var handler in _handlers ) ( ( EventHandler ) handler.Target ) .Invoke ( sender , e ) ; } public static WeakEvent < TEventArgs > operator + ( WeakEvent < TEventArgs > e , EventHandler handler ) { e._handlers.Add ( new WeakReference ( handler ) ) ; return e ; } public static WeakEvent < TEventArgs > operator - ( WeakEvent < TEventArgs > e , EventHandler handler ) { e._handlers.RemoveAll ( x = > ( EventHandler ) x.Target == handler ) ; return e ; } } | Is it a good idea to implement a C # event with a weak reference under the hood ? |
C_sharp : I have encountered an interesting situation where I get NRE from Uri.TryCreate method when it 's supposed to return false.You can reproduce the issue like below : I guess it 's failing during the parse , but when I try `` http : A '' for example , it returns true and parses it as relative url . Even if fails on parse it should just return false as I understand , what could be the problem here ? This seems like a bug in the implementation cause documentation does n't mention about any exception on this method.The error occurs in .NET 4.6.1 but not 4.0 <code> Uri url ; if ( Uri.TryCreate ( `` http : Ç '' , UriKind.RelativeOrAbsolute , out url ) ) { Console.WriteLine ( `` success '' ) ; } | Why Uri.TryCreate throws NRE when url contains Turkish character ? |
C_sharp : I am working with WPF+MVVM.I have a VM which contains a Customer property . The Customer has an ObservableCollection of Orders . Each Order has an ObservableCollection of Items . Each Items has a Price.Now , I have the following property on my VM : The problem is whenever a change occurs at any point in this graph of objects - the UI should be notified that TotalPrice had changed - but it does n't ... For example if the Customer will be altered from A to B , or an order will be added , or an item will be deleted , or an item 's price will be altered etc.Does anyone has an elegant solution for this ? Thanks . <code> public double TotalPrice { return Customer.Orders.Sum ( x = > x.Items.Sum ( y = > y.Price ) ) ; } | MVVM property depends on a graph of objects |
C_sharp : If I implement an interface for a value type and try to cast it to a List of it 's interface type , why does this result in an error whereas the reference type converts just fine ? This is the error : Can not convert instance argument type System.Collections.Generic.List < MyValueType > to System.Collections.Generic.IEnumerable < MyInterfaceType > I have to explicitely use the Cast < T > method to convert it , why ? Since IEnumerable is a readonly enumeration through a collection , it does n't make any sense to me that it can not be cast directly.Here 's example code to demonstrate the issue : <code> public interface I { } public class T : I { } public struct V : I { } public void test ( ) { var listT = new List < T > ( ) ; var listV = new List < V > ( ) ; var listIT = listT.ToList < I > ( ) ; //OK var listIV = listV.ToList < I > ( ) ; //FAILS to compile , why ? var listIV2 = listV.Cast < I > ( ) .ToList ( ) ; //OK } | Why does ToList < Interface > not work for value types ? |
C_sharp : I 'm trying to write a really simple bit of async code . I have a void method that does n't take any parameters , which is to be called from a Windows service . I want to kick it off async , so that the service does n't have to hang around waiting for the method to finish.I created a very simple test app to make sure I was doing the coding right , but the async method just is n't being called . Anyone able to see what I 've done wrong ? I 'm using .NET 4.0 by the way , so I ca n't use await ( which would be a whole lot simpler ! ) .Here is my entire test sample ... Thanks for any help you can give . <code> using System ; using System.Threading ; namespace AsyncCallback { internal class Program { private static void Main ( string [ ] args ) { Console.WriteLine ( DateTime.Now.ToLocalTime ( ) .ToLongTimeString ( ) + `` - About to ask for stuff to be done '' ) ; new Action ( DoStuff ) .BeginInvoke ( ar = > StuffDone ( ) , null ) ; Console.WriteLine ( DateTime.Now.ToLocalTime ( ) .ToLongTimeString ( ) + `` - Asked for stuff to be done '' ) ; } private static void StuffDone ( ) { Console.WriteLine ( DateTime.Now.ToLocalTime ( ) .ToLongTimeString ( ) + `` - Stuff done '' ) ; } private static void DoStuff ( ) { Console.WriteLine ( DateTime.Now.ToLocalTime ( ) .ToLongTimeString ( ) + `` - Starting to do stuff '' ) ; Thread.Sleep ( 1000 ) ; Console.WriteLine ( DateTime.Now.ToLocalTime ( ) .ToLongTimeString ( ) + `` - Ending doing stuff '' ) ; } } } | Why does n't this C # 4.0 async method get called ? |
C_sharp : I 'd like to write a method which does some work and finally returns another method with the same signature as the original method . The idea is to handle a stream of bytes depending on the previous byte value sequentially without going into a recursion . By calling it like this : To handover the method I want to assign them to a Func delegate . But I ran into the problem that this results in a recursive declaration without termination ... I 'm somehow lost here . How could I get around that ? <code> MyDelegate executeMethod = handleFirstByte //What form should be MyDelegate ? foreach ( Byte myByte in Bytes ) { executeMethod = executeMethod ( myByte ) ; //does stuff on byte and returns the method to handle the following byte } Func < byte , Func < byte , < Func < byte , etc ... > > > | How do I declare a Func Delegate which returns a Func Delegate of the same type ? |
C_sharp : My C # skills are low , but I ca n't understand why the following fails : Then the code is as follows : Am I simply doing something wrong and not seeing it ? Since Order implements Quotable , a list of order would go in as IList of quoatables . I have something like in Java and it works , so I 'm pretty sure its my lack of C # knowledge . <code> public interface IQuotable { } public class Order : IQuotable { } public class Proxy { public void GetQuotes ( IList < IQuotable > list ) { ... } } List < Order > orders = new List < Orders > ( ) ; orders.Add ( new Order ( ) ) ; orders.Add ( new Order ( ) ) ; Proxy proxy = new Proxy ( ) ; proxy.GetQuotes ( orders ) ; // produces compile error | C # generics and interfaces and simple OO |
C_sharp : I am currently working on an multiplayer shooter game . Basicly atm you play as a cube and you have your hand ( red square ) following the cursor ingame . I want to restrict the cursor movement to a perfect circle around my player sprite.See attached picture for clarification . https : //imgur.com/TLliade Following script is attached to the `` Hand '' ( red square ) .Now I want to restrict cursor movement inside my radius that is a public transform attached to my Player prefab like this : I am hard stuck and new to coding overall and I could use a push in the right direction . Basicly the same question is asked here if I am being to unclear : https : //answers.unity.com/questions/1439356/limit-mouse-movement-around-player.htmlEDIT : My goal in the end is to have similar hand movement as in the legendary `` Madness Interactive '' game , found here : https : //www.newgrounds.com/portal/view/118826EDIT2 : It might be impossible to lock the cursor inside the radius circle . Is it possible to just have the GameObject `` Hand '' locked inside this radius ? EDIT3 : This is the code I use and it works like a charm : <code> public class Handscript : MonoBehaviour { void Update ( ) { Cursor.visible = false ; Vector3 a = Camera.main.ScreenToWorldPoint ( new Vector3 ( Input.mousePosition.x , Input.mousePosition.y , 0 ) ) ; a.Set ( a.x , a.y , transform.position.z ) ; transform.position = Vector3.Lerp ( transform.position , a , 1f ) ; } } //Hand radius public float radius ; public Transform centerRadius ; using System ; using UnityEngine ; public class Handscript : Photon.MonoBehaviour { [ SerializeField ] private GameObject Player2 ; //Drag your player game object here for its position [ SerializeField ] private float radius ; //Set radius here public new PhotonView photonView ; //Never mind this if its not a photon project private void Start ( ) { Cursor.visible = false ; } void Update ( ) { if ( photonView.isMine ) //Never mind this if statement if it isnt a photon project { Vector3 cursorPos = Camera.main.ScreenToWorldPoint ( new Vector3 ( Input.mousePosition.x , Input.mousePosition.y , 0 ) ) ; Vector3 playerPos = Player2.transform.position ; Vector3 playerToCursor = cursorPos - playerPos ; Vector3 dir = playerToCursor.normalized ; Vector3 cursorVector = dir * radius ; if ( playerToCursor.magnitude < cursorVector.magnitude ) // detect if mouse is in inner radius cursorVector = playerToCursor ; transform.position = playerPos + cursorVector ; } } # if UNITY_EDITOR private void OnDrawGizmosSelected ( ) { UnityEditor.Handles.DrawWireDisc ( transform.parent.position , Vector3.back , radius ) ; // draw radius } # endif } | Restricting cursor to a radius around my Player |
C_sharp : The code inspection of Resharper suggests to use var in C # instead of explicit type pretty much everywhere . I do n't like that option because too much var makes things unclear so I 've disabled that option . However where i do like to use var is in cases of initializations with two times the type on the same line with generics ( so in similar situations as the diamond operator from java 7 ) , like : I made a custom pattern in Resharper : with a replace to : This works fine , but the pattern also finds lines that are already converted with the rule . Why and how do I fix that ? Edit : put part of the text in bold because nobody appears to read it . <code> Dictionary < string string > dic = new Dictionary < string , string > ( ) ; // I want a suggestion to replace this tovar dic = new Dictionary < string , string > ( ) ; // but I do n't want to replace things like this : Person p = new Person ( ) ; Dictionary < $ type1 $ , $ type2 $ > $ id $ = new Dictionary < $ type1 $ , $ type2 $ > ( ) ; var $ id $ = new Dictionary < $ type1 $ , $ type2 $ > ( ) ; | Resharper custom pattern var |
C_sharp : In the code below , the `` Console.WriteLine '' call needs the `` System '' using directive to work . I already have a UsingDirectiveSyntax object for `` using System '' and an InvocationExpressionSyntax object for `` Console.Writeline '' . But how can I know , using Roslyn , that the InvocationExpressionSyntax and UsingDirectiveSyntax objects belong to each other ? <code> using System ; public class Program { public static void Main ( ) { Console.WriteLine ( `` Hello World '' ) ; } } | Find UsingDirectiveSyntax that belongs to InvocationExpressionSyntax |
C_sharp : I have the following codeI have these SubA and SubB classes which inherits from Base class , you can see that i have a code that repeating it self which is setting the Time , is there a way to move the setting of the time to the base class ? <code> internal abstract class Base { public DateTime Time ; public string Message ; public string Log ; public abstract void Invoke ( string message ) ; } internal class SubA : Base { public override void Invoke ( string message ) { Time = DateTime.Now ; // Do A } } internal class SubB : Base { public override void Invoke ( string message ) { Time = DateTime.Now ; // Do B } } | Abstract class , how to avoid code duplication ? |
C_sharp : I 'm having a problem withWhen the DoSomething gets executed , it receives the latest value for each captured variable instead of the value I desired . I can imagine a solution for this , but it imagine you guys can come up with better solutions <code> foreach ( var category in categories ) { foreach ( var word in words ) { var waitCallback = new WaitCallback ( state = > { DoSomething ( word , category ) ; } ) ; ThreadPool.QueueUserWorkItem ( waitCallback ) ; } } | How to avoid captured variables ? |
C_sharp : Given the following class : I am torn apart between two ways to chain those constructors : The first one : The second one : So , is it better to chain from the parameterless constructor or the other way around ? <code> public class MyClass { private string _param ; public MyClass ( ) { _param = string.Empty ; } public MyClass ( string param ) { _param = param ; } } public MyClass ( ) : this ( string.Empty ) { } public MyClass ( string param ) { _param = param ; } public MyClass ( ) { _param = string.Empty ; } public MyClass ( string param ) : this ( ) { _param = param ; } | In C # , what is the best/accepted way of doing constructor chaining ? |
C_sharp : What is the correct term/name for the following construction : <code> string myString = ( boolValue==true ? `` true '' : `` false '' ) ; | What is the name of this code construction : condition ? true_expression : false_expression |
C_sharp : I have a website containing news stories . Each story has a list of tags associated with it . Other pages on the site also have a list of tags.On one of the other pages I want to list all the news stories that have one or more tags in common with the list of tags on the current page.I have written some Linq code that compares a single tag to the tags on each of the news stories but I need to extend it so that it works with a list of tags.What I want to do is replace currentTag with a list of tags . The list can contain between 1 and 6 tags . Can anyone help ? <code> query = query.Where ( x = > x.Tags.Contains ( currentTag ) ) ; | Using Linq to compare a list with a set of lists in C # |
C_sharp : Let me preface this by saying , I am noob , and I know not what I do . So , if there is a better way of doing this , I am all ears . Currently , I am working on project for which I need to be able to coerce a data source into a List < T > , where T is an anonymous type , and filter it using lambda expressions , or create lambda expressions on the fly , save them to a database . I have already created a static wrapper class for System.Linq.Dynamic.Core , called RunTimeType , that has methods which allow me to create an anonymous type from some data source , and then create a List < > of that anonymous type . After both of the anontype and List < anontype > are created , I am using an existing fluent interface to create an Expression < Func < T , bool > > . Once I build the Expression and compile it , I either want to execute it , or I want to convert it to a string and save it to a database , xml file , etc. , for later use . Case 1 : When compiling and then immediately executing the expression , I am good up until this line : var testList = anonList.Where ( castedExp ) .ToList ( ) ; where i recieve the following error : Error CS1973 C # has no applicable method named 'Where ' but appears to have an extension method by that name . Extension methods can not be dynamically dispatched . Consider casting the dynamic arguments or calling the extension method without the extension method syntax.This makes sense , because filter is declared as a dynamic , which I am forced to do , otherwise compiler would complain with the following : Error CS1061 'object ' does not contain a definition for 'By ' and no accessible extension method 'By ' accepting a first argument of type 'object ' could be found ( are you missing a using directive or an assembly reference ? ) Case2 : As for the case of building the expression , converting it to a string , and then compiling to a valid Func < T , TResult > , I am good up until this line : var castedExp = ( Func < dynamic , bool > ) compileExp ; where i recieve the following error : Error System.InvalidCastException 'System.Func2 [ < > f__AnonymousType02 [ System.String , System.String ] , System.Boolean ] ' to type 'System.Func ` 2 [ System.Object , System.Boolean ] ' . 'However , I know that if I do n't explicity cast to Func < dynamic , bool > , the compiler will complain with the following : Error CS1503 Argument 2 : can not convert from 'System.Delegate ' to 'System.Func < dynamic , bool > ' . So , my question is , how do I get around both of these situations , while still maintaining the ability use the anonymous type . Just to clarify again , I am forced to create an anonymous type because , I will not know what data set that I will be getting at run time , as these data sets are completely dynamic . I want to reiterate , that I am open to doing this in a different way as long as the project 's constraints are met . Frankly , I have been working on this for a while , I am out of ideas , and I need some guidance . Below is all of the relevant code . Test code : RunTimeType Class : ( for brevity , I have omitted the the overloads for the Create and CreateGenericList methods ) Update : I incorporated @ CSharpie 's answer , and tailored it to fit my implementation . Everything compiles , however , I am not getting the correct output ( see comments in code body ) . Final Update : For those that are interested , I finally got this working . I figured out that my CreateGenericList method , was returning a list of only the first instance of my anonymous type . Saying that CreateGenericList should be become : Reference : https : //github.com/StefH/System.Linq.Dynamic.Core/blob/master/src/System.Linq.Dynamic.Core/DynamicClass.csAnd then Main becomes : <code> using System ; using System.Collections.Generic ; using System.Linq.Expressions ; using ExpressionBuilder.Generics ; using ExpressionBuilder.Common ; using System.Linq ; using System.Linq.Dynamic ; using System.Linq.Dynamic.Core ; using ExpressionBuilterTest.TestImplementations ; namespace ExpressionBuilterTest { class Program { static void Main ( string [ ] args ) { //test Data source object [ , ] arrayTest = new object [ 3 , 2 ] ; arrayTest [ 0 , 0 ] = `` Field1 '' ; arrayTest [ 1 , 0 ] = `` X1 '' ; arrayTest [ 2 , 0 ] = `` Y1 '' ; arrayTest [ 0 , 1 ] = `` Field2 '' ; arrayTest [ 1 , 1 ] = `` X2 '' ; arrayTest [ 2 , 1 ] = `` Y2 '' ; var anonType = RunTimeType.Create ( arrayTest ) ; var anonList = RunTimeType.CreateGenericList ( anonType , arrayTest ) ; //Creation of List < anonymous > type var anonList = CreateGenericList ( anonType , arrayTest ) ; //Creation of List < anonymous > type Type genericFilter = typeof ( Filter < > ) ; Type constructedClass = genericFilter.MakeGenericType ( anonType ) ; //*************************Case 1************************* /* use dynamic otherwise compiler complains about accessing methods on the instance of the filter object */ dynamic filter = Activator.CreateInstance ( constructedClass ) ; filter.By ( `` Field1 '' , Operation.Contains , `` X1 `` ) .Or.By ( `` Field2 '' , Operation.Contains , `` X2 `` ) ; //returns Expression < Func < T , bool > > var lamda = filter.GetExpression ( ) ; //Error CS1973 IEnumerable < dynamic > testList = anonList.Where ( castedExp ) .ToList ( ) ; Console.WriteLine ( testList.Count ( ) .ToString ( ) ) ; Console.WriteLine ( `` \n '' ) ; //*************************Case 2************************* //convert to string string expString = lamda.Body.ToString ( ) .Replace ( `` AndAlso '' , `` & & '' ) .Replace ( `` OrElse '' , `` || '' ) ; // simulation of compiling an expression from a string which would be returned from a database var param = Expression.Parameter ( anonType , ExpressionParameterName.Parent ) ; var exp = System.Linq.Dynamic.DynamicExpression.ParseLambda ( new ParameterExpression [ ] { param } , typeof ( bool ) , expString ) ; var compiledExp = exp.Compile ( ) ; //******************************************************* //Error CS1973 'System.Func ` 2 [ < > f__AnonymousType0 ` 2 [ System.String , System.String ] , System.Boolean ] ' to type 'System.Func ` 2 [ System.Object , System.Boolean ] ' . ' var castedExp = ( Func < dynamic , bool > ) compileExp ; //******************************************************* var testList2 = anonList.Where ( castedExp ) .ToList ( ) ; Console.WriteLine ( testList2.Count ( ) .ToString ( ) ) ; Console.ReadKey ( ) ; } } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Linq.Dynamic.Core ; using System.Runtime.CompilerServices ; namespace ExpressionBuilterTest.TestImplementations { public static class RunTimeType { /// < summary > /// Creates an anonymous type from a 2d array that includes headers /// < /summary > public static Type Create < T > ( T [ , ] fieldNameAndValues ) { IList < System.Linq.Dynamic.Core.DynamicProperty > properties = new List < System.Linq.Dynamic.Core.DynamicProperty > ( ) ; int columnCount = fieldNameAndValues.GetLength ( 1 ) ; for ( int jj = 0 ; jj < columnCount ; jj++ ) properties.Add ( new System.Linq.Dynamic.Core.DynamicProperty ( fieldNameAndValues [ 0 , jj ] .ToString ( ) , fieldNameAndValues [ 1 , jj ] .GetType ( ) ) ) ; return DynamicClassFactory.CreateType ( properties ) ; } /// < summary > /// Creates an IEnumerable < dynamic > , where dynamic is an anonymous type , from a 2d array /// < /summary > /// < param name= '' type '' > Anonymous type < /param > /// < param name= '' data '' > 2 dimensional array of data < /param > public static IEnumerable < dynamic > CreateGenericList < T > ( Type anonType , T [ , ] data ) { ThrowIfNotAnonymousType ( anonType ) ; dynamic dynoObject = Activator.CreateInstance ( anonType ) ; var fieldNames = dynoObject.GetDynamicMemberNames ( ) ; Type genericListType = typeof ( List < > ) ; Type constructedClass = genericListType.MakeGenericType ( anonType ) ; dynamic list = ( IEnumerable < dynamic > ) Activator.CreateInstance ( constructedClass ) ; int rowCount = data.GetLength ( 0 ) ; int jj ; for ( int ii = 1 ; ii < rowCount ; ii++ ) //skip first row { jj = 0 ; foreach ( var field in fieldNames ) anonType.GetProperty ( field ) .SetValue ( dynoObject , data [ ii , jj ] , null ) ; jj++ ; list.Add ( dynoObject ) ; } return list ; } private static void ThrowIfNotAnonymousType ( Type type ) { if ( ! IsAnonymousType ( type ) ) throw new Exception ( `` 'anonType ' must be an anonymous type '' ) ; } //https : //stackoverflow.com/questions/1650681/determining-whether-a-type-is-an-anonymous-type private static Boolean IsAnonymousType ( Type type ) { Boolean hasCompilerGeneratedAttribute = type.GetCustomAttributes ( typeof ( CompilerGeneratedAttribute ) , false ) .Count ( ) > 0 ; Boolean nameContainsAnonymousType = type.FullName.Contains ( `` AnonymousType '' ) ; Boolean isAnonymousType = hasCompilerGeneratedAttribute & & nameContainsAnonymousType ; return isAnonymousType ; } } } static void Main ( string [ ] args ) { object [ , ] arrayTest = new object [ 3 , 2 ] ; arrayTest [ 0 , 0 ] = `` Field1 '' ; arrayTest [ 1 , 0 ] = `` X1 '' ; arrayTest [ 2 , 0 ] = `` Y1 '' ; arrayTest [ 0 , 1 ] = `` Field2 '' ; arrayTest [ 1 , 1 ] = `` X2 '' ; arrayTest [ 2 , 1 ] = `` Y2 '' ; var anonType = RunTimeType.Create ( arrayTest ) ; var anonList = RunTimeType.CreateGenericList ( anonType , arrayTest ) ; Type targetType = anonType ; Type genericFilter = typeof ( Filter < > ) ; Type constructedClass = genericFilter.MakeGenericType ( targetType ) ; dynamic filter = Activator.CreateInstance ( constructedClass ) ; //Dynamically build expression filter.By ( `` Field1 '' , Operation.Contains , `` X '' ) .Or.By ( `` Field2 '' , Operation.Contains , `` 2 '' ) ; //Returns Expression < Func < anonType , bool > > var lamda = filter.GetExpression ( ) ; string expString = lamda.Body.ToString ( ) ; expString = expString.Replace ( `` AndAlso '' , `` & & '' ) .Replace ( `` OrElse '' , `` || '' ) ; /* Prints : ( ( ( x.Field1 ! = null ) & & x.Field1.Trim ( ) .ToLower ( ) .Contains ( `` X '' .Trim ( ) .ToLower ( ) ) ) || ( ( x.Field2 ! = null ) & & x.Field2.Trim ( ) .ToLower ( ) .Contains ( `` 2 '' .Trim ( ) .ToLower ( ) ) ) ) */ Console.WriteLine ( expString ) ; ParameterExpression param = Expression.Parameter ( targetType , ExpressionParameterName.Parent ) ; LambdaExpression exp = System.Linq.Dynamic.DynamicExpression.ParseLambda ( new ParameterExpression [ ] { param } , typeof ( bool ) , expString ) ; Delegate compileExp = exp.Compile ( ) ; MethodInfo whereMethod = typeof ( Enumerable ) .GetMethods ( ) .Single ( m = > { if ( m.Name ! = `` Where '' || ! m.IsStatic ) return false ; ParameterInfo [ ] parameters = m.GetParameters ( ) ; return parameters.Length == 2 & & parameters [ 1 ] .ParameterType.GetGenericArguments ( ) .Length == 2 ; } ) ; MethodInfo finalMethod = whereMethod.MakeGenericMethod ( anonType ) ; IEnumerable resultList = ( IEnumerable ) finalMethod.Invoke ( null , new object [ ] { anonList , compileExp } ) ; /* Prints Nothing but should print the following : X1 X2 */ foreach ( dynamic val in resultList ) { Console.WriteLine ( val.Field1 + `` /t '' + val.Field2 ) ; } Console.ReadKey ( ) ; } /// < summary > /// Creates an IEnumerable < dynamic > , where dynamic is an anonymous type , from a 2d array /// < /summary > /// < param name= '' type '' > Anonymous type < /param > /// < param name= '' data '' > 2 dimensional array of data < /param > public static IEnumerable < dynamic > CreateGenericList < T > ( Type anonType , T [ , ] data ) { ThrowIfNotAnonymousType ( anonType ) ; Type genericListType = typeof ( List < > ) ; Type constructedClass = genericListType.MakeGenericType ( anonType ) ; dynamic list = ( IEnumerable < dynamic > ) Activator.CreateInstance ( constructedClass ) ; //first instance dynamic dynoObject = Activator.CreateInstance ( anonType ) ; //System.Linq.Dynamic.Core.DynamicClass.GetDynamicMemberNames ( ) var fieldNames = dynoObject.GetDynamicMemberNames ( ) ; int rowCount = data.GetLength ( 0 ) ; int jj ; for ( int ii = 1 ; ii < rowCount ; ii++ ) //skip first row { jj = 0 ; foreach ( var field in fieldNames ) { //System.Linq.Dynamic.Core.DynamicClass.SetDynamicPropertyValue ( ) dynoObject.SetDynamicPropertyValue ( field , data [ ii , jj ] ) ; jj++ ; } list.Add ( dynoObject ) ; //create a new instance for each iteration of the loop dynoObject = Activator.CreateInstance ( anonType ) ; } return list ; } static void Main ( string [ ] args ) { object [ , ] arrayTest = new object [ 3 , 2 ] ; arrayTest [ 0 , 0 ] = `` Field1 '' ; arrayTest [ 1 , 0 ] = `` X1 '' ; arrayTest [ 2 , 0 ] = `` blah '' ; arrayTest [ 0 , 1 ] = `` Field2 '' ; arrayTest [ 1 , 1 ] = `` Y1 '' ; arrayTest [ 2 , 1 ] = `` Y2 '' ; var anonType = RunTimeType.Create ( arrayTest ) ; var anonList = RunTimeType.CreateGenericList ( anonType , arrayTest ) ; Type genericFilter = typeof ( Filter < > ) ; Type constructedClass = genericFilter.MakeGenericType ( anonType ) ; dynamic filter = Activator.CreateInstance ( constructedClass ) ; //Dynamically build expression filter.By ( `` Field1 '' , Operation.Contains , `` blah '' ) .Or.By ( `` Field2 '' , Operation.Contains , `` 2 '' ) ; //Returns Expression < Func < anonType , bool > > var lamda = filter.GetExpression ( ) ; //Prints : System.Func ` 2 [ < > f__AnonymousType0 ` 2 [ System.String , System.String ] , System.Boolean ] Console.WriteLine ( lamda.Compile ( ) .ToString ( ) ) ; Console.WriteLine ( `` \n '' ) ; string expBodyString = lamda.Body.ToString ( ) ; /* Prints : ( ( ( x.Field1 ! = null ) AndAlso x.Field1.Trim ( ) .ToLower ( ) .Contains ( `` blah '' .Trim ( ) .ToLower ( ) ) ) OrElse ( ( x.Field2 ! = null ) AndAlso x.Field2.Trim ( ) .ToLower ( ) .Contains ( `` 2 '' .Trim ( ) .ToLower ( ) ) ) ) */ Console.WriteLine ( expBodyString ) ; Console.WriteLine ( `` \n '' ) ; expBodyString = expBodyString.Replace ( `` AndAlso '' , `` & & '' ) .Replace ( `` OrElse '' , `` || '' ) ; /* Prints : ( ( ( x.Field1 ! = null ) & & x.Field1.Trim ( ) .ToLower ( ) .Contains ( `` blah '' .Trim ( ) .ToLower ( ) ) ) || ( ( x.Field2 ! = null ) & & x.Field2.Trim ( ) .ToLower ( ) .Contains ( `` 2 '' .Trim ( ) .ToLower ( ) ) ) ) */ Console.WriteLine ( expBodyString ) ; Console.WriteLine ( `` \n '' ) ; ParameterExpression param = Expression.Parameter ( anonType , ExpressionParameterName.Parent ) ; LambdaExpression exp = System.Linq.Dynamic.Core.DynamicExpressionParser.ParseLambda ( new ParameterExpression [ ] { param } , typeof ( bool ) , expBodyString ) ; /* Prints : ( ( ( x.Field1 ! = null ) AndAlso x.Field1.Trim ( ) .ToLower ( ) .Contains ( `` blah '' .Trim ( ) .ToLower ( ) ) ) OrElse ( ( x.Field2 ! = null ) AndAlso x.Field2.Trim ( ) .ToLower ( ) .Contains ( `` 2 '' .Trim ( ) .ToLower ( ) ) ) ) */ Console.WriteLine ( exp.Body.ToString ( ) ) ; Console.WriteLine ( `` \n '' ) ; Delegate compileExp = exp.Compile ( ) ; //Prints : System.Func ` 2 [ < > f__AnonymousType0 ` 2 [ System.String , System.String ] , System.Boolean ] Console.WriteLine ( compileExp.ToString ( ) ) ; Console.WriteLine ( `` \n '' ) ; MethodInfo whereMethod = typeof ( Enumerable ) .GetMethods ( ) .Single ( m = > { if ( m.Name ! = `` Where '' || ! m.IsStatic ) return false ; ParameterInfo [ ] parameters = m.GetParameters ( ) ; return parameters.Length == 2 & & parameters [ 1 ] .ParameterType.GetGenericArguments ( ) .Length == 2 ; } ) ; MethodInfo finalMethod = whereMethod.MakeGenericMethod ( anonType ) ; IEnumerable resultList = ( IEnumerable ) finalMethod.Invoke ( null , new object [ ] { anonList , compileExp } ) ; //Prints : blah Y2 foreach ( dynamic val in resultList ) { Console.WriteLine ( val.Field1 + `` \t '' + val.Field2 ) ; } Console.ReadKey ( ) ; } | How to handle casting delegate of anonymous type < T > , to delegate of T for use in Where < T > ( ) method of an IEnumerable < T > |
C_sharp : I want to know what is purpose of '\ ' in vb ? I have this statement : and I want to convert it to C # .Please suggest . <code> frontDigitsToKeep \ 2 | \ operator in VB |
C_sharp : I have a centralized StructureMap configuration that various user interface applications append to . I have never had the need to modify the `` core '' configuration only append to it . I 've run into an instance today where I need to modify / remove the core configuration for a particular application . Of course I could move the core configuration code out to the different application , but before I do so I wanted to be sure I was not missing something obvious with the StructureMap api . Below is an abbreviated version of my core configuration : At runtime for this one application I would like to remove the configuration for types closing IValidationRule , but have yet to come up with anything viable . All of the eject methods seem to center around singletons meaning . Since I am not dealing with a singleton the following does not work : Is there a way that I can modify my StructureMap configuration to not look for IValidationRules ? Can I eject non-singleton instances of IValidationRules ? Do I have other options for modifying my StructureMap configuration ? <code> ObjectFactory.Initialize ( cfg = > { cfg.Scan ( scan = > { scan.Assembly ( `` Core '' ) ; scan.WithDefaultConventions ( ) ; scan.ConnectImplementationsToTypesClosing ( typeof ( IValidationRule < > ) ) ; // more after this ... . } } ObjectFactory.Model.For ( typeof ( IValidationRule < > ) ) .EjectAndRemoveAll ( ) ; //no workObjectFactory.Model.EjectAndRemove ( typeof ( IValidationRule < > ) ) ; //nor does this | How can I modify a previously configured StructureMap configuration ? |
C_sharp : I do n't have very much background regarding COM nor coclasses , so I do n't quite understand why I can use the new operator with an interface . From a language/framework-agnostic view , it 's confusing why this compiles and runs correctly : Inspecting Application in Visual Studio 2010 shows me : What is going on behind the scenes ? <code> using Microsoft.Office.Interop.Excel ; public class ExcelProgram { static void Main ( string [ ] args ) { Application excel = new Application ( ) ; } } using System.Runtime.InteropServices ; namespace Microsoft.Office.Interop.Excel { // Summary : // Represents the entire Microsoft Excel application . [ Guid ( `` 000208D5-0000-0000-C000-000000000046 '' ) ] [ CoClass ( typeof ( ApplicationClass ) ) ] public interface Application : _Application , AppEvents_Event { } } | Why is it possible to create a new instance of a COM interface ? |
C_sharp : It seems these two declarations are the same : andBut what is the need of this part new int [ ] in the second sample ? Does it make difference ? <code> int [ ] array1 = { 11 , 22 , 33 } ; int [ ] array2 = new int [ ] { 11 , 22 , 33 } ; | What is difference between these two array declarations ? |
C_sharp : I created a very simple event publisher and it looks like this.Here is what I have to publish messages.The issue I 'm having is that publishing a message is n't finding any handlers that can handle the payload . This makes sense because I registered my subscribers as Func < IHandle > instead of Func < IHandle < T > > .The interface my handler classes are inheriting from is from Caliburn.Micro.EventAggregator and it looks like this.What must the type of _subscribers be to handle the IHandle < > where the generic type can be any concrete type ? <code> public class EventPublisher { private readonly IList < Func < IHandle > > _subscribers ; public EventPublisher ( IList < Func < IHandle > > subscribers ) { _subscribers = subscribers ; } public void Publish < TPayload > ( TPayload payload ) where TPayload : class { var payloadHandlers = _subscribers.OfType < Func < IHandle < TPayload > > > ( ) ; foreach ( var payloadHandler in payloadHandlers ) { payloadHandler ( ) .Handle ( payload ) ; } } } var subscribers = new List < Func < IHandle > > { ( ) = > new SomeHandler ( ) } ; var eventPublisher = new EventPublisher ( subscribers ) ; eventPublisher.Publish ( new SomeMessage { Text = `` Some random text ... '' } ) ; public interface IHandle { } public interface IHandle < TMessage > : IHandle { void Handle ( TMessage message ) ; } | Is it possible to use an open generic as constructor argument ? |
C_sharp : I have a method , shown below , which calls a service.How can I run this method through thread ? <code> public List < AccessDetails > GetAccessListOfMirror ( string mirrorId , string server ) { List < AccessDetails > accessOfMirror = new List < AccessDetails > ( ) ; string loginUserId = SessionManager.Session.Current.LoggedInUserName ; string userPassword = SessionManager.Session.Current.Password ; using ( Service1Client client = new Service1Client ( ) ) { client.Open ( ) ; accessOfMirror = client.GetMirrorList1 ( mirrorId , server , null ) ; } return accessOfMirror ; } | can a method with return type as list be called from a thread |
C_sharp : Edit : fixed several syntax and consistency issues to make the code a little more apparent and close to what I actually am doing.I 've got some code that looks like this : where the DoSomething method is an extension method , and it expects a Func passed into it . So , each of the method calls in each of the DoSomething = > lambda 's returns a Result type.this is similar to a Maybe monad . Except instead of checking for nulls , I am checking the status of the Result class , and either calling the Func that was passed into DoSomething or returning the previous Result without calling the Functhe problem i face is that want to have this kind of composition in my code , but i also need to be able to pass data from one of the composed call results into the call of another , as you can see with the someClass variable.My question is n't whether or not this is technically correct ... i know this works , because I 'm currently doing it . My question is whether or not this is an abuse of closures , or command-query separation , or any other principles ... and then to ask what better patterns there are for handling this situation , because I 'm fairly sure that I 'm stuck in a `` shiny new hammer '' mode with this type of code , right now . <code> SomeClass someClass ; var finalResult = DoSomething ( ( ) = > { var result = SomeThingHappensHere ( ) ; someClass = result.Data ; return result ; } ) .DoSomething ( ( ) = > return SomeOtherThingHappensHere ( someClass ) ) .DoSomething ( ( ) = > return AndYetAnotherThing ( ) ) .DoSomething ( ( ) = > return AndOneMoreThing ( someClass ) ) .Result ; HandleTheFinalResultHere ( finalResult ) ; | Abuse of Closures ? Violations of various principles ? Or ok ? |
C_sharp : I have a struct like this , with an explicit conversion to float : I can convert a TwFix32 to int with a single explicit cast : ( int ) fix32But to convert it to decimal , I have to use two casts : ( decimal ) ( float ) fix32There is no implicit conversion from float to either int or decimal . Why does the compiler let me omit the intermediate cast to float when I 'm going to int , but not when I 'm going to decimal ? <code> struct TwFix32 { public static explicit operator float ( TwFix32 x ) { ... } } | Why do I need an intermediate conversion to go from struct to decimal , but not struct to int ? |
C_sharp : I have a number , for example 1234567897865 ; how do I max it out and create 99999999999999 ? I did this this way : what would be the better , proper and shorter way to approach this task ? <code> int len = ItemNo.ToString ( ) .Length ; String maxNumString = `` '' ; for ( int i = 0 ; i < len ; i++ ) { maxNumString += `` 9 '' ; } long maxNumber = long.Parse ( maxNumString ) ; | How to get the maximum number of a particular length |
C_sharp : which is better ? ? ? or <code> public class Order { private double _price ; private double _quantity ; public double TotalCash { get { return _price * _quantity ; } } public class Order { private double _totalCash ; private double _price ; private double _quantity ; private void CalcCashTotal ( ) { _totalCash = _price * _quantity } public double Price { set { _price = value ; CalcCashTotal ( ) ; } } public double Quantity { set { _price = value ; CalcCashTotal ( ) ; } } public double TotalCash { get { return _totalCash ; } } | do you put your calculations on your sets or your gets . |
C_sharp : Say I have a simple ( the simplest ? ) C # program : If , I compile that code and look at the resultant .exe , I see the `` Hello , world '' string in the exe image as expected.If I refactor the code to : If I compile that code and look at the resultant .exe , I see the `` Hello , world '' string literal in the exe image twice . This was surprising to me . I was under the impression that string literals were shared , and that it would therefor only show up in the image one time . Can anyone explain this ? Perhaps this second copy of the string is needed for reflection metadata ? <code> class Program { static void Main ( ) { System.Console.WriteLine ( `` Hello , world '' ) ; } } class Program { const string Greeting = `` Hello , world '' ; static void Main ( ) { System.Console.WriteLine ( Greeting ) ; } } | String constants embedded twice in .Net ? |
C_sharp : I wish to programatically unsubscribe to an event , which as been wired up.I wish to know how I can unsubscribe to the EndRequest event.I 'm not to sure how to do this , considering i 'm using inline code . ( is that the correct technical term ? ) I know i can use the some.Event -= MethodName to unsubscribe .. but I do n't have a method name , here.The reason I 'm using the inline code is because I wish to reference a variable defined outside of the event ( which I required .. but feels smelly ... i feel like I need to pass it in ) .Any suggestions ? Code time..This is just some sample code I have , for me to handle errors in a ASP.NET application.NOTE : Please do n't turn this into a discussion about ASP.NET error handling . I 'm just playing around with events and using these events for some sample R & D / learning . <code> public void Init ( HttpApplication httpApplication ) { httpApplication.EndRequest += ( sender , e ) = > { if ( some logic ) HandleCustomErrors ( httpApplication , sender , e , ( HttpStatusCode ) httpApplication.Response.StatusCode ) ; } ; httpApplication.Error += ( sender , e ) = > HandleCustomErrors ( httpApplication , sender , e ) ; } private static void HandleCustomErrors ( HttpApplication httpApplication , object sender , EventArgs e , HttpStatusCode httpStatusCode = HttpStatusCode.InternalServerError ) { ... } | How can I unsubscribe to this .NET event ? |
C_sharp : I 'm having a bit of performance problem with an EF query.We basically have this : Now , I would like to do : The problem is that , from what I can gather , this first causes the entire list being fetched , and then the count of it . When doing this in a loop this creates a performance problem.I assumed that it was due to the object being `` too concrete '' , so I 've tried to move the Visits.Count call as far back in repository as I can ( so that we 're sort of working directly with the DbContext ) . That did n't help.Any suggestions ? <code> public class Article { public int ID { get ; set ; } public virtual List < Visit > Visits { get ; set ; } } public class Visit { public int ? ArticleID { get ; set ; } public DateTime Date { get ; set ; } } Article a = ... ; vm.Count = a.Visits.Count ; | How to get count of lazy list in most efficient way ? |
C_sharp : I want to do something like this : However , I can not write a function like this : This does n't work , for some reason one can not use ref and params at the same time . Why so ? edit : OK , here 's some more information on why I need this : Through an Interface I get a lot of strings containing values , with a syntax like this : ( names in brackets are optional ) . Those values need to be parsed and stored in all specific variables . That is - they are not arrays at all . They are more like command-line arguments , but around 20 of them . I can of course do all that sequencially , but that produces hundreds of lines of code that contain a redundant pattern and are not well maintainable . <code> double a , b , c , d , e ; ParseAndWrite ( `` { 1 , 2 , 3 } '' , ref a , ref b , ref c ) ; ParseAndWrite ( `` { 4 , 5 } '' , ref d , ref e ) ; - > a = 1 , b = 2 , c = 3 , d = 4 , e = 5 private void ParseAndWrite ( string leInput , params ref double [ ] targets ) { ( ... ) } inputConfig : `` step , stepHeight , rStep , rStepHeight , ( nIterations , split , smooth ) `` outputConfig : `` dataSelection , ( corrected , units , outlierCount , restoreOriginalRange ) `` | Why ca n't I pass a various numbers of references to a function ? |
C_sharp : I have this asynchronous request : The problem is that I do n't know how to run it synchronously . Please help . <code> Pubnub pn = new Pubnub ( publishKey , subscribeKey , secretKey , cipherKey , enableSSL ) ; pn.HereNow ( `` testchannel '' , res = > //does n't return a Task { //response } , err = > { //error response } ) ; | Pubnub perform sync request |
C_sharp : I am rewriting some code ( targeting .NET 4.5.2. currently ) that uses reflection to compile for .NET Standard 1.4 . I therefore need to use GetTypeInfo ( ) on a Type at many places . In order to handle the edge cases correctly , my question is , can GetTypeInfo ( ) ever return null ? The documentation ( https : //msdn.microsoft.com/en-us/library/system.reflection.introspectionextensions.gettypeinfo ( v=vs.110 ) .aspx ) is silent about this.When I open a source of GetTypeInfo ( ) from a standard .NET 4.5.2 project , I get : That is still confusing . There is a code branch that returns null when ' ( IReflectableType ) type ' is null , but why ? - the 'type ' itself is checked against null before , and an exception is thrown when it is null , therefore I can not see how 'rcType ' can ever be null ( mind you , this is not an 'as ' operator , it is a straight typecast ) .In a good tradition , the documentation on IReflectableType.GetTypeInfo ( , https : //msdn.microsoft.com/en-us/library/system.reflection.ireflectabletype.gettypeinfo ( v=vs.110 ) .aspx ) is also silent about the possibility of a null outcome.A code that uses reflection needs to use GetTypeInfo at many places , and if a null results is allowed , it would therefore require to have a null check and a corresponding action at every such place . I have checked other people 's code ( including Microsoft 's own example at https : //msdn.microsoft.com/en-us/library/system.reflection.typeinfo % 28v=vs.110 % 29.aspx ? f=255 & MSPPError=-2147217396 ) and developers seem to be treating it as a null result was not possible . Is that correct ? <code> public static class IntrospectionExtensions { public static TypeInfo GetTypeInfo ( this Type type ) { if ( type == null ) { throw new ArgumentNullException ( `` type '' ) ; } var rcType= ( IReflectableType ) type ; if ( rcType==null ) { return null ; } else { return rcType.GetTypeInfo ( ) ; } } } | Can GetTypeInfo ever return null ? |
C_sharp : So I have to design a class that works on a collection of paired objects . There is a one-to-one mapping between objects . I expect the client of the class to have established this mapping before using my class.My question is what is the best way to allow the user of my class to give me that information ? Is it to ask for a collection of pairs like this ? Or seperate collections like this ? Or is there another option ? I like the first because the relationship is explicit , I do n't like it because of the extra work it puts on the client.I like the second because the types are more primitive and require less work , I do n't like it because the mapping is not explicit . I have to assume the order is correct.Opinions please ? <code> MyClass ( IEnumerable < KeyValuePair < Object , Object > > objects ) MyClass ( IEnumberable < Object > x , IEnumerable < Object > y ) | What is the most inuitive way to ask for objects in pairs ? |
C_sharp : I 'm creating a tree structure that is based on an AbstractNode class . The AbstractNode class has a generic collection property that contain its child nodes . See the code example below.Is there some way , possibly using generics , that I can restrict a concrete version of AbstractNode to only allow one type of child node ? See the code below for ConcreteNodeA , where its ChildNodes property is a collection of ConcreteNodeB rather then AbstractNode . This of course does not compile , but I 'm wondering if there is some other method I could use to have the same effect.Of course everything will work with the the ChildNodes collection property always being of type AbstractNode , but I 'm trying to embed some logic into my classes in regards to what nodes should be the children of other nodes . Plus when referencing the ChildNodes property it would be nice if I did n't have to cast the collection into a collection of the type I know it should be.UpdateAlright I think I figured out what I want to do but I 'd like to know if anyone thinks this `` feels bad '' or `` smells funny '' and why . Rather then my nodes having a ChildNodes collection property I 'm thinking of making each Node the actual collection . So my tree structure is would really just be a series of collections of collections . My abstract Node classes will then use various constraints on the generic to control the kinds of sub nodes it can have.Does this make sense ? Is there a reason I would n't want to do this ? I 've never used generics in one of my own classes before so I 'm not sure if I 'm overlooking something . <code> public abstract class AbstractNode { public abstract NodeCollection < AbstractNode > ChildNodes { get ; set ; } } public class ConcreteNodeA : AbstractNode { //THIS DOES NOT COMPLILE //Error 1 'ConcreteNodeA.ChildNodes ' : type must be 'NodeCollection < AbstractNode > ' //to match overridden member 'AbstractNode.ChildNodes ' public override NodeCollection < ConcreteNodeB > ChildNodes { get ; set ; } } public class ConcreteNodeB : AbstractNode { public override NodeCollection < AbstractNode > ChildNodes { get ; set ; } } public class NodeCollection < T > : BindingList < T > { //add extra events here that notify what nodes were added , removed , or changed } public interface INode { } public abstract class AbsNode < T > : BindingList < T > , INode where T : INode { } public abstract class AbsNodeA < T > : AbsNode < T > where T : AbsSubNodeA { } public abstract class ConcreteNodeA : AbsNodeA < AbsSubNodeA > { } public abstract class AbsSubNodeA : INode { } public class ConcreteSubNodeA : AbsSubNodeA { } public class ConcreteSubNodeB : AbsSubNodeA { } | How can I restrict the children of nodes in a tree structure |
C_sharp : I have a type and want to create an instance of it with test data . I know that frameworks like NBuilder or AutoFixture can create instances of types that are known on design time ( < T > ) . Are those frameworks able to create an instance based on a type that is only known at runtime ( Type ) ? On the end I want to do something like : <code> var value = Builder.Create ( type ) ; var constant = Expression.Constant ( value , type ) ; | Is there a way of creating an instance of a type with test data ? |
C_sharp : Here is my string : www.stackoverflow.com/questions/ask/user/endI split it with / into a list of separated words : myString.Split ( '/ ' ) .ToList ( ) Output : and I need to rejoin the string to get a list like this : I think about linq aggregate but it seems it is not suitable here . I want to do this all through linq <code> www.stackoverflow.comquestionsaskuserend www.stackoverflow.comwww.stackoverflow.com/questionswww.stackoverflow.com/questions/askwww.stackoverflow.com/questions/ask/userwww.stackoverflow.com/questions/ask/user/end | Split and then Joining the String step by step - C # Linq |
C_sharp : I 'm curious about the difference below two example.case 1 ) locking by readonly objectcase2 ) locking by target object itselfare both cases thread-safe enough ? i 'm wondering if garbage collector changes the address of list variable ( like 0x382743 = > 0x576382 ) at sometime so that it could fail thread-safe . <code> private readonly object key = new object ( ) ; private List < int > list = new List < int > ; private void foo ( ) { lock ( key ) { list.add ( 1 ) ; } } private List < int > list = new List < int > ; private void foo ( ) { lock ( list ) { list.add ( 1 ) ; } } | locking by target object self |
C_sharp : First of all , I 'm new to both WCF services and dropzone JS , but I 'm trying to combine the two to create a simple image uploader . I 've got my WCF working correctly for the metadata that I 've uploaded to through it ( so I know it 's passing things cross domain correctly ) , but the Stream that I 've captured from Dropzone does n't match the image that I dropped . In fact , every single image dropped results in the same encoded string server-side ... For example , I 've used this star image as a test , and by uploading the image to a base64 online converter , I can see that the beginning of the base64 string looks like this : However , when I debug my WCF code , the base64 converted string looks like this : This string above is the same one for created for every image that I try to send . So now for all the applicable code pieces . I 've got a simple webpage in one project and the WCF related files in another project in the same solution.Index.html : OperationContract : AddImageStream implementation : Webconfig applicable pieces : The problem is visible when I break on the encodedString piece and it does n't match what I 'm expecting . If I copy the entire string into another online image that generates images from base64 strings , it 's not a valid image . At this point I 'm stuck and have n't been able to determine why I ca n't read from dropzone . <code> data : image/png ; base64 , iVBORw0KGgoAAAANSUhEUgAAAOYAAADbCAMAAABOUB36AAAAwFBMVEX ... LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5T1RUV0I1RFZZdTVlM2NTNQ0KQ29udG ... < div class= '' col-lg-12 '' > < form action= '' http : //localhost:39194/ImageRESTService.svc/AddImageStream/ '' class= '' dropzone '' id= '' dropzone '' > < /form > < /div > ... Dropzone.options.dropzone = { maxFilesize : 10 , // MB } ; /* Stores a new image in the repository */ [ OperationContract ] [ WebInvoke ( Method = `` POST '' , ResponseFormat = WebMessageFormat.Json , UriTemplate = `` AddImageStream/ '' ) ] void AddImageStream ( Stream img ) ; public void AddImageStream ( Stream img ) { //try to save image to database byte [ ] buffer = new byte [ 10000 ] ; int bytesRead , totalBytesRead = 0 ; string encodedData = `` '' ; do { bytesRead = img.Read ( buffer , 0 , buffer.Length ) ; encodedData = encodedData + Convert.ToBase64String ( buffer , Base64FormattingOptions.InsertLineBreaks ) ; totalBytesRead += bytesRead ; } while ( bytesRead > 0 ) ; } < services > < service name= '' ImageRESTService.ImageRESTService '' behaviorConfiguration= '' serviceBehavior '' > < endpoint address= '' '' behaviorConfiguration= '' web '' contract= '' ImageRESTService.IImageRESTService '' binding= '' webHttpBinding '' bindingConfiguration= '' webHttpBinding '' > < /endpoint > < /service > < /services > < behaviors > < serviceBehaviors > < behavior name= '' serviceBehavior '' > < serviceMetadata httpGetEnabled= '' false '' / > < serviceDebug includeExceptionDetailInFaults= '' false '' / > < /behavior > < /serviceBehaviors > < endpointBehaviors > < behavior name= '' web '' > < webHttp / > < /behavior > < /endpointBehaviors > < /behaviors > < standardEndpoints > < webHttpEndpoint > < standardEndpoint name= '' '' helpEnabled= '' true '' automaticFormatSelectionEnabled= '' true '' maxReceivedMessageSize= '' 2147000000 '' / > < /webHttpEndpoint > < /standardEndpoints > < bindings > < webHttpBinding > < binding crossDomainScriptAccessEnabled= '' true '' name= '' ImagesBinding '' closeTimeout= '' 00:10:00 '' openTimeout= '' 00:10:00 '' receiveTimeout= '' 00:10:00 '' sendTimeout= '' 00:10:00 '' maxBufferSize= '' 2147483647 '' maxBufferPoolSize= '' 2147483647 '' maxReceivedMessageSize= '' 2147483647 '' / > < binding name= '' webHttpBinding '' transferMode= '' Streamed '' maxReceivedMessageSize= '' 2147483647 '' maxBufferSize= '' 10485760 '' closeTimeout= '' 00:01:00 '' openTimeout= '' 00:01:00 '' receiveTimeout= '' 00:10:00 '' sendTimeout= '' 00:01:00 '' > < readerQuotas maxStringContentLength= '' 2147483647 '' maxArrayLength= '' 1000000 '' / > < /binding > < /webHttpBinding > | Dropzone JS Upload to WCF Getting Wrong Data |
C_sharp : I have the following simplified code for pulling existing 8x10 PDFs from multiple locations , rotating them if need be ( almost all need to be ) , then writing them to a single 11x17 PDF page by page ... However the page rendered does n't have the pages rotated as they should be , I 've verified the height > width branch is indeed being taken but the pages returned are still 8x10 instead of 10x8 written on each 11x17 page.I searched around for a question this specific but could n't find one that was n't just writing to another file or the entire page instead of to a specific location on an 11x17 sheet.EDIT : So with a little experimenting and looking at other examples I 'm able to rotate the 8x10 page and write it to my 11x17 but unfortunately I ca n't seem to find a way to place it exactly where I want it here 's the relevant code snippet : <code> while ( Page < StackOne.Length ) { Files++ ; using ( var strm = new FileStream ( RenderPath + `` Test_ '' + Page + `` .pdf '' , FileMode.Create , FileAccess.Write , FileShare.Read ) ) { using ( var MasterReport = new iTextSharp.text.Document ( iTextSharp.text.PageSize._11X17 ) ) { using ( var writer = PdfWriter.GetInstance ( MasterReport , strm ) ) { MasterReport.Open ( ) ; MasterReport.NewPage ( ) ; var cb = writer.DirectContent ; for ( ; Page < = NumPages * Files & & Page < StackOne.Length ; Page++ ) { var ProductionEntry = StackOne [ Page - 1 ] ; var filepath = NetPath + ProductionEntry.UniqueProductId + `` .pdf '' ; if ( File.Exists ( filepath ) ) { var reader = new PdfReader ( filepath ) ; var pagesize = reader.GetPageSize ( 1 ) ; if ( pagesize.Height > pagesize.Width ) { var ExistingPage = reader.GetPageN ( 1 ) ; var rotation = ExistingPage.GetAsNumber ( PdfName.ROTATE ) ; int desiredrot = 90 ; if ( rotation ! = null ) { desiredrot += rotation.IntValue ; desiredrot % = 360 ; } ExistingPage.Put ( PdfName.ROTATE , new PdfNumber ( desiredrot ) ) ; } cb.AddTemplate ( writer.GetImportedPage ( reader , 1 ) , 50 , 50 ) ; } MasterReport.NewPage ( ) ; } } } } } var reader = new PdfReader ( filepath ) ; var tm = new AffineTransform ( 1.0F , 0 , 0 , 1.0F , x , y ) ; if ( reader.GetPageSize ( 1 ) .Height > reader.GetPageSize ( 1 ) .Width ) tm.SetTransform ( 0 , -1f , 1f , 0 , 0 , reader.GetPageSize ( 1 ) .Height ) ; writer.DirectContent.AddTemplate ( writer.GetImportedPage ( reader , 1 ) , tm ) ; | Rotate multiple PDFs and write to one single PDF |
C_sharp : To be honest I was n't sure how to word this question so forgive me if the actual question is n't what you were expecting based on the title . C # is the first statically typed language I 've ever programmed in and that aspect of it has been an absolute headache for me so far . I 'm fairly sure I just do n't have a good handle on the core ideas surrounding how to design a system in a statically typed manner.Here 's a rough idea of what I 'm trying to do . Suppose I have a hierarchy of classes like so : Now suppose I want to make a list of item where the items can be any kind of mold and I can get the Result property of each item in a foreach loop like so : As you probably already know , that does n't work . From what I 've read in my searches , it has to do with the fact that I ca n't declare the List to be of type DataMold < T > . What is the correct way to go about something like this ? <code> abstract class DataMold < T > { public abstract T Result { get ; } } class TextMold : DataMold < string > { public string Result = > `` ABC '' ; } class NumberMold : DataMold < int > { public int Result = > 123 } List < DataMold < T > > molds = new List < DataMold < T > > ( ) ; molds.Add ( new TextMold ( ) ) ; molds.Add ( new NumberMold ( ) ) ; foreach ( DataMold < T > mold in molds ) Console.WriteLine ( mold.Result ) ; | How do I properly work with calling methods on related but different classes in C # |
C_sharp : I have a ParseTree listener implementation that I 'm using to fetch global-scope declarations in standard VBA modules : Is there a way to tell the tree walker to stop walking ? Say I have a VBA module like this : I would like the tree walker to stop walking the parse tree as soon as it enters Public Sub DoSomething ( ) , for I 'm not interested in anything below that . Currently I 'm walking the entire parse tree , just not doing anything with whatever I pick up within a procedure scope.Is there a way , from within a parse tree listener implementation , to tell the walker to stop walking the tree ? <code> public class DeclarationSectionListener : DeclarationListener { private bool _insideProcedure ; public override void EnterVariableStmt ( VisualBasic6Parser.VariableStmtContext context ) { var visibility = context.visibility ( ) ; if ( ! _insideProcedure & & visibility == null || visibility.GetText ( ) == Tokens.Public || visibility.GetText ( ) == Tokens.Global ) { base.EnterVariableStmt ( context ) ; } } public override void EnterConstStmt ( VisualBasic6Parser.ConstStmtContext context ) { var visibility = context.visibility ( ) ; if ( ! _insideProcedure & & visibility == null || visibility.GetText ( ) == Tokens.Public || visibility.GetText ( ) == Tokens.Global ) { base.EnterConstStmt ( context ) ; } } public override void EnterArg ( VisualBasic6Parser.ArgContext context ) { return ; } public override void EnterSubStmt ( VisualBasic6Parser.SubStmtContext context ) { _insideProcedure = true ; } public override void EnterFunctionStmt ( VisualBasic6Parser.FunctionStmtContext context ) { _insideProcedure = true ; } public override void EnterPropertyGetStmt ( VisualBasic6Parser.PropertyGetStmtContext context ) { _insideProcedure = true ; } public override void EnterPropertyLetStmt ( VisualBasic6Parser.PropertyLetStmtContext context ) { _insideProcedure = true ; } public override void ExitPropertySetStmt ( VisualBasic6Parser.PropertySetStmtContext context ) { _insideProcedure = true ; } } Public Const foo = 123Public bar As StringPublic Sub DoSomething ( ) ' some codeEnd Sub ' ... ' 10K more lines of code ' ... Private Function GetSomething ( ) As String ' some code End Function | Can a walker be stopped ? |
C_sharp : The ProblemOur company make specialized devices running Windows XP ( Windows XPe , to be precise ) . One of the unbending legal requirements we face is that we must quickly detect when a fixed IDE drive is removed . Quickly as in within a few seconds.The drives in question are IDE drives . They are also software-protected from writes with an EWF ( Enhanced Write Filter ) layer . The EWF layer sits under the file system , protecting the disk from writes . If you change or write something on an EWF-protected volume , the actual changes happen only in a memory layer ( but the file system is n't aware of that ) .The problem is that Windows itself does n't seem to notice fixed drive removal . You can pull the drive out of the machine , and Windows Explorer will be happy to let you browse directories and even open files if they happen to still be cached in memory . And thanks to the EWF layer , I can even seem to write files to the missing drive.I need a clean software-only solution . Ideally in C # /.Net 1.1 , but I have no problem with using pinvoke or C++.Things I ca n't doNo , I ca n't retrofit thousands of devices with new hardware.No , we ca n't just super-glue drives in to meet legal requirements.No , a normal file write/read wo n't detect the situation , thanks to the EWF layer.No , we ca n't turn off the EWF layer.No , I ca n't ignore legal requirements , even if they are silly.No , I ca n't detect fixed drive removal the way I would for a USB or other removable drive . These are fixed drives.No , I ca n't use WMI ( Windows Management Instrumentation ) . It is n't installed on our machines.No I ca n't use versions of .Net past 1.1 . It wo n't fit on our small drives . ( But if an easy solution exists in a higher version of .Net , I might be able to port it back to 1.1 . ) Current awkward solutionI 'm not happy with our current solution . I 'm looking for something more elegant and efficient.What I 'm currently doing involves two threads.Thread A polls the drive . It first creates a special file on the drive using Kernel32.dll : Then it polls the drive by callingIf the drive has been removed , then thread A will hang for a long time before returning an error code.Thread B polls thread A.If thread B sees that thread A has locked up ( has n't updated a special variable in a while ) , then thread B raises an event that the drive has been removed.My current solution works , but I do n't like it . If anyone knows a cleaner software-only solution , I would appreciate it . <code> Kernel32.CreateFile ( filename , File_Access.GenericRead | File_Access.GenericWrite , File_Share.Read | File_Share.Write , IntPtr.Zero , CreationDisposition.CreateAlways , CreateFileFlagsAndAttributes.File_Attribute_Hidden | CreateFileFlagsAndAttributes.File_Attribute_System , IntPtr.Zero ) ; Kernel32.FlushFileBuffers ( fileHandle ) ; | Quickly detect removal of fixed IDE drive in Windows XP |
C_sharp : The following code works : So naturally you 'd think that this code would work too : But I get the error Invalid cast operation - does anybody know why that might happen ? UPDATE tblStocks is a list of LINQ to SQL object , tblStock.JsonStock is a simplified version of the tblStock class and gets returned to a webpage as a JSON object.The following operator was built to do the casting : <code> List < JsonStock > stock = new List < JsonStock > ( ) ; foreach ( tblStock item in repository.Single ( id ) .tblStocks ) stock.Add ( ( JsonStock ) item ) ; List < JsonStock > stock = repository.Single ( id ) .tblStocks.Cast < JsonStock > ( ) .ToList ( ) public partial class tblStock { public static explicit operator JsonStock ( tblStock stock ) { JsonStock item = new JsonStock { boxes = stock.boxes , boxtype = stock.tblBoxType.name , boxtype_id = stock.boxtype_id , grade = stock.grade , packrate = stock.packrate , weight = stock.weight } ; return item ; } } | Casting List < x > to List < y > |
C_sharp : Could anyone tell me why these two modulus calculations yield two different outcomes ? I just need to blame someone or something but me for all those hours I lost finding this bug.Using VS-2017 V15.3.5 <code> public void test1 ( ) { int stepAmount = 100 ; float t = 0.02f ; float remainder = t % ( 1f / stepAmount ) ; Debug.Log ( `` Remainder : `` + remainder ) ; // Remainder : 0.01 float fractions = 1f / stepAmount ; remainder = t % fractions ; Debug.Log ( `` Remainder : `` + remainder ) ; // Remainder : 0 } | Modulus gives wrong outcome ? |
C_sharp : This is driving me crazy . I have been looking for the source of the issue for hours , but i am starting to suspect this is not an issue in my logic ... Maybe i am wrong.Issue descriptionI have a simple Entry . Its Text property is bound to a property with type double in a ViewModel . At the same time i subscribe to the Unfocused Event whose EventHandler simply sets the entry.Text property to `` 1.0 '' ( actually i can reproduce the issue for x.y0 , that is any decimal whose final digit is 0 ) . If now i write in the Entry anything ( except `` 1 '' or `` 1 . '' or `` 1.0 '' ! ! ! ) and leave the Entry ( by tapping outside or taping on Done ) so that Unfocused is fired , the App becomes unresponsive.Note : I know that it sounds a bit strange to set entry.Text = 1.0 in the event handler . The truth is that i came across this issue by trying to format the entry.Text value as follows.There String.Format tries to round the decimal to two decimals . If i give 6.999 the expected value should be 7.00 , but the App becomes unresponsive instead.Steps to reproduce the issueCreate blank Xamarin.Forms proyect.Remove default Label in MainPage.xaml file to include following Entry , instead : In the code behind add the following EventHandler and set the BindingContext property of the page as follows : Create the ViewModel like : Run the App and type anything into the Entry.Leave the Entry so that Unfocused is fired.My System configuration : Visual Studio v. 16.3.8Xamarin.Forms 4.2.0.709249Android 8Could anyone explain what is going on here , and anyway to work around this issue ? <code> if ( double.TryParse ( entry.Text , out double result ) ) { entry.Text = String.Format ( `` { 0 : F2 } '' , result ) ; } < StackLayout > < Entry Text= '' { Binding Weight } '' Unfocused= '' entry_Unfocused '' / > < /StackLayout > public partial class MainPage : ContentPage { public MainPage ( ) { InitializeComponent ( ) ; } protected override void OnAppearing ( ) { base.OnAppearing ( ) ; BindingContext = new viewmodel ( ) ; } private void entry_Unfocused ( object sender , FocusEventArgs e ) { ( ( Entry ) sender ) .Text = `` 1.0 '' ; } } public class viewmodel : INotifyPropertyChanged { public viewmodel ( ) { } private double _Weight ; public double Weight { get = > _Weight ; set { if ( _Weight ! = value ) { _Weight = value ; OnPropertyChanged ( ) ; } } } public event PropertyChangedEventHandler PropertyChanged ; private void OnPropertyChanged ( [ CallerMemberName ] String propertyName = `` '' ) { PropertyChanged ? .Invoke ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } | Setter of property bound to Entry.Text loops infinitely |
C_sharp : I have this query to collection : This gets only the Panel that has an hyperlink with a certain id . I need to get not only the firstOrDefault but the matched element ( only the first ) and the 2 next within the sequence . I did n't try anything because do n't know how . <code> Panel thePanel = menuCell.Controls.OfType < Panel > ( ) .Where ( panel = > panel.Controls.OfType < HyperLink > ( ) .Any ( label = > label.ID == clas ) ) .FirstOrDefault ( ) ; | How to get an element range in linq within a sequence ? |
C_sharp : I confuse between double [ ] [ ] and double [ , ] in C # .My teammate give me a function like this : I want to use this function : It lead an error : invalid argument.I do n't want to edit my teammate 's code.Does it have any way to convert double [ ] [ ] to double [ , ] ? Thanks ! <code> public double [ ] [ ] Do_Something ( double [ ] [ ] A ) { ... ... . } double [ , ] data = survey.GetSurveyData ( ) ; //Get datadouble [ , ] inrma = Do_Something ( data ) ; | C # : double [ ] [ ] and double [ , ] |
C_sharp : I have a question on something I 've never seen before in C # . In the service provider in the new asp.net dependency injection , there is a method with return _ = > null ; https : //github.com/aspnet/DependencyInjection/blob/dev/src/Microsoft.Framework.DependencyInjection/ServiceProvider.csLines 63-72.The method in question : What is the _ ? Is it new in C # 6 ? Searching around for return _ does n't return anything useful , unless you want naming conventions . <code> private Func < MyServiceProvider , object > CreateServiceAccessor ( Type serviceType ) { var callSite = GetServiceCallSite ( serviceType , new HashSet < Type > ( ) ) ; if ( callSite ! = null ) { return RealizeService ( _table , serviceType , callSite ) ; } return _ = > null ; } | What is the return _ in C # |
C_sharp : EDIT : I 'm considering this question different from the potential duplicate because none of the answers on that one contain the approach I went with which is the BitConverter class . In case me marking this as not a duplicate gets rid of the potential duplicate question link here it is.I 'm wondering what the c # equivalent of this code is considering each element in the array is a byte and it 's getting copied to an int . <code> byte offsetdata [ sizeof ( int ) ] = { 0,0,0,0 } ; offsetdata [ 0 ] = m_Response [ responseIndex++ ] ; offsetdata [ 1 ] = m_Response [ responseIndex++ ] ; offsetdata [ 2 ] = m_Response [ responseIndex++ ] ; offsetdata [ 3 ] = m_Response [ responseIndex++ ] ; int offset = 0 ; memcpy ( & offset , offsetdata , sizeof offset ) ; m_ZOffset = offset ; | What is the C # equivalent of memcpy array to int ? |
C_sharp : I have a singleton that can register a func to resolve an id value for each type : for example : and then i want to resolve the id for an object , like these : where GetObjectId definition isThe question is , how can i store a reference for each func to invoke it lately.The problem is that each func has a different T type , and I ca n't do something like this : How can resolve it ? Expression trees ? regardsEzequiel <code> public void RegisterType < T > ( Func < T , uint > func ) RegisterType < Post > ( p = > p.PostId ) ; RegisterType < Comment > ( p = > p.CommentId ) ; GetObjectId ( myPost ) ; public uint GetObjectId ( object obj ) private Dictionary < Type , Func < object , uint > > _typeMap ; | references to Func 's of different types |
C_sharp : I am writing an API that connects to a service which either returns a simple `` Success '' message or one of over 100 different flavors of failure.Originally I thought to write the method that sends a request to this service such that if it succeeded the method returns nothing , but if it fails for whatever reason , it throws an exception.I did n't mind this design very much , but on the other hand just today I was reading Joshua Bloch 's `` How to Design a Good API and Why it Matters '' , where he says `` Throw Exceptions to indicate Exceptional Conditions ... Do n't force client to use exceptions for control flow . '' ( and `` Conversely , do n't fail silently . `` ) On the other-other hand , I noticed that the HttpWebRequest I am using seems to throw an exception when the request fails , rather than returning a Response containing a `` 500 Internal Server Error '' message.What is the best pattern for reporting errors in this case ? If I throw an exception on every failed request , am I in for massive pain at some point in the future ? Edit : Thank you very kindly for the responses so far . Some elaboration : it 's a DLL that will be given to the clients to reference in their application.an analogous example of the usage would be ChargeCreditCard ( CreditCardInfo i ) - obviously when the ChargeCreditCard ( ) method fails it 's a huge deal ; I 'm just not 100 % sure whether I should stop the presses or pass that responsibility on to the client.Edit the Second : Basically I 'm not entirely convinced which of these two methods to use : or e.g . when a user tries to charge a credit card , is the card being declined really an exceptional circumstance ? Am I going down too far in the rabbit hole by asking this question in the first place ? <code> try { ChargeCreditCard ( cardNumber , expDate , hugeAmountOMoney ) ; } catch ( ChargeFailException e ) { // client handles error depending on type of failure as specified by specific type of exception } var status = TryChargeCreditCard ( cardNumber , expDate , hugeAmountOMoney ) ; if ( ! status.wasSuccessful ) { // client handles error depending on type of failure as specified in status } | Best Practice way to indicate that a server request has failed ? |
C_sharp : Say I have a Repository class which has a DbContext . In this class I have a method : In a Service class I use this method to create an object : And finally in my api controller MyObjectController I return this object like so : I 'm confused about all these async and await keywords . I know that a Task is awaitable . Does this mean that I could just return the Task from CreateAsync without awaiting in neither CreateAsync or Create and then finally await it in Get ? Does it have a negative effect on my application that I do my awaits like in the example ? <code> public async Task < T > CreateAsync ( T obj ) { var o = _dbSet.Add ( obj ) ; await _dbContext.SaveChangesAsync ( ) ; return o ; } public async Task < MyObject > Create ( ) { return await _repository.CreateAsync ( new MyObject ( ) ) ; } public async Task < IHttpActionResult > Get ( ) { return Ok ( await _service.Create ( ) ) ; } | When should you await a Task ? |
C_sharp : I 'm not quite sure of the different betweenandBoth worked exactly the same , why would I need to change it to an _ like shown ? IMAGE OF THE `` POTENTIAL FIX '' <code> DataTable itemTable = new DataTable ( ) ; itemTable = //CODE _ = new DataTable ( ) ; DataTable itemTable = //CODE | C # Use discard ' _ ' |
C_sharp : For the long time I thought I get it , and I was going to create some puzzles to learn some of my „ students “ on the topic of operator precedence in c # .But it came out that I still do n't get it right . Puzzles : What ’ s the output here ? Output : -20All clear here , I expected thisNext , the problem one : Output : -10Well , here I also expected y to be -2… Now I ’ m trying to apply operator precedence rules and order of evaluation , and not sure I explained it to myself.Read this post again few times today , but still don ’ t quite get it why is the result here -1 ? Can someone help with how is the second result evaluated . why and how is it different than the first one ? <code> int a = 0 ; int x = -- a + a++ ; Console.WriteLine ( x ) ; Console.WriteLine ( a ) ; int b = 0 ; int y = b -- + b++ ; Console.WriteLine ( y ) ; Console.WriteLine ( b ) ; | ++ -- Operator precedence puzzle |
C_sharp : I am looking for a solution in LINQ but anything helps ( C # ) . I tried using Sort ( ) but its not working for example i have a sample list that contains the response I get is : and what I want is : any idea on a good unit test for this method ? just to text that it is getting sorted that way . <code> { `` a '' , `` b '' , `` f '' , `` aa '' , `` z '' , `` ac '' , `` ba '' } a , aa , ac , b , ba , f , z a , b , f , z , aa , ac , ba . | C # Sorting alphabetical order a - z and then to aa , ab - zz |
C_sharp : I created an application that stores byte arrays in my SQLiteDatabase.This same application also selects the byte arrays from the database every ' x ' seconds . The dataflow of my application is as follow : Application - > SQLiteDatabase - > ApplicationMy question is : How do I fill one byte array with all the incoming byte arrays from the SQLiteDatabase ? For example : Needs to be filled with the following byte array : IncomingData is constantly being filled by the SQLiteDatabase . Data needs to be filled with IncomingData constantly.Can someone help me out ? <code> Byte [ ] Data ; Byte [ ] IncomingData ; | Filling one byte [ ] with multiple byte [ ] s |
C_sharp : I have 2 ListViews and a TextBlock . The first ListView1 includes letters in Alphabetical order . And the second ListView2 includes the words that start with the selected letter ( in ListView1 ) . When I choose a letter from ListView1 and then click on a word loaded in ListView2 , I want to get the definition of this word in a TextBlock . This is my Xaml : If I click the first time on a letter ( ListView1 ) then on a word ( ListView2 ) it shows me the definition . However the second time I click on a letter , it gives me an OutOfRange Error where the ListView2.SelectedIndex = -1This is my C # code : Any idea what is the error I am doing ? <code> < ListView Width= '' 510 '' x : Name= '' ListView1 '' ItemsSource= '' { Binding } '' Background= '' White '' Foreground= '' Black '' TabIndex= '' 1 '' Margin= '' -7,8,0,0 '' IsSwipeEnabled= '' False '' SelectionChanged= '' ItemListView_SelectionChanged '' Grid.Row= '' 1 '' HorizontalAlignment= '' Left '' > < ListView.ItemTemplate > < DataTemplate > < StackPanel > < TextBlock Grid.Row= '' 0 '' Text= '' { Binding glossary_letter } '' Margin= '' 10,0,0,0 '' TextWrapping= '' Wrap '' Foreground= '' Black '' FontSize= '' 24 '' FontWeight= '' SemiBold '' VerticalAlignment= '' Center '' / > < /StackPanel > < /DataTemplate > < /ListView.ItemTemplate > < /ListView > < ListView Width= '' 361 '' x : Name= '' ListView2 '' Background= '' White '' Foreground= '' Black '' Margin= '' 425,8,230,0 '' Grid.Row= '' 1 '' HorizontalAlignment= '' Center '' ItemsSource= '' { Binding } '' SelectionChanged= '' itemListView2_SelectionChanged '' > < ListView.ItemTemplate > < DataTemplate > < StackPanel > < TextBlock Grid.Row= '' 1 '' TextWrapping= '' Wrap '' Foreground= '' Black '' Text= '' { Binding } '' FontSize= '' 24 '' FontWeight= '' SemiBold '' VerticalAlignment= '' Center '' / > < /StackPanel > < /DataTemplate > < /ListView.ItemTemplate > < /ListView > < StackPanel HorizontalAlignment= '' Right '' Background= '' White '' Width= '' 580 '' Margin= '' 0,10,0,0 '' Grid.Row= '' 1 '' Grid.ColumnSpan= '' 2 '' > < TextBlock x : Name= '' defBlock '' Foreground= '' Black '' Text= '' { Binding glossary_definition } '' > < /TextBlock > < /StackPanel > private void ListView1_SelectionChanged ( object sender , SelectionChangedEventArgs e ) { ListView2.ItemsSource = arrayW [ ListView1.SelectedIndex ] ; } private void ListView2_SelectionChanged ( object sender , SelectionChangedEventArgs e ) { defBlock.Text = arrayDef [ ListView1.SelectedIndex ] [ ListView2.SelectedIndex ] ; } | Can not set SelectedIndex= '' 0 '' in Xaml to ListView ( Windows Store App ) |
C_sharp : Are there any overheads to using the following sytax : As opposed to : When I was learning VB6 , I was told doing the quivelent in VB had an overhead - is the same true in .NET ? <code> Form1 myForm = new Form1 ( ) ; myForm.Show ( ) ; Form1 myForm ; myForm = new Form1 ( ) ; myForm.Show ( ) ; | C # Object Declarations |
C_sharp : I have a thread that spins until an int changed by another thread is a certain value.Does this.m_cur need to be declared volatile for this to work ? Is it possible that this will spin forever due to compiler optimization ? <code> int cur = this.m_cur ; while ( cur > this.Max ) { // spin until cur is < = max cur = this.m_cur ; } | Do I need this field to be volatile ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.