Search Results

Search found 1234 results on 50 pages for 'enum'.

Page 42/50 | < Previous Page | 38 39 40 41 42 43 44 45 46 47 48 49  | Next Page >

  • Compile time type determination in C++

    - by dicroce
    A coworker recently showed me some code that he found online. It appears to allow compile time determination of whether a type has an "is a" relationship with another type. I think this is totally awesome, but I have to admit that I'm clueless as to how this actually works. Can anyone explain this to me? template<typename BaseT, typename DerivedT> inline bool isRelated(const DerivedT&) { DerivedT derived(); char test(const BaseT&); // sizeof(test()) == sizeof(char) char (&test(...))[2]; // sizeof(test()) == sizeof(char[2]) struct conversion { enum { exists = (sizeof(test(derived())) == sizeof(char)) }; }; return conversion::exists; } Once this function is defined, you can use it like this: #include <iostream> class base {}; class derived : public base {}; class unrelated {}; int main() { base b; derived d; unrelated u; if( isRelated<base>( b ) ) std::cout << "b is related to base" << std::endl; if( isRelated<base>( d ) ) std::cout << "d is related to base" << std::endl; if( !isRelated<base>( u ) ) std::cout << "u is not related to base" << std::endl; }

    Read the article

  • Can a custom MFC window/dialog be a class template instantiation?

    - by John
    There's a bunch of special macros that MFC uses when creating dialogs, and in my quick tests I'm getting weird errors trying to compile a template dialog class. Is this likely to be a big pain to achieve? Here's what I tried: MyDlg.h template <class W> class CMyDlg : public CDialog { typedef CDialog super; DECLARE_DYNAMIC(CMyDlg <W>) public: CMyDlg (CWnd* pParent); // standard constructor virtual ~CMyDlg (); // Dialog Data enum { IDD = IDD_MYDLG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() private: W *m_pWidget; //W will always be a CDialog }; IMPLEMENT_DYNAMIC(CMyDlg<W>, super) <------------------- template <class W> CMyDlg<W>::CMyDlg(CWnd* pParent) : super(CMyDlg::IDD, pParent) { m_pWidget = new W(this); } I get a whole bunch of errors but main one appears to be: error C2955: 'CMyDlg' : use of class template requires template argument list I tried using some specialised template versions of macros but it doesn't help much, other errors change but this one remains. Note my code is all in one file, since C++ templates don't like .h/.cpp like normal. I'm assuming someone must have done this in the past, possibly creating custom versions of macros, but I can't find it by searching, since 'template' has other meanings.

    Read the article

  • Incompatible type for argument 1 of 'setBounds'

    - by Brandon
    I am trying to do my own custom classes and learn C and Objective C. I'm recieving the error that there is an incompatible type for argument 1. I've defined a struct and class like this: typedef enum { kRedColor, kGreenColor, kBlueColor } ShapeColor; typedef struct { int x, y, width, height; } ShapeRect; @interface Shape : NSObject { ShapeColor fillColor; ShapeRect bounds; } - (void) setFillColor: (ShapeColor) fillColor; - (void) setBounds: (ShapeRect) bounds; - (void) draw; @end // Shape Then I import the Shape.h file(code above) and try and create a shape like this: id shapes[4]; // I'm different! ShapeRect rect0 = { 0, 0, 10, 30 }; shapes[0] = [Shape new]; [shapes[0] setBounds: rect0]; I get the error that setBounds is incompatible. For some reason it isn't looking at the Shape.h class for the setBounds method and it is instead looking at the default setBounds method? Is there something I'm doing wrong? Thanks!

    Read the article

  • How much does an InnoDB table benefit from having fixed-length rows?

    - by Philip Eve
    I know that dependent on the database storage engine in use, a performance benefit can be found if all of the rows in the table can be guaranteed to be the same length (by avoiding nullable columns and not using any VARCHAR, TEXT or BLOB columns). I'm not clear on how far this applies to InnoDB, with its funny table arrangements. Let's give an example: I have the following table CREATE TABLE `PlayerGameRcd` ( `User` SMALLINT UNSIGNED NOT NULL, `Game` MEDIUMINT UNSIGNED NOT NULL, `GameResult` ENUM('Quit', 'Kicked by Vote', 'Kicked by Admin', 'Kicked by System', 'Finished 5th', 'Finished 4th', 'Finished 3rd', 'Finished 2nd', 'Finished 1st', 'Game Aborted', 'Playing', 'Hide' ) NOT NULL DEFAULT 'Playing', `Inherited` TINYINT NOT NULL, `GameCounts` TINYINT NOT NULL, `Colour` TINYINT UNSIGNED NOT NULL, `Score` SMALLINT UNSIGNED NOT NULL DEFAULT 0, `NumLongTurns` TINYINT UNSIGNED NOT NULL DEFAULT 0, `Notes` MEDIUMTEXT, `CurrentOccupant` TINYINT UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (`Game`, `User`), UNIQUE KEY `PGR_multi_uk` (`Game`, `CurrentOccupant`, `Colour`), INDEX `Stats_ind_PGR` (`GameCounts`, `GameResult`, `Score`, `User`), INDEX `GameList_ind_PGR` (`User`, `CurrentOccupant`, `Game`, `Colour`), CONSTRAINT `Constr_PlayerGameRcd_User_fk` FOREIGN KEY `User_fk` (`User`) REFERENCES `User` (`UserID`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `Constr_PlayerGameRcd_Game_fk` FOREIGN KEY `Game_fk` (`Game`) REFERENCES `Game` (`GameID`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_general_ci The only column that is nullable is Notes, which is MEDIUMTEXT. This table presently has 33097 rows (which I appreciate is small as yet). Of these rows, only 61 have values in Notes. How much of an improvement might I see from, say, adding a new table to store the Notes column in and performing LEFT JOINs when necessary?

    Read the article

  • How can I compile .NET 3.5 C# code on a system without Visual Studio?

    - by JimEvans
    I have some C# code that uses some constructs specific to .NET 3.5. When you install the .NET Framework distribution, you get the C# compiler installed with it (csc.exe). Even if I specify the csc.exe in C:\Windows\Microsoft.NET\Framework\v3.5, I cannot compile the code on a computer with only the .NET Framework installed, but not Visual Studio. I am able to compile code that uses v2.0 constructs without difficulty. How can I accomplish this? Here is a sample that demonstrates my problem: using System; class Program { public static void Main() { // The MacOSX value to the PlatformID enum was added after // .NET v2.0 if (Environment.OSVersion.Platform == PlatformID.MacOSX) { Console.WriteLine("Found mac"); } Console.WriteLine("Simple program"); } } When compiling this code using csc.exe, I receive the following error: test.cs(9, 58): error CS0117: 'System.PlatformID' does not contain a definition for 'MacOSX' When executing csc.exe /? I receive the banner: Microsoft (R) Visual C# 2008 Compiler version 3.5.21022.8 for Microsoft (R) .NET Framework version 3.5 Copyright (C) Microsoft Corporation. All rights reserved.

    Read the article

  • Handling Apache Thrift list/map Return Types in C++

    - by initzero
    First off, I'll say I'm not the most competent C++ programmer, but I'm learning, and enjoying the power of Thrift. I've implemented a Thrift Service with some basic functions that return void, i32, and list. I'm using a Python client controlled by a Django web app to make RPC calls and it works pretty well. The generated code is pretty straight forward, except for list returns: namespace cpp Remote enum N_PROTO { N_TCP, N_UDP, N_ANY } service Rcon { i32 ping() i32 KillFlows() i32 RestartDispatch() i32 PrintActiveFlows() i32 PrintActiveListeners(1:i32 proto) list<string> ListAllFlows() } The generated signatures from Rcon.h: int32_t ping(); int32_t KillFlows(); int32_t RestartDispatch(); int32_t PrintActiveFlows(); int32_t PrintActiveListeners(const int32_t proto); int64_t ListenerBytesReceived(const int32_t id); void ListAllFlows(std::vector<std::string> & _return); As you see, the ListAllFlows() function generated takes a reference to a vector of strings. I guess I expect it to return a vector of strings as laid out in the .thrift description. I'm wondering if I am meant to provide the function a vector of strings to modify and then Thrift will handle returning it to my client despite the function returning void. I can find absolutely no resources or example usages of Thrift list< types in C++. Any guidance would be appreciated.

    Read the article

  • Can this line of code really throw an IndexOutOfRange exception?

    - by Jonathan M
    I am getting an IndexOutOfRange exception on the following line of code: var searchLastCriteria = (SearchCriteria)Session.GetSafely(WebConstants.KeyNames.SEARCH_LAST_CRITERIA); I'll explain the above here: SearchCriteria is an Enum with only two values Session is the HttpSessionState GetSafely is an extension method that looks like this: public static object GetSafely(this HttpSessionState source, string key) { try { return source[key]; } catch (Exception exc) { log.Info(exc); return null; } } WebConstants.KeyNames.SEARCH_LAST_CRITERIA is simply a constant I've tried everything to replicate this error, but I cannot reproduce it. I am beginning to think the stack trace is wrong. I thought perhaps the exception was actually coming from the GetSafely call, but it is swallowing the exceptions, so that can't be the case, and even if it was, it should show up in the stack trace. Is there anything in the line of code above that could possible throw an IndexOutOfRange exception? I know the line will throw an NullReferenceException if GetSafely returns null, and it will also throw an InvalidCastException if it returns anything that cannot be cast to SearchCriteria, but an IndexOutOfRange exception? I'm scratching my head here. Here is the stack trace: $LOG--> 2010-06-11 07:01:33,814 [ERROR] SERVERA (14) Web.Global - Index was outside the bounds of the array. System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array. at IterateSearchResult(Boolean next) in C:\Projects\Web\UserControls\AccountHeader.ascx.cs:line 242 at nextAccountLink_Click(Object sender, EventArgs e) in C:\Projects\Web\UserControls\AccountHeader.ascx.cs:line 232

    Read the article

  • How to support comparisons for QVariant objects containing a custom type?

    - by Tyler McHenry
    According to the Qt documentation, QVariant::operator== does not work as one might expect if the variant contains a custom type: bool QVariant::operator== ( const QVariant & v ) const Compares this QVariant with v and returns true if they are equal; otherwise returns false. In the case of custom types, their equalness operators are not called. Instead the values' addresses are compared. How are you supposed to get this to behave meaningfully for your custom types? In my case, I'm storing an enumerated value in a QVariant, e.g. In a header: enum MyEnum { Foo, Bar }; Q_DECLARE_METATYPE(MyEnum); Somewhere in a function: QVariant var1 = QVariant::fromValue<MyEnum>(Foo); QVariant var2 = QVariant::fromValue<MyEnum>(Foo); assert(var1 == var2); // Fails! What do I need to do differently in order for this assertion to be true? I understand why it's not working -- each variant is storing a separate copy of the enumerated value, so they have different addresses. I want to know how I can change my approach to storing these values in variants so that either this is not an issue, or so that they do both reference the same underlying variable. It don't think it's possible for me to get around needing equality comparisons to work. The context is that I am using this enumeration as the UserData in items in a QComboBox and I want to be able to use QComboBox::findData to locate the item index corresponding to a particular enumerated value.

    Read the article

  • Compare Properties automatically

    - by juergen d
    I want to get the names of all properties that changed for matching objects. I have these (simplified) classes: public enum PersonType { Student, Professor, Employee } class Person { public string Name { get; set; } public PersonType Type { get; set; } } class Student : Person { public string MatriculationNumber { get; set; } } class Subject { public string Name { get; set; } public int WeeklyHours { get; set; } } class Professor : Person { public List<Subject> Subjects { get; set; } } Now I want to get the objects where the Property values differ: List<Person> oldPersonList = ... List<Person> newPersonList = ... List<Difference> = GetDifferences(oldPersonList, newPersonList); public List<Difference> GetDifferences(List<Person> oldP, List<Person> newP) { //how to check the properties without casting and checking //for each type and individual property?? //can this be done with Reflection even in Lists?? } In the end I would like to have a list of Differences like this: class Difference { public List<string> ChangedProperties { get; set; } public Person NewPerson { get; set; } public Person OldPerson { get; set; } } The ChangedProperties should contain the name of the changed properties.

    Read the article

  • What are the hibernate annotations used to persist a Map with an enumerated type as a key?

    - by Jason Novak
    I am having trouble getting the right hibernate annotations to use on a Map with an enumerated class as a key. Here is a simplified (and extremely contrived) example. public class Thing { public String id; public Letter startLetter; public Map<Letter,Double> letterCounts = new HashMap<Letter, Double>(); } public enum Letter { A, B, C, D } Here are my current annotations on Thing @Entity public class Thing { @Id public String id; @Enumerated(EnumType.STRING) public Letter startLetter; @CollectionOfElements @JoinTable(name = "Thing_letterFrequencies", joinColumns = @JoinColumn(name = "thingId")) @MapKey(columns = @Column(name = "letter", nullable = false)) @Column(name = "count") public Map<Letter,Double> letterCounts = new HashMap<Letter, Double>(); } Hibernate generates the following DDL to create the tables for my MySql database create table Thing (id varchar(255) not null, startLetter varchar(255), primary key (id)) type=InnoDB; create table Thing_letterFrequencies (thingId varchar(255) not null, count double precision, letter tinyblob not null, primary key (thingId, letter)) type=InnoDB; Notice that hibernate tries to define letter (my map key) as a tinyblob, however it defines startLetter as a varchar(255) even though both are of the enumerated type Letter. When I try to create the tables I see the following error BLOB/TEXT column 'letter' used in key specification without a key length I googled this error and it appears that MySql has issues when you try to make a tinyblob column part of a primary key, which is what hibernate needs to do with the Thing_letterFrequencies table. So I would rather have letter mapped to a varchar(255) the way startLetter is. Unfortunately, I've been fussing with the MapKey annotation for a while now and haven't been able to make this work. I've also tried @MapKeyManyToMany(targetEntity=Product.class) without success. Can anyone tell me what are the correct annotations for my letterCounts map so that hibernate will treat the letterCounts map key the same way it does startLetter?

    Read the article

  • Databinding to the DataGridView (Enums + Collections)

    - by Ian
    I'm after a little help with the techniques to use for Databinding. It's been quite a while since I used any proper data binding and want to try and do something with the DataGridView. I'm trying to configure as much as possible so that I can simply designed the DatagridView through the form editor, and then use a custom class that exposes all my information. The sort of information I've got is as follows: public class Result { public String Name { get; set; } public Boolean PK { get; set; } public MyEnum EnumValue { get; set; } public IList<ResultInfos> { get; set; } } public class ResultInfos { get; set; } { public class Name { get; set; } public Int Value { get; set; } public override String ToString() { return Name + " : " Value.ToString(); } } I can bind to the simple information without any problem. I want to bind to the EnumValue with a DataGridViewComboBoxColumn, but when I set the DataPropertyName I get exceptions saying the enum values aren't valid. Then comes the ResultInfo collection. Currently I can't figure out how to bind to this and display my items, again really I want this to be a combobox, where the 1st Item is selected. Anyone any suggestions on what I'm doing wrong? Thanks

    Read the article

  • C++ Operator Ambiguity

    - by Scott
    Forgive me, for I am fairly new to C++, but I am having some trouble regarding operator ambiguity. I think it is compiler-specific, for the code compiled on my desktop. However, it fails to compile on my laptop. I think I know what's going wrong, but I don't see an elegant way around it. Please let me know if I am making an obvious mistake. Anyhow, here's what I'm trying to do: I have made my own vector class called Vector4 which looks something like this: class Vector4 { private: GLfloat vector[4]; ... } Then I have these operators, which are causing the problem: operator GLfloat* () { return vector; } operator const GLfloat* () const { return vector; } GLfloat& operator [] (const size_t i) { return vector[i]; } const GLfloat& operator [] (const size_t i) const { return vector[i]; } I have the conversion operator so that I can pass an instance of my Vector4 class to glVertex3fv, and I have subscripting for obvious reasons. However, calls that involve subscripting the Vector4 become ambiguous to the compiler: enum {x, y, z, w} Vector4 v(1.0, 2.0, 3.0, 4.0); glTranslatef(v[x], v[y], v[z]); Here are the candidates: candidate 1: const GLfloat& Vector4:: operator[](size_t) const candidate 2: operator[](const GLfloat*, int) <built-in> Why would it try to convert my Vector4 to a GLfloat* first when the subscript operator is already defined on Vector4? Is there a simple way around this that doesn't involve typecasting? Am I just making a silly mistake? Thanks for any help in advance.

    Read the article

  • Render different view depending on the type of the data

    - by Miau
    Hi there So lets suppose we have an action in a controller that looks a bit like this: public ViewResult SomeAction(int id) { var data = _someService.GetData(id); ... //create new view model based on the data here return View(viewModel); } What I m trying to figure out is the best way to render a diferent view based on the type fo the data. the "_someService.GetData method returns an data that knows its out type (ie not only you can do typeof(data) but also you can do data.DataType and you ll get an enum value so I could achieve what I m trying to do doing something kinda like this public ViewResult SomeAction(int id) { var data = _someService.GetData(id); //I m mapping fields to the viewModel here var viewModel = GetViewModel(data); swtich(data.DataType) case DataType.TypeOne: return View("TypeOne", viewModel); break; ... } But this does not seem to be the nicest way, (I dont event know if it would work) Is this the way to go? Should I use some sort of RenderPartial Aproach? after all , waht will change in the view is mostly the order of the data (ie the rest of the view would be quite similar) Cheers

    Read the article

  • Is it legal to take sealed .NET framework class source and extend it?

    - by Giedrius
    To be short, I'm giving very specific example, but I'm interested in general situation. There is a FtpWebRequest class in .NET framework and it is missing some of new FTP operations, like MFCT. It is ok in a sense that this operation is still in draft mode, but it is not ok in a sense, that FtpWebRequest is sealed and there's no other way (at least I don't see it) to extend it with this new operation. Easiest way to do it would be take FtpWebRequest class source from .NET reference sources and extend it, in such way will be kept all the consistence in naming, implementation, etc. Question is how much legal it is? I won't sell this class as a product, I can publish my changes on web - nothing to hide here. If it is not legal, can I take this class source from mono and include in native .net project? Did you had similar case and how you solved it? Update: as long as extension method is offered, I'm pasting source from .NET framework which should show that extension methods are not the solution. So there's a property Method, where you can pass FTP command: public override string Method { get { return m_MethodInfo.Method; } set { if (String.IsNullOrEmpty(value)) { throw new ArgumentException(SR.GetString(SR.net_ftp_invalid_method_name), "value"); } if (InUse) { throw new InvalidOperationException(SR.GetString(SR.net_reqsubmitted)); } try { m_MethodInfo = FtpMethodInfo.GetMethodInfo(value); } catch (ArgumentException) { throw new ArgumentException(SR.GetString(SR.net_ftp_unsupported_method), "value"); } } } As you can see there FtpMethodInfo.GetMethodInfo(value) call in setter, which basically validates value against internal enum static array. Update 2: Checked mono implementation and it is not exact replica of native code + it does not implement some of the things.

    Read the article

  • Merging ILists to bind on datagridview to avoid using a database view

    - by P.Bjorklund
    In the form we have this where IntaktsBudgetsType is a poorly named enum that only specifies wether to populate the datagridview after customer or product (You do the budgeting either after product or customer) private void UpdateGridView() { bs = new BindingSource(); bs.DataSource = intaktsbudget.GetDataSource(this.comboBoxKundID.Text, IntaktsBudgetsType.PerKund); dataGridViewIntaktPerKund.DataSource = bs; } This populates the datagridview with a database view that merge the product, budget and customer tables. The logic has the following method to get the correct set of IList from the repository which only does GetTable<T>.ToList<T> public IEnumerable<IntaktsBudgetView> GetDataSource(string id, IntaktsBudgetsType type) { IList<IntaktsBudgetView> list = repository.SelectTable<IntaktsBudgetView>(); switch (type) { case IntaktsBudgetsType.PerKund: return from i in list where i.kundId == id select i; case IntaktsBudgetsType.PerProdukt: return from i in list where i.produktId == id select i; } return null; } Now I don't want to use a database view since that is read-only and I want to be able to perform CRUD actions on the datagridview. I could build a class that acts as a wrapper for the whole thing and bind the different table values to class properties but that doesn't seem quite right since I would have to do this for every single thing that requires "the merge". Something pretty important (and probably basic) is missing the the thought process but after spending a weekend on google and in books I give up and turn to the SO community.

    Read the article

  • App Engine - Query using a class member as parameter

    - by Zach
    I have a simple class, relevant details below: @PersistenceCapable(identityType = IdentityType.APPLICATION) public class SimpleCategory implements Serializable{ ... public static enum type{ Course, Category, Cuisine } @Persistent public type t; ... } I am attempting to query all SimpleCategory objects of the same type. public SimpleCategory[] getCategories(SimpleCategory.type type) { PersistenceManager pm = PMF.get().getPersistenceManager(); try{ Query q = pm.newQuery(SimpleCategory.class); q.setFilter("t == categoryType"); q.declareParameters("SimpleCategory.type categoryType"); List<SimpleCategory> cats = (List<SimpleCategory>) q.execute(type); ... } This results in a ClassNotResolvedException for SimpleCategory.type. The google hits I've found so far recommended to: Use query.declareImports to specify the class i.e. q.declareImports("com.test.zach.SimpleCategory.type"); Specify the fully qualified name of SimpleCategory in declareParameters Neither of these suggestions has worked. By removing .type and recompiling, I can verify that declareParameters can see SimpleCategory just fine, it simply cannot see the SimpleCategory.type, despite the fact that the remainder of the method has full visibility to it. What am I missing?

    Read the article

  • Sorting by some field and fetching whole tree from DB

    - by Niaxon
    Hello everyone, I am trying to do file browser in a tree form and have a problem to sort it somehow. I use PHP and MySQL for that. I've created mixed (nested set + adjacency) table 'element' with the following fields: element_id, left_key, right_key, level, parent_id, element_name, element_type (enum: 'folder','file'), element_size. Let's not discuss right now that it is better to move information about element (name, type, size) into other table. Function to scan specified directory and fill table work correctly. Noteworthy, i am adding elements to tree in specific order: folders first and only files. After that i can easily fetch and display whole table on the page using simple query: SELECT * FROM element WHERE 1=1 ORDER BY left_key With the result of that query and another function i can generate correct html code (<ul><li>... and so on). Now back to the question (finally, huh?). I am struggling to add sorting functionality. For example i want to order my result by size. Here i need to keep in my mind whole hierarchy of tree and rule: folders first, files later. I believe i can do that by generating in PHP recursive query: SELECT * FROM element WHERE parent_id = {$parentId} ORDER BY element_type (so folders would be first), size (or name for example) After that for each result which is folder i will send another query to get it's content. Also it's possible to fetch whole tree by left_key and after that sort it in PHP as array but i guess that would be worse :) I wonder if there is better and more efficient way to do such thing?

    Read the article

  • Can a custom MFC window/dialog be a template class?

    - by John
    There's a bunch of special macros that MFC uses when creating dialogs, and in my quick tests I'm getting weird errors trying to compile a template dialog class. Is this likely to be a big pain to achieve? Here's what I tried: MyDlg.h template <class W> class CMyDlg : public CDialog { typedef CDialog super; DECLARE_DYNAMIC(CMyDlg <W>) public: CMyDlg (CWnd* pParent); // standard constructor virtual ~CMyDlg (); // Dialog Data enum { IDD = IDD_MYDLG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() private: W *m_pWidget; //W will always be a CDialog }; IMPLEMENT_DYNAMIC(CMyDlg<W>, super) <------------------- template <class W> CMyDlg<W>::CMyDlg(CWnd* pParent) : super(CMyDlg::IDD, pParent) { m_pWidget = new W(this); } I get a whole bunch of errors but main one appears to be: error C2955: 'CMyDlg' : use of class template requires template argument list I tried using some specialised template versions of macros but it doesn't help much, other errors change but this one remains. Note my code is all in one file, since C++ templates don't like .h/.cpp like normal.

    Read the article

  • Asp.Net MVC3 - How create Dynamic DropDownList

    - by Bibo
    I found many articles on this but still I don´t know how exactly to do this. I am trying to create my own blog engine, I have View for create article (I am using EF and Code first) and now I must fill number of category in which article should be add but I want to change it to dropdownlist with names of categories. My model looks this: public class Article { public int ArticleID { get; set; } [Required] public string Title { get; set; } [Required] public int CategoryID { get; set; } public DateTime Date { get; set; } [Required()] [DataType(DataType.MultilineText)] [AllowHtml] public string Text { get; set; } public virtual Category Category { get; set; } public IEnumerable<SelectListItem> Categories { get; set; } public virtual ICollection<Comment> Comments { get; set; } } public class Category { public int CategoryID { get; set; } [Required] public string Name { get; set; } public virtual ICollection<Article> Articles { get; set; } } I know I must use Enum (or I think) but I am not exactly sure how. I don´t know which tutorial from that I found is best for me.

    Read the article

  • Creating serializeable unique compile-time identifiers for arbitrary UDT's.

    - by Endiannes
    I would like a generic way to create unique compile-time identifiers for any C++ user defined types. for example: unique_id<my_type>::value == 0 // true unique_id<other_type>::value == 1 // true I've managed to implement something like this using preprocessor meta programming, the problem is, serialization is not consistent. For instance if the class template unique_id is instantiated with other_type first, then any serialization in previous revisions of my program will be invalidated. I've searched for solutions to this problem, and found several ways to implement this with non-consistent serialization if the unique values are compile-time constants. If RTTI or similar methods, like boost::sp_typeinfo are used, then the unique values are obviously not compile-time constants and extra overhead is present. An ad-hoc solution to this problem would be, instantiating all of the unique_id's in a separate header in the correct order, but this causes additional maintenance and boilerplate code, which is not different than using an enum unique_id{my_type, other_type};. A good solution to this problem would be using user-defined literals, unfortunately, as far as I know, no compiler supports them at this moment. The syntax would be 'my_type'_id; 'other_type'_id; with udl's. I'm hoping somebody knows a trick that allows implementing serialize-able unique identifiers in C++ with the current standard (C++03/C++0x), I would be happy if it works with the latest stable MSVC and GNU-G++ compilers, although I expect if there is a solution, it's not portable.

    Read the article

  • no default constructor exists for class

    - by MixedCoder
    #include "Includes.h" enum BlowfishAlgorithm { ECB, CBC, CFB64, OFB64, }; class Blowfish { public: struct bf_key_st { unsigned long P[18]; unsigned long S[1024]; }; Blowfish(BlowfishAlgorithm algorithm); void Dispose(); void SetKey(unsigned char data[]); unsigned char Encrypt(unsigned char buffer[]); unsigned char Decrypt(unsigned char buffer[]); char EncryptIV(); char DecryptIV(); private: BlowfishAlgorithm _algorithm; unsigned char _encryptIv[200]; unsigned char _decryptIv[200]; int _encryptNum; int _decryptNum; }; class GameCryptography { public: Blowfish _blowfish; GameCryptography(unsigned char key[]); void Decrypt(unsigned char packet[]); void Encrypt(unsigned char packet[]); Blowfish Blowfish; void SetKey(unsigned char k[]); void SetIvs(unsigned char i1[],unsigned char i2[]); }; GameCryptography::GameCryptography(unsigned char key[]) { } Error:IntelliSense: no default constructor exists for class "Blowfish" ???!

    Read the article

  • C++ universal data type

    - by Gokul
    I have a universal data type, which is passed by value, but does not maintain the type information. We store only pointers and basic data types(like int, float etc) inside this. Now for the first time, we need to store std::string inside this. So we decided to convert it into std::string* and store it. Then comes the problem of destruction. We don't like to copy the std::string every time. So i am thinking of an approach like this. Say the data type looks like this class Atom { public : enum flags { IS_STRING, IS_EMPTY, HAS_GOT_COPIED, MARKER }; private: void* m_value; std::bitset<MARKER> m_flags; public: ..... Atom( Atom& atm ) { atm.m_flags.set( HAS_GOT_COPIED ); ..... } ..... ~Atom() { if( m_flags.test(IS_STRING) && !m_flags.test(HAS_GOT_COPIED) ) { std::string* val = static_cast<std::string*>(m_value); delete val; } } }; Is this a good approach to find out whether there is no more reference to std::string*? Any comments.. Thanks, Gokul.

    Read the article

  • Persisting object changes from child form to parent form based on button press.

    - by Shyran
    I have created a form that is used for both adding and editing a custom object. Which mode the form takes is provided by an enum value passed from the calling code. I also pass in an object of the custom type. All of my controls at data bound to the specific properties of the custom object. When the form is in Add mode, this works great as when the controls are updated with data, the underlying object is as well. However, in Edit mode, I keep two variables of the custom object supplied by the calling code, the original, and a temporary one made through deep copying. The controls are then bound to the temporary copy, this makes it easy to discard the changes if the user clicks the Cancel button. What I want to know is how to persist those changes back to the original object if the user clicks the OK button, since there is now a disconnect because of the deep copying. I am trying to avoid implementing a internal property on the Add/Edit form if I can. Below is an example of my code: public AddEditCustomerDialog(Customer customer, DialogMode mode) { InitializeComponent(); InitializeCustomer(customer, mode); } private void InitializeCustomer(Customer customer, DialogMode mode) { this.customer = customer; if (mode == DialogMode.Edit) { this.Text = "Edit Customer"; this.tempCustomer = ObjectCopyHelper.DeepCopy(this.customer); this.customerListBindingSource.DataSource = this.tempCustomer; this.phoneListBindingSource.DataSource = this.tempCustomer.PhoneList; } else { this.customerListBindingSource.DataSource = this.customer; this.phoneListBindingSource.DataSource = this.customer.PhoneList; } }

    Read the article

  • How to get readable classname and title from HWND handle? in WinApi c++

    - by Marko29
    I am using the following enumchild proc to get hwnd of each window, the problem is that i am unable to somehow detect any info from each hwnd so i can do what i want with the ones that are detected as the ones i need. For example, how could i get window class name and the title of each window in the enum bellow? I tried something like.. BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lParam) { TCHAR className[MAX_PATH]; GetClassName(hwnd, cName, _countof(cName)); cout << cName; return TRUE; } It just returns the hexadec handle info and every single time it is same, shouldnt the GetClassName func change the cName into new handle each time? Also GetClassName function returns number of chars written to cName, i dont really see how this is useful to me? I need to get my cName in some readable format so i can do something like if(cName == TEXT("classnameiamlookingfor" && hwndtitle = TEXT("thetitlethatinterestsme") DOSOMETHINGWITHIT(); But all i get here is hexadec mess.

    Read the article

  • Solving algorithm for a simple problem

    - by maolo
    I'm searching for an algorithm (should be rather simple for you guys) that does nothing but solve the chicken or the egg problem. I need to implement this in C++. What I've got so far is: enum ChickenOrEgg { Chicken, Egg }; ChickenOrEgg WhatWasFirst( ) { ChickenOrEgg ret; // magic happens here return ret; } // testing #include <iostream> using namespace std; if ( WhatWasFirst( ) == Chicken ) { cout << "The chicken was first."; } else { cout << "The egg was first."; } cout << endl; Question: How could the pseudocode for the solving function look? Notes: This is not a joke, not even a bad one. Before you close this, think of why this isn't a perfectly valid question according to the SO rules. If someone here can actually implement an algorithm solving the problem he gets $500 in cookies from me (that's a hell lot of cookies!). Please don't tell me that this is my homework, what teacher would ever give his students homework like that?

    Read the article

< Previous Page | 38 39 40 41 42 43 44 45 46 47 48 49  | Next Page >