Search Results

Search found 7127 results on 286 pages for 'calculated columns'.

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

  • T-SQL Operations on a Calculated Date Field

    - by firedrawndagger
    Can I do WHERE operations on a calculated date field? I have a lookup field, which has been written badly in SQL and unfortunately I can't change it. But basically it stores dates as characters such as "July-2010" or "June-2009" (along with other non date data). I want to extract the dates first (which I did using a LIKE opertor) and then extract data based on a date range. SELECT BusinessUnit, Lookup, ReleaseDate FROM ( SELECT TOP 10 LookupColumn As Lookup, BU as BusinessUnit, CONVERT(DATETIME, REPLACE(LookupColumn,'-',' ')) as ReleaseDate FROM [dbo].[LookupTable] WHERE LookupColumn LIKE N'%-2010' ) MyTable ORDER BY ReleaseDate WHERE ReleaseDate = '2010-02-01' I'm having issues with WHERE operator. I would assume creating a subquery to encapsulate the calculated field would allow me to do operations with it such as WHERE but maybe I'm wrong. Bottom line is it possible to do operations on calculated fields?

    Read the article

  • Calculated Fields - Idiosyncracies

    - by PointsToShare
    © 2011 By: Dov Trietsch. All rights reserved Calculated Fields and some of their Idiosyncrasies Did you try to write a calculate field formula directly into the screen? Good Luck – You’ll need it! Calculated Fields are a sophisticated OOB feature of SharePoint, so you could think that they are best left to the end users – at least to the power users. But they reach their limits before the “Professionals “do, and the tough ones come back to us anyway. Back to business; the simpler the formula, the easier it is. Still, use your favorite editor to write it, then cut it and paste it to the ridiculously small window. What about complex formulae? Write them in steps! Here is a case in point and an idiosyncrasy or two. Our welders need to be certified and recertified every two years. Some of them are certifiable…., but I digress. To be certified you need to pass an eye exam, and two more tests – test A and test B. for each of those you have an expiry date. When renewed, each expiry date is advanced by two years from the date of renewal. My users wanted a visual clue so that when the supervisor looks at the list, she’ll have a KPI symbol telling her if anything expired (Red), is going to expire within the next 90 days (Yellow) or is not to be worried about (green). Not all the dates are filled and any blank date implies a complete lack of certification in the particular requirement. Obviously, I needed to figure the minimal of these 3 dates – a simple enough formula: =MIN([Date_EyeExam], {Date_TestA], [Date_TestB]). Aha! Here is idiosyncrasy #1. When one of the dates is a null, MIN(Date1, Date2) returns the non null date. Null is construed as “Far, far away”. The funny thing is that when you compare it to Today, the null is the lesser one. So a null it is less than today, but not when MIN is calculated. Now, to me the fact that the welder does not have an exam date, is synonymous with his exam being prehistoric, or at least past due. So here is what I did: Solution: Let’s set a blank date to 1/1/1800. How will we do that? Use the IF. IF([Field] rel relValue, TrueValue, FalseValue). rel is any relationship operator <, >, <=, >=, =, <>. If the field is related to the relValue as prescribed, the “IF” returns the TrueValue, otherwise it returns the FalseValue. Thus: =IF([SomeDate]="",1/1/1800,[SomeDate]) will return 1/1/1800 if the date is blank and the date itself if not. So, using this formula, if the welder missed an exam, the returned exam date will be far in the past. It would be nice if we could take such a formula and make it into a reusable function. Alas, here is a calculated field serious shortcoming: You cannot write subs and functions!! Aha, but we can use interim calculated fields! So let’s create 3 calculated fields as follows: 1: c_DateTestA as a calculated field of the date type, with the formula:  IF([Date_TestA]="",1/1/1800,[Date_TestA]) 2: c_DateTestB as a calculated field of the date type, with the formula:  IF([Date_TestB]="",1/1/1800,[Date_TestB]) 3: c_DateEyeExam as a calculated field of the date type, with the formula:  IF([Date_EyeExam]="",1/1/1800,[Date_EyeExam]) And now use these to get c_MinDate. This is again a calculated field of type date with the formula: MIN(c_DateTestA, cDateTestB, c_DateEyeExam) Note that I missed the square parentheses. In “properly named fields – where there are no embedded spaces, we don’t need the square parentheses. I actually strongly recommend using underscores in place of spaces in all the field names in your lists. Among other things, it makes using CAML much simpler. Now, we still need to apply the KPI to this minimal date. I am going to use the available KPI graphics that come with SharePoint and are always available in your 12 hive. "/_layouts/images/kpidefault-2.gif" is the Red KPI "/_layouts/images/kpidefault-1.gif" is the Yellow KPI "/_layouts/images/kpidefault-0.gif" is the Green KPI And here is the nested IF formula that will do the trick: =IF(c_MinDate<=Today,"/_layouts/images/kpidefault-2.gif", IF(cMinDate<Today+90,"/_layouts/images/kpidefault-1.gif","/_layouts/images/kpidefault-0.gif")) Nice! BUT when I tested, it did not work! This is Idiosyncrasy #2: A calculated field based on a calculated field based on a calculated field does not work. You have to stop at two levels! Back to the drawing board: We have to reduce by one level. How? We’ll eliminate the c_DateX items in the formula and replace them with the proper IF formulae. Notice that this needs to be done with precision. You are much better off in doing it in your favorite line editor, than inside the cramped space that SharePoint gives you. So here is the result: MIN(IF([Date_TestA]="",1/1/1800,[ Date_TestA]), IF([Date_TestB]="",1/1/1800,[ Date_TestB]), 1/1/1800), IF([Date_EyeExam]="",1/1/1800,[Date_EyeExam])) Note that I bolded the parentheses and painted them red. They have to match for this formula to work. Now we can leave the KPI formula as is and test again. This time with SUCCESS! Conclusion: build the inner functions first, and then embed them inside the outer formulae. Do this as long as necessary. Use your favorite line editor. Limit yourself to 2 levels. That’s all folks! Almost! As soon as I finished doing all of the above, my users added yet another level of complexity. They added another test, a test that must be passed, but never expires and asked for yet another KPI, this time in Black to denote that any test is not just past due, but altogether missing. I just finished this. Let’s hope it ends here! And OH, the formula  =IF(c_MinDate<=Today,"/_layouts/images/kpidefault-2.gif",IF(cMinDate<Today+90,"/_layouts/images/kpidefault-1.gif","/_layouts/images/kpidefault-0.gif")) Deals with “Today” and this is a subject deserving a discussion of its own!  That’s all folks?! (and this time I mean it)

    Read the article

  • Performance Gains using Indexed Views and Computed Columns

    - by NeilHambly
    Hello This is a quick follow-up blog to the Presention I gave last night @ the London UG Meeting ( 17th March 2010 ) It was a great evening and we had a big full house (over 120 Registered for this event), due to time constraints we had I was unable to spend enough time on this topic to really give it justice or any the myriad of questions that arose form the session, I will be gathering all my material and putting a comprehensive BLOG entry on this topic in the next couple of days.. In the meantime here is the slides from last night if you wanted to again review it or if you where not @ the meeting If you wish to contact me then please feel free to send me emails @ [email protected] Finally  - a quick thanks to Tony Rogerson for allowing me to be a Presenter last night (so we know who we can blame !)  and all the other presenters for thier support Watch this space Folks more to follow soon.. 

    Read the article

  • TableAdapter to return ONLY selected columns? (VS2008)

    - by MattSlay
    (VS2008) I'm trying to configure a TableAdapter in a Typed DataSet to return only a certain subset of columns from the main schema of the table on which it is based, but it always returns the entire schema (all columns) with blank values in the columns I have omitted. The TableAdpater has the default Fill and GetData() methods that come from the wizard, which contain every column in the table, which is fine. I then added a new parameterized query method called GetActiveJobsByCustNo(CustNo), and I only included a few columns in the SQL query that I actually want to be in this table view. But, again, it returns all the columns in the master table schema, with empty values for the columns I omitted. The reason I am wanting this, is so I can just get a few columns back to use that table view with AutoGenerateColumns in an ASP.NET GridView. With it giving me back EVERY column i nthe schema, my presentation GridView contains way more columns that I want to show th user. And, I want to avoid have to declare the columns in the GridView.

    Read the article

  • Syntax error in SharePoint calculated column formula

    - by Jan Aagaard
    Is it possible to debug SharePoint calculated column formulas? I am trying with a really simple SharePoint calculated formula =IF([YTD]<[Budget], "OK", "Not OK"). This being a Danish installations of SharePoint I believe the fomula should look like this: =HVIS([YTD]<=[Budget]; "OK"; "Not OK") But this just leaves with the same syntax error or not supported error. I have tried all combinations of IF/HVIS, with/without the square brackets, comma/semicolon, single quotes/double quotes, but nothing works. The formula =YTD<=Budget works.

    Read the article

  • Registry (possibly) error in Windows 7 : I can not resize columns in any program except explorer

    - by Klugeman
    I experimented with Winbuilder and after some time I noticed that I cannot resize columns in uTorrent, move bookmarks and bookmark folders in Chrome, then cannot resize columns in Comodo Programs Manager - everywhere !!! Fro example , in uTorrent, columns just froze where I left them last time. But Windows Explorer is functioning properly. Where should I search for this problem ?? I think this is something wrong with registry, but regular registry cleaners do not helps. And I cannot even resize a columns in regedit - this is a real hell !

    Read the article

  • Ext JS 4: Show all columns in Ext.grid.Panel as custom option

    - by MacGyver
    Is there a function that can be called on an Ext.grid.Panel in ExtJS that will make all columns visible, if some of them are hidden by default? Whenever an end-user needs to show the hidden columns, they need to click each column. Below, I have some code to add a custom menu option when you select a field header. I'd like to execute this function so all columns show. As an example below, I have 'Project ID' and 'User Created' hidden by default. By choosing 'Select All Columns' would turn those columns on, so they show in the list view. listeners: { ... }, afterrender: function() { var menu = this.headerCt.getMenu(); menu.add([{ text: 'Select All Columns', handler: function() { var columnDataIndex = menu.activeHeader.dataIndex; alert('custom item for column "'+columnDataIndex+'" was pressed'); } }]); } } }); =========================== Answer (with code): Here's what I decided to do based on Eric's code below, since hiding all columns was silly. afterrender: function () { var menu = this.headerCt.getMenu(); menu.add([{ text: 'Show All Columns', handler: function () { var columnDataIndex = menu.activeHeader.dataIndex; Ext.each(grid.headerCt.getGridColumns(), function (column) { column.show(); }); } }]); menu.add([{ text: 'Hide All Columns Except This', handler: function () { var columnDataIndex = menu.activeHeader.dataIndex; alert(columnDataIndex); Ext.each(grid.headerCt.getGridColumns(), function (column) { if (column.dataIndex != columnDataIndex) { column.hide(); } }); } }]); }

    Read the article

  • sharepoint: conditional formula for calculated field

    - by fiuman007
    hi all, i want to create a formula for change my value from EUR into USD. FIELD1 (choice): EUR, USD FIELD2 (number): amount in EUR or USD Now, if USD is selected in FIELD1 following should happen: calaculate FIELD2*0,71 otherwiese the result is FIELD2. FIELD3 (calculated): =IF(FIELD1="USD", (FIELD2*0,71), FIELD2)) When I use this formula I get error message: The formula contains a syntax error or is not supported. Any idea? I´m using english version of WSS 3.0. Thank you, fiuman007

    Read the article

  • Sharepoint calculated Date field shows incorrectly in non-US region

    - by Proforce
    If a SharePoint user (with Regional Settings set to UK) views a calculated date field in a View details form, the field shows incorrectly showing the date is in US format, thus 01-Apr-2010 for 03-Jan-2010, and doesnt show unresolvalble dates such as 31-Dec-2010. This applies even with a simnple =[Modified] formula The Server is set up in the US for that locale. Does anyone know of a workaround for this or if there is a patch available ? Thanks in advance..

    Read the article

  • Sharepoint 2007 calculated Date field shows incorrectly in non-US region

    - by Proforce
    If a SharePoint user (with Regional Settings set to UK) views a calculated date field in a View details form, the field shows incorrectly. I am using: ddwrt:FormatDateTime(string(@RenewalDate), 1033, 'dd MMMM yyyy') Which shows 04 January 2010 for 01/04/2010 and, doesnt show unresolvable dates such as 31-Dec-2010. This applies even with a simnple =[Modified] formula The Server is set up in the US for that locale.

    Read the article

  • Excel, Pivot Calculated formula: SUM(Field1)/AVG(Field2)

    - by Bas
    I've a simple table with some amount and interval in sec by date and product name. Month | Product | Amount | Interval in sec ------------------------------------------ 05-'12| Prod A | 10 | 5 05-'12| Prod A | 3 | 5 05-'12| Prod B | 4 | 5 05-'12| Prod C | 13 | 5 05-'12| Prod C | 5 | 5 From this table I've derived a Pivot table with SUM(Amount), AVERAGE(Interval in sec) by Month and Product. Month | Product | SUM of Amount | AVG of Interval in sec -------------------------------------------------------- 05-'12| Prod A | 13 | 5 05-'12| Prod B | 4 | 5 05-'12| Prod C | 18 | 5 So far So good... Now i want to add and extra column to my Pivot table with gives me the outcome of SUM of Amount / AVG of Interval in sec Adding a calculated value =SUM(Amount)/AVERAGE(Interval) is not giving me the right values. Exel gives me. Month | Product | SUM of Amount | AVG of Interval in sec | Amount per sec ------------------------------------------------------------------------- 05-'12| Prod A | 13 | 5 | 1.3 05-'12| Prod B | 4 | 5 | 0.8 05-'12| Prod C | 18 | 5 | 1.8 What it actually is doing is =SUM(Amount)/SUM(Interval in sec) for every Month and Product based on the values in the first table... But I'm looking for Month | Product | SUM of Amount | AVG of Interval in sec | Amount per sec ------------------------------------------------------------------------- 05-'12| Prod A | 13 | 5 | 2.6 05-'12| Prod B | 4 | 5 | 0.8 05-'12| Prod C | 18 | 5 | 3.6 So litterly devide pivot field 'Sum of Amount' by pivot field 'AVG of Interval in sec' How to achieve this? Thank you in advanced

    Read the article

  • Word 2010, Multiple Columns, Vertical center one column only

    - by Nancy N Jones
    I am creating a document with two columns in Microsoft Word 2010. I want the first column to be centered vertically. I want the second column to be on the same page and the vertical placement to be from the top. I highlight my text in the first column that I want centered vertically, then go to Page Layout Margins Custom Margins Layout, you can choose to center the vertical alignment. I have choosen the "Section Start" to be "Column" and also tried "Continuous." In all cases it always shifts all of my second column information to a new page. I don't want my second column text to be on a new page, I want it to be on the same page and vertically aligned from the top--not the center. Am I understanding the functionality of the Section Start on the Layout tab correctly? Maybe the page layout isn't the correct formatting to use. What I am really doing is formatting columns. I haven't found anywhere to format the columns for this. Am I missing some important column formatting features? I know that I can use the paragraph formatting and add space above the first line of text to make it look like it is centered vertically. However, this is a template for a master document and will be changed frequently. I really would like the first column text to be automatically formatted to be centered vertically without having to go in and manually change the space above the paragraph every time. Your assistance would be greatly appreciated.

    Read the article

  • Infragistics Webgrid (Datagrid) dynamic adjusting columns

    - by mattgcon
    I want to explain this as best as I can. I have a Webgrid with a certain amount of columns. What I want is for the columns to adjust to the size of the largest string within each column, where the total of all width of columns does not exceed the width of the webgrid. At the same time however if the width of all columns is less than the width of the webgrid I want each column to adjust proportionately so that the total of columns widths equal the width of the webgrid. Can anyone help me with this logic?

    Read the article

  • Add columns to a datatable in c#?

    - by Pandiya Chendur
    I have a csv reader class that reads a .csv file and its values.... I have created datatable out of it... Consider my Datatable contains three header columns Name,EmailId,PhoneNo.... The values have been added successfully.... Now i want to add two columns IsDeleted,CreatedDate to this datatable... I have tried this but it doesn't seem to work, foreach (string strHeader in headers) { dt.Columns.Add(strHeader); } string[] data; while ((data = reader.GetCSVLine()) != null) { dt.Rows.Add(data); } dt.Columns.Add("IsDeleted", typeof(byte)); dt.Columns.Add(new DataColumn("CreatedDate", typeof(DateTime))); foreach (DataRow dr in dt.Rows) { dr["IsDeleted"] = Convert.ToByte(0); dr["CreatedDate"] = Convert.ToDateTime(System.DateTime.Now.ToString()); dt.Rows.Add(dr); } When i try to add isdeleted values an error saying This row already belongs to this table. ....

    Read the article

  • SharePoint - Summing Calculated Columns By Groups (DVWP)

    - by Mark Rackley
    I had a problem… okay.. okay.. so I have many problems… but let’s focus on one in particular or this blog post would never end… okay? Thank you…. So, I had an electronic timesheet where users entered hours for each day of the week. It also had a “Week Total” column which was a calculated column of the sum. The calculated column looked like this: Pretty easy.. nothing spectacular. So, what’s the problem? WELL……………….. There is a row in the timesheet for each task a person worked on in a given week. So, if you worked on 4 tasks, you would have 4 rows of data, and 4 week totals for that week: This is all fine and dandy, but I want to know what the total was for the entire week. Yes.. I realize the answer is 24 from my example… I mean, I know how to add! I just want SharePoint to display it for me for the executives (we all know, they have math problems).  You may be thinking, hey genius (in a sarcastic tone of course), why don’t you just go to the view and total on the “Week Total” field. What a brilliant idea! Why didn’t I think of that… let’s go to the view and do just that…. Ohhhhhh… you can’t total on a Calculated Column.. it’s not even an option…  Yeah… I had the same moment. So, what do you do? Well… what do you think I did? 1) Googled “SharePoint total calculated column” 2) Said it couldn’t be done 3) Took a nap 4) Asked the question on twitter? The correct answer of course is number 4… followed by number 3… although I may have told my boss number 2 so that I look more brilliant than I am? It’s safe to say I did NOT try to find the solution on my own doing step 1… that would be just WAY to easy… So, anyway, I posted the question on Twitter and it turns out several people had suggestions from using jQuery to using DVWPs. I tend to be a big fan of the DVWP except for the disgusting process of deploying them to another farm.. ugh… just shoot me…. so, that is the solution I went with. Laura Rogers (@WonderLaura) has a super duper easy to follow video on the subject over at EndUserSharePoint.com: SharePoint: Displaying Calculated Column SUMS in a View (Screencast) Laura’s video was very easy to follow and was ALMOST exactly what I needed. She does a great job walking you through every step of summing up a calculated field which was PART of my problem. The other part was my list is grouped by date! So, I wanted to see for a given week, the summed “Week Total” of hours. Laura got me on the right track with her video and I dug a little deeper into the DVWP to accomplish my task. So, here are the steps you follow: 1. Click on the "chevron” (I didn’t know it was actually called that until I heard Laura say it).. I always call it the “little-button-in-the-top-right-corner-with-the-greater-than-sign”.. but “chevron” is much shorter. So, click on the chevron, click on “Sort and Group”. The Add the field you want to group by, in my example it is the “Monday Date” of the timesheet entry. Make sure to check the check boxes for “Show Group Header” AND “Show Group Footer”. Click “OK”. The view now shows the count of each grouped set of data: Interesting, this looks very similar to Laura’s video… right? So, let’s take a look at the code for the Count: Count : <xsl:value-of select="count($nodeset)" /> Wow, also very similar… except in Laura’s video it looks like: Count : <xsl:value-of select="count($Rows)" /> So.. the only difference is that instead of $Rows we have $nodeset. It turns out the $nodeset will go through each Row in the group just like $Rows goes through each row in the entire view. So, using the exact same logic as in Laura’s blog except replacing $Rows with $nodeset we get the functionality of being able to sum up the values for a group. So, I want to replace “Count: #” with the total hours, this is done using the following changes to the above code: Week Total : <xsl:value-of select="sum($nodeset/@Monday)+sum($nodeset/@Tuesday) +sum($nodeset/@Wednesday)+sum($nodeset/@Thursday)+sum($nodeset/@Friday) +sum($nodeset/@Saturday)+sum($nodeset/@Sunday)" /> Our final output has the summed hours for each group! So… long story short… follow Laura’s blog, then group your list, then replace “$Rows” with “$nodeset”. One caveat, this will not work if you group by a person field. For some reason the person field does not go through each row in the group. I haven’t dug into this much yet. Maybe if I find some time… whatever that is… Anyway, Laura did all the work, I just took it one small step forward… as always, feel free to leave any additional insights you may have. We’re all learning here!

    Read the article

  • Start Time & Calculated Column Wonkiness in a SharePoint Event Calendar

    - by _zekeMouseOver
    I was creating some custom rollups on some of our event calendars and came across a very odd bug when trying to grab only the date component of the built-in Start Time field. One's first inclination will be to create a calculated column and give it the formula... =[Start Time]... and then assign its output type to be "Date Only." This works well until a user adds an All Day Event. For reasons unexplainable, the All Day Event flag causes your =[Start Time] to display the date minus one day. Here is an example of this in action:  Start Date and Time, Duration, Start Date Value and Start Day are all calculated fields. Notice how the Start Date and Time (=[Start Time]) is reporting 6:00PM of the previous day. The Start Date Value (=[Start Time] - Output Type: Number) confirms this (.75 = 6:00 PM.) Curiously enough, the Duration (=[End Time]-[Start Time]) is properly reporting the duration between 12:00AM and 11:59PM. Why? I don't know. Perhaps it's somehow bound to the regional settings on the site, but I'm not interested in changing a global site setting for the sake of one calculated field.With this information at our disposal, our calculated column to display the date part of the start date needs to be modified to add one day to the [Start Time] field if an All Day Event is selected. To determine this, we use the Duration above to assume the item is an all-day event and change our formula to be:=IF(TEXT(([End Time]-[Start Time])-TRUNC(([End Time]-[Start Time]),0),"0.000000000")="0.999305556",[Start Time] + 1, [Start Time])This will work, but what happens when the user de-selects the "All Day Event" checkbox? The duration stays the same, but all other values begin reporting the correct time: Since our formula above is strictly based on an expected duration, it will add one to the correct date, causing the date 5/11/2010 to appear. Notice though that the raw value of the start time (in this case) is a non-fractional number (40,308) whereas the all-day event was being represented as 6:00 PM (.75) of the previous day. We can use this to add one more nested branch of logic to our calculation:=IF(TEXT(([End Time]-[Start Time])-TRUNC(([End Time]-[Start Time]),0),"0.000000000")="0.999305556",IF([Start Time]=ROUND([Start Time],0),[Start Time],[Start Time]+1),[Start Time]) I feel somewhat... dirty about having to resort to this kind of calculation in what SHOULD have been a simple =[Start Time] to extract the date part of the Start Time field, but there you have it. Make sure to shower extra longer after having used it.

    Read the article

  • Can I keep columns from breaking across pages?

    - by Jakob
    In Microsoft Word 2007, if I put a passage of text into a column layout that spans two pages, Word first puts everything that fits on the first page into a column layout on the first page, then the rest into a column layout on the second page. I want to prevent this breaking. The question is difficult to phrase, so here's an example of what I want to accomplish: Instead of a c e b d f ----- g j m h k n i l o I want the columns to be preserved across the page break, like so: a f k b g l ----- c h m d i n e j o Is this possible in Microsoft Word 2007?

    Read the article

  • Excel 2007: Exporting more than 100 columns to a .prn file but data is concatenated

    - by Don1
    I want to export an Excel worksheet to a space delimited (.prn) file. The worksheet is pretty big (187 columns) and when I set the column widths and try to export the worksheet to a .prn file, the data gets cut at the 98th column (i.e. about 200 characters wide for my data) and the rest is placed directly underneath. It's like I ripped a page in half from top to bottom and placed the right-hand side directly under the left-hand side. How would I get it to export everything without getting concatenated?

    Read the article

  • Calculated Columns in Entity Framework Code First Migrations

    - by David Paquette
    I had a couple people ask me about calculated properties / columns in Entity Framework this week.  The question was, is there a way to specify a property in my C# class that is the result of some calculation involving 2 properties of the same class.  For example, in my database, I store a FirstName and a LastName column and I would like a FullName property that is computed from the FirstName and LastName columns.  My initial answer was: 1: public string FullName 2: { 3: get { return string.Format("{0} {1}", FirstName, LastName); } 4: } Of course, this works fine, but this does not give us the ability to write queries using the FullName property.  For example, this query: 1: var users = context.Users.Where(u => u.FullName.Contains("anan")); Would result in the following NotSupportedException: The specified type member 'FullName' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. It turns out there is a way to support this type of behavior with Entity Framework Code First Migrations by making use of Computed Columns in SQL Server.  While there is no native support for computed columns in Code First Migrations, we can manually configure our migration to use computed columns. Let’s start by defining our C# classes and DbContext: 1: public class UserProfile 2: { 3: public int Id { get; set; } 4: 5: public string FirstName { get; set; } 6: public string LastName { get; set; } 7: 8: [DatabaseGenerated(DatabaseGeneratedOption.Computed)] 9: public string FullName { get; private set; } 10: } 11: 12: public class UserContext : DbContext 13: { 14: public DbSet<UserProfile> Users { get; set; } 15: } The DatabaseGenerated attribute is needed on our FullName property.  This is a hint to let Entity Framework Code First know that the database will be computing this property for us. Next, we need to run 2 commands in the Package Manager Console.  First, run Enable-Migrations to enable Code First Migrations for the UserContext.  Next, run Add-Migration Initial to create an initial migration.  This will create a migration that creates the UserProfile table with 3 columns: FirstName, LastName, and FullName.  This is where we need to make a small change.  Instead of allowing Code First Migrations to create the FullName property, we will manually add that column as a computed column. 1: public partial class Initial : DbMigration 2: { 3: public override void Up() 4: { 5: CreateTable( 6: "dbo.UserProfiles", 7: c => new 8: { 9: Id = c.Int(nullable: false, identity: true), 10: FirstName = c.String(), 11: LastName = c.String(), 12: //FullName = c.String(), 13: }) 14: .PrimaryKey(t => t.Id); 15: Sql("ALTER TABLE dbo.UserProfiles ADD FullName AS FirstName + ' ' + LastName"); 16: } 17: 18: 19: public override void Down() 20: { 21: DropTable("dbo.UserProfiles"); 22: } 23: } Finally, run the Update-Database command.  Now we can query for Users using the FullName property and that query will be executed on the database server.  However, we encounter another potential problem. Since the FullName property is calculated by the database, it will get out of sync on the object side as soon as we make a change to the FirstName or LastName property.  Luckily, we can have the best of both worlds here by also adding the calculation back to the getter on the FullName property: 1: [DatabaseGenerated(DatabaseGeneratedOption.Computed)] 2: public string FullName 3: { 4: get { return FirstName + " " + LastName; } 5: private set 6: { 7: //Just need this here to trick EF 8: } 9: } Now we can both query for Users using the FullName property and we also won’t need to worry about the FullName property being out of sync with the FirstName and LastName properties.  When we run this code: 1: using(UserContext context = new UserContext()) 2: { 3: UserProfile userProfile = new UserProfile {FirstName = "Chanandler", LastName = "Bong"}; 4: 5: Console.WriteLine("Before saving: " + userProfile.FullName); 6: 7: context.Users.Add(userProfile); 8: context.SaveChanges(); 9:  10: Console.WriteLine("After saving: " + userProfile.FullName); 11:  12: UserProfile chanandler = context.Users.First(u => u.FullName == "Chanandler Bong"); 13: Console.WriteLine("After reading: " + chanandler.FullName); 14:  15: chanandler.FirstName = "Chandler"; 16: chanandler.LastName = "Bing"; 17:  18: Console.WriteLine("After changing: " + chanandler.FullName); 19:  20: } We get this output: It took a bit of work, but finally Chandler’s TV Guide can be delivered to the right person. The obvious downside to this implementation is that the FullName calculation is duplicated in the database and in the UserProfile class. This sample was written using Visual Studio 2012 and Entity Framework 5. Download the source code here.

    Read the article

  • Filter columns in flex datagrid using CheckBox

    - by Anupama
    Hi, I have a flex datagrid with 4 columns.I have a comboBox with 4 checkboxes,containing the column names of datagrid as its label.I want the datagrid to display only those columns which are selected in combobox.Can anyone tell me how this filtering of columns in datagrid can be done? Thanks in advance.

    Read the article

  • [R] Select columns for heatmap in R

    - by Philipp
    Hi stackoverflow-pros, I need your help again :) I wrote an R script, that generates a heatmap out of a given tab-seperated txt or xls file. At the moment, I delete all columns I don't want to have in the heatmap by hand in the xls file. Now I want to automatize it, but I don't know how :( The interesting columns all start the same in all xls files, followed by an individual name: xls-file 1: L1_tpm_xxxx L2_tpm_xxxx L3_tpm_xxxx xls-file 2: L1_tpm_xxxx L2_tpm_xxxx L3_tpm_xxxx L4_tpm_xxxx L5_tpm_xxxx Any ideas how to select those columns? Thanking you in anticipation, Philipp

    Read the article

  • Query a column and a calculation of columns at the same time PostgreSQL

    - by pablo
    Hi I have two tables, Products and BundleProducts that have o2o relation with BaseProducts. A BundleProduct is a collection of Products using a m2m realtion to the Products table. Products has a price column and the price of a BundleProduct is calculated as the sum of the prices of its Products. BaseProducts have columns like name and description so I can query it to get both Products and BundleProducts. Is it possible to query and sort by price both for the price column of the Products and calculated price of the BundleProducts? Thanks

    Read the article

  • Dynamic gridview columns event problem

    - by ropstah
    Hi, i have a GridView (selectable) in which I want to generate a dynamic GridView in a new row BELOW the selected row. I can add the row and gridview dynamically in the Gridview1 PreRender event. I need to use this event because: _OnDataBound is not called on every postback (same for _OnRowDataBound) _OnInit is not possible because the 'Inner table' for the Gridview is added after Init _OnLoad is not possible because the 'selected' row is not selected yet. I can add the columns to the dynamic GridView based on my ITemplate class. But now the button events won't fire.... Any suggestions? The dynamic adding of the gridview: Private Sub GridView1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.PreRender Dim g As GridView = sender g.DataBind() If g.SelectedRow IsNot Nothing AndAlso g.Controls.Count &gt; 0 Then Dim t As Table = g.Controls(0) Dim r As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal) Dim c As New TableCell Dim visibleColumnCount As Integer = 0 For Each d As DataControlField In g.Columns If d.Visible Then visibleColumnCount += 1 End If Next c.ColumnSpan = visibleColumnCount Dim ph As New PlaceHolder ph.Controls.Add(CreateStockGrid(g.SelectedDataKey.Value)) c.Controls.Add(ph) r.Cells.Add(c) t.Rows.AddAt(g.SelectedRow.RowIndex + 2, r) End If End Sub Private Function CreateStockGrid(ByVal PnmAutoKey As String) As GridView Dim col As Interfaces.esColumnMetadata Dim coll As New BLL.ViewStmCollection Dim entity As New BLL.ViewStm Dim query As BLL.ViewStmQuery = coll.Query Me._gridStock.AutoGenerateColumns = False Dim buttonf As New TemplateField() buttonf.ItemTemplate = New QuantityTemplateField(ListItemType.Item, "", "Button") buttonf.HeaderTemplate = New QuantityTemplateField(ListItemType.Header, "", "Button") buttonf.EditItemTemplate = New QuantityTemplateField(ListItemType.EditItem, "", "Button") Me._gridStock.Columns.Add(buttonf) For Each col In coll.es.Meta.Columns Dim headerf As New QuantityTemplateField(ListItemType.Header, col.PropertyName, col.Type.Name) Dim itemf As New QuantityTemplateField(ListItemType.Item, col.PropertyName, col.Type.Name) Dim editf As New QuantityTemplateField(ListItemType.EditItem, col.PropertyName, col.Type.Name) Dim f As New TemplateField() f.HeaderTemplate = headerf f.ItemTemplate = itemf f.EditItemTemplate = editf Me._gridStock.Columns.Add(f) Next query.Where(query.PnmAutoKey.Equal(PnmAutoKey)) coll.LoadAll() Me._gridStock.ID = "gvChild" Me._gridStock.DataSource = coll AddHandler Me._gridStock.RowCommand, AddressOf Me.gv_RowCommand Me._gridStock.DataBind() Return Me._gridStock End Function The ITemplate class: Public Class QuantityTemplateField : Implements ITemplate Private _itemType As ListItemType Private _fieldName As String Private _infoType As String Public Sub New(ByVal ItemType As ListItemType, ByVal FieldName As String, ByVal InfoType As String) Me._itemType = ItemType Me._fieldName = FieldName Me._infoType = InfoType End Sub Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn Select Case Me._itemType Case ListItemType.Header Dim l As New Literal l.Text = "&lt;b&gt;" & Me._fieldName & "</b>" container.Controls.Add(l) Case ListItemType.Item Select Case Me._infoType Case "Button" Dim ib As New Button() Dim eb As New Button() ib.ID = "InsertButton" eb.ID = "EditButton" ib.Text = "Insert" eb.Text = "Edit" ib.CommandName = "Edit" eb.CommandName = "Edit" AddHandler ib.Click, AddressOf Me.InsertButton_OnClick AddHandler eb.Click, AddressOf Me.EditButton_OnClick container.Controls.Add(ib) container.Controls.Add(eb) Case Else Dim l As New Label l.ID = Me._fieldName l.Text = "" AddHandler l.DataBinding, AddressOf Me.OnDataBinding container.Controls.Add(l) End Select Case ListItemType.EditItem Select Case Me._infoType Case "Button" Dim b As New Button b.ID = "UpdateButton" b.Text = "Update" b.CommandName = "Update" b.OnClientClick = "return confirm('Sure?')" container.Controls.Add(b) Case Else Dim t As New TextBox t.ID = Me._fieldName AddHandler t.DataBinding, AddressOf Me.OnDataBinding container.Controls.Add(t) End Select End Select End Sub Private Sub InsertButton_OnClick(ByVal sender As Object, ByVal e As EventArgs) Console.WriteLine("insert click") End Sub Private Sub EditButton_OnClick(ByVal sender As Object, ByVal e As EventArgs) Console.WriteLine("edit click") End Sub Private Sub OnDataBinding(ByVal sender As Object, ByVal e As EventArgs) Dim boundValue As Object = Nothing Dim ctrl As Control = sender Dim dataItemContainer As IDataItemContainer = ctrl.NamingContainer boundValue = DataBinder.Eval(dataItemContainer.DataItem, Me._fieldName) Select Case Me._itemType Case ListItemType.Item Dim fieldLiteral As Label = sender fieldLiteral.Text = boundValue.ToString() Case ListItemType.EditItem Dim fieldTextbox As TextBox = sender fieldTextbox.Text = boundValue.ToString() End Select End Sub End Class

    Read the article

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