Search Results

Search found 720 results on 29 pages for 'tolist'.

Page 12/29 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Jquery Asp.Net GridView Data Binding

    - by oraclee
    Hi all; <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Button" /> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </div> </form> How to call Method Jquery ? public void GetGrid() { DataProviderDataContext db = new DataProviderDataContext(); GridView1.DataSource = db.Employees.ToList(); GridView1.DataBind(); } I do not know English pls help

    Read the article

  • Silverlight 4 accessing WCF Data Services: BeginInvoke frustrations.

    - by Gatmando
    Hi, I'm attempting to follow a pattern for performing WCF data service queries using the Silverlight 4 beta. The following is my code: public CodeTables() { CodeCountries = new ObservableCollection<dsRealHomes.CodeCountries>(); dsRealHomes.RealHomesEntities myClient = null; myClient = staticGlobals.RealHomesContext(); object userState = null; myClient.BeginExecute<dsRealHomes.CodeCountries>(new Uri("CodeCountries"), (IAsyncResult asyncResult) => { Dispatcher.BeginInvoke( () => { var test = myClient.EndExecute<dsRealHomes.CodeCountries>asyncResult).ToList(); } ); }, userState); } This is derived from a number of examples I've come across for WCF data services with silverlight. Unfortunately no matter how I try to implement the code i end up with the following error on 'Dispatcher.BeginInvoke': 'An object reference is required for the non-static field, method, or property (System.Windows.Threading.Dispatcher.BeginInvoke(System.Action)' Thanks

    Read the article

  • IEnumerable<> to IList<>

    - by nachid
    I am using Linq to query my database and returning a generic IList. Whatever I tried I couldn't convert an IQueryable to an IList. Here is my code. I cannot write simpler than this and I don't understand why it is not working. public IList<IRegion> GetRegionList(string countryCode) { var query = from c in Database.RegionDataSource where (c.CountryCode == countryCode) orderby c.Name select new {c.RegionCode, c.RegionName}; return query.Cast<IRegion>().ToList(); } This returns an list with the right number of items but they are all empty Please help, I am bloqued with this for a couple of days now

    Read the article

  • LINQ OrderBy: best search results at top of results list

    - by p.campbell
    Consider the need to search a list of Customer by both first and last names. The desire is to have the results list sorted by the Customer with the most matches in the search terms. FirstName LastName ---------- --------- Foo Laurie Bar Jackson Jackson Bro Laurie Foo Jackson Laurie string[] searchTerms = new string[] {"Jackson", "Laurie"}; //want to find those customers with first, last or BOTH names in the searchTerms var matchingCusts = Customers .Where(m => searchTerms.Contains(m.FirstName) || searchTerms.Contains(m.LastName)) .ToList(); /* Want to sort for those results with BOTH FirstName and LastName matching in the search terms. Those that match on both First and Last should be at the top of the results, the rest who match on one property should be below. */ return matchingCusts.OrderBy(m=>m); Desired Sort: Jackson Laurie (matches on both properties) Foo Laurie Bar Jackson Jackson Bro Laurie Foo How can I achieve this desired functionality with LINQ and OrderBy / OrderByDescending?

    Read the article

  • Convert IEnumerable<dynamic> to JsonArray

    - by Burt
    I am selecting an IEnumerable<dynamic> from the database using Rob Conery's Massive framework. The structure comes back in a flat format Poco C#. I need to transform the data and output it to a Json array (format show at bottom). I thought I could do the transform using linq (my unsuccessful effort is shown below): using System.Collections.Generic; using System.Json; using System.Linq; using System.ServiceModel.Web; .... IEnumerable<dynamic> list = _repository.All("", "", 0).ToList(); JsonArray returnValue = from item in list select new JsonObject() { Name = item.Test, Data = new dyamic(){...}... }; Here is the Json I am trying to generate: [ { "id": "1", "title": "Data Title", "data": [ { "column1 name": "the value", "column2 name": "the value", "column3 name": "", "column4 name": "the value" } ] }, { "id": "2", "title": "Data Title", "data": [ { "column1 name": "the value", "column2 name": "the value", "column3 name": "the value", "column4 name": "the value" } ] } ]

    Read the article

  • Adding 90000 XElement to XDocument

    - by Jon
    I have a Dictionary<int, MyClass> It contains 100,000 items 10,000 items value is populated whilst 90,000 are null. I have this code: var nullitems = MyInfoCollection.Where(x => x.Value == null).ToList(); nullitems.ForEach(x => LogMissedSequenceError(x.Key + 1)); private void LogMissedSequenceError(long SequenceNumber) { DateTime recordTime = DateTime.Now; var errors = MyXDocument.Descendants("ERRORS").FirstOrDefault(); if (errors != null) { errors.Add( new XElement("ERROR", new XElement("DATETIME", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss:fff")), new XElement("DETAIL", "No information was read for expected sequence number " + SequenceNumber), new XAttribute("TYPE", "MISSED"), new XElement("PAGEID", SequenceNumber) ) ); } } This seems to take about 2 minutes to complete. I can't seem to find where the bottleneck might be or if this timing sounds about right? Can anyone see anything to why its taking so long?

    Read the article

  • linq sort many 2 many question

    - by user169867
    My main entity is called [Contract]. Contract has a many 2 many relationship w/ [Service]. When I query for a list of Contracts I grab the 1st Service available like this: q.Select(c => new ContractSearchResult() { ContractID = c.ContractID, FirstService = c.Contract2Service.FirstOrDefault().Service.Name, ServiceCount = c.Contract2Service.Count, } ).ToList(); q is an IQueryable that has some filtering & paging already applied. (When I display this list I show the FirstService if there's only 1. If 1 I show "My1stService (3)" to show I'm seeing the 1st of 3 services) This works fine. My question is this: Is there any way to sort by FirstService? Or is this impossible? I haven't found a way of expressing this in linq. Any help would be appreciated.

    Read the article

  • design business class for unit test

    - by Mauro Destro
    I'm trying to clean my code to make it unit-testable. I know that unit tests must be created while coding but... I have to do it now, with code completed. My business class is full of methods with a similar implementation like: var rep=new NHrepository<ModelClass1>(Session); rep.Where(x=>x.Field1==1).ToList(); first error (from my point of view) is that I don't have to use "new" but instead use DI and add in the ctor parameters a INHrepository modelClass1Repository. If in my class I have two or more repository of different model class? Each must be in the ctor? Or probably business class is not build with SeparationOfConcern principle?

    Read the article

  • Entity Framework - MySQL - Datetime format issue

    - by effkay
    Hello; I have a simple table with few date fields. Whenever I run following query: var docs = ( from d in base.EntityDataContext.document_reviews select d ).ToList(); I get following exception: Unable to convert MySQL date/time value to System.DateTime. MySql.Data.Types.MySqlConversionException: Unable to convert MySQL date/time value to System.DateTime The document reviews table has two date/time fields. One of them is nullable. I have tried placing following in connection string: Allow Zero Datetime=true; But I am still getting exception. Anyone with a solution?

    Read the article

  • Default Object being modified because of LINQ Query

    - by msarchet
    I'm doing the following code to filter a list of objects before it gets sent off to be printed. Dim printList As New List(Of dispillPatient) For Each pat As dispillPatient In patList If (From meds In pat.Medication Select meds Where meds.Print = True).Count > 0 Then Dim patAdd As New dispillPatient patAdd = pat patAdd.Medication = DirectCast((From meds In pat.Medication Select meds Where meds.Print = True).ToList, List(Of dispillMedication)) printList.Add(patAdd) End If Next What is happening is patList, which is my initial list, for every dispillPatient inside of it, that specific patients Medication object (which is another list), is being shorten to the list that is returned to the patAdd object. I think this has something to do with both the way that .NET makes the copy of my pat object when I do patAdd = pat and the LINQ query that I'm using. Has anyone had a similar issue before and\or what can I do to keep my initial list from getting truncated. Thanks

    Read the article

  • LINQ To Entities - Items, ItemCategories & Tags

    - by Simon
    Hi There, I have an Entity Model that has Items, which can belong to one or more categories, and which can have one or more tags. I need to write a query that finds all tags for a given ItemCategory, preferably with a single call to the database, as this is going to get called fairly often. I currently have: Dim q = (From ic In mContext.ItemCategory _ Where ic.CategoryID = forCategoryID _ Select ic).SelectMany(Function(cat) cat.Items).SelectMany(Function(i) i.Tags) _ .OrderByDescending(Function(t) t.Items.Count).ToList This is nearly there, apart from it doesn't contain the items for each tag, so I'd have to iterate through, loading the item reference to find out how many items each tag is related to (for font sizing). Ideally, I want to return a List(Of TagCount), which is just a structure, containing Tag as string, and Count as integer. I've looked at Group and Join, but I'm not getting anywhere so any help would be greatly appreciated!

    Read the article

  • Linq to SQL query error

    - by Tom Kong
    public class Service1 : IService1 { [OperationContract] public List<decmal> GetEnterCounts(DateTime StartTime, DateTime EndTime) { var db = new FACT_ENTER_EXIT(); return (from e in **db.ENTER_CNT** where StartTime < db.DATE_ID && db.DATE_ID > EndTime select e).ToList(); } } Ok, so I have this database FACT_ENTER_EXIT containing the field ENTER_CNT (nullable = false, type = decimal) which I want to return as a list VS2010 spits out the following error at 'db.ENTER_CNT': Error 1 Could not find an implementation of the query pattern for source type 'decimal'. 'Where' not found. I must be missing something, could someone please point out where I'm going wrong?? Thanks in advance, Tom

    Read the article

  • .Net Array or IList<T> from NumPy array in IronPython?

    - by Barry Wark
    Imagine I have a .Net application that supports user extensions in the form of Python modules by embedding IronPython. Using Ironclad, I can allow users to make use of the NumPy and SciPy packages from within their modules. How good is the interop provided by Ironclad? My question is: can I use a NumPy array of type T provided by the user's module in the rest of my app that requires an IList<T>? Edit To clarify, IronPython exposes any Python enumerable of objects of type T as an IEnumerable<T> or an IList<T>. I'm not sure if NumPy arrays fit in this category. I would rather not have to call .tolist() on the NumPy array as the arrays may be quite large.

    Read the article

  • Problem reading List Collection in ASP.net MVC View through Json

    - by Fraz Sundal
    Whenever i return a list collection from a controller through Json. Im unable to get that list but if i just return a string from controller its working fine. In View i have <script type="text/javascript" language="javascript"> $(function () { $('#btnFillList').click(function () { alert("btnclick"); var URL = '<%= Url.Action("JsonFunc2","Customer") %>'; $.post(URL, null, function (data) { for (var i = 0; i < data.length; i++) { } }); }); }); </script> <input type="submit" id="btnFillList" value="Load" /> In Controller i have public ActionResult JsonFunc2() { var cust = _db.tblCustomers.ToList(); return Json(cust); }

    Read the article

  • Easy way to Populate a Dictionary<string,List<string>>

    - by zion
    Greetings Guru's, my objective is to create a Dictionary of Lists, does a simpler technique exist? I prefer the List(t) to IEnumerable(t) which is why I chose the Dictionary of Lists over Ilookup or IGrouping. The code works but it seems like a messy way of doing things. string[] files = Directory.GetFiles (@"C:\test"); Dictionary<string,List<string>> DataX = new Dictionary<string,List<string>>(); foreach (var group in files.GroupBy (file => Path.GetExtension (file))) { DataX.Add (group.Key, group.ToList()); }

    Read the article

  • Get the ranking of highest score with earliest timestamp

    - by Billy
    I have the following records: name score Date Billy 32470 12/18/2010 7:26:35 PM Sally 1100 12/19/2010 12:00:00 AM Kitty 1111 12/21/2010 12:00:00 AM Sally 330 12/21/2010 8:23:34 PM Daisy 32460 12/22/2010 3:10:09 PM Sally 32460 12/23/2010 4:51:11 PM Kitty 32440 12/24/2010 12:00:27 PM Billy 32460 12/24/2010 12:11:36 PM I want to get the leaderboard of the highest score with earliest time stamp using LINQ. In this case, the correct one is rank name 1 Billy 2 Daisy 3 Sally I use the following query: var result = (from s in Submissions group s by s.name into g orderby g.Max(q => q.Score) descending,g.Min(q => q.Date) ascending select new ScoreRecord { name = g.Key Score = g.Max(q => q.Score) }).Take(3).ToList(); I get the following wrong result: rank name 1 Billy 2 Sally 3 Daisy What's the correct linq query in this case?

    Read the article

  • C# Linq Entity Conversion Error on Nonexistent Value?

    - by Ryan
    While trying to query some data using the Linq Entity Framework I'm receiving the following exception: {"Conversion failed when converting the varchar value '3208,7' to data type int."} The thing that is confusing is that this value does not even exist in the view I am querying from. It does exist in the table the view is based on, however. The query I'm running is the following: return context.vb_audit_department .Where(x => x.department_id == department_id && x.version_id == version_id) .GroupBy(x => new { x.action_date, x.change_type, x.user_ntid, x.label }) .Select(x => new { action_date = x.Key.action_date, change_type = x.Key.change_type, user_ntid = x.Key.user_ntid, label = x.Key.label, count = x.Count(), items = x }) .OrderByDescending(x => x.action_date) .Skip(startRowIndex) .Take(maximumRows) .ToList(); Can somebody explain why LINQ queries the underlying table instead of the actual view, and if there is any way around this behavior?

    Read the article

  • Convert PDF to Image Batch

    - by tro
    I am working on a solution where I can convert pdf files to images. I am using the following example from codeproject: http://www.codeproject.com/Articles/317700/Convert-a-PDF-into-a-series-of-images-using-Csharp?msg=4134859#xx4134859xx now I tried with the following code to generate from more then 1000 pdf files new images: using Cyotek.GhostScript; using Cyotek.GhostScript.PdfConversion; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RefClass_PDF2Image { class Program { static void Main(string[] args) { string outputPath = Properties.Settings.Default.outputPath; string pdfPath = Properties.Settings.Default.pdfPath; if (!Directory.Exists(outputPath)) { Console.WriteLine("Der angegebene Pfad " + outputPath + " für den Export wurde nicht gefunden. Bitte ändern Sie den Pfad (outputPath) in der App.Config Datei."); return; } else { Console.WriteLine("Output Pfad: " + outputPath + " gefunden."); } if (!Directory.Exists(pdfPath)) { Console.WriteLine("Der angegebene Pfad " + pdfPath + " zu den PDF Zeichnungen wurde nicht gefunden. Bitte ändern Sie den Pfad (pdfPath) in der App.Config Datei."); return; } else { Console.WriteLine("PDF Pfad: " + pdfPath + " gefunden."); } Pdf2ImageSettings settings = GetPDFSettings(); DateTime start = DateTime.Now; TimeSpan span; Console.WriteLine(""); Console.WriteLine("Extraktion der PDF Zeichnungen wird gestartet: " + start.ToShortTimeString()); Console.WriteLine(""); DirectoryInfo diretoryInfo = new DirectoryInfo(pdfPath); DirectoryInfo[] directories = diretoryInfo.GetDirectories(); Console.WriteLine(""); Console.WriteLine("Es wurden " + directories.Length + " verschiedende Verzeichnisse gefunden."); Console.WriteLine(""); List<string> filenamesPDF = Directory.GetFiles(pdfPath, "*.pdf*", SearchOption.AllDirectories).Select(x => Path.GetFullPath(x)).ToList(); List<string> filenamesOutput = Directory.GetFiles(outputPath, "*.*", SearchOption.AllDirectories).Select(x => Path.GetFullPath(x)).ToList(); Console.WriteLine(""); Console.WriteLine("Es wurden " + filenamesPDF.Count + " verschiedende PDF Zeichnungen gefunden."); Console.WriteLine(""); List<string> newFileNames = new List<string>(); int cutLength = pdfPath.Length; for (int i = 0; i < filenamesPDF.Count; i++) { string temp = filenamesPDF[i].Remove(0, cutLength); temp = outputPath + temp; temp = temp.Replace("pdf", "jpg"); newFileNames.Add(temp); } for (int i = 0; i < filenamesPDF.Count; i++) { FileInfo fi = new FileInfo(newFileNames[i]); if (!fi.Exists) { if (!Directory.Exists(fi.DirectoryName)) { Directory.CreateDirectory(fi.DirectoryName); } Bitmap firstPage = new Pdf2Image(filenamesPDF[i], settings).GetImage(); firstPage.Save(newFileNames[i], System.Drawing.Imaging.ImageFormat.Jpeg); firstPage.Dispose(); } //if (i % 20 == 0) //{ // GC.Collect(); // GC.WaitForPendingFinalizers(); //} } Console.ReadLine(); } private static Pdf2ImageSettings GetPDFSettings() { Pdf2ImageSettings settings; settings = new Pdf2ImageSettings(); settings.AntiAliasMode = AntiAliasMode.Medium; settings.Dpi = 150; settings.GridFitMode = GridFitMode.Topological; settings.ImageFormat = ImageFormat.Png24; settings.TrimMode = PdfTrimMode.CropBox; return settings; } } } unfortunately, I always get in the Pdf2Image.cs an out of memory exception. here the code: public Bitmap GetImage(int pageNumber) { Bitmap result; string workFile; //if (pageNumber < 1 || pageNumber > this.PageCount) // throw new ArgumentException("Page number is out of bounds", "pageNumber"); if (pageNumber < 1) throw new ArgumentException("Page number is out of bounds", "pageNumber"); workFile = Path.GetTempFileName(); try { this.ConvertPdfPageToImage(workFile, pageNumber); using (FileStream stream = new FileStream(workFile, FileMode.Open, FileAccess.Read)) { result = new Bitmap(stream); // --->>> here is the out of memory exception stream.Close(); stream.Dispose(); } } finally { File.Delete(workFile); } return result; } how can I fix that to avoid this exception? thanks for any help, tro

    Read the article

  • C# - Accesing to items for a collection inherited from List<string>

    - by Salvador
    I am trying to implement a new class inherited from List<string>, to load the contents from a text file to the items. using System.Collections.Generic; using System.IO; using System.Linq; public class ListExt: List<string> { string baseDirectory; public LoadFromFile(string FileName) { this._items = File.ReadAllLines(FileName).ToList();//does not work because _list is private } } but i dont knew how to load the lines into the _items property because is private. any suggestions?

    Read the article

  • Help with linq to sql compiled query

    - by stackoverflowuser
    Hi I am trying to use compiled query for one of my linq to sql queries. This query contains 5 to 6 joins. I was able to create the compiled query but the issue I am facing is my query needs to check if the key is within a collection of keys passed as input. But compiled queries do not allow passing of collection (since collection can have varying number of items hence not allowed). For instance input to the function is a collection of keys. Say: List<Guid> InputKeys List<SomeClass> output = null; var compiledQuery = CompiledQueries.Compile<DataContext, IQueryable<SomeClass>>( (context) => from a in context.GetTable<A>() where InputKeys.Contains(a.Key) select a); using(var dataContext = new DataContext()) { output = compiledQuery(dataContext).ToList(); } return output; Is there any work around or better way to do the above?

    Read the article

  • How can you increase timeout in Linq2Entities?

    - by Russell Steen
    I'm doing a basic select against a view. Unfortunately the result can be slow and I'm getting timeout errors intermittently. How can I increase the timeout? Using .NET 3.5, Sql Server 2000, Linq2Entities I'm using the very basic query List<MyData> result = db.MyData.Where(x.Attribute == search).ToList(); Fixing the query so that it's faster on the DB side is not an option here. Exact Error: "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding." Update: I'd prefer to just change it for this one query.

    Read the article

  • Is this code thread safe?

    - by Shawn Simon
    ''' <summary> ''' Returns true if a submission by the same IP address has not been submitted in the past n minutes. ''' </summary> Protected Function EnforceMinTimeBetweenSubmissions() As Boolean Dim minTimeBetweenRequestsMinutes As Integer = 0 Dim configuredTime = ConfigurationManager.AppSettings("MinTimeBetweenSchedulingRequestsMinutes") If String.IsNullOrEmpty(configuredTime) Then Return True If (Not Integer.TryParse(configuredTime, minTimeBetweenRequestsMinutes)) _ OrElse minTimeBetweenRequestsMinutes > 1440 _ OrElse minTimeBetweenRequestsMinutes < 0 Then Throw New ApplicationException("Invalid configuration setting for AppSetting 'MinTimeBetweenSchedulingRequestsMinutes'") End If If minTimeBetweenRequestsMinutes = 0 Then Return True End If If Cache("submitted-requests") Is Nothing Then Cache("submitted-requests") = New Dictionary(Of String, Date) End If ' Remove old requests. Dim submittedRequests As Dictionary(Of String, Date) = CType(Cache("submitted-requests"), Dictionary(Of String, Date)) Dim itemsToRemove = submittedRequests.Where(Function(s) s.Value < Now).Select(Function(s) s.Key).ToList For Each key As String In itemsToRemove submittedRequests.Remove(key) Next If submittedRequests.ContainsKey(Request.UserHostAddress) Then ' User has submitted a request in the past n minutes. Return False Else submittedRequests.Add(Request.UserHostAddress, Now.AddMinutes(minTimeBetweenRequestsMinutes)) End If Return True End Function

    Read the article

  • Should methods containing LINQ expressions be tested / mocked?

    - by Phil.Wheeler
    Assuming I have a class with a method that takes a System.Linq.Expressions.Expression as a parameter, how much value is there in unit testing it? public void IEnumerable<T> Find(Expression expression) { return someCollection.Where(expression).ToList(); } Unit testing or mocking these sorts of methods has been a mind-frying experience for me and I'm now at the point where I have to wonder whether it's all just not worth it. How would I unit test this method using some arbitrary expression like List<Animal> = myAnimalRepository.Find(x => x.Species == "Cat");

    Read the article

  • C# -Interview Question Anonymous Type

    - by Amutha
    Recently i was asked to prove the power of C# 3.0 in a single line( might be tricky) i wrote new int[] { 1, 2, 3 }.Union(new int[]{10,23,45}). ToList().ForEach(x => Console.WriteLine(x)); and explained you can have (i) anonymous array (ii) extension method (iii)lambda and closure all in a single line.I got spot offer. But..... The interviewer asked me how will you convert an anonymous type into know type :( I am 100% sure ,we can not do that.The interviewer replied there is 200% chance to do that if you have a small work around.I was clueless. As usual,I am waiting for your valuable reply(Is it possible?).

    Read the article

  • Return nested alias for linq expression

    - by Schotime
    I have the following Linq Expression var tooDeep = shoppers .Where(x => x.Cart.CartSuppliers.First().Name == "Supplier1") .ToList(); I need to turn the name part into the following string. x.Cart.CartSuppliers.Name As part of this I turned the Expression into a string and then split on the . and removed the First() argument. However, when I get to CartSuppliers this returns a Suppliers[] array. Is there a way to get the single type from this. eg. I need to get a Supplier back. Thanks

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >