Search Results

Search found 2625 results on 105 pages for 'friends'.

Page 5/105 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • SQLAuthority News – 5th Anniversary Giveaways

    - by pinaldave
    Please read my 5th Anniversary post and my quick note on history of the Database. I am sure that we all have friends and we value friendship more than anything. In fact, the complete model of Facebook is built on friends. If you have lots of friends, you must be a lucky person. Having a lot of friends is indeed a good thing. I consider all you blog readers as my friends so now I want do something for you. What is it? Well, send me details about how many of your friends like my page and you would have a chance to win lots of learning materials for yourself and your friends. Here are the exciting prizes awaiting the lucky winner: Combo set of 5 Joes 2 Pros Book – 1 for YOU and 1 for Friend This is USD 444 (each set USD 222) worth gift. It contains all the five Joes 2 Pros books (Vol1, Vol2, Vol3, Vol4, Vol5) + 1 Learning DVD. [Amazon] | [Flipkart] If in case you submitted an entry but didn’t win the Combo set of 5 Joes 2 Pros books, you could still will  my SQL Server Wait Stats book as a consolation prize! I will pick the next 5 participants who have the highest number of friends who “liked” the Facebook page, http://facebook.com/SQLAuth. Instead of sending one copy, I will send you 2 copies so you can share one copy with a friend of yours. Well, it is important to share our learning and love with friends, isn’t it? Note: Just take a screenshot of http://facebook.com/SQLAuth using Print Screen function and send it by Nov 7th to pinal ‘at’ sqlauthority.com.. There are no special freebies to early birds so take your time and see if you can increase your friends like count by Nov 7th. Guess – What is in it? It is quite possible you are not a Facebook or Twitter user. In that case you can still win a surprise from me. You have 2 days to guess what is in this box. If you guess it correct and you are one of the first 5 persons to have the correct answer – you will get what is in this box for free. Please note that you have only 48 hours to guess. Please give me your guess by commenting to this blog post. Reference:  Pinal Dave (http://blog.SQLAuthority.com) Filed under: About Me, Pinal Dave, PostADay, Readers Contribution, Readers Question, SQL, SQL Authority, SQL Milestone, SQL Query, SQL Server, SQL Tips and Tricks, SQLAuthority News, SQLServer, T SQL, Technology

    Read the article

  • Programming logic to group a users activities like facebook. E.g. Chris is now friends with A, B and C

    - by Chris Dowdeswell
    So I am trying to develop an activity feed for my site, Basically If I UNION a bunch of activities into a feed I would end up with something like the following. Chris is now friends with Mark Chris is now friends with Dave What I want though is a neater way of grouping these similar posts so the feed doesn't give information overload... E.g. Chris is now friends with Mark, Dave and 4 Others Any ideas on how I can approach this logically? I am using Classic ASP on SQL server. Here is the UNION statement I have so far... SELECT U.UserID As UserID, L.UN As UN,Left(U.UID,13) As ProfilePic,U.Fname + ' ' + U.Sname As FullName, 'said ' + WP.Post AS Activity, WP.Ctime FROM Users AS U LEFT JOIN Logins L ON L.userID = U.UserID LEFT OUTER JOIN WallPosts AS WP ON WP.userID = U.userID WHERE WP.Ctime IS NOT NULL UNION SELECT U.UserID As UserID, L.UN As UN,Left(U.UID,13) As ProfilePic,U.Fname + ' ' + U.Sname As FullName, 'commented ' + C.Comment AS Activity, C.Ctime FROM Users AS U LEFT JOIN Logins L ON L.userID = U.UserID LEFT OUTER JOIN Comments AS C ON C.UserID = U.userID WHERE C.Ctime IS NOT NULL UNION SELECT U.UserID As UserID, L.UN As UN,Left(U.UID,13) As ProfilePic, U.Fname + ' ' + U.Sname As FullName, 'connected with <a href="/profile.asp?un='+(SELECT Logins.un FROM Logins WHERE Logins.userID = Cn.ToUserID)+'">' + (SELECT Users.Fname + ' ' + Users.Sname FROM Users WHERE userID = Cn.ToUserID) + '</a>' AS Activity, Cn.Ctime FROM Users AS U LEFT JOIN Logins L ON L.userID = U.UserID LEFT OUTER JOIN Connections AS Cn ON Cn.UserID = U.userID WHERE CN.Ctime IS NOT NULL

    Read the article

  • How do I setup a proper VPN for my friends to play LAN games AND give them internet access?

    - by Gizmo
    I'm trying to setup a VPN on my local network, but everyone who connects to me DOES have access to my laptop but not to the internet or other devices on the network. How can I properly configure my VPN on windows to work correctly (giving internet + access to all devices on my network to the remote pc)? Or is there software on windows which makes creating a VPN server easier? or maybe a VMWare image linux vpn server? I can't find any of those! My requirement is that my friends don't have to install additional software, they have to be able to connect with default windows stuff. My OS is Windows 8 Standart edition (not pro or enterprise) OEM. Most of my friends have also windows 8, some windows 7. Extra info: My device is DMZ'ed (Demilitarized Zone, [disabled NAT on my device so it's accessible on the WAN]) I can access files, websites and services on other devices on my network, and all devices can access file shares, website and all other services on my device When enabling VPN everything works except the client is unable to get internet access or access to any device on my network, client has only access to my device.

    Read the article

  • When I use facebook connect how much access do I have to the user's friends?

    - by user220755
    So, if you sign in using facebook on my website, how much access do I have to your friends? I am asking this question because I want for example to know if a user asks me a question about his/her friend, I can go through their Facebook status messages for example and tell them the answer depending on parsing information but do I have access to the user's friends information or no? (And how can I do that if it is possible in another way)

    Read the article

  • VS.NET 2010 SP1, Win 7, Parallels, and a MBP&ndash;Hell, my friends&hellip;HELL!

    - by D'Arcy Lussier
    LightSwitch Beta 2 is out. That’s how all this started. All I wanted was to install it on my MBP’s Win7 Parallels VM. But as I’m finding with running a Win7 VM on a MBP, nothing is as easy as it should be. First my MBP froze during the SP1 installation. Not my VM crashing, the entire machine freezing…no mouse, nothing. Had to do a hard reset. BLECH. Then we’re back and I try to re-install SP1 (since the first try obviously failed). I get met with a dialog asking me where silverlight_sdk.msi was. It was *nowhere*! So I hit the net and download it from Microsoft’s site. Unfortunately, it only downloads an exe and not the individual files which would include the msi. Here’s what I did: - Download the tools for Silverlight 4 (http://www.microsoft.com/downloads/en/details.aspx?FamilyID=b3deb194-ca86-4fb6-a716-b67c2604a139&displaylang=en) - Run it, but don’t hit the install or next button when the dialog comes up - Look in your file structure for a folder with a weird name…bunch of numbers and letters. This is a temp folder that the exe creates and dumps all the necessary setup files into, and clears away after its done. - Inside this folder you’ll find the silverlight_sdk.msi (hooray!). Just copy it to a different location on the C drive. You can then cancel installation. Ok, so that takes care of that…but then running the SP1 installer I get hit with *another* dialog asking for the WCF RIA Services SP1 msi. Now it looks like this MSI is part of the Silverlight Tools package because you’ll see the MSI, but the VS.NET 2010 SP1 installer will thumb its nose at this unworthy msi…for whatever reason. So instead, go here: http://www.silverlight.net/getstarted/riaservices/ …and click on the “Install WCF Ria Services Sp1…” option. This downloads the msi, which you should save to your C drive and direct the VS.NET 2010 SP1 installer to. Then, if you’ve done all that, been good all year, and not made any little children cry, you *might* just be able to install VS.NET 2010 SP1 on your Parallels VM. If you were playing that “Take a shot every time he writes VS.NET 2010 Sp1” drinking game, then you’re drunk…which is a better place to be than where I am right now: watching the installation progress bar slowly creep to completion, hoping there’s no more surprises in store. D

    Read the article

  • HP and Microsoft: That&rsquo;s What Friends Are For ?

    - by andrewbrust
    Today, HP pre-announced the second coming out for its recently acquired Palm webOS mobile operating system.  I happen to think webOS is quite good, and when the Palm Pre first came out, I thought it a worthwhile phone.  I was worried though that the platform would never attract the developer mindshare it needed to be competitive, and that turned out to be the case.  But then HP acquired Palm and announced it would be revamping the webOS offering, not only on phones, but also on tablets.  It later announced that it would also use webOS as an embedded solution on HP printers. The timing of this came shortly after HP had announced it would be producing a “Slate” product running Windows 7. After the Palm deal, HP became vague about whether the Windows-powered slate would actually come out.  They did, in fact, bring the Slate 500 to market, but by some accounts, they only built 5000 units. Another recent awkward moment between HP and Microsoft: HP withdrew itself from the Windows Home Server ecosystem.  That one hurt, as they were the dominant OEM there.  But Microsoft’s decision to kill Drive Extender had driven away many parties, not just HP. On Wednesday, HP came out with their TouchPad, and new phone models.  Not a nice thing for Windows Phone 7, but other OEMs are taking a wait and see attitude there too, I suppose.  There was one more zinger though, and it was bigger: HP announced they’d be porting webOS to PCs. No Windows Phone 7? OK. No Windows Home Server?  Whatcha gonna do?  But no Windows 7 either?  From HP?  What comes after that, no ink and toner? Some people think Microsoft’s been around too long to be relevant.  But HP started out making oscilloscopes!  The notion that HP is too cool for Windows school is a it far-fetched.  This is the company that bought EDS. This is the company that bought Compaq.  And Compaq was the company that bought Digital Equipment Corporation.  Somehow, I don’t think the VT 220 outclasses Windows PCs. What could possibly be going on?  My sense is that HP wants to put webOS on PCs that also have Windows, and that people will buy because they have Windows.  And for every one of those sold, HP gets to count, technically speaking, another webOS unit in the install base.  webOS is really nice, as I said.  But being good isn’t good enough when you are trying to get market share.  Number of units shipped matters.  The question is whether counting PCs with webOS installed, but dormant, is helpful to HP’s cause.  Seems like a funny way to account for market share, and a strange way to treat a big partner in Redmond.

    Read the article

  • What are other ideologies to establish relationships between distinct users besides followers/following and friends?

    - by user784637
    Websites like myspace and facebook establish relationships between distinct users using the "friending" ideology, where one user sends a request to be accepted by another user in order for them to have the mutual permission to do stuff like post messages on each others walls. Less restrictive than the "friending" ideology, Twitter and instagram use the followers/following ideology where you can subscribe to the tweets or posts of another user without their permission. Less restrictive than the "followers/following" ideology, email and calling someone on the phone allows you to directly contact anyone. Are there other ideologies that have been successfully implemented either in social networking sites or other real world constructs to establish relations between users?

    Read the article

  • Help using left outer joins in SQL...

    - by Waffles
    I'm trying to create a list of people, their friends, and their friends of friends. My table of people is this: People: NAME Jow Smith Sandy Phil Friends LIKER LIKEE jow smith smith jow sandy phil Now, what I want is a table like this: User Friend FriendofFriend Jow smith jow Smith jow smith sandy phil phil I'm trying to create a table using the following: SELECT P.NAME, F.LIKEE, F2.LIKEE FROM PEOPLE P LEFT OUTER JOIN FRIENDS F ON P.NAME = F.LIKER LEFT OUTER JOIN FRIENDS F2 ON F.LIKEE = F2.LIKER But the above isn't working. How can I get a table of people and their friends, regardless of whether or not they actually HAVE any friends?

    Read the article

  • want to fetch the friends list of facebook thorough fbconnect in iphone using objective-c ?

    - by uttam
    how to fetch the friends list of facebook in iphone through fbconnect in objective-c? I am using this code (void)getUserName { NSString *fql = [NSString localizedStringWithFormat: @"SELECT uid FROM user WHERE is_app_user = 1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = %lld)",[FBSession session].uid]; NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@"query"]; [[FBRequest requestWithDelegate:self] call:@"facebook.friends.get" params:params]; } - (void)request:(FBRequest*)request didLoad:(id)result { if ([request.method isEqualToString:@"facebook.fql.query"]) { NSArray* users = result; NSDictionary* user = [users objectAtIndex:0]; NSString* name = [user objectForKey:@"name"]; _label.text = [NSString stringWithFormat:@"Logged in as %@", name]; } else if ([request.method isEqualToString:@"facebook.users.setStatus"]) { NSString* success = result; if ([success isEqualToString:@"1"]) { _label.text = [NSString stringWithFormat:@"Status successfully set"]; } else { _label.text = [NSString stringWithFormat:@"Problem setting status"]; } } else if ([request.method isEqualToString:@"facebook.freinds.get"]) { if(myList==nil) { NSArray* users = result; myList =[[NSArray alloc] initWithArray: users]; for(NSInteger i=0;i<[users count];i++) { NSDictionary* user = [users objectAtIndex:i]; NSString* uid = [user objectForKey:@"uid"]; NSString* fql = [NSString stringWithFormat: @"select name from user where uid == %@", uid]; NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@"query"]; [[FBRequest requestWithDelegate:self] call:@"facebook.fql.query" params:params]; } } else { NSArray* users = result; NSDictionary* user = [users objectAtIndex:0]; NSString* name = [user objectForKey:@"name"]; //txtView.text=[NSString localizedStringWithFormat:@"%@%@,\n",txtView.text,name]; NSLog(name); }} I want to get the friends list from facebook and then search/modify then add it to my addressbook. I know this code is doing this but I don't know how to use it or where do I use it.. If you could please post something or just elaborate on how do I use your code thru fbconnect framework. I have implemented upto get permissions and publish feeds one's wall. But please can you post here about the layout details of the results, like what do Ineed to use on the layout point of view.

    Read the article

  • Location tagging facebook open graph actions so that only friends in that location view in their feeds

    - by Arvind Srinivasan
    Is there a way to tag open graph actions so as to target certain recipients and not others? For example, if my app talks about new coffee shop openings in various cities, is there a way to publish the 'opening' action to the graph, perhaps with location / coordinates, such that this is only seen by friends in that locality? I really don't want to spam my friends in London about an opening I'm excited about in Portland. How can I help facebook with the feed relevance in these cases? I noticed that there is a "place" property on open graph objects - could this somehow be used?

    Read the article

  • is there something analogous to Connect.registerUsers in the Graph API

    - by timpone
    I am trying to figure this out. Basically, I'd like to reconcile my local emails with a users list of friends. I can see after OAuth token is established that I can get a list of users friends via http://graph.facebook.com/me/friends Would the solution be to keep track of a list of users friends over time and then reconcile with our local ids (in other words, i can know my id) and then use the friends API call to see if your friends are the same in local db?

    Read the article

  • Why getting active record error when trying to work on arrays?

    - by keruilin
    I have the following association in my User model: has_and_belongs_to_many :friends, :class_name => 'User', :foreign_key => 'friend_id' I have the following uniqueness constraint in my user_users table: UNIQUE KEY `no_duplicate_friends` (`user_id`,`friend_id`) In my code, I am retrieving a user's friends -- friends = user.friends. friends is an array. I have a scenario where I want add the user with all those friends to the friends array. Ex: friends << user_with_all_those_homies However, I get the following error: ActiveRecord::StatementInvalid: Mysql::Error: Duplicate entry '18-18' for key 'no_duplicate_friends': INSERT INTO `users_users` (`friend_id`, `user_id`) VALUES (18, 18) What gives?

    Read the article

  • Help needed to construct a SQL query

    - by song202y
    Need your help to get the list of suggested friends (who aren't friends of the current user but are friends of 2 or more of the current user's friends). The primary ordering should put people at the same school at the top, and the secondary ordering should put people with more common friends (that is, the number of people who are friends of that person and the current user) near the top. Users: user_id PK, user_name Profiles: user_id PK, school_name, ... Friendships: id PK, user_id FK, friend_id FK Thank you in advance. Joe

    Read the article

  • How can i get my delete messages function just appear for the user's own messages left on their friends page?

    - by Hannah_B
    I had been working on this trying the delete message button to work on my own profile page of my site. When I delete a message left by a friend it not only deletes it from the screen but deletes it from the database. The messages in the database have 4 fields: message_id, from, to and message. Here is my profile view that shows how Im deleting messages from my friends: if(!empty($messages)){ foreach($messages as $message): $delete = $message['message_id']; //var_dump($message); ?> <li><?=$message['from']?> says...: "<?=$message['message']?>"(<?=anchor("home/deleteMsg/$delete", 'delete')?>)</li> //this is where the delete button appears beside messages left <?php endforeach?> <?php }else{ ?> <?php echo 'No messages left yet !!!'; }?> Here is my controller showing the deleteMsg function called: function deleteMsg($messageid) { $this->messages->deleteMsg($messageid); redirect('home'); } Here is the messages model showing the deleteMsg model itself: function deleteMsg($message_id) { $this->db->where(array('message_id' => $message_id)); $this->db->delete('messages'); } Here is my friendprofile view where I want to implement the delete message command just so the button appears for messages Ive left and I can delete them. The delete button will not appear beside other friends comments on this page: <li><?=$message['from']?> says...: "<?=$message['message']?>"</li> Now I've tried creating a new delete Message function to no success so far, am I better off doing this than calling the same function? As this didnt work either.

    Read the article

  • How should I define my Java Objects?

    - by HonorGod
    I have a data grid where I sort of show the following information - All Guests Total Adults = 22 Total Children = 27 Confirmed Total Adults = 9 Total Children = 13 Country = Germany Total Adults = 5 Total Childres = 6 Friends Adults = 2 Children = 2 Relatives Adults = 3 Children = 4 Country = USA Total Adults = 4 Total Childres = 7 Friends Adults = 2 Children = 5 Relatives Adults = 2 Children = 2 Tentative Total Adults = 13 Total Children - 14 Country = Australia Total Adults = 7 Total Childres = 8 Friends Adults = 2 Children = 3 Relatives Adults = 5 Children = 5 Country = China Total Adults = 6 Total Childres = 6 Friends Adults = 2 Children = 4 Relatives Adults = 4 Children = 2 And in the database what I have is data at the lowest level which is Friends / Relatives and the corresponding countries set as a look-up value which in indirectly connected to another look-up that can tell me if they fall under confirmed or tentative. I guess my question is how do I layout my Java Object and perform the aggregations and give it back to the client. I am not sure if I am clear with my question, but feel free to comment so I can update the question accordingly.

    Read the article

  • Leveraging Social Networks for Retail

    - by David Dorf
    For retailers, social media is all about B2C2C. That is, Business to Consumer to Consumer, or more specifically, retailer to influencer to consumer. Traditional marketing targeted mass media, trying to expose the message to as many people as possible. While effective, this approach has never been very efficient, with high costs for relatively low penetration. Then it was thought that marketers should focus their efforts on a relative few super-influencers that would then sway the masses. History shows a few successes with this approach but lacked any consistency or predictability. After all, if super-influencers were easy to find, most campaigns would easily go viral. Alas, research shows that most wide-spread trends were the result of several fortunate events, including some luck. So do people exert influence over each other when it comes to purchase decisions? Of course they do, all the time. But that influence is usually limited to a small set of friends and specific specialization. For instance, although I have 165 friends on Facebook, I am only able to influence my close friends and family on PC purchases, and I have no sway at all for fashion purchases. People trust my knowledge on technology, but nobody asks my advice on shoes. How then should retailers leverage social networks in order to reinforce brand image and push promotions? Two obvious ways are Like and Share. Online advertisements or wall-postings receive more clicks when the viewer sees that friends have "liked" the posting. That's our modern-day version of word-of-mouth advertising. Statistics show that endorsements from friends make it more likely a person will engage. If my friends and I liked it, then I might also "share" (or "retweet" in the case of Twitter) it with other friends. In that case the retailer has paid for X showings of the advertisement, but sharing has pushed it to an additional Y people at no cost. And further, the implicit endorsement by the sharer makes it more likely the recipient will engage. So a good first step is to find people active in social networks that will Like and Share in order to exert influence. Its still tough to go viral, but doubling engagement is still a big step in the right direction. More complex social graph analysis would be a second step, but I'll leave that topic for another day. If you're interested in the academic side of social dynamics, I suggest reading Duncan Watts' work.

    Read the article

  • PHP classes totally forgotten something today - sorry

    - by russp
    Hi guys, really sorry about being "totally thick today" but I have forgotten how to do something simple - too much time not in php recently. Want to use the OS phpapi How do I print out the individual rows - see told you I was being thick today // The fields we will be fetching. if (isset($_GET['test']) && $_GET['test'] == 'plaxo') { // plaxo is a PortableContacts end-point so doesn't know about the OpenSocial specific fields $profile_fields = array(); } else { $profile_fields = array( 'aboutMe', 'displayName', 'bodyType', 'currentLocation', 'drinker', 'happiestWhen', 'lookingFor' ); } // The number of friends to fetch. $friend_count = 2; $batch = $osapi->newBatch(); // Fetch the current user. $self_request_params = array( 'userId' => $userId, // Person we are fetching. 'groupId' => '@self', // @self for one person. 'fields' => $profile_fields // Which profile fields to request. ); $batch->add($osapi->people->get($self_request_params), 'self'); // Fetch the friends of the user $friends_request_params = array( 'userId' => $userId, // Person whose friends we are fetching. 'groupId' => '@friends', // @friends for the Friends group. 'fields' => $profile_fields, // Which profile fields to request. 'count' => $friend_count // Max friends to fetch. ); $batch->add($osapi->people->get($friends_request_params), 'friends'); // Get supportedFields Request $batch->add($osapi->people->getSupportedFields(), 'supportedFields'); // Send the batch request. $result = $batch->execute(); Say I wanted to print out "aboutMe", whats the echo? cos echo $result['aboutMe'] doesn't work.

    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

  • Problems using an id from a model inside a custom sql query in Rails

    - by Thiago
    Hi there, I want to do a model class which associates to itself on Rails. Basically, a user has friends, which are also users. I typed the following inside a User model class: has_many :friends, :class_name => "User", :foreign_key => :user_id, :finder_sql => %{SELECT users.* FROM users INNER JOIN friends ON (users.id = friends.user_id OR users.id = friends.friend_id) WHERE users.id <> #{id}} But the funny fact is that it seems that this finder_sql is called twice whenever I type User.first.friends on irb. Why?

    Read the article

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