Search Results

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

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

  • How to execute stored procedure from Access using linked tables

    - by webworm
    I have an Access 2003 database that connects to a SQL Server 2008 box via ODBC. The tables from SQL Server are connected as linked tables in Access. I have a stored procedure on the SQL Server that I am trying to execute via ADO code. The problem I have is that Access cannot seem to find the procedure. What do I have to do within Access to be able to execute this stored procedure? Some facts ... The stored procedure in question accepts one parameter which is an integer. The stored procedure returns a recordset which I am hoping to use as the datasource for a ListBox. Here is my ADO code in Access ... Private Sub LoadUserCaseList(userID As Integer) Dim cmd As ADODB.Command Set cmd = New ADODB.Command cmd.ActiveConnection = CurrentProject.Connection cmd.CommandType = adCmdStoredProc cmd.CommandText = "uspGetUserCaseSummaryList" Dim par As New ADODB.Parameter Set par = cmd.CreateParameter("userID", adInteger) cmd.Parameters.Append par cmd.Parameters("userID") = userID Dim rs As ADODB.Recordset Set rs = cmd.Execute() lstUserCases.Recordset = rs End Sub The error I get is "the microsoft jet database engine cannot find the input table or query "uspGetUserCaseSummaryList".

    Read the article

  • Foreign key relationships in Entity Framework

    - by Anders Svensson
    I'm trying to add an object created from Entity Data Model classes. I have a table called Users, which has turned into a User EDM class. And I also have a table Pages, which has become a Page EDM class. These tables have a foreign key relationship, so that each page is associated with many users. Now I want to be able to add a page, but I can't get how to do it. I get a nullreference exception on Users below. I'm still rather confused by all this, so I'm sure it's a simple error, but I just can't see how to do it. Also, by the way, the compiler requires that I set PageID in the object initializer, even though this field is set to be an automatic id in the table. Am I doing it right just setting it to 0, expecting it to be updated automatically in the table when saved, or how should I do that? Any help appreciated! The method in question: private Page GetPage(User currentUser) { string url = _request.ServerVariables["url"].ToLower(); var userPages = from p in _context.PageSet where p.Users.UserID == currentUser.UserID select p; var existingPage = userPages.FirstOrDefault(e => e.Url == url); //Could be combined with above, but hard to read? if (existingPage != null) return existingPage; Page page = new Page() { Count = 0, Url = _request.ServerVariables["url"].ToLower(), PageID = 0, //Only initial value, changed later? }; _context.AddToPageSet(page); page.Users.UserID = currentUser.UserID; //Here's the problem... return page; }

    Read the article

  • Linq, should I join those two queries together?

    - by 5YrsLaterDBA
    I have a Logins table which records when user is login, logout or loginFailed and its timestamp. Now I want to get the list of loginFailed after last login and the loginFailed happened within 24 hrs. What I am doing now is get the last login timestamp first. then use second query to get the final list. do you think I should join those two queris together? why not? why yes? var lastLoginTime = (from inRecord in db.Logins where inRecord.Users.UserId == userId && inRecord.Action == "I" orderby inRecord.Timestamp descending select inRecord.Timestamp).Take(1); if (lastLoginTime.Count() == 1) { DateTime lastInTime = (DateTime)lastLoginTime.First(); DateTime since = DateTime.Now.AddHours(-24); String actionStr = "F"; var records = from record in db.Logins where record.Users.UserId == userId && record.Timestamp >= since && record.Action == actionStr && record.Timestamp > lastInTime orderby record.Timestamp select record; }

    Read the article

  • DataReader is not returning results from a MySQL Stored Proc

    - by Glenn Slaven
    I have a stored proc in MySQL (5.5) that I'm calling from a C# application (using MySQL.Data v6.4.4.0). I have a bunch of other procs that work fine, but this is not returning any results, the data reader says the result set is empty. The proc does a couple of inserts & an update inside a transaction then selects 2 local variables to return. The inserts & update are happening, but the select is not returning. When I run the proc manually it works, gives a single row with the two fields, but the data reader is empty. This is the proc: CREATE DEFINER=`root`@`localhost` PROCEDURE `File_UpdateFile`(IN siteId INT, IN fileId INT, IN description VARCHAR(100), IN folderId INT, IN fileSize INT, IN filePath VARCHAR(100), IN userId INT) BEGIN START TRANSACTION; SELECT MAX(v.versionNumber) + 1 INTO @versionNumber FROM `file_version` v JOIN `file` f ON (v.fileId = f.fileId) WHERE v.fileId = fileId AND f.siteId = siteId; INSERT INTO `file_version` (fileId, versionNumber, description, fileSize, filePath, uploadedOn, uploadedBy, fileVersionState) VALUES (fileId, @versionNumber, description, fileSize, filePath, NOW(), userId, 0); INSERT INTO filehistory (fileId, `action`, userId, createdOn) VALUES (fileId, 'UPDATE', userId, NOW()); UPDATE `file` f SET f.checkedOutBy = NULL WHERE f.fileId = fileId; COMMIT; SELECT fileId, @versionNumber `versionNumber`; END$$ I'm calling the proc using Dapper, but I've debugged into the SqlMapper class and I can see that the reader is not returning anything.

    Read the article

  • "Too many indexes on table" error when creating relationships in Microsoft Access 2010.

    - by avianattackarmada
    I have tblUsers which has a primary key of UserID. UserID is used as a foreign key in many tables. Within a table, it is used as a foreign key for multiple fields (e.g. ObserverID, RecorderID, CheckerID). I have successfully added relationships (with in the the MS Access 'Relationship' view), where I have table aliases to do the multiple relationships per table: *tblUser.UserID - 1 to many - tblResight.ObserverID *tblUser_1.UserID - 1 to many - tblResight.CheckerID After creating about 25 relationships with enforcement of referential integrity, when I try to add an additional one, I get the following error: "The operation failed. There are too many indexes on table 'tblUsers.' Delete some of the indexes on the table and try the operation again." I ran the code I found here and it returned that I have 6 indexes on tblUsers. I know there is a limit of 32 indexes per table. Am I using the relationship GUI wrong? Does access create an index for the enforcement of referential integrity any time I create a relationship (especially indexes that wouldn't turn up when I ran the script)? I'm kind of baffled, any help would be appreciated.

    Read the article

  • Optimization of SQL query regarding pair comparisons

    - by InfiniteSquirrel
    Hi, I'm working on a pair comparison site where a user loads a list of films and grades from another site. My site then picks two random movies and matches them against each other, the user selects the better of the two and a new pair is loaded. This gives a complete list of movies ordered by whichever is best. The database contains three tables; fm_film_data - this contains all imported movies fm_film_data(id int(11), imdb_id varchar(10), tmdb_id varchar(10), title varchar(255), original_title varchar(255), year year(4), director text, description text, poster_url varchar(255)) fm_films - this contains all information related to a user, what movies the user has seen, what grades the user has given, as well as information about each film's wins/losses for that user. fm_films(id int(11), user_id int(11), film_id int(11), grade int(11), wins int(11), losses int(11)) fm_log - this contains records of every duel that has occurred. fm_log(id int(11), user_id int(11), winner int(11), loser int(11)) To pick a pair to show the user, I've created a mySQL query that checks the log and picks a pair at random. SELECT pair.id1, pair.id2 FROM (SELECT part1.id AS id1, part2.id AS id2 FROM fm_films AS part1, fm_films AS part2 WHERE part1.id <> part2.id AND part1.user_id = [!!USERID!!] AND part2.user_id = [!!USERID!!]) AS pair LEFT JOIN (SELECT winner AS id1, loser AS id2 FROM fm_log WHERE fm_log.user_id = [!!USERID!!] UNION SELECT loser AS id1, winner AS id2 FROM fm_log WHERE fm_log.user_id = [!!USERID!!]) AS log ON pair.id1 = log.id1 AND pair.id2 = log.id2 WHERE log.id1 IS NULL ORDER BY RAND() LIMIT 1 This query takes some time to load, about 6 seconds in our tests with two users with about 800 grades each. I'm looking for a way to optimize this but still limit all duels to appear only once. The server runs MySQL version 5.0.90-community.

    Read the article

  • MVC + Is validation attributes enough?

    - by ebb
    My ViewModel has validation attributes that ensure that it wont be empty etc. - Is that enough or should I let my the code contracts I have made be in the ActionResult too? Example: // CreateCaseViewModel.cs public class CreateCaseViewModel { [Required] public string Topic { get; set; } [Required] public string Message { get; set; } } // CaseController.cs [AuthWhere(AuthorizeRole.Developer)] [HttpPost] public ActionResult Create(CreateCaseViewModel model) { if(!ModelState.IsValid) { // TODO: some cool stuff? } if (string.IsNullOrWhiteSpace(model.Message)) { throw new ArgumentException("Message cannot be null or empty", model.Message); } if (string.IsNullOrWhiteSpace(model.Topic)) { throw new ArgumentException("Topic cannot be null or empty", model.Topic); } var success = false; string message; var userId = new Guid(_membershipService.GetUserByUserName(User.Identity.Name).ProviderUserKey.ToString()); if(userId == Guid.Empty) { throw new ArgumentException("UserId cannot be empty"); } Case createCase = _caseService.CreateCase(model.Topic, model.Message); if(createCase == null) { throw new ArgumentException("Case cannot be null"); } if(_caseService.AddCase(createCase, userId)) { message = ControllerResources.CaseCreateFail; } else { success = true; message = ControllerResources.CaseCreateSuccess; } return Json(new { Success = success, Message = message, Partial = RenderPartialViewToString(ListView, GetCases) }); }

    Read the article

  • Redirect To Another Site With Header Information Attached Javascript

    - by Nick LaMarca
    I am trying to make a client side click and redirect to another site with header information added, my client side code for the onclick is this: function selectApp(appGUID, userId ,embedUrl) { if(embedUrl==="") { var success = setAppGUID(appGUID); window.location.replace('AppDetail.aspx'); } else { $.ajax({ type: "POST", url: embedUrl, contentType: "text/html", beforeSend: function (xhr, settings) { xhr.setRequestHeader("UserId", userId); }, success: function (msg) { //go to slx window.location.replace(embedUrl); } }); } } And the server side code in "embedUrl" is protected void Page_Load(object sender, EventArgs e) { string isSet = (String)HttpContext.Current.Session["saveUserID"]; if (String.IsNullOrEmpty(isSet)) { NameValueCollection headers = base.Request.Headers; for (int i = 0; i < headers.Count; i++) { if (headers.GetKey(i).Equals("UserId")) { HttpContext.Current.Session["saveUserID"] = headers.Get(i); } } } else { TextBox1.Text = HttpContext.Current.Session["saveUserID"].ToString(); } } This seems to work but its not too elegant. Is there a way to redirect with header data? Without (what Im doing) Saving header info in a session var then doing a redirect in 2 seperate pieces.

    Read the article

  • SELECT Statement without duplicate rows on the multiple join tables

    - by theBo
    I have 4 tables built with JOINS and I would like to SELECT DISTINCT rows on the setsTbl.s_id so they always show regardless if there's relational data against them or not!. This is what I have at present which displays the data but doesn't display all of but not the entire distinct row! SELECT setsTbl.s_id, setsTbl.setName, userProfilesTbl.no + ' ' + userProfilesTbl.surname AS Name, trainingTbl.t_date, userAssessmentTbl.o_id FROM userProfilesTbl LEFT OUTER JOIN userAssessmentTbl ON userProfilesTbl.UserId = userAssessmentTbl.UserId FULL OUTER JOIN trainingTbl ON userAssessmentTbl.tt_id = trainingTbl.tt_id RIGHT OUTER JOIN setsTbl ON trainingTbl.s_id = setsTbl.s_id WHERE (userProfilesTbl.st_id=@st_id AND userProfilesTbl.sh_id=@sh_id) AND (DATEPART(yyyy,t_date) = @y_date ) OR (userAssessmentTbl.o_id IS NULL) ORDER BY setName ASC, t_date ASC With this statement I get some of the rows (the ones with data against them) but as stated the s_id field does not return distinct. This following inner select statement works in part when used in SQL Query analyzer and returns pretty much the data i require s_id setName Name o_id ----- ----- ----- ------ 1 100 Barnes 2 2 100 Beardsley 3 3 101 Aldridge 1 4 102 Molby 2 5 102 Whelan 3 but not when used outside of that environment. select * from ( SELECT userProfilesTbl.serviceNo + ' ' + userProfilesTbl.surname AS Name, userProfilesTbl.st_id, userProfilesTbl.sh_id, userAssessmentTbl.o_id, setsTbl.s_id, setsTbl.setName, row_number() over ( partition by setsTbl.s_id order by setsTbl.s_id ) r FROM userProfilesTbl LEFT OUTER JOIN userAssessmentTbl ON userProfilesTbl.UserId = userAssessmentTbl.UserId FULL OUTER JOIN trainingTbl ON userAssessmentTbl.tt_id = trainingTbl.tt_id RIGHT OUTER JOIN setsTbl ON trainingTbl.s_id = setsTbl.s_id ) x where x.r = 1 Not receiving any errors just not displaying the data?

    Read the article

  • Hibernate Exception, what wrong ? [[Exception in thread "main" org.hibernate.InvalidMappingException

    - by user195970
    I use netbean 6.7.1 to write "hello world" witch hibernate, but I get some errors, plz help me, thank you very much. my exception init: deps-module-jar: deps-ear-jar: deps-jar: Copying 1 file to F:\Documents and Settings\My Dropbox\DropboxNetBeanProjects\loginspring\build\web\WEB-INF\classes compile-single: run-main: Oct 25, 2009 2:44:05 AM org.hibernate.cfg.Environment <clinit> INFO: Hibernate 3.2.5 Oct 25, 2009 2:44:05 AM org.hibernate.cfg.Environment <clinit> INFO: hibernate.properties not found Oct 25, 2009 2:44:05 AM org.hibernate.cfg.Environment buildBytecodeProvider INFO: Bytecode provider name : cglib Oct 25, 2009 2:44:05 AM org.hibernate.cfg.Environment <clinit> INFO: using JDK 1.4 java.sql.Timestamp handling Oct 25, 2009 2:44:05 AM org.hibernate.cfg.Configuration configure INFO: configuring from resource: /hibernate.cfg.xml Oct 25, 2009 2:44:05 AM org.hibernate.cfg.Configuration getConfigurationInputStream INFO: Configuration resource: /hibernate.cfg.xml Oct 25, 2009 2:44:06 AM org.hibernate.cfg.Configuration addResource INFO: Reading mappings from resource : hibernate/Tbluser.hbm.xml Oct 25, 2009 2:44:06 AM org.hibernate.util.XMLHelper$ErrorLogger error SEVERE: Error parsing XML: XML InputStream(1) Document is invalid: no grammar found. Oct 25, 2009 2:44:06 AM org.hibernate.util.XMLHelper$ErrorLogger error SEVERE: Error parsing XML: XML InputStream(1) Document root element "hibernate-mapping", must match DOCTYPE root "null". Exception in thread "main" org.hibernate.InvalidMappingException: Could not parse mapping document from resource hibernate/Tbluser.hbm.xml at org.hibernate.cfg.Configuration.addResource(Configuration.java:569) at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1587) at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1555) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1534) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1508) at org.hibernate.cfg.Configuration.configure(Configuration.java:1428) at org.hibernate.cfg.Configuration.configure(Configuration.java:1414) at hibernate.CreateTest.main(CreateTest.java:22) Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from invalid mapping at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:502) at org.hibernate.cfg.Configuration.addResource(Configuration.java:566) ... 7 more Caused by: org.xml.sax.SAXParseException: Document is invalid: no grammar found. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:250) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:626) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3095) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:921) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205) at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522) at org.dom4j.io.SAXReader.read(SAXReader.java:465) at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:499) ... 8 more Java Result: 1 BUILD SUCCESSFUL (total time: 1 second) 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/hibernate</property> <property name="hibernate.connection.username">root</property> </session-factory> </hibernate-configuration> Tbluser.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 Oct 25, 2009 2:37:30 AM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="hibernate.Tbluser" table="tbluser" catalog="hibernate"> <id name="userId" type="java.lang.Integer"> <column name="userID" /> <generator class="identity" /> </id> <property name="username" type="string"> <column name="username" length="50" /> </property> <property name="password" type="string"> <column name="password" length="50" /> </property> <property name="email" type="string"> <column name="email" length="50" /> </property> <property name="phone" type="string"> <column name="phone" length="50" /> </property> <property name="groupId" type="java.lang.Integer"> <column name="groupID" /> </property> </class> </hibernate-mapping> Tbluser.java package hibernate; // Generated Oct 25, 2009 2:37:30 AM by Hibernate Tools 3.2.1.GA /** * Tbluser generated by hbm2java */ public class Tbluser implements java.io.Serializable { private Integer userId; private String username; private String password; private String email; private String phone; private Integer groupId; public Tbluser() { } public Tbluser(String username, String password, String email, String phone, Integer groupId) { this.username = username; this.password = password; this.email = email; this.phone = phone; this.groupId = groupId; } public Integer getUserId() { return this.userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return this.phone; } public void setPhone(String phone) { this.phone = phone; } public Integer getGroupId() { return this.groupId; } public void setGroupId(Integer groupId) { this.groupId = groupId; } }

    Read the article

  • Importing oracle dump file, getting error on stored procedures

    - by Paul Tomblin
    I export an oracle "schema" using exp userid=/ file=pt.dmp log=pt.log owner=FOO buffer=10000000 statistics=NONE direct=Y and then import it into a different schema on the same oracle instance on the same SID using imp userid=/ file=pt.dmp fromuser=FOO touser=paul When I try to access the stored procedures, I get ORA-29541: class PAUL.ESMQOracleStoredProc could not be resolved Any idea why one user can resolve this but another one can't?

    Read the article

  • SQL Subquery in LINQ for Entity Framework 4.0

    - by Jorin
    I'm new to LINQ and EF, but I've been able to stumble through for the majority of the queries I have, but this one has me completely confused. No matter what I try, it comes up in SQL Profiler as a big mess :-). I have two tables: Users and UsersProjects. The goal of this query is to list all the users who are working on projects with the specified user. Here is the query as I have it written in SQL. It's a subquery, but I don't know of a way to simplify it further, but I'm open to suggestions there as well. SELECT DISTINCT Users.FirstName, Users.LastName FROM Users INNER JOIN UsersProjects ON Users.ID=UsersProjects.UserID WHERE UsersProjects.ProjectID IN (SELECT ProjectID FROM UsersProjects WHERE UserID=@UserID) Anybody able to help?? It seems like a fairly simple subquery in SQL, but in LINQ, I'm baffled. Thanks, Jorin

    Read the article

  • DB structure for Twitter home/Facebook wall?

    - by mathon12
    Basically a live feed of all your friends' recent posts. In a stupid sort of approach I think I'd start by building a query like: SELECT * FROM tblposts WHERE userid=friend_id_1OR userid=friend_id_2...... and so on Where friend_id_% is the userid of a friend from your friends list. But this must be a very inefficient way of doing it, right? Is there any faster way of doing this in MySQL? Maybe some clever DB schema? (I know FB uses Hadoob but I'm not experienced enough to go that far :( )

    Read the article

  • Databind gridview with LINQ

    - by Anders Svensson
    I have two database tables, one for Users of a web site, containing the fields "UserID", "Name" and the foreign key "PageID". And the other with the fields "PageID" (here the primary key), and "Url". I want to be able to show the data in a gridview with data from both tables, and I'd like to do it with databinding in the aspx page. I'm not sure how to do this, though, and I can't find any good examples of this particular situation. Here's what I have so far: <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="LinqBinding._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> Testing LINQ </h2> <asp:GridView ID="GridView1" runat="server" DataSourceID="LinqDataSourceUsers" AutoGenerateColumns="false"> <Columns> <asp:CommandField ShowSelectButton="True" /> <asp:BoundField DataField="UserID" HeaderText="UserID" /> <asp:BoundField DataField="Name" HeaderText="Name" /> <asp:BoundField DataField="PageID" HeaderText="PageID" /> <asp:TemplateField HeaderText="Pages"> <ItemTemplate <asp:DropDownList ID="DropDownList1" DataSourceID="LinqDataSourcePages" SelectedValue='<%#Bind("PageID") %>' DataTextField="Url" DataValueField="PageID" runat="server"> </asp:DropDownList> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:LinqDataSource ID="LinqDataSourcePages" runat="server" ContextTypeName="LinqBinding.UserDataContext" EntityTypeName="" TableName="Pages"> </asp:LinqDataSource> <asp:LinqDataSource ID="LinqDataSourceUsers" runat="server" ContextTypeName="LinqBinding.UserDataContext" EntityTypeName="" TableName="Users"> </asp:LinqDataSource> </asp:Content> But this only works in so far as it gets the user table into the gridview (that's not a problem), and I get the page data into the dropdown, but here's the problem: I of course get ALL the page data in there, not just the pages for each user on each row. So how do I put some sort of "where" constraint on dropdown for each row to only show the pages for the user in that row? (Also, to be honest I'm not sure I'm getting the foreign key relationship right, because I'm not too used to working with relationships). EDIT: I think I have set up the relationship incorrectly. I keep getting the message that "Pages" doesn't exist as a property on the User object. And I guess it can't since the relationship right now is one way. So I tried to create a many-to-many relationship. Again, my database knowledge is a bit limited, but I added a so called "junction table" with the fields UserID and PageID, same as the other tables' primary keys. I wasn't able to make both of these primary keys in the junction table though (which it looked like some people had in examples I've seen...but since it wasn't possible I guessed they shouldn't be). Anyway, I created a relationship from each table and created new LINQ classes from that. But then what do I do? I set the junction table as the Linq data source, since I guessed I had to do this to access both tables, but that doesn't work. Then it complains there is no Name property on that object. So how do I access the related tables? Here's what I have now with the many-to-many relationship: <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ManyToMany._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> Many to many LINQ </h2> <asp:GridView ID="GridView1" runat="server" DataSourceID="LinqDataSource1" AutoGenerateColumns="false"> <Columns> <asp:CommandField ShowSelectButton="True" /> <asp:BoundField DataField="UserID" HeaderText="UserID" /> <asp:BoundField DataField="Name" HeaderText="Name" /> <asp:BoundField DataField="PageID" HeaderText="PageID" /> <asp:TemplateField HeaderText="Pages"> <ItemTemplate> <asp:DropDownList ID="DropDownList1" DataSource='<%#Eval("Pages") %>' SelectedValue='<%#Bind("PageID") %>' DataTextField="Url" DataValueField="PageID" runat="server"> </asp:DropDownList> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="ManyToMany.UserPageDataContext" EntityTypeName="" TableName="UserPages"> </asp:LinqDataSource> </asp:Content>

    Read the article

  • Why is my WCF RIA Services custom object deserializing with an extra list member?

    - by oasasaurus
    I have been developing a Silverlight WCF RIA Services application dealing with mock financial transactions. To more efficiently send summary data to the client without going overboard with serialized entities I have created a summary class that isn’t in my EDM, and figured out how to serialize and send it over the wire to the SL client using DataContract() and DataMember(). Everything seemed to be working out great, until I tried to bind controls to a list inside my custom object. The list seems to always get deserialized with an extra, almost empty entity in it that I don’t know how to get rid of. So, here are some of the pieces. First the relevant bits from the custom object class: <DataContract()> _ Public Class EconomicsSummary Public Sub New() RecentTransactions = New List(Of Transaction) TotalAccountHistory = New List(Of Transaction) End Sub Public Sub New(ByVal enUser As EntityUser) Me.UserId = enUser.UserId Me.UserName = enUser.UserName Me.Accounts = enUser.Accounts Me.Jobs = enUser.Jobs RecentTransactions = New List(Of Transaction) TotalAccountHistory = New List(Of Transaction) End Sub <DataMember()> _ <Key()> _ Public Property UserId As System.Guid <DataMember()> _ Public Property NumTransactions As Integer <DataMember()> _ <Include()> _ <Association("Summary_RecentTransactions", "UserId", "User_UserId")> _ Public Property RecentTransactions As List(Of Transaction) <DataMember()> _ <Include()> _ <Association("Summary_TotalAccountHistory", "UserId", "User_UserId")> _ Public Property TotalAccountHistory As List(Of Transaction) End Class Next, the relevant parts of the function called to return the object: Public Function GetEconomicsSummary(ByVal guidUserId As System.Guid) As EconomicsSummary Dim objOutput As New EconomicsSummary(enUser) For Each objTransaction As Transaction In (From t As Transaction In Me.ObjectContext.Transactions.Include("Account") Where t.Account.aspnet_User_UserId = guidUserId Select t Order By t.TransactionDate Descending Take 10) objTransaction.User_UserId = objOutput.UserId objOutput.RecentTransactions.Add(objTransaction) Next objOutput.NumTransactions = objOutput.RecentTransactions.Count … Return objOutput End Function Notice that I’m collecting the NumTransactions count before serialization. Should be 10 right? It is – BEFORE serialization. The DataGrid is bound to the data source as follows: <sdk:DataGrid AutoGenerateColumns="False" Height="100" MaxWidth="{Binding ElementName=aciSummary, Path=ActualWidth}" ItemsSource="{Binding Source={StaticResource EconomicsSummaryRecentTransactionsViewSource}, Mode=OneWay}" Name="gridRecentTransactions" RowDetailsVisibilityMode="VisibleWhenSelected" IsReadOnly="True"> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn x:Name="TransactionDateColumn" Binding="{Binding Path=TransactionDate, StringFormat=\{0:d\}}" Header="Date" Width="SizeToHeader" /> <sdk:DataGridTextColumn x:Name="AccountNameColumn" Binding="{Binding Path=Account.Title}" Header="Account" Width="SizeToCells" /> <sdk:DataGridTextColumn x:Name="CurrencyAmountColumn" Binding="{Binding Path=CurrencyAmount, StringFormat=\{0:c\}}" Header="Amount" Width="SizeToHeader" /> <sdk:DataGridTextColumn x:Name="TitleColumn" Binding="{Binding Path=Title}" Header="Description" Width="SizeToCells" /> <sdk:DataGridTextColumn x:Name="ItemQuantityColumn" Binding="{Binding Path=ItemQuantity}" Header="Qty" Width="SizeToHeader" /> </sdk:DataGrid.Columns> </sdk:DataGrid> You might be wondering where the ItemsSource is coming from, that looks like this: <CollectionViewSource x:Key="EconomicsSummaryRecentTransactionsViewSource" Source="{Binding Path=DataView.RecentTransactions, ElementName=EconomicsSummaryDomainDataSource}" /> When I noticed that the DataGrid had the extra row I tried outputting some data after the data source finishes loading, as follows: Private Sub EconomicsSummaryDomainDataSource_LoadedData(ByVal sender As System.Object, ByVal e As System.Windows.Controls.LoadedDataEventArgs) Handles EconomicsSummaryDomainDataSource.LoadedData If e.HasError Then System.Windows.MessageBox.Show(e.Error.ToString, "Load Error", System.Windows.MessageBoxButton.OK) e.MarkErrorAsHandled() End If Dim objSummary As EconomicsSummary = CType(EconomicsSummaryDomainDataSource.Data(0), EconomicsSummary) Dim sb As New StringBuilder("") sb.AppendLine(String.Format("Num Transactions: {0} ({1})", objSummary.RecentTransactions.Count.ToString(), objSummary.NumTransactions.ToString())) For Each objTransaction As Transaction In objSummary.RecentTransactions sb.AppendLine(String.Format("Recent TransactionId {0} dated {1} CurrencyAmount {2} NewBalance {3}", objTransaction.TransactionId.ToString, objTransaction.TransactionDate.ToString("d"), objTransaction.CurrencyAmount.ToString("c"), objTransaction.NewBalance.ToString("c"))) Next txtDebug.Text = sb.ToString() End Sub Output from that looks like this: Num Transactions: 11 (10) Recent TransactionId 2283 dated 6/1/2010 CurrencyAmount $31.00 NewBalance $392.00 Recent TransactionId 2281 dated 5/31/2010 CurrencyAmount $33.00 NewBalance $361.00 Recent TransactionId 2279 dated 5/28/2010 CurrencyAmount $8.00 NewBalance $328.00 Recent TransactionId 2277 dated 5/26/2010 CurrencyAmount $22.00 NewBalance $320.00 Recent TransactionId 2275 dated 5/24/2010 CurrencyAmount $5.00 NewBalance $298.00 Recent TransactionId 2273 dated 5/21/2010 CurrencyAmount $19.00 NewBalance $293.00 Recent TransactionId 2271 dated 5/20/2010 CurrencyAmount $20.00 NewBalance $274.00 Recent TransactionId 2269 dated 5/19/2010 CurrencyAmount $48.00 NewBalance $254.00 Recent TransactionId 2267 dated 5/18/2010 CurrencyAmount $42.00 NewBalance $206.00 Recent TransactionId 2265 dated 5/14/2010 CurrencyAmount $5.00 NewBalance $164.00 Recent TransactionId 0 dated 6/1/2010 CurrencyAmount $0.00 NewBalance $361.00 So I have a few different questions: -First and foremost, where the devil is that extra Transaction entity coming from and how do I get rid of it? Does it have anything to do with the other list of Transaction entities being serialized as part of the EconomicsSummary class (TotalAccountHistory)? Do I need to decorate the EconomicsSummary class members a little more/differently? -Second, where are the peculiar values coming from on that extra entity? PRE-POSTING UPDATE 1: I did a little checking, it looks like that last entry is the first one in the TotalAccountHistory list. Do I need to do something with CollectionDataContract()? PRE-POSTING UPDATE 2: I fixed one bug in TotalAccountHistory, since the objects weren’t coming from the database their keys weren’t unique. So I set the keys on the Transaction entities inside TotalAccountHistory to be unique and guess what? Now, after deserialization RecentTransactions contains all its original items, plus every item in TotalAccountHistory. I’m pretty sure this has to do with the deserializer getting confused by two collections of the same type. But I don’t yet know how to resolve it…

    Read the article

  • HBase schema help

    - by Jody Powlette
    Coming from a SQL Server background, I'm a newbie with regard to HBase, but the technology looks to be a good fit for what we're doing and the cost is definitely right! I need to maintain a list of log entries which normally I would create in an RDBS as: create table Log ( UserID int, SiteID int, Page varchar(50), Date smalldatetime ) where one user may have 0 or 1000 rows in this simple table. Typical queries would be to find all the rows for one user or all the rows for one user on one site. How does this translate into a "map" in HBase where there is no "row key" AND the same (SiteID,Page) may appear many times. My first thought is that UserID is a row key, but I still don't understand "column families" and the other terminology well enough to understand how to setup the table to hold this data where the one UserID can have many (SiteID,Page,Date) "rows". Any direction is appreciated!

    Read the article

  • MVC routing - why does my request not match the route?

    - by Anders Juul
    Hi all, I'm making a request that I thought would be caught by my route, but there is no match. What am I doing wrong? Any comments appreciated, Anders, Denmark -- Url : EventReponse/ComingAdmin/386/01e71c45-cb67-4711-a51f-df5fcb54bb8b Expected match: routes.MapRoute( "Editing event responses for other user", // Route name "EventResponse/{action}/{eventId}/userId", // URL with parameters new {controller = "EventResponse", action = "ComingAdmin"} // Parameter defaults ); Desired controller (but I guess this does not come into play): public class EventResponseController : ControllerBase { (...) public ActionResult ComingAdmin(int eventId, Guid userId) { return RegisterEventResponse(eventId, AttendanceStatus.Coming, userId); } }

    Read the article

  • .NET and Closing SQL Server connections

    - by user307076
    I am having a hard time figuring out why the following constructor will not close connnections. When I view the active connections. Here is the code that I have. Public Sub New(ByVal UserID As Integer) Dim oConn As New SqlConnection(ConfigurationManager.ConnectionStrings("connStr").ToString()) Dim cmd As New SqlCommand("stored proc", oConn) Dim sdr As SqlDataReader cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@userID", UserID) oConn.Open() sdr = cmd.ExecuteReader() Try If Not sdr.HasRows Then sdr.Close() If Not oConn Is Nothing Then If oConn.State <> ConnectionState.Closed Then oConn.Close() End If End If cmd.Dispose() Exit Sub End If 'User has account in WATS, proceed to load account information While sdr.Read _firstname = Convert.ToString(sdr("First Name")) _lastname = Convert.ToString(sdr("Last Name")) End While Catch ex As Exception 'Throw New Exception("User Error: " + ex.Message) Finally sdr.Close() If Not oConn Is Nothing Then If oConn.State <> ConnectionState.Closed Then oConn.Close() End If End If cmd.Dispose() End Try End Sub

    Read the article

  • Multiple join query in eSql

    - by Syma
    Hi guys, This is my first question in stackoverflow but really not the first time to get solution here. I am struggling with multiple join in entity framework 4. I have three tables (Accounts, Users and AccountUsers) that am finding difficult to query. What I want is to get all the users for the provided accountId including the account creator. I can get all the account users with no problem but the hard side for me is getting the account creator since it's not added to AccountUsers table. below is a quick preview how the tables are related. Accounts AccountId UserId (account creator) ...other columns Users UserId ...other columns AccountUsers AccountId UserId I would prefer the query to be esql, but Linq to Entities will do. I trust you guys on stackoverflow, so I know this won't take long to get the 'Answer' mark. Thanks for even reading.

    Read the article

  • .NET and Closing MSSQL connections

    - by user307076
    I am having a hard time figuring out why the following constructor will not close connnections. When I view the active connections. Here is the code that I have. Public Sub New(ByVal UserID As Integer) Dim oConn As New SqlConnection(ConfigurationManager.ConnectionStrings("connStr").ToString()) Dim cmd As New SqlCommand("stored proc", oConn) Dim sdr As SqlDataReader cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@userID", UserID) oConn.Open() sdr = cmd.ExecuteReader() Try If Not sdr.HasRows Then sdr.Close() If Not oConn Is Nothing Then If oConn.State <> ConnectionState.Closed Then oConn.Close() End If End If cmd.Dispose() Exit Sub End If 'User has account in WATS, proceed to load account information While sdr.Read _firstname = Convert.ToString(sdr("First Name")) _lastname = Convert.ToString(sdr("Last Name")) End While Catch ex As Exception 'Throw New Exception("User Error: " + ex.Message) Finally sdr.Close() If Not oConn Is Nothing Then If oConn.State <> ConnectionState.Closed Then oConn.Close() End If End If cmd.Dispose() End Try End Sub

    Read the article

  • Searching a set of data with multiple terms using Linq

    - by Cj Anderson
    I'm in the process of moving from ADO.NET to Linq. The application is a directory search program to look people up. The users are allowed to type the search criteria into a single textbox. They can separate each term with a space, or wrap a phrase in quotes such as "park place" to indicate that it is one term. Behind the scenes the data comes from a XML file that has about 90,000 records in it and is about 65 megs. I load the data into a DataTable and then use the .Select method with a SQL query to perform the searches. The query I pass is built from the search terms the user passed. I split the string from the textbox into an array using a regular expression that will split everything into a separate element that has a space in it. However if there are quotes around a phrase, that becomes it's own element in the array. I then end up with a single dimension array with x number of elements, which I iterate over to build a long query. I then build the search expression below: query = query & _ "((userid LIKE '" & tempstr & "%') OR " & _ "(nickname LIKE '" & tempstr & "%') OR " & _ "(lastname LIKE '" & tempstr & "%') OR " & _ "(firstname LIKE '" & tempstr & "%') OR " & _ "(department LIKE '" & tempstr & "%') OR " & _ "(telephoneNumber LIKE '" & tempstr & "%') OR " & _ "(email LIKE '" & tempstr & "%') OR " & _ "(Office LIKE '" & tempstr & "%'))" Each term will have a set of the above query. If there is more than one term, I put an AND in between, and build another query like above with the next term. I'm not sure how to do this in Linq. So far, I've got the XML file loading correctly. I'm able to search it with specific criteria, but I'm not sure how to best implement the search over multiple terms. 'this works but far too simple to get the job done Dim results = From c In m_DataSet...<Users> _ Where c.<userid>.Value = "XXXX" _ Select c The above code also doesn't use the LIKE operator either. So partial matches don't work. It looks like what I'd want to use is the .Startswith but that appears to be only in Linq2SQL. Any guidance would be appreciated. I'm new to Linq, so I might be missing a simple way to do this. The XML file looks like so: <?xml version="1.0" standalone="yes"?> <theusers> <Users> <userid>person1</userid> <nickname></nickname> <lastname></lastname> <firstname></firstname> <department></department> <telephoneNumber></telephoneNumber> <email></email> </Users> <Users> <userid>person2</userid> <nickname></nickname> <lastname></lastname> <firstname></firstname> <department></department> <telephoneNumber></telephoneNumber> <email></email> </Users>

    Read the article

  • SOA design principles with regards to database relationships

    - by Eitan
    If I were to extricate my current membership provider from my solution, i.e. as a dll and expose it as a web service with it's own db, how would I model the relationships with regards to SOA design. For example I have a table: USER id, name, lastname, username, password, role. and table PRODUCT id, name, price, createdate, userid the foreign key being userid to table user. How would I model the relationship and/or query the db. If I wanted to get all products that were uploaded today for example, before I would query: SELECT u.name, u.lastname, u.username, p.* FROM PRODUCT p INNER JOIN USER u ON p.userid = u.id WHERE createdate = '05/05/2010' Now that I don't have the table within the database how would I perform this query? Thanks.

    Read the article

  • NHibernate HQL logic problem

    - by Jon
    Hi I'm trying to write an NHibernate HQL query that makes use of parenthesis in the where clause. However, the HQL parser seems to be ignoring my parenthesis, thus changing the meaning of my statement. Can anyone shed any light on the matter? The following HQL query: from WebUser u left join fetch u.WebUserProfile left join fetch u.CommunicationPreferences where (u.CommunicationPreferences.Email = 0 and u.SyncDate is not null) or u.DateDeleted is not null translates to: from WebUser webuser0_ left outer join WebUserProfile webuserpro1_ on webuser0_.UserId = webuserpro1_.WebUserId left outer join WebUserCommunicationPreferences communicat2_ on webuser0_.UserId = communicat2_.UserId where communicat2_.Email = 0 and (webuser0_.SyncDate is not null) or webuser0_.DateDeleted is not null Thanks Jon

    Read the article

  • Database query optimization

    - by hdx
    Ok my Giant friends once again I seek a little space in your shoulders :P Here is the issue, I have a python script that is fixing some database issues but it is taking way too long, the main update statement is this: cursor.execute("UPDATE jiveuser SET username = '%s' WHERE userid = %d" % (newName,userId)) That is getting called about 9500 times with different newName and userid pairs... Any suggestions on how to speed up the process? Maybe somehow a way where I can do all updates with just one query? Any help will be much appreciated! PS: Postgres is the db being used.

    Read the article

  • Core Data Null Relationship

    - by Dylan Copeland
    I have a to-one relationship in my data model with Core Data. I'm trying to set the value of the relationship but Core Data keeps thinking that it's nil. The "creatorUser" relationship is not optional, so when I go to save my managed object context, Core Data gives errors because it thinks the "creatorUser" is nil. Any help would be greatly advised. NSManagedObject *teamManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"DCTeam" inManagedObjectContext:_managedObjectContext]; // Creator Properties NSManagedObject *creator = [self userForID:[ticketInfo objectForKey:@"userid"]]; if (!creator) { creator = [NSEntityDescription insertNewObjectForEntityForName:@"DCUser" inManagedObjectContext:_managedObjectContext]; [creator setValue:[personInfo objectForKey:@"userid"] forKey:@"userid"]; [creator setValue:[personInfo objectForKey:@"creatorName"] forKey:@"name"]; } [teamManagedObject setValue:creator forKey:@"creatorUser"];

    Read the article

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