Search Results

Search found 1816 results on 73 pages for 'equals'.

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

  • Equality between two enumerables

    - by Berryl
    I have two enumerables with the exact same reference elements, and wondering why Equals wouldn't be true. As a side question, the code below to compare each element works, but there must be a more elegant way Cheers, Berryl var other = (ActivityService) obj; if (!AllAccounts.Count().Equals(other.AllAccounts.Count())) return false; for (int i = 0; i < AllAccounts.Count(); i++) { if (!AllAccounts.ElementAt(i).Equals(other.AllAccounts.ElementAt(i))) { return false; } } return true;

    Read the article

  • Java Array Comparison

    - by BlairHippo
    Working within Java, let's say I have two objects that, thanks to obj.getClass().isArray(), I know are both arrays. Let's further say that I want to compare those two arrays to each other -- possibly by using Arrays.equals. Is there a graceful way to do this without resorting to a big exhaustive if/else tree to figure out which flavor of Arrays.equals needs to be used? I'm looking for something that's less of an eyesore than this: if (obj1 instanceof byte[] && obj2 instanceof byte[]) { return Arrays.equals((byte[])obj1, (byte[])obj2); } else if (obj1 instanceof boolean[] && obj2 instanceof boolean[]) { ...

    Read the article

  • How to perform a many-to-many Linq query with Include in the EF.

    - by despart
    Hi, I don't know how to perform this query using Linq and the EF. Imagine I have three tables A, B and C. A and B have a many-to-many relationship. B and C have a 1-to-many relationship. I want to obtain records from B including C but filtering from A's Id. I can get easily the records from B: var b = Context.A.Where(x => x.Id.Equals(aId)).SelectMany(x => x.B); but when I try to include C I don't know how to do it: //This doesn't work var b = Context.A.Where(x => x.Id.Equals(aId)).SelectMany(x => x.B.Include("C")); Also I've tried this with no luck (it is equivalent to the above): //Not working var b = (from a in Context.A.Where(x => x.Id.Equals(aId)) from b in a.B.Include("C") select b); Thanks for your help.

    Read the article

  • Gracefully avoiding NullPointerException in Java

    - by Yuval A
    Consider this line: if (object.getAttribute("someAttr").equals("true")) { // .... Obviously this line is a potential bug, the attribute might be null and we will get a NullPointerException. So we need to refactor it to one of two choices: First option: if ("true".equals(object.getAttribute("someAttr"))) { // .... Second option: String attr = object.getAttribute("someAttr"); if (attr != null) { if (attr.equals("true")) { // .... The first option is awkward to read but more concise, while the second one is clear in intent, but verbose. Which option do you prefer in terms of readability?

    Read the article

  • Need help with developing a class for my JUnit test

    - by alpdog14
    I have this JUnit test that I need help developing a Interface and Class for, here is the test: Box b1 = new DefaultBox( "abc" ); Box b2 = new DefaultBox( "def" ); Box b3 = new DefaultBox( "" ); assertEquals("abc", b1.contents()); assertEquals("[abc]", b1.toString()); assertTrue(b1.equals(b1)); assertFalse(b1.equals(b2)); assertFalse(b1.equals(null)); assertEquals("cba", b1.flip().contents()); assertEquals("", b3.flip().contents()); can anyone help me in developing a Default box class and a box interface to make these test pass? Any help would be most appreciated.

    Read the article

  • Adding a Third Table to a Two-Table Join Query

    - by John
    Hello, The query below works just fine. It pulls fields from two MySQL tables, "comment" and "login". It does this for rows where "username" in the table "login" equals the variable "$profile." It also pulls fields for rows where "loginid" in the table "comment" equals the "loginid" that is also being pulled from "login." I would like to pull data from a third table called "submission," which has the following fields: submissionid loginid title url displayurl datesubmitted I would like to pull fields from rows in "submission" where "loginid" equals the "loginid" that is already being pulled from the other two tables, "login" and "comment." How can I do this? Thanks in advance, John Query: $sqlStrc = "SELECT l.username, l.loginid, c.loginid, c.commentid, c.submissionid, c.comment, c.datecommented FROM comment AS c INNER JOIN login AS l ON c.loginid = l.loginid WHERE l.username = '$profile' ORDER BY c.datecommented DESC LIMIT 10";

    Read the article

  • Unable to type cast <AnonymousType#1> to <WindowsFormsApplication1.Attributes> [ C#3.0 ]

    - by Newbie
    I have List<Attributes> la = new List<Attributes>(); la = (from t in result let t1 = t.AttributeCollection from t2 in t1 where t2.AttributeCode.Equals(attributeType) let t3 = t2.TimeSeriesData from k in t3.ToList() where k.Key.Equals(startDate) && k.Key.Equals(endDate) select new { AttributeCode = attributeType, TimeSeriesData = fn(k.Key, k.Value.ToString()) }).ToList<Attributes>(); I am getting the error: 'System.Collections.Generic.IEnumerable<AnonymousType#1>' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList<TSource>(System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments I understood tye error meaning but how to type cast it. I have used var and then iterating over it got the result. But without that any other way by which I can do it? Using C# 3.0 Thanks

    Read the article

  • Default Values Specflow Step Definitions

    - by Gavin Osborn
    I'm starting out in the world of SpecFlow and I have come across my first problem. In terms of keeping my code DRY I'd like to do the following: Have two scenarios: Given I am on a product page And myfield equals todays date Then... Given I am on a product page And myfield equals todays date plus 4 days Then... I was hoping to use the following Step Definition to cover both variants of my And clause: [Given(@"myfield equals todays date(?: (plus|minus) (\d+) days)?")] public void MyfieldEqualsTodaysDate(string direction, int? days) { //do stuff } However I keep getting exceptions when SpecFlow tries to parse the int? param. I've checked the regular expression and it definitely parses the scenario as expected. I'm aware that I could so something as crude as method overloading etc, I was just wondering if SpecFlow supported the idea of default parameter values, or indeed another way to achieve the same effect. Many Thanks

    Read the article

  • I can't Distinct, Sum, or Count from 3 tables with group clauses

    - by Rio Inggit Dharmawangsa
    I'm still learning linq, now i'm getting confused. I need data for report from 3 tables, I get the result, but it's duplicate. I have used distinct but it's not working, n I need data to be sum still not working. Here is my query, can somebody explain what's wrong? var report= (from u in myDb.TBL_TRANSAKSI_MKN_MNMs.AsEnumerable() where u.TGL_TRANSAKSI.Value.Date.Equals(dateTimePicker1.Value.Date) join l in myDb.TBL_DETAIL_TRANSAKSIs.AsEnumerable() on u.ID_NOTA equals l.ID_NOTA join m in myDb.TBL_MKN_MNMs.AsEnumerable() on l.ID_MKN_MNM equals m.ID_MKN_MNM group new { u, l, m } by new { m.NAMA_MKN_MNM, m.HARGA_JUAL, u.TGL_TRANSAKSI, l.ID_MKN_MNM, u.USERNAME, l.Jumlah } into grp select new { MakanMinum = grp.Key.NAMA_MKN_MNM, HargaJual = grp.Key.HARGA_JUAL, Stok = grp.Sum(groupedthing => groupedthing.l.Jumlah), Tanggal = grp.Key.TGL_TRANSAKSI, Jumlah =(grp.Key.HARGA_JUAL * grp.Sum(groupedthing => groupedthing.l.Jumlah)), Total = grp.Sum(grouptotal => grp.Key.HARGA_JUAL * grp.Sum(groupedthing => groupedthing.l.Jumlah)), Username = grp.Key.USERNAME }).Distinct();

    Read the article

  • Linq to SQL - How to compare against a collection in the where clause?

    - by Sgraffite
    I'd like to compare against an IEnumerable collection in my where clause. Do I need to manually loop through the collection to pull out the column I want to compare against, or is there a generic way to handle this? I want something like this: public IEnumerable<Cookie> GetCookiesForUsers(IEnumerable<User> Users) { var cookies = from c in db.Cookies join uc in db.UserCookies on c.CookieID equals uc.CookieID join u in db.Users on uc.UserID equals u.UserID where u.UserID.Equals(Users.UserID) select c; return cookies.ToList(); } I'm used to using the lambda Linq to SQL syntax, but I decided to try the SQLesque syntax since I was using joins this time. What is a good way to do this?

    Read the article

  • Initializing a value through a Session variable

    - by William Calleja
    I need to Initialize a value in a Javascript by using a c# literal that makes reference to a Session Variable. I am using the following code <script type="text/javascript" language="javascript" > var myIndex = <%= !((Session["myIndex"]).Equals(null)||(Session["myIndex"]).Equals("")) ? Session["backgroundIndex"] : "1" %>; However the code above is giving me a classic Object reference not set to an instance of an object. error. Why? Shouldn't (Session["myIndex"]).Equals(null) capture this particular error?

    Read the article

  • Is it possible to pass arithmetic operators to a method in java?

    - by drJames
    Right now I'm going to have to write a method that looks like this: public String Calculate(String Operator, Double Operand1, Double Operand2) { if (Operator.equals("+")) { return String.valueOf(Operand1 + Operand2); } else if (Operator.equals("-")) { return String.valueOf(Operand1 - Operand2); } else if (Operator.equals("*")) { return String.valueOf(Operand1 * Operand2); } else { return "error..."; } } It would be nice if I could write the code more like this: public String Calculate(String Operator, Double Operand1, Double Operand2) { return String.valueOf(Operand1 Operator Operand2); } So Operator would replace the Arithmetic Operators (+, -, *, /...) Does anyone know if something like this is possible in java?

    Read the article

  • anonymous type and multiple properties

    - by ognjenb
    I have this error: An anonymous type cannot have multiple properties with the same name. Whether this can be resolved with alias ie, whether an alias exists in LINQ var device_query = from d in DevicesEntities.device join dt in DevicesEntities.devicetype on d.DeviceTypeId equals dt.Id join l in DevicesEntities.location on d.Id equals l.DeviceId join loc in DevicesEntities.locationname on l.LocationNameId equals loc.Id where l.DeviceId == d.Id select new { d.Id, d.DeviceTypeId, d.SerialNumber, d.FirmwareRev, d.ProductionDate, d.ReparationDate, d.DateOfLastCalibration, d.DateOfLastCalibrationCheck, d.CalCertificateFile, d.Notes, d.TestReportFile, d.WarrantyFile, d.CertificateOfOriginFile, d.QCPermissionFile, d.Reserved, d.ReservedFor, d.Weight, d.Price, d.SoftwareVersion, dt.Name, dt.ArticleNumber, dt.Type, l.StartDate, //AS LastStartDate, l.LocationNameId, loc.Name //in this line I have problem };

    Read the article

  • Is it possible to pass arithmatic operators to a method in java?

    - by user349611
    Right now I'm going to have to write a method that looks like this: public String Calculate(String Operator, Double Operand1, Double Operand2) { if (Operator.equals("+")) { return String.valueOf(Operand1 + Operand2); } else if (Operator.equals("-")) { return String.valueOf(Operand1 - Operand2); } else if (Operator.equals("*")) { return String.valueOf(Operand1 * Operand2); } else { return "error..."; } } It would be nice if I could write the code more like this: public String Calculate(String Operator, Double Operand1, Double Operand2) { return String.valueOf(Operand1 Operator Operand2); } So Operator would replace the Arithmetic Operators (+, -, *, /...) Does anyone know if something like this is possible in java?

    Read the article

  • How to edit item in a listbox shown from reading a .csv file?

    - by Shuvo
    I am working in a project where my application can open a .csv file and read data from it. The .csv file contains the latitude, longitude of places. The application reads data from the file shows it in a static map and display icon on the right places. The application can open multiple file at a time and it opens with a new tab every time. But I am having trouble in couple of cases When I am trying to add a new point to the .csv file opened. I am able to write new point on the same file instead adding a new point data to the existing its replacing others and writing the new point only. I cannot use selectedIndexChange event to perform edit option on the listbox and then save the file. Any direction would be great. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace CourseworkExample { public partial class Form1 : Form { public GPSDataPoint gpsdp; List<GPSDataPoint> data; List<PictureBox> pictures; List<TabPage> tabs; public static int pn = 0; private TabPage currentComponent; private Bitmap bmp1; string[] symbols = { "hospital", "university" }; Image[] symbolImages; ListBox lb = new ListBox(); string name = ""; string path = ""; public Form1() { InitializeComponent(); data = new List<GPSDataPoint>(); pictures = new List<PictureBox>(); tabs = new List<TabPage>(); symbolImages = new Image[symbols.Length]; for (int i = 0; i < 2; i++) { string location = "data/" + symbols[i] + ".png"; symbolImages[i] = Image.FromFile(location); } } private void openToolStripMenuItem_Click(object sender, EventArgs e) { FileDialog ofd = new OpenFileDialog(); string filter = "CSV File (*.csv)|*.csv"; ofd.Filter = filter; DialogResult dr = ofd.ShowDialog(); if (dr.Equals(DialogResult.OK)) { int i = ofd.FileName.LastIndexOf("\\"); name = ofd.FileName; path = ofd.FileName; if (i > 0) { name = ofd.FileName.Substring(i + 1); path = ofd.FileName.Substring(0, i + 1); } TextReader input = new StreamReader(ofd.FileName); string mapName = input.ReadLine(); GPSDataPoint gpsD = new GPSDataPoint(); gpsD.setBounds(input.ReadLine()); string s; while ((s = input.ReadLine()) != null) { gpsD.addWaypoint(s); } input.Close(); TabPage tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; lb.Width = 300; int selectedindex = lb.SelectedIndex; lb.Items.Add(mapName); lb.Items.Add("Bounds"); lb.Items.Add(gpsD.Bounds[0] + " " + gpsD.Bounds[1] + " " + gpsD.Bounds[2] + " " + gpsD.Bounds[3]); lb.Items.Add("Waypoint"); foreach (WayPoint wp in gpsD.DataList) { lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); } tabPage.Controls.Add(lb); pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = name; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); tabControl1.Controls.Add(tabPage); tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = mapName; string location = path + mapName; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); PictureBox pb = new PictureBox(); pb.Name = "pictureBox" + pn; pb.Image = Image.FromFile(location); tabControl2.Controls.Add(tabPage); pb.Width = pb.Image.Width; pb.Height = pb.Image.Height; tabPage.Controls.Add(pb); currentComponent = tabPage; tabPage.Width = pb.Width; tabPage.Height = pb.Height; pn++; tabControl2.Width = pb.Width; tabControl2.Height = pb.Height; bmp1 = (Bitmap)pb.Image; int lx, ly; float realWidth = gpsD.Bounds[1] - gpsD.Bounds[3]; float imageW = pb.Image.Width; float dx = imageW * (gpsD.Bounds[1] - gpsD.getWayPoint(0).Longitude) / realWidth; float realHeight = gpsD.Bounds[0] - gpsD.Bounds[2]; float imageH = pb.Image.Height; float dy = imageH * (gpsD.Bounds[0] - gpsD.getWayPoint(0).Latitude) / realHeight; lx = (int)dx; ly = (int)dy; using (Graphics g = Graphics.FromImage(bmp1)) { Rectangle rect = new Rectangle(lx, ly, 20, 20); if (gpsD.getWayPoint(0).Sym.Equals("")) { g.DrawRectangle(new Pen(Color.Red), rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("hospital")) { g.DrawImage(symbolImages[0], rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("university")) { g.DrawImage(symbolImages[1], rect); } } } } pb.Image = bmp1; pb.Invalidate(); } } private void openToolStripMenuItem_Click_1(object sender, EventArgs e) { FileDialog ofd = new OpenFileDialog(); string filter = "CSV File (*.csv)|*.csv"; ofd.Filter = filter; DialogResult dr = ofd.ShowDialog(); if (dr.Equals(DialogResult.OK)) { int i = ofd.FileName.LastIndexOf("\\"); name = ofd.FileName; path = ofd.FileName; if (i > 0) { name = ofd.FileName.Substring(i + 1); path = ofd.FileName.Substring(0, i + 1); } TextReader input = new StreamReader(ofd.FileName); string mapName = input.ReadLine(); GPSDataPoint gpsD = new GPSDataPoint(); gpsD.setBounds(input.ReadLine()); string s; while ((s = input.ReadLine()) != null) { gpsD.addWaypoint(s); } input.Close(); TabPage tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; ListBox lb = new ListBox(); lb.Width = 300; lb.Items.Add(mapName); lb.Items.Add("Bounds"); lb.Items.Add(gpsD.Bounds[0] + " " + gpsD.Bounds[1] + " " + gpsD.Bounds[2] + " " + gpsD.Bounds[3]); lb.Items.Add("Waypoint"); foreach (WayPoint wp in gpsD.DataList) { lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); } tabPage.Controls.Add(lb); pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = name; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); tabControl1.Controls.Add(tabPage); tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = mapName; string location = path + mapName; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); PictureBox pb = new PictureBox(); pb.Name = "pictureBox" + pn; pb.Image = Image.FromFile(location); tabControl2.Controls.Add(tabPage); pb.Width = pb.Image.Width; pb.Height = pb.Image.Height; tabPage.Controls.Add(pb); currentComponent = tabPage; tabPage.Width = pb.Width; tabPage.Height = pb.Height; pn++; tabControl2.Width = pb.Width; tabControl2.Height = pb.Height; bmp1 = (Bitmap)pb.Image; int lx, ly; float realWidth = gpsD.Bounds[1] - gpsD.Bounds[3]; float imageW = pb.Image.Width; float dx = imageW * (gpsD.Bounds[1] - gpsD.getWayPoint(0).Longitude) / realWidth; float realHeight = gpsD.Bounds[0] - gpsD.Bounds[2]; float imageH = pb.Image.Height; float dy = imageH * (gpsD.Bounds[0] - gpsD.getWayPoint(0).Latitude) / realHeight; lx = (int)dx; ly = (int)dy; using (Graphics g = Graphics.FromImage(bmp1)) { Rectangle rect = new Rectangle(lx, ly, 20, 20); if (gpsD.getWayPoint(0).Sym.Equals("")) { g.DrawRectangle(new Pen(Color.Red), rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("hospital")) { g.DrawImage(symbolImages[0], rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("university")) { g.DrawImage(symbolImages[1], rect); } } } } pb.Image = bmp1; pb.Invalidate(); MessageBox.Show(data.ToString()); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void addBtn_Click(object sender, EventArgs e) { string wayName = nameTxtBox.Text; float wayLat = Convert.ToSingle(latTxtBox.Text); float wayLong = Convert.ToSingle(longTxtBox.Text); float wayEle = Convert.ToSingle(elevTxtBox.Text); WayPoint wp = new WayPoint(wayName, wayLat, wayLong, wayEle); GPSDataPoint gdp = new GPSDataPoint(); data = new List<GPSDataPoint>(); gdp.Add(wp); lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); lb.Refresh(); StreamWriter sr = new StreamWriter(name); sr.Write(lb); sr.Close(); DialogResult result = MessageBox.Show("Save in New File?","Save", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.FileName = "default.csv"; DialogResult saveResult = saveDialog.ShowDialog(); if (saveResult == DialogResult.OK) { sr = new StreamWriter(saveDialog.FileName, true); sr.WriteLine(wayName + "," + wayLat + "," + wayLong + "," + wayEle); sr.Close(); } } else { // sr = new StreamWriter(name, true); // sr.WriteLine(wayName + "," + wayLat + "," + wayLong + "," + wayEle); sr.Close(); } MessageBox.Show(name + path); } } } GPSDataPoint.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace CourseworkExample { public class GPSDataPoint { private float[] bounds; private List<WayPoint> dataList; public GPSDataPoint() { dataList = new List<WayPoint>(); } internal void setBounds(string p) { string[] b = p.Split(','); bounds = new float[b.Length]; for (int i = 0; i < b.Length; i++) { bounds[i] = Convert.ToSingle(b[i]); } } public float[] Bounds { get { return bounds; } } internal void addWaypoint(string s) { WayPoint wp = new WayPoint(s); dataList.Add(wp); } public WayPoint getWayPoint(int i) { if (i < dataList.Count) { return dataList[i]; } else return null; } public List<WayPoint> DataList { get { return dataList; } } internal void Add(WayPoint wp) { dataList.Add(wp); } } } WayPoint.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CourseworkExample { public class WayPoint { private string name; private float ele; private float latitude; private float longitude; private string sym; public WayPoint(string name, float latitude, float longitude, float elevation) { this.name = name; this.latitude = latitude; this.longitude = longitude; this.ele = elevation; } public WayPoint() { name = "no name"; ele = 3.5F; latitude = 3.5F; longitude = 0.0F; sym = "no symbol"; } public WayPoint(string s) { string[] bits = s.Split(','); name = bits[0]; longitude = Convert.ToSingle(bits[2]); latitude = Convert.ToSingle(bits[1]); if (bits.Length > 4) sym = bits[4]; else sym = ""; try { ele = Convert.ToSingle(bits[3]); } catch (Exception e) { ele = 0.0f; } } public float Longitude { get { return longitude; } set { longitude = value; } } public float Latitude { get { return latitude; } set { latitude = value; } } public float Ele { get { return ele; } set { ele = value; } } public string Name { get { return name; } set { name = value; } } public string Sym { get { return sym; } set { sym = value; } } } } .csv file data birthplace.png 51.483788,-0.351906,51.460745,-0.302982 Born Here,51.473805,-0.32532,-,hospital Danced here,51,483805,-0.32532,-,hospital

    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

  • Working with Joins in LINQ

    - by vik20000in
    While working with data most of the time we have to work with relation between different lists of data. Many a times we want to fetch data from both the list at once. This requires us to make different kind of joins between the lists of data. LINQ support different kinds of join Inner Join     List<Customer> customers = GetCustomerList();     List<Supplier> suppliers = GetSupplierList();      var custSupJoin =         from sup in suppliers         join cust in customers on sup.Country equals cust.Country         select new { Country = sup.Country, SupplierName = sup.SupplierName, CustomerName = cust.CompanyName }; Group Join – where By the joined dataset is also grouped.     List<Customer> customers = GetCustomerList();     List<Supplier> suppliers = GetSupplierList();      var custSupQuery =         from sup in suppliers         join cust in customers on sup.Country equals cust.Country into cs         select new { Key = sup.Country, Items = cs }; We can also work with the Left outer join in LINQ like this.     List<Customer> customers = GetCustomerList();     List<Supplier> suppliers = GetSupplierList();      var supplierCusts =         from sup in suppliers         join cust in customers on sup.Country equals cust.Country into cs         from c in cs.DefaultIfEmpty()  // DefaultIfEmpty preserves left-hand elements that have no matches on the right side         orderby sup.SupplierName         select new { Country = sup.Country, CompanyName = c == null ? "(No customers)" : c.CompanyName,                      SupplierName = sup.SupplierName};Vikram

    Read the article

  • Team Foundation Server 2012 Build Global List Problems

    - by Bob Hardister
    My experience with the upgrade and use of TFS 2012 has been very positive. I did come across a couple of issues recently that tripped things up for a while. ISSUE 1 The first issue is that 2012 prior to Update 1 published an invalid build list item value to the collection global list. In 2010, the build global list, list item value syntax is an underscore between the build definition and the build number. In the 2012 RTM this underscore was replaced with a backslash, which is invalid.  Specifically, an upload of the global list fails when the backslash is followed at some point by a period. The error when using the API is: <detail ExceptionMessage="TF26204: The account you entered is not recognized. Contact your Team Foundation Server administrator to add your account." BaseExceptionName="Microsoft.TeamFoundation.WorkItemTracking.Server.ValidationException"><details id="600019" http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/faultdetail/03"http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/faultdetail/03" /></detail> when uploading the global list via the process editor the error is: This issue is corrected in Update1 as the backslash is changed to a forward slash. ISSUE 2 The second issue is that when upgrading from 2010 to 2012, the builds in 2010 are not published to the 2012 global list.  After the upgrade the 2012 global lists doesn’t have any builds and only builds run in 2012 are published to the global list. This was reported to the MSDN forums and Connect. To correct this I wrote a utility to pull all the builds and recreate the builds global list for each project in each collection.  This is a console application with a program.cs, a globallists.cs and a app.config (not published here). The utility connects to TFS 2012, loops through the collections or a target collection as specified in the app.config. Then loops through the projects, the build definitions, and builds.  It creates a global list for each project if that project has at least one build. Then it imports the new list to TFS.  Here’s the code for program and globalists classes. Program.CS using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.TeamFoundation.Framework.Client; using Microsoft.TeamFoundation.Framework.Common; using Microsoft.TeamFoundation.Client; using Microsoft.TeamFoundation.Server; using System.IO; using System.Xml; using Microsoft.TeamFoundation.WorkItemTracking.Client; using System.Diagnostics; using Utilities; using System.Configuration; namespace TFSProjectUpdater_CLC { class Program { static void Main(string[] args) { DateTime temp_d = System.DateTime.Now; string logName = temp_d.ToShortDateString(); logName = logName.Replace("/", "_"); logName = logName + "_" + temp_d.TimeOfDay; logName = logName.Replace(":", "."); logName = "TFSGlobalListBuildsUpdater_" + logName + ".log"; Trace.Listeners.Add(new TextWriterTraceListener(Path.Combine(ConfigurationManager.AppSettings["logLocation"], logName))); Trace.AutoFlush = true; Trace.WriteLine("Start:" + DateTime.Now.ToString()); Console.WriteLine("Start:" + DateTime.Now.ToString()); string tfsServer = ConfigurationManager.AppSettings["TargetTFS"].ToString(); GlobalLists gl = new GlobalLists(); //replace this with the URL to your TFS instance. Uri tfsUri = new Uri("https://" + tfsServer + "/tfs"); //bool foundLite = false; TfsConfigurationServer config = new TfsConfigurationServer(tfsUri, new UICredentialsProvider()); config.EnsureAuthenticated(); ITeamProjectCollectionService collectionService = config.GetService<ITeamProjectCollectionService>(); IList<TeamProjectCollection> collections = collectionService.GetCollections().OrderBy(collection => collection.Name.ToString()).ToList(); //target Collection string targetCollection = ConfigurationManager.AppSettings["targetCollection"]; foreach (TeamProjectCollection coll in collections) { if (targetCollection.Equals(string.Empty)) { if (!coll.Name.Equals("TFS Archive") && !coll.Name.Equals("DefaultCol") && !coll.Name.Equals("Team Project Template Gallery")) { doWork(coll, tfsServer); } } else { if (coll.Name.Equals(targetCollection)) { doWork(coll, tfsServer); } } } Trace.WriteLine("Finished:" + DateTime.Now.ToString()); Console.WriteLine("Finished:" + DateTime.Now.ToString()); if (System.Diagnostics.Debugger.IsAttached) { Console.WriteLine("\nHit any key to exit..."); Console.ReadKey(); } Trace.Close(); } static void doWork(TeamProjectCollection coll, string tfsServer) { GlobalLists gl = new GlobalLists(); //target Collection string targetProject = ConfigurationManager.AppSettings["targetProject"]; Trace.WriteLine("Collection: " + coll.Name); Uri u = new Uri("https://" + tfsServer + "/tfs/" + coll.Name.ToString()); TfsTeamProjectCollection c = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(u); ICommonStructureService icss = c.GetService<ICommonStructureService>(); try { Trace.WriteLine("\tChecking Collection Global Lists."); gl.RebuildBuildGlobalLists(c); } catch (Exception ex) { Console.WriteLine("Exception! :" + coll.Name); } } } } GlobalLists.CS using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.TeamFoundation.Client; using Microsoft.TeamFoundation.Framework.Client; using Microsoft.TeamFoundation.Framework.Common; using Microsoft.TeamFoundation.Server; using Microsoft.TeamFoundation.WorkItemTracking.Client; using Microsoft.TeamFoundation.Build.Client; using System.Configuration; using System.Xml; using System.Xml.Linq; using System.Diagnostics; namespace Utilities { public class GlobalLists { string GL_NewList = @"<gl:GLOBALLISTS xmlns:gl=""http://schemas.microsoft.com/VisualStudio/2005/workitemtracking/globallists""> <GLOBALLIST> </GLOBALLIST> </gl:GLOBALLISTS>"; public void RebuildBuildGlobalLists(TfsTeamProjectCollection _tfs) { WorkItemStore wis = new WorkItemStore(_tfs); //export the current globals lists file for the collection to save as a backup XmlDocument globalListsFile = wis.ExportGlobalLists(); globalListsFile.Save(@"c:\temp\" + _tfs.Name.Replace("\\", "_") + "_backupGlobalList.xml"); LogExportCurrentCollectionGlobalListsAsBackup(_tfs); //Build a new global build list from each build definition within each team project IBuildServer buildServer = _tfs.GetService<IBuildServer>(); foreach (Project p in wis.Projects) { XmlDocument newProjectGlobalList = new XmlDocument(); newProjectGlobalList.LoadXml(GL_NewList); LogInstanciateNewProjectBuildGlobalList(_tfs, p); BuildNewProjectBuildGlobalList(_tfs, wis, newProjectGlobalList, buildServer, p); LogEndOfProject(_tfs, p); } } // Private Methods private static void BuildNewProjectBuildGlobalList(TfsTeamProjectCollection _tfs, WorkItemStore wis, XmlDocument newProjectGlobalList, IBuildServer buildServer, Project p) { //locate the template node XmlNamespaceManager nsmgr = new XmlNamespaceManager(newProjectGlobalList.NameTable); nsmgr.AddNamespace("gl", "http://schemas.microsoft.com/VisualStudio/2005/workitemtracking/globallists"); XmlNode node = newProjectGlobalList.SelectSingleNode("//gl:GLOBALLISTS/GLOBALLIST", nsmgr); LogLocatedGlobalListNode(_tfs, p); //add the name attribute for the project build global list XmlElement buildListNode = (XmlElement)node; buildListNode.SetAttribute("name", "Builds - " + p.Name); LogAddedBuildNodeName(_tfs, p); //add new builds to the team project build global list bool buildsExist = false; if (AddNewBuilds(_tfs, newProjectGlobalList, buildServer, p, node, buildsExist)) { //import the new build global list for each project that has builds newProjectGlobalList.Save(@"c:\temp\" + _tfs.Name.Replace("\\", "_") + "_" + p.Name + "_" + "newGlobalList.xml"); //write out temp copy of the global list file to be imported LogImportReady(_tfs, p); wis.ImportGlobalLists(newProjectGlobalList.InnerXml); LogImportComplete(_tfs, p); } } private static bool AddNewBuilds(TfsTeamProjectCollection _tfs, XmlDocument newProjectGlobalList, IBuildServer buildServer, Project p, XmlNode node, bool buildsExist) { var buildDefinitions = buildServer.QueryBuildDefinitions(p.Name); foreach (var buildDefinition in buildDefinitions) { var builds = buildDefinition.QueryBuilds(); foreach (var build in builds) { //insert the builds into the current build list node in the correct 2012 format buildsExist = true; XmlElement listItem = newProjectGlobalList.CreateElement("LISTITEM"); listItem.SetAttribute("value", buildDefinition.Name + "/" + build.BuildNumber.ToString().Replace(buildDefinition.Name + "_", "")); node.AppendChild(listItem); } } if (buildsExist) LogBuildListCreated(_tfs, p); else LogNoBuildsInProject(_tfs, p); return buildsExist; } // Logging Methods private static void LogExportCurrentCollectionGlobalListsAsBackup(TfsTeamProjectCollection _tfs) { Trace.WriteLine("\tExported Global List for " + _tfs.Name + " collection."); Console.WriteLine("\tExported Global List for " + _tfs.Name + " collection."); } private void LogInstanciateNewProjectBuildGlobalList(TfsTeamProjectCollection _tfs, Project p) { Trace.WriteLine("\t\tInstanciated the new build global list for project " + p.Name + " in the " + _tfs.Name + " collection."); Console.WriteLine("\t\tInstanciated the new build global list for project \n\t\t\t" + p.Name + " in the \n\t\t\t" + _tfs.Name + " collection."); } private static void LogLocatedGlobalListNode(TfsTeamProjectCollection _tfs, Project p) { Trace.WriteLine("\t\tLocated the build global list node for project " + p.Name + " in the " + _tfs.Name + " collection."); Console.WriteLine("\t\tLocated the build global list node for project \n\t\t\t" + p.Name + " in the \n\t\t\t" + _tfs.Name + " collection."); } private static void LogAddedBuildNodeName(TfsTeamProjectCollection _tfs, Project p) { Trace.WriteLine("\t\tAdded the name attribute to the build global list for project " + p.Name + " in the " + _tfs.Name + " collection."); Console.WriteLine("\t\tAdded the name attribute to the build global list for project \n\t\t\t" + p.Name + " in the \n\t\t\t" + _tfs.Name + " collection."); } private static void LogBuildListCreated(TfsTeamProjectCollection _tfs, Project p) { Trace.WriteLine("\t\tAdded all builds into the " + "Builds - " + p.Name + " list in the " + _tfs.Name + " collection."); Console.WriteLine("\t\tAdded all builds into the " + "Builds - \n\t\t\t" + p.Name + " list in the \n\t\t\t" + _tfs.Name + " collection."); } private static void LogNoBuildsInProject(TfsTeamProjectCollection _tfs, Project p) { Trace.WriteLine("\t\tNo builds found for project " + p.Name + " in the " + _tfs.Name + " collection."); Console.WriteLine("\t\tNo builds found for project " + p.Name + " \n\t\t\tin the " + _tfs.Name + " collection."); } private void LogEndOfProject(TfsTeamProjectCollection _tfs, Project p) { Trace.WriteLine("\t\tEND OF PROJECT " + p.Name); Trace.WriteLine(" "); Console.WriteLine("\t\tEND OF PROJECT " + p.Name); Console.WriteLine(); } private static void LogImportReady(TfsTeamProjectCollection _tfs, Project p) { Trace.WriteLine("\t\tReady to import the build global list for project " + p.Name + " to the " + _tfs.Name + " collection."); Console.WriteLine("\t\tReady to import the build global list for project \n\t\t\t" + p.Name + " to the \n\t\t\t" + _tfs.Name + " collection."); } private static void LogImportComplete(TfsTeamProjectCollection _tfs, Project p) { Trace.WriteLine("\t\tImport of the build global list for project " + p.Name + " to the " + _tfs.Name + " collection completed."); Console.WriteLine("\t\tImport of the build global list for project \n\t\t\t" + p.Name + " to the \n\t\t\t" + _tfs.Name + " collection completed."); } } }

    Read the article

  • LINQ: Enhancing Distinct With The SelectorEqualityComparer

    - by Paulo Morgado
    On my last post, I introduced the PredicateEqualityComparer and a Distinct extension method that receives a predicate to internally create a PredicateEqualityComparer to filter elements. Using the predicate, greatly improves readability, conciseness and expressiveness of the queries, but it can be even better. Most of the times, we don’t want to provide a comparison method but just to extract the comaprison key for the elements. So, I developed a SelectorEqualityComparer that takes a method that extracts the key value for each element. Something like this: public class SelectorEqualityComparer<TSource, Tkey> : EqualityComparer<TSource> where Tkey : IEquatable<Tkey> { private Func<TSource, Tkey> selector; public SelectorEqualityComparer(Func<TSource, Tkey> selector) : base() { this.selector = selector; } public override bool Equals(TSource x, TSource y) { Tkey xKey = this.GetKey(x); Tkey yKey = this.GetKey(y); if (xKey != null) { return ((yKey != null) && xKey.Equals(yKey)); } return (yKey == null); } public override int GetHashCode(TSource obj) { Tkey key = this.GetKey(obj); return (key == null) ? 0 : key.GetHashCode(); } public override bool Equals(object obj) { SelectorEqualityComparer<TSource, Tkey> comparer = obj as SelectorEqualityComparer<TSource, Tkey>; return (comparer != null); } public override int GetHashCode() { return base.GetType().Name.GetHashCode(); } private Tkey GetKey(TSource obj) { return (obj == null) ? (Tkey)(object)null : this.selector(obj); } } Now I can write code like this: .Distinct(new SelectorEqualityComparer<Source, Key>(x => x.Field)) And, for improved readability, conciseness and expressiveness and support for anonymous types the corresponding Distinct extension method: public static IEnumerable<TSource> Distinct<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IEquatable<TKey> { return source.Distinct(new SelectorEqualityComparer<TSource, TKey>(selector)); } And the query is now written like this: .Distinct(x => x.Field) For most usages, it’s simpler than using a predicate.

    Read the article

  • Gradle for NetBeans RCP

    - by Geertjan
    Start with the NetBeans Paint Application and do the following to build it via Gradle (i.e., no Gradle/NetBeans plugin is needed for the following steps), assuming you've set up Gradle. Do everything below in the Files or Favorites window, not in the Projects window. In the application directory "Paint Application". Create a file named "settings.gradle", with this content: include 'ColorChooser', 'Paint' Create another file in the same location, named "build.gradle", with this content: subprojects { apply plugin: "announce" apply plugin: "java" sourceSets { main { java { srcDir 'src' } resources { srcDir 'src' } } } } In the module directory "Paint". Create a file named "build.gradle", with this content: dependencies { compile fileTree("$rootDir/build/public-package-jars").matching { include '**/*.jar' } } task show << { configurations.compile.each { dep -> println "$dep ${dep.isFile()}" } } Note: The above is a temporary solution, as you can see, the expectation is that the JARs are in the 'build/public-packages-jars' folder, which assumes an Ant build has been done prior to the Gradle build. Now run 'gradle classes' in the "Paint Application" folder and everything will compile correctly. So, this is how the Paint Application now looks: Preferable to the second 'build.gradle' would be this, which uses the JARs found in the NetBeans Platform... netbeansHome = '/home/geertjan/netbeans-dev-201111110600' dependencies { compile files("$rootDir/ColorChooser/release/modules/ext/ColorChooser.jar") def projectXml = new XmlParser().parse("nbproject/project.xml") projectXml.configuration.data."module-dependencies".dependency."code-name-base".each { if (it.text().equals('org.openide.filesystems')) { def dep = "$netbeansHome/platform/core/"+it.text().replace('.','-')+'.jar' compile files(dep) } else if (it.text().equals('org.openide.util.lookup') || it.text().equals('org.openide.util')) { def dep = "$netbeansHome/platform/lib/"+it.text().replace('.','-')+'.jar' compile files(dep) } else { def dep = "$netbeansHome/platform/modules/"+it.text().replace('.','-')+'.jar' compile files(dep) } } } task show << { configurations.compile.each { dep -> println "$dep ${dep.isFile()}" } } However, when you run 'gradle classes' with the above, you get an error like this: geertjan@geertjan:~/NetBeansProjects/PaintApp1/Paint$ gradle classes :Paint:compileJava [ant:javac] Note: Attempting to workaround javac bug #6512707 [ant:javac] [ant:javac] [ant:javac] An annotation processor threw an uncaught exception. [ant:javac] Consult the following stack trace for details. [ant:javac] java.lang.NullPointerException [ant:javac] at com.sun.tools.javac.util.DefaultFileManager.getFileForOutput(DefaultFileManager.java:1058) No idea why the above happens, still trying to figure it out. Once the above works, we can start figuring out how to use the NetBeans Maven repo instead and then the user of the plugin will be able to select whether to use local JARs or JARs from the NetBeans Maven repo. Many thanks to Hans Dockter who put the above together with me today, via Skype!

    Read the article

  • What are the best patterns/designs for stateful API development?

    - by Svante
    I am about to implement a API for my TCP/IP server written in Java. Right now I have a temporary method that takes a String, executes a command based on the String and returns a String basically like the following. public void communicate(BufferedReader in, PrintWriter out) { while(true) { out.println(handleCommand(in.readLine())); } } private String handleCommand(String command) { if (command.equals("command1") { // do stuff return "Command 1 executed"; } else if (command.equals("command2") { // do some other stuff return "Command 2 executed"; } } I really want to do something more extensible, smarter and stateful, so I could handle more complex and stateful commands and without the method/class getting bloated. How would you start? Suggestions, ideas, or links for further reading are very welcome.

    Read the article

  • Using mocks to set up object even if you will not be mocking any behavior or verifying any interaction with it?

    - by smp7d
    When building a unit test, is it appropriate to use a mocking tool to assist you in setting up an object even if you will not be mocking any behavior or verifying any interaction with that object? Here is a simple example in pseudo-code: //an object we actually want to mock Object someMockedObject = Mock(Object.class); EqualityChecker checker = new EqualityChecker(someMockedObject); //an object we are mocking only to avoid figuring out how to instantiate or //tying ourselves to some constructor that may be removed in the future ComplicatedObject someObjectThatIsHardToInstantiate = Mock(ComplicatedObject.class); //set the expectation on the mock When(someMockedObject).equals(someObjectThatIsHardToInstantiate).return(false); Assert(equalityChecker.check(someObjectThatIsHardToInstantiate)).isFalse(); //verify that the mock was interacted with properly Verify(someMockedObject).equals(someObjectThatIsHardToInstantiate).oneTime(); Is it appropriate to mock ComplicatedObject in this scenario?

    Read the article

  • Generic IEqualityComparer

    - by Nettuce
    A generic equality comparer that takes a property expression or a comparison Func public class GenericComparer<T> : IEqualityComparer<T> where T : class         {             private readonly Func<T, T, bool> comparerExpression;             private readonly string propertyName;             public GenericComparer(Func<T, T, bool> comparerExpression)             {                 this.comparerExpression = comparerExpression;             }             public GenericComparer(Expression<Func<T, object>> propertyExpression)             {                 propertyName = (propertyExpression.Body is UnaryExpression ? (MemberExpression)((UnaryExpression)propertyExpression.Body).Operand : (MemberExpression)propertyExpression.Body).Member.Name;             }             public bool Equals(T x, T y)             {                 return comparerExpression == null ? x.GetType().GetProperty(propertyName).GetValue(x, null).Equals(y.GetType().GetProperty(propertyName).GetValue(y, null)) : comparerExpression.Invoke(x, y);             }             public int GetHashCode(T obj)             {                 return obj.ToString().GetHashCode();             }         }

    Read the article

  • How to refresh a GridView?

    - by Daniel
    Hello everyone, I have a GridView which is pretty similar to the Google tutorial, except that I want to add the ImageViews on runtime (via a subactivity). The results are okay, but the layout of the View is messed up: The GridView doesn't fill the content of its parent, what do I have to do to design it properly? Here the code of adding the children: public void initializeWorkbench(GridView gv, Vector<String> items) { Prototype.workbench.setDimension(screenWidth, divider.height()+workbenchArea.height()); Prototype.workbench.activateWorkbench(); // this measures the workbench correctly Log.d(Prototype.TAG, "workbench width: "+Prototype.workbench.getMeasuredWidth()); // 320 Log.d(Prototype.TAG, "workbench height: "+Prototype.workbench.getMeasuredHeight()); // 30 ImageAdapter imgAdapter = new ImageAdapter(this.getContext(), items); gv.setAdapter(imgAdapter); gv.measure(screenWidth, screenHeight); gv.requestLayout(); gv.forceLayout(); Log.d(Prototype.TAG, "gv width: "+gv.getMeasuredWidth()); // 22 Log.d(Prototype.TAG, "gv height: "+gv.getMeasuredHeight()); // 119 Prototype.workbench.setDimension(screenWidth, divider.height()+workbenchArea.height()); } } activateWorkbench, setDimension and measure in the workbench (LinearLayout above the GridView): public void activateWorkbench() { if(this.equals(Prototype.workbench)) { this.setOrientation(VERTICAL); show = true; measure(); } } public void setDimension(int w, int h) { width = w; height = h; this.setLayoutParams(new LinearLayout.LayoutParams(width, height)); this.invalidate(); } private void measure() { if (this.getOrientation() == LinearLayout.VERTICAL) { int h = 0; int w = 0; this.measureChildren(0, 0); for (int i = 0; i < this.getChildCount(); i++) { View v = this.getChildAt(i); h += v.getMeasuredHeight(); w = (w < v.getMeasuredWidth()) ? v.getMeasuredWidth() : w; } if (this.equals(Prototype.tagarea)) height = (h < height) ? height : h; if (this.equals(Prototype.tagarea)) width = (w < width) ? width : w; } this.setMeasuredDimension(width, height); } The ImageAdapter constructor: public ImageAdapter(Context c, Vector<String> items) { mContext = c; boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but // all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; } if (mExternalStorageAvailable && mExternalStorageWriteable) { for (String item : items) { File f = new File(item); if (f.exists()) { try { FileInputStream fis = new FileInputStream(f); Bitmap b = BitmapFactory.decodeStream(fis); bitmaps.add(b); files.add(f); } catch (FileNotFoundException e) { Log.e(Prototype.TAG, "", e); } } } } } And the xml layout: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:gravity="bottom" android:paddingLeft="0px" android:paddingTop="0px" android:paddingRight="0px"> <com.unimelb.pt3.ui.TransparentPanel android:id="@+id/workbench" android:layout_width="fill_parent" android:layout_height="10px" android:paddingTop="0px" android:paddingLeft="0px" android:paddingBottom="0px" android:paddingRight="0px"> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="90dp" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center" /> </com.unimelb.pt3.ui.TransparentPanel> </LinearLayout>

    Read the article

  • Any way to turn off quips in OOWeb?

    - by Misha Koshelev
    http://ooweb.sourceforge.net/tutorial.html Not really a question, but I can't seem to stop writing stuff like this. Maybe someone will find it useful. I know rewriting an HTTP server is not the way to turn off the quips ;) /* Copyright 2010 Misha Koshelev. All Rights Reserved. */ package com.mksoft.common; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.net.ServerSocket; import java.net.Socket; /** * Simple HTTP Server. * * @author Misha Koshelev */ public class HttpServer extends Thread { /* * Constants */ /** * 404 Not Found Result */ protected final static String result404NotFound="<html><head><title>404 Not Found</title></head><body bgcolor='#ffffff'><h1>404 Not Found</h1></body></html>"; /* * Variables */ /** * Port on which HTTP server handles requests. */ protected int port; public int getPort() { return port; } public void setPort(int _port) { port=_port; } /* * Constructors */ public HttpServer(int _port) { setPort(_port); } /* * Helpers */ /** * Errors */ protected void error(String message) { System.err.println(message); System.err.flush(); } /** * Debugging */ protected boolean debugOutput=true; protected void debug(String message) { if (debugOutput) { error(message); } } /** * Lock object */ private Object lock=new Object(); /** * Should we quit? */ protected boolean doQuit=false; /** * Are we done? */ protected boolean areWeDone=false; /** * Process POST request headers */ protected String processPostRequest(String url,LinkedHashMap<String,String> headers,String inputLine) { debug("HttpServer.processPostRequest: url=\""+url); if (debugOutput) { for (String key: headers.keySet()) { debug("HttpServer.processPostRequest: headers."+key+"=\""+headers.get(key)+"\""); } } debug("HttpServer.processPostRequest: inputLine=\""+inputLine+"\""); try { inputLine=new URLDecoder().decode(inputLine,"UTF-8"); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); } String[] keyValues=inputLine.split("&"); LinkedHashMap<String,String> post=new LinkedHashMap<String,String>(); for (int i=0;i<keyValues.length;i++) { String keyValue=keyValues[i]; int equals=keyValue.indexOf('='); String key=keyValue.substring(0,equals); String value=keyValue.substring(equals+1); post.put(key,value); } return post(url,headers,post); } /** * Server loop (here for exception handling purposes) */ protected void serverLoop() throws IOException { /* Start server socket */ ServerSocket serverSocket=null; try { serverSocket=new ServerSocket(getPort()); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); } Socket clientSocket=null; while (true) { /* Quit if necessary */ if (doQuit) { break; } /* Accept incoming connections */ try { clientSocket=serverSocket.accept(); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); } /* Read request */ BufferedReader in=null; String inputLine=null; String firstLine=null; String blankLine=null; LinkedHashMap<String,String> headers=new LinkedHashMap<String,String>(); try { in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); while (true) { if (blankLine==null) { inputLine=in.readLine(); } else { /* POST request, read Content-length bytes */ int contentLength=new Integer(headers.get("Content-Length")).intValue(); StringBuilder sb=new StringBuilder(contentLength); for (int i=0;i<contentLength;i++) { sb.append((char)in.read()); } inputLine=sb.toString(); break; } if (firstLine==null) { firstLine=inputLine; } else if (blankLine==null) { if (inputLine.equals("")) { if (firstLine.startsWith("GET ")) { break; } blankLine=inputLine; } else { int colon=inputLine.indexOf(": "); String key=inputLine.substring(0,colon); String value=inputLine.substring(colon+2); headers.put(key,value); } } } } catch (IOException ioe) { ioe.printStackTrace(); } /* Process request */ String result=null; firstLine=firstLine.replaceAll(" HTTP/.*",""); if (firstLine.startsWith("GET ")) { result=get(firstLine.replaceFirst("GET ",""),headers); } else if (firstLine.startsWith("POST ")) { result=processPostRequest(firstLine.replaceFirst("POST ",""),headers,inputLine); } else { error("HttpServer.ServerLoop: Unhandled request \""+firstLine+"\""); } debug("HttpServer.ServerLoop: result=\""+result+"\""); /* Send response */ PrintWriter out=null; try { out=new PrintWriter(clientSocket.getOutputStream(),true); } catch (IOException ioe) { ioe.printStackTrace(); } if (result!=null) { out.println("HTTP/1.1 200 OK"); } else { out.println("HTTP/1.0 404 Not Found"); result=result404NotFound; } Date now=new Date(); out.println("Date: "+new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(now)); out.println("Content-Type: text/html; charset=UTF-8"); out.println("Content-Length: "+result.length()); out.println(""); out.print(result); /* Clean up */ out.close(); if (in!=null) { in.close(); } clientSocket.close(); } serverSocket.close(); areWeDone=true; synchronized(lock) { lock.notifyAll(); } } /* * Methods */ /** * Run server on port specified in constructor. */ public void run() { try { serverLoop(); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); } } /** * Process GET request (should be overwritten). */ public String get(String url,LinkedHashMap<String,String> headers) { debug("HttpServer.get: url=\""+url+"\""); if (debugOutput) { for (String key: headers.keySet()) { debug("HttpServer.get: headers."+key+"=\""+headers.get(key)+"\""); } } if (url.equals("/")) { return "<html><head><title>HttpServer GET Test Page</title></head>\r\n"+ "<body bgcolor='#ffffff'>\r\n"+ "<center><h1>HttpServer GET Test Page</h1></center>\r\n"+ "<hr />\r\n"+ "<center><table>\r\n"+ "<form method='post' action='/'>\r\n"+ "<tr><td align=right>Test 1:</td>\r\n"+ " <td><input type='text' name='text 1' value='test me !!! !@#$'></td></tr>\r\n"+ "<tr><td align=right>Test 2:</td>\r\n"+ " <td><input type='text' name='text 2' value='type smthng'></td></tr>\r\n"+ "<tr><td>&nbsp;</td>\r\n"+ " <td align=right><input type='submit' value='Submit'></td></tr>\r\n"+ "</form>\r\n"+ "</table></center>\r\n"+ "<hr />\r\n"+ "<center><a href='/quit'>Shutdown Server</a></center>\r\n"+ "</html>"; } else if (url.equals("/quit")) { quit(); return ""; } else { return null; } } /** * Process POST request (should be overwritten). */ public String post(String url,LinkedHashMap<String,String> headers,LinkedHashMap<String,String> post) { debug("HttpServer.post: url=\""+url+"\""); if (debugOutput) { for (String key: headers.keySet()) { debug("HttpServer.post: headers."+key+"=\""+headers.get(key)+"\""); } } if (url.equals("/")) { String result="<html><head><title>HttpServer Post Test Page</title></head>\r\n"+ "<body bgcolor='#ffffff'>\r\n"+ "<center><h1>HttpServer Post Test Page</h1></center>\r\n"+ "<hr />\r\n"+ "<center><table>\r\n"+ "<tr><th>Key</th><th>Value</th></tr>\r\n"; for (String key: post.keySet()) { result+="<tr><td align=right>"+key+"</td><td align=left>"+post.get(key)+"</td></tr>\r\n"; } result+="</table></center>\r\n"+ "</html>"; return result; } else { return null; } } /** * Wait for server to quit. */ public void waitForCompletion() { while (areWeDone==false) { synchronized(lock) { try { lock.wait(); } catch (InterruptedException ie) { } } } } /** * Shutdown server. */ public void quit() { doQuit=true; } }

    Read the article

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