Search Results

Search found 7391 results on 296 pages for 'record locking'.

Page 26/296 | < Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >

  • Fread binary file dynamic size string [C]

    - by Blackbinary
    I've been working on this assignment, where I need to read in "records" and write them to a file, and then have the ability to read/find them later. On each run of the program, the user can decide to write a new record, or read an old record (either by Name or #) The file is binary, here is its definition: typedef struct{ char * name; char * address; short addressLength, nameLength; int phoneNumber; }employeeRecord; employeeRecord record; The way the program works, it will store the structure, then the name, then the address. Name and address are dynamically allocated, which is why it is necessary to read the structure first to find the size of the name and address, allocate memory for them, then read them into that memory. For debugging purposes I have two programs at the moment. I have my file writing program, and file reading. My actual problem is this, when I read a file I have written, i read in the structure, print out the phone # to make sure it works (which works fine), and then fread the name (now being able to use record.nameLength which reports the proper value too). Fread however, does not return a usable name, it returns blank. I see two problems, either I haven't written the name to the file correctly, or I haven't read it in correctly. Here is how i write to the file: where fp is the file pointer. record.name is a proper value, so is record.nameLength. Also i am writing the name including the null terminator. (e.g. 'Jack\0') fwrite(&record,sizeof record,1,fp); fwrite(record.name,sizeof(char),record.nameLength,fp); fwrite(record.address,sizeof(char),record.addressLength,fp); And i then close the file. here is how i read the file: fp = fopen("employeeRecord","r"); fread(&record,sizeof record,1,fp); printf("Number: %d\n",record.phoneNumber); char *nameString = malloc(sizeof(char)*record.nameLength); printf("\nName Length: %d",record.nameLength); fread(nameString,sizeof(char),record.nameLength,fp); printf("\nName: %s",nameString); Notice there is some debug stuff in there (name length and number, both of which are correct). So i know the file opened properly, and I can use the name length fine. Why then is my output blank, or a newline, or something like that? (The output is just Name: with nothing after it, and program finishes just fine) Thanks for the help.

    Read the article

  • How to salvage SQL server 2008 query from KILLED/ROLLBACK state?

    - by littlegreen
    I have a stored procedure that inserts batches of millions of rows, emerging from a certain query, into an SQL database. It has one parameter selecting the batch; when this parameter is omitted, it will gather a list of batches and recursively call itself, in order to iterate over batches. In (pseudo-)code, it looks something like this: CREATE PROCEDURE spProcedure AS BEGIN IF @code = 0 BEGIN ... WHILE @@Fetch_Status=0 BEGIN EXEC spProcedure @code FETCH NEXT ... INTO @code END END ELSE BEGIN -- Disable indexes ... INSERT INTO table SELECT (...) -- Enable indexes ... Now it can happen that this procedure is slow, for whatever reason: it can't get a lock, one of the indexes it uses is misdefined or disabled. In that case, I want to be able kill the procedure, truncate and recreate the resulting table, and try again. However, when I try and kill the procedure, the process frequently oozes into a KILLED/ROLLBACK state from which there seems to be no return. From Google I have learned to do an sp_lock, find the spid, and then kill it with KILL <spid>. But when I try to kill it, it tells me SPID 75: transaction rollback in progress. Estimated rollback completion: 0%. Estimated time remaining: 554 seconds. I did find a forum message hinting that another spid should be killed before the other one can start a rollback. But that didn't work for me either, plus I do not understand, why that would be the case... could it be because I am recursively calling my own stored procedure? (But it should be having the same spid, right?) In any case, my process is just sitting there, being dead, not responding to kills, and locking the table. This is very frustrating, as I want to go on developing my queries, not waiting hours on my server sitting dead while pretending to be finishing a supposed rollback. Is there some way in which I can tell the server not to store any rollback information for my query? Or not to allow any other queries to interfere with the rollback, so that it will not take so long? Or how to rewrite my query in a better way, or how kill the process successfully without restarting the server?

    Read the article

  • Query for rows including child rows

    - by MAD9
    A few weeks ago, I asked a question about how to generate hierarchical XML from a table, that has a parentID column. It all works fine. The point is, according to the hierarchy, I also want to query a table. I'll give you an example: Thats the table with the codes: ID CODE NAME PARENTID 1 ROOT IndustryCode NULL 2 IND Industry 1 3 CON Consulting 1 4 FIN Finance 1 5 PHARM Pharmaceuticals 2 6 AUTO Automotive 2 7 STRAT Strategy 3 8 IMPL Implementation 3 9 CFIN Corporate Finance 4 10 CMRKT Capital Markets 9 From which I generate (for displaying in a TreeViewControl) this XML: <record key="1" parentkey="" Code="ROOT" Name="IndustryCode"> <record key="2" parentkey="1" Code="IND" Name="Industry"> <record key="5" parentkey="2" Code="PHARM" Name="Pharmaceuticals" /> <record key="6" parentkey="2" Code="AUTO" Name="Automotive" /> </record> <record key="3" parentkey="1" Code="CON" Name="Consulting"> <record key="7" parentkey="3" Code="STRAT" Name="Strategy" /> <record key="8" parentkey="3" Code="IMPL" Name="Implementation" /> </record> <record key="4" parentkey="1" Code="FIN" Name="Finance"> <record key="9" parentkey="4" Code="CFIN" Name="Corporate Finance"> <record key="10" parentkey="9" Code="CMRKT" Name="Capital Markets" /> </record> </record> </record> As you can see, some codes are subordinate to others, for example AUTO << IND << ROOT What I want (and have absolutely no idea how to realise or even, where to start) is to be able to query another table (where one column is this certain code of course) for a code and get all records with the specific code and all subordinate codes For example: I query the other table for "IndustryCode = IND[ustry]" and get (of course) the records containing "IND", but also AUTO[motive] and PHARM[aceutical] (= all subordinates) Its an SQL Express Server 2008 with Advanced Services.

    Read the article

  • Query column and everything subordinate (hard to describe, non native speaker, PLS let me explain)

    - by MAD9
    A few weeks ago, I asked a question about how to generate hierarchical XML from a table, that has a parentID column. It all works fine. The point is, according to the hierarchy, I also want to query a table. I'll give you an example: Thats the table with the codes: ID CODE NAME PARENTID 1 ROOT IndustryCode NULL 2 IND Industry 1 3 CON Consulting 1 4 FIN Finance 1 5 PHARM Pharmaceuticals 2 6 AUTO Automotive 2 7 STRAT Strategy 3 8 IMPL Implementation 3 9 CFIN Corporate Finance 4 10 CMRKT Capital Markets 9 From which I generate (for displaying in a TreeViewControl) this XML: <record key="1" parentkey="" Code="ROOT" Name="IndustryCode"> <record key="2" parentkey="1" Code="IND" Name="Industry"> <record key="5" parentkey="2" Code="PHARM" Name="Pharmaceuticals" /> <record key="6" parentkey="2" Code="AUTO" Name="Automotive" /> </record> <record key="3" parentkey="1" Code="CON" Name="Consulting"> <record key="7" parentkey="3" Code="STRAT" Name="Strategy" /> <record key="8" parentkey="3" Code="IMPL" Name="Implementation" /> </record> <record key="4" parentkey="1" Code="FIN" Name="Finance"> <record key="9" parentkey="4" Code="CFIN" Name="Corporate Finance"> <record key="10" parentkey="9" Code="CMRKT" Name="Capital Markets" /> </record> </record> </record> As you can see, some codes are subordinate to others, for example AUTO << IND << ROOT What I want (and have absolutely no idea how to realise or even, where to start) is to be able to query another table (where one column is this certain code of course) for a code and get all records with the specific code and all subordinate codes For example: I query the other table for "IndustryCode = IND[ustry]" and get (of course) the records containing "IND", but also AUTO[motive] and PHARM[aceutical] (= all subordinates) Its an SQL Express Server 2008 with Advanced Services.

    Read the article

  • How to salvage SQL server 2008 query from KILLED/ROLLBACK state without waiting half a day?

    - by littlegreen
    I have a stored procedure that inserts batches of millions of rows, emerging from a certain query, into an SQL database. It has one parameter selecting the batch; when this parameter is omitted, it will gather a list of batches and recursively call itself, in order to iterate over batches. In (pseudo-)code, it looks something like this: CREATE PROCEDURE spProcedure AS BEGIN IF @code = 0 BEGIN ... WHILE @@Fetch_Status=0 BEGIN EXEC spProcedure @code FETCH NEXT ... INTO @code END END ELSE BEGIN -- Disable indexes ... INSERT INTO table SELECT (...) -- Enable indexes ... Now it can happen that this procedure is slow, for whatever reason: it can't get a lock, one of the indexes it uses is misdefined or disabled. In that case, I want to be able kill the procedure, truncate and recreate the resulting table, and try again. However, when I try and kill the procedure, the process frequently oozes into a KILLED/ROLLBACK state from which there seems to be no return. From Google I have learned to do an sp_lock, find the spid, and then kill it with KILL <spid>. But when I try to kill it, it tells me SPID 75: transaction rollback in progress. Estimated rollback completion: 0%. Estimated time remaining: 554 seconds. I did find a forum message hinting that another spid should be killed before the other one can start a rollback. But that didn't work for me either, plus I do not understand, why that would be the case... could it be because I am recursively calling my own stored procedure? (But it should be having the same spid, right?) In any case, my process is just sitting there, being dead, not responding to kills, and locking the table. This is very frustrating, as I want to go on developing my queries, not waiting hours on my server sitting dead while pretending to be finishing a supposed rollback. Is there some way in which I can tell the server not to store any rollback information for my query? Or not to allow any other queries to interfere with the rollback, so that it will not take so long? Or how to rewrite my query in a better way, or how kill the process successfully without restarting the server?

    Read the article

  • How to get Media Picker Field via proxy record of many-to-many in orchard

    - by Sergey Schipanov
    I need to access mediapickerfield in Widget view. This field is relative to 'ActionPart'. I have a problem, when I create many-to-many relationships to display my 'ActionPart' in the widget. When I mapped many-to-many I take an 'ActionPart' and but cannot access the mediapickerfield. Records classes public class ActionPartRecord : ContentPartRecord { public virtual string Text { get; set; } public virtual double Price { get; set; } public virtual int TextPosX { get; set; } public virtual int TextPosY { get; set; } public virtual String TextSale { get; set; } public virtual int Color { get; set; } } public class ActionListRecord { public virtual int Id { get; set; } public virtual ActionPartRecord ActionPartRecord { get; set; } public virtual ActionWidgetPartRecord ActionWidgetPartRecord { get; set; } } public class ActionWidgetPartRecord : ContentPartRecord { public ActionWidgetPartRecord() { ActionList = new List<ActionListRecord>(); } public virtual IList<ActionListRecord> ActionList { get; set; } } public class ActionWidgetPart : ContentPart<ActionWidgetPartRecord> { public IEnumerable<ActionPartRecord> ActionList { get { return Record.ActionList.Select(x => x.ActionPartRecord); } } } ActionPart class public class ActionPart : ContentPart<ActionPartRecord> { public String Text { get { return Record.Text; } set { Record.Text = value; } } /*other field*/ } Migrations public int Create() { SchemaBuilder.CreateTable("ActionPartRecord", table => table .ContentPartRecord() .Column<string>("Text") .Column<double>("Price") .Column<int>("TextPosX") .Column<int>("TextPosY") .Column<string>("TextSale") .Column<int>("Color") ); ContentDefinitionManager.AlterPartDefinition("ActionPart", builder => builder .WithField("BaseImage", fieldBuilder => fieldBuilder.OfType("MediaPickerField").WithDisplayName("Action Image")) .WithField("PatternImage", fieldBuilder => fieldBuilder.OfType("MediaPickerField").WithDisplayName("Pattern Image")) .WithField("TimeExp", fieldBuilder => fieldBuilder.OfType("DateTimeField").WithDisplayName("Expecting date")) .Attachable()); ContentDefinitionManager.AlterTypeDefinition("Action", cfg => cfg .WithPart("CommonPart") .WithPart("TitlePart") .WithPart("RoutePart") .WithPart("BodyPart") .WithPart("ActionPart") .Creatable() .Indexed()); SchemaBuilder.CreateTable("ActionListRecord", table => table .Column<int>("Id", column => column.PrimaryKey().Identity()) .Column<int>("ActionPartRecord_Id") .Column<int>("ActionWidgetPartRecord_Id") ); SchemaBuilder.CreateTable("ActionWidgetPartRecord", table => table .ContentPartRecord() ); ContentDefinitionManager.AlterPartDefinition( "ActionWidgetPart", builder => builder.Attachable()); ContentDefinitionManager.AlterTypeDefinition("ActionWidget", cfg => cfg .WithPart("ActionWidgetPart") .WithPart("WidgetPart") .WithPart("CommonPart") .WithSetting("Stereotype", "Widget")); return 1; } Driver Display method protected override DriverResult Display( ActionWidgetPart part, string displayType, dynamic shapeHelper) { return ContentShape("Parts_ActionWidget", () => shapeHelper.Parts_ActionWidget( ContentPart: part, ActionList: part.ActionList)); } Widget View @foreach (var action in Model.ActionList) { <div class="item"> *How to access BaseImage Field in this row* <div class="sale-pattern"></div> <div class="container"> <div class="carousel-caption"> <h1>@action.Text</h1> <h1 class="price">@action.Price</h1> </div> </div> </div> }

    Read the article

  • How do I Insert Record MVVM through WCF

    - by DG KOL
    Hello, I’m new in MVVM Pattern (Using Galasoft MVVM Light toolkit). I’ve created a Test Project where I want to fetch some records from Database through WCF. This is working fine but I’ve failed to insert new record from View; Here is My Code: Database Table Name: TestUser (First Name, LastName) WCF (NWCustomer) Two Methods Public List<TestUser> GetAllUsers() [“LINQ2SQL Operation”] Public bool AddUser(TestUser testuser) Public bool AddUser(TestUser testuser) { try { using (DBDataContext db = new DBDataContext()) { TestUser test = new TestUser() { FirstName = testuser.FirstName, LastName = testuser.LastName }; db.TestUser.InsertOnSubmit(test); db.SubmitChanges(); } } catch (Exception ex) { return false; } return true; } Silverlight Project MODEL consists ITestUserService.cs TestUserService.cs public void AddTestTable(TestTableViewModel testuser, Action<bool> callback) { NWCustomerClient client = new NWCustomerClient("BasicHttpBinding_NWCustomer"); client.AddTestUserCompleted += (s, e) => { var userCallback = e.UserState as Action<bool>; if (userCallback == null) { return; } if (e.Error == null) { userCallback(e.Result); return; } userCallback(false); }; client.AddTestUserAsync(testuser.Model); } VIEWMODEL TestUserViewModel public TestUser User { get; private set; } public const string DirtyVisibilityPropertyName = "DirtyVisibility"; private Visibility _dirty = Visibility.Collapsed; public Visibility DirtyVisibility { get { return _dirty; } set { if (_dirty == value) { return; } _dirty = value; RaisePropertyChanged(DirtyVisibilityPropertyName); } } public TestUserViewModel (TestUser user) { User = user; user.PropertyChanged += (s, e) => { DirtyVisibility = Visibility.Visible; }; } MainViewModel public ObservableCollection<TestUserViewModel> TestTables { get; private set; } public const string ErrorMessagePropertyName = "ErrorMessage"; private string _errorMessage = string.Empty; public string ErrorMessage { get { return _errorMessage; } set { if (_errorMessage == value) { return; } _errorMessage = value; RaisePropertyChanged(ErrorMessagePropertyName); } } private ITestUserService _service; public RelayCommand< TestUserViewModel> AddTestUserRecord { get; private set; } public MainTestTableViewModel (ICustomerService service) { _service = service; TestTables = new ObservableCollection<TestTableViewModel>(); service.GetAllTestTable(HandleResult); } private void HandleResult(IEnumerable<TestTable> result, Exception ex) { TestTables.Clear(); if (ex != null) { //Error return; } if (result == null) { return; } foreach (var test in result) { var table = new TestTableViewModel(test); TestTables.Add(table); } } XAML <Grid x:Name="LayoutRoot"> <StackPanel> <TextBox Text="FirstName" /> <TextBox Text="LastName" /> <Button Content="Add Record" Command="{Binding AddTestUserRecord}" /> </StackPanel> </Grid> I want to add records into TestTable (Database Table). How do I insert record? In XAML two text box and a button control is present. Thanking you. DG

    Read the article

  • Generating different randoms valid for a day on different independent devices?

    - by Pentium10
    Let me describe the system. There are several mobile devices, each independent from each other, and they are generating content for the same record id. I want to avoid generating the same content for the same record on different devices, for this I though I would use a random and make it so too cluster the content pool based on these randoms. Suppose you have choices from 1 to 100. Day 1 Device#1 will choose for the record#33 between 1-10 Device#2 will choose for the record#33 between 40-50 Device#3 will choose for the record#33 between 50-60 Device#1 will choose for the record#55 between 40-50 Device#2 will choose for the record#55 between 1-10 Device#3 will choose for the record#55 between 10-20 Device#1 will choose for the record#11 between 1-10 Device#2 will choose for the record#22 between 1-10 Device#3 will choose for the record#99 between 1-10 Day 2 Device#1 will choose for the record#33 between 90-100 Device#2 will choose for the record#33 between 1-10 Device#3 will choose for the record#33 between 50-60 They don't have access to a central server. Data available for each of them: IMEI (unique per mobile) Date of today (same on all devices) Record id (same on all devices) What do you think, how is it possible? ps. tags can be edited

    Read the article

  • Java: Making concurrent MySQL queries from multiple clients synchronised

    - by Misha Gale
    I work at a gaming cybercafe, and we've got a system here (smartlaunch) which keeps track of game licenses. I've written a program which interfaces with this system (actually, with it's backend MySQL database). The program is meant to be run on a client PC and (1) query the database to select an unused license from the pool available, then (2) mark this license as in use by the client PC. The problem is, I've got a concurrency bug. The program is meant to be launched simultaneously on multiple machines, and when this happens, some machines often try and acquire the same license. I think that this is because steps (1) and (2) are not synchronised, i.e. one program determines that license #5 is available and selects it, but before it can mark #5 as in use another copy of the program on another PC tries to grab that same license. I've tried to solve this problem by using transactions and table locking, but it doesn't seem to make any difference - Am I doing this right? Here follows the code in question: public LicenseKey Acquire() throws SmartLaunchException, SQLException { Connection conn = SmartLaunchDB.getConnection(); int PCID = SmartLaunchDB.getCurrentPCID(); conn.createStatement().execute("LOCK TABLE `licensekeys` WRITE"); String sql = "SELECT * FROM `licensekeys` WHERE `InUseByPC` = 0 AND LicenseSetupID = ? ORDER BY `ID` DESC LIMIT 1"; PreparedStatement statement = conn.prepareStatement(sql); statement.setInt(1, this.id); ResultSet results = statement.executeQuery(); if (results.next()) { int licenseID = results.getInt("ID"); sql = "UPDATE `licensekeys` SET `InUseByPC` = ? WHERE `ID` = ?"; statement = conn.prepareStatement(sql); statement.setInt(1, PCID); statement.setInt(2, licenseID); statement.executeUpdate(); statement.close(); conn.commit(); conn.createStatement().execute("UNLOCK TABLES"); return new LicenseKey(results.getInt("ID"), this, results.getString("LicenseKey"), results.getInt("LicenseKeyType")); } else { throw new SmartLaunchException("All licenses of type " + this.name + "are in use"); } }

    Read the article

  • How to write my own global lock / unlock functions for PostgreSQL

    - by rafalmag
    I have postgresql (in perlu) function getTravelTime(integer, timestamp), which tries to select data for specified ID and timestamp. If there are no data or if data is old, it downloads them from external server (downloading time ~300ms). Multiple process use this database and this function. There is an error when two process do not find data and download them and try to do an insert to travel_time table (id and timestamp pair have to be unique). I thought about locks. Locking whole table would block all processes and allow only one to proceed. I need to lock only on id and timestamp. pg_advisory_lock seems to lock only in "current session". But my processes uses their own sessions. I tried to write my own lock/unlock functions. Am I doing it right? I use active waiting, how can I omit this? Maybe there is a way to use pg_advisory_lock() as global lock? My code: CREATE TABLE travel_time_locks ( id_key integer NOT NULL, time_key timestamp without time zone NOT NULL, UNIQUE (id_key, time_key) ); ------------ -- Function: mylock(integer, timestamp) DROP FUNCTION IF EXISTS mylock(integer, timestamp) CASCADE; -- Usage: SELECT mylock(1, '2010-03-28T19:45'); -- function tries to do a global lock similar to pg_advisory_lock(key, key) CREATE OR REPLACE FUNCTION mylock(id_input integer, time_input timestamp) RETURNS void AS $BODY$ DECLARE rows int; BEGIN LOOP BEGIN -- active waiting here !!!! :( INSERT INTO travel_time_locks (id_key, time_key) VALUES (id_input, time_input); EXCEPTION WHEN unique_violation THEN CONTINUE; END; EXIT; END LOOP; END; $BODY$ LANGUAGE 'plpgsql' VOLATILE COST 1; ------------ -- Function: myunlock(integer, timestamp) DROP FUNCTION IF EXISTS myunlock(integer, timestamp) CASCADE; -- Usage: SELECT myunlock(1, '2010-03-28T19:45'); -- function tries to do a global unlock similar to pg_advisory_unlock(key, key) CREATE OR REPLACE FUNCTION myunlock(id_input integer, time_input timestamp) RETURNS integer AS $BODY$ DECLARE BEGIN DELETE FROM ONLY travel_time_locks WHERE id_key=id_input AND time_key=time_input; RETURN 1; END; $BODY$ LANGUAGE 'plpgsql' VOLATILE COST 1;

    Read the article

  • How to change the "record external input" in Fraps?

    - by CyanPrime
    I'm using a TV to USB capture thingy called Hauppauge USB-Live2 (http://www.hauppauge.com/site/products/data_usblive2.html) and I'm using Media Player Classic Home Cinema to view my device's output, and finally I'm using Fraps to record the output off of MPC. It all works nicely except I can't get my mic to record, or even show up in the "Record External Input" area of Fraps while my Hauppauge is plugged in. My question is: How can I select my mic as the "record external input" in fraps?

    Read the article

  • A deadlock was detected while trying to lock variables in SSIS

    Error: 0xC001405C at SQL Log Status: A deadlock was detected while trying to lock variables "User::RowCount" for read/write access. A lock cannot be acquired after 16 attempts. The locks timed out. Have you ever considered variable locking when building your SSIS packages? I expect many people haven’t just because most of the time you never see an error like the one above. I’ll try and explain a few key concepts about variable locking and hopefully you never will see that error. First of all, what is all this variable locking all about? Put simply SSIS variables have to be locked before they can be accessed, and then of course unlocked once you have finished with them. This is baked into SSIS, presumably to reduce the risk of race conditions, but with that comes some additional overhead in that you need to be careful to avoid lock conflicts in some scenarios. The most obvious place you will come across any hint of locking (no pun intended) is the Script Task or Script Component with their ReadOnlyVariables and ReadWriteVariables properties. These two properties allow you to enter lists of variables to be used within the task, or to put it another way, these lists of variables to be locked, so that they are available within the task. During the task pre-execute phase the variables and locked, you then use them during the execute phase when you code is run, and then unlocked for you during the post-execute phase. So by entering the variable names in one of the two list, the locking is taken care of for you, and you just read and write to the Dts.Variables collection that is exposed in the task for the purpose. As you can see in the image above, the variable PackageInt is specified, which means when I write the code inside that task I don’t have to worry about locking at all, as shown below. public void Main() { // Set the variable value to something new Dts.Variables["PackageInt"].Value = 199; // Raise an event so we can play in the event handler bool fireAgain = true; Dts.Events.FireInformation(0, "Script Task Code", "This is the script task raising an event.", null, 0, ref fireAgain); Dts.TaskResult = (int)ScriptResults.Success; } As you can see as well as accessing the variable, hassle free, I also raise an event. Now consider a scenario where I have an event hander as well as shown below. Now what if my event handler uses tries to use the same variable as well? Well obviously for the point of this post, it fails with the error quoted previously. The reason why is clearly illustrated if you consider the following sequence of events. Package execution starts Script Task in Control Flow starts Script Task in Control Flow locks the PackageInt variable as specified in the ReadWriteVariables property Script Task in Control Flow executes script, and the On Information event is raised The On Information event handler starts Script Task in On Information event handler starts Script Task in On Information event handler attempts to lock the PackageInt variable (for either read or write it doesn’t matter), but will fail because the variable is already locked. The problem is caused by the event handler task trying to use a variable that is already locked by the task in Control Flow. Events are always raised synchronously, therefore the task in Control Flow that is raising the event will not regain control until the event handler has completed, so we really do have un-resolvable locking conflict, better known as a deadlock. In this scenario we can easily resolve the problem by managing the variable locking explicitly in code, so no need to specify anything for the ReadOnlyVariables and ReadWriteVariables properties. public void Main() { // Set the variable value to something new, with explicit lock control Variables lockedVariables = null; Dts.VariableDispenser.LockOneForWrite("PackageInt", ref lockedVariables); lockedVariables["PackageInt"].Value = 199; lockedVariables.Unlock(); // Raise an event so we can play in the event handler bool fireAgain = true; Dts.Events.FireInformation(0, "Script Task Code", "This is the script task raising an event.", null, 0, ref fireAgain); Dts.TaskResult = (int)ScriptResults.Success; } Now the package will execute successfully because the variable lock has already been released by the time the event is raised, so no conflict occurs. For those of you with a SQL Engine background this should all sound strangely familiar, and boils down to getting in and out as fast as you can to reduce the risk of lock contention, be that SQL pages or SSIS variables. Unfortunately we cannot always manage the locking ourselves. The Execute SQL Task is very often used in conjunction with variables, either to pass in parameter values or get results out. Either way the task will manage the locking for you, and will fail when it cannot lock the variables it requires. The scenario outlined above is clear cut deadlock scenario, both parties are waiting on each other, so it is un-resolvable. The mechanism used within SSIS isn’t actually that clever, and whilst the message says it is a deadlock, it really just means it tried a few times, and then gave up. The last part of the error message is actually the most accurate in terms of the failure, A lock cannot be acquired after 16 attempts. The locks timed out.  Now this may come across as a recommendation to always manage locking manually in the Script Task or Script Component yourself, but I think that would be an overreaction. It is more of a reminder to be aware that in high concurrency scenarios, especially when sharing variables across multiple objects, locking is important design consideration. Update – Make sure you don’t try and use explicit locking as well as leaving the variable names in the ReadOnlyVariables and ReadWriteVariables lock lists otherwise you’ll get the deadlock error, you cannot lock a variable twice!

    Read the article

  • How do I avoid a race condition in my Rails app?

    - by Cathal
    Hi, I have a really simple Rails application that allows users to register their attendance on a set of courses. The ActiveRecord models are as follows: class Course < ActiveRecord::Base has_many :scheduled_runs ... end class ScheduledRun < ActiveRecord::Base belongs_to :course has_many :attendances has_many :attendees, :through => :attendances ... end class Attendance < ActiveRecord::Base belongs_to :user belongs_to :scheduled_run, :counter_cache => true ... end class User < ActiveRecord::Base has_many :attendances has_many :registered_courses, :through => :attendances, :source => :scheduled_run end A ScheduledRun instance has a finite number of places available, and once the limit is reached, no more attendances can be accepted. def full? attendances_count == capacity end attendances_count is a counter cache column holding the number of attendance associations created for a particular ScheduledRun record. My problem is that I don't fully know the correct way to ensure that a race condition doesn't occur when 1 or more people attempt to register for the last available place on a course at the same time. My Attendance controller looks like this: class AttendancesController < ApplicationController before_filter :load_scheduled_run before_filter :load_user, :only => :create def new @user = User.new end def create unless @user.valid? render :action => 'new' end @attendance = @user.attendances.build(:scheduled_run_id => params[:scheduled_run_id]) if @attendance.save flash[:notice] = "Successfully created attendance." redirect_to root_url else render :action => 'new' end end protected def load_scheduled_run @run = ScheduledRun.find(params[:scheduled_run_id]) end def load_user @user = User.create_new_or_load_existing(params[:user]) end end As you can see, it doesn't take into account where the ScheduledRun instance has already reached capacity. Any help on this would be greatly appreciated.

    Read the article

  • Adding new record to a VFP data table in VB.NET with ADO recordsets

    - by Gerry
    I am trying to add a new record to a Visual FoxPro data table using an ADO dataset with no luck. The code runs fine with no exceptions but when I check the dbf after the fact there is no new record. The mDataPath variable shown in the code snippet is the path to the .dbc file for the entire database. A note about the For loop at the bottom; I am adding the body of incoming emails to this MEMO field so thought I needed to break the addition of this string into 256 character Chunks. Any guidance would be greatly appreciated. cnn1.Open("Driver={Microsoft Visual FoxPro Driver};" & _ "SourceType=DBC;" & _ "SourceDB=" & mDataPath & ";Exclusive=No") Dim RS As ADODB.RecordsetS = New ADODB.Recordset RS.Open("select * from gennote", cnn1, 1, 3, 1) RS.AddNew() 'Assign values to the first three fields RS.Fields("ignnoteid").Value = NextIDI RS.Fields("cnotetitle").Value = "'" & mail.Subject & "'" RS.Fields("cfilename").Value = "''" 'Looping through 254 characters at a time and add the data 'to Ado Field buffer For i As Integer = 1 To Len(memo) Step liChunkSize liStartAt = i liWorkString = Mid(mail.Body, liStartAt, liChunkSize) RS.Fields("mnote").AppendChunk(liWorkString) Next 'Update the recordset RS.Update() RS.Requery() RS.Close()

    Read the article

  • Subsonic 3.0.0.4 Does not Update

    - by geocine
    I tried 3 variants but doesn't seem to update (I am using Linq Templates and MSSQL) Luna.Data.GameDBDB db = new Luna.Data.GameDBDB(); db.Update<Luna.Record.TB_ITEM>() .Set(x => x.ITEM_DURABILITY == Convert.ToInt32(quantity)) .Where(x => x.ITEM_DBIDX == Convert.ToInt32(dbdidx)) .Execute(); Here is the other one var db = new Luna.Data.GameDBDB(); var query = (from p in db.TB_ITEMS where p.ITEM_DBIDX == Convert.ToInt32(dbidx) select p).Single(); query.ITEM_DURABILITY = Convert.ToInt32(quantity); db.tp TP_ITEM_UPDATE(); and the other one var db = new Luna.Data.GameDBDB(); var query = (from p in db.TB_ITEMS where p.ITEM_DBIDX == Convert.ToInt32(dbidx) select p).Single(); query.ITEM_DURABILITY = Convert.ToInt32(quantity); db.Update<Luna.Data.TB_ITEM>(); However it worked using LINQ-to-SQL LunaDataContext db = new LunaDataContext(); var query = (from p in db.TB_ITEMs where p.ITEM_DBIDX == Convert.ToInt32(dbidx) select p).Single(); query.ITEM_DURABILITY = Convert.ToInt32(quantity); db.SubmitChanges(); Is this a bug in 3.0.0.4, the database record couldn't be updated using Linq Templates and ActiveRecord.

    Read the article

  • AVAudioRecorder Won't Record On Device

    - by Dyldo42
    This is my method: -(void) playOrRecord:(UIButton *)sender { if (playBool == YES) { NSError *error = nil; NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat: @"%d", [sender tag]] ofType:@"caf"]; NSURL *fileUrl = [NSURL fileURLWithPath:filePath]; AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error]; [player setNumberOfLoops:0]; [player play]; } else if (playBool == NO) { if ([recorder isRecording]) { [recorder stop]; [nowRecording setImage:[UIImage imageNamed:@"NormalNormal.png"] forState:UIControlStateNormal]; [nowRecording setImage:[UIImage imageNamed:@"NormalSelected.png"] forState:UIControlStateSelected]; } if (nowRecording == sender) { nowRecording = nil; return; } nowRecording = sender; NSError *error = nil; NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat: @"%d", [sender tag]] ofType:@"caf"]; NSURL *fileUrl = [NSURL fileURLWithPath:filePath]; [sender setImage:[UIImage imageNamed:@"RecordingNormal.png"] forState:UIControlStateNormal]; [sender setImage:[UIImage imageNamed:@"RecordingSelected.png"] forState:UIControlStateSelected]; recorder = [[AVAudioRecorder alloc] initWithURL:fileUrl settings:recordSettings error:&error]; [recorder record]; } } Most of it is self explanatory; playBool is a BOOL that is YES when it is in play mode. Everything works in the simulator however, when I run it on a device, [recorder record] returns NO. Does anyone have a clue as to why this is happening?

    Read the article

  • subsonic . navigate among records ,view,query

    - by gmo camilo
    hello everybody i'm some newbie in this matter of .net i'm trying understand this new paradigm i began with linq for SQl but i found this library, kind of framework of T4 more specifically: subsonic T4 i think it could be very usefull but the support docs outside are very scarce my first intention is use them in the very simple form: a catalog lets say... Users so... how can i use the model generated with subsonic ( using the iactiverecord) to implement the record-navigational part.,...???!!! i mean i want a simple form to create, delete or modify records and that is fairy easy but what about to move among records ? i found how to get the first, the last record.. but how can i advance or go back among them??? how can i order the records..? it seems everytime imust query the table.. its so? but how can imove among the records i already got? all of the exmples found are very simple dont touch the matter and/ or are repetitive everywhere so.. please if anybody can help me or give more references... i'd thank you a lot gmo camilo

    Read the article

  • Ability to draw and record a signature as part of a form - iphone

    - by mustic
    Apolgies in advance for any errors.. new to this and am not a developer/programmer.. just have some basic unix experience. I have searched the web and struggled to find a solution to my problem when I stumbled onto this website which maybe suggested that there is a solution to my question. For work i use a windows mobile device because we have to get customers to sign and form after a customer visit. the signature being very important. On the windows device i use the notes application and am able to record details and obtain/record (using draw) a customer signature. the form is then emailed back to HQ. The format being used is a *.pwi I have downloaded and paid for several applications for my iphone which is my preferred device and cant quite find anything that does both. the critical bit here is to be able to take a signature on the phone, save the doc in a format such as .txt, .doc or .pdf where i can control the file name then be able to email back to HQ. Am i asking too much? I hope that makes sense.. Any help would be much appreciated many thanks in advance

    Read the article

  • Active Record two belongs_to calls or single table inheritance

    - by ethyreal
    In linking a sports event to two teams, at first this seemed to make sense: events - id:integer - integer:home_team_id - integer:away_team_id teams - integer:id - string:name However I am troubled by how I would link that up in the active record model: class Event belongs_to :home_team, :class_name => 'Team', :foreign_key => "home_team_id" belongs_to :away_team, :class_name => 'Team', :foreign_key => "away_team_id" end Is that the best solution? In an answer to a similar question I was pointed to single table inheritance, and then later found polymorphic associations. Neither of which seemed to fit this association. Perhaps I am looking at this wrong, but I see no need to subclass a team into home and away teams since the distinction is only in where the game is played. If I did go with single table inheritance I wouldn't want each team to belong_to an event so would this work? # app/models/event.rb class Event < ActiveRecord::Base belongs_to :home_team belongs_to :away_team end # app/models/team.rb class Team < ActiveRecord::Base has_many :teams end # app/models/home_team.rb class HomeTeam < Team end # app/models/away_team.rb class AwayTeam < Team end I thought also about a has_many through association but that seems two much as I will only ever need two teams, but those two teams don't belong to any one event. event_teams - integer:event_id - integer:team_id - boolean:is_home Is there a cleaner more semantic way for making these associations in active record? or is one of these solutions the best choice? Thanks

    Read the article

  • Active Record two belongs_to calls to the same model

    - by ethyreal
    In linking a sports event to two teams, at first this seemed to make since: events - id:integer - integer:home_team_id - integer:away_team_id teams - integer:id - string:name However I am troubled by how I would link that up in the active record model: class Event belongs_to :home_team, :class_name => 'Team', :foreign_key => "home_team_id" belongs_to :away_team, :class_name => 'Team', :foreign_key => "away_team_id" end Is that the best solution? In an answer to a similar question I was pointed to single table inheritance, and then later found polymorphic associations. Neither of which seemed to fit this association. Perhaps I am looking at this wrong, but I see no need to subclass a team into home and away teams since the distinction is only in where the game is played. I thought also about a has_many through association but that seems two much as I will only ever need two teams, but those two teams don't belong to any one event. event_teams - integer:event_id - integer:team_id - boolean:is_home Is there a cleaner more semantic way for making these associations in active record? Thanks

    Read the article

  • Displaying tree path of record in SQL Server 2005

    - by jskiles1
    An example of my tree table is: ([id] is an identity) [id], [parent_id], [path] 1, NULL, 1 2, 1, 1-2 3, 1, 1-3 4, 3, 1-3-4 My goal is to query quickly for multiple rows of this table and view the full path of the node from its root, through its superiors, down to itself. The ultimate question is, should I generate this path on inserts and maintain it in its own column or generate this path on query to save disk space? I guess it depends if this table is write heavy or read heavy. I've been contemplating several approaches to using the "path" characteristic of this parent/child relationship and I just can't seem to settle on one. This "path" is simply for display purposes and serves absolutely no purpose other than that. Here is what I have done to implement this "path." AFTER INSERT TRIGGER - requires passing a NULL path to the insert and updating the path for the record at the inserted rows identity INSTEAD OF INSERT TRIGGER - does not require insert to have NULL path passed, but does require the trigger to insert with a NULL path and updating the path for the record at SCOPE_IDENTITY() STORED PROCEDURE - requiring all inserts into this table to be done through the stored procedure implementing the trigger logic VIEW - requires building the path in the view 1 and 2 seem annoying if massive amounts of data are entered at once. 3 seems annoying because all inserts must go through the procedure in order to have a valid path populated. 1, 2, and 3 require maintaining a path column on the table. 4 removes all the limitations of the above but require the view to perform the path logic and requires use of the view if a path is to be displayed. I have successfully implemented all of the above approaches and I'm mainly looking for some advice. Am I way off the mark here or are any of the above acceptable? Each has it's advantages and disadvantages.

    Read the article

  • How to record video in iphone

    - by Timmi
    HI, I need to record video using iPhone. To do that i used UIImagePickerController. I have an iPhone 3G, with me. when i run my code to check if source type available it says device not supported. My OS is 3.2.1, where i am wrong, can some one tell me what i need to change. Also is there some other way to record video. What i need to do is to get the video stream as it is recorded. UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; NSArray *sourceTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType]; if (![sourceTypes containsObject:(NSString *)kUTTypeVideo ]){ NSLog(@"device not supported"); return; } //picker.allowsEditing = YES; picker.sourceType = UIImagePickerControllerSourceTypeCamera; picker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeVideo]; picker.videoQuality = UIImagePickerControllerQualityTypeHigh; [self presentModalViewController:picker animated:YES]; Thanks,

    Read the article

  • Error while updating Database record with Entity Framework on ASP.NET MVC Page

    - by Rupa
    Hi I have an ASP.NET Page that updates registered User Address Details for a selected record. Below is the Update method that i am calling from Controller. When i am calling ApplyPropertyChanges method, I am getting the below error. Did anyone run into the same error while updating the record with Entity Framework. Appreciate your responses. Error Message: The existing object in the ObjectContext is in the Added state. Changes can only be applied when the existing object is in an unchanged or modified state. My Update Method Code: [HttpPost] public bool UpdateAddressDetail([Bind(Prefix = "RegUser")] AddressDetail regUserAddress, FormCollection formData) { regUserAddress.AD_Id = 3; regUserAddress.LastUpdated = HttpContext.User.Identity.Name; regUserAddress.UpdatedOn = DateTime.Now; regUserAddress.AddressType = ((AddressDetail)Session["CurrentAddress"]).AddressType ?? "Primary"; regUserAddress.Phone = ((AddressDetail)Session["CurrentAddress"]).Phone; regUserAddress.Country = ((AddressDetail)Session["CurrentAddress"]).AddressType ?? "USA"; miEntity.ApplyPropertyChanges(regUserAddress.EntityKey.EntitySetName, regUserAddress); miEntity.SaveChanges(); return true; }

    Read the article

  • Need to get 3 record for database on current date using sqlite

    - by Umaid
    SELECT rowid, Day, Advice from MainCategory where ((Day = ((cast(strftime('%d',date('now','-1 day')) as Integer)))) and (Month = (strftime('%m',date('now'))))) and ((Day = ((cast(strftime('%d',date('now')) as Integer)))) and (Month = (strftime('%m',date('now'))))) , ((Day = ((cast(strftime('%d',date('now','+1 day')) as Integer)))) and (Month = (strftime('%m',date('now',+1 month))))); What if i make my Month column in Integer data type then it would be. SELECT rowid, Month, Day, Advice from MainCategory where ((Day = ((cast(strftime('%d',date('now','-1 day')) as Integer)))) and (Month = (strftime('%m',date('now'))))) and ((Day = ((cast(strftime('%d',date('now')) as Integer)))) and (Month = (strftime('%m',date('now'))))) , ((Day = ((cast(strftime('%d',date('now','+1 day')) as Integer)))) and (Month = (strftime('%m',date('now',+1 month))))); Please note that I have over this scenerio when I am in middle of month but below query returns 2 records and 1 from begining from all 11 months as (feb is exclusive) then record will be 33 but i need three 3 records from the table and increment it on next button. Please write 3 querys one which return all three record on current date, next all 3 records must be incremented by 1 on every next button click finally all 3 records must be decremented by 1 on every previous button click keep last day and begining date on the month in minds else i have also achieved for middle of month. Running query but returns 33 records instead of 3. SELECT rowid,Month, Day, Advice from MainCategory where Day in ((cast(strftime('%d',date('now','-1 day')) as Integer)),(cast(strftime('%d',date('now')) as Integer)),(cast(strftime('%d',date('now','+1 day')) as Integer)));

    Read the article

  • Query next/previous record

    - by Rob
    I'm trying to find a better way to get the next or previous record from a table. Let's say I have a blog or news table: CREATE TABLE news ( news_id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, news_datestamp DATETIME NOT NULL, news_author VARCHAR(100) NOT NULL, news_title VARCHAR(100) NOT NULL, news_text MEDIUMTEXT NOT NULL ); Now on the frontend I want navigation buttons for the next or previous records, if i'm sorting by news_id, I can do something rather simple like: SELECT MIN(news_id) AS next_news_id FROM news WHERE news_id > '$old_news_id' LIMIT 1 SELECT MAX(news_id) AS prev_news_id FROM news WHERE news_id < '$old_news_id' LIMIT 1 But the news can be sorted by any field, and I don't necessarily know which field is sorted on, so this won't work if the user sorts on news_author for example. I've resorted to the rather ugly and inefficient method of sorting the entire table and looping through all records until I find the record I need. $res = mysql_query("SELECT news_id FROM news ORDER BY `$sort_column` $sort_way"); $found = $prev = $next = 0; while(list($id) = mysql_fetch_row($res)) { if($found) { $next = $id; break; } if($id == $old_news_id) { $found = true; continue; } $prev = $id; } There's got to be a better way.

    Read the article

< Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >