Search Results

Search found 1372 results on 55 pages for 'userid'.

Page 19/55 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • C++ Builder 2010 Exception Dead Lock ???

    - by James
    Hello Is this some kind of exception dead lock i am facing? How to avoid it ? Have a look at below line where i have TIdContext objects of connected clients stored in an objlist and at times i need to process it. But if one user is disconnected while another thread is processing the list, then for that freed TIdContext-Data object I am getting Access voilation, Ok its fine i am using try/catch but problem is that at below line there is some kind of dead lock and process hangs , if i attach a debuger it show Access voilation Again and Again and Again, and cpu coonsumption goes up because of that exception dead lock. AnsiString UserID = ((Tmyobject*) ((TIdContext*) ObjList->Objects[i])->Data)->UserID; i know i can check before accessing the object, if object is not Null, It works.. But my question is what if once in a blue moon the Data object is freed at the point when NULL check is performed and on next line when again i am accessing the object i get same dead lock ??? So how to avoid/handle this dead lock exception ? Here is the call stack... :005F07C0 System::AnsiStringBase::AnsiStringBase(this=:0285FCE0, src=????) :0040223F System::AnsiStringT<0>::AnsiStringT<0>(this=:0285FCE0, src=:00000008) :00457996 TSomeClass::SomeFunction(this=:009D8230, UserID={ }, DataSize={ }, ) :0047BFF1 __linkproc__ ThreadProc(Thread=:009561C0) :004AD00E __linkproc__ ThreadWrapper(Parameter=:009EAA30) :7c80b729 ; C:\WINDOWS\system32\kernel32.dll Please helppppppppppppppppppppp Thanks

    Read the article

  • Entity Framework - Many to Many Subquery

    - by Jorin
    I asked a question about this previously but my database structure has changed, and while it made other things simpler, now this part is more complicated. Here is the previous question. At the time, my EF Context had a UsersProjects object because there were other properties. Now that I've simplified that table, it is just the keys, so all my EF context knows about is Users and Projects and the M2M relationship between them. There is no more UsersProjects as far as EF knows. So my goal is to say "show me all the users who are working on projects with me." in SQL, this would go something like: SELECT * FROM Users INNER JOIN UsersProjects ON Users.ID=UsersProjects.UserID WHERE ProjectID IN (SELECT ProjectID FROM UsersProjects WHERE UserID=@UserID) and I started in EF with something like this: var myProjects = (from p in edmx.Projects where p.Users.Contains(edmx.Users.FirstOrDefault(u => u.Email == UserEmail)) orderby p.Name select p).ToList(); var associatedUsers = (from u in edmx.Users where myProjects.Contains(?????????) //where myProjects.Any(????????) select u); The trick is finding what to put in the ????????. Anyone help here?

    Read the article

  • "A generic error occurred in GDI+" error while showing uploaded images

    - by Prasad
    i am using the following code to show the image that has been saved in my database from my asp.net mvc(C#) application:. public ActionResult GetSiteHeaderLogo() { SiteHeader _siteHeader = new SiteHeader(); Image imgImage = null; long userId = Utility.GetUserIdFromSession(); if (userId > 0) { _siteHeader = this.siteBLL.GetSiteHeaderLogo(userId); if (_siteHeader.Logo != null && _siteHeader.Logo.Length > 0) { byte[] _imageBytes = _siteHeader.Logo; if (_imageBytes != null) { using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream(_imageBytes)) { imgImage = Image.FromStream(imageStream); } } string sFileExtension = _siteHeader.FileName.Substring(_siteHeader.FileName.IndexOf('.') + 1, _siteHeader.FileName.Length - (_siteHeader.FileName.IndexOf('.') + 1)); Response.ContentType = Utility.GetContentTypeByExtension(sFileExtension.ToLower()); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.BufferOutput = false; if (imgImage != null) { ImageFormat _imageFormat = Utility.GetImageFormat(sFileExtension.ToLower()); imgImage.Save(Response.OutputStream, _imageFormat); imgImage.Dispose(); } } } return new EmptyResult(); } It works fine when i upload original image. But when i upload any downloaded images, it throws the following error: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) at System.Drawing.Image.Save(Stream stream, ImageFormat format) For. Ex: When i upload the original image, it shows as logo in my site and i downloaded that logo from the site and when i re-upload the same downloaded image, it throws the above error. It seems very weird to me and not able to find why its happening. Any ideas on this?

    Read the article

  • C# Dataset Dynamically Add DataColumn

    - by Wesley
    I am trying to add a extra column to a dataset after a query has completed. I have a database relationship of the following: Employees / \ Groups EmployeeGroups Empoyees holds all the data for that individual, I'll name the unique key the UserID. Groups holds all the groups that a employee can be a part of, i.e. Super User, Admin, User; etc. I will name the unique key GroupID EmployeeGroups holds all the associations of which groups each employee belongs too. (UserID | GroupID) What I am trying to accomplish is after querying for a all users I want to loop though each user and add what groups that user is a part of by adding a new column to the dataset named 'Groups' which is a string to insert the values of the next query to get all the groups that user is a part of. Then by user of databinding populate a listview with all employees and their group associations My code is as follows; Position 5 is the new column I am trying to add to the dataset. string theQuery = "select UserID, FirstName, LastName, EmployeeID, Active from Employees"; DataSet theEmployeeSet = itsDatabase.runQuery(theQuery); DataColumn theCol = new DataColumn("Groups", typeof(string)); theEmployeeSet.Tables[0].Columns.Add(theCol); foreach (DataRow theRow in theEmployeeSet.Tables[0].Rows) { theRow.ItemArray[5] = "1234"; } At the moment, the code will create the new column but when i assign the data to that column nothing will be assigned, what am I missing? If there is any further explination or information I can provide, please let me know. Thank you all

    Read the article

  • Error occurs while validating form input using jQuery in Firebug

    - by Param-Ganak
    I have written a custom validation code in jQuery, which is working fine. I have a login form which has two fields, i.e. userid and password. I have written a custom code for client side validation for these fields. This code is working fine and gives me proper error messages as per the situation. But the problem with this code is that when I enter the invalid data in any or both field and press submit button of form then it displays the proper error message but at the same time when I checked it in Firebug it displays following error message when submit button of the form is clicked validate is not defined function onclick(event) { javascript: return validate(); } (click clientX=473, clientY=273) Here is the JQUERY validation code $(document).ready(function (){ $("#id_login_form").validate({ rules: { userid: { required: true, minlength: 6, maxlength: 20, // basic: true }, password: { required: true, minlength: 6, maxlength: 15, // basic: true } }, messages: { userid: { required: " Please enter the username.", minlength: "User Name should be minimum 6 characters long.", maxlength: "User Name should be maximum 15 characters long.", // basic: "working here" }, password: { required: " Please enter the password.", minlength: "Password should be minimum 6 characters long.", maxlength: "Password should be maximum 15 characters long.", // basic: "working here too.", } }, errorClass: "errortext", errorLabelContainer: "#messagebox" } }); }); /* $.validator.addMethod('username_alphanum', function (value) { return /^(?![0-9]+$)[a-zA-Z 0-9_.]+$/.test(value); }, 'User name should be alphabetic or Alphanumeric and may contain . and _.'); $.validator.addMethod('alphanum', function (value) { return /^(?![a-zA-Z]+$)(?![0-9]+$)[a-zA-Z 0-9]+$/.test(value); }, 'Password should be Alphanumeric.'); $.validator.addMethod('basic', function (value) { return /^[a-zA-Z 0-9_.]+$/.test(value); }, 'working working working'); */ So please tell me where is I am wrong in my jQuery code. Thank You!

    Read the article

  • Increase and decrease row value by 1 in MySQL

    - by Elliott
    Hi I have a MySQL database table "points" the user can click a button and a point should be removed from their account, the button they pressed has an ID of another user, therefore their account must increase by one. I have it working in jQuery and checked the varibles/posts in Firebug, and it does send the correct data, such as: userid= 1 posterid = 4 I think the problem is with my PHP page: <?php include ('../functions.php'); $userid=mysql_real_escape_string($_POST['user_id']); $posterid=mysql_real_escape_string($_POST['poster_id']); if (loggedin()) { include ('../connection.php'); $query1 = "UPDATE `points` SET `points` = `points` - 1 WHERE `userID` = '$userid'"; $result1=mysql_query($query1); $query2 = "UPDATE `points` SET `points` = `points` + 1 WHERE `userID` = '$posterid'"; $result2=mysql_query($query2); if ($result1 && result2) { echo "Successful"; return 1; } else { echo mysql_error(); return 0; } } ?> Any ideas? Thanks :)

    Read the article

  • Inefficient 'ANY' LINQ clause

    - by Focus
    I have a query that pulls back a user's "feed" which is essentially all of their activity. If the user is logged in the query will be filtered so that the feed not only includes all of the specified user's data, but also any of their friends. The database structure includes an Actions table that holds the user that created the action and a UserFriends table which holds any pairing of friends using a FrienderId and FriendeeId column which map to UserIds. I have set up my LINQ query and it works fine to pull back the data I want, however, I noticed that the query gets turned into X number of CASE clauses in profiler where X is the number of total Actions in the database. This will obviously be horrible when the database has a user base larger than just me and 3 test users. Here's the SQL query I'm trying to achieve: select * from [Action] a where a.UserId = 'GUID' OR a.UserId in (SELECT FriendeeId from UserFriends uf where uf.FrienderId = 'GUID') OR a.UserId in (SELECT FrienderId from UserFriends uf where uf.FriendeeId = 'GUID') This is what I currently have as my LINQ query. feed = feed.Where(o => o.User.UserKey == user.UserKey || db.Users.Any(u => u.UserFriends.Any(ufr => ufr.Friender.UserKey == user.UserKey && ufr.isApproved) || db.Users.Any(u2 => u2.UserFriends.Any(ufr => ufr.Friendee.UserKey == user.UserKey && ufr.isApproved) ))); This query creates this: http://pastebin.com/UQhT90wh That shows up X times in the profile trace, once for each Action in the table. What am I doing wrong? Is there any way to clean this up?

    Read the article

  • Struts2 Hibernate Login with User table and group table

    - by J2ME NewBiew
    My problem is, i have a table User and Table Group (this table use to authorization for user - it mean when user belong to a group like admin, they can login into admincp and other user belong to group member, they just only read and write and can not login into admincp) each user maybe belong to many groups and each group has been contain many users and they have relationship are many to many I use hibernate for persistence storage. and struts 2 to handle business logic. When i want to implement login action from Struts2 how can i get value of group member belong to ? to compare with value i want to know? Example I get user from username and password then get group from user class but i dont know how to get value of group user belong to it mean if user belong to Groupid is 1 and in group table , at column adminpermission is 1, that user can login into admincp, otherwise he can't my code: User.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.dejavu.software.model; import java.io.Serializable; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.persistence.Temporal; /** * * @author Administrator */ @Entity @Table(name="User") public class User implements Serializable{ private static final long serialVersionUID = 2575677114183358003L; private Long userId; private String username; private String password; private String email; private Date DOB; private String address; private String city; private String country; private String avatar; private Set<Group> groups = new HashSet<Group>(0); @Column(name="dob") @Temporal(javax.persistence.TemporalType.DATE) public Date getDOB() { return DOB; } public void setDOB(Date DOB) { this.DOB = DOB; } @Column(name="address") public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Column(name="city") public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Column(name="country") public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @Column(name="email") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinTable(name="usergroup",joinColumns={@JoinColumn(name="userid")},inverseJoinColumns={@JoinColumn( name="groupid")}) public Set<Group> getGroups() { return groups; } public void setGroups(Set<Group> groups) { this.groups = groups; } @Column(name="password") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Id @GeneratedValue @Column(name="iduser") public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } @Column(name="username") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Column(name="avatar") public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } } Group.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.dejavu.software.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * * @author Administrator */ @Entity @Table(name="Group") public class Group implements Serializable{ private static final long serialVersionUID = -2722005617166945195L; private Long idgroup; private String groupname; private String adminpermission; private String editpermission; private String modpermission; @Column(name="adminpermission") public String getAdminpermission() { return adminpermission; } public void setAdminpermission(String adminpermission) { this.adminpermission = adminpermission; } @Column(name="editpermission") public String getEditpermission() { return editpermission; } public void setEditpermission(String editpermission) { this.editpermission = editpermission; } @Column(name="groupname") public String getGroupname() { return groupname; } public void setGroupname(String groupname) { this.groupname = groupname; } @Id @GeneratedValue @Column (name="idgroup") public Long getIdgroup() { return idgroup; } public void setIdgroup(Long idgroup) { this.idgroup = idgroup; } @Column(name="modpermission") public String getModpermission() { return modpermission; } public void setModpermission(String modpermission) { this.modpermission = modpermission; } } UserDAO /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.dejavu.software.dao; import java.util.List; import org.dejavu.software.model.User; import org.dejavu.software.util.HibernateUtil; import org.hibernate.Query; import org.hibernate.Session; /** * * @author Administrator */ public class UserDAO extends HibernateUtil{ public User addUser(User user){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); session.save(user); session.getTransaction().commit(); return user; } public List<User> getAllUser(){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); List<User> user = null; try { user = session.createQuery("from User").list(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } session.getTransaction().commit(); return user; } public User checkUsernamePassword(String username, String password){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); User user = null; try { Query query = session.createQuery("from User where username = :name and password = :password"); query.setString("username", username); query.setString("password", password); user = (User) query.uniqueResult(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } session.getTransaction().commit(); return user; } } AdminLoginAction /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.dejavu.software.view; import com.opensymphony.xwork2.ActionSupport; import org.dejavu.software.dao.UserDAO; import org.dejavu.software.model.User; /** * * @author Administrator */ public class AdminLoginAction extends ActionSupport{ private User user; private String username,password; private String role; private UserDAO userDAO; public AdminLoginAction(){ userDAO = new UserDAO(); } @Override public String execute(){ return SUCCESS; } @Override public void validate(){ if(getUsername().length() == 0){ addFieldError("username", "Username is required"); }if(getPassword().length()==0){ addFieldError("password", getText("Password is required")); } } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } other question. i saw some example about Login, i saw some developers use interceptor, im cant understand why they use it, and what benefit "Interceptor" will be taken for us? Thank You Very Much!

    Read the article

  • Storing values in the DataValueField and DataTextField of a dropdownlist using a linq query

    - by user1318369
    I have a website for dance academy where Users can register and add/drop dance classes. In the web page to drop a particular dance, for a particular user, the dropdown displays her registered dances. Now I want to delete one of the dances from the list. So I'll remove the row from the table and also from the dropdownlist. The problem is that everytime the item with the lowest ID (index) is getting deleted, no matter which one the user selects. I think I am storing the DataTextField and DataValueField for the dropdown incorrectly. The code is: private void PopulateDanceDropDown() { // Retrieve the username MembershipUser currentUser = Membership.GetUser(); var username = currentUser.UserName; // Retrive the userid of the curren user var dancerIdFromDB = from d in context.DANCER where d.UserName == username select d.UserId; Guid dancerId = new Guid(); var first = dancerIdFromDB.FirstOrDefault(); if (first != null) { dancerId = first; } dances.DataSource = (from dd in context.DANCER_AND_DANCE where dd.UserId == dancerId select new { Text = dd.DanceName, Value = dd.DanceId }).ToList(); dances.DataTextField = "Text"; dances.DataValueField = "Value"; dances.DataBind(); } protected void dropthedance(object o, EventArgs e) { String strDataValueField = dances.SelectedItem.Value; int danceIDFromDropDown = Convert.ToInt32(strDataValueField); var dancer_dance = from dd in context.DANCER_AND_DANCE where dd.DanceId == danceIDFromDropDown select dd; foreach (var dndd in dancer_dance) { context.DANCER_AND_DANCE.DeleteOnSubmit(dndd); } try { context.SubmitChanges(); } catch (Exception ex) { Console.WriteLine(ex); } } The problem is in the line: String strDataValueField = dances.SelectedItem.Value; The strDataValueField is always getting the minimum id from the list of dance item ids in the dropdown (which happens by default). I want this to hold the id of the dance selected by the user.

    Read the article

  • Dependencyproperty doesn't have value on load

    - by Jakob
    My problem is this, I have a UC called profile that contains another UC called FollowImageControl. In my Profile.xaml i declaretively bind a property of FollowImageControl called FollowerId to a CurrentUserId from Profile.xaml.cs. Problem is that I CurrentUserId is assigned in Profile.xaml.cs; the Profile.xaml code-behind. This means that I do not initially get the FollowerId. I have these methods in the FollowImageControl.xaml.cs: public static readonly DependencyProperty _followUserId = DependencyProperty.Register("FollowUserId", typeof(Guid), typeof(FollowImageControl), null); public Guid FollowUserId { get { return (Guid)GetValue(_followUserId); } set { SetValue(_followUserId, value); } } public FollowImageControl() { // Required to initialize variables InitializeComponent(); LoggedInUserId = WebContext.Current.User.UserId; var ctx = new NotesDomainContext(); if (ctx.IsFollowingUser(LoggedInUserId, FollowUserId).Value) SwitchToDelete.Begin(); } private void AddImg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (LoggedInUserId != FollowUserId) { var ctx = new NotesDomainContext(); ctx.FollowUser(FollowUserId, LoggedInUserId); ctx.SubmitChanges(); } } THE WEIRD THING IS that when i insert breakpoints the FollowerUserId in FollowImageControl() is 0, but it has a value in AddImg_MouseLeftButtonDown, and there is no inbetween logic that sets the value of it. How is this??? Here's a little more code info: This is my binding from profile.xaml <internalCtrl:FollowImageControl FollowUserId="{Binding ElementName=ProfileCtrl, Path=CurrentUserId}" /> this is my constructor in profile.xaml.cs wherein the CurrentUserId is set public static readonly DependencyProperty _CurrentUserId = DependencyProperty.Register("CurrentUserId", typeof(Guid), typeof(Profile), null); public Guid CurrentUserId { get { return (Guid)GetValue(_CurrentUserId); } set { SetValue(_CurrentUserId, value); } } public Profile(Guid UserId) { CurrentUserId = UserId; InitializeComponent(); Loaded += new RoutedEventHandler(Profile_Loaded); } I'm seriously dumbfound that one minute the FollowerId has no value, and the next it holds the right, without me having changed the value in the code-behind.

    Read the article

  • Basic user authentication with records in AngularFire

    - by ajkochanowicz
    Having spent literally days trying the different, various recommended ways to do this, I've landed on what I think is the most simple and promising. Also thanks to the kind gents from this SO question: Get the index ID of an item in Firebase AngularFire Curent setup Users can log in with email and social networks, so when they create a record, it saves the userId as a sort of foreign key. Good so far. But I want to create a rule so twitter2934392 cannot read facebook63203497's records. Off to the security panel Match the IDs on the backend Unfortunately, the docs are inconsistent with the method from is firebase user id unique per provider (facebook, twitter, password) which suggest appending the social network to the ID. The docs expect you to create a different rule for each of the login method's ids. Why anyone using 1 login method would want to do that is beyond me. (From: https://www.firebase.com/docs/security/rule-expressions/auth.html) So I'll try to match the concatenated auth.provider with auth.id to the record in userId for the respective registry item. According to the API, this should be as easy as In my case using $registry instead of $user of course. { "rules": { ".read": true, ".write": true, "registry": { "$registry": { ".read": "$registry == auth.id" } } } } But that won't work, because (see the first image above), AngularFire sets each record under an index value. In the image above, it's 0. Here's where things get complicated. Also, I can't test anything in the simulator, as I cannot edit {some: 'json'} To even authenticate. The input box rejects any input. My best guess is the following. { "rules": { ".write": true, "registry": { "$registry": { ".read": "data.child('userId').val() == (auth.provider + auth.id)" } } } } Which both throws authentication errors and simultaneously grants full read access to all users. I'm losing my mind. What am I supposed to do here?

    Read the article

  • How to show alert in a jsp from a servlet and then redirect to another jsp?

    - by Xaul Omar Tobar
    I tried this but does not display the message only redirects login.jsp <form method="post" action="Login_Servlet" > <input name="idUsuario" type="text"/> <input name="password" type="password" /> <button type="submit">Entrar</button> </form> Login_Servlet response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String userid= request.getParameter("idUser"); String password = request.getParameter("password"); Login_Service login_Service = new Login_Service(); boolean result = login_Servicio.aut(userid, password); Usuario user = login_Servicio.getUsuariosByUsuario(userid); if(result == true){ request.getSession().setAttribute("user", user); response.sendRedirect("vistas/Inicio.jsp"); } else{ out.println("<script type=\"text/javascript\">"); out.println("alert('User or password incorrect');"); out.println("</script>"); response.sendRedirect("index.jsp"); } Is it possible to display a message like this? if so I'm doing wrong?

    Read the article

  • Saving Data to Relational Database (Entity Framework)

    - by sheefy
    I'm having a little bit of trouble saving data to a database. Basically, I have a main table that has associations to other tables (Example Below). Tbl_Listing ID UserID - Associated to ID in User Table CategoryID - Associated to ID in Category Table LevelID - Associated to ID in Level Table. Name Address Normally, it's easy for me to add data to the DB (using Entity Framework). However, I'm not sure how to add data to the fields with associations. The numerous ID fields just need to hold an int value that corresponds with the ID in the associated table. For example; when I try to access the column in the following manner I get a "Object reference not set to an instance of an object." error. Listing NewListing = new Listing(); NewListing.Tbl_User.ID = 1; NewListing.Tbl_Category.ID = 2; ... DBEntities.AddToListingSet(NewListing); DBEntities.SaveChanges(); I am using NewListing.Tbl_User.ID instead of NewListing.UserID because the UserID field is not available through intellisense. If I try and create an object for each related field I get a "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects." error. With this method, I am trying to add the object without the .ID shown above - example NewListing.User = UserObject. I know this should be simple as I just want to reference the ID from the associated table in the main Listing's table. Any help would be greatly appreciated. Thanks in advance, -S

    Read the article

  • Mapping many-to-many association table with extra column(s)

    - by user635524
    My database contains 3 tables: User and Service entities have many-to-many relationship and are joined with the SERVICE_USER table as follows: USERS - SERVICE_USER - SERVICES SERVICE_USER table contains additional BLOCKED column. What is the best way to perform such a mapping? These are my Entity classes @Entity @Table(name = "USERS") public class User implements java.io.Serializable { private String userid; private String email; @Id @Column(name = "USERID", unique = true, nullable = false,) public String getUserid() { return this.userid; } .... some get/set methods } @Entity @Table(name = "SERVICES") public class CmsService implements java.io.Serializable { private String serviceCode; @Id @Column(name = "SERVICE_CODE", unique = true, nullable = false, length = 100) public String getServiceCode() { return this.serviceCode; } .... some additional fields and get/set methods } I followed this example http://giannigar.wordpress.com/2009/09/04/m ... using-jpa/ Here is some test code: User user = new User(); user.setEmail("e2"); user.setUserid("ui2"); user.setPassword("p2"); CmsService service= new CmsService("cd2","name2"); List<UserService> userServiceList = new ArrayList<UserService>(); UserService userService = new UserService(); userService.setService(service); userService.setUser(user); userService.setBlocked(true); service.getUserServices().add(userService); userDAO.save(user); The problem is that hibernate persists User object and UserService one. No success with the CmsService object I tried to use EAGER fetch - no progress Is it possible to achieve the behaviour I'm expecting with the mapping provided above? Maybe there is some more elegant way of mapping many to many join table with additional column?

    Read the article

  • While in a transaction, how can reads to an affected row be prevented until the transaction is done?

    - by Mahn
    I'm fairly sure this has a simple solution, but I haven't been able to find it so far. Provided an InnoDB MySQL database with the isolation level set to SERIALIZABLE, and given the following operation: BEGIN WORK; SELECT * FROM users WHERE userID=1; UPDATE users SET credits=100 WHERE userID=1; COMMIT; I would like to make sure that as soon as the select inside the transaction is issued, the row corresponding to userID=1 is locked for reads until the transaction is done. As it stands now, UPDATEs to this row will wait for the transaction to be finished if it is in process, but SELECTs simply will read the previous value. I understand this is the expected behaviour in this case, but I wonder if there is a way to lock the row in such a way that SELECTs will also wait until the transaction is finished to return the values? The reason I'm looking for that is that at some point, and with enough concurrent users, it could happen that while the previous transaction is in process someone else reads the "credits" to calculate something else. Ideally the code run by that someone else should wait for the transaction to finish to use the new value, because otherwise it could lead to irreversible desync issues. Note that I don't want to lock the entire table for reads, just the specific row. Also, I could add a boolean "locked" field to the tables and set it to 1 every time I'm starting a transaction but I don't really feel this is the most elegant solution here, unless there is absolutely no other way to handle this through mysql directly.

    Read the article

  • Value is zero after filter SQL in C#

    - by Chuki2
    I`m new in C#.. I have write function to filter department. And this function will return idDepartment. New problem is, department keep value "System.Windows.Forms.Label, Text : ADMIN ", that`s why i got zero. So how can i take "ADMIN" only and keep to department? Update : public partial class frmEditStaff : Form { private string connString; private string userId, department; //Department parameter coming from here private string conString = "Datasource"; public frmEditStaff(string strUserID, string strPosition) { InitializeComponent(); //Pass value from frmListStaff to userID text box tbStaffId.Text = strUserID.ToString(); userId = strUserID.ToString(); department = strPosition.ToString(); } This code below is working, don`t have any problem. public int lookUpDepart() { int idDepart=0; using (SqlConnection openCon = new SqlConnection(conString)) { string lookUpDepartmenId = "SELECT idDepartment FROM tbl_department WHERE department = '" + department + "';"; openCon.Open(); using (SqlCommand querylookUpDepartmenId = new SqlCommand(lookUpDepartmenId, openCon)) { SqlDataReader read = querylookUpDepartmenId.ExecuteReader(); while (read.Read()) { idDepart = int.Parse(read[0].ToString()); break; } } openCon.Close(); return idDepart; } } Thanks for help. Happy nice day!

    Read the article

  • How to find intersect rows when condition depend on some columns in one table

    - by user3695637
    Table subscribe subscriber | subscribeto (columns) 1 | 5 1 | 6 1 | 7 1 | 8 1 | 9 1 | 10 2 | 5 2 | 6 2 | 7 There are two users that have id 1 and 2. They subscribe to various user and I inserted these data to table subscribe. Column subscriber indicates who is subscriber and column subscribeto indicates who they've subscribe to. From the above table can conclude that; user id=1 subscribed to 6 users user id=2 subscribed to 3 users I want to find manual of subscription (like Facebook is manual friends) user 1 subscribe to user 5,6,7,8,9,10 user 2 subscribe to user 5,6,7 So, Manual subscription of user 1 and 2 are: 5,6,7 And I'm trying to create SQL statement.. I give you user table for my SQL statement and I think we can use only subscribe table but I can't figure out. Table user userid (columns) 1 2 3 ... ... SQL "select * from user where (select count( 1 ) from subscribe where subscriber = '1' and subscribeto = user.userid) and (select count( 1 ) from subscribe where subscriber = '2' and subscribeto = user.userid);" This SQL can work correctly, but it very slow for thousands of columns. Please provide better SQL for me, Thanks.

    Read the article

  • Adding a MySQL StoredProcedure causes not responding state

    - by Omie
    Hello I'm on Windows 7 ultimate 32bit + xampp 1.7.2 [MySQL v5.1.37] This is my stored procedure : delimiter // CREATE PROCEDURE updatePoints(IN parentid INT(5),IN userid INT(5)) DECLARE chpoints INT(5); BEGIN SELECT points INTO chpoints FROM quiz_challenges WHERE id = parentid; UPDATE quiz_users SET points = points + chpoints WHERE forumid=userid; END; // delimiter ; At first it was showing error 1064 while creating stored procedure. I added delimiters part and when I tried running the query from phpmyadmin, Firefox went into not responding state. After that I started Internet Explorer and tried opening my pages which use the same database, it worked fine. However, I tried opening phpmyadmin and IE went into not responding state as well. I restarted both servers. Later restarted PC. Tried again but its same behavior. So whats wrong with this tiny little code ? Am I missing something which might be causing infinite loop ? Thanks

    Read the article

  • Adding a MySQL StoredProcedure causes not responding state

    - by Omie
    I'm on Windows 7 ultimate 32bit + xampp 1.7.2 [MySQL v5.1.37] This is my stored procedure : delimiter // CREATE PROCEDURE updatePoints(IN parentid INT(5),IN userid INT(5)) DECLARE chpoints INT(5); BEGIN SELECT points INTO chpoints FROM quiz_challenges WHERE id = parentid; UPDATE quiz_users SET points = points + chpoints WHERE forumid=userid; END; // delimiter ; At first it was showing error 1064 while creating stored procedure. I added delimiters part and when I tried running the query from phpmyadmin, Firefox went into not responding state. After that I started Internet Explorer and tried opening my pages which use the same database, it worked fine. However, I tried opening phpmyadmin and IE went into not responding state as well. I restarted both servers. Later restarted PC. Tried again but its same behavior. So whats wrong with this tiny little code ? Am I missing something which might be causing infinite loop ? Thanks

    Read the article

  • SubSonic Stored Procedure Issue - Data Generated at Stored Procedure is different from Data Received

    - by ShaShaIn
    Hi All, I am facing a unknown problem while using stored procedure with SubSonic. I have written a stored procedure & application code that takes first name & last name as input parameter and return last login id as ouput parameter. It creates login id as first character of first name & complete last name for no-existing login id otherwise it adds 1 in the last login id e.g. First Name - Mark, Last Name - Waugh, First Login Id - MWaugh, Second Login Id - MWaugh1, Third Login Id - MWaugh2 etc. Stored Procedure SET ANSI_NULLS OFF GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[Users_FetchLoginId] ( @FirstName nvarchar(64), @LastName nvarchar(64), @LoginId nvarchar(256) OUTPUT ) AS DECLARE @UserId nvarchar(256); SET @UserId = NULL; SET @LoginId = NULL; SELECT @UserId = LoweredUserName FROM aspnet_Users WHERE LoweredUserName LIKE (LOWER(SUBSTRING(@FirstName,1,1) + @LastName)) IF @@rowcount = 0 OR @UserId IS NULL BEGIN SET @LoginId = (SUBSTRING(@FirstName, 1, 1) + @LastName); print @LoginId RETURN 1; END ELSE BEGIN SELECT TOP 1 LoweredUserName FROM aspnet_Users WHERE LoweredUserName LIKE (LOWER(SUBSTRING(@FirstName,1,1) + @LastName + '%')) ORDER BY LoweredUserName DESC RETURN 2; END Application Code public string FetchLoginId(string firstName, string lastName) { SubSonic.StoredProcedure sp = SPs.UsersFetchLoginId( firstName, lastName, null ); sp.Command.AddReturnParameter(); sp.Execute(); if (sp.Command.Parameters.Find(delegate(QueryParameter queryParameter) { return queryParameter.Mode == ParameterDirection.ReturnValue; }).ParameterValue != System.DBNull.Value) { int returnCode = Convert.ToInt32(sp.Command.Parameters.Find(delegate(QueryParameter queryParameter) { return queryParameter.Mode == ParameterDirection.ReturnValue; }).ParameterValue, CultureInfo.InvariantCulture); if (returnCode == 1) { // UserName as First Character of First Name & Full Last Name return sp.Command.Parameters[2].ParameterValue.ToString(); } if (returnCode == 2) { DataSet ds = sp.GetDataSet(); if (null == ds || null == ds.Tables[0] || 0 == ds.Tables[0].Rows.Count) return ""; string maxLoginId = ds.Tables[0].Rows[0]["LoweredUserName"].ToString(); string initialLoginId = firstName.Substring(0, 1) + lastName; int maxLoginIdIndex = 0; int initialLoginIdLength = initialLoginId.Length; if (maxLoginId.Substring(initialLoginIdLength).Length == 0) { maxLoginIdIndex++; // UserName as Max Lowered User Name Found & Incrementer as Suffix (Here, First Incrementer i.e. 1) return (initialLoginId + maxLoginIdIndex); } if (int.TryParse(maxLoginId.Substring(initialLoginIdLength), out maxLoginIdIndex)) { if (maxLoginIdIndex > 0) { maxLoginIdIndex++; // UserName as Max Lowered User Name Found & Incrementer as Suffix return (initialLoginId + maxLoginIdIndex); } } } } Now the problem is for some input (see test data below), the login id created at sql server end correctly but at application subsonic dal side, it truncates some characters. First Name - Jenelia and Last Name - Kanupatikenalaalayampentyalavelugoplansubhramanayam [dbo].[Users_FetchLoginId] - Execute Stored Procedure Separately - Login Id Is Correct JKanupatikenalaalayampentyalavelugoplansubhramanayam public string FetchLoginId(string firstName, string lastName) - Application Code DAL Side - LginId Is Wrongly Received From Stored Procedure JKanupatikenalaalayampentyalavelugoplansubhramanay You can easily see that 2 charactes are removed. If the data is correctly generated by stored procedure then why the characters are removed when data is received in output parameter of stored procedure? Is it due to any internal known or unknown bug of SubSonic? Your help is significant. Thanks in advance...

    Read the article

  • jquery small refactoring , json call

    - by Alexander Corotchi
    Hi everybody, I need you suggestion to make some refactoring in jquery code because now it looks terrible for me. I have 4 json calls but the difference it is just the URL call. EX: var userId = MyuserID; var perPage = '45'; var showOnPage = '45'; var tag = 'tag1'; var tag1 = 'tag2'; var tag2 = 'tagn'; $.getJSON('http://api.flickr.com/services/rest/?format=json&method='+ 'flickr.photos.search&api_key=' + apiKey + '&user_id=' + userId + '&tags=' + tag + '&per_page=' + perPage + '&jsoncallback=?', function(data){ var classShown = 'class="lightbox"'; var classHidden = 'class="lightbox hidden"'; $.each(data.photos.photo, function(i, rPhoto){ var basePhotoURL = 'http://farm' + rPhoto.farm + '.static.flickr.com/' + rPhoto.server + '/' + rPhoto.id + '_' + rPhoto.secret; var thumbPhotoURL = basePhotoURL + '_s.jpg'; var mediumPhotoURL = basePhotoURL + '.jpg'; var photoStringStart = '<li><a '; var photoStringEnd = 'title="' + rPhoto.title + '" href="'+ mediumPhotoURL +'"><img src="' + thumbPhotoURL + '" alt="' + rPhoto.title + '"/></a><span>'+rPhoto.title+'</span></li>;' var photoString = (i < showOnPage) ? photoStringStart + classShown + photoStringEnd : photoStringStart + classHidden + photoStringEnd; $(photoString).appendTo("#flickr ul"); }); $("#flickr a").fancybox(); }); $.getJSON('http://api.flickr.com/services/rest/?format=json&method='+ 'flickr.photos.search&api_key=' + apiKey + '&user_id=' + userId + '&tags=' + tag1 + '&per_page=' + perPage + '&jsoncallback=?', function(data){ var classShown = 'class="lightbox"'; var classHidden = 'class="lightbox hidden"'; $.each(data.photos.photo, function(i, rPhoto){ var basePhotoURL = 'http://farm' + rPhoto.farm + '.static.flickr.com/' + rPhoto.server + '/' + rPhoto.id + '_' + rPhoto.secret; var thumbPhotoURL = basePhotoURL + '_s.jpg'; var mediumPhotoURL = basePhotoURL + '.jpg'; var photoStringStart = '<li><a '; var photoStringEnd = 'title="' + rPhoto.title + '" href="'+ mediumPhotoURL +'"><img src="' + thumbPhotoURL + '" alt="' + rPhoto.title + '"/></a><span>'+rPhoto.title+'</span></li>;' var photoString = (i < showOnPage) ? photoStringStart + classShown + photoStringEnd : photoStringStart + classHidden + photoStringEnd; $(photoString).appendTo(".SetPinos1 ul"); }); $(".Sets a").fancybox(); }); $.getJSON('http://api.flickr.com/services/rest/?format=json&method='+ 'flickr.photos.search&api_key=' + apiKey + '&user_id=' + userId + '&tags=' + tagn + '&per_page=' + perPage + '&jsoncallback=?', function(data){ var classShown = 'class="lightbox"'; var classHidden = 'class="lightbox hidden"'; $.each(data.photos.photo, function(i, rPhoto){ var basePhotoURL = 'http://farm' + rPhoto.farm + '.static.flickr.com/' + rPhoto.server + '/' + rPhoto.id + '_' + rPhoto.secret; var thumbPhotoURL = basePhotoURL + '_s.jpg'; var mediumPhotoURL = basePhotoURL + '.jpg'; var photoStringStart = '<li><a '; var photoStringEnd = 'title="' + rPhoto.title + '" href="'+ mediumPhotoURL +'"><img src="' + thumbPhotoURL + '" alt="' + rPhoto.title + '"/></a><span>'+rPhoto.title+'</span></li>;' var photoString = (i < showOnPage) ? photoStringStart + classShown + photoStringEnd : photoStringStart + classHidden + photoStringEnd; $(photoString).appendTo(".SetPinos ul"); }); $(".Sets a").fancybox(); }); var tag is only one difference in this url : Can somebody help me not to repeat all this stuff ?? Sorry by so long garbage :(

    Read the article

  • Why do some Flask session values disappear from the session after closing the browser window, but then reappear later without me adding them?

    - by Ben
    So my understanding of Flask sessions is that I can use it like a dictionary and add values to a session by doing: session['key name'] = 'some value here' And that works fine. On a route I have the client call using AJAX post, I assign a value to the session. And it works fine. I can click on various pages of my site and the value stays in the session. If I close the browser window however, and then go back to my site, the session value I had in there is gone. So that's weird and you would think the problem is the session isn't permanent. I also implemented Flask-Openid and that uses the session to store information and that does persist if I close the browser window and open it back up again. I also checked the cookie after closing the browser window, but before going back to my site, and the cookie is indeed still there. Another odd piece of behaviour (which may be related) is that some values I have written to the session for testing purposes will go away when I access the AJAX post route and assign the correct value. So that is odd, but what is truly weird is that when I then close the browser window and open it up again, and have thus lost the value I was trying to retain, the ones that I lost previously actually return! They aren't being reassigned because there's no code in my Python files to reassign those values. Here is some outputs to helper make it clearer. They are all outputed from a route for a real page, and not the AJAX post route I mentioned above. This is the output after I have assigned the value I want to store in the session. The value key is 'userid' - all the other values are dummy ones I have added in trying to solve this problem. 'userid': 8 will stay in the session as long as I don't close the browser window. I can access other routes and the value will stay there just like it should. ['session.=', <SecureCookieSession {'userid': 8, 'test_variable_num': 102, 'adding using before request': 'hi', '_permanent': True, 'test_variable_text': 'hi!'}>] If I do close the browser window, and go back into the site, but without redoing the AJAX post request, I get this output: ['session.=', <SecureCookieSession {'adding using before request': 'hi', '_permanent': True, 'yo': 'yo'}>] The 'yo' value was not in the first first output. I don't know where it came from. I searched my code for 'yo' and there is no instances of me assigning that value anywhere. I think I may have added it to the session days ago. So it seems like it is persisting, but being hidden when the other values are written. And this last one is me accessing the AJAX post route again, and then going to the page that prints out the keys using debug. Same output as the first output I pasted above, which you would expect, and the 'yo' value is gone again (but it will come back if I close the browser window) ['session.=', <SecureCookieSession {'userid': 8, 'test_variable_num': 102, 'adding using before request': 'hi', '_permanent': True, 'test_variable_text': 'hi!'}>] I tested this in both Chrome and Firefox. So I find this all weird and I am guessing it stems from a misunderstanding of how sessions work. I think they're dictionaries and I can write dictionary values into them and retrieve them days later as long as I set the session to permanent and the cookie doesn't get deleted. Any ideas why this weird behaviour is happening?

    Read the article

  • on Google App Engine 500 Error, it should be 200 instead of 500

    - by Faisal Amjad
    requestToken = function() { var getTokenURI = '/gettoken?userid=' + userid; var httpRequest = makeRequest(getTokenURI, true); httpRequest.onreadystatechange = function() { if (httpRequest.readyState == 4) { if (httpRequest.status == 200) { openChannel(httpRequest.responseText); } else { alert('ERROR: AJAX request status = ' + httpRequest.status); } } } }; function makeRequest(url, async) { var httpRequest; if (window.XMLHttpRequest) { httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } if (!httpRequest) { return false; } httpRequest.open('POST', url, async); httpRequest.send(); return httpRequest; } it is running excellent on localhost...but on google app engine it httpRequest.status equals 500 and goes in else statement. WHY? LOG on google app engine: /getFriendList?userid=d 500 253ms 0kb Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11 175.110.179.86 - - [17/Dec/2012:08:35:33 -0800] "POST /getFriendList?userid=d HTTP/1.1" 500 0 "http://faisalimmsngr.appspot.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11" "faisalimmsngr.appspot.com" ms=254 cpu_ms=110 instance=00c61b117caf2d11ca57d2a2296ccd0b902b038a W 2012-12-17 08:35:33.272 Failed startup of context com.google.apphosting.utils.jetty.RuntimeAppEngineWebAppContext@10ff62a{/,/base/data/home/apps/s~faisalimmsngr/1.363934467542140431} org.mortbay.util.MultiException[java.lang.UnsupportedClassVersionError: adv/web/mid/exam/FriendServlet : Unsupported major.minor version 51.0, java.lang.UnsupportedClassVersionError: adv/web/mid/exam/MessageServlet : Unsupported major.minor version 51.0, java.lang.UnsupportedClassVersionError: adv/web/mid/exam/TokenServlet : Unsupported major.minor version 51.0] at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:656) at org.mortbay.jetty.servlet.Context.startContext(Context.java:140) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:219) at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:194) at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:134) at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:447) at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:454) at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:461) at com.google.tracing.TraceContext.runInContext(TraceContext.java:703) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:338) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:330) at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:458) at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251) at java.lang.Thread.run(Thread.java:679) java.lang.UnsupportedClassVersionError: adv/web/mid/exam/FriendServlet : Unsupported major.minor version 51.0 at com.google.appengine.runtime.Request.process-c04431eac3a1f275(Request.java) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:634) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:277) at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at org.mortbay.util.Loader.loadClass(Loader.java:91) at org.mortbay.util.Loader.loadClass(Loader.java:71) at org.mortbay.jetty.servlet.Holder.doStart(Holder.java:73) at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:242) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685) at org.mortbay.jetty.servlet.Context.startContext(Context.java:140) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:454) at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:461) at com.google.tracing.TraceContext.runInContext(TraceContext.java:703) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:338) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:330) at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:458) at java.lang.Thread.run(Thread.java:679)

    Read the article

  • How to get data from struts2 action with jQuery?

    - by Rafa Romero
    I have an Struts2 Web with GoogleMaps. I want to load a list of markers which are saved in a SQL DDBB. To do this, I tried with jQuery and Ajax. Here you are the code: loadMarkers.java public class loadMarkers extends ActionSupport implements ServletRequestAware,ServletResponseAware{ //Variables de sesion/cookie FunctionClass ses; protected HttpServletResponse servletResponse; protected HttpServletRequest servletRequest; private String userID=""; //Variables del marker private List<marker> markersList = new ArrayList<marker>(); public String execute() throws Exception{ FunctionClass friends = new FunctionClass(); //Leemos de la cookie for(Cookie c : servletRequest.getCookies()) { if (c.getName().equals("userID")) userID = (c.getValue()); } System.out.println("en el loadMarkers"); connectionBBDD con = new connectionBBDD(); markersList = con.loadMarkers(userID); return SUCCESS; } I want to use the markerList array in Javascript, to create the markers. This is the struts.xml file: <package name="jsonActions" namespace="/test" extends="json-default"> <action name="LoadMarkers" class="web.localizadroid.maps.loadMarkers"> <interceptor-ref name="basicStack"/> <result type="json"> <param name="root">markersList</param> </result> </action> </package> And here you are the Javascript (jQuery) code: function loadMarkersJ(){ alert("dentro"); $.ajax({ type : "post", url : "LoadMarkers", dataType: "json", success : function(data) { alert(data); var image = new google.maps.MarkerImage ('http://i53.tinypic.com/ettquh.png'); var jSon_Object = eval("(" + data + ")"); //For para analizar los datos (Json) obtenidos de la BBDD for (x = 0; x < jSon_Object.length; x++) { var markersArray = []; var myLatlng = new google.maps.LatLng(jSon_Object[x].lat, jSon_Object[x].lon); markerLoaded = new google.maps.Marker( { position : myLatlng, map : map, icon: image, title: "NOMBRE: " + jSon_Object[x].tarjetName + "\n" + "ANOTACIONES: " + jSon_Object[x].anotaciones + "\n" + "TIME: " + jSon_Object[x].time }); markersArray.push(markerLoaded); if (markersArray) { for (i in markersArray) { alert("entro en forColocaMarkers"); if (markersArray[i].getAnimation() != null) { markersArray[i].setAnimation(null); } else { markersArray[i].setAnimation(google.maps.Animation.BOUNCE); } markersArray[i].setMap(map); } } } } }); } From success : function(data) { to the end, is JavaScript code to create de markers, and this it's OK. The problem is whith ajax, because I don't get to obtain markerList Array by jSon data return...I think that the problem is in the url attribute from $.ajax...I tried loadMarkers.action and loadMarkers, but nothing happens. When I execute the web, only prints the alert alert("dentro"), the alert alert(data) never has been printed. I have forgotten to add the code where I call the Javascript function (loadMarkersJ). Here you are: <p><s:a action="LoadMarkers.action" namespace="/test" onclick="loadMarkersJ(this)">Cargar Marcadores S</s:a></p> Somebody can help me please?

    Read the article

  • simplexml help how do I parse this?

    - by bbutle01
    I haven't done any xml projects, so I'm not quite sure what to do with this data... I'm using curl to make a request to salesforce, and they give me back a response that I need to parse. I want to use simplexml. Here's part of the response: <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <loginResponse> <result> <metadataServerUrl> https://na6-api.salesforce.com/services/Soap/m/18.0/ </metadataServerUrl> <passwordExpired> false </passwordExpired> <sandbox> false </sandbox> <serverUrl> https://na6-api.salesforce.com/services/Soap/u/18.0/ </serverUrl> <sessionId> !AQ4AQLtDIqY. </sessionId> <userId> </userId> <userInfo> <accessibilityMode> false </accessibilityMode> <currencySymbol> $ </currencySymbol> <orgDefaultCurrencyIsoCode> USD </orgDefaultCurrencyIsoCode> <orgDisallowHtmlAttachments> false </orgDisallowHtmlAttachments> <orgHasPersonAccounts> false </orgHasPersonAccounts> <organizationId> </organizationId> <organizationMultiCurrency> false </organizationMultiCurrency> <organizationName> Ox </organizationName> <profileId> sdfgsdfg </profileId> <roleId> sdfgsdfg </roleId> <userDefaultCurrencyIsoCode xsi:nil="true"/> <userEmail> ###@gmail.com </userEmail> <userFullName> ### ### </userFullName> <userId> asdfasdf </userId> <userLanguage> en_US </userLanguage> <userLocale> en_US </userLocale> <userName> [email protected] </userName> <userTimeZone> America/Chicago </userTimeZone> <userType> Standard </userType> <userUiSkin> Theme3 </userUiSkin> </userInfo> </result> </loginResponse> </soapenv:Body> </soapenv:Envelope> Anyway, I expected to feed that stuff (we'll call it data) into $results = simplexml_load_string($data); var_dump($results); And that would give me all the data back... and then to access specific parts, it would be $results-body-loginResponse-blah-blah... But It's not giving me that, it's not really giving me anything back, just an empty simple xml object... So one website made me think I might need an XSLT to read this correctly. Or something else made me think it's because I don't have at the top. Help!

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >