Search Results

Search found 236 results on 10 pages for 'hashset'.

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

  • JPA entities -- org.hibernate.TypeMismatchException

    - by shane lee
    Environment: JDK 1.6, JEE5 Hibernate Core 3.3.1.GA, Hibernate Annotations 3.4.0.GA DB:Informix Used reverse engineering to create my persistence entities from db schema [NB:This is a schema in work i cannot change] Getting exception when selecting list of basic_auth_accounts org.hibernate.TypeMismatchException: Provided id of the wrong type for class ebusiness.weblogic.model.UserAccounts. Expected: class ebusiness.weblogic.model.UserAccountsId, got class ebusiness.weblogic.model.BasicAuthAccountsId Both basic_auth_accounts and user_accounts have composite primary keys and one-to-one relationships. Any clues what to do here? This is pretty important that i get this to work. Cannot find any substantial solution on the net, some say to create an ID class which hibernate has done, and some say not to have a one-to-one relationship. Please help me!! /** * BasicAuthAccounts generated by hbm2java */ @Entity @Table(name = "basic_auth_accounts", schema = "ebusdevt", catalog = "ebusiness_dev", uniqueConstraints = @UniqueConstraint(columnNames = { "realm_type_id", "realm_qualifier", "account_name" })) public class BasicAuthAccounts implements java.io.Serializable { private BasicAuthAccountsId id; private UserAccounts userAccounts; private String accountName; private String hashedPassword; private boolean passwdChangeReqd; private String hashMethodId; private int failedAttemptNo; private Date failedAttemptDate; private Date lastAccess; public BasicAuthAccounts() { } public BasicAuthAccounts(UserAccounts userAccounts, String accountName, String hashedPassword, boolean passwdChangeReqd, String hashMethodId, int failedAttemptNo) { this.userAccounts = userAccounts; this.accountName = accountName; this.hashedPassword = hashedPassword; this.passwdChangeReqd = passwdChangeReqd; this.hashMethodId = hashMethodId; this.failedAttemptNo = failedAttemptNo; } public BasicAuthAccounts(UserAccounts userAccounts, String accountName, String hashedPassword, boolean passwdChangeReqd, String hashMethodId, int failedAttemptNo, Date failedAttemptDate, Date lastAccess) { this.userAccounts = userAccounts; this.accountName = accountName; this.hashedPassword = hashedPassword; this.passwdChangeReqd = passwdChangeReqd; this.hashMethodId = hashMethodId; this.failedAttemptNo = failedAttemptNo; this.failedAttemptDate = failedAttemptDate; this.lastAccess = lastAccess; } @EmbeddedId @AttributeOverrides( { @AttributeOverride(name = "realmTypeId", column = @Column(name = "realm_type_id", nullable = false, length = 32)), @AttributeOverride(name = "realmQualifier", column = @Column(name = "realm_qualifier", nullable = false, length = 32)), @AttributeOverride(name = "accountId", column = @Column(name = "account_id", nullable = false)) }) public BasicAuthAccountsId getId() { return this.id; } public void setId(BasicAuthAccountsId id) { this.id = id; } @OneToOne(fetch = FetchType.LAZY) @PrimaryKeyJoinColumn @NotNull public UserAccounts getUserAccounts() { return this.userAccounts; } public void setUserAccounts(UserAccounts userAccounts) { this.userAccounts = userAccounts; } /** * BasicAuthAccountsId generated by hbm2java */ @Embeddable public class BasicAuthAccountsId implements java.io.Serializable { private String realmTypeId; private String realmQualifier; private long accountId; public BasicAuthAccountsId() { } public BasicAuthAccountsId(String realmTypeId, String realmQualifier, long accountId) { this.realmTypeId = realmTypeId; this.realmQualifier = realmQualifier; this.accountId = accountId; } /** * UserAccounts generated by hbm2java */ @Entity @Table(name = "user_accounts", schema = "ebusdevt", catalog = "ebusiness_dev") public class UserAccounts implements java.io.Serializable { private UserAccountsId id; private Realms realms; private UserDetails userDetails; private Integer accessLevel; private String status; private boolean isEdge; private String role; private boolean chargesAccess; private Date createdTimestamp; private Date lastStatusChangeTimestamp; private BasicAuthAccounts basicAuthAccounts; private Set<Sessions> sessionses = new HashSet<Sessions>(0); private Set<AccountGroups> accountGroupses = new HashSet<AccountGroups>(0); private Set<UserPrivileges> userPrivilegeses = new HashSet<UserPrivileges>(0); public UserAccounts() { } public UserAccounts(UserAccountsId id, Realms realms, UserDetails userDetails, String status, boolean isEdge, boolean chargesAccess) { this.id = id; this.realms = realms; this.userDetails = userDetails; this.status = status; this.isEdge = isEdge; this.chargesAccess = chargesAccess; } @EmbeddedId @AttributeOverrides( { @AttributeOverride(name = "realmTypeId", column = @Column(name = "realm_type_id", nullable = false, length = 32)), @AttributeOverride(name = "realmQualifier", column = @Column(name = "realm_qualifier", nullable = false, length = 32)), @AttributeOverride(name = "accountId", column = @Column(name = "account_id", nullable = false)) }) @NotNull public UserAccountsId getId() { return this.id; } public void setId(UserAccountsId id) { this.id = id; } @OneToOne(fetch = FetchType.LAZY, mappedBy = "userAccounts") public BasicAuthAccounts getBasicAuthAccounts() { return this.basicAuthAccounts; } public void setBasicAuthAccounts(BasicAuthAccounts basicAuthAccounts) { this.basicAuthAccounts = basicAuthAccounts; } /** * UserAccountsId generated by hbm2java */ @Embeddable public class UserAccountsId implements java.io.Serializable { private String realmTypeId; private String realmQualifier; private long accountId; public UserAccountsId() { } public UserAccountsId(String realmTypeId, String realmQualifier, long accountId) { this.realmTypeId = realmTypeId; this.realmQualifier = realmQualifier; this.accountId = accountId; } @Column(name = "realm_type_id", nullable = false, length = 32) @NotNull @Length(max = 32) public String getRealmTypeId() { return this.realmTypeId; } public void setRealmTypeId(String realmTypeId) { this.realmTypeId = realmTypeId; } @Column(name = "realm_qualifier", nullable = false, length = 32) @NotNull @Length(max = 32) public String getRealmQualifier() { return this.realmQualifier; } public void setRealmQualifier(String realmQualifier) { this.realmQualifier = realmQualifier; } @Column(name = "account_id", nullable = false) public long getAccountId() { return this.accountId; } public void setAccountId(long accountId) { this.accountId = accountId; } Main Code for classes are:

    Read the article

  • MVC DropDownListFor not populating the selected value

    - by user2254436
    I'm really having troubles with MVC, in another project I've done the same thing and it worked fine but in this project I just don't understand why the selected item in the dropdown is not populating the class correctly with EF. I have 2 classes: public partial class License { public License() { this.Customers = new HashSet<Customer>(); } public int LicenseID { get; set; } public int Lic_LicenseTypeID { get; set; } public int Lic_LicenseStatusID { get; set; } public string Lic_LicenseComments { get; set; } public virtual EntitiesList LicenseStatus { get; set; } public virtual EntitiesList LicenseType { get; set; } } public partial class EntitiesList { public EntitiesList() { this.LicensesStatus = new HashSet<License>(); this.LicensesType = new HashSet<License>(); } public int ListID { get; set; } public string List_EntityValue { get; set; } public string List_Comments { get; set; } public string List_EntityName { get; set; } public virtual ICollection<License> LicensesStatus { get; set; } public virtual ICollection<License> LicensesType { get; set; } public string List_DisplayName { get { return Regex.Replace(List_EntityName, "([a-z])([A-Z])", "$1 $2"); ; } } public string List_DisplayValue { get { return Regex.Replace(List_EntityValue, "([a-z])([A-Z])", "$1 $2"); } } } The EntitiesList is table in db that have all my "enum" lists. For example: ListID - 0 List_EntityValue - Activate List_EntityName - LicenseStatus ListID - 1 List_EntityValue - Basic List_EntityName - LicenseType This is my model: public class LicenseModel { public License License { get; set; } public SelectList LicenseStatuses { get; set; } public int SelectedStatus { get; set; } public SelectList LicenseTypes { get; set; } public int SelectedType { get; set; } } My controller for create: public ActionResult Create() { LicenseModel model = new LicenseModel(); model.License = new License(); model.LicenseStatuses = new SelectList(managerLists.GetAllLicenseStatuses(), "ListID", "List_DisplayValue"); model.LicenseTypes = new SelectList(managerLists.GetAllLicenseTypes(), "ListID", "List_DisplayValue"); return View(model); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(LicenseModel model) { if (ModelState.IsValid) { model.License.Lic_LicenseTypeID = model.SelectedType; model.License.Lic_LicenseStatusID = model.SelectedStatus; managerLicense.AddNewObject(model.License); return RedirectToAction("Index"); } return View(model); } managerLists and managerLicense are the managers that connect between the entities in db and the MVC UI, nothing special... they contains queries for adding new objects, getting the lists, editing and so on. And the view for creating the License: @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>License</legend> <div class="form-group"> @Html.LabelFor(model => model.License.Lic_LicenseTypeID) @Html.DropDownListFor(model => model.SelectedType, Model.LicenseTypes, new { @class = "form-control" }) <p class="help-block">@Html.ValidationMessageFor(model => model.License.Lic_LicenseTypeID)</p> </div> <div class="form-group"> @Html.LabelFor(model => model.License.Lic_LicenseStatusID) @Html.DropDownListFor(model => model.SelectedStatus, Model.LicenseStatuses, new { @class = "form-control" }) <p class="help-block">@Html.ValidationMessageFor(model => model.License.Lic_LicenseStatusID)</p> </div> <div class="form-group"> @Html.LabelFor(model => model.License.Lic_LicenseComments) @Html.TextAreaFor(model => model.License.Lic_LicenseComments, new { @class = "form-control", rows = "3" }) <p class="help-block">@Html.ValidationMessageFor(model => model.License.Lic_LicenseComments)</p> </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } Now, when I'm trying to save the new license, when it gets to the db.SaveChanges() in the manager I'm getting: "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details." In breakpoint, the Lic_LicenseTypeID and Lic_LicenseStatusID are getting correctly the ID's from the selected item in the dropdown but the LicenseStatus and LicenseStatus properties are null. What an I missing?

    Read the article

  • Is Java's ElementCollection Considered a Bad Practice?

    - by SoulBeaver
    From my understanding, an ElementCollection has no primary key, is embedded with the class, and cannot be queried. This sounds pretty hefty, but it allows me the comfort of writing an enum class which also helps with internationalization (using the enum key for lookup in my ResourceBundle). Example: We have a user on a media site and he can choose in which format he downloads the files @Entity @Table(name = "user") public class User { /* snip other fields */ @Enumerated @ElementCollection( targetClass = DownloadFilePreference.class, fetch = FetchType.EAGER ) @CollectionTable(name = "download_file_preference", joinColumns = @JoinColumn(name = "user_id") ) @Column(name = "name") private Set<DownloadFilePreference> downloadFilePreferences = new HashSet<>(); } public enum DownloadFilePreference { MP3, WAV, AIF, OGG; } This seems pretty great to me, and I suppose it comes down to "it depends on your use case", but I also know that I'm quite frankly only an initiate when it comes to Database design. Some best practices suggest to never have a class without a primary key- even in this case? It also doesn't seem very extensible- should I use this and gamble on the chance I will never need to query on the FilePreferences?

    Read the article

  • When to use functional programming approach and when not? (in Java)

    - by john smith optional
    let's assume I have a task to create a Set of class names. To remove duplication of .getName() method calls for each class, I used org.apache.commons.collections.CollectionUtils and org.apache.commons.collections.Transformer as follows: Snippet 1: Set<String> myNames = new HashSet<String>(); CollectionUtils.collect( Arrays.<Class<?>>asList(My1.class, My2.class, My3.class, My4.class, My5.class), new Transformer() { public Object transform(Object o) { return ((Class<?>) o).getName(); } }, myNames); An alternative would be this code: Snippet 2: Collections.addAll(myNames, My1.class.getName(), My2.class.getName(), My3.class.getName(), My4.class.getName(), My5.class.getName()); So, when using functional programming approach is overhead and when it's not and why? Isn't my usage of functional programming approach in snippet 1 is an overhead and why?

    Read the article

  • Efficiency of Java "Double Brace Initialization"?

    - by Jim Ferrans
    In Hidden Features of Java the top answer mentions Double Brace Initialization, with a very enticing syntax: Set<String> flavors = new HashSet<String>() {{ add("vanilla"); add("strawberry"); add("chocolate"); add("butter pecan"); }}; This idiom creates an anonymous inner class with just an instance initializer in it, which "can use any [...] methods in the containing scope". Main question: Is this as inefficient as it sounds? Should its use be limited to one-off initializations? (And of course showing off!) Second question: The new HashSet must be the "this" used in the instance initializer ... can anyone shed light on the mechanism? Third question: Is this idiom too obscure to use in production code? Summary: Very, very nice answers, thanks everyone. On question (3), people felt the syntax should be clear (though I'd recommend an occasional comment, especially if your code will pass on to developers who may not be familiar with it). On question (1), The generated code should run quickly. The extra .class files do cause jar file clutter, and slow program startup slightly (thanks to coobird for measuring that). Thilo pointed out that garbage collection can be affected, and the memory cost for the extra loaded classes may be a factor in some cases. Question (2) turned out to be most interesting to me. If I understand the answers, what's happening in DBI is that the anonymous inner class extends the class of the object being constructed by the new operator, and hence has a "this" value referencing the instance being constructed. Very neat. Overall, DBI strikes me as something of an intellectual curiousity. Coobird and others point out you can achieve the same effect with Arrays.asList, varargs methods, Google Collections, and the proposed Java 7 Collection literals. Newer JVM languages like Scala, JRuby, and Groovy also offer concise notations for list construction, and interoperate well with Java. Given that DBI clutters up the classpath, slows down class loading a bit, and makes the code a tad more obscure, I'd probably shy away from it. However, I plan to spring this on a friend who's just gotten his SCJP and loves good natured jousts about Java semantics! ;-) Thanks everyone!

    Read the article

  • c# order preserving data structures

    - by Oren Mazor
    Oddly enough, MSDN has no information on the order preserving properties of data structures. So I've been making the assumption that: Hashtable and Hashset do not preserve the insertion order (aka the "hash" in there is a giveaway) Dictionary and List DO preserve the insertion order. from this I extrapolate that if I have a Dictionary<double,double> foo that defines a curve, foo.Keys.ToList() and foo.Values.ToList() will give me an ordered list of the scope and domain of that curve without messing about with it?

    Read the article

  • fail-fast iterator

    - by joy
    I get this definition : As name suggest fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. what it mean by since iteration has begun? is that mean after Iterator it=set.iterator() this line of code? public static void customize(BufferedReader br) throws IOException{ Set<String> set=new HashSet<String>(); // Actual type parameter added **Iterator it=set.iterator();**

    Read the article

  • Determine the relative compliment of two IEnumerable<T> sets in .net

    - by SFun28
    Hi! Is there an easy way to get the relative compliment of two sets? Perhaps using LINQ? http://en.wikipedia.org/wiki/Complement_(set_theory) I have to find the relative compliment of a set A relative to B. Both A and B are of type HashSet but I think the algorithm could be made more generation (IEnumerable or even ISet)? I could use a solution in either vb.net or C#.

    Read the article

  • BufferedReader no longer buffering after a while?

    - by BobTurbo
    Sorry I can't post code but I have a bufferedreader with 50000000 bytes set as the buffer size. It works as you would expect for half an hour, the HDD light flashing every two minutes or so, reading in the big chunk of data, and then going quiet again as the CPU processes it. But after about half an hour (this is a very big file), the HDD starts thrashing as if it is reading one byte at a time. It is still in the same loop and I think I checked free ram to rule out swapping (heap size is default). Probably won't get any helpful answers, but worth a try. OK I have changed heap size to 768mb and still nothing. There is plenty of free memory and java.exe is only using about 300mb. Now I have profiled it and heap stays at about 200MB, well below what is available. CPU stays at 50%. Yet the HDD starts thrashing like crazy. I have.. no idea. I am going to rewrite the whole thing in c#, that is my solution. Here is the code (it is just a throw-away script, not pretty): BufferedReader s = null; HashMap<String, Integer> allWords = new HashMap<String, Integer>(); HashSet<String> pageWords = new HashSet<String>(); long[] pageCount = new long[78592]; long pages = 0; Scanner wordFile = new Scanner(new BufferedReader(new FileReader("allWords.txt"))); while (wordFile.hasNext()) { allWords.put(wordFile.next(), Integer.parseInt(wordFile.next())); } s = new BufferedReader(new FileReader("wikipedia/enwiki-latest-pages-articles.xml"), 50000000); StringBuilder words = new StringBuilder(); String nextLine = null; while ((nextLine = s.readLine()) != null) { if (a.matcher(nextLine).matches()) { continue; } else if (b.matcher(nextLine).matches()) { continue; } else if (c.matcher(nextLine).matches()) { continue; } else if (d.matcher(nextLine).matches()) { nextLine = s.readLine(); if (e.matcher(nextLine).matches()) { if (f.matcher(s.readLine()).matches()) { pageWords.addAll(Arrays.asList(words.toString().toLowerCase().split("[^a-zA-Z]"))); words.setLength(0); pages++; for (String word : pageWords) { if (allWords.containsKey(word)) { pageCount[allWords.get(word)]++; } else if (!word.isEmpty() && allWords.containsKey(word.substring(0, word.length() - 1))) { pageCount[allWords.get(word.substring(0, word.length() - 1))]++; } } pageWords.clear(); } } } else if (g.matcher(nextLine).matches()) { continue; } words.append(nextLine); words.append(" "); }

    Read the article

  • Using a model to represent the overall state of a view

    - by James P.
    Is there a standard practise for representing the state of a user interface that is not linked to a single Component? For example, a Swing interface could have a series of tabs with a constraint that a single tab should only be displayed once per a given entity type (this could be represented as a HashSet). Or a message could give the result of the last operation carried out. Or a JPanel could be linked to a single entity instance for editing purposes.

    Read the article

  • Why is Dictionary.First() so slow?

    - by Rotsor
    Not a real question because I already found out the answer, but still interesting thing. I always thought that hash table is the fastest associative container if you hash properly. However, the following code is terribly slow. It executes only about 1 million iterations and takes more than 2 minutes of time on a Core 2 CPU. The code does the following: it maintains the collection todo of items it needs to process. At each iteration it takes an item from this collection (doesn't matter which item), deletes it, processes it if it wasn't processed (possibly adding more items to process), and repeats this until there are no items to process. The culprit seems to be the Dictionary.Keys.First() operation. The question is why is it slow? Stopwatch watch = new Stopwatch(); watch.Start(); HashSet<int> processed = new HashSet<int>(); Dictionary<int, int> todo = new Dictionary<int, int>(); todo.Add(1, 1); int iterations = 0; int limit = 500000; while (todo.Count > 0) { iterations++; var key = todo.Keys.First(); var value = todo[key]; todo.Remove(key); if (!processed.Contains(key)) { processed.Add(key); // process item here if (key < limit) { todo[key + 13] = value + 1; todo[key + 7] = value + 1; } // doesn't matter much how } } Console.WriteLine("Iterations: {0}; Time: {1}.", iterations, watch.Elapsed); This results in: Iterations: 923007; Time: 00:02:09.8414388. Simply changing Dictionary to SortedDictionary yields: Iterations: 499976; Time: 00:00:00.4451514. 300 times faster while having only 2 times less iterations. The same happens in java. Used HashMap instead of Dictionary and keySet().iterator().next() instead of Keys.First().

    Read the article

  • Data from 6 ArrayLists into a single JTable - Java Swing

    - by Splunk
    I have created a JTable which is populated by various arraylists which get their data from a text list using a "~" to split. The issue I am having is that the table is displaying all data from the list on a single row. For example: Column1 Column2 Column2 Column2 Column3 Column4 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 When I want it to display Column1 Column2 Column2 Column2 Column3 Column4 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 You get the idea. From previous advice, I think the issue may be looping, but I am not sure. Any advice would be great. The code is below: private void table(){ String[] colName = { "Course", "Examiner", "Moderator", "Semester Available ", "Associated Programs", "Associated Majors"}; DefaultTableModel model = new DefaultTableModel(colName,0); for(Object item : courseList){ Object[] row = new Object[6]; // String[] row = new String[6]; row[0] = fileManage.getCourseList(); row[1] = fileManage.getNameList(); row[2] = fileManage.getModeratorList(); row[3] = fileManage.getSemesterList(); row[4] = fileManage.getProgramList(); row[5] = fileManage.getMajorList(); model.addRow(row); textArea = new JTable(model); } This is the class that has the arraylists: import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Scanner; public class FileIOManagement { private ArrayList<String> nameList = new ArrayList<String>(); private ArrayList<String> courseList = new ArrayList<String>(); private ArrayList<String> semesterList = new ArrayList<String>(); private ArrayList<String> moderatorList = new ArrayList<String>(); private ArrayList<String> programList = new ArrayList<String>(); private ArrayList<String> majorList = new ArrayList<String>(); public ArrayList<String> getNameList(){ return this.nameList; } public ArrayList<String> getCourseList(){ return this.courseList; } public ArrayList<String> getSemesterList(){ return this.semesterList; } public ArrayList<String> getModeratorList(){ return this.moderatorList; } public ArrayList<String> getProgramList(){ return this.programList; } public ArrayList<String> getMajorList(){ return this.majorList; } public void setNameList(ArrayList<String> nameList){ this.nameList = nameList; } public void setCourseList(ArrayList<String> courseList){ this.courseList = courseList; } public void setSemesterList(ArrayList<String> semesterList){ this.semesterList = semesterList; } public void setModeratorList(ArrayList<String> moderatorList){ this.moderatorList = moderatorList; } public void setProgramList(ArrayList<String> programList){ this.programList = programList; } public void setMajorList(ArrayList<String> majorList){ this.majorList = majorList; } public FileIOManagement(){ setNameList(new ArrayList<String>()); setCourseList(new ArrayList<String>()); setSemesterList(new ArrayList<String>()); setModeratorList(new ArrayList<String>()); setProgramList(new ArrayList<String>()); setMajorList(new ArrayList<String>()); readTextFile(); getNameList(); getCourseList(); } private void readTextFile(){ try{ Scanner scan = new Scanner(new File("Course.txt")); while(scan.hasNextLine()){ String line = scan.nextLine(); String[] tokens = line.split("~"); String course = tokens[0].trim(); String examiner = tokens[1].trim(); String moderator = tokens[2].trim(); String semester = tokens[3].trim(); String program = tokens[4].trim(); String major = tokens[5].trim(); courseList.add(course); semesterList.add(semester); nameList.add(examiner); moderatorList.add(moderator); programList.add(program); majorList.add(major); HashSet hs = new HashSet(); hs.addAll(nameList); nameList.clear(); nameList.addAll(hs); Collections.sort(nameList); } scan.close(); } catch (FileNotFoundException e){ e.printStackTrace(); } } } This is the class where I need to have the JTable: import java.awt.*; import javax.swing.*; import java.io.*; import javax.swing.border.EmptyBorder; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.table.DefaultTableModel; public class AllDataGUI extends JFrame{ private JButton saveCloseBtn = new JButton("Save Changes and Close"); private JButton closeButton = new JButton("Exit Without Saving"); private JFrame frame=new JFrame("Viewing All Program Details"); private final FileIOManagement fileManage = new FileIOManagement(); private ArrayList<String> nameList = new ArrayList(); private ArrayList<String> courseList = new ArrayList(); private ArrayList<String> semesterList = new ArrayList(); private ArrayList<String> moderatorList = new ArrayList(); private ArrayList<String> majorList = new ArrayList(); private ArrayList<String> programList = new ArrayList(); private JTable textArea; public ArrayList<String> getNameList(){ return this.nameList; } public ArrayList<String> getCourseList(){ return this.courseList; } public ArrayList<String> getSemesterList(){ return this.semesterList; } public ArrayList<String> getModeratorList(){ return this.moderatorList; } public ArrayList<String> getProgramList(){ return this.programList; } public ArrayList<String> getMajorList(){ return this.majorList; } public void setNameList(ArrayList<String> nameList){ this.nameList = nameList; } public void setCourseList(ArrayList<String> courseList){ this.courseList = courseList; } public void setSemesterList(ArrayList<String> semesterList){ this.semesterList = semesterList; } public void setModeratorList(ArrayList<String> moderatorList){ this.moderatorList = moderatorList; } public void setProgramList(ArrayList<String> programList){ this.programList = programList; } public void setMajorList(ArrayList<String> majorList){ this.majorList = majorList; } public AllDataGUI(){ getData(); table(); panels(); } public Object getValueAt(int rowIndex, int columnIndex) { String[] token = nameList.get(rowIndex).split(","); return token[columnIndex]; } private void table(){ String[] colName = { "Course", "Examiner", "Moderator", "Semester Available ", "Associated Programs", "Associated Majors"}; DefaultTableModel model = new DefaultTableModel(colName,0); for(Object item : courseList){ Object[] row = new Object[6]; // String[] row = new String[6]; row[0] = fileManage.getCourseList(); row[1] = fileManage.getNameList(); row[2] = fileManage.getModeratorList(); row[3] = fileManage.getSemesterList(); row[4] = fileManage.getProgramList(); row[5] = fileManage.getMajorList(); model.addRow(row); textArea = new JTable(model); // String END_OF_LINE = ","; // // String[] colName = { "Course", "Examiner", "Moderator", "Semester Available ", "Associated Programs", "Associated Majors"}; //// textArea.getTableHeader().setBackground(Color.WHITE); //// textArea.getTableHeader().setForeground(Color.BLUE); // // Font Tablefont = new Font("Details", Font.BOLD, 12); // // textArea.getTableHeader().setFont(Tablefont); // Object[][] object = new Object[100][100]; // int i = 0; // if (fileManage.size() != 0) { // for (fileManage book : fileManage) { // object[i][0] = fileManage.getCourseList(); // object[i][1] = fileManage.getNameList(); // object[i][2] = fileManage.getModeratorList(); // object[i][3] = fileManage.getSemesterList(); // object[i][4] = fileManage.getProgramList(); // object[i][5] = fileManage.getMajorList(); // // textArea = new JTable(object, colName); // } // } } } public void getData(){ nameList = fileManage.getNameList(); courseList = fileManage.getCourseList(); semesterList = fileManage.getSemesterList(); moderatorList = fileManage.getModeratorList(); majorList = fileManage.getMajorList(); programList = fileManage.getProgramList(); // textArea.(write()); } private JButton getCloseButton(){ return closeButton; } private void panels(){ JPanel panel = new JPanel(new GridLayout(1,1)); panel.setBorder(new EmptyBorder(5, 5, 5, 5)); JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10)); rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10)); JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); panel.add(scrollBarForTextArea); frame.add(panel); frame.getContentPane().add(rightPanel,BorderLayout.EAST); rightPanel.add(saveCloseBtn); rightPanel.add(closeButton); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); } }); saveCloseBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //saveBtn(); frame.dispose(); } }); frame.setSize(1000, 700); frame.setVisible(true); frame.setLocationRelativeTo(null); } // private void saveBtn(){ // File file = null; // FileWriter out=null; // try { // file = new File("Course.txt"); // out = new FileWriter(file); // out.write(textArea.getText()); // out.close(); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // JOptionPane.showMessageDialog(this, "File Successfully Updated"); // // } }

    Read the article

  • Hibernate - how to delete bidirectional many-to-many association

    - by slomir
    Problem: I have many-to-many association between two entities A and B. I set A entity as an owner of their relationship(inverse=true is on A's collection in b.hbm.xml). When i delete an A entity, corresponding records in join table are deleted. When i delete an B entity, corresponding records in join table are not deleted (integrity violation exception). -- Let's consider some very simple example: class A{ Set<B> bset=new HashSet<B>(); //... } class B{ Set<A> aset=new HashSet<A>(); //... } File a.hbm.xml [m-to-m mappings only]: <set name="bset" table="AB"> <key name="a_id"/> <many-to-many column="b_id" class="B"/> </set> File b.hbm.xml [m-to-m mappings only]: <set name="aset" table="AB" inverse="true"> <key name="b_id"/> <many-to-many column="a_id" class="A"/> </set> Database relations: A(id,...) B(id,...) AB(a_id,b_id) Suppose that we have some records in AB joint table. For example: AB = {(1,1),(1,2)} where AB= { (a_id , b_id) | ... ... } -- Situation 1 - works probably because A is owner of AB relationship: A a=aDao.read(1); //read A entity with id=1 aDao.delete(a); //delete 'a' entity and both relations with B-entities Situation 2 - doesn't work: B b=bDao.read(1); //read B entity with id=1 bDao.delete(b); //foreign key integrity violation On the one hand, this is somehow logical to me, because the A entity is responsible for his relation with B. But, on the other hand, it is not logical or at least it is not orm-like solution that I have to explicitly delete all records in join table where concrete B entity appears, and then to delete the B entity, as I show in situation 3: Situation 3 - works, but it is not 'elegant': B b=bDao.read(1); Set<A> aset=b.getA(); //get set with A entities Iterator i=aset.iterator(); //while removes 'b' from all related A entities //while breaks relationships on A-side of relation (A is owner) while(i.hasNext()){ A a=i.next(); a.bset.remove(b); //remove entity 'b' from related 'a' entity aDao.update(a); //key point!!! this line breaks relation in database } bDao.delete(b); //'b' is deleted because there is no related A-entities -- So, my question: is there any more convenient way to delete no-owner entity (B in my example) in bidirectional many-to-many association and all of his many-to-many relations from joint table?

    Read the article

  • Winforms controls and "generic" events handlers. How can I do this?

    - by Yanko Hernández Alvarez
    In the demo of the ObjectListView control there is this code (in the "Complex Example" tab page) to allow for a custom editor (a ComboBox) (Adapted to my case and edited for clarity): EventHandler CurrentEH; private void ObjectListView_CellEditStarting(object sender, CellEditEventArgs e) { if (e.Column == SomeCol) { ISomeInterface M = (e.RowObject as ObjectListView1Row).SomeObject; //(1) ComboBox cb = new ComboBox(); cb.Bounds = e.CellBounds; cb.DropDownStyle = ComboBoxStyle.DropDownList; cb.DataSource = ISomeOtherObjectCollection; cb.DisplayMember = "propertyName"; cb.DataBindings.Add("SelectedItem", M, "ISomeOtherObject", false, DataSourceUpdateMode.Never); e.Control = cb; cb.SelectedIndexChanged += CurrentEH = (object sender2, EventArgs e2) => M.ISomeOtherObject = (ISomeOtherObject)((ComboBox)sender2).SelectedValue; //(2) } } private void ObjectListView_CellEditFinishing(object sender, CellEditEventArgs e) { if (e.Column == SomeCol) { // Stop listening for change events ((ComboBox)e.Control).SelectedIndexChanged -= CurrentEH; // Any updating will have been down in the SelectedIndexChanged // event handler. // Here we simply make the list redraw the involved ListViewItem ((ObjectListView)sender).RefreshItem(e.ListViewItem); // We have updated the model object, so we cancel the auto update e.Cancel = true; } } I have too many other columns with combo editors inside objectlistviews to use a copy& paste strategy (besides, copy&paste is a serious source of bugs), so I tried to parameterize the code to keep the code duplication to a minimum. ObjectListView_CellEditFinishing is a piece of cake: HashSet<OLVColumn> cbColumns = new HashSet<OLVColumn> (new OLVColumn[] { SomeCol, SomeCol2, ...}; private void ObjectListView_CellEditFinishing(object sender, CellEditEventArgs e) { if (cbColumns.Contains(e.Column)) ... but ObjectListView_CellEditStarting is the problematic. I guess in CellEditStarting I will have to discriminate each case separately: private void ObjectListView_CellEditStarting(object sender, CellEditEventArgs e) { if (e.Column == SomeCol) // code to create the combo, put the correct list as the datasource, etc. else if (e.Column == SomeOtherCol) // code to create the combo, put the correct list as the datasource, etc. And so on. But how can I parameterize the "code to create the combo, put the correct list as the datasource, etc."? Problem lines are (1) Get SomeObject. the property NAME varies. (2) Set ISomeOtherObject, the property name varies too. The types vary too, but I can cover those cases with a generic method combined with a not so "typesafe" API (for instance, the cb.DataBindings.Add and cb.DataSource both use an object) Reflection? more lambdas? Any ideas? Any other way to do the same? PS: I want to be able to do something like this: private void ObjectListView_CellEditStarting(object sender, CellEditEventArgs e) { if (e.Column == SomeCol) SetUpCombo<ISomeInterface>(ISomeOtherObjectCollection, "propertyName", SomeObject, ISomeOtherObject); else if (e.Column == SomeOtherCol) SetUpCombo<ISomeInterface2>(ISomeOtherObject2Collection, "propertyName2", SomeObject2 ISomeOtherObject2); and so on. Or something like that. I know, parameters SomeObject and ISomeOtherObject are not real parameters per see, but you get the idea of what I want. I want not to repeat the same code skeleton again and again and again. One solution would be "preprocessor generics" like C's DEFINE, but I don't thing c# has something like that. So, does anyone have some alternate ideas to solve this?

    Read the article

  • Problem detaching entire object graph in GAE-J with JDO

    - by tempy
    I am trying to load the full object graph for User, which contains a collection of decks, which then contains a collection of cards, as such: User: @PersistenceCapable(detachable = "true") @Inheritance(strategy = InheritanceStrategy.SUBCLASS_TABLE) @FetchGroup(name = "decks", members = { @Persistent(name = "_Decks") }) public abstract class User { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) protected Key _ID; @Persistent protected String _UniqueIdentifier; @Persistent(mappedBy = "_Owner") @Element(dependent = "true") protected Set<Deck> _Decks; protected User() { } } Each Deck has a collection of Cards, as such: @PersistenceCapable(detachable = "true") @FetchGroup(name = "cards", members = { @Persistent(name = "_Cards") }) public class Deck { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Key _ID; @Persistent String _Name; @Persistent(mappedBy = "_Parent") @Element(dependent = "true") private Set<Card> _Cards = new HashSet<Card>(); @Persistent private Set<String> _Tags = new HashSet<String>(); @Persistent private User _Owner; } And finally, each card: @PersistenceCapable public class Card { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Key _ID; @Persistent private Text _Question; @Persistent private Text _Answer; @Persistent private Deck _Parent; } I am trying to retrieve and then detach the entire object graph. I can see in the debugger that it loads fine, but then when I get to detaching, I can't make anything beyond the User object load. (No Decks, no Cards). At first I tried without a transaction to simply "touch" all the fields on the attached object before detaching, but that didn't help. Then I tried adding everything to the default fetch group, but that just generated warnings about GAE not supporting joins. I tried setting the fetch plan's max fetch depth to -1, but that didn't do it. Finally, I tried using FetchGroups as you can see above, and then retrieving with the following code: PersistenceManager pm = _pmf.getPersistenceManager(); pm.setDetachAllOnCommit(true); pm.getFetchPlan().setGroup("decks"); pm.getFetchPlan().setGroup("cards"); Transaction tx = pm.currentTransaction(); Query query = null; try { tx.begin(); query = pm.newQuery(GoogleAccountsUser.class); //Subclass of User query.setFilter("_UniqueIdentifier == TheUser"); query.declareParameters("String TheUser"); List<User> results = (List<User>)query.execute(ID); //ID = Supplied parameter //TODO: Test for more than one result and throw if(results.size() == 0) { tx.commit(); return null; } else { User usr = (User)results.get(0); //usr = pm.detachCopy(usr); tx.commit(); return usr; } } finally { query.closeAll(); if (tx.isActive()) { tx.rollback(); } pm.close(); } This also doesn't work, and I'm running out of ideas...

    Read the article

  • .NET HTML Sanitation for rich HTML Input

    - by Rick Strahl
    Recently I was working on updating a legacy application to MVC 4 that included free form text input. When I set up the new site my initial approach was to not allow any rich HTML input, only simple text formatting that would respect a few simple HTML commands for bold, lists etc. and automatically handles line break processing for new lines and paragraphs. This is typical for what I do with most multi-line text input in my apps and it works very well with very little development effort involved. Then the client sprung another note: Oh by the way we have a bunch of customers (real estate agents) who need to post complete HTML documents. Oh uh! There goes the simple theory. After some discussion and pleading on my part (<snicker>) to try and avoid this type of raw HTML input because of potential XSS issues, the client decided to go ahead and allow raw HTML input anyway. There has been lots of discussions on this subject on StackOverFlow (and here and here) but to after reading through some of the solutions I didn't really find anything that would work even closely for what I needed. Specifically we need to be able to allow just about any HTML markup, with the exception of script code. Remote CSS and Images need to be loaded, links need to work and so. While the 'legit' HTML posted by these agents is basic in nature it does span most of the full gamut of HTML (4). Most of the solutions XSS prevention/sanitizer solutions I found were way to aggressive and rendered the posted output unusable mostly because they tend to strip any externally loaded content. In short I needed a custom solution. I thought the best solution to this would be to use an HTML parser - in this case the Html Agility Pack - and then to run through all the HTML markup provided and remove any of the blacklisted tags and a number of attributes that are prone to JavaScript injection. There's much discussion on whether to use blacklists vs. whitelists in the discussions mentioned above, but I found that whitelists can make sense in simple scenarios where you might allow manual HTML input, but when you need to allow a larger array of HTML functionality a blacklist is probably easier to manage as the vast majority of elements and attributes could be allowed. Also white listing gets a bit more complex with HTML5 and the new proliferation of new HTML tags and most new tags generally don't affect XSS issues directly. Pure whitelisting based on elements and attributes also doesn't capture many edge cases (see some of the XSS cheat sheets listed below) so even with a white list, custom logic is still required to handle many of those edge cases. The Microsoft Web Protection Library (AntiXSS) My first thought was to check out the Microsoft AntiXSS library. Microsoft has an HTML Encoding and Sanitation library in the Microsoft Web Protection Library (formerly AntiXSS Library) on CodePlex, which provides stricter functions for whitelist encoding and sanitation. Initially I thought the Sanitation class and its static members would do the trick for me,but I found that this library is way too restrictive for my needs. Specifically the Sanitation class strips out images and links which rendered the full HTML from our real estate clients completely useless. I didn't spend much time with it, but apparently I'm not alone if feeling this library is not really useful without some way to configure operation. To give you an example of what didn't work for me with the library here's a small and simple HTML fragment that includes script, img and anchor tags. I would expect the script to be stripped and everything else to be left intact. Here's the original HTML:var value = "<b>Here</b> <script>alert('hello')</script> we go. Visit the " + "<a href='http://west-wind.com'>West Wind</a> site. " + "<img src='http://west-wind.com/images/new.gif' /> " ; and the code to sanitize it with the AntiXSS Sanitize class:@Html.Raw(Microsoft.Security.Application.Sanitizer.GetSafeHtmlFragment(value)) This produced a not so useful sanitized string: Here we go. Visit the <a>West Wind</a> site. While it removed the <script> tag (good) it also removed the href from the link and the image tag altogether (bad). In some situations this might be useful, but for most tasks I doubt this is the desired behavior. While links can contain javascript: references and images can 'broadcast' information to a server, without configuration to tell the library what to restrict this becomes useless to me. I couldn't find any way to customize the white list, nor is there code available in this 'open source' library on CodePlex. Using Html Agility Pack for HTML Parsing The WPL library wasn't going to cut it. After doing a bit of research I decided the best approach for a custom solution would be to use an HTML parser and inspect the HTML fragment/document I'm trying to import. I've used the HTML Agility Pack before for a number of apps where I needed an HTML parser without requiring an instance of a full browser like the Internet Explorer Application object which is inadequate in Web apps. In case you haven't checked out the Html Agility Pack before, it's a powerful HTML parser library that you can use from your .NET code. It provides a simple, parsable HTML DOM model to full HTML documents or HTML fragments that let you walk through each of the elements in your document. If you've used the HTML or XML DOM in a browser before you'll feel right at home with the Agility Pack. Blacklist based HTML Parsing to strip XSS Code For my purposes of HTML sanitation, the process involved is to walk the HTML document one element at a time and then check each element and attribute against a blacklist. There's quite a bit of argument of what's better: A whitelist of allowed items or a blacklist of denied items. While whitelists tend to be more secure, they also require a lot more configuration. In the case of HTML5 a whitelist could be very extensive. For what I need, I only want to ensure that no JavaScript is executed, so a blacklist includes the obvious <script> tag plus any tag that allows loading of external content including <iframe>, <object>, <embed> and <link> etc. <form>  is also excluded to avoid posting content to a different location. I also disallow <head> and <meta> tags in particular for my case, since I'm only allowing posting of HTML fragments. There is also some internal logic to exclude some attributes or attributes that include references to JavaScript or CSS expressions. The default tag blacklist reflects my use case, but is customizable and can be added to. Here's my HtmlSanitizer implementation:using System.Collections.Generic; using System.IO; using System.Xml; using HtmlAgilityPack; namespace Westwind.Web.Utilities { public class HtmlSanitizer { public HashSet<string> BlackList = new HashSet<string>() { { "script" }, { "iframe" }, { "form" }, { "object" }, { "embed" }, { "link" }, { "head" }, { "meta" } }; /// <summary> /// Cleans up an HTML string and removes HTML tags in blacklist /// </summary> /// <param name="html"></param> /// <returns></returns> public static string SanitizeHtml(string html, params string[] blackList) { var sanitizer = new HtmlSanitizer(); if (blackList != null && blackList.Length > 0) { sanitizer.BlackList.Clear(); foreach (string item in blackList) sanitizer.BlackList.Add(item); } return sanitizer.Sanitize(html); } /// <summary> /// Cleans up an HTML string by removing elements /// on the blacklist and all elements that start /// with onXXX . /// </summary> /// <param name="html"></param> /// <returns></returns> public string Sanitize(string html) { var doc = new HtmlDocument(); doc.LoadHtml(html); SanitizeHtmlNode(doc.DocumentNode); //return doc.DocumentNode.WriteTo(); string output = null; // Use an XmlTextWriter to create self-closing tags using (StringWriter sw = new StringWriter()) { XmlWriter writer = new XmlTextWriter(sw); doc.DocumentNode.WriteTo(writer); output = sw.ToString(); // strip off XML doc header if (!string.IsNullOrEmpty(output)) { int at = output.IndexOf("?>"); output = output.Substring(at + 2); } writer.Close(); } doc = null; return output; } private void SanitizeHtmlNode(HtmlNode node) { if (node.NodeType == HtmlNodeType.Element) { // check for blacklist items and remove if (BlackList.Contains(node.Name)) { node.Remove(); return; } // remove CSS Expressions and embedded script links if (node.Name == "style") { if (string.IsNullOrEmpty(node.InnerText)) { if (node.InnerHtml.Contains("expression") || node.InnerHtml.Contains("javascript:")) node.ParentNode.RemoveChild(node); } } // remove script attributes if (node.HasAttributes) { for (int i = node.Attributes.Count - 1; i >= 0; i--) { HtmlAttribute currentAttribute = node.Attributes[i]; var attr = currentAttribute.Name.ToLower(); var val = currentAttribute.Value.ToLower(); span style="background: white; color: green">// remove event handlers if (attr.StartsWith("on")) node.Attributes.Remove(currentAttribute); // remove script links else if ( //(attr == "href" || attr== "src" || attr == "dynsrc" || attr == "lowsrc") && val != null && val.Contains("javascript:")) node.Attributes.Remove(currentAttribute); // Remove CSS Expressions else if (attr == "style" && val != null && val.Contains("expression") || val.Contains("javascript:") || val.Contains("vbscript:")) node.Attributes.Remove(currentAttribute); } } } // Look through child nodes recursively if (node.HasChildNodes) { for (int i = node.ChildNodes.Count - 1; i >= 0; i--) { SanitizeHtmlNode(node.ChildNodes[i]); } } } } } Please note: Use this as a starting point only for your own parsing and review the code for your specific use case! If your needs are less lenient than mine were you can you can make this much stricter by not allowing src and href attributes or CSS links if your HTML doesn't allow it. You can also check links for external URLs and disallow those - lots of options.  The code is simple enough to make it easy to extend to fit your use cases more specifically. It's also quite easy to make this code work using a WhiteList approach if you want to go that route. The code above is semi-generic for allowing full featured HTML fragments that only disallow script related content. The Sanitize method walks through each node of the document and then recursively drills into all of its children until the entire document has been traversed. Note that the code here uses an XmlTextWriter to write output - this is done to preserve XHTML style self-closing tags which are otherwise left as non-self-closing tags. The sanitizer code scans for blacklist elements and removes those elements not allowed. Note that the blacklist is configurable either in the instance class as a property or in the static method via the string parameter list. Additionally the code goes through each element's attributes and looks for a host of rules gleaned from some of the XSS cheat sheets listed at the end of the post. Clearly there are a lot more XSS vulnerabilities, but a lot of them apply to ancient browsers (IE6 and versions of Netscape) - many of these glaring holes (like CSS expressions - WTF IE?) have been removed in modern browsers. What a Pain To be honest this is NOT a piece of code that I wanted to write. I think building anything related to XSS is better left to people who have far more knowledge of the topic than I do. Unfortunately, I was unable to find a tool that worked even closely for me, or even provided a working base. For the project I was working on I had no choice and I'm sharing the code here merely as a base line to start with and potentially expand on for specific needs. It's sad that Microsoft Web Protection Library is currently such a train wreck - this is really something that should come from Microsoft as the systems vendor or possibly a third party that provides security tools. Luckily for my application we are dealing with a authenticated and validated users so the user base is fairly well known, and relatively small - this is not a wide open Internet application that's directly public facing. As I mentioned earlier in the post, if I had my way I would simply not allow this type of raw HTML input in the first place, and instead rely on a more controlled HTML input mechanism like MarkDown or even a good HTML Edit control that can provide some limits on what types of input are allowed. Alas in this case I was overridden and we had to go forward and allow *any* raw HTML posted. Sometimes I really feel sad that it's come this far - how many good applications and tools have been thwarted by fear of XSS (or worse) attacks? So many things that could be done *if* we had a more secure browser experience and didn't have to deal with every little script twerp trying to hack into Web pages and obscure browser bugs. So much time wasted building secure apps, so much time wasted by others trying to hack apps… We're a funny species - no other species manages to waste as much time, effort and resources as we humans do :-) Resources Code on GitHub Html Agility Pack XSS Cheat Sheet XSS Prevention Cheat Sheet Microsoft Web Protection Library (AntiXss) StackOverflow Links: http://stackoverflow.com/questions/341872/html-sanitizer-for-net http://blog.stackoverflow.com/2008/06/safe-html-and-xss/ http://code.google.com/p/subsonicforums/source/browse/trunk/SubSonic.Forums.Data/HtmlScrubber.cs?r=61© Rick Strahl, West Wind Technologies, 2005-2012Posted in Security  HTML  ASP.NET  JavaScript   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Generating EF Code First model classes from an existing database

    - by Jon Galloway
    Entity Framework Code First is a lightweight way to "turn on" data access for a simple CLR class. As the name implies, the intended use is that you're writing the code first and thinking about the database later. However, I really like the Entity Framework Code First works, and I want to use it in existing projects and projects with pre-existing databases. For example, MVC Music Store comes with a SQL Express database that's pre-loaded with a catalog of music (including genres, artists, and songs), and while it may eventually make sense to load that seed data from a different source, for the MVC 3 release we wanted to keep using the existing database. While I'm not getting the full benefit of Code First - writing code which drives the database schema - I can still benefit from the simplicity of the lightweight code approach. Scott Guthrie blogged about how to use entity framework with an existing database, looking at how you can override the Entity Framework Code First conventions so that it can work with a database which was created following other conventions. That gives you the information you need to create the model classes manually. However, it turns out that with Entity Framework 4 CTP 5, there's a way to generate the model classes from the database schema. Once the grunt work is done, of course, you can go in and modify the model classes as you'd like, but you can save the time and frustration of figuring out things like mapping SQL database types to .NET types. Note that this template requires Entity Framework 4 CTP 5 or later. You can install EF 4 CTP 5 here. Step One: Generate an EF Model from your existing database The code generation system in Entity Framework works from a model. You can add a model to your existing project and delete it when you're done, but I think it's simpler to just spin up a separate project to generate the model classes. When you're done, you can delete the project without affecting your application, or you may choose to keep it around in case you have other database schema updates which require model changes. I chose to add the Model classes to the Models folder of a new MVC 3 application. Right-click the folder and select "Add / New Item..."   Next, select ADO.NET Entity Data Model from the Data Templates list, and name it whatever you want (the name is unimportant).   Next, select "Generate from database." This is important - it's what kicks off the next few steps, which read your database's schema.   Now it's time to point the Entity Data Model Wizard at your existing database. I'll assume you know how to find your database - if not, I covered that a bit in the MVC Music Store tutorial section on Models and Data. Select your database, uncheck the "Save entity connection settings in Web.config" (since we won't be using them within the application), and click Next.   Now you can select the database objects you'd like modeled. I just selected all tables and clicked Finish.   And there's your model. If you want, you can make additional changes here before going on to generate the code.   Step Two: Add the DbContext Generator Like most code generation systems in Visual Studio lately, Entity Framework uses T4 templates which allow for some control over how the code is generated. K Scott Allen wrote a detailed article on T4 Templates and the Entity Framework on MSDN recently, if you'd like to know more. Fortunately for us, there's already a template that does just what we need without any customization. Right-click a blank space in the Entity Framework model surface and select "Add Code Generation Item..." Select the Code groupt in the Installed Templates section and pick the ADO.NET DbContext Generator. If you don't see this listed, make sure you've got EF 4 CTP 5 installed and that you're looking at the Code templates group. Note that the DbContext Generator template is similar to the EF POCO template which came out last year, but with "fix up" code (unnecessary in EF Code First) removed.   As soon as you do this, you'll two terrifying Security Warnings - unless you click the "Do not show this message again" checkbox the first time. It will also be displayed (twice) every time you rebuild the project, so I checked the box and no immediate harm befell my computer (fingers crossed!).   Here's the payoff: two templates (filenames ending with .tt) have been added to the project, and they've generated the code I needed.   The "MusicStoreEntities.Context.tt" template built a DbContext class which holds the entity collections, and the "MusicStoreEntities.tt" template build a separate class for each table I selected earlier. We'll customize them in the next step. I recommend copying all the generated .cs files into your application at this point, since accidentally rebuilding the generation project will overwrite your changes if you leave them there. Step Three: Modify and use your POCO entity classes Note: I made a bunch of tweaks to my POCO classes after they were generated. You don't have to do any of this, but I think it's important that you can - they're your classes, and EF Code First respects that. Modify them as you need for your application, or don't. The Context class derives from DbContext, which is what turns on the EF Code First features. It holds a DbSet for each entity. Think of DbSet as a simple List, but with Entity Framework features turned on.   //------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace EF_CodeFirst_From_Existing_Database.Models { using System; using System.Data.Entity; public partial class Entities : DbContext { public Entities() : base("name=Entities") { } public DbSet<Album> Albums { get; set; } public DbSet<Artist> Artists { get; set; } public DbSet<Cart> Carts { get; set; } public DbSet<Genre> Genres { get; set; } public DbSet<OrderDetail> OrderDetails { get; set; } public DbSet<Order> Orders { get; set; } } } It's a pretty lightweight class as generated, so I just took out the comments, set the namespace, removed the constructor, and formatted it a bit. Done. If I wanted, though, I could have added or removed DbSets, overridden conventions, etc. using System.Data.Entity; namespace MvcMusicStore.Models { public class MusicStoreEntities : DbContext { public DbSet Albums { get; set; } public DbSet Genres { get; set; } public DbSet Artists { get; set; } public DbSet Carts { get; set; } public DbSet Orders { get; set; } public DbSet OrderDetails { get; set; } } } Next, it's time to look at the individual classes. Some of mine were pretty simple - for the Cart class, I just need to remove the header and clean up the namespace. //------------------------------------------------------------------------------ // // This code was generated from a template. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace EF_CodeFirst_From_Existing_Database.Models { using System; using System.Collections.Generic; public partial class Cart { // Primitive properties public int RecordId { get; set; } public string CartId { get; set; } public int AlbumId { get; set; } public int Count { get; set; } public System.DateTime DateCreated { get; set; } // Navigation properties public virtual Album Album { get; set; } } } I did a bit more customization on the Album class. Here's what was generated: //------------------------------------------------------------------------------ // // This code was generated from a template. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace EF_CodeFirst_From_Existing_Database.Models { using System; using System.Collections.Generic; public partial class Album { public Album() { this.Carts = new HashSet(); this.OrderDetails = new HashSet(); } // Primitive properties public int AlbumId { get; set; } public int GenreId { get; set; } public int ArtistId { get; set; } public string Title { get; set; } public decimal Price { get; set; } public string AlbumArtUrl { get; set; } // Navigation properties public virtual Artist Artist { get; set; } public virtual Genre Genre { get; set; } public virtual ICollection Carts { get; set; } public virtual ICollection OrderDetails { get; set; } } } I removed the header, changed the namespace, and removed some of the navigation properties. One nice thing about EF Code First is that you don't have to have a property for each database column or foreign key. In the Music Store sample, for instance, we build the app up using code first and start with just a few columns, adding in fields and navigation properties as the application needs them. EF Code First handles the columsn we've told it about and doesn't complain about the others. Here's the basic class: using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using System.Collections.Generic; namespace MvcMusicStore.Models { public class Album { public int AlbumId { get; set; } public int GenreId { get; set; } public int ArtistId { get; set; } public string Title { get; set; } public decimal Price { get; set; } public string AlbumArtUrl { get; set; } public virtual Genre Genre { get; set; } public virtual Artist Artist { get; set; } public virtual List OrderDetails { get; set; } } } It's my class, not Entity Framework's, so I'm free to do what I want with it. I added a bunch of MVC 3 annotations for scaffolding and validation support, as shown below: using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using System.Collections.Generic; namespace MvcMusicStore.Models { [Bind(Exclude = "AlbumId")] public class Album { [ScaffoldColumn(false)] public int AlbumId { get; set; } [DisplayName("Genre")] public int GenreId { get; set; } [DisplayName("Artist")] public int ArtistId { get; set; } [Required(ErrorMessage = "An Album Title is required")] [StringLength(160)] public string Title { get; set; } [Required(ErrorMessage = "Price is required")] [Range(0.01, 100.00, ErrorMessage = "Price must be between 0.01 and 100.00")] public decimal Price { get; set; } [DisplayName("Album Art URL")] [StringLength(1024)] public string AlbumArtUrl { get; set; } public virtual Genre Genre { get; set; } public virtual Artist Artist { get; set; } public virtual List<OrderDetail> OrderDetails { get; set; } } } The end result was that I had working EF Code First model code for the finished application. You can follow along through the tutorial to see how I built up to the finished model classes, starting with simple 2-3 property classes and building up to the full working schema. Thanks to Diego Vega (on the Entity Framework team) for pointing me to the DbContext template.

    Read the article

  • How can I eager-load a child collection mapped to a non-primary key in NHibernate 2.1.2?

    - by David Rubin
    Hi, I have two objects with a many-to-many relationship between them, as follows: public class LeftHandSide { public LeftHandSide() { Name = String.Empty; Rights = new HashSet<RightHandSide>(); } public int Id { get; set; } public string Name { get; set; } public ICollection<RightHandSide> Rights { get; set; } } public class RightHandSide { public RightHandSide() { OtherProp = String.Empty; Lefts = new HashSet<LeftHandSide>(); } public int Id { get; set; } public string OtherProp { get; set; } public ICollection<LeftHandSide> Lefts { get; set; } } and I'm using a legacy database, so my mappings look like: Notice that LeftHandSide and RightHandSide are associated by a different column than RightHandSide's primary key. <class name="LeftHandSide" table="[dbo].[lefts]" lazy="false"> <id name="Id" column="ID" unsaved-value="0"> <generator class="identity" /> </id> <property name="Name" not-null="true" /> <set name="Rights" table="[dbo].[lefts2rights]"> <key column="leftId" /> <!-- THIS IS THE IMPORTANT BIT: I MUST USE PROPERTY-REF --> <many-to-many class="RightHandSide" column="rightProp" property-ref="OtherProp" /> </set> </class> <class name="RightHandSide" table="[dbo].[rights]" lazy="false"> <id name="Id" column="id" unsaved-value="0"> <generator class="identity" /> </id> <property name="OtherProp" column="otherProp" /> <set name="Lefts" table="[dbo].[lefts2rights]"> <!-- THIS IS THE IMPORTANT BIT: I MUST USE PROPERTY-REF --> <key column="rightProp" property-ref="OtherProp" /> <many-to-many class="LeftHandSide" column="leftId" /> </set> </class> The problem comes when I go to do a query: LeftHandSide lhs = _session.CreateCriteria<LeftHandSide>() .Add(Expression.IdEq(13)) .UniqueResult<LeftHandSide>(); works just fine. But LeftHandSide lhs = _session.CreateCriteria<LeftHandSide>() .Add(Expression.IdEq(13)) .SetFetchMode("Rights", FetchMode.Join) .UniqueResult<LeftHandSide>(); throws an exception (see below). Interestingly, RightHandSide rhs = _session.CreateCriteria<RightHandSide>() .Add(Expression.IdEq(127)) .SetFetchMode("Lefts", FetchMode.Join) .UniqueResult<RightHandSide>(); seems to be perfectly fine as well. NHibernate.Exceptions.GenericADOException Message: Error performing LoadByUniqueKey[SQL: SQL not available] Source: NHibernate StackTrace: c:\opt\nhibernate\2.1.2\source\src\NHibernate\Type\EntityType.cs(563,0): at NHibernate.Type.EntityType.LoadByUniqueKey(String entityName, String uniqueKeyPropertyName, Object key, ISessionImplementor session) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Type\EntityType.cs(428,0): at NHibernate.Type.EntityType.ResolveIdentifier(Object value, ISessionImplementor session, Object owner) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Type\EntityType.cs(300,0): at NHibernate.Type.EntityType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Persister\Collection\AbstractCollectionPersister.cs(695,0): at NHibernate.Persister.Collection.AbstractCollectionPersister.ReadElement(IDataReader rs, Object owner, String[] aliases, ISessionImplementor session) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Collection\Generic\PersistentGenericSet.cs(54,0): at NHibernate.Collection.Generic.PersistentGenericSet`1.ReadFrom(IDataReader rs, ICollectionPersister role, ICollectionAliases descriptor, Object owner) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Loader\Loader.cs(706,0): at NHibernate.Loader.Loader.ReadCollectionElement(Object optionalOwner, Object optionalKey, ICollectionPersister persister, ICollectionAliases descriptor, IDataReader rs, ISessionImplementor session) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Loader\Loader.cs(385,0): at NHibernate.Loader.Loader.ReadCollectionElements(Object[] row, IDataReader resultSet, ISessionImplementor session) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Loader\Loader.cs(326,0): at NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Loader\Loader.cs(453,0): at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Loader\Loader.cs(236,0): at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Loader\Loader.cs(1649,0): at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Loader\Loader.cs(1568,0): at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Loader\Loader.cs(1562,0): at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Loader\Criteria\CriteriaLoader.cs(73,0): at NHibernate.Loader.Criteria.CriteriaLoader.List(ISessionImplementor session) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Impl\SessionImpl.cs(1936,0): at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Impl\CriteriaImpl.cs(246,0): at NHibernate.Impl.CriteriaImpl.List(IList results) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Impl\CriteriaImpl.cs(237,0): at NHibernate.Impl.CriteriaImpl.List() c:\opt\nhibernate\2.1.2\source\src\NHibernate\Impl\CriteriaImpl.cs(398,0): at NHibernate.Impl.CriteriaImpl.UniqueResult() c:\opt\nhibernate\2.1.2\source\src\NHibernate\Impl\CriteriaImpl.cs(263,0): at NHibernate.Impl.CriteriaImpl.UniqueResult[T]() D:\proj\CMS3\branches\nh_auth\DomainModel2Tests\Authorization\TempTests.cs(46,0): at CMS.DomainModel.Authorization.TempTests.Test1() Inner Exception System.Collections.Generic.KeyNotFoundException Message: The given key was not present in the dictionary. Source: mscorlib StackTrace: at System.ThrowHelper.ThrowKeyNotFoundException() at System.Collections.Generic.Dictionary`2.get_Item(TKey key) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Persister\Entity\AbstractEntityPersister.cs(2047,0): at NHibernate.Persister.Entity.AbstractEntityPersister.GetAppropriateUniqueKeyLoader(String propertyName, IDictionary`2 enabledFilters) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Persister\Entity\AbstractEntityPersister.cs(2037,0): at NHibernate.Persister.Entity.AbstractEntityPersister.LoadByUniqueKey(String propertyName, Object uniqueKey, ISessionImplementor session) c:\opt\nhibernate\2.1.2\source\src\NHibernate\Type\EntityType.cs(552,0): at NHibernate.Type.EntityType.LoadByUniqueKey(String entityName, String uniqueKeyPropertyName, Object key, ISessionImplementor session) I'm using NHibernate 2.1.2 and I've been debugging into the NHibernate source, but I'm coming up empty. Any suggestions? Thanks so much!

    Read the article

  • Collection.contains(Enum.Value) in HQL?

    - by Seth
    I'm a little confused about how to do something in HQL. So let's say I have a class Foo that I'm persisting in hibernate. It contains a set of enum values, like so: public class Foo { @CollectionOfElements private Set<Bar> barSet = new HashSet<Bar>(); //getters and setters here ... } and public enum Bar { A, B } Is there an HQL statement I can use to fetch only Foo instances who'se barSet containst Bar.B? List foos = session.createQuery("from Foo as foo " + "where foo.barSet.contains.Bar.B").list(); Or am I stuck fetching all Foo instances and filtering them out at the DAO level? List foos = session.createQuery("from Foo as foo").list(); List results = new ArrayList(); for(Foo f : foos) { if(f.barSet.contains(Bar.B)) results.add(f); } Thanks!

    Read the article

  • Hibernate exception

    - by Mark
    Hi all, im new to hibernate! i have followed the netbeans tutorial on creating a hibernate enabled application. after sucessfully creating a database in mysql workbench i reversed engineered the pojos etc and then tried to run a simple query(from Course) and got the following org.hibernate.MappingException: An association from the table coursemodule refers to an unmapped class: DAL.Module at org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1252) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1170) at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:324) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1286) at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859) heres the generated class for Course package DAL; // Generated 02-May-2010 16:41:16 by Hibernate Tools 3.2.1.GA import java.util.HashSet; import java.util.Set; /** * Course generated by hbm2java */ public class Course implements java.io.Serializable { private int id; private String name; private Set<Module> modules = new HashSet<Module>(0); public Course() { } public Course(int id, String name) { this.id = id; this.name = name; } public Course(int id, String name, Set<Module> modules) { this.id = id; this.name = name; this.modules = modules; } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Set<Module> getModules() { return this.modules; } public void setModules(Set<Module> modules) { this.modules = modules; } } and its config file course.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 02-May-2010 16:41:16 by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="DAL.Course" table="course" catalog="walkthrough"> <id name="id" type="int"> <column name="id" /> <generator class="assigned" /> </id> <property name="name" type="string"> <column name="name" not-null="true" /> </property> <set name="modules" inverse="false" table="coursemodule"> <key> <column name="courseId" not-null="true" unique="true" /> </key> <many-to-many entity-name="DAL.Module"> <column name="moduleId" not-null="true" unique="true" /> </many-to-many> </set> </class> </hibernate-mapping> hibernate.reveng.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd"> <hibernate-reverse-engineering> <schema-selection match-catalog="Walkthrough"/> <table-filter match-name="walkthrough"/> <table-filter match-name="course"/> <table-filter match-name="module"/> <table-filter match-name="studentmodule"/> <table-filter match-name="attendee"/> <table-filter match-name="student"/> <table-filter match-name="coursemodule"/> <table-filter match-name="session"/> <table-filter match-name="test"/> </hibernate-reverse-engineering> hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/Walkthrough</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.current_session_context_class">thread</property> <mapping resource="DAL/Student.hbm.xml"/> <mapping resource="DAL/Walkthrough.hbm.xml"/> <mapping resource="DAL/Test.hbm.xml"/> <mapping resource="DAL/Module.hbm.xml"/> <mapping resource="DAL/Session.hbm.xml"/> <mapping resource="DAL/Course.hbm.xml"/> </session-factory> </hibernate-configuration> any ideas on why im getting this exception? ps. test is just a table with an id in it and is not related to anything. running "from Test" works

    Read the article

  • java: Preferences API vs. Apache Commons Configuration

    - by Jason S
    I need to allow the user to store/load an arbitrary number of lists of objects (assume they are Serializable). Conceptually I want a data model like class FooBean { /* bean stuff here */ } class FooList { final private Set<FooBean> items = new HashSet<FooBean>(); public boolean add(FooBean item) { return items.add(item); } public boolean remove(FooBean item) { return items.remove(item); } public Collection<FooBean> getItems() { return Collections.unmodifiableSet(items); } } class FooStore { public FooStore() { /* something... uses Preferences or Commons Configuration */ } public FooList load(String key) { /* something... retrieves a FooList associated with the key */ } public void store(String key, FooList items) { /* something... saves a FooList under the given key */ } } Should I use the Preferences API or Commons Config? What's the advantages of each?

    Read the article

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