Search Results

Search found 1746 results on 70 pages for 'expressions'.

Page 4/70 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Can a class inherit from LambdaExpression in .NET? Or is this not recommended?

    - by d.
    Consider the following code (C# 4.0): public class Foo : LambdaExpression { } This throws the following design-time error: Foo does not implement inherited abstract member System.Linq.Expressions.LambdaExpression.Accept(System.Linq.Expressions.Compiler.StackSpiller) There's absolutely no problem with public class Foo : Expression { } but, out of curiosity and for the sake of learning, I've searched in Google System.Linq.Expressions.LambdaExpression.Accept(System.Linq.Expressions.Compiler.StackSpiller) and guess what: zero results returned (when was the last time you saw that?). Needless to say, I haven't found any documentation on this method anywhere else. As I said, one can easily inherit from Expression; on the other hand LambdaExpression, while not marked as sealed (Expression<TDelegate> inherits from it), seems to be designed to prevent inheriting from it. Is this actually the case? Does anyone out there know what this method is about? EDIT (1): More info based on the first answers - If you try to implement Accept, the editor (C# 2010 Express) automatically gives you the following stub: protected override Expression Accept(System.Linq.Expressions.ExpressionVisitor visitor) { return base.Accept(visitor); } But you still get the same error. If you try to use a parameter of type StackSpiller directly, the compiler throws a different error: System.Linq.Expressions.Compiler.StackSpiller is inaccessible due to its protection level. EDIT (2): Based on other answers, inheriting from LambdaExpression is not possible so the question as to whether or not it is recommended becomes irrelevant. I wonder if, in cases like this, the error message should be Foo cannot implement inherited abstract member System.Linq.Expressions.LambdaExpression.Accept(System.Linq.Expressions.Compiler.StackSpiller) because [reasons go here]; the current error message (as some answers prove) seems to tell me that all I need to do is implement Accept (which I can't do).

    Read the article

  • ASP.NET Localization: Enabling resource expressions with an external resource assembly

    - by Brian Schroer
    I have several related projects that need the same localized text, so my global resources files are in a shared assembly that’s referenced by each of those projects. It took an embarrassingly long time to figure out how to have my .resx files generate “public” properties instead of “internal” so I could have a shared resources assembly (apparently it was pretty tricky pre-VS2008, and my “googling” bogged me down some out-of-date instructions). It’s easy though – Just change the “Custom Tool” to “PublicResXFileCodeGenerator”:    …which can be done via the “Access Modifier” dropdown of the resource file designer window:   A reference to my shared resources DLL gives me the ability to use the resources in code, but by default, the ASP.NET resource expression syntax: <asp:Button ID="BeerButton" runat="server" Text="<%$ Resources:MyResources, Beer %>" />   …assumes that your resources are in your web site project.   To make resource expressions work with my shared resources assembly, I added two classes to the resources assembly: 1) a custom IResourceProvider implementation:   1: using System; 2: using System.Web.Compilation; 3: using System.Globalization; 4:   5: namespace DuffBeer 6: { 7: public class CustomResourceProvider : IResourceProvider 8: { 9: public object GetObject(string resourceKey, CultureInfo culture) 10: { 11: return MyResources.ResourceManager.GetObject(resourceKey, culture); 12: } 13:   14: public System.Resources.IResourceReader ResourceReader 15: { 16: get { throw new NotSupportedException(); } 17: } 18: } 19: }   2) and a custom factory class inheriting from the ResourceProviderFactory base class:   1: using System; 2: using System.Web.Compilation; 3:   4: namespace DuffBeer 5: { 6: public class CustomResourceProviderFactory : ResourceProviderFactory 7: { 8: public override IResourceProvider CreateGlobalResourceProvider(string classKey) 9: { 10: return new CustomResourceProvider(); 11: } 12:   13: public override IResourceProvider CreateLocalResourceProvider(string virtualPath) 14: { 15: throw new NotSupportedException(String.Format( 16: "{0} does not support local resources.", 17: this.GetType().Name)); 18: } 19: } 20: }   In the “system.web / globalization” section of my web.config file, I point the “resourceProviderFactoryType" property to my custom factory:   <system.web> <globalization culture="auto:en-US" uiCulture="auto:en-US" resourceProviderFactoryType="DuffBeer.CustomResourceProviderFactory, DuffBeer" />   This simple approach met my needs for these projects , but if you want to create reusable resource provider and factory classes that allow you to specify the assembly in the resource expression, the instructions are here.

    Read the article

  • RadioButtons and Lambda Expressions

    - by MightyZot
    Radio buttons operate in groups. They are used to present mutually exclusive lists of options. Since I started programming in Windows 20 years ago, I have always been frustrated about how they are implemented. To make them operate as a group, you put your radio buttons in a group box. Conversely, to group radio buttons in HTML, you simply give them all the same name. Radio buttons with the same name or ID in HTML operate as one mutually exclusive group of options. In C#, all your radio buttons must have unique names and you use group boxes to group them. I’m in the process of converting some old code to C# and I’m tasked with creating a user control with groups of radio buttons on it. I started out writing the traditional switch…case statements to check the appropriate radio button based upon value, loops to uncheck them all, etc. Then it occurred to me that I could stick the radio buttons in a Dictionary or List and use Lambda expressions to make my code a lot more maintainable. So, here is what I ended up with: Here is a dictionary that contains my list of radio buttons and their values. I used their values as the keys, so that I can select them by value. Now, instead of using loops and switch…case statements to control the radio buttons, I use the lambda syntax and extension methods. Selecting a Radio Button by Value This code is inside of a property accessor, so “value” represents the value passed into the property accessor. The “First” extension method uses the delegate represented by the lambda expression to select the radio button (actually KeyValuePair) that represents the passed in value. Finally, the resulting checkbox is checked. Since the radio buttons are in the same group, they function as a group, the appropriate radio button is selected while the others are unselected. Reading the Value This is the get accessor for the property that returns the value of the checked radio button. Now, if you’re using binding, this code is likely not necessary; however, I didn’t want to use binding in this case, so I think this is a good alternative to the traditional loops and switch…case statements.

    Read the article

  • Does replacing statements by expressions using the C++ comma operator could allow more compiler opti

    - by Gabriel Cuvillier
    The C++ comma operator is used to chain individual expressions, yielding the value of the last executed expression as the result. For example the skeleton code (6 statements, 6 expressions): step1; step2; if (condition) step3; return step4; else return step5; May be rewritten to: (1 statement, 6 expressions) return step1, step2, condition? step3, step4 : step5; I noticed that it is not possible to perform step-by-step debugging of such code, as the expression chain seems to be executed as a whole. Does it means that the compiler is able to perform special optimizations which are not possible with the traditional statement approach (specially if the steps are const or inline)? Note: I'm not talking about the coding style merit of that way of expressing sequence of expressions! Just about the possible optimisations allowed by replacing statements by expressions.

    Read the article

  • How do I mix functions in complex SSRS expressions?

    - by Boydski
    I'm writing a report against a data repository that has null values within some of the columns. The problem is building expressions is as temperamental as a hormonal old lady and doesn't like my mixing of functions. Here's an expression I've written that does not work if the data in the field is null/nothing: =IIF( IsNumeric(Fields!ADataField.Value), RunningValue( IIF( DatePart("q", Fields!CreatedOn.Value) = "2", Fields!ADataField.Value, 0 ), Sum, Nothing ), Sum(0) ) (Pseudocode) "If the data is valid and if the data was created in the second quarter of the year, add it to the overall Sum, otherwise, add zero to the sum." Looks pretty straight forward. And the individual pieces of the expression work by themselves. IE: IsNumeric(), DatePart(), etc. But when I put them all together, the expression throws an error. I've attempted about every permutation of what's shown above, all to no avail. Null values in Fields!ADataField.Value cause errors. Thoughts?

    Read the article

  • Are .NET's regular expressions Turing complete?

    - by Robert
    Regular expressions are often pointed to as the classical example of a language that is not Turning complete. For example "regular expressions" is given in as the answer to this SO question looking for languages that are not Turing complete. In my, perhaps somewhat basic, understanding of the notion of Turning completeness, this means that regular expressions cannot be used check for patterns that are "balanced". Balanced meaning have an equal number of opening characters as closing characters. This is because to do this would require you to have some kind of state, to allow you to match the opening and closing characters. However the .NET implementation of regular expressions introduces the notion of a balanced group. This construct is designed to let you backtrack and see if a previous group was matched. This means that a .NET regular expressions: ^(?<p>a)*(?<-p>b)*(?(p)(?!))$ Could match a pattern that: ab aabb aaabbb aaaabbbb ... etc. ... Does this means .NET's regular expressions are Turing complete? Or are there other things that are missing that would be required for the language to be Turing complete?

    Read the article

  • Lambda expressions - set the value of one property in a collection of objects based on the value of

    - by Michael Rut
    I'm new to lambda expressions and looking to leverage the syntax to set the value of one property in a collection based on another value in a collection Typically I would do a loop: class item{ public string name {get;set;} public string value {get;set;} } class business { item item1 = new item(name="name1"); item item2 = new item(name="name2"); item item3 = new item(name="name3"); Collection<item> items = new Collection() {item1,item2,item3}; //This is what I want to simplify for( int i = 0; i < items.count; i++) { if(items[i].item.name == "name2") { //set the value items[i].item.value = "value2"; } } }

    Read the article

  • ASP.NET: Using conditionals in data binding expressions

    - by DigiMortal
    ASP.NET 2.0 has no support for using conditionals in data binding expressions but it will change in ASP.NET 4.0. In this posting I will show you how to implement Iif() function for ASP.NET 2.0 and how ASP.NET 4.0 solves this problem smoothly without any code. Problem Let’s say we have simple repeater. <asp:Repeater runat="server" ID="itemsList">     <HeaderTemplate>         <table border="1" cellspacing="0" cellpadding="5">     </HeaderTemplate>     <ItemTemplate>         <tr>         <td align="right"><%# Container.ItemIndex + 1 %>.</td>         <td><%# Eval("Title") %></td>         </tr>     </ItemTemplate>     <FooterTemplate>         </table>     </FooterTemplate> </asp:Repeater> Repeater is bound to data when form loads. protected void Page_Load(object sender, EventArgs e) {     var items = new[] {                     new { Id = 1, Title = "Headline 1" },                     new { Id = 2, Title = "Headline 2" },                     new { Id = 2, Title = "Headline 3" },                     new { Id = 2, Title = "Headline 4" },                     new { Id = 2, Title = "Headline 5" }                 };     itemsList.DataSource = items;     itemsList.DataBind(); } We need to format even and odd rows differently. Let’s say we want even rows to be with whitesmoke background and odd rows with white background. Just like shown on screenshot on right. Our first thought is to use some simple expression to avoid writing custom methods. We cannot use construct like this <%# Container.ItemIndex % 2==0 ? "white" : "whitesmoke"  %> because all we get are template compilation errors. ASP.NET 2.0: Iif() method For ASP.NET 2.0 pages and controls we can create Iif() method and call it from our templates. This is out Iif() method. protected object Iif(bool condition, object trueResult, object falseResult) {     return condition ? trueResult : falseResult; } And here you can see how to use it. <asp:Repeater runat="server" ID="itemsList">   <HeaderTemplate>     <table border="1" cellspacing="0" cellpadding="5">     </HeaderTemplate>   <ItemTemplate>     <tr style='background-color:'       <%# Iif(Container.ItemIndex % 2==0 ? "white" : "whitesmoke") %>'>       <td align="right">         <%# Container.ItemIndex + 1 %>.</td>       <td>         <%# Eval("Title") %></td>     </tr>   </ItemTemplate>   <FooterTemplate>     </table>   </FooterTemplate> </asp:Repeater> This method does not care about types because it works with all objects (and value-types). I had to define this method in code-behind file of my user control because using this method as extension method made it undetectable for ASP.NET template engine. ASP.NET 4.0: Conditionals are supported In ASP.NET 4.0 we will write … hmm … we will write nothing special. Here is solution. <asp:Repeater runat="server" ID="itemsList">   <HeaderTemplate>     <table border="1" cellspacing="0" cellpadding="5">     </HeaderTemplate>   <ItemTemplate>     <tr style='background-color:'       <%# Container.ItemIndex % 2==0 ? "white" : "whitesmoke" %>'>       <td align="right">         <%# Container.ItemIndex + 1 %>.</td>       <td>         <%# Eval("Title") %></td>     </tr>   </ItemTemplate>   <FooterTemplate>     </table>   </FooterTemplate> </asp:Repeater> Yes, it works well. :)

    Read the article

  • How can I combine several Expressions into a fast method?

    - by chillitom
    Suppose I have the following expressions: Expression<Action<T, StringBuilder>> expr1 = (t, sb) => sb.Append(t.Name); Expression<Action<T, StringBuilder>> expr2 = (t, sb) => sb.Append(", "); Expression<Action<T, StringBuilder>> expr3 = (t, sb) => sb.Append(t.Description); I'd like to be able to compile these into a method/delegate equivalent to the following: void Method(T t, StringBuilder sb) { sb.Append(t.Name); sb.Append(", "); sb.Append(t.Description); } What is the best way to approach this? I'd like it to perform well, ideally with performance equivalent to the above method. UPDATE So, whilst it appears that there is no way to do this directly in C#3 is there a way to convert an expression to IL so that I can use it with System.Reflection.Emit?

    Read the article

  • Getting Dynamic in SSIS Queries

    - by ejohnson2010
    When you start working with SQL Server and SSIS, it isn’t long before you find yourself wishing you could change bits of SQL queries dynamically. Most commonly, I see people that want to change the date portion of a query so that you can limit your query to the last 30 days, for example. This can be done using a combination of expressions and variables. I will do this in two parts, first I will build a variable that will always contain the 1 st day of the previous month and then I will dynamically...(read more)

    Read the article

  • rm command and regular expressions via Linux BASH shell

    - by PeanutsMonkey
    I am attempting to use regular expressions to remove set of files however the bash shell returns the message rm: cannot remove `[0-99]+ -': No such file or directory rm: cannot remove `[a-zA-Z': No such file or directory rm: cannot remove `]+.[a-z]+': No such file or directory The command is [0-99]+\ - [a-zA-Z ]+\.[a-z]+ Questions Can I use regular expressions? If yes, how do I use them with commands such as rm, mkdir, etc

    Read the article

  • How To Use Regular Expressions for Data Validation and Cleanup

    You need to provide data validation at the server level for complex strings like phone numbers, email addresses, etc. You may also need to do data cleanup / standardization before moving it from source to target. Although SQL Server provides a fair number of string functions, the code developed with these built-in functions can become complex and hard to maintain or reuse. The Future of SQL Server Monitoring "Being web-based, SQL Monitor 2.0 enables you to check on your servers from almost any location" Jonathan Allen.Try SQL Monitor now.

    Read the article

  • Using LINQ Lambda Expressions to Design Customizable Generic Components

    LINQ makes code easier to write and maintain by abstracting the data source. It provides a uniform way to handle widely diverse data structures within an application. LINQ’s Lambda syntax is clever enough even to allow you to create generic building blocks with hooks into which you can inject arbitrary functions. Michael Sorens explains, and demonstrates with examples.

    Read the article

  • Using LINQ Lambda Expressions to Design Customizable Generic Components

    LINQ makes code easier to write and maintain by abstracting the data source. It provides a uniform way to handle widely diverse data structures within an application. LINQ’s Lambda syntax is clever enough to even allow you to create generic building blocks with hooks, into which you can inject arbitrary functions. Michael Sorens explains, and demonstrates with examples. span.fullpost {display:none;}

    Read the article

  • Databinder.Eval using Lamda Expressions

    Using lambda expression to help with compile time checking of Eval statements...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • List querying with Lamda Expressions in C#.NET

    - by Pavan Kumar Pabothu
    public class Employees {     public int EmployeeId { get; set; }     public string Name { get; set; }     public decimal Salary { get; set; } } List<Employees> employeeList = new List<Employees>(); List<Employees> resultList = new List<Employees>(); decimal maxSalary; List<string> employeeNames = new List<string>(); protected void Page_Load(object sender, EventArgs e) {     if (!IsPostBack)     {         FillEmployees();     }     // Getting a max salary     maxSalary = employeeList.Max((emp) => emp.Salary);     // Filtering a List     resultList = employeeList.Where((emp) => emp.Salary > 50000).ToList();     // Sorting a List     // To get a descending order replace OrderBy with OrderByDescending     resultList = employeeList.OrderBy<Employees, decimal>((emp) => emp.Salary).ToList();     // Get the List of employee names only     employeeNames = employeeList.Select<Employees, string>(emp => emp.Name).ToList();        // Getting a customized object with a given list     var employeeResultSet = employeeList.Select((emp) => new { Name = emp.Name, BigSalary = emp.Salary > 50000 }).ToList(); } private void FillEmployees() {     employeeList.Add(new Employees { EmployeeId = 1, Name = "Shankar", Salary = 125000 });     employeeList.Add(new Employees { EmployeeId = 2, Name = "Prasad", Salary = 90000 });     employeeList.Add(new Employees { EmployeeId = 3, Name = "Mahesh", Salary = 36000 }); }

    Read the article

  • Use Expressions with LINQ to Entities

    - by EltonStoneman
    [Source: http://geekswithblogs.net/EltonStoneman] Recently I've been putting together a generic approach for paging the response from a WCF service. Paging changes the service signature, so it's not as simple as adding a behavior to an existing service in config, but the complexity of the paging is isolated in a generic base class. We're using the Entity Framework talking to SQL Server, so when we ask for a page using LINQ's .Take() method we get a nice efficient SQL query for just the rows we want, with minimal impact on SQL Server and network traffic. We use the maximum ID of the record returned as a high-water mark (rather than using .Skip() to go to the next record), so the approach caters for records being deleted between page requests. In the paged response we include a HasMorePages indicator, computed by comparing the max ID in the page of results to the max ID for the whole resultset - if the latter is bigger, then there are more pages. In some quick performance testing, the paged version of the service performed much more slowly than the unpaged version, which was unexpected. We narrowed it down to the code which gets the max ID for the full resultset - instead of building an efficient MAX() SQL query, EF was returning the whole resultset and then computing the max ID in the service layer. It's easy to reproduce - take this AdventureWorks query:             var context = new AdventureWorksEntities();             var query = from od in context.SalesOrderDetail                         where od.ModifiedDate >= modified                          && od.SalesOrderDetailID.CompareTo(id) > 0                         orderby od.SalesOrderDetailID                         select od;   We can find the maximum SalesOrderDetailID like this:             var maxIdEfficiently = query.Max(od => od.SalesOrderDetailID);   which produces our efficient MAX() SQL query. If we're doing this generically and we already have the ID function in a Func:             Func<SalesOrderDetail, int> idFunc = od => od.SalesOrderDetailID;             var maxIdInefficiently = query.Max(idFunc);   This fetches all the results from the query and then runs the Max() function in code. If you look at the difference in Reflector, the first call passes an Expression to the Max(), while the second call passes a Func. So it's an easy fix - wrap the Func in an Expression:             Expression<Func<SalesOrderDetail, int>> idExpression = od => od.SalesOrderDetailID;             var maxIdEfficientlyAgain = query.Max(idExpression);   - and we're back to running an efficient MAX() statement. Evidently the EF provider can dissect an Expression and build its equivalent in SQL, but it can't do that with Funcs.

    Read the article

  • Expressions that are idiomatic in one language but not used or impossible in another

    - by Tungsten
    I often find myself working in unfamiliar languages. I like to read code written by others and then jump in and write something myself before going back and learning the corners of each language. To speed up this process, it really helps to know a few of the idioms you'll encounter ahead of time. Some of these, I've found are fairly unique. In Python you might do something like this: '\n'.join(listOfThings) Not all languages allow you to call methods on string literals like this. In C, you can write a loop like this: int i = 50; while(i--) { /* do something 50 times */ } C lets you decrement in the loop condition expression. Most more modern languages disallow this. Do you have any other good examples? I'm interested in often used constructions not odd corner cases.

    Read the article

  • SQL Server: Writing CASE expressions properly when NULLs are involved

    - by Mladen Prajdic
    We’ve all written a CASE expression (yes, it’s an expression and not a statement) or two every now and then. But did you know there are actually 2 formats you can write the CASE expression in? This actually bit me when I was trying to add some new functionality to an old stored procedure. In some rare cases the stored procedure just didn’t work correctly. After a quick look it turned out to be a CASE expression problem when dealing with NULLS. In the first format we make simple “equals to” comparisons to a value: SELECT CASE <value> WHEN <equals this value> THEN <return this> WHEN <equals this value> THEN <return this> -- ... more WHEN's here ELSE <return this> END Second format is much more flexible since it allows for complex conditions. USE THIS ONE! SELECT CASE WHEN <value> <compared to> <value> THEN <return this> WHEN <value> <compared to> <value> THEN <return this> -- ... more WHEN's here ELSE <return this> END Now that we know both formats and you know which to use (the second one if that hasn’t been clear enough) here’s an example how the first format WILL make your evaluation logic WRONG. Run the following code for different values of @i. Just comment out any 2 out of 3 “SELECT @i =” statements. DECLARE @i INTSELECT  @i = -1 -- first resultSELECT  @i = 55 -- second resultSELECT  @i = NULL -- third resultSELECT @i AS OriginalValue, -- first CASE format. DON'T USE THIS! CASE @i WHEN -1 THEN '-1' WHEN NULL THEN 'We have a NULL!' ELSE 'We landed in ELSE' END AS DontUseThisCaseFormatValue, -- second CASE format. USE THIS! CASE WHEN @i = -1 THEN '-1' WHEN @i IS NULL THEN 'We have a NULL!' ELSE 'We landed in ELSE' END AS UseThisCaseFormatValue When the value of @i is –1 everything works as expected, since both formats go into the –1 WHEN branch. When the value of @i is 55 everything again works as expected, since both formats go into the ELSE branch. When the value of @i is NULL the problems become evident. The first format doesn’t go into the WHEN NULL branch because it makes an equality comparison between two NULLs. Because a NULL is an unknown value: NULL = NULL is false. That is why the first format goes into the ELSE Branch but the second format correctly handles the proper IS NULL comparison.   Please use the second more explicit format. Your future self will be very grateful to you when he doesn’t have to discover these kinds of bugs.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >