.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Compile issue with List<> and Linq

Posted By:      Posted Date: September 02, 2010    Points: 0   Category :SharePoint
I am pretty sure this is some framework version issue but I am getting this on a (custom layout) page compile migrated over from MOSS. The following code complies in my MOSS 2007 environment but does not in my new 2010 environment. Thanks in advance for any help. Code section #1: private bool isSuccessReturnCode(string s) { bool bReturn = false; // Following line fails looking for ';' XDocument loaded = XDocument.Parse(s); var q = from c in loaded.Descendants("Node") select (string)c.Element("ReturnCode");   Code Section #2 private InvoiceItem getInvoiceItem(Guid ID) { List<InvoiceItem> InvoiceItems = ((List<InvoiceItem>)ViewState["INVOICEITEMS"]);

View Complete Post

More Related Resource Links

C#, LINQ: (List<>) Question???


Hi Everyone,

I have a strange problem:


There is an entity (Table) called "Filters" in my .edmx which has all my tables and stuff in it (to use it for LINQ queries)

I have created a class called "CustomFilters" which inherits "Filters". So now my cutom class has all the properties of the original "Filters" class (table) and 1 more additional property that i wanted which is a List of "CustomFilters":

List<CustomFilters> children = new List<CustomFilters>();

Now i get all my records into:

List<CustomFilters> theOriginalList = new List<CustomFilters>();

NOTE: first all records are tken into a List<Filters> and then these are added into List<CustomFilters> where List<CustomFilters> for children of that record is added, and then children of the child records, and so on......

so now, every record is an instance of CustomFilters which has a property named "children" which is a list again; and each child again has instanaces of "CustomFilters", and each instance again has children...and on and on and on.....

(basiacally its a data source for a treeview in my silverlight control)

every thing is good and working as expected.


Query an arraylist of array list using linq


I have an array list called Customer. I t holds a list of array list which has the account details.

proj.customer -> collection of arraylist of type customer

proj.customer.account -> collection of arraylist of type account

Account array list holds type account and it has a poperty account balance. How can I query all accounts which has account balance  >100

I tried the following one

var Accountlist= from Account accountdetails in proj.customer.account

where accountid.balance >100

select accountdetails.id

But it is always throwing an error saying cannot cast type customer to type account

Please help

Datalist with embedded Grid or List...Sub Totals issue with iteration


Let me see if one of you can assist with this one...


i have a similar situation, but mine does not use the selected item (item Command). Here is what the form is to do:


1. this is for an educational environment, so we use SID- NOT SSN's, but i use the SID as a filter in the subset as the grouping unique id.

2. I'm trying to inject a sub total row at the last line item of each SID (if more than one item in the report for that SID).

3. I'm looping thru the items in the Datalist Item Command with a for each (item i in Datalist2.Items).

Issue with List Definition of same base content type and deployed via same feature


I am trying to deploy two custom list definitions using only one single feature.  Below are the details of my issue.

  • Two custom list definitions
  • Each custom list definition has its own custom content type
  • Each custom content type inherits from the base content type Picture (Type = 109)
  • The custom list definitions are grouped together under one single feature
  • The custom content types are grouped together under a seperate single feature

When I deploy my solution in this configuration, the second list definition gets the first custom content type applied to it and the list schema from the first list definition is also applied to the second list definition.

What makes this more interesting, when I seperate both of the list definitions under two seperate features it all works fine.  Custom content types and list schemas get applied correctly.

Can anyone tell me why I can not deploy both list definitions under one single feature?

If you need me to post any of the origional code or XML to this post please let me know.



Linq query results to List collection



I have a GridView in my page. I want to use below code in code beind. query nothwing DB using linq . add linq query result to new list and then bind list as gridview Datasource

I use below code . But I don't know how to add results to List? Could any one tell me how !

Public Class OrderCity
        Private _name As String
        Private _city As String
        Public Property name As String
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value

            End Set
        End Property
        Public Property city As String
                Return _city
            End Get
            Set(ByVal value As String)
                _city = value

            End Set
        End Property
    End Class
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim dbe As New SFFAV1DataContext
        Dim latestadsDs = From p In dbe.Products _
                            Select New With {p.Title, p.ProducedCity} _
                             Take (2)

        Dim FilteredList As New List(Of OrderCity)()
        For Each result In latestadsDs
            Dim Menedfcou = Nothing
            FilteredList.Insert(0, Menedfcou)

How to handle null while converting from my datatable to List<> using LINQ


I am converting my datatable to LISt using LINQ
how do I handle nulls coming from database

List<Port> portDetails = new List<Port>();
DataTable dt = ds.Tables[0];               
portDetails = (from q in dt.AsEnumerable()
select new Port
PortCode = q.Field<string>("Code"),
ExtCode = q.Field<string>("Nb"),
Name = q.Field<string>("Name"))

In the above query if Code is null I do not want property
portcode to be set to the value it should only set if it is
not null or not blank 
PortCode = q.Field<string>("Code"),

What should be syntax
I was trying somethign like this which doesnt work
Portcode = q.Field<bool>("Code") == null ? null : q.Field<bool>("Code")


Reorder List Header Columns Issue

Hello to all, Today my senior told me to add functionality of Drag N Drop inside the GridView then i googled it and i found that Reorder List is the Same control i am looking for. But after doing Analysis on that i found that these templates are there in ReOrder List Control DragHandleTemplate EditItemTemplate EmptyListTemplate InsertItemTemplate ItemTemplate ReorderTemplate Its same as gridview or listview control but its dosent support paging in that.But i am not able to found Header Template inside that Control.   So Can any 1 Tell me how can i add header Template inside ReOrder List so Each Column will have its Rows. My sample example 1 Column is Eating all my columns and the rest of the columns are blank. I am looking any solution for this.   Waiting for a Solution   Regards    

Insert a "Select User" row in Linq for a dropdown list

I'm new to Linq. I have searched and searched the web for a soluion, and can't find anything. I have a Linq query and I want to insert a row ("Select User") to the top before I pass it to the drop down list. I've been trying to use the Union but to now avail (it keeps telling me that my object doesn't support the Union method). My code, prior to attempting to inser a row, is very simple.public SelectList DropDown_Users()        {            var context = new VivarianDataContext();            var query = from t in context.AspnetUsers                        select new { t.UserId, t.LastName };            list = new SelectList(query.AsEnumerable(), "UserId", "LastName");            return list;        }Now I try to insert a row and I found this on the internet and it seems to say that his solution will work. But it is filled with syntax errors. http://magicode.wordpress.com/2009/08/20/inserting-an-item-in-iqueryable-object-using-union-met

Linq forward compatibility issue

In Linq 3.5 I used to be able to do this, but the code in bold is no longer compatible in Linq 4.0, Is there another way to declare the query variable prior to assigning it (PLEASE DO NOT SUGGEST TO DECLARE AS VAR, IT DOES NOT WORK AND CAN NOT BE DECLARED AS NULL):   ProjectArtifactsDataContext dbProjectAttributes = new ProjectArtifactsDataContext();IQueryable<ProjectArtifacts.Defect> query1 = null;   This type of declaration allowed me to create aggregate and complex queries such as         if (UserControlHost.ShowMyItemsOnly)        {            Guid currentUserId = (Guid)Membership.GetUser(Membership.GetUser().UserName).ProviderUserKey;            query1 = dbProjectAttributes.Defects.Where(defect =>                 defect.Active == true && defect.AssignedTo == currentUserId);        }         else        {            if (FilterInactive == true)                que

How to update List Items with LINQ?

In the code below, the For Each will loop through the list and populate the ListBox.  When I add "item.LeadTime = 5" to try updating an item, Visual Studio says that it is ReadOnly.  Any ideas on what's wrong or missing from the code? Dim spWebUrl As String = SPContext.Current.Web.Url Dim dc As New MyDataContext(spWebUrl) Dim Asgns = From a In dc.GetList(Of AssignmentsItem)("Assignments") Select a.LeadTime, a.Frequency For Each item In Asgns      ListBox1.Items.Add(item.Frequency)      item.LeadTime = 5      dc.SubmitChanges() Next  

Issue Adding a new Lookup Field to an existing List Instance

I have a code base that houses all of the column, content types, template, and list instance definitions. Am using the Update functionlaity a lot from version to version. Has been working well to this point. I just added two new columns (fields), one a Lookup and the other a Multi-Lookup. The fields are added fine on the update, columns look correct and the content type to which these were added also look fine. I can create a new List instance from the content type, and the new lookup columns are fine. The problem is this. Any existing list instances that were created from this same content type, now blow up when I try and access list items via the SP GUI. Something about a valid GUID, I dont't have the exect error anymore, but will repost it when I recreate the issue for the tenth time. I tried deleting the new lookup fields from this new list instance, thinking that I might be able to re-add them to fix the problem, but I get a new stack trace when I try and re-add them. Any hints on where I can start digging would be appreciated. I think I'll start with comparing the list instance schemas between an existing list and a newly created one.  

LINQ to SQL Compact db, file copy issue

Our application uses LINQ and SQL compact database .sdf file as datasource.  It is using Miscrosoft SQL Server Compact 3.5 SP 1 and .NET Framework 3.5 SP1. We store our application's project data into a .sdf file.  When our application opens a .sdf file (e.g. projectA.sdf), it will make a temporary copy of it and open the temporary file instead of the original file.  If we change one table cell value (i.e. one property value of an object that is created by LINQ), and call DataContext.SubmitChanges(ConflictMode.ContinueOnConflict), and then call File.Copy(DataContext.Connection.Database, filename, true); to copy the temporary file back to the original file (replacing the original one).   We found that the table value is not changed in projectA.sdf.  But in the temporary copy, the value is changed.  If we re-open db connection by calling DataContext.Connection.Close(); DataContext.Connection.Open(); right before calling File.Copy(), the changed value is copied successfully to projectA.sdf. If we do a lot of value changes in the database, or adding / deleting table row, then submit changes.  Without re-opening the db connection, after File.Copy(), the projectA.sdf have those changes copied. This strange behaviour looks like the temporary db file is cached.  For a small change, the cached version is not changed.  The File.Copy() use t

Relation List Lookup Issue

Hi, I have 2 lists that are related. List 1 - costs ----- cost - Number quarter - Drop Down Created By - Default SP Field List 2 - people ----- person - User/Group AD Lookup team - drop down I am trying to link these 2 lists so I can retrieve the users team from the people list in a view for the costs. I have tried making it so the user has manually select their name for each cost (instead of using the Created By field), but when I try to make this value a lookup it doesn't allow me to select the person or team field from the people list? Does a lookup only allow you to lookup text values and is there a work around? Many Thanks, Michael

Using LINQ to Get Filtered List of Controls


I have zero experience with LINQ but had occasion to use it today.  I implemented a working solution but do have a question.

First, let me provide the background:

I have 20 large web pages that altogether have several hundred data input controls on them.  There are strong similarities between how each type of control is handled.  Rather than wire up each control individually (ie. hard code it in the layout page), I thought it would be a lot easier to just do so dynamically through a common method.  On each of these web pages there's a MultiView control, inside of which are 2+ View controls.  The guts of my original version of the common method looked like this:

      foreach (View view in multiView.Controls)
        foreach (Control ctrl in view.Controls)
          switch (ctrl.GetType().Name)
            case "DropDownList":
              DropDownList ddList = (DropDownList)ctrl;

Textbox and LIST<> issue


I would like to read data from a textbox, and then add every word to List<string> colletcion.

My problem is I can add to a List one big string and it always is of [0] index.


  List<string>lst1 = new List<string>();

How can i separate and add each word to a collection?

LINQ to SQL Classes (dbml file) across multiple websites issue



I have a single LINQ to SQL Classes (dbml file) compiled in a Class Library that's referenced by 3 websites. Inside that Class Library there's also a class that's using the DBML to manipulate data.

At one point it needs to save in a user table the user info (firstname, lastname, email). SOMEHOW (!?) two of the 3 webapps saves email instead of firstname and viceversa while the other 1 saves them correctly ! The one compiled last seems to be the one saving correctly.

There's no code error as I have debugged this multiple times. The values are assigned correctly but before the SubmitChanges() call the data inside the database object is corrupted.

Now, I have already fixed this locally by putting every website in a separate AppPool (which also needs to be set to "Classic" and not "Integrated". However I really don't want to bug the client with such IIS changes so I'm looking for another workaround !

Please Help!



Linq to Entities Many to Many Persistence Issue


I am having problems persisting a many to many. My code saves the Problem but not the users that can be attached to a problem. My Linq to Entities Mapping is below in the first three code blocks. I then have my ASP MVC controller method which receives a problem, a file (optional), and a string array of users which are allowed to view the problem. I retrieve the Users from the UserRepository and add them to a List which is then passed through to the ProblemRespository with the problem and added to the problem.Users collection. However when submitted only the problem is being saved and not the records which are required in the junction table. Any help would be appreciated. This is the first time I've attempted my own mapping.
Thanks in advance.
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend