Search Results

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

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

  • Joins in LINQ to SQL

    - by rajbk
    The following post shows how to write different types of joins in LINQ to SQL. I am using the Northwind database and LINQ to SQL for these examples. NorthwindDataContext dataContext = new NorthwindDataContext(); Inner Join var q1 = from c in dataContext.Customers join o in dataContext.Orders on c.CustomerID equals o.CustomerID select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]FROM [dbo].[Customers] AS [t0]INNER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID] Left Join var q2 = from c in dataContext.Customers join o in dataContext.Orders on c.CustomerID equals o.CustomerID into g from a in g.DefaultIfEmpty() select new { c.CustomerID, c.ContactName, a.OrderID, a.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID] AS [OrderID], [t1].[OrderDate] AS [OrderDate]FROM [dbo].[Customers] AS [t0]LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID] Inner Join on multiple //We mark our anonymous type properties as a and b otherwise//we get the compiler error "Type inferencce failed in the call to 'Join’var q3 = from c in dataContext.Customers join o in dataContext.Orders on new { a = c.CustomerID, b = c.Country } equals new { a = o.CustomerID, b = "USA" } select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]FROM [dbo].[Customers] AS [t0]INNER JOIN [dbo].[Orders] AS [t1] ON ([t0].[CustomerID] = [t1].[CustomerID]) AND ([t0].[Country] = @p0) Inner Join on multiple with ‘OR’ clause var q4 = from c in dataContext.Customers from o in dataContext.Orders.Where(a => a.CustomerID == c.CustomerID || c.Country == "USA") select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]FROM [dbo].[Customers] AS [t0], [dbo].[Orders] AS [t1]WHERE ([t1].[CustomerID] = [t0].[CustomerID]) OR ([t0].[Country] = @p0) Left Join on multiple with ‘OR’ clause var q5 = from c in dataContext.Customers from o in dataContext.Orders.Where(a => a.CustomerID == c.CustomerID || c.Country == "USA").DefaultIfEmpty() select new { c.CustomerID, c.ContactName, o.OrderID, o.OrderDate }; SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID] AS [OrderID], [t1].[OrderDate] AS [OrderDate]FROM [dbo].[Customers] AS [t0]LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON ([t1].[CustomerID] = [t0].[CustomerID]) OR ([t0].[Country] = @p0)

    Read the article

  • XMLPad – a new tool in my developer utility belt

    - by jamiet
    Yesterday I was on the lookout for a free tool that would help me write XPath statements. I put a shout out on Twitter and Johan Barnard replied saying : Give XMLPad a try http://www.wmhelp.com/xmlpad3.htm I’m sure there are legions of developers out there that know all about XMLPad but I had never heard about it so I suspect some of you reading haven’t either. Today I downloaded it to give it a run out and I gotta say – I love it. I only used it to do one thing –constructing an XPath expression to point to a particular Configuration definition in a .dtsx file- and it allowed me to do that with consummate ease. The feature I particularly loved was that, similar to Google Suggest, it showed me results from my expression as I typed. Here is a screenshot of my XPath expression to find (and just try saying this in a hurry) the value of a property whose DTS:Name attribute equals ‘ConfigurationString’ of a Configuration definition where the value of that Configuration definition’s property whose DTS:Name attribute equals ‘ObjectName’, equals ‘BIConfig My XPath expression: /DTS:Executable/DTS:Configuration[DTS:Property[@DTS:Name=’ObjectName’]=’BIConfig’]/DTS:Property[@DTS:Name=’ConfigurationString’] and believe me, there was no way I would have been able to come up with that without a tool to help me! So, an easy tip for you – if you need to write XPath expression download XMLPad for free from http://www.wmhelp.com/xmlpad3.htm and see what it can do for you. That’s all. Its now Friday evening and I’m shutting down and relaxing before heading to the big game at Twickenham tomorrow (yes, I have a ticket ). Have a good one! @Jamiet

    Read the article

  • Strange if-else branching behavior in a fragment shader

    - by Winged
    In my fragment shader I have passed an uniform int uLightType variable, which indicates what type of light is in usage right now. The problem is that if-else branching does not work correctly - the fragment shader performs instructions in every if statement block. if (uLightType == 1) { // Spotlight light type vec3 depthTextureCoord = vDepthPosition.xyz / vDepthPosition.w; shadowDepth = unpack(texture2D(uDepthMapSampler, depthTextureCoord.xy)); } else if (uLightType == 2) { // Omni-directional light type shadowDepth = unpack(textureCube(uDepthCubemapSampler, -lightVec)); } In the case when uLightType equals 1, unless I comment out the content of the second if block, it assigns an another value to shadowDepth. Also while uLightType equals 1, when I remove the second 'if' block and change == to != like in the sample code below, nothing happens (which means that uLightType really equals 1). if (uLightType != 1) { // Spotlight light type vec3 depthTextureCoord = vDepthPosition.xyz / vDepthPosition.w; shadowDepth = unpack(texture2D(uDepthMapSampler, depthTextureCoord.xy)); } Also, when I manually create an int variable (which is not an uniform) like this: var lightType = 1; and replace uLightType with it in the if-else branch, everything works fine, so I guess it have something to do with the fact that uLightType is the uniform.

    Read the article

  • Common Substring of two strings

    - by Chander Shivdasani
    This particular interview-question stumped me: Given two Strings S1 and S2. Find the longest Substring which is a Prefix of S1 and suffix of S2. Through Google, I came across the following solution, but didnt quite understand what it was doing. public String findLongestSubstring(String s1, String s2) { List<Integer> occurs = new ArrayList<>(); for (int i = 0; i < s1.length(); i++) { if (s1.charAt(i) == s2.charAt(s2.length()-1)) { occurs.add(i); } } Collections.reverse(occurs); for(int index : occurs) { boolean equals = true; for(int i = index; i >= 0; i--) { if (s1.charAt(index-i) != s2.charAt(s2.length() - i - 1)) { equals = false; break; } } if(equals) { return s1.substring(0,index+1); } } return null; }

    Read the article

  • How to add image in ListView android

    - by Wawan Den Frastøtende
    i would like to add images on my list view, and i have this code package com.wilis.appmysql; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; //import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class menulayanan extends ListActivity { /** Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); // Create an array of Strings, that will be put to our ListActivity String[] menulayanan = new String[] { "Berita Terbaru", "Info Item", "Customer Service", "Help","Exit"}; //Menset nilai array ke dalam list adapater sehingga data pada array akan dimunculkan dalam list this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,menulayanan)); } @Override /**method ini akan mengoveride method onListItemClick yang ada pada class List Activity * method ini akan dipanggil apabilai ada salah satu item dari list menu yang dipilih */ protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // Get the item that was clicked // Menangkap nilai text yang dklik Object o = this.getListAdapter().getItem(position); String pilihan = o.toString(); // Menampilkan hasil pilihan menu dalam bentuk Toast tampilkanPilihan(pilihan); } /** * Tampilkan Activity sesuai dengan menu yang dipilih * */ protected void tampilkanPilihan(String pilihan) { try { //Intent digunakan untuk sebagai pengenal suatu activity Intent i = null; if (pilihan.equals("Berita Terbaru")) { i = new Intent(this, PraBayar.class); } else if (pilihan.equals("Info Item")) { i = new Intent(this, PascaBayar.class); } else if (pilihan.equals("Customer Service")) { i = new Intent(this, CustomerService.class); } else if (pilihan.equals("Help")) { i = new Intent(this, Help.class); } else if (pilihan.equals("Exit")) { finish(); } else { Toast.makeText(this,"Anda Memilih: " + pilihan + " , Actionnya belum dibuat", Toast.LENGTH_LONG).show(); } startActivity(i); } catch (Exception e) { e.printStackTrace(); } } } and i want to add different image per list, so i mean is i want to add a.png to "Berita Terbaru", b.png to "Info Item", c.png "Customer Service" , so how to do it? i was very confused about this, thanks before...

    Read the article

  • Trying to implement a method that can compare any two lists but it always returns false

    - by Tyler Pfaff
    Hello like the title says I'm trying to make a method that can compare any two lists for equality. I'm trying to compare them in a way that validates that every element of one list has the same value as every element of another list. My Equals method below always returns false, can anyone see why that is? Thank you! using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class IEnumerableComparer<T> : IEqualityComparer<IEnumerable<T>> { public bool Equals(IEnumerable<T> x, IEnumerable<T> y) { for(int i = 0; i<x.Count();i++){ if(!Object.Equals(x.ElementAt(i), y.ElementAt(i))){ return false; } } return true; } public int GetHashCode(IEnumerable<T> obj) { if (obj == null) return 0; return unchecked(obj.Select(e => e.GetHashCode()).Aggregate(0, (a, b) => a + b)); } } Here is my data I'm using to test this Equals method. static void Main(string[] args) { Car car1 = new Car(); car1.make = "Toyota"; car1.model = "xB"; Car car2 = new Car(); car2.make = "Toyota"; car2.model = "xB"; List<Car> l1 = new List<Car>(); List<Car> l2 = new List<Car>(); l1.Add(car1); l2.Add(car2); IEnumerableComparer<Car> seq = new IEnumerableComparer<Car>(); bool b = seq.Equals(l1, l2); Console.Write(b); //always says false Console.Read(); } } Car class class Car { public String make { get; set; } public String model { get; set; } }

    Read the article

  • arrayListOutOfBoundsException... Please Help?

    - by Jacob
    This is my class Debugger. Can anyone try and run it and see whens wrong? Ive spent hours on it already. :( public class Debugger { private String codeToDebug = ""; public Debugger(String code) { codeToDebug = code; } /** * This method itterates over a css file and adds all the properties to an arraylist */ public void searchDuplicates() { boolean isInside = false; ArrayList<String> methodStorage = new ArrayList(); int stored = 0; String[] codeArray = codeToDebug.split(""); try { int i = 0; while(i<codeArray.length) { if(codeArray[i].equals("}")) { isInside = false; } if(isInside && !codeArray[i].equals(" ")) { boolean methodFound = false; String method = ""; int c = i; while(!methodFound) { method += codeArray[c]; if(codeArray[c+1].equals(":")) { methodFound = true; } else { c++; } } methodStorage.add(stored, method); System.out.println(methodStorage.get(stored)); stored++; boolean stillInside = true; int skip = i; while(stillInside) { if(codeArray[skip].equals(";")) { stillInside = false; } else { skip++; } } i = skip; } if(codeArray[i].equals("{")) { isInside = true; } i++; } } catch(ArrayIndexOutOfBoundsException ar) { System.out.println("------- array out of bounds exception -------"); } } /** * Takes in String and outputs the number of characters it contains * @param input * @return Number of characters */ public static int countString(String input) { String[] words = input.split(""); int counter = -1; for(int i = 0; i<words.length; i++){ counter++; } return counter; } public static void main(String[] args) { Debugger h = new Debugger("body {margin:;\n}"); h.searchDuplicates(); } }

    Read the article

  • Constructors from extended class in Java

    - by Crystal
    I'm having some trouble with a hw assignment. In one assignment, we had to create a Person class. Mine was: public class Person { String firstName; String lastName; String telephone; String email; public Person() { firstName = ""; lastName = ""; telephone = ""; email = ""; } public Person(String firstName) { this.firstName = firstName; } public Person(String firstName, String lastName, String telephone, String email) { this.firstName = firstName; this.lastName = lastName; this.telephone = telephone; this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean equals(Object otherObject) { // a quick test to see if the objects are identical if (this == otherObject) { return true; } // must return false if the explicit parameter is null if (otherObject == null) { return false; } if (!(otherObject instanceof Person)) { return false; } Person other = (Person) otherObject; return firstName.equals(other.firstName) && lastName.equals(other.lastName) && telephone.equals(other.telephone) && email.equals(other.email); } public int hashCode() { return 7 * firstName.hashCode() + 11 * lastName.hashCode() + 13 * telephone.hashCode() + 15 * email.hashCode(); } public String toString() { return getClass().getName() + "[firstName = " + firstName + '\n' + "lastName = " + lastName + '\n' + "telephone = " + telephone + '\n' + "email = " + email + "]"; } } Now we have to extend that class and use that class in our constructor. The function protoype is: public CarLoan(Person client, double vehiclePrice, double downPayment, double salesTax, double interestRate, CAR_LOAN_TERMS length) I'm confused on how I use the Person constructor from the superclass. I cannot necessarily do super(client); in my constructor which is what the book did with some primitive types in their example. Not sure what the correct thing to do is... Any thoughts? Thanks!

    Read the article

  • Distinctly LINQ &ndash; Getting a Distinct List of Objects

    - by David Totzke
    Let’s say that you have a list of objects that contains duplicate items and you want to extract a subset of distinct items.  This is pretty straight forward in the trivial case where the duplicate objects are considered the same such as in the following example: List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 }; IEnumerable<int> distinctAges = ages.Distinct(); Console.WriteLine("Distinct ages:"); foreach (int age in distinctAges) { Console.WriteLine(age); } /* This code produces the following output: Distinct ages: 21 46 55 17 */ What if you are working with reference types instead?  Imagine a list of search results where items in the results, while unique in and of themselves, also point to a parent.  We’d like to be able to select a bunch of items in the list but then see only a distinct list of parents.  Distinct isn’t going to help us much on its own as all of the items are distinct already.  Perhaps we can create a class with just the information we are interested in like the Id and Name of the parents.  public class SelectedItem { public int ItemID { get; set; } public string DisplayName { get; set; } } We can then use LINQ to populate a list containing objects with just the information we are interested in and then get rid of the duplicates. IEnumerable<SelectedItem> list = (from item in ResultView.SelectedRows.OfType<Contract.ReceiptSelectResults>() select new SelectedItem { ItemID = item.ParentId, DisplayName = item.ParentName }) .Distinct(); Most of you will have guessed that this didn’t work.  Even though some of our objects are now duplicates, because we are working with reference types, it doesn’t matter that their properties are the same, they’re still considered unique.  What we need is a way to define equality for the Distinct() extension method. IEqualityComparer<T> Looking at the Distinct method we see that there is an overload that accepts an IEqualityComparer<T>.  We can simply create a class that implements this interface and that allows us to define equality for our SelectedItem class. public class SelectedItemComparer : IEqualityComparer<SelectedItem> { public new bool Equals(SelectedItem abc, SelectedItem def) { return abc.ItemID == def.ItemID && abc.DisplayName == def.DisplayName; } public int GetHashCode(SelectedItem obj) { string code = obj.DisplayName + obj.ItemID.ToString(); return code.GetHashCode(); } } In the Equals method we simply do whatever comparisons are necessary to determine equality and then return true or false.  Take note of the implementation of the GetHashCode method.  GetHashCode must return the same value for two different objects if our Equals method says they are equal.  Get this wrong and your comparer won’t work .  Even though the Equals method returns true, mismatched hash codes will cause the comparison to fail.  For our example, we simply build a string from the properties of the object and then call GetHashCode() on that. Now all we have to do is pass an instance of our IEqualitlyComarer<T> to Distinct and all will be well: IEnumerable<SelectedItem> list =     (from item in ResultView.SelectedRows.OfType<Contract.ReceiptSelectResults>()         select new SelectedItem { ItemID = item.dahfkp, DisplayName = item.document_code })                         .Distinct(new SelectedItemComparer());   Enjoy. Dave Just because I can… Technorati Tags: LINQ,C#

    Read the article

  • Deploying a SharePoint 2007 theme using Features

    - by Kelly Jones
    I recently had a requirement to update the branding on an existing Windows SharePoint Services (WSS version 3.0) site.  I needed to update the theme, along with the master page.  An additional requirement is that my client likes to have all changes bundled up in SharePoint solutions.  This makes it much easier to move code from dev to test to prod and more importantly, makes it easier to undo code migrations if any issues would arise (I agree with this approach). Updating the theme was easy enough.  I created a new theme, along with a two new features.  The first feature, scoped at the farm level, deploys the theme, adding it to the spthemes.xml file (in the 12 hive –> \Template\layouts\1033 folder).  Here’s the method that I call from the feature activated event: private static void AddThemeToSpThemes(string id, string name, string description, string thumbnail, string preview, SPFeatureReceiverProperties properties) { XmlDocument spThemes = new XmlDocument(); //use GetGenericSetupPath to find the 12 hive folder string spThemesPath = SPUtility.GetGenericSetupPath(@"TEMPLATE\LAYOUTS\1033\spThemes.xml"); //load the spthemes file into our xmldocument, since it is just xml spThemes.Load(spThemesPath); XmlNode root = spThemes.DocumentElement; //search the themes file to see if our theme is already added bool found = false; foreach (XmlNode node in root.ChildNodes) { foreach (XmlNode prop in node.ChildNodes) { if (prop.Name.Equals("TemplateID")) { if (prop.InnerText.Equals(id)) { found = true; break; } } } if (found) { break; } } if (!found) //theme not found, so add it { //This is what we need to add: // <Templates> // <TemplateID>ThemeName</TemplateID> // <DisplayName>Theme Display Name</DisplayName> // <Description>My theme description</Description> // <Thumbnail>images/mythemethumb.gif</Thumbnail> // <Preview>images/mythemepreview.gif</Preview> // </Templates> StringBuilder sb = new StringBuilder(); sb.Append("<Templates><TemplateID>"); sb.Append(id); sb.Append("</TemplateID><DisplayName>"); sb.Append(name); sb.Append("</DisplayName><Description>"); sb.Append(description); sb.Append("</Description><Thumbnail>"); sb.Append(thumbnail); sb.Append("</Thumbnail><Preview>"); sb.Append(preview); sb.Append("</Preview></Templates>"); root.CreateNavigator().AppendChild(sb.ToString()); spThemes.Save(spThemesPath); } } Just as important, is the code that removes the theme when the feature is deactivated: private static void RemoveThemeFromSpThemes(string id) { XmlDocument spThemes = new XmlDocument(); string spThemesPath = HostingEnvironment.MapPath("/_layouts/") + @"1033\spThemes.xml"; spThemes.Load(spThemesPath); XmlNode root = spThemes.DocumentElement; foreach (XmlNode node in root.ChildNodes) { foreach (XmlNode prop in node.ChildNodes) { if (prop.Name.Equals("TemplateID")) { if (prop.InnerText.Equals(id)) { root.RemoveChild(node); spThemes.Save(spThemesPath); break; } } } } } So, that takes care of deploying the theme.  In order to apply the theme to the web, my activate feature method looks like this: public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { using (SPWeb curweb = (SPWeb)properties.Feature.Parent) { curweb.ApplyTheme("myThemeName"); curweb.Update(); } } Deactivating is just as simple: public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { using (SPWeb curweb = (SPWeb)properties.Feature.Parent) { curweb.ApplyTheme("none"); curweb.Update(); } } Ok, that’s the code necessary to deploy, apply, un-apply, and retract the theme.  Also, the solution (WSP file) contains the actual theme files. SO, next is the master page, which I’ll cover in my next blog post.

    Read the article

  • NHibernate Pitfalls: Custom Types and Detecting Changes

    - by Ricardo Peres
    This is part of a series of posts about NHibernate Pitfalls. See the entire collection here. NHibernate supports the declaration of properties of user-defined types, that is, not entities, collections or primitive types. These are used for mapping a database columns, of any type, into a different type, which may not even be an entity; think, for example, of a custom user type that converts a BLOB column into an Image. User types must implement interface NHibernate.UserTypes.IUserType. This interface specifies an Equals method that is used for comparing two instances of the user type. If this method returns false, the entity is marked as dirty, and, when the session is flushed, will trigger an UPDATE. So, in your custom user type, you must implement this carefully so that it is not mistakenly considered changed. For example, you can cache the original column value inside of it, and compare it with the one in the other instance. Let’s see an example implementation of a custom user type that converts a Byte[] from a BLOB column into an Image: 1: [Serializable] 2: public sealed class ImageUserType : IUserType 3: { 4: private Byte[] data = null; 5: 6: public ImageUserType() 7: { 8: this.ImageFormat = ImageFormat.Png; 9: } 10: 11: public ImageFormat ImageFormat 12: { 13: get; 14: set; 15: } 16: 17: public Boolean IsMutable 18: { 19: get 20: { 21: return (true); 22: } 23: } 24: 25: public Object Assemble(Object cached, Object owner) 26: { 27: return (cached); 28: } 29: 30: public Object DeepCopy(Object value) 31: { 32: return (value); 33: } 34: 35: public Object Disassemble(Object value) 36: { 37: return (value); 38: } 39: 40: public new Boolean Equals(Object x, Object y) 41: { 42: return (Object.Equals(x, y)); 43: } 44: 45: public Int32 GetHashCode(Object x) 46: { 47: return ((x != null) ? x.GetHashCode() : 0); 48: } 49: 50: public override Int32 GetHashCode() 51: { 52: return ((this.data != null) ? this.data.GetHashCode() : 0); 53: } 54: 55: public override Boolean Equals(Object obj) 56: { 57: ImageUserType other = obj as ImageUserType; 58: 59: if (other == null) 60: { 61: return (false); 62: } 63: 64: if (Object.ReferenceEquals(this, other) == true) 65: { 66: return (true); 67: } 68: 69: return (this.data.SequenceEqual(other.data)); 70: } 71: 72: public Object NullSafeGet(IDataReader rs, String[] names, Object owner) 73: { 74: Int32 index = rs.GetOrdinal(names[0]); 75: Byte[] data = rs.GetValue(index) as Byte[]; 76: 77: this.data = data as Byte[]; 78: 79: if (data == null) 80: { 81: return (null); 82: } 83: 84: using (MemoryStream stream = new MemoryStream(this.data ?? new Byte[0])) 85: { 86: return (Image.FromStream(stream)); 87: } 88: } 89: 90: public void NullSafeSet(IDbCommand cmd, Object value, Int32 index) 91: { 92: if (value != null) 93: { 94: Image data = value as Image; 95: 96: using (MemoryStream stream = new MemoryStream()) 97: { 98: data.Save(stream, this.ImageFormat); 99: value = stream.ToArray(); 100: } 101: } 102: 103: (cmd.Parameters[index] as DbParameter).Value = value ?? DBNull.Value; 104: } 105: 106: public Object Replace(Object original, Object target, Object owner) 107: { 108: return (original); 109: } 110: 111: public Type ReturnedType 112: { 113: get 114: { 115: return (typeof(Image)); 116: } 117: } 118: 119: public SqlType[] SqlTypes 120: { 121: get 122: { 123: return (new SqlType[] { new SqlType(DbType.Binary) }); 124: } 125: } 126: } In this case, we need to cache the original Byte[] data because it’s not easy to compare two Image instances, unless, of course, they are the same.

    Read the article

  • Executing Stored Procedures in Visual Studio LightSwitch.

    - by dataintegration
    A LightSwitch Project is very easy way to visualize and manipulate information directly from one of our ADO.NET Providers. But when it comes to executing the Stored Procedures, it can be a bit more complicated. In this article, we will demonstrate how to execute a Stored Procedure in LightSwitch. For the purposes of this article, we will be using the RSSBus Email Data Provider, but the same process will work with any of our ADO.NET Providers. Creating the RIA Service. Step 1: Open Visual Studio and create a new WCF RIA Service Class Project. Step 2:Add the reference to the RSSBus Email Data Provider dll in the (ProjectName).Web project. Step 3: Add a new Domain Service Class to the (ProjectName).Web project. Step 4: In the new Domain Service Class, create a new class with the attributes needed for the Stored Procedure's parameters. In this demo, the Stored Procedure we are executing is called SendMessage. The parameters we will need are as follows: public class NewMessage{ [Key] public int ID { get; set; } public string FromEmail { get; set; } public string ToEmail { get; set; } public string Subject { get; set; } public string Text { get; set; } } Note: The created class must have an ID which will serve as the key value. Step 5: Create a new method that will executed when the insert event fires. Inside this method you can use the standards ADO.NET code which will execute the stored procedure. [Insert] public void SendMessage(NewMessage newMessage) { try { EmailConnection conn = new EmailConnection(connectionString); EmailCommand comm = new EmailCommand("SendMessage", conn); comm.CommandType = System.Data.CommandType.StoredProcedure; if (!newMessage.FromEmail.Equals("")) comm.Parameters.Add(new EmailParameter("@From", newMessage.FromEmail)); if (!newMessage.ToEmail.Equals("")) comm.Parameters.Add(new EmailParameter("@To", newMessage.ToEmail)); if (!newMessage.Subject.Equals("")) comm.Parameters.Add(new EmailParameter("@Subject", newMessage.Subject)); if (!newMessage.Text.Equals("")) comm.Parameters.Add(new EmailParameter("@Text", newMessage.Text)); comm.ExecuteNonQuery(); } catch (Exception exc) { Console.WriteLine(exc.Message); } } Step 6: Create a query method. We are not going to be using getNewMessages(), so it does not matter what it returns for the purpose of our example, but you will need to create a method for the query event as well. [Query(IsDefault=true)] public IEnumerable<NewMessage> getNewMessages() { return null; } Step 7: Rebuild the whole solution. Creating the LightSwitch Project. Step 8: Open Visual Studio and create a new LightSwitch Application Project. Step 9: On the Data Sources, add a new data source. Choose a WCF RIA Service Step 10: Choose to add a new reference and select the (Project Name).Web.dll generated from the RIA Service. Step 11: Select the entities you would like to import. In this case, we are using the recently created NewMessage entity. Step 13: On the Screens section, create a new screen and select the NewMessage entity as the Screen Data. Step 14: After you run the project, you will be able to add a new record and save it. This will execute the Stored Procedure and send the new message. If you create a screen to check the sent messages, you can refresh this screen to see the mail you sent. Sample Project To help you with get started using stored procedures in LightSwitch, download the fully functional sample project. You will also need the RSSBus Email Data Provider to make the connection. You can download a free trial here.

    Read the article

  • Hashtable comparator problem

    - by user288245
    Hi guys i've never written a comparator b4 and im having a real problem. I've created a hashtable. Hashtable <String, Objects> ht; Could someone show how you'd write a comparator for a Hashtable? the examples i've seen overide equals and everything but i simply dont have a clue. The code below is not mine but an example i found, the key thing in hashtables means i cant do it like this i guess. public class Comparator implements Comparable<Name> { private final String firstName, lastName; public void Name(String firstName, String lastName) { if (firstName == null || lastName == null) throw new NullPointerException(); this.firstName = firstName; this.lastName = lastName; } public String firstName() { return firstName; } public String lastName() { return lastName; } public boolean equals(Object o) { if (!(o instanceof Name)) return false; Name n = (Name)o; return n.firstName.equals(firstName) && n.lastName.equals(lastName); } public int hashCode() { return 31*firstName.hashCode() + lastName.hashCode(); } public String toString() { return firstName + " " + lastName; } public int compareTo(Name n) { int lastCmp = lastName.compareTo(n.lastName); return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName)); } }

    Read the article

  • Linq: the linked objects are null, why?

    - by user46503
    Hello, I have several linked tables (entities). I'm trying to get the entities using the following linq: ObjectQuery<Location> locations = context.Location; ObjectQuery<ProductPrice> productPrice = context.ProductPrice; ObjectQuery<Product> products = context.Product; IQueryable<ProductPrice> res1 = from pp in productPrice join loc in locations on pp.Location equals loc join prod in products on pp.Product equals prod where prod.Title.ToLower().IndexOf(Word.ToLower()) > -1 select pp; This query returns 2 records, ProductPrice objects that have linked object Location and Product but they are null and I cannot understand why. If I try to fill them in the linq as below: res = from pp in productPrice join loc in locations on pp.Location equals loc join prod in products on pp.Product equals prod where prod.Title.ToLower().IndexOf(Word.ToLower()) > -1 select new ProductPrice { ProductPriceId = pp.ProductPriceId, Product = prod }; I have the exception "The entity or complex type 'PBExplorerData.ProductPrice' cannot be constructed in a LINQ to Entities query" Could someone please explain me what happens and what I need to do? Thanks

    Read the article

  • Join + IEqualityComparer<T> and HashCode

    - by Jesus Rodriguez
    Im writing my own LINQ reference but Im getting troubles with some of the more complicated operators implementations. There is a Join implementation that takes a IEqualityComparer Im getting just crazy. Im trying to understand it first before I write (obviously) Image this two lists: List<string> initials = new List<string> {"A", "B", "C", "D", "E"}; List<string> words = new List<string> {"Ant", "Crawl", "Pig", "Boat", "Elephant", "Arc"}; Nothing weird here. I want to join both lists by the Initial, something like: Initial=A Word=Ant Initial=A Word=Arc Initial=B Word=Boat ... I need a comparator, I wrote this: public class InitialComparator : IEqualityComparer<string> { public bool Equals(string x, string y) { return x.StartsWith(y); } public int GetHashCode(string obj) { return obj[0].GetHashCode(); } } The Join itself: var blah = initials.Join(words, initial => initial, word => word, (initial, word) => new {Initial = initial, Word = word}, new InitialComparator()); It's the first time Im using HashCodes, after a good session of debugging I see that every word go to the comparator and look at its HashCode, if another word has the same HashCode it calls equals. Since I want to compare just the initial I though that I just need the first letter Hash (Am I wrong?) The thing is that this is not working correctly. Its says that "Ant" and "Arc" are equals, Ok, its comparing every word in the same list or not, But it adds only the last word it finds, in this case Arc, ignoring Ant and Ant is equals to "A" too... If I put "Ant" and "Ant" it add both. In short, What is the way of doing something like that? I know that Im doing something wrong. Thank you.

    Read the article

  • How do I write test code to exercise a C# generic Pair<TKey, TValue> ?

    - by Scott Davies
    Hi, I am reading through Jon Skeet's "C# in Depth", first edition (which is a great book). I'm in section 3.3.3, page 84, "Implementing Generics". Generics always confuse me, so I wrote some code to exercise the sample. The code provided is: using System; using System.Collections.Generic; public sealed class Pair<TFirst, TSecond> : IEquatable<Pair<TFirst, TSecond>> { private readonly TFirst first; private readonly TSecond second; public Pair(TFirst first, TSecond second) { this.first = first; this.second = second; } ...property getters... public bool Equals(Pair<TFirst, TSecond> other) { if (other == null) { return false; } return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) && EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second); } My code is: class MyClass { public static void Main (string[] args) { // Create new pair. Pair thePair = new Pair(new String("1"), new String("1")); // Compare a new pair to previous pair by generating a second pair. if (thePair.Equals(new Pair(new string("1"), new string("1")))) System.Console.WriteLine("Equal"); else System.Console.WriteLine("Not equal"); } } The compiler complains: "Using the generic type 'ManningListing36.Paie' requires 2 type argument(s) CS0305" What am I doing wrong ? Thanks, Scott

    Read the article

  • Storing a jpa entity where only the timestamp changes results in updates rather than inserts (desire

    - by David Schlenk
    I have a JPA entity that stores a fk id, a boolean and a timestamp: @Entity public class ChannelInUse implements Serializable { @Id @GeneratedValue private Long id; @ManyToOne @JoinColumn(nullable = false) private Channel channel; private boolean inUse = false; @Temporal(TemporalType.TIMESTAMP) private Date inUseAt = new Date(); ... } I want every new instance of this entity to result in a new row in the table. For whatever reason no matter what I do it always results in the row getting updated with a new timestamp value rather than creating a new row. Even tried to just use a native query to run an insert but channel's ID wasn't populated yet so I gave up on that. I've tried using an embedded id class consisting of channel.getId and inUseAt. My equals and hashcode for are: public boolean equals(Object obj){ if(this == obj) return true; if(!(obj instanceof ChannelInUse)) return false; ChannelInUse ciu = (ChannelInUse) obj; return ( (this.inUseAt == null ? ciu.inUseAt == null : this.inUseAt.equals(ciu.inUseAt)) && (this.inUse == ciu.inUse) && (this.channel == null ? ciu.channel == null : this.channel.equals(ciu.channel)) ); } /** * hashcode generated from at, channel and inUse properties. */ public int hashCode(){ int hash = 1; hash = hash * 31 + (this.inUseAt == null ? 0 : this.inUseAt.hashCode()); hash = hash * 31 + (this.channel == null ? 0 : this.channel.hashCode()); if(inUse) hash = hash * 31 + 1; else hash = hash * 31 + 0; return hash; } } I've tried using hibernate's Entity annotation with mutable=false. I'm probably just not understanding what makes an entity unique or something. Hit the google pretty hard but can't figure this one out.

    Read the article

  • Access denied to path , when uploading image to folder in server

    - by apekshabs
    Am getting error when you are going to upload the file on specified folder in the server. Here I am going to upload P6100083.jpg in storeimg folder. When I am going to upload I am getting the following error: Access to the path 'C:\inetpub\vhosts\bookmygroups.com\httpdocs\storeimg\P6100083.jpg' is denied. Can anyone help me... How to use permisiion and were to use... My code is while uploading image if (FileUpload1.HasFile) { float fileSize = FileUpload1.PostedFile.ContentLength; float floatConverttoKB = fileSize / 1024; float floatConverttoMB = floatConverttoKB / 1024; string DirName = "storeimg"; string savepath = Server.MapPath(DirName + "/"); DirectoryInfo dir = new DirectoryInfo(savepath); // string savepath = "C:\\Documents and Settings\\ssis3\\My Documents\\Visual Studio 2005\\WebSites\\finalbookgroups\\" + DirName + "\\"; if (fileSize < 4194304) { string filename = Server.HtmlEncode(FileUpload1.FileName); string extension = System.IO.Path.GetExtension(filename).ToUpper(); if (extension.Equals(".jpg") || extension.Equals(".JPG") || extension.Equals(".JPEG") || extension.Equals(".GIF")) { savepath += filename; FileUpload1.SaveAs(savepath); } } Thanks in advance

    Read the article

  • Scala always returning true....WHY?

    - by jhamm
    I am trying to learn Scala and am a newbie. I know that this is not optimal functional code and welcome any advice that anyone can give me, but I want to understand why I keep getting true for this function. def balance(chars: List[Char]): Boolean = { val newList = chars.filter(x => x.equals('(') || x.equals(')')); return countParams(newList, 0) } def countParams(xs: List[Char], y: Int): Boolean = { println(y + " right Here") if (y < 0) { println(y + " Here") return false } else { println(y + " Greater than 0") if (xs.size > 0) { println(xs.size + " this is the size") xs match { case xs if (xs.head.equals('(')) => countParams(xs.tail, y + 1) case xs if (xs.head.equals(')')) => countParams(xs.tail, y - 1) case xs => 0 } } } return true; } balance("()())))".toList) I know that I am hitting the false branch of my if statement, but it still returns true at the end of my function. Please help me understand. Thanks.

    Read the article

  • String doesn't match regex when read from keyboard.

    - by athspk
    public static void main(String[] args) throws IOException { String str1 = "??123456"; System.out.println(str1+"-"+str1.matches("^\\p{InGreek}{2}\\d{6}")); //??123456-true BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str2 = br.readLine(); //??123456 same as str1. System.out.println(str2+"-"+str2.matches("^\\p{InGreek}{2}\\d{6}")); //?”??123456-false System.out.println(str1.equals(str2)); //false } The same String doesn't match regex when read from keyboard. What causes this problem, and how can we solve this? Thanks in advance. EDIT: I used System.console() for input and output. public static void main(String[] args) throws IOException { PrintWriter pr = System.console().writer(); String str1 = "??123456"; pr.println(str1+"-"+str1.matches("^\\p{InGreek}{2}\\d{6}")+"-"+str1.length()); String str2 = System.console().readLine(); pr.println(str2+"-"+str2.matches("^\\p{InGreek}{2}\\d{6}")+"-"+str2.length()); pr.println("str1.equals(str2)="+str1.equals(str2)); } Output: ??123456-true-8 ??123456 ??123456-true-8 str1.equals(str2)=true

    Read the article

  • Translate an IQueryable instance to LINQ syntax in a string

    - by James Dunne
    I would like to find out if anyone has existing work surrounding formatting an IQueryable instance back into a LINQ C# syntax inside a string. It'd be a nice-to-have feature for an internal LINQ-to-SQL auditing framework I'm building. Once my framework gets the IQueryable instance from a data repository method, I'd like to output something like: This LINQ query: from ce in db.EiClassEnrollment join c in db.EiCourse on ce.CourseID equals c.CourseID join cl in db.EiClass on ce.ClassID equals cl.ClassID join t in db.EiTerm on ce.TermID equals t.TermID join st in db.EiStaff on cl.Instructor equals st.StaffID where (ce.StudentID == studentID) && (ce.TermID == termID) && (cl.Campus == campusID) select new { ce, cl, t, c, st }; Generates the following LINQ-to-SQL query: DECLARE @p0 int; DECLARE @p1 int; DECLARE @p2 int; SET @p0 = 777; SET @p1 = 778; SET @p2 = 779; SELECT [t0].[ClassEnrollmentID], ..., [t4].[Name] FROM [dbo].[ei_ClassEnrollment] AS [t0] INNER JOIN [dbo].[ei_Course] AS [t1] ON [t0].[CourseID] = [t1].[CourseID] INNER JOIN [dbo].[ei_Class] AS [t2] ON [t0].[ClassID] = [t2].[ClassID] INNER JOIN [dbo].[ei_Term] AS [t3] ON [t0].[TermID] = [t3].[TermID] INNER JOIN [dbo].[ei_Staff] AS [t4] ON [t2].[Instructor] = [t4].[StaffID] WHERE ([t0].[StudentID] = @p0) AND ([t0].[TermID] = @p1) AND ([t2].[Campus] = @p2) I already have the SQL output working as you can see. I just need to find a way to get the IQueryable to translate into a string representing its original LINQ syntax (with an acceptable translation loss). I'm not afraid of writing it myself, but I'd like to see if anyone else has done this first.

    Read the article

  • Question regarding filesystems true or false?

    - by Avon
    Hello all, though I'm familiar with stackoverflow , and loving it , i've actually got a couple of questions myself about something other then programming. Here are my question Is it true that in FAT filesystems the maximum number of files per filesystem equals the number of entries in the FAT table. And is it also true that in indexed filesystems the maximum number of files per filesystem equals the number of indexblocks – 1. I'm reading some stuff and am trying to get a good understanding of it.

    Read the article

  • Parsing xml files locally from assets folder using XmlPullParser

    - by Randolphg
    Im trying to parse a local xml file that I place in my assets folder. I've been trying to do this for almost a week now. Here is my test xml file Test1 Test2 Test3 Test4 Test5 I keep getting the same error: W/System.err(22458): org.xmlpull.v1.XmlPullParserException: unexpected type (position:TEXT Code: public void xmlParser() throws XmlPullParserException, IOException, ParserConfigurationException, SAXException { Log.d("tag", "xmlParsing...."); Arithmetic arthm = new Arithmetic(); XmlPullParserFactory xmlPF = XmlPullParserFactory.newInstance(); xmlPF.setValidating(false); XmlPullParser xml = xmlPF.newPullParser(); InputStream raw = getApplication().getAssets().open("menu.xml"); xml.setInput(raw, null); xml.nextTag(); Log.d("tag", "start parsing...."); String elementText = null; String elemName = null; int nofTags = 0; while (xml.getEventType() != XmlPullParser.END_DOCUMENT) { Log.d("tag", "while(xml.next)..."); switch (xml.getEventType()) { case XmlPullParser.START_DOCUMENT: Log.d("tag", "while (xml.getEventType() != XmlPullParser.END_DOCUMENT)"); break; case XmlPullParser.START_TAG: Log.d("tag", " case XmlPullParser.START_TAG"); elementText = xml.getName(); Log.d("tag", "elementText = " + elementText); if (xml.getEventType() != XmlPullParser.END_TAG) { xml.nextTag(); } break; case XmlPullParser.TEXT: Log.d("tag", "case TEXT"); if (elementText.equals("menu") && xml.isWhitespace()) { Log.d("tag", "<" + elementText + ">"); arthm.menu_name = xml.getText(); Log.d("tag", "value " + xml.getText() + " added"); } else if (elementText.equals("item")) { arthm.description = xml.getText(); Log.d("tag", "value " + xml.getText() + " added"); } else if (elementText.equals("SUBCATEGORY NAME")) { arthm.subcategoryDesc.add(xml.getText()); Log.d("tag", "value " + xml.getText() + " added"); } else if (elementText.equals("SUBCATEGORY DESC")) { arthm.subcategoryName.add(xml.getText()); Log.d("tag", "value " + xml.getText() + " added"); } break; case XmlPullParser.END_TAG: Log.d("tag", "case END_TAG"); nofTags += 1; String tags = Integer.toString(nofTags); Log.d("tags", elementText + " number of tags" + tags); if (xml.nextTag() != XmlPullParser.START_TAG) { xml.next(); } break; case XmlPullParser.END_DOCUMENT: Log.d("tag", "case END_DOCUMENT"); break; default: break; } } Log.d("tag", "Success!"); } Thanks in advance.

    Read the article

  • How does formatting works with a PowerShell function that returns a set of elements?

    - by Steve B
    If I write this small function : function Foo { Get-Process | % { $_ } } And if I run Foo It displays only a small subset of properties: PS C:\Users\Administrator> foo Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 86 10 1680 412 31 0,02 5916 alg 136 10 2772 2356 78 0,06 3684 atieclxx 123 7 1780 1040 33 0,03 668 atiesrxx ... ... But even if only 8 columns are shown, there are plenty of other properties (as foo | gm is showing). What is causing this function to show only this 8 properties? I'm actually trying to build a similar function that is returning complex objects from a 3rd party .Net library. The library is flatting a 2 level hierarchy of objects : function Actual { $someDotnetObject.ACollectionProperty.ASecondLevelCollection | % { $_ } } This method is dumping the objects in a list form (one line per property). How can I control what is displayed, keeping the actual object available? I have tried this : function Actual { $someDotnetObject.ACollectionProperty.ASecondLevelCollection | % { $_ } | format-table Property1, Property2 } It shows in a console the expected table : Property1 Property2 --------- --------- ValA ValD ValB ValE ValC ValF But I lost my objects. Running Get-Member on the result shows : TypeName: Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() autosizeInfo Property Microsoft.PowerShell.Commands.Internal.Format.AutosizeInfo autosizeInfo {get;set;} ClassId2e4f51ef21dd47e99d3c952918aff9cd Property System.String ClassId2e4f51ef21dd47e99d3c952918aff9cd {get;} groupingEntry Property Microsoft.PowerShell.Commands.Internal.Format.GroupingEntry groupingEntry {get;set;} pageFooterEntry Property Microsoft.PowerShell.Commands.Internal.Format.PageFooterEntry pageFooterEntry {get;set;} pageHeaderEntry Property Microsoft.PowerShell.Commands.Internal.Format.PageHeaderEntry pageHeaderEntry {get;set;} shapeInfo Property Microsoft.PowerShell.Commands.Internal.Format.ShapeInfo shapeInfo {get;set;} TypeName: Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() ClassId2e4f51ef21dd47e99d3c952918aff9cd Property System.String ClassId2e4f51ef21dd47e99d3c952918aff9cd {get;} groupingEntry Property Microsoft.PowerShell.Commands.Internal.Format.GroupingEntry groupingEntry {get;set;} shapeInfo Property Microsoft.PowerShell.Commands.Internal.Format.ShapeInfo shapeInfo {get;set;} Instead of showing the 2nd level child object members. In this case, I can't pipe the result to functions waiting for this type of argument. How does Powershell is supposed to handle such scenario?

    Read the article

  • Bing maps silverlight control in c#

    - by Dan Sewell
    Hello Chaps. Wondering if you could help me on this one.. Im trying to control my map with this c# code below. But for some reason its not doing anything when I call this method, and im not quite sure why?! Not sure if im using the .Equals properly? C# private void NW_zoom(object sender, ManipulationStartedEventArgs e) { GeoCoordinate abc = new GeoCoordinate(51.510, -0.1151); Map.CenterProperty.Equals(abc); var zoom = 12; Map.ZoomLevelProperty.Equals(zoom); } XMAL map control: <maps:Map ZoomLevel="10" Mode="Road" Margin="0,0,0,54" ZoomBarVisibility="Visible" ScaleVisibility="Visible" CredentialsProvider="xxxxxxx" Grid.Row="1"> <maps:Map.Center> <device:GeoCoordinate Latitude="51.510669" Longitude="-0.11512800"/> </maps:Map.Center> <maps:MapLayer x:Name="QuakeLayer" Height="726" Width="477" /> </maps:Map>

    Read the article

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