Search Results

Search found 6630 results on 266 pages for 'cname record'.

Page 29/266 | < Previous Page | 25 26 27 28 29 30 31 32 33 34 35 36  | Next Page >

  • Exception when retrieving record using Nhibernate

    - by Muhammad Akhtar
    I am new to NHibernate and have just started right now. I have very simple table contain Id(Int primary key and auto incremented), Name(varchar(100)), Description(varchar(100)) Here is my XML <class name="DevelopmentStep" table="DevelopmentSteps" lazy="true"> <id name="Id" type="Int32" column="Id"> </id> <property name="Name" column="Name" type="String" length="100" not-null="false"/> <property name="Description" column="Description" type="String" length="100" not-null="false"/> here is how I want to get all the record public List<DevelopmentStep> getDevelopmentSteps() { List<DevelopmentStep> developmentStep; developmentStep = Repository.FindAll<DevelopmentStep>(new OrderBy("Name", Order.Asc)); return developmentStep; } But I am getting exception The element 'id' in namespace 'urn:nhibernate-mapping-2.2' has incomplete content. List of possible elements expected: 'urn:nhibernate-mapping-2.2:meta urn:nhibernate-mapping- 2.2:column urn:nhibernate-mapping-2.2:generator'. Please Advise me --- Thanks

    Read the article

  • rails xml to active record object

    - by Brian D.
    I've been googling for a while to try and convert and incoming XML request into an active record object. I've tried using the ActiveRecordObject.new.from_xml method but it doesn't seem to handle relationships. For example, say I have the following xml: <blog> <title></title> <blog-pages> <blog-page> <page-number></page-number> <content></content> </blog-page> </blog-pages> </blog> And I have the following model objects: class Blog < ActiveRecord::Base has_many :blog_pages end class BlogPage < ActiveRecord::Base belongs_to :blog end Is there a way to convert the xml into a blog object WITH relationships? Or do I need to manually parse the XML? Thanks in advance.

    Read the article

  • codeigniter active record and mysql

    - by sea_1987
    I am running a query with Active Record in a modal of my codeigniter application, the query looks like this, public function selectAllJobs() { $this->db->select('*') ->from('job_listing') ->join('job_listing_has_employer_details', 'job_listing_has_employer_details.employer_details_id = job_listing.id', 'left'); //->join('employer_details', 'employer_details.users_id = job_listing_has_employer_details.employer_details_id'); $query = $this->db->get(); return $query->result_array(); } This returns an array that looks like this, [0]=> array(13) { ["id"]=> string(1) "1" ["job_titles_id"]=> string(1) "1" ["location"]=> string(12) "Huddersfield" ["location_postcode"]=> string(7) "HD3 4AG" ["basic_salary"]=> string(19) "£20,000 - £25,000" ["bonus"]=> string(12) "php, html, j" ["benefits"]=> string(11) "Compnay Car" ["key_skills"]=> string(1) "1" ["retrain_position"]=> string(3) "YES" ["summary"]=> string(73) "Lorem Ipsum is simply dummy text of the printing and typesetting industry" ["description"]=> string(73) "Lorem Ipsum is simply dummy text of the printing and typesetting industry" ["job_listing_id"]=> NULL ["employer_details_id"]=> NULL } } The job_listing_id and employer_details_id return as NULL however if I run the SQL in phpmyadmin I get full set of results, the query i running in phpmyadmin is, SELECT * FROM ( `job_listing` ) LEFT JOIN `job_listing_has_employer_details` ON `job_listing_has_employer_details`.`employer_details_id` LIMIT 0 , 30 Is there a reason why I am getting differing results?

    Read the article

  • Can't delete record via the datacontext it was retrieved from

    - by Antilogic
    I just upgraded one of my application's methods to use compiled queries (not sure if this is relevant). Now I'm getting contradicting error messages when I run the code. This is my method: MyClass existing = Queries.MyStaticCompiledQuery(MyRequestScopedDataContext, param1, param2).SingleOrDefault(); if (existing != null) { MyRequestScopedDataContext.MyClasses.DeleteOnSubmit(existing); } When I run it I get this message: Cannot remove an entity that has not been attached. Note that the compiled query and the DeleteOnSubmit reference the same DataContext. Still I figured I'd humor the application and add an attach command before the DeleteOnSubmit, like so: MyClass existing = Queries.MyStaticCompiledQuery(MyRequestScopedDataContext, param1, param2).SingleOrDefault(); if (existing != null) { MyRequestScopedDataContext.MyClasses.Attach(existing); MyRequestScopedDataContext.MyClasses.DeleteOnSubmit(existing); } BUT... When I run this code, I get a completely different contradictory error message: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported. I'm at a complete loss... Does anyone else have some insight as to why I can't delete a record via the same DataContext I retrieved it from?

    Read the article

  • How can I record and save flash video's with an H264 codec

    - by JimHendriks
    Right now I am working on an AIR 3.2 application which lets you stream a video to a Flash Media Server and saves it on a hard drive. This sequence works fine with the standard Sorenson codec but I want to use H.264 for my videos. I found lots example c ode and implemented it in my code, but when I record a video of myself I am unable to re-watch it afterwards. I found how to implement a H.264 encoding in a realeyes blog post here. My code is here. It saves the video as a .f4v file, but my browser (I've tried the latest versions of both Chrome and Firefox, with the latest Flash) and also VLC are unable to load the video. I also used a program called Movie Player which is able to open the file but can only show the first frame and the audio. Neither am I able to upload the video to YouTube because they do not support the file extension. Here is an example video file it saved: H264Test1.f4v. My question is: How do I stream and save the movie with a file extension that I am able to re-watch while using the H.264 codec?

    Read the article

  • SQL query for the latest record for each day

    - by Mac
    I've got an Oracle 10g database with a table with a structure and content very similar to the following: CREATE TABLE MyTable ( id INTEGER PRIMARY KEY, otherData VARCHAR2(100), submitted DATE ); INSERT INTO MyTable VALUES (1, 'a', TO_DATE('28/04/2010 05:13', ''DD/MM/YYYY HH24:MI)); INSERT INTO MyTable VALUES (2, 'b', TO_DATE('28/04/2010 03:48', ''DD/MM/YYYY HH24:MI)); INSERT INTO MyTable VALUES (3, 'c', TO_DATE('29/04/2010 05:13', ''DD/MM/YYYY HH24:MI)); INSERT INTO MyTable VALUES (4, 'd', TO_DATE('29/04/2010 17:16', ''DD/MM/YYYY HH24:MI)); INSERT INTO MyTable VALUES (5, 'e', TO_DATE('29/04/2010 08:49', ''DD/MM/YYYY HH24:MI)); What I need to do is query the database for the latest record submitted on each given day. For example, with the above data I would expect the records with ID numbers 1 and 4 to be returned, as these are the latest each for 28 April and 29 April respectively. Unfortunately, I have little expertise as far as SQL is concerned. Could anybody possibly provide some insight as to how to achieve this? Thanks in advance!

    Read the article

  • Cannot locate record in delphi ADO query

    - by Danatela
    I can't locate any record in TADOQuery using PK. First, I was trying to use standard Locate method: PPUQuery.Locate('ID', SpPlansQuery['PPONREC'], []); It always returns False, but manual search (passing the whole query matching ID with given PPONREC which is really slow) finds the desired row. I tried using loPartialKey and switched CursorLocation of query to clUseServer, but it didn't help. Next, I tried to filter my PPUQuery: PPUQuery.Filter := 'ID = ' + VarToStr(SpPlansQuery['PPONREC']); PPUQuery.Filtered := True; PPUQuery.First; But after that the PPUQuery.Eof is True and PPUQuery.RecordCount equals 0. Underlying database is Oracle 9 and the ID is of type INTEGER and is PK of table TPORDER_CMK. PPUQuery.SQL is: SELECT tp.*, la.*, lm.*, ld.*, ld1.*, to_cmk.* FROM ppu_plan.tporder_cmk tp JOIN PPU_PLAN.LARTICLES la ON TP.ARTICLE = LA.ID JOIN PPU_PLAN.LMATERIAL lm ON TP.MATERIAL = lm.id JOIN PPU_PLAN.LCADEP ld ON TP.CADEP = LD.ID JOIN PPU_PLAN.LCADEP ld1 ON TP.PRODUCER = LD1.ID JOIN PPU_PLAN.TORDER_CMK to_cmk ON TP.order_id=TO_cmk.ID WHERE TP.PLAN_ID = :pplan_id What should I try next and how to solve this problem?

    Read the article

  • Rails active record association problem

    - by Harm de Wit
    Hello, I'm new at active record association in rails so i don't know how to solve the following problem: I have a tables called 'meetings' and 'users'. I have correctly associated these two together by making a table 'participants' and set the following association statements: class Meeting < ActiveRecord::Base has_many :participants, :dependent => :destroy has_many :users, :through => :participants and class Participant < ActiveRecord::Base belongs_to :meeting belongs_to :user and the last model class User < ActiveRecord::Base has_many :participants, :dependent => :destroy At this point all is going well and i can access the user values of attending participants of a specific meeting by calling @meeting.users in the normal meetingshow.html.erb view. Now i want to make connections between these participants. Therefore i made a model called 'connections' and created the columns of 'meeting_id', 'user_id' and 'connected_user_id'. So these connections are kinda like friendships within a certain meeting. My question is: How can i set the model associations so i can easily control these connections? I would like to see a solution where i could use @meeting.users.each do |user| user.connections.each do |c| <do something> end end I tried this by changing the model of meetings to this: class Meeting < ActiveRecord::Base has_many :participants, :dependent => :destroy has_many :users, :through => :participants has_many :connections, :dependent => :destroy has_many :participating_user_connections, :through => :connections, :source => :user Please, does anyone have a solution/tip how to solve this the rails way?

    Read the article

  • Simple search only searching last word of record

    - by bennett_an
    I set up a simple search as instructed in part of railscast #240. in controller @reports = Report.search(params[:search]).order('created_at DESC').paginate(:page => params[:page], :per_page => 5) in model def self.search(search) if search where('apparatus LIKE ?', "%#{search}") else scoped end end in view <%= form_tag reports_path, :method => :get do %> <p> <%= text_field_tag :search, params[:search] %> <%= submit_tag "Search", :name => nil %> </p> <% end %> it all works... but... I have a few records for example, one with "another time test" and another with "last test of time" if i search "test" the first comes up but the second doesn't, and if i search "time" the second comes up but not the first. It is only seeing the last word of the record. what gives?

    Read the article

  • Need help INSERT record(s) MySQL DB

    - by JM4
    I have an online form which collects member(s) information and stores it into a very long MySQL database. We allow up to 16 members to enroll at a single time and originally structured the DB to allow such. For example: If 1 Member enrolls, his personal information (first name, last name, address, phone, email) are stored on a single row. If 15 Members enroll (all at once), their personal information are stored in the same single row. The row has information housing columns for all 'possible' inputs. I am trying to consolidate this code and having every nth member that enrolls put onto a new record within the database. I have seen sugestions before for inserting multiple records as such: INSERT INTO tablename VALUES (('$f1name', '$f1address', '$f1phone'), ('$f2name', '$f2address', '$f2phone')... The issue with this is two fold: I do not know how many records are being enrolled from person to person so the only way to make the statement above is to use a loop The information collected from the forms is NOT a single array so I can't loop through one array and have it parse out. My information is collected as individual input fields like such: Member1FirstName, Member1LastName, Member1Phone, Member2Firstname, Member2LastName, Member2Phone... and so on Is it possible to store information in separate rows WITHOUT using a loop (and therefore having to go back and completely restructure my form field names and such (which can't happen due to the way the validation rules are built.)

    Read the article

  • Create rails record from two ids

    - by Michael Luby
    The functionality I'm trying to build allows Users to Visit a Restaurant. I have Users, Locations, and Restaurants models. Locations have many Restaurants. I've created a Visits model with user_id and restaurant_id attributes, and a visits_controller with create and destroy methods. Thing is, I can't create an actual Visit record. Any thoughts on how I can accomplish this? Or am I going about it the wrong way. Here's the code: Model: class Visit < ActiveRecord::Base attr_accessible :restaurant_id, :user_id belongs_to :user belongs_to :restaurant end View: <% @restaurants.each do |restaurant| %> <%= link_to 'Visit', location_restaurant_visits_path(current_user.id, restaurant.id), method: :create %> <% @visit = Visit.find_by_user_id_and_restaurant_id(current_user.id, restaurant.id) %> <%= @visit != nil ? "true" : "false" %> <% end %> Controller: class VisitsController < ApplicationController before_filter :find_restaurant before_filter :find_user def create @visit = Visit.create(params[:user_id => @user.id, :restaurant_id => @restaurant.id]) respond_to do |format| if @visit.save format.html { redirect_to location_restaurants_path(@location), notice: 'Visit created.' } format.json { render json: @visit, status: :created, location: @visit } else format.html { render action: "new" } format.json { render json: @visit.errors, status: :unprocessable_entity } end end end def destroy @visit = Visit.find(params[:user_id => @user.id, :restaurant_id => @restaurant.id]) @restaurant.destroy respond_to do |format| format.html { redirect_to location_restaurants_path(@restaurant.location_id), notice: 'Unvisited.' } format.json { head :no_content } end end private def find_restaurant @restaurant = Restaurant.find(params[:restaurant_id]) end def find_user @user = current_user end end

    Read the article

  • SUM of column with Left Outer Join

    - by Matt
    I am trying to get the Count of all records that have at least on person who is authorized on the record. Basically, a Record can have more than one person associated with it. I want to return the count of Total Records, a count of total Authorized Records where at least 1 person is authorized, and a count of total NotAuthorized records where no person associated with record is authorized. It doesn't matter if one person is authorized per Record or if 3 people are authorized for that record, that should add 1 to the Authorized counter. The current query is incrementing Auth and Non auth for each person added per record rather, than one per record. If no people are assigned to the record that should also count towards Not Auth. SELECT Count(DISTINCT Record.RecordID) AS TotalRecords, SUM(CASE WHEN People.PersonLevel = 1 THEN 1 ELSE 0 END) AS Authorized, SUM(CASE WHEN People.PersonLevel <> 1 THEN 1 ELSE 0 END) AS NotAuthorized FROM Record LEFT OUTER JOIN RecordPeople ON Record.RecordID = RecordPeople.RecordID LEFT OUTER JOIN People ON RecordPeople.PersonID = People.PersonID

    Read the article

  • Cocoa: AVAudioRecorder Fails to Record

    - by kumaryr
    AVAudioSession *audioSession = [AVAudioSession sharedInstance]; NSError *err = nil; [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&err]; if(err){ NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]); return; } [audioSession setActive:YES error:&err]; err = nil; if(err){ NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]); return; } NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init]; [recordSetting setValue:[NSNumber numberWithInt: kAudioFormatAppleIMA4] forKey:AVFormatIDKey]; [recordSetting setValue:[NSNumber numberWithFloat:40000.0] forKey:AVSampleRateKey]; [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey]; [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; [recordSetting setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey]; [recordSetting setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey]; // Create a new dated file NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0]; NSString *caldate = [now description]; NSString *recorderFilePath = [[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain]; NSLog(recorderFilePath); url = [NSURL fileURLWithPath:recorderFilePath]; err = nil; recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err]; if(!recorder){ NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]); UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Warning" message: [err localizedDescription] delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; return; } //prepare to record [recorder setDelegate:self]; [recorder prepareToRecord]; recorder.meteringEnabled = YES; BOOL audioHWAvailable = audioSession.inputIsAvailable; if (! audioHWAvailable) { UIAlertView *cantRecordAlert = [[UIAlertView alloc] initWithTitle: @"Warning" message: @"Audio input hardware not available" delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [cantRecordAlert show]; [cantRecordAlert release]; return; } // [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector( updateTimerDisplay) userInfo:nil repeats:YES]; // [recorder recordForDuration:(NSTimeInterval)10 ]; // [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector( updateTimerDisplay) userInfo:nil repeats:YES];

    Read the article

  • sendmail and MX records when mail server is not on web host

    - by Jim Nelson
    This is a problem I'm sure is easy to fix, but I've been banging my head on it all day. I'm developing a new web site for a client. The web site resides at (this is an example) website.com. I have a PHP form script to email visitors' requests to [email protected]. When I coded this on a staging server on a different domain, all worked fine. When I moved it to website.com, the mail messages never arrived. The web server is on a virtual host with a major ISP. Here's what I've learned since then: My client's mail server is Microsoft Exchange on a box physically in their office. Whenever someone on the outside world emails [email protected], the mail arrives. But if the web server sends to the same email address, it fails every time. This is not a PHP problem. I secure shell in to the web server and have tested this both with sendmail and the UNIX mail application. I've also tested it by emailing various email accounts from the shell. I can email myself, for example, just nobody at the website.com domain. In short, when I'm logged in to website.com, mail to [email protected], [email protected], [email protected] all fail. All other addresses work fine. What I've discovered is those dropped emails are routed to the web server's "catchall" account where they sit in its inbox. I've done an MX lookup on website.com. The MX record points to mailsec.website.com. I can telnet to mailsec.website.com port 25 and see the SMTP server. It appears to me that website.com isn't doing an MX lookup when it's sending mail to [email protected]. My theory is that it recognizes the domain as local, sees that there's no "requests" user account to deliver it to, and drops the mail into the catchall account. What I want is to force sendmail to do the MX lookup and send the message on to the Exchange server. I'm at wit's end here. I can't figure out how to do this. For that matter, I may be way off base here and have misdiagnosed this entirely. Internet mail and MX has always seemed a black art to me, and my ignorance is certainly showing in this question.

    Read the article

  • Stop output of image if no record - paperclip - Ruby on rails

    - by bgadoci
    I have just installed paperclip into my ruby on rails blog application. Everything is working great...too great. I am trying to figure out how to tell paperclip not to output anything if there is no record in the table so that I don't have broken image links everywhere. How, and where, do I do this? Here is my code: class Post < ActiveRecord::Base has_attached_file :photo, :styles => { :small => "150x150"} validates_presence_of :body, :title has_many :comments, :dependent => :destroy has_many :tags, :dependent => :destroy has_many :ugtags, :dependent => :destroy has_many :votes, :dependent => :destroy belongs_to :user after_create :self_vote def self_vote # I am assuming you have a user_id field in `posts` and `votes` table. self.votes.create(:user => self.user) end cattr_reader :per_page @@per_page = 10 end View <% div_for post do %> <div id="post-wrapper"> <div id="post-photo"> <%= image_tag post.photo.url(:small) %> </div> <h2><%= link_to_unless_current h(post.title), post %></h2> <div class="light-color"> <i>Posted <%= time_ago_in_words(post.created_at) %></i> ago </div> <%= simple_format truncate(post.body, :length => 600) %> <div id="post-options"> <%= link_to "Read More >>", post %> | <%= link_to "Comments (#{post.comments.count})", post %> | <%= link_to "Strings (#{post.tags.count})", post %> | <%= link_to "Contributions (#{post.ugtags.count})", post %> | <%= link_to "Likes (#{post.votes.count})", post %> </div> </div> <% end %>

    Read the article

  • Can't destroy record in many-to-many relationship

    - by Dmart
    I'm new to Rails, so I'm sure I've made a simple mistake. I've set up a many-to-many relationship between two models: User and Group. They're connected through the junction model GroupMember. Here are my models (removed irrelevant stuff): class User < ActiveRecord::Base has_many :group_members has_many :groups, :through => :group_members end class GroupMember < ActiveRecord::Base belongs_to :group belongs_to :user end class Group < ActiveRecord::Base has_many :group_members has_many :users, :through => :group_members end The table for GroupMembers contains additional information about the relationship, so I didn't use has_and_belongs_to_many (as per the Rails "Active Record Associations" guide). The problem I'm having is that I can't destroy a GroupMember. Here's the output from rails console: irb(main):006:0> m = GroupMember.new => #<GroupMember group_id: nil, user_id: nil, active: nil, created_at: nil, updated_at: nil> irb(main):007:0> m.group_id =1 => 1 irb(main):008:0> m.user_id = 16 => 16 irb(main):009:0> m.save => true irb(main):010:0> m.destroy NoMethodError: undefined method `eq' for nil:NilClass from /usr/local/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/whiny_nil.rb:48:in `method_missing' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.4/lib/active_record/persistence.rb:79:in `destroy' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.4/lib/active_record/locking/optimistic.rb:110:in `destroy' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.4/lib/active_record/callbacks.rb:260:in `destroy' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/callbacks.rb:413:in `_run_destroy_callbacks' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.4/lib/active_record/callbacks.rb:260:in `destroy' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.4/lib/active_record/transactions.rb:235:in `destroy' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.4/lib/active_record/transactions.rb:292:in `with_transaction_returning_status' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.4/lib/active_record/connection_adapters/abstract/database_statements.rb:139:in `transaction' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.4/lib/active_record/transactions.rb:207:in `transaction' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.4/lib/active_record/transactions.rb:290:in `with_transaction_returning_status' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-3.0.4/lib/active_record/transactions.rb:235:in `destroy' from (irb):10 This is driving me crazy, so any help would be greatly appreciated.

    Read the article

  • Loading the last related record instantly for multiple parent records using Entity framework

    - by Guillaume Schuermans
    Does anyone know a good approach using Entity Framework for the problem described below? I am trying for our next release to come up with a performant way to show the placed orders for the logged on customer. Of course paging is always a good technique to use when a lot of data is available I would like to see an answer without any paging techniques. Here's the story: a customer places an order which gets an orderstatus = PENDING. Depending on some strategy we move that order up the chain in order to get it APPROVED. Every change of status is logged so we can see a trace for statusses and maybe even an extra line of comment per status which can provide some extra valuable information to whoever sees this order in an interface. So an Order is linked to a Customer. One order can have multiple orderstatusses stored in OrderStatusHistory. In my testscenario I am using a customer which has 100+ Orders each with about 5 records in the OrderStatusHistory-table. I would for now like to see all orders in one page not using paging where for each Order I show the last relevant Status and the extra comment (if there is any for this last status; both fields coming from OrderStatusHistory; the record with the highest Id for the given OrderId). There are multiple scenarios I have tried, but I would like to see any potential other solutions or comments on the things I have already tried. Trying to do Include() when getting Orders but this still results in multiple queries launched on the database. Each order triggers an extra query to the database to get all orderstatusses in the history table. So all statusses are queried here instead of just returning the last relevant one, plus 100 extra queries are launched for 100 orders. You can imagine the problem when there are 100000+ orders in the database. Having 2 computed columns on the database: LastStatus, LastStatusInformation and a regular Linq-Query which gets those columns which are available through the Entity-model. The problem with this approach is the fact that those computed columns are determined using a scalar function which can not be changed without removing the formula from the computed column, etc... In the end I am very familiar with SQL and Stored procedures, but since the rest of the data-layer uses Entity Framework I would like to stick to it as long as possible, even though I have my doubts about performance. Using the SQL approach I would write something like this: WITH cte (RN, OrderId, [Status], Information) AS ( SELECT ROW_NUMBER() OVER (PARTITION BY OrderId ORDER BY Id DESC), OrderId, [Status], Information FROM OrderStatus ) SELECT o.Id, cte.[Status], cte.Information AS StatusInformation, o.* FROM [Order] o INNER JOIN cte ON o.Id = cte.OrderId AND cte.RN = 1 WHERE CustomerId = @CustomerId ORDER BY 1 DESC; which returns all orders for the customer with the statusinformation provided by the Common Table Expression. Does anyone know a good approach using Entity Framework?

    Read the article

  • SQL Server - Get Inserted Record Identity Value when Using a View's Instead Of Trigger

    - by CuppM
    For several tables that have identity fields, we are implementing a Row Level Security scheme using Views and Instead Of triggers on those views. Here is a simplified example structure: -- Table CREATE TABLE tblItem ( ItemId int identity(1,1) primary key, Name varchar(20) ) go -- View CREATE VIEW vwItem AS SELECT * FROM tblItem -- RLS Filtering Condition go -- Instead Of Insert Trigger CREATE TRIGGER IO_vwItem_Insert ON vwItem INSTEAD OF INSERT AS BEGIN -- RLS Security Checks on inserted Table -- Insert Records Into Table INSERT INTO tblItem (Name) SELECT Name FROM inserted; END go If I want to insert a record and get its identity, before implementing the RLS Instead Of trigger, I used: DECLARE @ItemId int; INSERT INTO tblItem (Name) VALUES ('MyName'); SELECT @ItemId = SCOPE_IDENTITY(); With the trigger, SCOPE_IDENTITY() no longer works - it returns NULL. I've seen suggestions for using the OUTPUT clause to get the identity back, but I can't seem to get it to work the way I need it to. If I put the OUTPUT clause on the view insert, nothing is ever entered into it. -- Nothing is added to @ItemIds DECLARE @ItemIds TABLE (ItemId int); INSERT INTO vwItem (Name) OUTPUT INSERTED.ItemId INTO @ItemIds VALUES ('MyName'); If I put the OUTPUT clause in the trigger on the INSERT statement, the trigger returns the table (I can view it from SQL Management Studio). I can't seem to capture it in the calling code; either by using an OUTPUT clause on that call or using a SELECT * FROM (). -- Modified Instead Of Insert Trigger w/ Output CREATE TRIGGER IO_vwItem_Insert ON vwItem INSTEAD OF INSERT AS BEGIN -- RLS Security Checks on inserted Table -- Insert Records Into Table INSERT INTO tblItem (Name) OUTPUT INSERTED.ItemId SELECT Name FROM inserted; END go -- Calling Code INSERT INTO vwItem (Name) VALUES ('MyName'); The only thing I can think of is to use the IDENT_CURRENT() function. Since that doesn't operate in the current scope, there's an issue of concurrent users inserting at the same time and messing it up. If the entire operation is wrapped in a transaction, would that prevent the concurrency issue? BEGIN TRANSACTION DECLARE @ItemId int; INSERT INTO tblItem (Name) VALUES ('MyName'); SELECT @ItemId = IDENT_CURRENT('tblItem'); COMMIT TRANSACTION Does anyone have any suggestions on how to do this better? I know people out there who will read this and say "Triggers are EVIL, don't use them!" While I appreciate your convictions, please don't offer that "suggestion".

    Read the article

  • Add a record to relational XML with C#

    - by Megawolt
    I have a XML and XSD I want to add a record to trck table with Dataset i'm also write that code but need trackListrow... how can i handle that? playListDS rec = new playListDS(); if(File.Exists(Server.MapPath("~/playlist.xml"))) rec.ReadXml(Server.MapPath("~/playlist.xml")); int id = int.Parse(rec.track.Rows[rec.track.Rows.Count - 1][0].ToString()) + 1; if (ViewState["Filename"] != null && ViewState["Cover"] != null) { playListDS.trackListRow row = new playListDS.trackListRow(); rec.track.AddtrackRow(id.ToString(), "mp3/" + ViewState["Filename"].ToString(), txtartist.Text, txtalbum.Text, txttitle.Text, txtannotation.Text, txtduration.Text, "mp3/cover" + ViewState["Cover"].ToString(), txtinfo.Text, txtlink.Text); <?xml version="1.0"?> <!-- Generated using Flame-Ware Solutions XML-2-XSD v2.0 at http://www.flame-ware.com/Products/XML-2-XSD/ --> <xs:schema id="playListDS" targetNamespace="http://tempuri.org/playListDS.xsd" xmlns:mstns="http://tempuri.org/playListDS.xsd" xmlns="http://tempuri.org/playListDS.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified"> <xs:element name="playListDS" msdata:IsDataSet="true" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="1"> <xs:element name="trackList"> <xs:complexType> <xs:sequence> <xs:element name="track" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="FileID" type="xs:string" minOccurs="0" /> <xs:element name="location" type="xs:string" minOccurs="0" /> <xs:element name="creator" type="xs:string" minOccurs="0" /> <xs:element name="album" type="xs:string" minOccurs="0" /> <xs:element name="title" type="xs:string" minOccurs="0" /> <xs:element name="annotation" type="xs:string" minOccurs="0" /> <xs:element name="duration" type="xs:string" minOccurs="0" /> <xs:element name="image" type="xs:string" minOccurs="0" /> <xs:element name="info" type="xs:string" minOccurs="0" /> <xs:element name="link" type="xs:string" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <?xml version="1.0" standalone="yes"?> <playListDS xmlns="http://tempuri.org/playListDS.xsd"> <trackList> <track> <FileID>6</FileID> <location>mp3/Gomez - See The World-1.mp3</location> <creator>Gomez</creator> <album>How We Operate</album> <title>See the World</title> <annotation>Buraya kendi yorumun gelicek bos kalabilir</annotation> <duration>243670</duration> <image>mp3/coverChrysanthemum.jpg</image> <info /> <link>Grubun bi sitesi fln varsa buraya yazabilisin yoksa beni sil</link> </track> </trackList> </playListDS>

    Read the article

  • Stuck with the first record while parsing an XML in Java

    - by Ritwik G
    I am parsing the following XML : <table ID="customer"> <T><C_CUSTKEY>1</C_CUSTKEY><C_NAME>Customer#000000001</C_NAME><C_ADDRESS>IVhzIApeRb ot,c,E</C_ADDRESS><C_NATIONKEY>15</C_NATIONKEY><C_PHONE>25-989-741-2988</C_PHONE><C_ACCTBAL>711.56</C_ACCTBAL><C_MKTSEGMENT>BUILDING</C_MKTSEGMENT><C_COMMENT>regular, regular platelets are fluffily according to the even attainments. blithely iron</C_COMMENT></T> <T><C_CUSTKEY>2</C_CUSTKEY><C_NAME>Customer#000000002</C_NAME><C_ADDRESS>XSTf4,NCwDVaWNe6tEgvwfmRchLXak</C_ADDRESS><C_NATIONKEY>13</C_NATIONKEY><C_PHONE>23-768-687-3665</C_PHONE><C_ACCTBAL>121.65</C_ACCTBAL><C_MKTSEGMENT>AUTOMOBILE</C_MKTSEGMENT><C_COMMENT>furiously special deposits solve slyly. furiously even foxes wake alongside of the furiously ironic ideas. pending</C_COMMENT></T> <T><C_CUSTKEY>3</C_CUSTKEY><C_NAME>Customer#000000003</C_NAME><C_ADDRESS>MG9kdTD2WBHm</C_ADDRESS><C_NATIONKEY>1</C_NATIONKEY><C_PHONE>11-719-748-3364</C_PHONE><C_ACCTBAL>7498.12</C_ACCTBAL><C_MKTSEGMENT>AUTOMOBILE</C_MKTSEGMENT><C_COMMENT>special packages wake. slyly reg</C_COMMENT></T> <T><C_CUSTKEY>4</C_CUSTKEY><C_NAME>Customer#000000004</C_NAME><C_ADDRESS>XxVSJsLAGtn</C_ADDRESS><C_NATIONKEY>4</C_NATIONKEY><C_PHONE>14-128-190-5944</C_PHONE><C_ACCTBAL>2866.83</C_ACCTBAL><C_MKTSEGMENT>MACHINERY</C_MKTSEGMENT><C_COMMENT>slyly final accounts sublate carefully. slyly ironic asymptotes nod across the quickly regular pack</C_COMMENT></T> <T><C_CUSTKEY>5</C_CUSTKEY><C_NAME>Customer#000000005</C_NAME><C_ADDRESS>KvpyuHCplrB84WgAiGV6sYpZq7Tj</C_ADDRESS><C_NATIONKEY>3</C_NATIONKEY><C_PHONE>13-750-942-6364</C_PHONE><C_ACCTBAL>794.47</C_ACCTBAL><C_MKTSEGMENT>HOUSEHOLD</C_MKTSEGMENT><C_COMMENT>blithely final instructions haggle; stealthy sauternes nod; carefully regu</C_COMMENT></T> </table> with the following java code: package xmlparserformining; import java.util.List; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Node; import org.dom4j.io.SAXReader; public class XmlParserForMining { public static Document getDocument( final String xmlFileName ) { Document document = null; SAXReader reader = new SAXReader(); try { document = reader.read( xmlFileName ); } catch (DocumentException e) { e.printStackTrace(); } return document; } public static void main(String[] args) { String xmlFileName = "/home/r/javaCodez/parsing in java/customer.xml"; String xPath = "//table/T/C_ADDRESS"; Document document = getDocument( xmlFileName ); List<Node> nodes = document.selectNodes( xPath ); System.out.println(nodes.size()); for (Node node : nodes) { String customer_address = node.valueOf(xPath); System.out.println( "Customer address: " + customer_address); } } } However, instead of getting all the various customer records, I am getting the following output: 1500 Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E Customer address: IVhzIApeRb ot,c,E and so on .. What is wrong here? Why is it printing only the first record ?

    Read the article

  • Can a DNS server return NXDOMAIN and an unresolved CNAME even though the alias exists?

    - by Martin
    I'm trying to understand why one given DNS server is not resolving our domain correctly. When I look up www.foo.com from this name server, a CNAME foo.bar.cc is correctly returned but there's no attached A record and the response status is NXDOMAIN. I understand that this could happen if the DNS server can not resolve the alias foo.bar.cc. However, if I use the same DNS server and look up foo.bar.cc directly, I always get the correct A record. When using any other DNS servers I've tested (different ISPs, Google DNS, Open DNS) our domain resolves correctly. Given this situation, is there some possible problem in our DNS that could cause this? Or does it seem like this given DNS server is to blame? The DNS server in question is used by a lot of people and it seems more likely that the problem is caused by us, but I don't see how - any clues?

    Read the article

  • vb.net sqlite how to loop through selected records and pass each record as a parameter to another fu

    - by mazrabul
    Hi, I have a sqlite table with following fields: Langauge level hours German 2 50 French 3 40 English 1 60 German 1 10 English 2 50 English 3 60 German 1 20 French 2 40 I want to loop through the records based on language and other conditions and then pass the current selected record to a different function. So I have the following mixture of actual code and psudo code. I need help with converting the psudo code to actual code, please. I am finding it difficult to do so. Here is what I have: Private sub mainp() Dim oslcConnection As New SQLite.SQLiteConnection Dim oslcCommand As SQLite.SQLiteCommand Dim langs() As String = {"German", "French", "English"} Dim i as Integer = 0 oslcConnection.ConnectionString = "Data Source=" & My.Settings.dbFullPath & ";" oslcConnection.Open() oslcCommand = oslcConnection.CreateCommand Do While i <= langs.count If langs(i) = "German" Then oslcCommand.CommandText = "SELECT * FROM table WHERE language = '" & langs(i) & "';" For each record selected 'psudo code If level = 1 Then 'psudo code update level to 2 'psudo code minorp(currentRecord) 'psudo code: calling minorp function and passing the whole record as a parameter End If 'psudo code If level = 2 Then 'psudo code update level to 3 'psudo code minorp(currentRecord) 'psudo code: calling minorp function and passing the whole record as a parameter End If 'psudo code Next 'psudo code End If If langs(i) = "French" Then oslcCommand.CommandText = "SELECT * FROM table WHERE language = '" & langs(i) & "';" For each record selected 'psudo code If level = 1 Then 'psudo code update level to 2 'psudo code minorp(currentRecord) 'psudo code: calling minorp function and passing the whole record as a parameter End If 'psudo code If level = 2 Then 'psudo code update level to 3 'psudo code minorp(currentRecord) 'psudo code: calling minorp function and passing the whole record as a parameter End If 'psudo code Next 'psudo code End If Loop End Sub Many thanks for your help.

    Read the article

  • Play and record streaming audio

    - by Igor
    I'm working on an iPhone app that should be able to play and record audio streaming data simultaneously. Is it actually possible? I'm trying to mix SpeakHere and AudioRecorder samples and getting an empty file with no audio data... Here is my .m code: import "AzRadioViewController.h" @implementation azRadioViewController static const CFOptionFlags kNetworkEvents = kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable | kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred; void MyAudioQueueOutputCallback( void* inClientData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer, const AudioTimeStamp inStartTime, UInt32 inNumberPacketDescriptions, const AudioStreamPacketDescription inPacketDesc ) { NSLog(@"start MyAudioQueueOutputCallback"); MyData* myData = (MyData*)inClientData; NSLog(@"--- %i", inNumberPacketDescriptions); if(inNumberPacketDescriptions == 0 && myData-dataFormat.mBytesPerPacket != 0) { inNumberPacketDescriptions = inBuffer-mAudioDataByteSize / myData-dataFormat.mBytesPerPacket; } OSStatus status = AudioFileWritePackets(myData-audioFile, FALSE, inBuffer-mAudioDataByteSize, inPacketDesc, myData-currentPacket, &inNumberPacketDescriptions, inBuffer-mAudioData); if(status == 0) { myData-currentPacket += inNumberPacketDescriptions; } NSLog(@"status:%i curpac:%i pcdesct: %i", status, myData-currentPacket, inNumberPacketDescriptions); unsigned int bufIndex = MyFindQueueBuffer(myData, inBuffer); pthread_mutex_lock(&myData-mutex); myData-inuse[bufIndex] = false; pthread_cond_signal(&myData-cond); pthread_mutex_unlock(&myData-mutex); } OSStatus StartQueueIfNeeded(MyData* myData) { NSLog(@"start StartQueueIfNeeded"); OSStatus err = noErr; if (!myData-started) { err = AudioQueueStart(myData-queue, NULL); if (err) { PRINTERROR("AudioQueueStart"); myData-failed = true; return err; } myData-started = true; printf("started\n"); } return err; } OSStatus MyEnqueueBuffer(MyData* myData) { NSLog(@"start MyEnqueueBuffer"); OSStatus err = noErr; myData-inuse[myData-fillBufferIndex] = true; AudioQueueBufferRef fillBuf = myData-audioQueueBuffer[myData-fillBufferIndex]; fillBuf-mAudioDataByteSize = myData-bytesFilled; err = AudioQueueEnqueueBuffer(myData-queue, fillBuf, myData-packetsFilled, myData-packetDescs); if (err) { PRINTERROR("AudioQueueEnqueueBuffer"); myData-failed = true; return err; } StartQueueIfNeeded(myData); return err; } void WaitForFreeBuffer(MyData* myData) { NSLog(@"start WaitForFreeBuffer"); if (++myData-fillBufferIndex = kNumAQBufs) myData-fillBufferIndex = 0; myData-bytesFilled = 0; myData-packetsFilled = 0; printf("-lock\n"); pthread_mutex_lock(&myData-mutex); while (myData-inuse[myData-fillBufferIndex]) { printf("... WAITING ...\n"); pthread_cond_wait(&myData-cond, &myData-mutex); } pthread_mutex_unlock(&myData-mutex); printf("<-unlock\n"); } int MyFindQueueBuffer(MyData* myData, AudioQueueBufferRef inBuffer) { NSLog(@"start MyFindQueueBuffer"); for (unsigned int i = 0; i < kNumAQBufs; ++i) { if (inBuffer == myData-audioQueueBuffer[i]) return i; } return -1; } void MyAudioQueueIsRunningCallback( void* inClientData, AudioQueueRef inAQ, AudioQueuePropertyID inID) { NSLog(@"start MyAudioQueueIsRunningCallback"); MyData* myData = (MyData*)inClientData; UInt32 running; UInt32 size; OSStatus err = AudioQueueGetProperty(inAQ, kAudioQueueProperty_IsRunning, &running, &size); if (err) { PRINTERROR("get kAudioQueueProperty_IsRunning"); return; } if (!running) { pthread_mutex_lock(&myData-mutex); pthread_cond_signal(&myData-done); pthread_mutex_unlock(&myData-mutex); } } void MyPropertyListenerProc( void * inClientData, AudioFileStreamID inAudioFileStream, AudioFileStreamPropertyID inPropertyID, UInt32 * ioFlags) { NSLog(@"start MyPropertyListenerProc"); MyData* myData = (MyData*)inClientData; OSStatus err = noErr; printf("found property '%c%c%c%c'\n", (inPropertyID24)&255, (inPropertyID16)&255, (inPropertyID8)&255, inPropertyID&255); switch (inPropertyID) { case kAudioFileStreamProperty_ReadyToProducePackets : { AudioStreamBasicDescription asbd; UInt32 asbdSize = sizeof(asbd); err = AudioFileStreamGetProperty(inAudioFileStream, kAudioFileStreamProperty_DataFormat, &asbdSize, &asbd); if (err) { PRINTERROR("get kAudioFileStreamProperty_DataFormat"); myData-failed = true; break; } err = AudioQueueNewOutput(&asbd, MyAudioQueueOutputCallback, myData, NULL, NULL, 0, &myData-queue); if (err) { PRINTERROR("AudioQueueNewOutput"); myData-failed = true; break; } for (unsigned int i = 0; i < kNumAQBufs; ++i) { err = AudioQueueAllocateBuffer(myData-queue, kAQBufSize, &myData-audioQueueBuffer[i]); if (err) { PRINTERROR("AudioQueueAllocateBuffer"); myData-failed = true; break; } } UInt32 cookieSize; Boolean writable; err = AudioFileStreamGetPropertyInfo(inAudioFileStream, kAudioFileStreamProperty_MagicCookieData, &cookieSize, &writable); if (err) { PRINTERROR("info kAudioFileStreamProperty_MagicCookieData"); break; } printf("cookieSize %d\n", cookieSize); void* cookieData = calloc(1, cookieSize); err = AudioFileStreamGetProperty(inAudioFileStream, kAudioFileStreamProperty_MagicCookieData, &cookieSize, cookieData); if (err) { PRINTERROR("get kAudioFileStreamProperty_MagicCookieData"); free(cookieData); break; } err = AudioQueueSetProperty(myData-queue, kAudioQueueProperty_MagicCookie, cookieData, cookieSize); free(cookieData); if (err) { PRINTERROR("set kAudioQueueProperty_MagicCookie"); break; } err = AudioQueueAddPropertyListener(myData-queue, kAudioQueueProperty_IsRunning, MyAudioQueueIsRunningCallback, myData); if (err) { PRINTERROR("AudioQueueAddPropertyListener"); myData-failed = true; break; } break; } } } static void ReadStreamClientCallBack(CFReadStreamRef stream, CFStreamEventType type, void *clientCallBackInfo) { NSLog(@"start ReadStreamClientCallBack"); if(type == kCFStreamEventHasBytesAvailable) { UInt8 buffer[2048]; CFIndex bytesRead = CFReadStreamRead(stream, buffer, sizeof(buffer)); if (bytesRead < 0) { } else if (bytesRead) { OSStatus err = AudioFileStreamParseBytes(globalMyData-audioFileStream, bytesRead, buffer, 0); if (err) { PRINTERROR("AudioFileStreamParseBytes"); } } } } void MyPacketsProc(void * inClientData, UInt32 inNumberBytes, UInt32 inNumberPackets, const void * inInputData, AudioStreamPacketDescription inPacketDescriptions) { NSLog(@"start MyPacketsProc"); MyData myData = (MyData*)inClientData; printf("got data. bytes: %d packets: %d\n", inNumberBytes, inNumberPackets); for (int i = 0; i < inNumberPackets; ++i) { SInt64 packetOffset = inPacketDescriptions[i].mStartOffset; SInt64 packetSize = inPacketDescriptions[i].mDataByteSize; size_t bufSpaceRemaining = kAQBufSize - myData-bytesFilled; if (bufSpaceRemaining < packetSize) { MyEnqueueBuffer(myData); WaitForFreeBuffer(myData); } AudioQueueBufferRef fillBuf = myData-audioQueueBuffer[myData-fillBufferIndex]; memcpy((char*)fillBuf-mAudioData + myData-bytesFilled, (const char*)inInputData + packetOffset, packetSize); myData-packetDescs[myData-packetsFilled] = inPacketDescriptions[i]; myData-packetDescs[myData-packetsFilled].mStartOffset = myData-bytesFilled; myData-bytesFilled += packetSize; myData-packetsFilled += 1; size_t packetsDescsRemaining = kAQMaxPacketDescs - myData-packetsFilled; if (packetsDescsRemaining == 0) { MyEnqueueBuffer(myData); WaitForFreeBuffer(myData); } } } (IBAction)buttonPlayPressedid)sender { label.text = @"Buffering"; [self connectionStart]; } (IBAction)buttonSavePressedid)sender { NSLog(@"save"); AudioFileClose(myData.audioFile); AudioQueueDispose(myData.queue, TRUE); } bool getFilename(char* buffer,int maxBufferLength) { NSArray paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString docDir = [paths objectAtIndex:0]; NSString* file = [docDir stringByAppendingString:@"/rec.caf"]; return [file getCString:buffer maxLength:maxBufferLength encoding:NSUTF8StringEncoding]; } -(void)connectionStart { @try { MyData* myData = (MyData*)calloc(1, sizeof(MyData)); globalMyData = myData; pthread_mutex_init(&myData-mutex, NULL); pthread_cond_init(&myData-cond, NULL); pthread_cond_init(&myData-done, NULL); NSLog(@"Start"); myData-dataFormat.mSampleRate = 16000.0f; myData-dataFormat.mFormatID = kAudioFormatLinearPCM; myData-dataFormat.mFramesPerPacket = 1; myData-dataFormat.mChannelsPerFrame = 1; myData-dataFormat.mBytesPerFrame = 2; myData-dataFormat.mBytesPerPacket = 2; myData-dataFormat.mBitsPerChannel = 16; myData-dataFormat.mReserved = 0; myData-dataFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked; int i, bufferByteSize; UInt32 size; AudioQueueNewInput( &myData-dataFormat, MyAudioQueueOutputCallback, &myData, NULL /* run loop /, kCFRunLoopCommonModes / run loop mode /, 0 / flags */, &myData-queue); size = sizeof(&myData-dataFormat); AudioQueueGetProperty(&myData-queue, kAudioQueueProperty_StreamDescription, &myData-dataFormat, &size); CFURLRef fileURL; char path[256]; memset(path,0,sizeof(path)); getFilename(path,256); fileURL = CFURLCreateFromFileSystemRepresentation(NULL, (UInt8*)path, strlen(path), FALSE); AudioFileCreateWithURL(fileURL, kAudioFileCAFType, &myData-dataFormat, kAudioFileFlags_EraseFile, &myData-audioFile); OSStatus err = AudioFileStreamOpen(myData, MyPropertyListenerProc, MyPacketsProc, kAudioFileMP3Type, &myData-audioFileStream); if (err) { PRINTERROR("AudioFileStreamOpen"); return 1; } CFStreamClientContext ctxt = {0, self, NULL, NULL, NULL}; CFStringRef bodyData = CFSTR(""); // Usually used for POST data CFStringRef headerFieldName = CFSTR("X-My-Favorite-Field"); CFStringRef headerFieldValue = CFSTR("Dreams"); CFStringRef url = CFSTR(RADIO_LOCATION); CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, url, NULL); CFStringRef requestMethod = CFSTR("GET"); CFHTTPMessageRef myRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL, kCFHTTPVersion1_1); CFHTTPMessageSetBody(myRequest, bodyData); CFHTTPMessageSetHeaderFieldValue(myRequest, headerFieldName, headerFieldValue); CFReadStreamRef stream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, myRequest); if (!stream) { NSLog(@"Creating the stream failed"); return; } if (!CFReadStreamSetClient(stream, kNetworkEvents, ReadStreamClientCallBack, &ctxt)) { CFRelease(stream); NSLog(@"Setting the stream's client failed."); return; } CFReadStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); if (!CFReadStreamOpen(stream)) { CFReadStreamSetClient(stream, 0, NULL, NULL); CFReadStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); CFRelease(stream); NSLog(@"Opening the stream failed."); return; } } @catch (NSException *exception) { NSLog(@"main: Caught %@: %@", [exception name], [exception reason]); } } (void)viewDidLoad { [[UIApplication sharedApplication] setIdleTimerDisabled:YES]; [super viewDidLoad]; } (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } (void)viewDidUnload { } (void)dealloc { [super dealloc]; } @end

    Read the article

  • Proper way to add record to many to many relationship in Django

    - by blcArmadillo
    First off, I'm planning on running my project on google app engine so I'm using djangoappengine which as far as I know doesn't support django's ManyToManyField type. Because of this I've setup my models like this: from django.db import models from django.contrib.auth.models import User class Group(models.Model): name = models.CharField(max_length=200) class UserGroup(models.Model): user = models.ForeignKey(User) group = models.ForeignKey(Group) On a page I have a form field where people can enter a group name. I want the results from this form field to create a UserGroup object for the user - group combination and if the group doesn't yet exist create a new Group object. At first I started putting this logic in the UserGroup class with a add_group method but quickly realized that it doesn't really make sense to put this in the UserGroup class. What would the proper way of doing this be? I saw some stuff about model managers. Is this what those are for?

    Read the article

  • Entity Framework Adding new record with foreign key constraint

    - by Brono The Vibrator
    In an effort to learn the entity framework I have created two tables in a one to many relationship. The one table (Author) has the following fields - AuthorID, FirstName, LastName. The many table (Payroll) has the following fields - PayrollID, AuthorID, Salary. I have CRUD stored procdures for insert, update and delete. What I am tying to figure-out is how to add new payroll records to the payroll table.

    Read the article

< Previous Page | 25 26 27 28 29 30 31 32 33 34 35 36  | Next Page >