Search Results

Search found 6357 results on 255 pages for 'generic relations'.

Page 89/255 | < Previous Page | 85 86 87 88 89 90 91 92 93 94 95 96  | Next Page >

  • List<object>.RemoveAll - How to create an appropriate Predicate

    - by CJM
    This is a bit of noob question - I'm still fairly new to C# and generics and completely new to predicates, delegates and lamda expressions... I have a class 'Enquiries' which contains a generic list of another class called 'Vehicles'. I'm building up the code to add/edit/delete Vehicles from the parent Enquiry. And at the moment, I'm specifically looking at deletions. From what I've read so far, it appears that I can use Vehicles.RemoveAll() to delete an item with a particular VehicleID or all items with a particular EnquiryID. My problem is understanding how to feed .RemoveAll the right predicate - the examples I have seen are too simplistic (or perhaps I am too simplistic given my lack of knowledge of predicates, delegates and lambda expressions). So if I had a List<Of Vehicle> Vehicles where each Vehicle had an EnquiryID, how would I use Vehicles.RemoveAll() to remove all vehicles for a given EnquiryID? I understand there are several approaches to this so I'd be keen to hear the differences between approaches - as much as I need to get something working, this is also a learning exercise. As an supplementary question, is a Generic list the best repository for these objects? My first inclination was towards a Collection, but it appears I am out of date. Certainly Generics seem to be preferred, but I'm curious as to other alternatives. Thanks

    Read the article

  • C++ Returning Multiple Items

    - by Travis Parks
    I am designing a class in C++ that extracts URLs from an HTML page. I am using Boost's Regex library to do the heavy lifting for me. I started designing a class and realized that I didn't want to tie down how the URLs are stored. One option would be to accept a std::vector<Url> by reference and just call push_back on it. I'd like to avoid forcing consumers of my class to use std::vector. So, I created a member template that took a destination iterator. It looks like this: template <typename TForwardIterator, typename TOutputIterator> TOutputIterator UrlExtractor::get_urls( TForwardIterator begin, TForwardIterator end, TOutputIterator dest); I feel like I am overcomplicating things. I like to write fairly generic code in C++, and I struggle to lock down my interfaces. But then I get into these predicaments where I am trying to templatize everything. At this point, someone reading the code doesn't realize that TForwardIterator is iterating over a std::string. In my particular situation, I am wondering if being this generic is a good thing. At what point do you start making code more explicit? Is there a standard approach to getting values out of a function generically?

    Read the article

  • Inner join and outer join options in Entity Framework 4.0

    - by bigb
    I am using EF 4.0 and I need to implement query with one inner join and with N outer joins I started to implement this using different approaches but get into trouble at some point. Here is two examples how I started of doing this using ObjectQuery<'T' and Linq to Entity 1)Using ObjectQuery<'T' I implement flexible outer join but I don't know how to perform inner join with entity Rules in that case (by default Include("Rules") doing outer join, but i need to inner join by Id). public static IEnumerable<Race> GetRace(List<string> includes, DateTime date) { IRepository repository = new Repository(new BEntities()); ObjectQuery<Race> result = (ObjectQuery<Race>)repository.AsQueryable<Race>(); //perform outer joins with related entities if (includes != null) foreach (string include in includes) result = result.Include(include); //here i need inner join insteard of default outer join result = result.Include("Rules"); return result.ToList(); } 2)Using Linq To Entity I need to have kind of outer join(somethin like in GetRace()) where i may pass a List with entities to include) and also i need to perform correct inner join with entity Rules public static IEnumerable<Race> GetRace2(List<string> includes, DateTime date) { IRepository repository = new Repository(new BEntities()); IEnumerable<Race> result = from o in repository.AsQueryable<Race>() from b in o.RaceBetRules select new { o }); //I need here: // 1. to perform the same way inner joins with related entities like with ObjectQuery above //here i getting List<AnonymousType> which i cant cast to //IEnumerable<Race> when i did try to cast like //(IEnumerable<Race>)result.ToList(); i did get error: //Unable to cast object of type //'System.Collections.Generic.List`1[<>f__AnonymousType0`1[BetsTipster.Entity.Tip.Types.Race]]' //to type //'System.Collections.Generic.IEnumerable`1[BetsTipster.Entity.Tip.Types.Race]'. return result.ToList(); } May be someone have some ideas about that.

    Read the article

  • Create a strongly typed view which inherites a class which is concrete

    - by Ashwani K
    Hello All: I am having one class called BaseClass which contains some logic applicable to whole web site. In order to create a strongly typed view we need to inherit the page from System.Web.Mvc.ViewPage generic class. But In our case I have to Inherit the BaseClass from System.Web.Mvc.ViewPage to apply some common settings, but the BaseClass should be inherited from System.Web.Mvc.ViewPage< generic version. But I cannot inherit the BaseClass from System.Web.Mvc.ViewPage< as it will change other class also. So I created one more class of type BaseClass< inheriting it from System.Web.Mvc.ViewPage< and copied the whole code of BaseClass in BaseClass<. But the code in BaseClass is controlled by other team so it will be changed frequently so my BaseClass< should be in sync with BaseClass. Please help me in eliminating the code duplication or any other approach to make strongly typed View. Thanks Ashwani

    Read the article

  • ASP.net file operations delay

    - by mtranda
    Ok, so here's the problem: I'm reading the stream from a FileUpload control, reading in chunks of n bytes and writing the array in a loop until I reach the stream's end. Now the reason I do this is because I need to check several things while the upload is still going on (rather than doing a Save(); which does the whole thing in one go). Here's the problem: when doing this from the local machine, I can see the file just fine as it's uploading and its size increases (had to add a Sleep(); clause in the loop to actually get to see the file being written). However, when I upload the file from a remote machine, I don't get to see it until the the file has completed uploading. Also, I've added another call to write the progress to a text file as the progress is going on, and I get the same thing. Local: the file updates as the upload goes on, remote: the token file only appears after the upload's done (which is somewhat useless since I need it while the upload's still happening). Is there some sort of security setting in (or ASP.net) that maybe saves files in a temporary location for remote machines as opposed to the local machine and then moves them to the specified destination? I would liken this with ASP.net displaying error messages when browsing from the local machine (even on the public hostname) as opposed to the generic compilation error page/generic exception page that is shown when browsing from a remote machine (and customErrors are not off) Any clues on this? Thanks in advance.

    Read the article

  • Android getting XML values

    - by Nils
    Hello, I have the following XML code, which I got by a UPnP device and like to get the res value - the RTSP URL. In this case rtsp://10.42.0.103:554/live.sdp How can I do this? I heard that Android has some built-in support for reading XML. Is that true? <DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/"> <item id="11" parentID="1" restricted="1"> <dc:title>Network Camera Stream 1</dc:title> <upnp:class>object.item.videoItem</upnp:class> <res protocolInfo="rtsp-rtp-udp:*:video/mpeg4-generic:*" resolution="640x480">rtsp://10.42.0.103:554/live.sdp</res> </item> <item id="12" parentID="1" restricted="1"> <dc:title>Network Camera Stream 2</dc:title> <upnp:class>object.item.videoItem</upnp:class> <res protocolInfo="rtsp-rtp-udp:*:video/mpeg4-generic:*" resolution="176x144">rtsp://10.42.0.103:554/live2.sdp</res> </item> </DIDL-Lite>

    Read the article

  • Add additional content to the middle of string from within a method

    - by Sammy T
    I am working with a log file and I have a method which is creating a generic entry in to the log. The generic log entry looks like this: public StringBuilder GetLogMessage(LogEventType logType, object message) { StringBuilder logEntry = new StringBuilder(); logEntry.AppendFormat("DATE={0} ", DateTime.Now.ToString("dd-MMM-yyyy", new CultureInfo(CommonConfig.EnglishCultureCode))); logEntry.AppendFormat("TIME={0} ", DateTime.Now.ToString("HH:mm:ss", new CultureInfo(CommonConfig.EnglishCultureCode))); logEntry.AppendFormat("ERRORNO={0} ", base.RemoteIPAddress.ToString().Replace(".", string.Empty)); logEntry.AppendFormat("IP={0}", base.RemoteIPAddress.ToString()); logEntry.AppendFormat("LANG={0} ", base.Culture.TwoLetterISOLanguageName); logEntry.AppendFormat("PNR={0} ", this.RecordLocator); logEntry.AppendFormat("AGENT={0} ", base.UserAgent); logEntry.AppendFormat("REF={0} ", base.Referrer); logEntry.AppendFormat("SID={0} ", base.CurrentContext.Session.SessionID); logEntry.AppendFormat("LOGTYPE={0} ", logType.ToString() ); logEntry.AppendFormat("MESSAGE={0} ", message); return logEntry; } What would be the best approach for adding additional parameters before "MESSAGE="? For example if I wanted to add "MODULE=" from a derived class when the GetLogMessage is being run. Would a delegate be what I am looking for or marking the method as virtual and overriding it or do I need something entirely different? Any help would be appreciated.

    Read the article

  • Boost lambda: Invoke method on object

    - by ckarras
    I'm looking at boost::lambda as a way to to make a generic algorithm that can work with any "getter" method of any class. The algorithm is used to detect duplicate values of a property, and I would like for it to work for any property of any class. In C#, I would do something like this: class Dummy { public String GetId() ... public String GetName() ... } IEnumerable<String> FindNonUniqueValues<ClassT> (Func<ClassT,String> propertyGetter) { ... } Example use of the method: var duplicateIds = FindNonUniqueValues<Dummy>(d => d.GetId()); var duplicateNames = FindNonUniqueValues<Dummy>(d => d.GetName()); I can get the for "any class" part to work, using either interfaces or template methods, but have not found yet how to make the "for any method" part work. Is there a way to do something similar to the "d = d.GetId()" lambda in C++ (either with or without Boost)? Alternative, more C++ian solutions to make the algorithm generic are welcome too. I'm using C++/CLI with VS2008, so I can't use C++0x lambdas.

    Read the article

  • .net runtime type casting when using reflection

    - by Mike
    I have need to cast a generic list of a concrete type to a generic list of an interface that the concrete types implement. This interface list is a property on an object and I am assigning the value using reflection. I only know the value at runtime. Below is a simple code example of what I am trying to accomplish: public void EmployeeTest() { IList<Employee> initialStaff = new List<Employee> { new Employee("John Smith"), new Employee("Jane Doe") }; Company testCompany = new Company("Acme Inc"); //testCompany.Staff = initialStaff; PropertyInfo staffProperty = testCompany.GetType().GetProperty("Staff"); staffProperty.SetValue(testCompany, (staffProperty.PropertyType)initialStaff, null); } Classes are defined like so: public class Company { private string _name; public string Name { get { return _name; } set { _name = value; } } private IList<IEmployee> _staff; public IList<IEmployee> Staff { get { return _staff; } set { _staff = value; } } public Company(string name) { _name = name; } } public class Employee : IEmployee { private string _name; public string Name { get { return _name; } set { _name = value; } } public Employee(string name) { _name = name; } } public interface IEmployee { string Name { get; set; } } Any thoughts? I am using .NET 4.0. Would the new covariant or contravariant features help? Thanks in advance.

    Read the article

  • Javascript Callback when variable is set to X

    - by Erik
    Hey everyone, Have an issue I can't seem to wrap my head around. I'm wanting to write a generic javascript function that will accept a variable and a callback, and continue to execute until that variable is something other than false. For example, the variable SpeedFeed.user.sid is false until something else happens in the code, but I don't want to execute a particular callback until it has been set. The call: SpeedFeed.helper_ready(SpeedFeed.user.sid, function(){ alert(SpeedFeed.user.sid); // Run function that requires sid to be set. }); The function: helper_ready: function(vtrue, callback){ if(vtrue != false){ callback(); } else { setTimeout(function(){ SpeedFeed.helper_ready(vtrue, callback); }, SpeedFeed.apiCheckTime); } } The issue I've narrowed it down to appears to be that because in the setTimeout I call vtrue instead of the actual SpeedFeed.user.sid, it's going to be set to false always. I realize I could write a specific function for each time that just evaluates the SpeedFeed.user.sid, but I'd like to have a generic method that I could use throughout the application. Thanks for any insight :)

    Read the article

  • Populating dropdownlist in asp.net mvc doesn't seem to work for me...

    - by Pandiya Chendur
    I use a dropdownlist in one of my create.aspx but it some how doesnt seem to work... public IEnumerable<Materials> FindAllMeasurements() { var mesurements = from mt in db.MeasurementTypes select new Materials() { Id= Convert.ToInt64(mt.Id), Mes_Name= mt.Name }; return mesurements; } and my controller, public ActionResult Create() { var mesurementTypes = consRepository.FindAllMeasurements().AsEnumerable(); ViewData["MeasurementType"] = new SelectList(mesurementTypes, "Id", "Mes_Name"); return View(); } and my create.aspx has this, <p> <label for="MeasurementTypeId">MeasurementType:</label> <%= Html.DropDownList("MeasurementType", ViewData["MeasurementType"])%> <%= Html.ValidationMessage("MeasurementTypeId", "*") %> </p> When i execute this i got these errors, System.Web.Mvc.HtmlHelper<CrMVC.Models.Material>' does not contain a definition for 'DropDownList' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>)' has some invalid arguments 2.cannot convert from 'object' to 'System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>

    Read the article

  • How can I properly handle 404s in ASP.NET MVC?

    - by Brian
    I am just getting started on ASP.NET MVC so bear with me. I've searched around this site and various others and have seen a few implementations of this. EDIT: I forgot to mention I am using RC2 Using URL Routing: routes.MapRoute( "Error", "{*url}", new { controller = "Errors", action = "NotFound" } //404s ); The above seems to take care of requests like this (assuming default route tables setup by initial MVC project): "/blah/blah/blah/blah" Overriding HandleUnknownAction() in the controller itself: //404s - handle here (bad action requested protected override void HandleUnknownAction(string actionName) { ViewData["actionName"] = actionName; View("NotFound").ExecuteResult(this.ControllerContext); } However the previous strategies do not handle a request to a Bad/Unknown controller. For example, I do not have a "/IDoNotExist", if I request this I get the generic 404 page from the web server and not my 404 if I use routing + override. So finally, my question is: Is there any way to catch this type of request using a route or something else in the MVC framework itself? OR should I just default to using Web.Config customErrors as my 404 handler and forget all this? I assume if I go with customErrors I'll have to store the generic 404 page outside of /Views due to the Web.Config restrictions on direct access. Anyway any best practices or guidance is appreciated.

    Read the article

  • Are there pitfalls to using static class/event as an application message bus

    - by Doug Clutter
    I have a static generic class that helps me move events around with very little overhead: public static class MessageBus<T> where T : EventArgs { public static event EventHandler<T> MessageReceived; public static void SendMessage(object sender, T message) { if (MessageReceived != null) MessageReceived(sender, message); } } To create a system-wide message bus, I simply need to define an EventArgs class to pass around any arbitrary bits of information: class MyEventArgs : EventArgs { public string Message { get; set; } } Anywhere I'm interested in this event, I just wire up a handler: MessageBus<MyEventArgs>.MessageReceived += (s,e) => DoSomething(); Likewise, triggering the event is just as easy: MessageBus<MyEventArgs>.SendMessage(this, new MyEventArgs() {Message="hi mom"}); Using MessageBus and a custom EventArgs class lets me have an application wide message sink for a specific type of message. This comes in handy when you have several forms that, for example, display customer information and maybe a couple forms that update that information. None of the forms know about each other and none of them need to be wired to a static "super class". I have a couple questions: fxCop complains about using static methods with generics, but this is exactly what I'm after here. I want there to be exactly one MessageBus for each type of message handled. Using a static with a generic saves me from writing all the code that would maintain the list of MessageBus objects. Are the listening objects being kept "alive" via the MessageReceived event? For instance, perhaps I have this code in a Form.Load event: MessageBus<CustomerChangedEventArgs>.MessageReceived += (s,e) => DoReload(); When the Form is Closed, is the Form being retained in memory because MessageReceived has a reference to its DoReload method? Should I be removing the reference when the form closes: MessageBus<CustomerChangedEventArgs>.MessageReceived -= (s,e) => DoReload();

    Read the article

  • how to read in a list of custom configuration objects

    - by Johnny
    hi, I want to implement Craig Andera's custom XML configuration handler in a slightly different scenario. What I want to be able to do is to read in a list of arbitrary length of custom objects defined as: public class TextFileInfo { public string Name { get; set; } public string TextFilePath { get; set; } public string XmlFilePath { get; set; } } I managed to replicate Craig's solution for one custom object but what if I want several? Craig's deserialization code is: public class XmlSerializerSectionHandler : IConfigurationSectionHandler { public object Create(object parent, object configContext, XmlNode section) { XPathNavigator nav = section.CreateNavigator(); string typename = (string)nav.Evaluate("string(@type)"); Type t = Type.GetType(typename); XmlSerializer ser = new XmlSerializer(t); return ser.Deserialize(new XmlNodeReader(section)); } } I think I could do this if I could get Type t = Type.GetType("System.Collections.Generic.List<TextFileInfo>") to work but it throws Could not load type 'System.Collections.Generic.List<Test1.TextFileInfo>' from assembly 'Test1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

    Read the article

  • How to update GUI thread/class from worker thread/class?

    - by user315182
    First question here so hello everyone. The requirement I'm working on is a small test application that communicates with an external device over a serial port. The communication can take a long time, and the device can return all sorts of errors. The device is nicely abstracted in its own class that the GUI thread starts to run in its own thread and has the usual open/close/read data/write data basic functions. The GUI is also pretty simple - choose COM port, open, close, show data read or errors from device, allow modification and write back etc. The question is simply how to update the GUI from the device class? There are several distinct types of data the device deals with so I need a relatively generic bridge between the GUI form/thread class and the working device class/thread. In the GUI to device direction everything works fine with [Begin]Invoke calls for open/close/read/write etc. on various GUI generated events. I've read the thread here (How to update GUI from another thread in C#?) where the assumption is made that the GUI and worker thread are in the same class. Google searches throw up how to create a delegate or how to create the classic background worker but that's not at all what I need, although they may be part of the solution. So, is there a simple but generic structure that can be used? My level of C# is moderate and I've been programming all my working life, given a clue I'll figure it out (and post back)... Thanks in advance for any help.

    Read the article

  • Fluent NHibernate Repository with subclasses

    - by reallyJim
    Having some difficulty understanding the best way to implement subclasses with a generic repository using Fluent NHibernate. I have a base class and two subclasses, say: public abstract class Person { public virtual int PersonId { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } } public class Student : Person { public virtual decimal GPA { get; set; } } public class Teacher : Person { public virtual decimal Salary { get; set; } } My Mappings are as follows: public class PersonMap : ClassMap { public PersonMap() { Table("Persons"); Id(x => x.PersonId).GeneratedBy.Identity(); Map(x => x.FirstName); Map(x => x.LastName); } } public class StudentMap : SubclassMap<Student> { public StudentMap() { Table("Students"); KeyColumn("PersonId"); Map(x => x.GPA); } } public class TeacherMap : SubclassMap<Teacher> { public TeacherMap() { Table("Teachers"); KeyColumn("PersonId"); Map(x => x.Salary); } } I use a generic repository to save/retreive/update the entities, and it works great--provided I'm working with Repository--where I already know that I'm working with students or working with teachers. The problem I run into is this: What happens when I have an ID, and need to determine the TYPE of person? If a user comes to my site as PersonId = 23, how do I go about figuring out which type of person it is?

    Read the article

  • Java Generics Class Parameter Type Inference

    - by Pindatjuh
    Given the interface: public interface BasedOnOther<T, U extends BasedList<T>> { public T getOther(); public void staticStatisfied(final U list); } The BasedOnOther<T, U extends BasedList<T>> looks very ugly in my use-cases. It is because the T type parameter is already defined in the BasedList<T> part, so the "uglyness" comes from that T needs to be typed twice. Problem: is it possible to let the Java compiler infer the generic T type from BasedList<T> in a generic class/interface definition? Ultimately, I'd like to use the interface like: class X implements BasedOnOther<BasedList<SomeType>> { public SomeType getOther() { ... } public void staticStatisfied(final BasedList<SomeType> list) { ... } } // Does not compile, due to invalid parameter count. Instead: class X implements BasedOnOther<SomeType, BasedList<SomeType>> { public SomeType getOther() { ... } public void staticStatisfied(final BasedList<SomeType> list) { ... } }

    Read the article

  • Using LINQ on observable with GroupBy and Sum aggregate

    - by Mark Oates
    I have the following block of code which works fine; var boughtItemsToday = (from DBControl.MoneySpent bought in BoughtItemDB.BoughtItems select bought); BoughtItems = new ObservableCollection<DBControl.MoneySpent>(boughtItemsToday); It returns data from my MoneySpent table which includes ItemCategory, ItemAmount, ItemDateTime. I want to change it to group by ItemCategory and ItemAmount so I can see where I am spending most of my money, so I created a GroupBy query, and ended up with this; var finalQuery = boughtItemsToday.AsQueryable().GroupBy(category => category.ItemCategory); BoughtItems = new ObservableCollection<DBControl.MoneySpent>(finalQuery); Which gives me 2 errors; Error 1 The best overloaded method match for 'System.Collections.ObjectModel.ObservableCollection.ObservableCollection(System.Collections.Generic.List)' has some invalid arguments Error 2 Argument 1: cannot convert from 'System.Linq.IQueryable' to 'System.Collections.Generic.List' And this is where I'm stuck! How can I use the GroupBy and Sum aggregate function to get a list of my categories and the associated spend in 1 LINQ query?! Any help/suggestions gratefully received. Mark

    Read the article

  • (500) Internal Server Error with C# and Web Dev 2008 Express

    - by user32848
    The code below is generic, found in a variety of places, including a book I have. I have used it as a base for a working program in VS 2005. Now I've resurrected it with my current Visual Web Developer 2008 Express Edition and I seem to have problems connecting it to my default development server (I don't have IIS on my XP). The error is: (500) Internal Server Error. Is this saying what I thought it did (above) or something else, and how do I solve this problem? using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Net; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text.RegularExpressions; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string strResult = ""; string url = "http://weather.unisys.com"; WebResponse objResponse; WebRequest objRequest; try { objRequest = System.Net.HttpWebRequest.Create(url); } catch { objRequest = System.Net.HttpWebRequest.Create("http://"+ url); } objResponse = objRequest.GetResponse(); using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) { strResult = sr.ReadToEnd(); sr.Close(); } } }

    Read the article

  • using STI and ActiveRecordBase<> with full FindAll

    - by oillio
    Is it possible to use generic support with single table inheritance, and still be able to FindAll of the base class? As a bonus question, will I be able to use ActiveRecordLinqBase< as well? I do love those queries. More detail: Say I have the following classes defined: public interface ICompany { int ID { get; set; } string Name { get; set; } } [ActiveRecord("companies", DiscriminatorColumn="type", DiscriminatorType="String", DiscriminatorValue="NA")] public abstract class Company<T> : ActiveRecordBase<T>, ICompany { [PrimaryKey] private int Id { get; set; } [Property] public String Name { get; set; } } [ActiveRecord(DiscriminatorValue="firm")] public class Firm : Company<Firm> { [Property] public string Description { get; set; } } [ActiveRecord(DiscriminatorValue="client")] public class Client : Company<Client> { [Property] public int ChargeRate { get; set; } } This works fine for most cases. I can do things like: var x = Client.FindAll(); But sometimes I want all of the companies. If I was not using generics I could do: var x = (Company[]) FindAll(Company); Client a = (Client)x[0]; Firm b = (Firm)x[1]; Is there a way to write a FindAll that returns an array of ICompany's that can then be typecast into their respective types? Something like: var x = (ICompany[]) FindAll(Company<ICompany>); Client a = (Client)x[0]; Or maybe I am going about implementing the generic support all wrong?

    Read the article

  • Dealing with multiple generics in a method call

    - by thaBadDawg
    I've been dealing a lot lately with abstract classes that use generics. This is all good and fine because I get a lot of utility out of these classes but now it's making for some rather ugly code down the line. For example: abstract class ClassBase<T> { T Property { get; set; } } class MyClass : ClassBase<string> { OtherClass PropertyDetail { get; set; } } This implementation isn't all that crazy, except when I want to reference the abstract class from a helper class and then I have to make a list of generics just to make reference to the implemented class, like this below. class Helper { void HelpMe<C, T>(object Value) where C : ClassBase<T>, new() { DoWork(); } } This is just a tame example, because I have some method calls where the list of where clauses end up being 5 or 6 lines long to handle all of the generic data. What I'd really like to do is class Helper { void HelpMe<C>(object Value) where C : ClassBase, new() { DoWork(); } } but it obviously won't compile. I want to reference ClassBase without having to pass it a whole array of generic classes to get the function to work, but I don't want to reference the higher level classes because there are a dozen of those. Am I the victim of my own cleverness or is there an avenue that I haven't considered yet?

    Read the article

  • Java Generics Class Type Parameter Inference

    - by Pindatjuh
    Given the interface: public interface BasedOnOther<T, U extends BasedList<T>> { public T getOther(); public void staticStatisfied(final U list); } The BasedOnOther<T, U extends BasedList<T>> looks very ugly in my use-cases. It is because the T type parameter is already defined in the BasedList<T> part, so the "uglyness" comes from that T needs to be typed twice. Problem: is it possible to let the Java compiler infer the generic T type from BasedList<T> in a generic class/interface definition? Ultimately, I'd like to use the interface like: class X extends BasedOnOther<BasedList<SomeType>> { public SomeType getOther() { ... } public void staticStatisfied(final BasedList<SomeType> list) { ... } } Instead: class X extends BasedOnOther<SomeType, BasedList<SomeType>> { public SomeType getOther() { ... } public void staticStatisfied(final BasedList<SomeType> list) { ... } }

    Read the article

  • jQuery ajax form submit - how to ensure dynamically loaded form's action is used

    - by kenny99
    Hi, i'm having a problem with dynamically loaded forms - instead of using the action attribute of the newly loaded form, my jquery code is still using the action attribute of the first form loaded. I have the following code: //generic ajax form handler - calls next page load on success $('input.next:not(#eligibility)').live("click", function(){ $(".form_container form").validationEngine({ ajaxSubmit: true, ajaxSubmitFile: $(this).attr('action'), success : function() { var url = $('input.next').attr('rel'); ajaxFormStage(url); }, failure : function() { } }); }); But when the next form is loaded, the above code does not pick up the new action attribute. I have tried adding the above code to my callback on successful ajax load (shown below), but this doesn't make any difference. Can anyone help? Many thanks function ajaxFormStage(url) { var $data = $('#main_body #content'); $.validationEngine.closePrompt('body'); //close any validation messages $data.fadeOut('fast', function(){ $data.load(url, function(){ $data.animate({ opacity: 'show' }, 'fast'); '); //generic ajax form handler - calls next page load on success $('input.next:not(#eligibility)').live("click", function(){ $(".form_container form").validationEngine({ ajaxSubmit: true, ajaxSubmitFile: $(this).attr('action'), success : function() { var url = $('input.next').attr('rel'); ajaxFormStage(url); }, failure : function() { } }); }); }); });

    Read the article

  • Why doesn't the Java Collections API include a Graph implementation?

    - by dvanaria
    I’m currently learning the Java Collections API and feel I have a good understanding of the basics, but I’ve never understood why this standard API doesn’t include a Graph implementation. The three base classes are easily understandable (List, Set, and Map) and all their implementations in the API are mostly straightforward and consistent. Considering how often graphs come up as a potential way to model a given problem, this just doesn’t make sense to me (it’s possible it does exist in the API and I’m not looking in the right place of course). Steve Yegge suggests in one of his blog posts that a programmer should consider graphs first when attacking a problem, and if the problem domain doesn’t fit naturally into this data structure, only then consider the alternative structures. My first guess is that there is no universal way to represent graphs, or that their interfaces may not be generic enough for an API implementation to be useful? But if you strip down a graph to its basic components (vertices and a set of edges that connect some or all of the vertices) and consider the ways that graphs are commonly constructed (methods like addVertex(v) and insertEdge(v1, v2)) it seems that a generic Graph implementation would be possible and useful. Thanks for helping me understand this better.

    Read the article

  • Generics vs inheritance (when no collection classes are involved)

    - by Ram
    This is an extension of this questionand probably might even be a duplicate of some other question(If so, please forgive me). I see from MSDN that generics are usually used with collections The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees and so on where operations such as adding and removing items from the collection are performed in much the same way regardless of the type of data being stored. The examples I have seen also validate the above statement. Can someone give a valid use of generics in a real-life scenario which does not involve any collections ? Pedantically, I was thinking about making an example which does not involve collections public class Animal<T> { public void Speak() { Console.WriteLine("I am an Animal and my type is " + typeof(T).ToString()); } public void Eat() { //Eat food } } public class Dog { public void WhoAmI() { Console.WriteLine(this.GetType().ToString()); } } and "An Animal of type Dog" will be Animal<Dog> magic = new Animal<Dog>(); It is entirely possible to have Dog getting inherited from Animal (Assuming a non-generic version of Animal)Dog:Animal Therefore Dog is an Animal Another example I was thinking was a BankAccount. It can be BankAccount<Checking>,BankAccount<Savings>. This can very well be Checking:BankAccount and Savings:BankAccount. Are there any best practices to determine if we should go with generics or with inheritance ?

    Read the article

< Previous Page | 85 86 87 88 89 90 91 92 93 94 95 96  | Next Page >