Search Results

Search found 4837 results on 194 pages for 'a person'.

Page 16/194 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • How to initialize an Object?

    - by John
    I have a class like this, public class person { name Name {set; get;} string Address {set; get;} } public class name { string First {set; get;} string Last {set; get;} } Now when I create the object an try to set the first or last name I get an error. "Object reference not set to an instance of an object." person Person = new person(); Person.Name.First = "John"; Person.Name.Last ="Smith"; What am I doing wrong?

    Read the article

  • Use Automapper to flatten sub-class of property

    - by Neil
    Given the classes: public class Person { public string Name { get; set; } } public class Student : Person { public int StudentId { get; set; } } public class Source { public Person Person { get; set; } } public class Dest { public string PersonName { get; set; } public int? PersonStudentId { get; set; } } I want to use Automapper to map Source - Dest. This test obviously fails: Mapper.CreateMap<Source, Dest>(); var source = new Source() { Person = new Student(){ Name = "J", StudentId = 5 }}; var dest = Mapper.Map<Source, Dest>(source); Assert.AreEqual(5, dest.PersonStudentId); What would be the best approach to mapping this given that "Person" is actually a heavily used data-type throughout our domain model.

    Read the article

  • Should an event-sourced aggregate root have access to the event sourcing repository?

    - by JD Courtoy
    I'm working on an event-sourced CQRS implementation, using DDD in the application / domain layer. I have an object model that looks like this: public class Person : AggregateRootBase { private Guid? _bookingId; public Person(Identification identification) { Apply(new PersonCreatedEvent(identification)); } public Booking CreateBooking() { // Enforce Person invariants var booking = new Booking(); Apply(new PersonBookedEvent(booking.Id)); return booking; } public void Release() { // Enforce Person invariants // Should we load the booking here from the aggregate repository? // We need to ensure that booking is released as well. var booking = BookingRepository.Load(_bookingId); booking.Release(); Apply(new PersonReleasedEvent(_bookingId)); } [EventHandler] public void Handle(PersonBookedEvent @event) { _bookingId = @event.BookingId; } [EventHandler] public void Handle(PersonReleasedEvent @event) { _bookingId = null; } } public class Booking : AggregateRootBase { private DateTime _bookingDate; private DateTime? _releaseDate; public Booking() { //Enforce invariants Apply(new BookingCreatedEvent()); } public void Release() { //Enforce invariants Apply(new BookingReleasedEvent()); } [EventHandler] public void Handle(BookingCreatedEvent @event) { _bookingDate = SystemTime.Now(); } [EventHandler] public void Handle(BookingReleasedEvent @event) { _releaseDate = SystemTime.Now(); } // Some other business activities unrelated to a person } With my understanding of DDD so far, both Person and Booking are seperate aggregate roots for two reasons: There are times when business components will pull Booking objects separately from the database. (ie, a person that has been released has a previous booking modified due to incorrect information). There should not be locking contention between Person and Booking whenever a Booking needs to be updated. One other business requirement is that a Booking can never occur for a Person more than once at a time. Due to this, I'm concerned about querying the query database on the read side as there could potentially be some inconsistency there (due to using CQRS and having an eventually consistent read database). Should the aggregate roots be allowed to query the event-sourced backing store by id for objects (lazy-loading them as needed)? Are there any other avenues of implementation that would make more sense?

    Read the article

  • DbMetal chokes on repeated foreign key references in SQLite - any ideas?

    - by DanM
    I've been struggling to get DbMetal to process my SQLite database. I finally isolated the problem. It won't allow a table to have two foreign key references to the same column. For example, a SQLite database with these two tables will fail: CREATE TABLE Person ( Id INTEGER PRIMARY KEY, Name TEXT NOT NULL ); CREATE TABLE Match ( Id INTEGER PRIMARY KEY, WinnerPersonId INTEGER NOT NULL REFERENCES Person(Id), LoserPersonId INTEGER NOT NULL REFERENCES Person(Id) ); I get this error: DbMetal: Sequence contains more than one matching element If I get rid of the second foreign key reference, no error occurs. So, this works: CREATE TABLE Match ( Id INTEGER PRIMARY KEY, WinnerPersonId INTEGER NOT NULL REFERENCES Person(Id), LoserPersonId INTEGER NOT NULL ); But I really need both "person" columns to reference the person table. I submitted a bug report for this, but I could use a workaround in the meantime. Any ideas?

    Read the article

  • Lua: Why changing value on one variable changes value on an other one too?

    - by user474563
    I think that running this code you will get excactly what I mean. I want to register 5 names to a register(people). I loop 5 times and in each loop I have a variable newPerson which is supposed to save all information about a person and then be added to the people register. In this example only the names of the people are being registered for simplicity. The problem is that in the end all people turn to have the same name: "Petra". I playied a bit with this but can't get a reasonable reason for this behaviour. Help appreciated! local people={} local person={ name="Johan", lastName="Seferidis", class="B" } local names={"Markus", "Eva", "Nikol", "Adam", "Petra"} --people to register for i=1, 5 do --register 5 people local newPerson=person local name=names[i] for field=1, 3 do --for each field(name, lastname, class) if field==1 then newPerson["name"]=name end --register name end people[i]=newPerson end print("First person name: " ..people[1]["name"]) print("Second person name: "..people[2]["name"]) print("Third person name: " ..people[3]["name"])

    Read the article

  • Linq query challenge - can this be done?

    - by vdh_ant
    My table structure is as follows: Person 1-M PesonAddress Person 1-M PesonPhone Person 1-M PesonEmail Person 1-M Contract Contract M-M Program Contract M-1 Organization At the end of this query I need a populated object graph where each person has their: PesonAddress's PesonPhone's PesonEmail's PesonPhone's Contract's - and this has its respective Program's Now I had the following query and I thought that it was working great, but it has a couple of problems: from people in ctx.People.Include("PersonAddress") .Include("PersonLandline") .Include("PersonMobile") .Include("PersonEmail") .Include("Contract") .Include("Contract.Program") where people.Contract.Any( contract => (param.OrganizationId == contract.OrganizationId) && contract.Program.Any( contractProgram => (param.ProgramId == contractProgram.ProgramId))) select people; The problem is that it filters the person to the criteria but not the Contracts or the Contract's Programs. It brings back all Contracts that each person has not just the ones that have an OrganizationId of x and the same goes for each of those Contract's Programs respectively. What I want is only the people that have at least one contract with an OrgId of x with and where that contract has a Program with the Id of y... and for the object graph that is returned to have only the contracts that match and programs within that contract that match. I kinda understand why its not working, but I don't know how to change it so it is working... This is my attempt thus far: from people in ctx.People.Include("PersonAddress") .Include("PersonLandline") .Include("PersonMobile") .Include("PersonEmail") .Include("Contract") .Include("Contract.Program") let currentContracts = from contract in people.Contract where (param.OrganizationId == contract.OrganizationId) select contract let currentContractPrograms = from contractProgram in currentContracts let temp = from x in contractProgram.Program where (param.ProgramId == contractProgram.ProgramId) select x where temp.Any() select temp where currentContracts.Any() && currentContractPrograms.Any() select new Person { PersonId = people.PersonId, FirstName = people.FirstName, ..., ...., MiddleName = people.MiddleName, Surname = people.Surname, ..., ...., Gender = people.Gender, DateOfBirth = people.DateOfBirth, ..., ...., Contract = currentContracts, ... }; //This doesn't work But this has several problems (where the Person type is an EF object): I am left to do the mapping by myself, which in this case there is quite a lot to map When ever I try to map a list to a property (i.e. Scholarship = currentScholarships) it says I can't because IEnumerable is trying to be cast to EntityCollection Include doesn't work Hence how do I get this to work. Keeping in mind that I am trying to do this as a compiled query so I think that means anonymous types are out.

    Read the article

  • How do I do multiple has_and_belongs_to_many associations between the same two classes?

    - by Ermin
    I have the following setup: class Publication < ActiveRecord::Base has_and_belongs_to_many :authors, :class_name=>'Person', :join_table => 'authors_publications' has_and_belongs_to_many :editors, :class_name=>'Person', :join_table => 'editors_publications' end class Person < ActiveRecord::Base has_and_belongs_to_many :publications end With this setup I can do stuff like Publication.first.authors. But if I want to list all publications in which a person is involved Person.first.publications, an error about a missing join table people_publications it thrown. How could I fix that? Should I maybe switch to separate models for authors and editors? It would however introduce some redundancy to the database, since a person can be an author of one publication and an editor of another.

    Read the article

  • How do I query through a many-to-many relationship using NHibernate Criteria and Lambda Extensions?

    - by Brian Kendig
    In my database I have a Person table and an Event table (parties, meetings, &c.). This many-to-many relationship is represented through an Invitation table. Each Person can have many Invitations. Each Event can also have many Invitations. If I want a list of Events to which a Person is invited, I can use this HQL query: IQuery query = Session.CreateQuery("SELECT i.Event from Invitation i where i.Person = :p"); query.SetParameter("p", person); return query.List<Person>(); How would I write this query with NHibernate criteria and Lambda Extensions?

    Read the article

  • How to access a field's value in an object using reflection

    - by kentcdodds
    My Question: How to overcome an IllegalAccessException to access the value of a an object's field using reflection. Expansion: I'm trying to learn about reflection to make some of my projects more generic. I'm running into an IllegalAccessException when trying to call field.getValue(object) to get the value of that field in that object. I can get the name and type just fine. If I change the declaration from private to public then this works fine. But in an effort to follow the "rules" of encapsulation I don't want to do this. Any help would be greatly appreciated! Thanks! My Code: package main; import java.lang.reflect.Field; public class Tester { public static void main(String args[]) throws Exception { new Tester().reflectionTest(); } public void reflectionTest() throws Exception { Person person = new Person("John Doe", "555-123-4567", "Rover"); Field[] fields = person.getClass().getDeclaredFields(); for (Field field : fields) { System.out.println("Field Name: " + field.getName()); System.out.println("Field Type: " + field.getType()); System.out.println("Field Value: " + field.get(person)); //The line above throws: Exception in thread "main" java.lang.IllegalAccessException: Class main.Tester can not access a member of class main.Tester$Person with modifiers "private final" } } public class Person { private final String name; private final String phoneNumber; private final String dogsName; public Person(String name, String phoneNumber, String dogsName) { this.name = name; this.phoneNumber = phoneNumber; this.dogsName = dogsName; } } } The Output: run: Field Name: name Field Type: class java.lang.String Exception in thread "main" java.lang.IllegalAccessException: Class main.Tester can not access a member of class main.Tester$Person with modifiers "private final" at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:95) at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:261) at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:253) at java.lang.reflect.Field.doSecurityCheck(Field.java:983) at java.lang.reflect.Field.getFieldAccessor(Field.java:927) at java.lang.reflect.Field.get(Field.java:372) at main.Tester.reflectionTest(Tester.java:17) at main.Tester.main(Tester.java:8) Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds)

    Read the article

  • How can I use a prefix for the fields in my strongly typed View?

    - by deadtime
    Hi, I have an EditProfile action in my PersonController, that finds a Person object by ID and does return View(person). The EditProfile view has a bunch of fields that should be filled in with the information from the Person object. One of the fields is named "Person.FirstName", and is not filled in automatically when the View is rendered. However, if I rename the textbox to "FirstName", it gets filled in. My question is: How can I specify to the view that it should use the "Person" prefix when filling in the information from the Person object? The reason I want to do this is because of consistency - in some of my views I allow the user to edit more than one object at the same time, and use prefixes in order to bind these correctly.

    Read the article

  • Rails Model has_many with multiple foreign_keys

    - by Kenzie
    Relatively new to rails and trying to model a very simple family "tree" with a single Person model that has a name, gender, father_id and mother_id (2 parents). Below is basically what I want to do, but obviously I can't repeat the :children in a has_many (the first gets overwritten). class Person < ActiveRecord::Base belongs_to :father, :class_name => 'Person' belongs_to :mother, :class_name => 'Person' has_many :children, :class_name => 'Person', :foreign_key => 'mother_id' has_many :children, :class_name => 'Person', :foreign_key => 'father_id' end Is there a simple way to use has_many with 2 foreign keys, or maybe change the foreign key based on the object's gender? Or is there another/better way altogether? Thanks!

    Read the article

  • Hibernate is performing unwanted SELECTs on call to saveOrUpdate

    - by digiarnie
    Let's say I have a House entity which maps to many Person entities. I then load an existing House which has 20 occupants. beginTransaction(); House house = houseDao.find(1L); commitTransaction(); Later in the code, I can then add a new Person to the House: ... List<Person> people = house.getPeople(); people.add(new Person("Dilbert")); .... When I make the call: session.saveOrUpdate(house); Hibernate performs 21 queries: 1 to SELECT the House and 20 to SELECT each existing Person in the House. I'm sure it's a small issue on my part, however, what should I do so that I can add a new Person to the house without having such a heavy hit on the database in this situation? This is all done within the same session.

    Read the article

  • Hibernate Annotation for Entity existing in more than 1 catalog

    - by user286395
    I have a Person entity mapped by Hibernate to a database table in a database catalog "Active". After a period of time, records in this database table in the "Active" catalog are archived/moved to an exact copy of the table in a database Catalog "History". I have the need to retrieve from both the Active and History Catalogs. Is there a better way to model this with Hibernate annotations than making an abstract class that 2 classes extend from. This is what I have now. @MappedSuperclass public abstract class Person { @Id private Integer id; private String name; } @Entity @Table(name="Person", catalog="Active") public class PersonActive extends Person { } @Entity @Table(name="Person", catalog="History") public class PersonHistory extends Person { }

    Read the article

  • SUM of column with Left Outer Join

    - by Matt
    I am trying to get the Count of all records that have at least on person who is authorized on the record. Basically, a Record can have more than one person associated with it. I want to return the count of Total Records, a count of total Authorized Records where at least 1 person is authorized, and a count of total NotAuthorized records where no person associated with record is authorized. It doesn't matter if one person is authorized per Record or if 3 people are authorized for that record, that should add 1 to the Authorized counter. The current query is incrementing Auth and Non auth for each person added per record rather, than one per record. If no people are assigned to the record that should also count towards Not Auth. SELECT Count(DISTINCT Record.RecordID) AS TotalRecords, SUM(CASE WHEN People.PersonLevel = 1 THEN 1 ELSE 0 END) AS Authorized, SUM(CASE WHEN People.PersonLevel <> 1 THEN 1 ELSE 0 END) AS NotAuthorized FROM Record LEFT OUTER JOIN RecordPeople ON Record.RecordID = RecordPeople.RecordID LEFT OUTER JOIN People ON RecordPeople.PersonID = People.PersonID

    Read the article

  • Binding multiple objects in Grails

    - by WaZ
    I have there domain classes: :: Person. (Person.ID, Name,Address) :: Designation.(Designation.ID, Title, Band) :: SalarySlip (Person.ID, Designation.ID, totalIncome, Tax etc etc.) In the update method the person controller when I assign a person a designation from a list of designation values I want to insert a new record inside SalarySlip. Something like: def update = { def SalarySlipInstance = new SalarySlip() SalarySlipInstance.Person.ID = Params.ID //is this correct? SalarySlipInstance.Designation.ID = ?? //since the value is coming from a list. How can I bind this field? } Much Appreciated, Thanks, WB

    Read the article

  • Bulk update & occasional insert (coredata) - Too slow

    - by Andrew
    Update: Currently looking into NSSET's minusSet links: http://stackoverflow.com/questions/1475636/comparing-two-arrays Hi guys, Could benefit from your wisdom here.. I'm using Coredata in my app, on first launch I download a data file and insert over 500 objects (each with 60 attributes) - fast, no problem. Each subsequent launch I download an updated version of the file, from which I need to update all existing objects' attributes (except maybe 5 attributes) and create new ones for items which have been added to the downloaded file. So, first launch I get 500 objects.. say a week later my file now contains 507 items.. I create two arrays, one for existing and one for downloaded. NSArray *peopleArrayDownloaded = [CoreDataHelper getObjectsFromContext:@"person" :@"person_id" :YES :managedObjectContextPeopleTemp]; NSArray *peopleArrayExisting = [CoreDataHelper getObjectsFromContext:@"person" :@"person_id" :YES :managedObjectContextPeople]; If the count of each array is equal then I just do this: NSUInteger index = 0; if ([peopleArrayExisting count] == [peopleArrayDownloaded count]) { NSLog(@"Number of people downloaded is same as the number of people existing"); for (person *existingPerson in peopleArrayExisting) { person *tempPerson = [peopleArrayDownloaded objectAtIndex:index]; // NSLog(@"Updating id: %@ with id: %@",existingPerson.person_id,tempPerson.person_id); // I have 60 attributes which I to update on each object, is there a quicker way other than overwriting existing? index++; } } else { NSLog(@"Number of people downloaded is different to number of players existing"); So now comes the slow part. I end up using this (which is tooooo slow): NSLog(@"Need people added to the league"); for (person *tempPerson in peopeArrayDownloaded) { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"person_id = %@",tempPerson.person_id]; // NSLog(@"Searching for existing person, person_id: %@",existingPerson.person_id); NSArray *filteredArray = [peopleArrayExisting filteredArrayUsingPredicate:predicate]; if ([filteredArray count] == 0) { NSLog(@"Couldn't find an existing person in the downloaded file. Adding.."); person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"person" inManagedObjectContext:managedObjectContextPeople]; Is there a way to generate a new array of index items referring to the additional items in my downloaded file? Incidentally, on my tableViews I'm using NSFetchedResultsController so updating attributes will call [cell setNeedsDisplay]; .. about 60 times per cell, not a good thing and it can crash the app. Thanks for reading :)

    Read the article

  • replicating master tables mapping in transaction tables

    - by NoDisplay
    I have three master tables for location information Country {ID, Name} State {ID, Name, CountryID} City {ID, Name, StateID} Now I have one transcation table called Person which hold the person name and his location information. My Question is shall I have only CityID in the Person table like this: Person {ID, Name, CityID}' And have view of join query which give me detail like "Person{ID,Name,City,State,Country}" or Shall I replicate the mapping Person {ID, Name, CityID, StateID, CountryID} Please suggest which do you feel is to be selected and why? if there is any other option available, please suggest. Thanks in advance.

    Read the article

  • My Optimized Adam &amp; Eve

    - by MarkPearl
    Today I had a few minutes in the evening to go over my original Adam and Eve code… what I wanted to see tonight was if I could optimize the code any further… which I was pretty sure could be done. Ultimately what I wanted to find from the experiment was a balance between optimized code an reusable code. On the one hand I can put everything into a single function and end up with a totally unusable function that is extremely compressed, which would have big comebacks when making modifications at a later stage. Alternatively I could have many single line functions that are extremely loosely coupled but sparsely spaced and so would almost be to fragmented to grok. Ultimately I found with my current iteration something that I consider readable, yet compressed. Code below… // Learn more about F# at http://fsharp.net open System let people = [ ("Adam", None); ("Eve", None); ("Cain", Some("Adam", "Eve")); ("Abel", Some("Adam", "Eve")) ] // // Prints the details // let showDetails(person : string * (string * string) option) = let ParentsName = let parents = snd(person) match parents with | Some(dad, mum) -> "Father " + dad + " and Mother " + mum | None -> "Has no parents!" let result = fst(person) + Environment.NewLine + ParentsName result // // Searches an array of people and looks for a match of names // let findPerson(name : string, people : (string * (string * string) option) list) = // Try and find a match of the name let o = Seq.tryFind(fun person -> match name with | firstName when firstName = fst(person) -> true | _ -> false) people // Show the details based on the match result match o with | Option.Some(x) -> showDetails(Option.get(o)) | _ -> "Not Found" Console.WriteLine(findPerson("Cains", people)) Console.ReadLine()

    Read the article

  • Learning MVC for a JSP Resource and ASP.Net WebForms Resource

    - by Lijo
    Statement from a colleque: - "People with ASP.Net WebForms skills should be able to learn it easily as the fundamental concept is same.” Consider two people –one from JSP background and other from ASP.Net WebForms background. Now both need to learn ASP.Net MVC in RAZOR. Do you think the person from ASP.Net Webforms background has significant advantage over the person from JSP background? My feeling is – it is equally difficult for JSP person and ASP.Net Webforms person to learn MVC with RAZOR. What is your take on it? Any statistics that you can provide for this?

    Read the article

  • Good alternative to NetLimiter(windows) for ubuntu

    - by Harsh
    there is program NetLimiter for windows. while I was using windows it was very useful to me to find out the IP address of ther person who was downloading from me, or to know IP address of any person on lan who was using DC++ with some nick. and after that I can easily know the computer name of that person using nbtstat. I was wondering if there is any tool for ubuntu using which I an find out the IP address of person who is downloading from me or from whom I am downloading on lan. I am on university lan and we are using PtokaX and DC++ for file sharing on lan. people sometimes put some offencive stuff on open chat on DC++ using some Nick and I don't know how to trace them while I am using Ubuntu. Plz help.

    Read the article

  • How to prepare for a programming competition? Graphs, Stacks, Trees, oh my! [closed]

    - by Simucal
    Last semester I attended ACM's (Association for Computing Machinery) bi-annual programming competition at a local University. My University sent 2 teams of 3 people and we competed amongst other schools in the mid-west. We got our butts kicked. You are given a packet with about 11 problems (1 problem per page) and you have 4 hours to solve as many as you can. They'll run your program you submit against a set of data and your output must match theirs exactly. In fact, the judging is automated for the most part. In any case.. I went there fairly confident in my programming skills and I left there feeling drained and weak. It was a terribly humbling experience. In 4 hours my team of 3 people completed only one of the problems. The top team completed 4 of them and took 1st place. The problems they asked were like no problems I have ever had to answer before. I later learned that in order to solve them some of them effectively you have to use graphs/graph algorithms, trees, stacks. Some of them were simply "greedy" algo's. My question is, how can I better prepare for this semesters programming competition so I don't leave there feeling like a complete moron? What tips do you have for me to be able to answer these problems that involve graphs, trees, various "well known" algorithms? How can I easily identify the algorithm we should implement for a given problem? I have yet to take Algorithm Design in school so I just feel a little out of my element. Here are some examples of the questions asked at the competitions: ACM Problem Sets Update: Just wanted to update this since the latest competition is over. My team placed 1st for our small region (about 6-7 universities with between 1-5 teams each school) and ~15th for the midwest! So, it is a marked improvement over last years performance for sure. We also had no graduate students on our team and after reviewing the rules we found out that many teams had several! So, that would be a pretty big advantage in my own opinion. Problems this semester ranged from about 1-2 "easy" problems (ie bit manipulation, string manipulation) to hard (graph problems involving fairly complex math and network flow problems). We were able to solve 4 problems in our 5 hours. Just wanted to thank everyone for the resources they provided here, we used them for our weekly team practices and it definitely helped! Some quick tips that I have that aren't suggested below: When you are seated at your computer before the competition starts, quickly type out various data structures that you might need that you won't have access to in your languages libraries. I typed out a Graph data-structure complete with floyd-warshall and dijkstra's algorithm before the competition began. We ended up using it in our 2nd problem that we solved and this is the main reason why we solved this problem before anyone else in the midwest. We had it ready to go from the beginning. Similarly, type out the code to read in a file since this will be required for every problem. Save this answer "template" someplace so you can quickly copy/paste it to your IDE at the beginning of each problem. There are no rules on programming anything before the competition starts so get any boilerplate code out the way. We found it useful to have one person who is on permanent whiteboard duty. This is usually the person who is best at math and at working out solutions to get a head start on future problems you will be doing. One person is on permanent programming duty. Your fastest/most skilled "programmer" (most familiar with the language). This will save debugging time also. The last person has several roles between assessing the packet of problems for the next "easiest" problem, helping the person on the whiteboard work out solutions and helping the person programming work out bugs/issues. This person needs to be flexible and be able to switch between roles easily.

    Read the article

  • Is it appropriate for a class to only be a collection of information with no logic?

    - by qegal
    Say I have a class Person that has instance variables age, weight, and height, and another class Fruit that has instance variables sugarContent and texture. The Person class has no methods save setters and getters, while the Fruit class has both setters and getters and logic methods like calculateSweetness. Is the Fruit class the type of class that is better practice than the Person class. What I mean by this is that the Person class seems like it doesn't have much purpose; it exists solely to organize data, while the Fruit class organizes data and actually contains methods for logic.

    Read the article

  • Why is my Simplex Noise appearing in four columns?

    - by Joe the Person
    I'm trying to make a Texture out of Simplex noise, but it keeps appearing like this regardless of how big or small scale is: The following code is used to produce the image's color date: private Color[,] GetSimplex() { Color[,] colors = new Color[800, 600]; float scale = colors.GetLength(0); for (int x = 0; x < 800; x++) { for (int y = 0; y < 600; y++) { byte noise = (byte)(Noise.Generate(x / scale, y / scale) * 255); colors[x, y] = new Color(noise, noise, noise); } } return colors; }

    Read the article

  • Use a Fake Http Channel to Unit Test with HttpClient

    - by Steve Michelotti
    Applications get data from lots of different sources. The most common is to get data from a database or a web service. Typically, we encapsulate calls to a database in a Repository object and we create some sort of IRepository interface as an abstraction to decouple between layers and enable easier unit testing by leveraging faking and mocking. This works great for database interaction. However, when consuming a RESTful web service, this is is not always the best approach. The WCF Web APIs that are available on CodePlex (current drop is Preview 3) provide a variety of features to make building HTTP REST services more robust. When you download the latest bits, you’ll also find a new HttpClient which has been updated for .NET 4.0 as compared to the one that shipped for 3.5 in the original REST Starter Kit. The HttpClient currently provides the best API for consuming REST services on the .NET platform and the WCF Web APIs provide a number of extension methods which extend HttpClient and make it even easier to use. Let’s say you have a client application that is consuming an HTTP service – this could be Silverlight, WPF, or any UI technology but for my example I’ll use an MVC application: 1: using System; 2: using System.Net.Http; 3: using System.Web.Mvc; 4: using FakeChannelExample.Models; 5: using Microsoft.Runtime.Serialization; 6:   7: namespace FakeChannelExample.Controllers 8: { 9: public class HomeController : Controller 10: { 11: private readonly HttpClient httpClient; 12:   13: public HomeController(HttpClient httpClient) 14: { 15: this.httpClient = httpClient; 16: } 17:   18: public ActionResult Index() 19: { 20: var response = httpClient.Get("Person(1)"); 21: var person = response.Content.ReadAsDataContract<Person>(); 22:   23: this.ViewBag.Message = person.FirstName + " " + person.LastName; 24: 25: return View(); 26: } 27: } 28: } On line #20 of the code above you can see I’m performing an HTTP GET request to a Person resource exposed by an HTTP service. On line #21, I use the ReadAsDataContract() extension method provided by the WCF Web APIs to serialize to a Person object. In this example, the HttpClient is being passed into the constructor by MVC’s dependency resolver – in this case, I’m using StructureMap as an IoC and my StructureMap initialization code looks like this: 1: using StructureMap; 2: using System.Net.Http; 3:   4: namespace FakeChannelExample 5: { 6: public static class IoC 7: { 8: public static IContainer Initialize() 9: { 10: ObjectFactory.Initialize(x => 11: { 12: x.For<HttpClient>().Use(() => new HttpClient("http://localhost:31614/")); 13: }); 14: return ObjectFactory.Container; 15: } 16: } 17: } My controller code currently depends on a concrete instance of the HttpClient. Now I *could* create some sort of interface and wrap the HttpClient in this interface and use that object inside my controller instead – however, there are a few why reasons that is not desirable: For one thing, the API provided by the HttpClient provides nice features for dealing with HTTP services. I don’t really *want* these to look like C# RPC method calls – when HTTP services have REST features, I may want to inspect HTTP response headers and hypermedia contained within the message so that I can make intelligent decisions as to what to do next in my workflow (although I don’t happen to be doing these things in my example above) – this type of workflow is common in hypermedia REST scenarios. If I just encapsulate HttpClient behind some IRepository interface and make it look like a C# RPC method call, it will become difficult to take advantage of these types of things. Second, it could get pretty mind-numbing to have to create interfaces all over the place just to wrap the HttpClient. Then you’re probably going to have to hard-code HTTP knowledge into your code to formulate requests rather than just “following the links” that the hypermedia in a message might provide. Third, at first glance it might appear that we need to create an interface to facilitate unit testing, but actually it’s unnecessary. Even though the code above is dependent on a concrete type, it’s actually very easy to fake the data in a unit test. The HttpClient provides a Channel property (of type HttpMessageChannel) which allows you to create a fake message channel which can be leveraged in unit testing. In this case, what I want is to be able to write a unit test that just returns fake data. I also want this to be as re-usable as possible for my unit testing. I want to be able to write a unit test that looks like this: 1: [TestClass] 2: public class HomeControllerTest 3: { 4: [TestMethod] 5: public void Index() 6: { 7: // Arrange 8: var httpClient = new HttpClient("http://foo.com"); 9: httpClient.Channel = new FakeHttpChannel<Person>(new Person { FirstName = "Joe", LastName = "Blow" }); 10:   11: HomeController controller = new HomeController(httpClient); 12:   13: // Act 14: ViewResult result = controller.Index() as ViewResult; 15:   16: // Assert 17: Assert.AreEqual("Joe Blow", result.ViewBag.Message); 18: } 19: } Notice on line #9, I’m setting the Channel property of the HttpClient to be a fake channel. I’m also specifying the fake object that I want to be in the response on my “fake” Http request. I don’t need to rely on any mocking frameworks to do this. All I need is my FakeHttpChannel. The code to do this is not complex: 1: using System; 2: using System.IO; 3: using System.Net.Http; 4: using System.Runtime.Serialization; 5: using System.Threading; 6: using FakeChannelExample.Models; 7:   8: namespace FakeChannelExample.Tests 9: { 10: public class FakeHttpChannel<T> : HttpClientChannel 11: { 12: private T responseObject; 13:   14: public FakeHttpChannel(T responseObject) 15: { 16: this.responseObject = responseObject; 17: } 18:   19: protected override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) 20: { 21: return new HttpResponseMessage() 22: { 23: RequestMessage = request, 24: Content = new StreamContent(this.GetContentStream()) 25: }; 26: } 27:   28: private Stream GetContentStream() 29: { 30: var serializer = new DataContractSerializer(typeof(T)); 31: Stream stream = new MemoryStream(); 32: serializer.WriteObject(stream, this.responseObject); 33: stream.Position = 0; 34: return stream; 35: } 36: } 37: } The HttpClientChannel provides a Send() method which you can override to return any HttpResponseMessage that you want. You can see I’m using the DataContractSerializer to serialize the object and write it to a stream. That’s all you need to do. In the example above, the only thing I’ve chosen to do is to provide a way to return different response objects. But there are many more features you could add to your own re-usable FakeHttpChannel. For example, you might want to provide the ability to add HTTP headers to the message. You might want to use a different serializer other than the DataContractSerializer. You might want to provide custom hypermedia in the response as well as just an object or set HTTP response codes. This list goes on. This is the just one example of the really cool features being added to the next version of WCF to enable various HTTP scenarios. The code sample for this post can be downloaded here.

    Read the article

  • Is this how dynamic language copes with dynamic requirement?

    - by Amumu
    The question is in the title. I want to have my thinking verified by experienced people. You can add more or disregard my opinion, but give me a reason. Here is an example requirement: Suppose you are required to implement a fighting game. Initially, the game only includes fighters, who can attack each other. Each fighter can punch, kick or block incoming attacks. Fighters can have various fighting styles: Karate, Judo, Kung Fu... That's it for the simple universe of the game. In an OO like Java, it can be implemented similar to this way: abstract class Fighter { int hp, attack; void punch(Fighter otherFighter); void kick(Fighter otherFighter); void block(Figther otherFighter); }; class KarateFighter extends Fighter { //...implementation...}; class JudoFighter extends Fighter { //...implementation... }; class KungFuFighter extends Fighter { //...implementation ... }; This is fine if the game stays like this forever. But, somehow the game designers decide to change the theme of the game: instead of a simple fighting game, the game evolves to become a RPG, in which characters can not only fight but perform other activities, i.e. the character can be a priest, an accountant, a scientist etc... At this point, to make it more generic, we have to change the structure of our original design: Fighter is not used to refer to a person anymore; it refers to a profession. The specialized classes of Fighter (KaraterFighter, JudoFighter, KungFuFighter) . Now we have to create a generic class named Person. However, to adapt this change, I have to change the method signatures of the original operations: class Person { int hp, attack; List<Profession> skillSet; }; abstract class Profession {}; class Fighter extends Profession { void punch(Person otherFighter); void kick(Person otherFighter); void block(Person otherFighter); }; class KarateFighter extends Fighter { //...implementation...}; class JudoFighter extends Fighter { //...implementation... }; class KungFuFighter extends Fighter { //...implementation ... }; class Accountant extends Profession { void calculateTax(Person p) { //...implementation...}; void calculateTax(Company c) { //...implementation...}; }; //... more professions... Here are the problems: To adapt to the method changes, I have to fix the places where the changed methods are called (refactoring). Every time a new requirement is introduced, the current structural design has to be broken to adapt the changes. This leads to the first problem. Rigid structure makes it hard for code reuse. A function can only accept the predefined types, but it cannot accept future unknown types. A written function is bound to its current universe and has no way to accommodate to the new types, without modifications or rewrite from scratch. I see Java has a lot of deprecated methods. OO is an extreme case because it has inheritance to add up the complexity, but in general for statically typed language, types are very strict. In contrast, a dynamic language can handle the above case as follow: ;;fighter1 punch fighter2 (defun perform-punch (fighter1 fighter2) ...implementation... ) ;;fighter1 kick fighter2 (defun perform-kick (fighter1 fighter2) ...implementation... ) ;;fighter1 blocks attacks from fighter2 (defun perform-block (fighter1 fighter2) ...implementation... ) fighter1 and fighter2 can be anything as long as it has the required data for calculation; or methods (duck typing). You don't have to change from the type Fighter to Person. In the case of Lisp, because Lisp only has a single data structure: list, it's even easier to adapt to changes. However, other dynamic languages can have similar behaviors as well. I work primarily with static languages (mainly C and Java, but working with Java was a long time ago). I started learning Lisp and some other dynamic languages this year. I can see how it helps improving my productivity.

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >