Search Results

Search found 785 results on 32 pages for 'gettype'.

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

  • How to hide GetType() method from COM?

    - by ticky
    I made an automation Add-In for Excel, and I made several functions (formulas). I have a class which header looks like this (it is COM visible): [ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class Functions {} In a list of methods, I see: ToString(), Equals(), GetHashCode() and GetType() methods. Since all methods of my class are COM visible, I should somehow hide those 4. I succeeded with 3 of them: ToString(), Equals(), GetHashCode() but GetType() cannot be overriden. Here is what I did with 3 of them: [ComVisible(false)] public override string ToString() { return base.ToString(); } [ComVisible(false)] public override bool Equals(object obj) { return base.Equals(obj); } [ComVisible(false)] public override int GetHashCode() { return base.GetHashCode(); } This doesn't work: [ComVisible(false)] public override Type GetType() { return base.GetType(); } Here is the error message in Visual Studio when compile: ..GetType()': cannot override inherited member 'object.GetType()' because it is not marked virtual, abstract, or override So, what should I do to hide the GetType() method from COM?

    Read the article

  • Dynamically loading type in Silverlight with Type.GetType()

    - by ondesertverge
    Trying to specify the assembly name like this: Type.GetType(string.Format("{0}.{1}, {0}", widget.Assembly, widget.Class)); Throws this: The requested assembly version conflicts with what is already bound in the app domain or specified in the manifest Trying it without the the assembly: Type.GetType(string.Format("{0}.{1}", widget.Assembly, widget.Class)); Returns null. I am looking for a way to instantiate a class using it's fully qualified name in Silverlight 4.0. Thanks.

    Read the article

  • C# class can not disguise to be another class because GetType method cannot be override

    - by zinking
    there is a statement in the CLR via C# saying in C#, one class cannot disguise to be another, because GetType is virutal and thus it cannot be override but I think in C# we can still hide the parent implementation of GetType. I must missed something if I hide the base GetType implementation then I can disguise my class to be another class, is that correct? The key here is not whether GetType is virutal or not, the question is can we disguise one class to be another in C# Following is the NO.4 answer from the possible duplicate, so My question is more on this. is this kind of disguise possible, if so, how can we say that we can prevent class type disguise in C# ? regardless of the GetType is virtual or not While its true that you cannot override the object.GetType() method, you can use "new" to overload it completely, thereby spoofing another known type. This is interesting, however, I haven't figured out how to create an instance of the "Type" object from scratch, so the example below pretends to be another type. public class NotAString { private string m_RealString = string.Empty; public new Type GetType() { return m_RealString.GetType(); } } After creating an instance of this, (new NotAString()).GetType(), will indeed return the type for a string. share|edit|flag answered Mar 15 at 18:39 Dr Snooze 213 By almost anything that looks at GetType has an instance of object, or at the very least some base type that they control or can reason about. If you already have an instance of the most derived type then there is no need to call GetType on it. The point is as long as someone uses GetType on an object they can be sure it's the system's implementation, not any other custom definition. – Servy Mar 15 at 18:54 add comment

    Read the article

  • IXmlSerializable Dictionary

    - by Shimmy
    I was trying to create a generic Dictionary that implements IXmlSerializable. Here is my trial: Sub Main() Dim z As New SerializableDictionary(Of String, String) z.Add("asdf", "asd") Console.WriteLine(z.Serialize) End Sub Result: <?xml version="1.0" encoding="utf-16"?><Entry key="asdf" value="asd" /> I placed a breakpoint on top of the WriteXml method and I see that when it stops, the writer contains no data at all, and IMHO it should contain the root element and the xml declaration. <Serializable()> _ Public Class SerializableDictionary(Of TKey, TValue) : Inherits Dictionary(Of TKey, TValue) : Implements IXmlSerializable Private Const EntryString As String = "Entry" Private Const KeyString As String = "key" Private Const ValueString As String = "value" Private Shared ReadOnly AttributableTypes As Type() = New Type() {GetType(Boolean), GetType(Byte), GetType(Char), GetType(DateTime), GetType(Decimal), GetType(Double), GetType([Enum]), GetType(Guid), GetType(Int16), GetType(Int32), GetType(Int64), GetType(SByte), GetType(Single), GetType(String), GetType(TimeSpan), GetType(UInt16), GetType(UInt32), GetType(UInt64)} Private Shared ReadOnly GetIsAttributable As Predicate(Of Type) = Function(t) AttributableTypes.Contains(t) Private Shared ReadOnly IsKeyAttributable As Boolean = GetIsAttributable(GetType(TKey)) Private Shared ReadOnly IsValueAttributable As Boolean = GetIsAttributable(GetType(TValue)) Private Shared ReadOnly GetElementName As Func(Of Boolean, String) = Function(isKey) If(isKey, KeyString, ValueString) Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema Return Nothing End Function Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml For Each entry In Me writer.WriteStartElement(EntryString) WriteData(IsKeyAttributable, writer, True, entry.Key) WriteData(IsValueAttributable, writer, False, entry.Value) writer.WriteEndElement() Next End Sub Private Sub WriteData(Of T)(ByVal attributable As Boolean, ByVal writer As XmlWriter, ByVal isKey As Boolean, ByVal value As T) Dim name = GetElementName(isKey) If attributable Then writer.WriteAttributeString(name, value.ToString) Else Dim serializer As New XmlSerializer(GetType(T)) writer.WriteStartElement(name) serializer.Serialize(writer, value) writer.WriteEndElement() End If End Sub Public Sub ReadXml(ByVal reader As XmlReader) Implements IXmlSerializable.ReadXml Dim empty = reader.IsEmptyElement reader.Read() If empty Then Exit Sub Clear() While reader.NodeType <> XmlNodeType.EndElement While reader.NodeType = XmlNodeType.Whitespace reader.Read() Dim key = ReadData(Of TKey)(IsKeyAttributable, reader, True) Dim value = ReadData(Of TValue)(IsValueAttributable, reader, False) Add(key, value) If Not IsKeyAttributable AndAlso Not IsValueAttributable Then reader.ReadEndElement() Else reader.Read() While reader.NodeType = XmlNodeType.Whitespace reader.Read() End While End While reader.ReadEndElement() End While End Sub Private Function ReadData(Of T)(ByVal attributable As Boolean, ByVal reader As XmlReader, ByVal isKey As Boolean) As T Dim name = GetElementName(isKey) Dim type = GetType(T) If attributable Then Return Convert.ChangeType(reader.GetAttribute(name), type) Else Dim serializer As New XmlSerializer(type) While reader.Name <> name reader.Read() End While reader.ReadStartElement(name) Dim value = serializer.Deserialize(reader) reader.ReadEndElement() Return value End If End Function Public Shared Function Serialize(ByVal dictionary As SerializableDictionary(Of TKey, TValue)) As String Dim sb As New StringBuilder(1024) Dim sw As New StringWriter(sb) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) xs.Serialize(sw, dictionary) sw.Dispose() Return sb.ToString End Function Public Shared Function Deserialize(ByVal xml As String) As SerializableDictionary(Of TKey, TValue) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) Return xs.Deserialize(xr) xr.Close() End Function Public Function Serialize() As String Dim sb As New StringBuilder Dim xw = XmlWriter.Create(sb) WriteXml(xw) xw.Close() Return sb.ToString End Function Public Sub Parse(ByVal xml As String) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) ReadXml(xr) xr.Close() End Sub End Class

    Read the article

  • IXmlSerializable Dictionary problem

    - by Shimmy
    I was trying to create a generic Dictionary that implements IXmlSerializable. Here is my trial: Sub Main() Dim z As New SerializableDictionary(Of String, String) z.Add("asdf", "asd") Console.WriteLine(z.Serialize) End Sub Result: <?xml version="1.0" encoding="utf-16"?><Entry key="asdf" value="asd" /> I placed a breakpoint on top of the WriteXml method and I see that when it stops, the writer contains no data at all, and IMHO it should contain the root element and the xml declaration. <Serializable()> _ Public Class SerializableDictionary(Of TKey, TValue) : Inherits Dictionary(Of TKey, TValue) : Implements IXmlSerializable Private Const EntryString As String = "Entry" Private Const KeyString As String = "key" Private Const ValueString As String = "value" Private Shared ReadOnly AttributableTypes As Type() = New Type() {GetType(Boolean), GetType(Byte), GetType(Char), GetType(DateTime), GetType(Decimal), GetType(Double), GetType([Enum]), GetType(Guid), GetType(Int16), GetType(Int32), GetType(Int64), GetType(SByte), GetType(Single), GetType(String), GetType(TimeSpan), GetType(UInt16), GetType(UInt32), GetType(UInt64)} Private Shared ReadOnly GetIsAttributable As Predicate(Of Type) = Function(t) AttributableTypes.Contains(t) Private Shared ReadOnly IsKeyAttributable As Boolean = GetIsAttributable(GetType(TKey)) Private Shared ReadOnly IsValueAttributable As Boolean = GetIsAttributable(GetType(TValue)) Private Shared ReadOnly GetElementName As Func(Of Boolean, String) = Function(isKey) If(isKey, KeyString, ValueString) Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema Return Nothing End Function Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml For Each entry In Me writer.WriteStartElement(EntryString) WriteData(IsKeyAttributable, writer, True, entry.Key) WriteData(IsValueAttributable, writer, False, entry.Value) writer.WriteEndElement() Next End Sub Private Sub WriteData(Of T)(ByVal attributable As Boolean, ByVal writer As XmlWriter, ByVal isKey As Boolean, ByVal value As T) Dim name = GetElementName(isKey) If attributable Then writer.WriteAttributeString(name, value.ToString) Else Dim serializer As New XmlSerializer(GetType(T)) writer.WriteStartElement(name) serializer.Serialize(writer, value) writer.WriteEndElement() End If End Sub Public Sub ReadXml(ByVal reader As XmlReader) Implements IXmlSerializable.ReadXml Dim empty = reader.IsEmptyElement reader.Read() If empty Then Exit Sub Clear() While reader.NodeType <> XmlNodeType.EndElement While reader.NodeType = XmlNodeType.Whitespace reader.Read() Dim key = ReadData(Of TKey)(IsKeyAttributable, reader, True) Dim value = ReadData(Of TValue)(IsValueAttributable, reader, False) Add(key, value) If Not IsKeyAttributable AndAlso Not IsValueAttributable Then reader.ReadEndElement() Else reader.Read() While reader.NodeType = XmlNodeType.Whitespace reader.Read() End While End While reader.ReadEndElement() End While End Sub Private Function ReadData(Of T)(ByVal attributable As Boolean, ByVal reader As XmlReader, ByVal isKey As Boolean) As T Dim name = GetElementName(isKey) Dim type = GetType(T) If attributable Then Return Convert.ChangeType(reader.GetAttribute(name), type) Else Dim serializer As New XmlSerializer(type) While reader.Name <> name reader.Read() End While reader.ReadStartElement(name) Dim value = serializer.Deserialize(reader) reader.ReadEndElement() Return value End If End Function Public Shared Function Serialize(ByVal dictionary As SerializableDictionary(Of TKey, TValue)) As String Dim sb As New StringBuilder(1024) Dim sw As New StringWriter(sb) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) xs.Serialize(sw, dictionary) sw.Dispose() Return sb.ToString End Function Public Shared Function Deserialize(ByVal xml As String) As SerializableDictionary(Of TKey, TValue) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) Return xs.Deserialize(xr) xr.Close() End Function Public Function Serialize() As String Dim sb As New StringBuilder Dim xw = XmlWriter.Create(sb) WriteXml(xw) xw.Close() Return sb.ToString End Function Public Sub Parse(ByVal xml As String) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) ReadXml(xr) xr.Close() End Sub End Class

    Read the article

  • Getting the type of an array of T, without specifying T - Type.GetType("T[]")

    - by Merlyn Morgan-Graham
    I am trying to create a type that refers to an array of a generic type, without specifying the generic type. That is, I would like to do the equivalent of Type.GetType("T[]"). I already know how to do this with a non-array type. E.g. Type.GetType("System.Collections.Generic.IEnumerable`1") // or typeof(IEnumerable<>) Here's some sample code that reproduces the problem. using System; using System.Collections.Generic; public class Program { public static void SomeFunc<T>(IEnumerable<T> collection) { } public static void SomeArrayFunc<T>(T[] collection) { } static void Main(string[] args) { Action<Type> printType = t => Console.WriteLine(t != null ? t.ToString() : "(null)"); Action<string> printFirstParameterType = methodName => printType( typeof(Program).GetMethod(methodName).GetParameters()[0].ParameterType ); printFirstParameterType("SomeFunc"); printFirstParameterType("SomeArrayFunc"); var iEnumerableT = Type.GetType("System.Collections.Generic.IEnumerable`1"); printType(iEnumerableT); var iEnumerableTFromTypeof = typeof(IEnumerable<>); printType(iEnumerableTFromTypeof); var arrayOfT = Type.GetType("T[]"); printType(arrayOfT); // Prints "(null)" // ... not even sure where to start for typeof(T[]) } } The output is: System.Collections.Generic.IEnumerable`1[T] T[] System.Collections.Generic.IEnumerable`1[T] System.Collections.Generic.IEnumerable`1[T] (null) I'd like to correct that last "(null)". This will be used to get an overload of a function via reflections by specifying the method signature: var someMethod = someType.GetMethod("MethodName", new[] { typeOfArrayOfT }); // ... call someMethod.MakeGenericMethod some time later I've already gotten my code mostly working by filtering the result of GetMethods(), so this is more of an exercise in knowledge and understanding.

    Read the article

  • gettype and unknown type in php

    - by justjoe
    i just start to practice with php built-in, gettype() and its return value. This function is capable to return testing result such as boolean, integer, unknown type, etc. But among those testing result, there's one caught my eyes : unknown type. After reading gettype, and try to find some reference here, i can not get any. So, the question is what kind of type can be categorized as "unknown type" ? is it possible ? or am i just missing reading something ?

    Read the article

  • PHP object help -> unexpected T_OBJECT_OPERATOR

    - by php-b-grader
    Please help me understand: print gettype(new CustomerObject()) prints: "object" (so it is an object) BUT print gettype((new CustomerObject())->get_customer()); prints: unexpected T_OBJECT_OPERATOR If I do it over two lines it works fine $object = new Customer($order->customer_id); print gettype($object); prints: object $customer = $object->get_customer(); print gettype($customer); prints: array It appears that the lines cannot be joined into a single call. Is this correct? and what is the logic behind that?

    Read the article

  • How to dynamically use the PropertyType reflection attribute to create a respective typed Function<

    - by vsj
    I want to use type returned by PropertyType to create a typed function. I found this similiar http://stackoverflow.com/questions/914578/using-type-returned-by-type-gettype-in-c but this mentions how to create a list but does not mention how we can create a Func<. Please help me out. Pseudocode: PropertyInfo inf = typeof(SomeClass).GetProperty("PropertyName"); Type T=inf.PropertyType; Expression<Func<SomeClass,T>> le = GetPropertyOrFieldByName<SomeClass, T>("PropertyName");

    Read the article

  • C# class type - How to determine whether it is a standard .net framework class

    - by HorstWalter
    C# / .net framework What is the most reliable way to determine whether a class (type) is a class provided by the .net framework and not any of my classes or 3rd party library classes. I have tested some approaches The namespace, e.g. starting with "System." The Codebase of the assembly, where the dll is located All this "feels" a little clumsy though it works. Question: What is the easiest and most reliable way to determine this?

    Read the article

  • How to get the type of the class for comparison

    - by Halo
    I have this object which is an instance of a superclass. I want to know which subclass that object really is, so that I can decide what to do with it. There is this getClass() method but it's apparently not used for comparison issues. How can I get the sub-type of my object?

    Read the article

  • Get the parent class of a null object (C# Reflection)

    - by Nick
    How would I get the parent class of an object that has a value of null? For example... 'Class A' contains 'int? i' which is not set to any value when the class is created. Then in some other place in the code I want to pass in 'i' as a parameter to some function. Using 'i' as the only info, I want to be able to figure out that 'Class A' "owns" 'i'. The reason for this is because 'Class A' also contains some other object, and I want to call this other object's value from that same function mentioned in the above paragraph. Could also be: public class A { public class B { public int? i; public int? j; } B classBInstance = new B(); public string s; } { ... A someClassAInstance = new A(); ... doSomething(someClassAInstance.classBInstance.i); ... } public static bool doSomething(object theObject) { string s = /* SOMETHING on theObject to get to "s" from Class A */; int someValue = (int)theObject; }

    Read the article

  • Problem Implementing StructureMap in VB.Net Conversion of SharpArchitecture

    - by Monkeeman69
    I work in a VB.Net environment and have recently been tasked with creating an MVC enviroment to use as a base to work from. I decided to convert the latest SharpArchitecture release (Q3 2009) into VB, which on the whole has gone fine after a bit of hair pulling. I came across a problem with Castle Windsor where my custom repository interface (lives in the core/domain project) that was reference in the constructor of my test controller was not getting injected with the concrete implementation (from the data project). I hit a brick wall with this so basically decided to switch out Castle Windsor for StructureMap. I think I have implemented this ok as everything compiles and runs and my controller ran ok when referencing a custom repository interface. It appears now that I have/or cannot now setup my generic interfaces up properly (I hope this makes sense so far as I am new to all this). When I use IRepository(Of T) (wanting it to be injected with a concrete implementation of Repository(Of Type)) in the controller constructor I am getting the following runtime error: "StructureMap Exception Code: 202 No Default Instance defined for PluginFamily SharpArch.Core.PersistenceSupport.IRepository`1[[DebtRemedy.Core.Page, DebtRemedy.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], SharpArch.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b5f559ae0ac4e006" Here are my code excerpts that I am using (my project is called DebtRemedy). My structuremap registry class Public Class DefaultRegistry Inherits Registry Public Sub New() ''//Generic Repositories AddGenericRepositories() ''//Custom Repositories AddCustomRepositories() ''//Application Services AddApplicationServices() ''//Validator [For](GetType(IValidator)).Use(GetType(Validator)) End Sub Private Sub AddGenericRepositories() ''//ForRequestedType(GetType(IRepository(Of ))).TheDefaultIsConcreteType(GetType(Repository(Of ))) [For](GetType(IEntityDuplicateChecker)).Use(GetType(EntityDuplicateChecker)) [For](GetType(IRepository(Of ))).Use(GetType(Repository(Of ))) [For](GetType(INHibernateRepository(Of ))).Use(GetType(NHibernateRepository(Of ))) [For](GetType(IRepositoryWithTypedId(Of ,))).Use(GetType(RepositoryWithTypedId(Of ,))) [For](GetType(INHibernateRepositoryWithTypedId(Of ,))).Use(GetType(NHibernateRepositoryWithTypedId(Of ,))) End Sub Private Sub AddCustomRepositories() Scan(AddressOf SetupCustomRepositories) End Sub Private Shared Sub SetupCustomRepositories(ByVal y As IAssemblyScanner) y.Assembly("DebtRemedy.Core") y.Assembly("DebtRemedy.Data") y.WithDefaultConventions() End Sub Private Sub AddApplicationServices() Scan(AddressOf SetupApplicationServices) End Sub Private Shared Sub SetupApplicationServices(ByVal y As IAssemblyScanner) y.Assembly("DebtRemedy.ApplicationServices") y.With(New FirstInterfaceConvention) End Sub End Class Public Class FirstInterfaceConvention Implements ITypeScanner Public Sub Process(ByVal type As Type, ByVal graph As PluginGraph) Implements ITypeScanner.Process If Not IsConcrete(type) Then Exit Sub End If ''//only works on concrete types Dim firstinterface = type.GetInterfaces().FirstOrDefault() ''//grabs first interface If firstinterface IsNot Nothing Then graph.AddType(firstinterface, type) Else ''//registers type ''//adds concrete types with no interfaces graph.AddType(type) End If End Sub End Class I have tried both ForRequestedType (which I think is now deprecated) and For. IRepository(Of T) lives in SharpArch.Core.PersistenceSupport. Repository(Of T) lives in SharpArch.Data.NHibernate. My servicelocator class Public Class StructureMapServiceLocator Inherits ServiceLocatorImplBase Private container As IContainer Public Sub New(ByVal container As IContainer) Me.container = container End Sub Protected Overloads Overrides Function DoGetInstance(ByVal serviceType As Type, ByVal key As String) As Object Return If(String.IsNullOrEmpty(key), container.GetInstance(serviceType), container.GetInstance(serviceType, key)) End Function Protected Overloads Overrides Function DoGetAllInstances(ByVal serviceType As Type) As IEnumerable(Of Object) Dim objList As New List(Of Object) For Each obj As Object In container.GetAllInstances(serviceType) objList.Add(obj) Next Return objList End Function End Class My controllerfactory class Public Class ServiceLocatorControllerFactory Inherits DefaultControllerFactory Protected Overloads Overrides Function GetControllerInstance(ByVal requestContext As RequestContext, ByVal controllerType As Type) As IController If controllerType Is Nothing Then Return Nothing End If Try Return TryCast(ObjectFactory.GetInstance(controllerType), Controller) Catch generatedExceptionName As StructureMapException System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave()) Throw End Try End Function End Class The initialise stuff in my gloabal.asax Dim container As IContainer = New Container(New DefaultRegistry) ControllerBuilder.Current.SetControllerFactory(New ServiceLocatorControllerFactory()) ServiceLocator.SetLocatorProvider(Function() New StructureMapServiceLocator(container)) My test controller Public Class DataCaptureController Inherits BaseController Private ReadOnly clientRepository As IClientRepository() Private ReadOnly pageRepository As IRepository(Of Page) Public Sub New(ByVal clientRepository As IClientRepository(), ByVal pageRepository As IRepository(Of Page)) Check.Require(clientRepository IsNot Nothing, "clientRepository may not be null") Check.Require(pageRepository IsNot Nothing, "pageRepository may not be null") Me.clientRepository = clientRepository Me.pageRepository = pageRepository End Sub Function Index() As ActionResult Return View() End Function The above works fine when I take out everything to do with the pageRepository which is IRepository(Of T). Any help with this would be greatly appreciated.

    Read the article

  • Converting Generic Type into reference type after checking its type using GetType(). How ?

    - by Shantanu Gupta
    i am trying to call a function that is defined in a class RFIDeas_Wrapper(dll being used). But when i checked for type of reader and after that i used it to call function it shows me error Cannot convert type T to RFIDeas_Wrapper. EDIT private List<string> GetTagCollection<T>(T Reader) { TagCollection = new List<string>(); if (Reader.GetType() == typeof(RFIDeas_Wrapper)) { ((RFIDeas_Wrapper)Reader).OpenDevice(); // here Reader is of type RFIDeas_Wrapper //, but i m not able to convert Reader into its datatype. string Tag_Id = ((RFIDeas_Wrapper)Reader).TagID(); //Adds Valid Tag Ids into the collection if(Tag_Id!="0") TagCollection.Add(Tag_Id); } else if (Reader.GetType() == typeof(AlienReader)) TagCollection = ((AlienReader)Reader).TagCollection; return TagCollection; } ((RFIDeas_Wrapper)Reader).OpenDevice(); , ((AlienReader)Reader).TagCollection; I want this line to be executed without any issue. As Reader will always be of the type i m specifying. How to make compiler understand the same thing.

    Read the article

  • Efficient Search function with Linq to SQL

    - by Bayonian
    Hi, I'm using VB.NET and Linq to SQL. I have a table with thousands of rows and growing. Right now I'm using .Contains() in the Where clause to perform the query. Below is my search function : Public Shared Function DemoSearchFunction(ByVal keyword As String) As DataTable Dim db As New BibleDataClassesDataContext() Dim query = From b In db.khmer_books _ From ch In db.khmer_chapters _ From v In db.testing_khmers _ Where v.t_v.Contains(keyword) And ch.kh_book_id = b.kh_b_id And v.t_chid = ch.kh_ch_id _ Select b.kh_b_id, b.kh_b_title, ch.kh_ch_id, ch.kh_ch_number, v.t_id, v.t_vn, v.t_v Dim dtDataTableOne = New DataTable("dtOne") dtDataTableOne.Columns.Add("bid", GetType(Integer)) dtDataTableOne.Columns.Add("btitle", GetType(String)) dtDataTableOne.Columns.Add("chid", GetType(Integer)) dtDataTableOne.Columns.Add("chn", GetType(Integer)) dtDataTableOne.Columns.Add("vid", GetType(Integer)) dtDataTableOne.Columns.Add("vn", GetType(Integer)) dtDataTableOne.Columns.Add("verse", GetType(String)) For Each r In query dtDataTableOne.Rows.Add(New Object() {r.kh_b_id, r.kh_b_title, r.kh_ch_id, r.kh_ch_number, r.t_id, r.t_vn, r.t_v}) Next Return dtDataTableOne End Function I would like to know other methods for doing efficient search using Linq to SQL. Thanks.

    Read the article

  • Is it poor practice to identify objects via an enumeration property, instead of using GetType()?

    - by James
    I have a collection of objects that all implement one (custom) interface: IAuditEvent. Each object can be stored in a database and a unique numeric id is used for each object type. The method that stores the objects loops around a List<IAuditEvent>, so it needs to know the specific type of each object in order to store the correct numeric id. Is it poor practice to have an enumeration property on IAuditEvent so that each object can identify itself with a unique enumeration value? I can see that the simplest solution would be to write a method that translates a Type into an integer, but what if I need an enumeration of audit events for another purpose? Would it still be wrong to have my enumeration property on IAuditEvent?

    Read the article

  • Copying Properties between 2 Different Types&hellip;

    - by Shawn Cicoria
    I’m not sure where I had seen some of this base code, but this comes up time & time again on projects. Here’s a little method that copies all the R/W properties (public) between 2 distinct class definitions: It’s called as follows: private static void Test1() { MyClass obj1 = new MyClass() { Prop1 = "one", Prop2 = "two", Prop3 = 100 }; MyOtherClass obj2 = null; obj2 = CopyClass(obj1); Console.WriteLine(obj1); Console.WriteLine(obj2); } namespace Space1 { public class MyClass { public string Prop1 { get; set; } public string Prop2 { get; set; } public int Prop3 { get; set; } public override string ToString() { var rv = string.Format("MyClass: {0} Prop2: {1} Prop3 {2}", Prop1, Prop2, Prop3); return rv; } } } namespace Space2 { public class MyOtherClass { public string Prop1 { get; set; } public string Prop2 { get; set; } public int Prop3 { get; set; } public override string ToString() { var rv = string.Format("MyOtherClass: {0} Prop2: {1} Prop3 {2}", Prop1, Prop2, Prop3); return rv; } } Source of the method: /// /// Provides a Copy of Public fields between 2 distinct classes /// /// Source class name /// Target class name /// Instance of type Source /// An instance of type Target copying all public properties matching name from the Source. public static T CopyClass(S source) where T : new() { T target = default(T); BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; if (source == null) { return (T)target; } if (target == null) target = new T(); PropertyInfo[] objProperties = target.GetType().GetProperties(flags); foreach (PropertyInfo pi in objProperties) { string name = pi.Name; PropertyInfo sourceProp = source.GetType().GetProperty(name, flags); if (sourceProp == null) { throw new ApplicationException(string.Format("CopyClass - object type {0} & {1} mismatch in property:{2}", source.GetType(), target.GetType(), name)); } if (pi.CanWrite && sourceProp.CanRead) { object sourceValue = sourceProp.GetValue(source, null); pi.SetValue(target, sourceValue, null); } else { throw new ApplicationException(string.Format("CopyClass - can't read/write a property object types {0} & {1} property:{2}", source.GetType(), target.GetType(), name)); } } return target; }

    Read the article

  • Unicode Collations problem ?

    - by Bayonian
    (.NET 3.5 SP1, VS 2008, VB.NET, MSSQL Server 2008) I'm writing a small web app to test the Khmer Unicode and Lao Unicode. I have a table that store text in Khmer Unicode with the following structure : [t_id] [int] IDENTITY(1,1) NOT NULL [t_chid] [int] NOT NULL [t_vn] [int] NOT NULL [t_v] [nvarchar](max) NOT NULL I can use Linq to SQL to do CRUD normally. The text display properly on the web page, even though I didn't change the default collation of MSSQL Server 2008. When it comes to search the column [t_v], the page will take a very long time to load and in fact, it loads every row of that column. It never compares with the "key word" criteria that I use for the search. Here's my query for the search : Public Shared Function SearchTestingKhmerTable(ByVal keyword As String) As DataTable Dim db As New BibleDataClassesDataContext() Dim query = From b In db.khmer_books _ From ch In db.khmer_chapters _ From v In db.testing_khmers _ Where v.t_v.Contains(keyword) And ch.kh_book_id = b.kh_b_id And v.t_chid = ch.kh_ch_id _ Select b.kh_b_id, b.kh_b_title, ch.kh_ch_id, ch.kh_ch_number, v.t_id, v.t_vn, v.t_v Dim dtDataTableOne = New DataTable("dtOne") dtDataTableOne.Columns.Add("bid", GetType(Integer)) dtDataTableOne.Columns.Add("btitle", GetType(String)) dtDataTableOne.Columns.Add("chid", GetType(Integer)) dtDataTableOne.Columns.Add("chn", GetType(Integer)) dtDataTableOne.Columns.Add("vid", GetType(Integer)) dtDataTableOne.Columns.Add("vn", GetType(Integer)) dtDataTableOne.Columns.Add("verse", GetType(String)) For Each r In query dtDataTableOne.Rows.Add(New Object() {r.kh_b_id, r.kh_b_title, r.kh_ch_id, r.kh_ch_number, r.t_id, r.t_vn, r.t_v}) Next Return dtDataTableOne End Function Please note that I use the exact same code and database design with Lao Unicode and it works just fine. I get the returned query as expected for the search. I can't figure out what the problem with searching for query in Khmer table.

    Read the article

  • overload Equals, is this wrong?

    - by Zka
    Reading some piece of code and I keep seeing this : public override bool Equals (object obj) { if (obj == null || this.GetType ().Equals (obj.GetType())) return false; //compare code... } Shouldn't it be like this (note the !): public override bool Equals (object obj) { if (obj == null || !this.GetType ().Equals (obj.GetType())) return false; //compare code... } Or does the equals perform differently in this case?

    Read the article

  • General type conversion without risking Exceptions

    - by Mongus Pong
    I am working on a control that can take a number of different datatypes (anything that implements IComparable). I need to be able to compare these with another variable passed in. If the main datatype is a DateTime, and I am passed a String, I need to attempt to convert the String to a DateTime to perform a Date comparison. if the String cannot be converted to a DateTime then do a String comparison. So I need a general way to attempt to convert from any type to any type. Easy enough, .Net provides us with the TypeConverter class. Now, the best I can work out to do to determine if the String can be converted to a DateTime is to use exceptions. If the ConvertFrom raises an exception, I know I cant do the conversion and have to do the string comparison. The following is the best I got : string theString = "99/12/2009"; DateTime theDate = new DateTime ( 2009, 11, 1 ); IComparable obj1 = theString as IComparable; IComparable obj2 = theDate as IComparable; try { TypeConverter converter = TypeDescriptor.GetConverter ( obj2.GetType () ); if ( converter.CanConvertFrom ( obj1.GetType () ) ) { Console.WriteLine ( obj2.CompareTo ( converter.ConvertFrom ( obj1 ) ) ); Console.WriteLine ( "Date comparison" ); } } catch ( FormatException ) { Console.WriteLine ( obj1.ToString ().CompareTo ( obj2.ToString () ) ); Console.WriteLine ( "String comparison" ); } Part of our standards at work state that : Exceptions should only be raised when an Exception situation - ie. an error is encountered. But this is not an exceptional situation. I need another way around it. Most variable types have a TryParse method which returns a boolean to allow you to determine if the conversion has succeeded or not. But there is no TryConvert method available to TypeConverter. CanConvertFrom only dermines if it is possible to convert between these types and doesnt consider the actual data to be converted. The IsValid method is also useless. Any ideas? EDIT I cannot use AS and IS. I do not know either data types at compile time. So I dont know what to As and Is to!!! EDIT Ok nailed the bastard. Its not as tidy as Marc Gravells, but it works (I hope). Thanks for the inpiration Marc. Will work on tidying it up when I get the time, but I've got a bit stack of bugfixes that I have to get on with. public static class CleanConverter { /// <summary> /// Stores the cache of all types that can be converted to all types. /// </summary> private static Dictionary<Type, Dictionary<Type, ConversionCache>> _Types = new Dictionary<Type, Dictionary<Type, ConversionCache>> (); /// <summary> /// Try parsing. /// </summary> /// <param name="s"></param> /// <param name="value"></param> /// <returns></returns> public static bool TryParse ( IComparable s, ref IComparable value ) { // First get the cached conversion method. Dictionary<Type, ConversionCache> type1Cache = null; ConversionCache type2Cache = null; if ( !_Types.ContainsKey ( s.GetType () ) ) { type1Cache = new Dictionary<Type, ConversionCache> (); _Types.Add ( s.GetType (), type1Cache ); } else { type1Cache = _Types[s.GetType ()]; } if ( !type1Cache.ContainsKey ( value.GetType () ) ) { // We havent converted this type before, so create a new conversion type2Cache = new ConversionCache ( s.GetType (), value.GetType () ); // Add to the cache type1Cache.Add ( value.GetType (), type2Cache ); } else { type2Cache = type1Cache[value.GetType ()]; } // Attempt the parse return type2Cache.TryParse ( s, ref value ); } /// <summary> /// Stores the method to convert from Type1 to Type2 /// </summary> internal class ConversionCache { internal bool TryParse ( IComparable s, ref IComparable value ) { if ( this._Method != null ) { // Invoke the cached TryParse method. object[] parameters = new object[] { s, value }; bool result = (bool)this._Method.Invoke ( null, parameters); if ( result ) value = parameters[1] as IComparable; return result; } else return false; } private MethodInfo _Method; internal ConversionCache ( Type type1, Type type2 ) { // Use reflection to get the TryParse method from it. this._Method = type2.GetMethod ( "TryParse", new Type[] { type1, type2.MakeByRefType () } ); } } }

    Read the article

  • C++ - Conway's Game of Life & Stepping Backwards

    - by Gabe
    I was able to create a version Conway's Game of Life that either stepped forward each click, or just ran forward using a timer. (I'm doing this using Qt.) Now, I need to be able to save all previous game grids, so that I can step backwards by clicking a button. I'm trying to use a stack, and it seems like I'm pushing the old gridcells onto the stack correctly. But when I run it in QT, the grids don't change when I click BACK. I've tried different things for the last three hours, to no avail. Any ideas? gridwindow.cpp - My problem should be in here somewhere. Probably the handleBack() func. #include <iostream> #include "gridwindow.h" using namespace std; // Constructor for window. It constructs the three portions of the GUI and lays them out vertically. GridWindow::GridWindow(QWidget *parent,int rows,int cols) : QWidget(parent) { QHBoxLayout *header = setupHeader(); // Setup the title at the top. QGridLayout *grid = setupGrid(rows,cols); // Setup the grid of colored cells in the middle. QHBoxLayout *buttonRow = setupButtonRow(); // Setup the row of buttons across the bottom. QVBoxLayout *layout = new QVBoxLayout(); // Puts everything together. layout->addLayout(header); layout->addLayout(grid); layout->addLayout(buttonRow); setLayout(layout); } // Destructor. GridWindow::~GridWindow() { delete title; } // Builds header section of the GUI. QHBoxLayout* GridWindow::setupHeader() { QHBoxLayout *header = new QHBoxLayout(); // Creates horizontal box. header->setAlignment(Qt::AlignHCenter); this->title = new QLabel("CONWAY'S GAME OF LIFE",this); // Creates big, bold, centered label (title): "Conway's Game of Life." this->title->setAlignment(Qt::AlignHCenter); this->title->setFont(QFont("Arial", 32, QFont::Bold)); header->addWidget(this->title); // Adds widget to layout. return header; // Returns header to grid window. } // Builds the grid of cells. This method populates the grid's 2D array of GridCells with MxN cells. QGridLayout* GridWindow::setupGrid(int rows,int cols) { isRunning = false; QGridLayout *grid = new QGridLayout(); // Creates grid layout. grid->setHorizontalSpacing(0); // No empty spaces. Cells should be contiguous. grid->setVerticalSpacing(0); grid->setSpacing(0); grid->setAlignment(Qt::AlignHCenter); for(int i=0; i < rows; i++) //Each row is a vector of grid cells. { std::vector<GridCell*> row; // Creates new vector for current row. cells.push_back(row); for(int j=0; j < cols; j++) { GridCell *cell = new GridCell(); // Creates and adds new cell to row. cells.at(i).push_back(cell); grid->addWidget(cell,i,j); // Adds to cell to grid layout. Column expands vertically. grid->setColumnStretch(j,1); } grid->setRowStretch(i,1); // Sets row expansion horizontally. } return grid; // Returns grid. } // Builds footer section of the GUI. QHBoxLayout* GridWindow::setupButtonRow() { QHBoxLayout *buttonRow = new QHBoxLayout(); // Creates horizontal box for buttons. buttonRow->setAlignment(Qt::AlignHCenter); // Clear Button - Clears cell; sets them all to DEAD/white. QPushButton *clearButton = new QPushButton("CLEAR"); clearButton->setFixedSize(100,25); connect(clearButton, SIGNAL(clicked()), this, SLOT(handlePause())); // Pauses timer before clearing. connect(clearButton, SIGNAL(clicked()), this, SLOT(handleClear())); // Connects to clear function to make all cells DEAD/white. buttonRow->addWidget(clearButton); // Forward Button - Steps one step forward. QPushButton *forwardButton = new QPushButton("FORWARD"); forwardButton->setFixedSize(100,25); connect(forwardButton, SIGNAL(clicked()), this, SLOT(handleForward())); // Signals to handleForward function.. buttonRow->addWidget(forwardButton); // Back Button - Steps one step backward. QPushButton *backButton = new QPushButton("BACK"); backButton->setFixedSize(100,25); connect(backButton, SIGNAL(clicked()), this, SLOT(handleBack())); // Signals to handleBack funciton. buttonRow->addWidget(backButton); // Start Button - Starts game when user clicks. Or, resumes game after being paused. QPushButton *startButton = new QPushButton("START/RESUME"); startButton->setFixedSize(100,25); connect(startButton, SIGNAL(clicked()), this, SLOT(handlePause())); // Deletes current timer if there is one. Then restarts everything. connect(startButton, SIGNAL(clicked()), this, SLOT(handleStart())); // Signals to handleStart function. buttonRow->addWidget(startButton); // Pause Button - Pauses simulation of game. QPushButton *pauseButton = new QPushButton("PAUSE"); pauseButton->setFixedSize(100,25); connect(pauseButton, SIGNAL(clicked()), this, SLOT(handlePause())); // Signals to pause function which pauses timer. buttonRow->addWidget(pauseButton); // Quit Button - Exits program. QPushButton *quitButton = new QPushButton("EXIT"); quitButton->setFixedSize(100,25); connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); // Signals the quit slot which ends the program. buttonRow->addWidget(quitButton); return buttonRow; // Returns bottom of layout. } /* SLOT method for handling clicks on the "clear" button. Receives "clicked" signals on the "Clear" button and sets all cells to DEAD. */ void GridWindow::handleClear() { for(unsigned int row=0; row < cells.size(); row++) // Loops through current rows' cells. { for(unsigned int col=0; col < cells[row].size(); col++) // Loops through the rows'columns' cells. { GridCell *cell = cells[row][col]; // Grab the current cell & set its value to dead. cell->setType(DEAD); } } } /* SLOT method for handling clicks on the "start" button. Receives "clicked" signals on the "start" button and begins game simulation. */ void GridWindow::handleStart() { isRunning = true; // It is running. Sets isRunning to true. this->timer = new QTimer(this); // Creates new timer. connect(this->timer, SIGNAL(timeout()), this, SLOT(timerFired())); // Connect "timerFired" method class to the "timeout" signal fired by the timer. this->timer->start(500); // Timer to fire every 500 milliseconds. } /* SLOT method for handling clicks on the "pause" button. Receives "clicked" signals on the "pause" button and stops the game simulation. */ void GridWindow::handlePause() { if(isRunning) // If it is running... this->timer->stop(); // Stops the timer. isRunning = false; // Set to false. } void GridWindow::handleForward() { if(isRunning); // If it's running, do nothing. else timerFired(); // It not running, step forward one step. } void GridWindow::handleBack() { std::vector<std::vector<GridCell*> > cells2; if(isRunning); // If it's running, do nothing. else if(backStack.empty()) cout << "EMPTYYY" << endl; else { cells2 = backStack.peek(); for (unsigned int f = 0; f < cells.size(); f++) // Loop through cells' rows. { for (unsigned int g = 0; g < cells.at(f).size(); g++) // Loop through cells columns. { cells[f][g]->setType(cells2[f][g]->getType()); // Set cells[f][g]'s type to cells2[f][g]'s type. } } cout << "PRE=POP" << endl; backStack.pop(); cout << "OYYYY" << endl; } } // Accessor method - Gets the 2D vector of grid cells. std::vector<std::vector<GridCell*> >& GridWindow::getCells() { return this->cells; } /* TimerFired function: 1) 2D-Vector cells2 is declared. 2) cells2 is initliazed with loops/push_backs so that all its cells are DEAD. 3) We loop through cells, and count the number of LIVE neighbors next to a given cell. --> Depending on how many cells are living, we choose if the cell should be LIVE or DEAD in the next simulation, according to the rules. -----> We save the cell type in cell2 at the same indice (the same row and column cell in cells2). 4) After check all the cells (and save the next round values in cells 2), we set cells's gridcells equal to cells2 gridcells. --> This causes the cells to be redrawn with cells2 types (white or black). */ void GridWindow::timerFired() { backStack.push(cells); std::vector<std::vector<GridCell*> > cells2; // Holds new values for 2D vector. These are the next simulation round of cell types. for(unsigned int i = 0; i < cells.size(); i++) // Loop through the rows of cells2. (Same size as cells' rows.) { vector<GridCell*> row; // Creates Gridcell* vector to push_back into cells2. cells2.push_back(row); // Pushes back row vectors into cells2. for(unsigned int j = 0; j < cells[i].size(); j++) // Loop through the columns (the cells in each row). { GridCell *cell = new GridCell(); // Creates new GridCell. cell->setType(DEAD); // Sets cell type to DEAD/white. cells2.at(i).push_back(cell); // Pushes back the DEAD cell into cells2. } // This makes a gridwindow the same size as cells with all DEAD cells. } for (unsigned int m = 0; m < cells.size(); m++) // Loop through cells' rows. { for (unsigned int n = 0; n < cells.at(m).size(); n++) // Loop through cells' columns. { unsigned int neighbors = 0; // Counter for number of LIVE neighbors for a given cell. // We know check all different variations of cells[i][j] to count the number of living neighbors for each cell. // We check m > 0 and/or n > 0 to make sure we don't access negative indexes (ex: cells[-1][0].) // We check m < size to make sure we don't try to access rows out of the vector (ex: row 5, if only 4 rows). // We check n < row size to make sure we don't access column item out of the vector (ex: 10th item in a column of only 9 items). // If we find that the Type = 1 (it is LIVE), then we add 1 to the neighbor. // Else - we add nothing to the neighbor counter. // Neighbor is the number of LIVE cells next to the current cell. if(m > 0 && n > 0) { if (cells[m-1][n-1]->getType() == 1) neighbors += 1; } if(m > 0) { if (cells[m-1][n]->getType() == 1) neighbors += 1; if(n < (cells.at(m).size() - 1)) { if (cells[m-1][n+1]->getType() == 1) neighbors += 1; } } if(n > 0) { if (cells[m][n-1]->getType() == 1) neighbors += 1; if(m < (cells.size() - 1)) { if (cells[m+1][n-1]->getType() == 1) neighbors += 1; } } if(n < (cells.at(m).size() - 1)) { if (cells[m][n+1]->getType() == 1) neighbors += 1; } if(m < (cells.size() - 1)) { if (cells[m+1][n]->getType() == 1) neighbors += 1; } if(m < (cells.size() - 1) && n < (cells.at(m).size() - 1)) { if (cells[m+1][n+1]->getType() == 1) neighbors += 1; } // Done checking number of neighbors for cells[m][n] // Now we change cells2 if it should switch in the next simulation step. // cells2 holds the values of what cells should be on the next iteration of the game. // We can't change cells right now, or it would through off our other cell values. // Apply game rules to cells: Create new, updated grid with the roundtwo vector. // Note - LIVE is 1; DEAD is 0. if (cells[m][n]->getType() == 1 && neighbors < 2) // If cell is LIVE and has less than 2 LIVE neighbors -> Set to DEAD. cells2[m][n]->setType(DEAD); else if (cells[m][n]->getType() == 1 && neighbors > 3) // If cell is LIVE and has more than 3 LIVE neighbors -> Set to DEAD. cells2[m][n]->setType(DEAD); else if (cells[m][n]->getType() == 1 && (neighbors == 2 || neighbors == 3)) // If cell is LIVE and has 2 or 3 LIVE neighbors -> Set to LIVE. cells2[m][n]->setType(LIVE); else if (cells[m][n]->getType() == 0 && neighbors == 3) // If cell is DEAD and has 3 LIVE neighbors -> Set to LIVE. cells2[m][n]->setType(LIVE); } } // Now we've gone through all of cells, and saved the new values in cells2. // Now we loop through cells and set all the cells' types to those of cells2. for (unsigned int f = 0; f < cells.size(); f++) // Loop through cells' rows. { for (unsigned int g = 0; g < cells.at(f).size(); g++) // Loop through cells columns. { cells[f][g]->setType(cells2[f][g]->getType()); // Set cells[f][g]'s type to cells2[f][g]'s type. } } } stack.h - Here's my stack. #ifndef STACK_H_ #define STACK_H_ #include <iostream> #include "node.h" template <typename T> class Stack { private: Node<T>* top; int listSize; public: Stack(); int size() const; bool empty() const; void push(const T& value); void pop(); T& peek() const; }; template <typename T> Stack<T>::Stack() : top(NULL) { listSize = 0; } template <typename T> int Stack<T>::size() const { return listSize; } template <typename T> bool Stack<T>::empty() const { if(listSize == 0) return true; else return false; } template <typename T> void Stack<T>::push(const T& value) { Node<T>* newOne = new Node<T>(value); newOne->next = top; top = newOne; listSize++; } template <typename T> void Stack<T>::pop() { Node<T>* oldT = top; top = top->next; delete oldT; listSize--; } template <typename T> T& Stack<T>::peek() const { return top->data; // Returns data in top item. } #endif gridcell.cpp - Gridcell implementation #include <iostream> #include "gridcell.h" using namespace std; // Constructor: Creates a grid cell. GridCell::GridCell(QWidget *parent) : QFrame(parent) { this->type = DEAD; // Default: Cell is DEAD (white). setFrameStyle(QFrame::Box); // Set the frame style. This is what gives each box its black border. this->button = new QPushButton(this); //Creates button that fills entirety of each grid cell. this->button->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); // Expands button to fill space. this->button->setMinimumSize(19,19); //width,height // Min height and width of button. QHBoxLayout *layout = new QHBoxLayout(); //Creates a simple layout to hold our button and add the button to it. layout->addWidget(this->button); setLayout(layout); layout->setStretchFactor(this->button,1); // Lets the buttons expand all the way to the edges of the current frame with no space leftover layout->setContentsMargins(0,0,0,0); layout->setSpacing(0); connect(this->button,SIGNAL(clicked()),this,SLOT(handleClick())); // Connects clicked signal with handleClick slot. redrawCell(); // Calls function to redraw (set new type for) the cell. } // Basic destructor. GridCell::~GridCell() { delete this->button; } // Accessor for the cell type. CellType GridCell::getType() const { return(this->type); } // Mutator for the cell type. Also has the side effect of causing the cell to be redrawn on the GUI. void GridCell::setType(CellType type) { this->type = type; redrawCell(); // Sets type and redraws cell. } // Handler slot for button clicks. This method is called whenever the user clicks on this cell in the grid. void GridCell::handleClick() { // When clicked on... if(this->type == DEAD) // If type is DEAD (white), change to LIVE (black). type = LIVE; else type = DEAD; // If type is LIVE (black), change to DEAD (white). setType(type); // Sets new type (color). setType Calls redrawCell() to recolor. } // Method to check cell type and return the color of that type. Qt::GlobalColor GridCell::getColorForCellType() { switch(this->type) { default: case DEAD: return Qt::white; case LIVE: return Qt::black; } } // Helper method. Forces current cell to be redrawn on the GUI. Called whenever the setType method is invoked. void GridCell::redrawCell() { Qt::GlobalColor gc = getColorForCellType(); //Find out what color this cell should be. this->button->setPalette(QPalette(gc,gc)); //Force the button in the cell to be the proper color. this->button->setAutoFillBackground(true); this->button->setFlat(true); //Force QT to NOT draw the borders on the button } Thanks a lot. Let me know if you need anything else.

    Read the article

  • Conway's Game of Life - C++ and Qt

    - by Jeff Bridge
    I've done all of the layouts and have most of the code written even. But, I'm stuck in two places. 1) I'm not quite sure how to set up the timer. Am I using it correctly in the gridwindow class? And, am I used the timer functions/signals/slots correctly with the other gridwindow functions. 2) In GridWindow's timerFired() function, I'm having trouble checking/creating the vector-vectors. I wrote out in the comments in that function exactly what I am trying to do. Any help would be much appreciated. main.cpp // Main file for running the grid window application. #include <QApplication> #include "gridwindow.h" //#include "timerwindow.h" #include <stdexcept> #include <string> #include <fstream> #include <sstream> #include <iostream> void Welcome(); // Welcome Function - Prints upon running program; outputs program name, student name/id, class section. void Rules(); // Rules Function: Prints the rules for Conway's Game of Life. using namespace std; // A simple main method to create the window class and then pop it up on the screen. int main(int argc, char *argv[]) { Welcome(); // Calls Welcome function to print student/assignment info. Rules(); // Prints Conway's Game Rules. QApplication app(argc, argv); // Creates the overall windowed application. int rows = 25, cols = 35; //The number of rows & columns in the game grid. GridWindow widget(NULL,rows,cols); // Creates the actual window (for the grid). widget.show(); // Shows the window on the screen. return app.exec(); // Goes into visual loop; starts executing GUI. } // Welcome Function: Prints my name/id, my class number, the assignment, and the program name. void Welcome() { cout << endl; cout << "-------------------------------------------------------------------------------------------------" << endl; cout << "Name/ID - Gabe Audick #7681539807" << endl; cout << "Class/Assignment - CSCI-102 Disccusion 29915: Homework Assignment #4" << endl; cout << "-------------------------------------------------------------------------------------------------" << endl << endl; } // Rules Function: Prints the rules for Conway's Game of Life. void Rules() { cout << "Welcome to Conway's Game of Life." << endl; cout << "Game Rules:" << endl; cout << "\t 1) Any living cell with fewer than two living neighbours dies, as if caused by underpopulation." << endl; cout << "\t 2) Any live cell with more than three live neighbours dies, as if by overcrowding." << endl; cout << "\t 3) Any live cell with two or three live neighbours lives on to the next generation." << endl; cout << "\t 4) Any dead cell with exactly three live neighbours becomes a live cell." << endl << endl; cout << "Enjoy." << endl << endl; } gridcell.h // A header file for a class representing a single cell in a grid of cells. #ifndef GRIDCELL_H_ #define GRIDCELL_H_ #include <QPalette> #include <QColor> #include <QPushButton> #include <Qt> #include <QWidget> #include <QFrame> #include <QHBoxLayout> #include <iostream> // An enum representing the two different states a cell can have. enum CellType { DEAD, // DEAD = Dead Cell. --> Color = White. LIVE // LIVE = Living Cell. ---> Color = White. }; /* Class: GridCell. A class representing a single cell in a grid. Each cell is implemented as a QT QFrame that contains a single QPushButton. The button is sized so that it takes up the entire frame. Each cell also keeps track of what type of cell it is based on the CellType enum. */ class GridCell : public QFrame { Q_OBJECT // Macro allowing us to have signals & slots on this object. private: QPushButton* button; // The button inside the cell that gives its clickability. CellType type; // The type of cell (DEAD or LIVE.) public slots: void handleClick(); // Callback for handling a click on the current cell. void setType(CellType type); // Cell type mutator. Calls the "redrawCell" function. signals: void typeChanged(CellType type); // Signal to notify listeners when the cell type has changed. public: GridCell(QWidget *parent = NULL); // Constructor for creating a cell. Takes parent widget or default parent to NULL. virtual ~GridCell(); // Destructor. void redrawCell(); // Redraws cell: Sets new type/color. CellType getType() const; //Simple getter for the cell type. private: Qt::GlobalColor getColorForCellType(); // Helper method. Returns color that cell should be based from its value. }; #endif gridcell.cpp #include <iostream> #include "gridcell.h" #include "utility.h" using namespace std; // Constructor: Creates a grid cell. GridCell::GridCell(QWidget *parent) : QFrame(parent) { this->type = DEAD; // Default: Cell is DEAD (white). setFrameStyle(QFrame::Box); // Set the frame style. This is what gives each box its black border. this->button = new QPushButton(this); //Creates button that fills entirety of each grid cell. this->button->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); // Expands button to fill space. this->button->setMinimumSize(19,19); //width,height // Min height and width of button. QHBoxLayout *layout = new QHBoxLayout(); //Creates a simple layout to hold our button and add the button to it. layout->addWidget(this->button); setLayout(layout); layout->setStretchFactor(this->button,1); // Lets the buttons expand all the way to the edges of the current frame with no space leftover layout->setContentsMargins(0,0,0,0); layout->setSpacing(0); connect(this->button,SIGNAL(clicked()),this,SLOT(handleClick())); // Connects clicked signal with handleClick slot. redrawCell(); // Calls function to redraw (set new type for) the cell. } // Basic destructor. GridCell::~GridCell() { delete this->button; } // Accessor for the cell type. CellType GridCell::getType() const { return(this->type); } // Mutator for the cell type. Also has the side effect of causing the cell to be redrawn on the GUI. void GridCell::setType(CellType type) { this->type = type; redrawCell(); } // Handler slot for button clicks. This method is called whenever the user clicks on this cell in the grid. void GridCell::handleClick() { // When clicked on... if(this->type == DEAD) // If type is DEAD (white), change to LIVE (black). type = LIVE; else type = DEAD; // If type is LIVE (black), change to DEAD (white). setType(type); // Sets new type (color). setType Calls redrawCell() to recolor. } // Method to check cell type and return the color of that type. Qt::GlobalColor GridCell::getColorForCellType() { switch(this->type) { default: case DEAD: return Qt::white; case LIVE: return Qt::black; } } // Helper method. Forces current cell to be redrawn on the GUI. Called whenever the setType method is invoked. void GridCell::redrawCell() { Qt::GlobalColor gc = getColorForCellType(); //Find out what color this cell should be. this->button->setPalette(QPalette(gc,gc)); //Force the button in the cell to be the proper color. this->button->setAutoFillBackground(true); this->button->setFlat(true); //Force QT to NOT draw the borders on the button } gridwindow.h // A header file for a QT window that holds a grid of cells. #ifndef GRIDWINDOW_H_ #define GRIDWINDOW_H_ #include <vector> #include <QWidget> #include <QTimer> #include <QGridLayout> #include <QLabel> #include <QApplication> #include "gridcell.h" /* class GridWindow: This is the class representing the whole window that comes up when this program runs. It contains a header section with a title, a middle section of MxN cells and a bottom section with buttons. */ class GridWindow : public QWidget { Q_OBJECT // Macro to allow this object to have signals & slots. private: std::vector<std::vector<GridCell*> > cells; // A 2D vector containing pointers to all the cells in the grid. QLabel *title; // A pointer to the Title text on the window. QTimer *timer; // Creates timer object. public slots: void handleClear(); // Handler function for clicking the Clear button. void handleStart(); // Handler function for clicking the Start button. void handlePause(); // Handler function for clicking the Pause button. void timerFired(); // Method called whenever timer fires. public: GridWindow(QWidget *parent = NULL,int rows=3,int cols=3); // Constructor. virtual ~GridWindow(); // Destructor. std::vector<std::vector<GridCell*> >& getCells(); // Accessor for the array of grid cells. private: QHBoxLayout* setupHeader(); // Helper function to construct the GUI header. QGridLayout* setupGrid(int rows,int cols); // Helper function to constructor the GUI's grid. QHBoxLayout* setupButtonRow(); // Helper function to setup the row of buttons at the bottom. }; #endif gridwindow.cpp #include <iostream> #include "gridwindow.h" using namespace std; // Constructor for window. It constructs the three portions of the GUI and lays them out vertically. GridWindow::GridWindow(QWidget *parent,int rows,int cols) : QWidget(parent) { QHBoxLayout *header = setupHeader(); // Setup the title at the top. QGridLayout *grid = setupGrid(rows,cols); // Setup the grid of colored cells in the middle. QHBoxLayout *buttonRow = setupButtonRow(); // Setup the row of buttons across the bottom. QVBoxLayout *layout = new QVBoxLayout(); // Puts everything together. layout->addLayout(header); layout->addLayout(grid); layout->addLayout(buttonRow); setLayout(layout); } // Destructor. GridWindow::~GridWindow() { delete title; } // Builds header section of the GUI. QHBoxLayout* GridWindow::setupHeader() { QHBoxLayout *header = new QHBoxLayout(); // Creates horizontal box. header->setAlignment(Qt::AlignHCenter); this->title = new QLabel("CONWAY'S GAME OF LIFE",this); // Creates big, bold, centered label (title): "Conway's Game of Life." this->title->setAlignment(Qt::AlignHCenter); this->title->setFont(QFont("Arial", 32, QFont::Bold)); header->addWidget(this->title); // Adds widget to layout. return header; // Returns header to grid window. } // Builds the grid of cells. This method populates the grid's 2D array of GridCells with MxN cells. QGridLayout* GridWindow::setupGrid(int rows,int cols) { QGridLayout *grid = new QGridLayout(); // Creates grid layout. grid->setHorizontalSpacing(0); // No empty spaces. Cells should be contiguous. grid->setVerticalSpacing(0); grid->setSpacing(0); grid->setAlignment(Qt::AlignHCenter); for(int i=0; i < rows; i++) //Each row is a vector of grid cells. { std::vector<GridCell*> row; // Creates new vector for current row. cells.push_back(row); for(int j=0; j < cols; j++) { GridCell *cell = new GridCell(); // Creates and adds new cell to row. cells.at(i).push_back(cell); grid->addWidget(cell,i,j); // Adds to cell to grid layout. Column expands vertically. grid->setColumnStretch(j,1); } grid->setRowStretch(i,1); // Sets row expansion horizontally. } return grid; // Returns grid. } // Builds footer section of the GUI. QHBoxLayout* GridWindow::setupButtonRow() { QHBoxLayout *buttonRow = new QHBoxLayout(); // Creates horizontal box for buttons. buttonRow->setAlignment(Qt::AlignHCenter); // Clear Button - Clears cell; sets them all to DEAD/white. QPushButton *clearButton = new QPushButton("CLEAR"); clearButton->setFixedSize(100,25); connect(clearButton, SIGNAL(clicked()), this, SLOT(handleClear())); buttonRow->addWidget(clearButton); // Start Button - Starts game when user clicks. Or, resumes game after being paused. QPushButton *startButton = new QPushButton("START/RESUME"); startButton->setFixedSize(100,25); connect(startButton, SIGNAL(clicked()), this, SLOT(handleStart())); buttonRow->addWidget(startButton); // Pause Button - Pauses simulation of game. QPushButton *pauseButton = new QPushButton("PAUSE"); pauseButton->setFixedSize(100,25); connect(pauseButton, SIGNAL(clicked()), this, SLOT(handlePause())); buttonRow->addWidget(pauseButton); // Quit Button - Exits program. QPushButton *quitButton = new QPushButton("EXIT"); quitButton->setFixedSize(100,25); connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); buttonRow->addWidget(quitButton); return buttonRow; // Returns bottom of layout. } /* SLOT method for handling clicks on the "clear" button. Receives "clicked" signals on the "Clear" button and sets all cells to DEAD. */ void GridWindow::handleClear() { for(unsigned int row=0; row < cells.size(); row++) // Loops through current rows' cells. { for(unsigned int col=0; col < cells[row].size(); col++) { GridCell *cell = cells[row][col]; // Grab the current cell & set its value to dead. cell->setType(DEAD); } } } /* SLOT method for handling clicks on the "start" button. Receives "clicked" signals on the "start" button and begins game simulation. */ void GridWindow::handleStart() { this->timer = new QTimer(this); // Creates new timer. connect(this->timer, SIGNAL(timeout()), this, SLOT(timerFired())); // Connect "timerFired" method class to the "timeout" signal fired by the timer. this->timer->start(500); // Timer to fire every 500 milliseconds. } /* SLOT method for handling clicks on the "pause" button. Receives "clicked" signals on the "pause" button and stops the game simulation. */ void GridWindow::handlePause() { this->timer->stop(); // Stops the timer. delete this->timer; // Deletes timer. } // Accessor method - Gets the 2D vector of grid cells. std::vector<std::vector<GridCell*> >& GridWindow::getCells() { return this->cells; } void GridWindow::timerFired() { // I'm not sure how to write this code. // I want to take the original vector-vector, and also make a new, empty vector-vector of the same size. // I would then go through the code below with the original vector, and apply the rules to the new vector-vector. // Finally, I would make the new vector-vecotr the original vector-vector. (That would be one step in the simulation.) cout << cells[1][2]; /* for (unsigned int m = 0; m < original.size(); m++) { for (unsigned int n = 0; n < original.at(m).size(); n++) { unsigned int neighbors = 0; //Begin counting number of neighbors. if (original[m-1][n-1].getType() == LIVE) // If a cell next to [i][j] is LIVE, add one to the neighbor count. neighbors += 1; if (original[m-1][n].getType() == LIVE) neighbors += 1; if (original[m-1][n+1].getType() == LIVE) neighbors += 1; if (original[m][n-1].getType() == LIVE) neighbors += 1; if (original[m][n+1].getType() == LIVE) neighbors += 1; if (original[m+1][n-1].getType() == LIVE) neighbors += 1; if (original[m+1][n].getType() == LIVE) neighbors += 1; if (original[m+1][n+1].getType() == LIVE) neighbors += 1; if (original[m][n].getType() == LIVE && neighbors < 2) // Apply game rules to cells: Create new, updated grid with the roundtwo vector. roundtwo[m][n].setType(LIVE); else if (original[m][n].getType() == LIVE && neighbors > 3) roundtwo[m][n].setType(DEAD); else if (original[m][n].getType() == LIVE && (neighbors == 2 || neighbors == 3)) roundtwo[m][n].setType(LIVE); else if (original[m][n].getType() == DEAD && neighbors == 3) roundtwo[m][n].setType(LIVE); } }*/ }

    Read the article

  • A Custom View Engine with Dynamic View Location

    - by imran_ku07
        Introduction:          One of the nice feature of ASP.NET MVC framework is its pluggability. This means you can completely replace the default view engine(s) with a custom one. One of the reason for using a custom view engine is to change the default views location and sometimes you need to change the views location at run-time. For doing this, you can extend the default view engine(s) and then change the default views location variables at run-time.  But, you cannot directly change the default views location variables at run-time because they are static and shared among all requests. In this article, I will show you how you can dynamically change the views location without changing the default views location variables at run-time.       Description:           Let's say you need to synchronize the views location with controller name and controller namespace. So, instead of searching to the default views location(Views/ControllerName/ViewName) to locate views, this(these) custom view engine(s) will search in the Views/ControllerNameSpace/ControllerName/ViewName folder to locate views.           First of all create a sample ASP.NET MVC 3 application and then add these custom view engines to your application,   public class MyRazorViewEngine : RazorViewEngine { public MyRazorViewEngine() : base() { AreaViewLocationFormats = new[] { "~/Areas/{2}/Views/%1/{1}/{0}.cshtml", "~/Areas/{2}/Views/%1/{1}/{0}.vbhtml", "~/Areas/{2}/Views/%1/Shared/{0}.cshtml", "~/Areas/{2}/Views/%1/Shared/{0}.vbhtml" }; AreaMasterLocationFormats = new[] { "~/Areas/{2}/Views/%1/{1}/{0}.cshtml", "~/Areas/{2}/Views/%1/{1}/{0}.vbhtml", "~/Areas/{2}/Views/%1/Shared/{0}.cshtml", "~/Areas/{2}/Views/%1/Shared/{0}.vbhtml" }; AreaPartialViewLocationFormats = new[] { "~/Areas/{2}/Views/%1/{1}/{0}.cshtml", "~/Areas/{2}/Views/%1/{1}/{0}.vbhtml", "~/Areas/{2}/Views/%1/Shared/{0}.cshtml", "~/Areas/{2}/Views/%1/Shared/{0}.vbhtml" }; ViewLocationFormats = new[] { "~/Views/%1/{1}/{0}.cshtml", "~/Views/%1/{1}/{0}.vbhtml", "~/Views/%1/Shared/{0}.cshtml", "~/Views/%1/Shared/{0}.vbhtml" }; MasterLocationFormats = new[] { "~/Views/%1/{1}/{0}.cshtml", "~/Views/%1/{1}/{0}.vbhtml", "~/Views/%1/Shared/{0}.cshtml", "~/Views/%1/Shared/{0}.vbhtml" }; PartialViewLocationFormats = new[] { "~/Views/%1/{1}/{0}.cshtml", "~/Views/%1/{1}/{0}.vbhtml", "~/Views/%1/Shared/{0}.cshtml", "~/Views/%1/Shared/{0}.vbhtml" }; } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { var nameSpace = controllerContext.Controller.GetType().Namespace; return base.CreatePartialView(controllerContext, partialPath.Replace("%1", nameSpace)); } protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { var nameSpace = controllerContext.Controller.GetType().Namespace; return base.CreateView(controllerContext, viewPath.Replace("%1", nameSpace), masterPath.Replace("%1", nameSpace)); } protected override bool FileExists(ControllerContext controllerContext, string virtualPath) { var nameSpace = controllerContext.Controller.GetType().Namespace; return base.FileExists(controllerContext, virtualPath.Replace("%1", nameSpace)); } } public class MyWebFormViewEngine : WebFormViewEngine { public MyWebFormViewEngine() : base() { MasterLocationFormats = new[] { "~/Views/%1/{1}/{0}.master", "~/Views/%1/Shared/{0}.master" }; AreaMasterLocationFormats = new[] { "~/Areas/{2}/Views/%1/{1}/{0}.master", "~/Areas/{2}/Views/%1/Shared/{0}.master", }; ViewLocationFormats = new[] { "~/Views/%1/{1}/{0}.aspx", "~/Views/%1/{1}/{0}.ascx", "~/Views/%1/Shared/{0}.aspx", "~/Views/%1/Shared/{0}.ascx" }; AreaViewLocationFormats = new[] { "~/Areas/{2}/Views/%1/{1}/{0}.aspx", "~/Areas/{2}/Views/%1/{1}/{0}.ascx", "~/Areas/{2}/Views/%1/Shared/{0}.aspx", "~/Areas/{2}/Views/%1/Shared/{0}.ascx", }; PartialViewLocationFormats = ViewLocationFormats; AreaPartialViewLocationFormats = AreaViewLocationFormats; } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { var nameSpace = controllerContext.Controller.GetType().Namespace; return base.CreatePartialView(controllerContext, partialPath.Replace("%1", nameSpace)); } protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { var nameSpace = controllerContext.Controller.GetType().Namespace; return base.CreateView(controllerContext, viewPath.Replace("%1", nameSpace), masterPath.Replace("%1", nameSpace)); } protected override bool FileExists(ControllerContext controllerContext, string virtualPath) { var nameSpace = controllerContext.Controller.GetType().Namespace; return base.FileExists(controllerContext, virtualPath.Replace("%1", nameSpace)); } }             Here, I am extending the RazorViewEngine and WebFormViewEngine class and then appending /%1 in each views location variable, so that we can replace /%1 at run-time. I am also overriding the FileExists, CreateView and CreatePartialView methods. In each of these method implementation, I am replacing /%1 with controller namespace. Now, just register these view engines in Application_Start method in Global.asax.cs file,   protected void Application_Start() { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new MyRazorViewEngine()); ViewEngines.Engines.Add(new MyWebFormViewEngine()); ................................................ ................................................ }             Now just create a controller and put this controller's view inside Views/ControllerNameSpace/ControllerName folder and then run this application. You will find that everything works just fine.       Summary:          ASP.NET MVC uses convention over configuration to locate views. For many applications this convention to locate views is acceptable. But sometimes you may need to locate views at run-time. In this article, I showed you how you can dynamically locate your views by using a custom view engine. I am also attaching a sample application. Hopefully you will enjoy this article too. SyntaxHighlighter.all()  

    Read the article

  • Enumerating all strings in resx

    - by Erik Hesselink
    We would like to enumerate all strings in a resource file in .NET (resx file). We want this to generate a javascript object containing all these key-value pairs. We do this now for satellite assemblies with code like this (this is VB.NET, but any example code is fine): Dim rm As ResourceManager rm = New ResourceManager([resource name], [your assembly]) Dim Rs As ResourceSet Rs = rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, True, True) For Each Kvp As DictionaryEntry In Rs [Write out Kvp.Key and Kvp.Value] Next However, we haven't found a way to do this for .resx files yet, sadly. How can we enumerate all localization strings in a resx file? UPDATE: Following Dennis Myren's comment and the ideas from here, I built a ResXResourceManager. Now I can do the same with .resx files as I did with the embedded resources. Here is the code. Note that Microsoft made a needed constructor private, so I use reflection to access it. You need full trust when using this. Imports System.Globalization Imports System.Reflection Imports System.Resources Imports System.Windows.Forms Public Class ResXResourceManager Inherits ResourceManager Public Sub New(ByVal BaseName As String, ByVal ResourceDir As String) Me.New(BaseName, ResourceDir, GetType(ResXResourceSet)) End Sub Protected Sub New(ByVal BaseName As String, ByVal ResourceDir As String, ByVal UsingResourceSet As Type) Dim BaseType As Type = Me.GetType().BaseType Dim Flags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance Dim Constructor As ConstructorInfo = BaseType.GetConstructor(Flags, Nothing, New Type() { GetType(String), GetType(String), GetType(Type) }, Nothing) Constructor.Invoke(Me, Flags, Nothing, New Object() { BaseName, ResourceDir, UsingResourceSet }, Nothing) End Sub Protected Overrides Function GetResourceFileName(ByVal culture As CultureInfo) As String Dim FileName As String FileName = MyBase.GetResourceFileName(culture) If FileName IsNot Nothing AndAlso FileName.Length > 10 Then Return FileName.Substring(0, FileName.Length - 10) & ".resx" End If Return Nothing End Function End Class

    Read the article

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