Search Results

Search found 1685 results on 68 pages for 'joe doe'.

Page 7/68 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Setting routes in application.ini in Zend Framework

    - by Paul Watson
    I'm a Zend Framework newbie, and I'm trying to work out how to add another route to my application.ini file. I currently have my routes set up as follows: resources.router.routes.artists.route = /artists/:stub resources.router.routes.artists.defaults.controller = artists resources.router.routes.artists.defaults.action = display ...so that /artists/joe-bloggs uses the "display" action of the "artists" controller to dipslay the profile the artist in question - that works fine. What I want to do now is to set up another route so that /artists/joe-bloggs/random-gallery-name goes to the "galleries" action of the "artists" controller. I tried adding an additional block to the application.ini file (beneath the block above) like so: resources.router.routes.artists.route = /artists/:stub/:gallery resources.router.routes.artists.defaults.controller = artists resources.router.routes.artists.defaults.action = galleries ...but when I do that the page at /artists/joe-bloggs no longer works (Zend tries to route it to the "joe-bloggs" controller). How do I set up the routes in application.ini so that I can change the action of the "artists" controller depending on whether "/:gallery" exists? I realise I'm probably making a really stupid mistake, so please point out my stupidity and set me on the right path (no pun intended).

    Read the article

  • How to configure Users permissions in Windows Server 2008 R2 by command line?

    - by Répás
    I have to create about 800 users in our Windows S 2008 R2 and I'd like to make a few settings with them. Create user: net user Joe 1mb4pASs /add /fullname:"John Smith" /passwordchg:no /comment:"no comment" Set never expired password: wmic useraccount where "Name='Joe'" set PasswordExpires=FALSE Add the user to two groups (like in the Members Of tab in the GUI) Remote Desktop Users (I translated it from hungarian, because the server) Terminal Services - Computers to enable the use of applications via webaccess Step 3 is where I'm having problems. What command(s) should I use for this?

    Read the article

  • /usr/bin/env: ruby1.8: No such file or directory

    - by sandstrom
    Problem Trying to setup CI Joe (https://github.com/defunkt/cijoe) and I get the following error: /usr/bin/env: ruby1.8: No such file or directory What I'm doing CI Joe is run as www-data, and the command I'm running is RAILS_ENV=test bundle exec rake -s test When I log in as www-data (sudo su www-data) and execute the same command it works. So I'm trying to figure out what may be wrong. Debug Output $ which ruby1.8 /usr/bin/ruby1.8 This problem is similar to: http://stackoverflow.com/questions/6126165/usr-bin-env-ruby-1-8-no-such-file-or

    Read the article

  • How can I make Mac OS X Address Book display a person’s home address from an LDAP server?

    - by Arcturus
    Hi, (I've posted this question on Stack Overflow first, but someone told me it belonged here.) I have a custom LDAP server, which I can customize to generate whichever object class and attributes I need. I'm trying to display people from that server in the Mac OS X address book. Names and organizations display correctly, as well as work-related phone and address. However, I've never been able to have a home address displayed in the address book. This is an example of output from running a ldapsearch: # extended LDIF # # LDAPv3 # base <dc=example,dc=com> with scope subtree # filter: (givenName=Joh*) # requesting: ALL # # 10041, example.com dn: uid=10041,dc=example,dc=com objectclass: top objectclass: person objectclass: organizationalPerson objectclass: inetOrgPerson objectclass: mozillaOrgPerson uid: 10041 cn: John Doe givenName: John sn: Doe o: Acme telephoneNumber: 500 00 00 mobile: 500 00 00 mail: [email protected] street: Baker St postalCode: 10098 l: New York c: US homePostalAddress: White St mozillaHomePostalCode: 10098 mozillaHomeLocalityName: New York mozillaHomeCountryName: US # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 Every piece of information shows up in the address book up to here: homePostalAddress: White St mozillaHomePostalCode: 10098 mozillaHomeLocalityName: New York mozillaHomeCountryName: US Which object class or attribute name should I use to have the home address show up in the Mac OS X address book?

    Read the article

  • How to dispose NHibernate ISession in an ASP.NET MVC App

    - by Joe Young
    I have NHibernate hooked up in my asp.net mvc app. Everything works fine, if I DON'T dispose the ISession. I have read however that you should dispose, but when I do, I get random "Session is closed" exceptions. I am injecting the ISession into my other objects with Windsor. Here is my current NHModule: public class NHibernateHttpModule : IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += context_BeginRequest; context.EndRequest += context_EndRequest; } static void context_EndRequest(object sender, EventArgs e) { CurrentSessionContext.Unbind(MvcApplication.SessionFactory); } static void context_BeginRequest(object sender, EventArgs e) { CurrentSessionContext.Bind(MvcApplication.SessionFactory.OpenSession()); } public void Dispose() { // do nothing } } Registering the ISession: container .Register(Component.For<ISession>() .UsingFactoryMethod(() => MvcApplication.SessionFactory.GetCurrentSession()).LifeStyle.Transient); The error happens when I tack the Dispose on the unbind in the module. Since I keep getting the session is closed error I assume this is not the correct way to do this, so what is the correct way? Thanks, Joe

    Read the article

  • write client ip in iis 7.0 log over firewalls

    - by Guy Bertental
    Hi, I a solution for IIS 7.0 which runs on windows server 2008 64bit to write my clients IP to IIS logs while the server is behind firewalls and proxies (Pass X-Forwarded-For header value). I've tried to install the an ISAPI Filter written by Joe Pruitt. it works great on Windows Server 2003 32bit IIS 6.0, but seems to do nothing at all on windows server 2008 64bit IIS 7.0. Did anyone try this ISAPI filter on this version of OS? or have another solution? link to the Joe Pruitt's (from F5) ISAPI filter: http://devcentral.f5.com/weblogs/Joe/archive/2009/08/19/x_forwarded_for_log_filter_for_windows_servers.aspx best regards, guy bertental

    Read the article

  • PHP File Exists Always False

    - by Joe
    I have a case where file_exists() is always returning false. My latest attempt was to just test to see if it would return true for $_SERVER["SCRIPT_FILENAME"] and then return the value of the path if it couldn't find the file which it does. The path while not necessarily relevant to solving the problem is: /Users/joe/Workspace/720/app/webroot/index.php I have obviously verified that the file is there, and am not even sure how it couldn't be there since php is serving it up. I should mention this is on an install of OS X Snow Leopard running PHP 5.3.0. Any ideas would be fantastic. CODE SAMPLE: if (!file_exists($_SERVER["SCRIPT_FILENAME"])) $errors[] = 'Cant find:'. $_SERVER["SCRIPT_FILENAME"];

    Read the article

  • Cucumber/Webrat: follow link by CSS class?

    - by Joe
    Hello there, is it possible to follow a link by it's class name instead of the id, text or title? Given I have (haha, cucumber insider he?) the following html code: <div id="some_information_container"> <a href="edit" class="edit_button">Translation here</a> </div> I do not want to match by text because I'd have to care about the translation values in my tests I want to have my buttons look all the same style, so I will use the CSS class. I don't want to assign a id to every single link, because some of them are perfectly identified through the container and the link class Is there anything I missed in Cucumber/Webrat? Or do you have some advices to solve this in a better way? Thanks for your help and best regards, Joe edit: I found an interesting discussion going on about this topic right here - seems to remain an open issue for now. Do you have any other solutions for this?

    Read the article

  • How to compile scheme into native binary files ?

    - by Joe
    I am very new to scheme. And now I am trying to compile some scheme code into binary file which will be loaded faster into interpreter. (The interpreter is a hybrid interpreter)Some one told me that I can compile the code into native binary file and then load it into interperter. And my question is: 1. What is the native binary file? 2. How can I compile the scheme code into a native binary file? 3. How can I load native bianry file into scheme interpreter? Thanks in advance. Joe Suggested that I want to compile below code into native binary file: (define test (lambda() (display "this is a test")) And then load the bianry file into interpreter and call the function "test".

    Read the article

  • How to count incrementally in SQL SERVER

    - by joe
    Hi Folks, I am assigned a problem which i am not sure how to write it in SQL SEVER (version 5/8) yet. Here is the simple query and its output: Select location, date_time, Item_sold From Product Location Date_time Item_sold VA 12/10/2010 1:30:00 PM Candy VA 12/10/2010 3:30:00 PM Chips VA 12/13/2010 12:50:00 AM Wine DC 12/13/2010 8:00:00 AM Gum DC 12/13/2010 12:30:00 PM Bags DC 12/13/2010 1:16:00 PM Cheese DC 12/13/2010 12:00:00 AM Hotdog NJ 12/15/2010 12:00:00 AM Coffee NJ 12/15/2010 1:15:00 PM Beers NJ 12/15/2010 3:45:00 AM Cream Here is my desired output, which I guess a while/for loop or a pivot function could do the job but my experience is not there yet. Basically, I need to count the number of item sold from the Item_sold column incrementally (base line date starts from 12/8 to 12/9, 12/8 to 12/10, 12/8 to 12/11, 12/8 to 12/12...) I was wondering if anyone could edcuate and solve this problem. Many thanks in advance, Joe Location 12/8 |12/8-12/9 |12/8-12/10 |12/8 - 12/11 |12/8 - 12/12 |12/8 - 12/13 VA 0 0 2 0 0 3 DC 0 0 0 0 0 4

    Read the article

  • I'm not sure if I should use a redirect

    - by Joe
    Hi there, I have an affiliate link on my webpage. When you click on the link it follows the href value which is as follows: www.site_name.com/?refer=my_affiliate_id This would be fine, except that the site offers no tracking for the ads, so I can't tell how many clicks I am getting. I could easily implement my own tracking by changing the original link href value to a php script which increments some click stats in a database and then redirects the user to the original page. But I have read some articles that say that using redirects may be seen by google as a sign of 'blackhat' techniques and they might rank me lower, unindex my site or even hurt the site that I'm redirecting too. Does anybody know if this is true, or have any idea of the best way I could go about this? Many thanks in advance Joe

    Read the article

  • Twig Template For loop Results

    - by user981480
    I am trying to print out a the contents of an array but am not getting the expected results. any help is much appreciated: PHP code: $list[1]['first_name'] = 'Joe'; $list[1]['last_name'] = 'Smith'; $list[2]['first_name'] = 'John'; $list[2]['last_name'] = 'brand'; $data = array( 'customer' => $list ); echo $template->render($data); Template Markup: <html> <head><title>My first Twig template!</title></head> <body> {% for person in customer %} {{ person.first_name }} {% endfor %} </body> RESULTS: Array ( [first_name] = Joe [last_name] = Smith ) first_name Joe Array ( [first_name] = John [last_name] = brand ) first_name John

    Read the article

  • OWL inferencing question

    - by user439170
    I am using the Jena semantic web framework version 2.6.3. I have code that creates a model with owl inferencing and then adds the following triples: [:bnode-3 rdf:type owl:Restriction] [:bnode-3 owl:onProperty :offspringOf] [:bnode-3 owl:someValuesFrom :Person] [:bnode-3 rdfs:subClassOf :Person] bnode-3 is supposed to be a restriction class which, for example, would contain :joe if :bob is a :Person and the following triple were asserted: [:joe :offspringOf :bob]. Then, since the restriction class is a subclass of Person, :joe would also be a person. And, in fact, this works. Whats confusing to me is that after I assert just the 4 triples at the top of this post, the inferencer creates a blank node which is a Person. In other words, the following triple is now in the model: [_:b0 rdf:type :Person] I don't understand why it would do this. Any help in understanding this would be greatly appreciated. Thanks. Kent.

    Read the article

  • Retrieve a user's Exchange database in powershell

    - by Paul
    Hey Everyone, I've scoured the interwebs for a few days now off and on to find this. I am creating a powershell script for email-enabling new user's(Exchange 2007). To give you a little background when we have a new hire, their AD account is created at our off-site helpdesk, but they don't create their email account. I'm trying to automate the process of mail-enabling the user which involves putting them in the same database as an existing user, disable imap pop activesync, and lastly email the requester of the ticket. I would like to just get prompted for the New User's name, User to Replicate(mailbox, storage group, database), and the person to email after it's been created. So if someone could just help with a command to Retrieve a user's Exchange database in powershell that would be great, but if people also want to help with my hacked up script please do so as well!!! Here is what I have so far: Write-output “ENTER THE FOLLOWING DETAILS” $DName = Read-Host “User Diplay Name" $RUser = Read-Host "Replicate User(Database Grab)" ***$RData = #get the Replicate user's mailbox database here*** $REmail = #either just use a Read-Host “Requester's Email address" or ask for Requester's name and pipe through their email address by digging for it w/ powershell Enable-Mailbox -Identity "$DName" -Database "$RData" Send-MailMessage -From "John Doe <[email protected]>" -To (put $REmail here which is the Requester's email) -Subject "Test Person's email account" -Body "Test Person's email account has been setup.`n`n`nJohn Doe`nGeneric Company`nSystems Administrator`nOffice: 123.456.7890`[email protected]" -SmtpServer genericexchange.exchange.com

    Read the article

  • C++ STL map.find() not finding my stuff

    - by Joe
    Hello, I have constructed a map and loaded it with data. If I iterate over all the elements I see they are all valid. However, the find method doesn't find my item. I'm sure it's something stupid I am doing. Here is snippet: // definitions // I am inserting a person class and using the firstname as the key typedef std::map<char*,Person *> mapType; mapType _myMap; mapType::iterator _mapIter; ... Person *pers = new Person(FirstName, LastName, Address, Phone); _myMap.insert(make_pair(pers->firstName, pers); ... ...later.... _mapIter = _myMap.find(firstName); // returns map.end _mapIter = _myMap.find("joe"); // returns map.end and I have no idea why :(

    Read the article

  • phpunit - generate tests for all the classes from a directory

    - by joe
    Hi! I have a directoy structure, and all the classes of the business logic are placed in the app_dir/lib/ directory. I would like to generate unit tests for all the classes from this lib/ folder. The problem is, that I haven't found any option to specify the source directory, only the source file: from app_dir: phpunit --skeleton-class lib/ Error: "lib/.php" could not be opened. Is it the only solution to write my own php script, which iterates through the /lib folder and calls the skeleton generator for every file found? And how can I specify the output folder, where all the generated test files are placed? Thanx, Joe

    Read the article

  • How do I find the Recaptcha ID?

    - by Joe
    I've been stuck on something for the past day. I'm building a RoR bot, and part of it involves signing up for an email account with mail.com. I've automated all the filling out of the form, apart from the captcha (Recaptcha). I'll be using the deathbycaptcha Ruby gem. However, in order to have the captcha solved, I'll need to get either its ID or its URL. While this shows up when I "enable form details" with the Firefox Web Developer toolbar, it doesn't seem to be in the source. How can I find it out? I'm using Watir. Thanks! Joe

    Read the article

  • linux: automount internal hard drive during boot?

    - by John Doe
    i try to create my own NAS and i need to automount the internal sata disks during boot i know i could do using fstab but im searching for a more easy/generalized way so its easier to scale with less handwork needed for every hard drive attached (or every mainboard added to the cluster) so anyone knows how to automount internal disks without using fstab like ubuntu does for usb drives? im using ubuntu server 9.10 thx all

    Read the article

  • Can't get MultiViews to work on Apache 2.2 - negotiation problem

    - by Doe
    Hi I can't get MultiViews to set up properly on my Apache 2.2. When I go to filtered.com/something, I expect it to execute something.pl but it doesn't. I get a Error 404 page. In my error logs it says: " [Fri Apr 16 13:04:20 2010] [error] [client 78.85.152.94] Negotiation: discovere\ d file(s) matching request: /var/www/html/filtered.net/translate-english (None could be negotiated)., referer: http://filtered.net/" Would anyone kindly help me so that MultiViews is properly installed on my server? ServerAdmin [email protected] ServerAlias *.filtered.net DocumentRoot /var/www/html/filtered.net ServerName filtered.net ErrorLog logs/filtered.net-error_log CustomLog logs/filtered.net-access_log common Options ExecCGI +Indexes +IncludesNoExec +MultiViews +ExecCGI AllowOverride None Order allow,deny Allow from all <IfModule mod_dir.c> DirectoryIndex index.php index.html index.pl </IfModule> </Directory> </VirtualHost>

    Read the article

  • linux kernel option to set sata disk to udma/133 1.5gbps

    - by John Doe
    hi, i try to speed up boot time of my linux server box which uses removable HDD rack's the current boot time is around 2 min's but if i connect the hdd's directly to the mainboard its about 2 sec's the problem is that ahci's kernel implementation causes a timeout of around 30 seconds for each disk during boot which originates from the hdd-rack after the timeout the kernel prints that the disk is limited with speed to 1.5gbps and udma/133 is used so the question i have is: how can i set this in grub as a boot option so the kernel doesnt have to wait for a timeout and just hardcoded limits the speed of the disks? i read about a few options like pci=nomsi or such, which dont work thats why im asking for limiting precisely the disks during boot thx

    Read the article

  • Download resume support blocked by isp?

    - by John Doe
    Can ISP block resume support for downloads ? I'm using IDM (internet download manager) to download of the internet from resume supported websites, yet I am unable to resume downloads. I tried different computers with the same result. Turned off firewall, didn't have any effect i was able to download with no issues until a couple of days ago. Another thing i noticed is that before IDM used to try to connect to several connections to speed up my download, but now it can only connect to one connection. Also i tried to download using my vpn, and i was able to download and resume downloads with no problem.

    Read the article

  • Simple way to encode a string according to a password?

    - by RexE
    Does Python have a built-in, simple way of encoding/decoding strings using a password? Something like this: >>> encode('John Doe', password = 'mypass') 'sjkl28cn2sx0' >>> decode('sjkl28cn2sx0', password = 'mypass') 'John Doe' I would like to use these encrypted strings as URL parameters. My goal is obfuscation, not strong security. I realize I could use a database table to store keys and values, but am trying to be minimalist.

    Read the article

  • Need help with SQL Query

    - by StackOverflowNewbie
    Say I have 2 tables: Person - Id - Name PersonAttribute - Id - PersonId - Name - Value Further, let's say that each person had 2 attributes (say, gender and age). A sample record would be like this: Person->Id = 1 Person->Name = 'John Doe' PersonAttribute->Id = 1 PersonAttribute->PersonId = 1 PersonAttribute->Name = 'Gender' PersonAttribute->Value = 'Male' PersonAttribute->Id = 2 PersonAttribute->PersonId = 1 PersonAttribute->Name = 'Age' PersonAttribute->Value = '30' Question: how do I query this such that I get a result like this: 'John Doe', 'Male', '30'

    Read the article

  • Using LINQ Distinct: With an Example on ASP.NET MVC SelectListItem

    - by Joe Mayo
    One of the things that might be surprising in the LINQ Distinct standard query operator is that it doesn’t automatically work properly on custom classes. There are reasons for this, which I’ll explain shortly. The example I’ll use in this post focuses on pulling a unique list of names to load into a drop-down list. I’ll explain the sample application, show you typical first shot at Distinct, explain why it won’t work as you expect, and then demonstrate a solution to make Distinct work with any custom class. The technologies I’m using are  LINQ to Twitter, LINQ to Objects, Telerik Extensions for ASP.NET MVC, ASP.NET MVC 2, and Visual Studio 2010. The function of the example program is to show a list of people that I follow.  In Twitter API vernacular, these people are called “Friends”; though I’ve never met most of them in real life. This is part of the ubiquitous language of social networking, and Twitter in particular, so you’ll see my objects named accordingly. Where Distinct comes into play is because I want to have a drop-down list with the names of the friends appearing in the list. Some friends are quite verbose, which means I can’t just extract names from each tweet and populate the drop-down; otherwise, I would end up with many duplicate names. Therefore, Distinct is the appropriate operator to eliminate the extra entries from my friends who tend to be enthusiastic tweeters. The sample doesn’t do anything with the drop-down list and I leave that up to imagination for what it’s practical purpose could be; perhaps a filter for the list if I only want to see a certain person’s tweets or maybe a quick list that I plan to combine with a TextBox and Button to reply to a friend. When the program runs, you’ll need to authenticate with Twitter, because I’m using OAuth (DotNetOpenAuth), for authentication, and then you’ll see the drop-down list of names above the grid with the most recent tweets from friends. Here’s what the application looks like when it runs: As you can see, there is a drop-down list above the grid. The drop-down list is where most of the focus of this article will be. There is some description of the code before we talk about the Distinct operator, but we’ll get there soon. This is an ASP.NET MVC2 application, written with VS 2010. Here’s the View that produces this screen: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TwitterFriendsViewModel>" %> <%@ Import Namespace="DistinctSelectList.Models" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">     Home Page </asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">     <fieldset>         <legend>Twitter Friends</legend>         <div>             <%= Html.DropDownListFor(                     twendVM => twendVM.FriendNames,                     Model.FriendNames,                     "<All Friends>") %>         </div>         <div>             <% Html.Telerik().Grid<TweetViewModel>(Model.Tweets)                    .Name("TwitterFriendsGrid")                    .Columns(cols =>                     {                         cols.Template(col =>                             { %>                                 <img src="<%= col.ImageUrl %>"                                      alt="<%= col.ScreenName %>" />                         <% });                         cols.Bound(col => col.ScreenName);                         cols.Bound(col => col.Tweet);                     })                    .Render(); %>         </div>     </fieldset> </asp:Content> As shown above, the Grid is from Telerik’s Extensions for ASP.NET MVC. The first column is a template that renders the user’s Avatar from a URL provided by the Twitter query. Both the Grid and DropDownListFor display properties that are collections from a TwitterFriendsViewModel class, shown below: using System.Collections.Generic; using System.Web.Mvc; namespace DistinctSelectList.Models { /// /// For finding friend info on screen /// public class TwitterFriendsViewModel { /// /// Display names of friends in drop-down list /// public List FriendNames { get; set; } /// /// Display tweets in grid /// public List Tweets { get; set; } } } I created the TwitterFreindsViewModel. The two Lists are what the View consumes to populate the DropDownListFor and Grid. Notice that FriendNames is a List of SelectListItem, which is an MVC class. Another custom class I created is the TweetViewModel (the type of the Tweets List), shown below: namespace DistinctSelectList.Models { /// /// Info on friend tweets /// public class TweetViewModel { /// /// User's avatar /// public string ImageUrl { get; set; } /// /// User's Twitter name /// public string ScreenName { get; set; } /// /// Text containing user's tweet /// public string Tweet { get; set; } } } The initial Twitter query returns much more information than we need for our purposes and this a special class for displaying info in the View.  Now you know about the View and how it’s constructed. Let’s look at the controller next. The controller for this demo performs authentication, data retrieval, data manipulation, and view selection. I’ll skip the description of the authentication because it’s a normal part of using OAuth with LINQ to Twitter. Instead, we’ll drill down and focus on the Distinct operator. However, I’ll show you the entire controller, below,  so that you can see how it all fits together: using System.Linq; using System.Web.Mvc; using DistinctSelectList.Models; using LinqToTwitter; namespace DistinctSelectList.Controllers { [HandleError] public class HomeController : Controller { private MvcOAuthAuthorization auth; private TwitterContext twitterCtx; /// /// Display a list of friends current tweets /// /// public ActionResult Index() { auth = new MvcOAuthAuthorization(InMemoryTokenManager.Instance, InMemoryTokenManager.AccessToken); string accessToken = auth.CompleteAuthorize(); if (accessToken != null) { InMemoryTokenManager.AccessToken = accessToken; } if (auth.CachedCredentialsAvailable) { auth.SignOn(); } else { return auth.BeginAuthorize(); } twitterCtx = new TwitterContext(auth); var friendTweets = (from tweet in twitterCtx.Status where tweet.Type == StatusType.Friends select new TweetViewModel { ImageUrl = tweet.User.ProfileImageUrl, ScreenName = tweet.User.Identifier.ScreenName, Tweet = tweet.Text }) .ToList(); var friendNames = (from tweet in friendTweets select new SelectListItem { Text = tweet.ScreenName, Value = tweet.ScreenName }) .Distinct() .ToList(); var twendsVM = new TwitterFriendsViewModel { Tweets = friendTweets, FriendNames = friendNames }; return View(twendsVM); } public ActionResult About() { return View(); } } } The important part of the listing above are the LINQ to Twitter queries for friendTweets and friendNames. Both of these results are used in the subsequent population of the twendsVM instance that is passed to the view. Let’s dissect these two statements for clarification and focus on what is happening with Distinct. The query for friendTweets gets a list of the 20 most recent tweets (as specified by the Twitter API for friend queries) and performs a projection into the custom TweetViewModel class, repeated below for your convenience: var friendTweets = (from tweet in twitterCtx.Status where tweet.Type == StatusType.Friends select new TweetViewModel { ImageUrl = tweet.User.ProfileImageUrl, ScreenName = tweet.User.Identifier.ScreenName, Tweet = tweet.Text }) .ToList(); The LINQ to Twitter query above simplifies what we need to work with in the View and the reduces the amount of information we have to look at in subsequent queries. Given the friendTweets above, the next query performs another projection into an MVC SelectListItem, which is required for binding to the DropDownList.  This brings us to the focus of this blog post, writing a correct query that uses the Distinct operator. The query below uses LINQ to Objects, querying the friendTweets collection to get friendNames: var friendNames = (from tweet in friendTweets select new SelectListItem { Text = tweet.ScreenName, Value = tweet.ScreenName }) .Distinct() .ToList(); The above implementation of Distinct seems normal, but it is deceptively incorrect. After running the query above, by executing the application, you’ll notice that the drop-down list contains many duplicates.  This will send you back to the code scratching your head, but there’s a reason why this happens. To understand the problem, we must examine how Distinct works in LINQ to Objects. Distinct has two overloads: one without parameters, as shown above, and another that takes a parameter of type IEqualityComparer<T>.  In the case above, no parameters, Distinct will call EqualityComparer<T>.Default behind the scenes to make comparisons as it iterates through the list. You don’t have problems with the built-in types, such as string, int, DateTime, etc, because they all implement IEquatable<T>. However, many .NET Framework classes, such as SelectListItem, don’t implement IEquatable<T>. So, what happens is that EqualityComparer<T>.Default results in a call to Object.Equals, which performs reference equality on reference type objects.  You don’t have this problem with value types because the default implementation of Object.Equals is bitwise equality. However, most of your projections that use Distinct are on classes, just like the SelectListItem used in this demo application. So, the reason why Distinct didn’t produce the results we wanted was because we used a type that doesn’t define its own equality and Distinct used the default reference equality. This resulted in all objects being included in the results because they are all separate instances in memory with unique references. As you might have guessed, the solution to the problem is to use the second overload of Distinct that accepts an IEqualityComparer<T> instance. If you were projecting into your own custom type, you could make that type implement IEqualityComparer<T>, but SelectListItem belongs to the .NET Framework Class Library.  Therefore, the solution is to create a custom type to implement IEqualityComparer<T>, as in the SelectListItemComparer class, shown below: using System.Collections.Generic; using System.Web.Mvc; namespace DistinctSelectList.Models { public class SelectListItemComparer : EqualityComparer { public override bool Equals(SelectListItem x, SelectListItem y) { return x.Value.Equals(y.Value); } public override int GetHashCode(SelectListItem obj) { return obj.Value.GetHashCode(); } } } The SelectListItemComparer class above doesn’t implement IEqualityComparer<SelectListItem>, but rather derives from EqualityComparer<SelectListItem>. Microsoft recommends this approach for consistency with the behavior of generic collection classes. However, if your custom type already derives from a base class, go ahead and implement IEqualityComparer<T>, which will still work. EqualityComparer is an abstract class, that implements IEqualityComparer<T> with Equals and GetHashCode abstract methods. For the purposes of this application, the SelectListItem.Value property is sufficient to determine if two items are equal.   Since SelectListItem.Value is type string, the code delegates equality to the string class. The code also delegates the GetHashCode operation to the string class.You might have other criteria in your own object and would need to define what it means for your object to be equal. Now that we have an IEqualityComparer<SelectListItem>, let’s fix the problem. The code below modifies the query where we want distinct values: var friendNames = (from tweet in friendTweets select new SelectListItem { Text = tweet.ScreenName, Value = tweet.ScreenName }) .Distinct(new SelectListItemComparer()) .ToList(); Notice how the code above passes a new instance of SelectListItemComparer as the parameter to the Distinct operator. Now, when you run the application, the drop-down list will behave as you expect, showing only a unique set of names. In addition to Distinct, other LINQ Standard Query Operators have overloads that accept IEqualityComparer<T>’s, You can use the same techniques as shown here, with SelectListItemComparer, with those other operators as well. Now you know how to resolve problems with getting Distinct to work properly and also have a way to fix problems with other operators that require equality comparisons. @JoeMayo

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >