Search Results

Search found 2441 results on 98 pages for 'delegate'.

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

  • DRY Authenticated Tasks in Cocoa (with distributed objects)

    - by arbales
    I'm kind of surprise/infuriated that the only way for me to run an authenticated task, like perhaps sudo gem install shi*t, is to make a tool with pre-written code. I'm writing a MacRuby application, which doesn't seem to expose the KAuthorization* constants/methods. So.. I learned Cocoa and Objective-C. My application creates a object, serves it and calls the a tool that elevates itself and then performs a selector on a distributed object (in the tool's thread). I hoped that the distributed object's methods would evaluated inside the tool, so I could use delegation to create "privileged" tasks. If this won't work, don't try to save it, I just want a DRY/cocoa solution. AuthHelper.m //AuthorizationExecuteWithPrivileges of this. AuthResponder* my_responder = [AuthResponder sharedResponder]; // Gets the proxy object (and it's delegate) NSString *selector = [NSString stringWithUTF8String:argv[3]]; NSLog(@"Performing selector: %@", selector); setuid(0); if ([[my_responder delegate] respondsToSelector:NSSelectorFromString(selector)]){ [[my_responder delegate] performSelectorOnMainThread:NSSelectorFromString(selector) withObject:nil waitUntilDone:YES]; } RandomController.m - (void)awakeFromNib { helperToolPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/AuthHelper"]; delegatePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/ABExtensions.rb"]; AuthResponder* my_responder = [AuthResponder initAsService]; [my_responder setDelegate:self]; } -(oneway void)install_gems{ NSArray *args = [NSArray arrayWithObjects: @"gem", @"install", @"sinatra", nil]; [NSTask launchedTaskWithLaunchPath:@"/usr/bin/sudo" arguments:args]; NSLog(@"Ran AuthResponder.delegate.install_gems"); // This prints. } ... other privileges tasks. "sudo gem update --system" for one. I'm guessing the proxy object is performing the selector in it's own thread, but I want the current (privileged thread) to do it so I can use sudo. Can I force the distributed object to evaluate the selector on the tool's thread? How else can I accomplish this dryly/cocoaly?

    Read the article

  • BackgroundWorker.ReportProgress() not updating property and locking up the UI

    - by Willem
    i am using a backgroundWorker to do a long running operation: BackgroundWorker backgroundWorker = new BackgroundWorker() { WorkerSupportsCancellation = true, WorkerReportsProgress = true }; backgroundWorker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args) { }; backgroundWorker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args) { someViewModel.SomeProperty.Add((SomeObject)args.UserState); }; backgroundWorker.DoWork += delegate(object s, DoWorkEventArgs args) { someViewModel.SomeList.ForEach(x => { someViewModel.SomeInterface.SomeMethod(backgroundWorker, someViewModel, someViewModel.SomeList, x); }); }; backgroundWorker.RunWorkerAsync(); Then in SomeInterface.SomeMethod: public void SomeMethod(BackgroundWorker backgroundWorker, SomeViewModel someViewModel//....) { //Filtering happens backgroundWorker.ReportProgress(0, someObjectFoundWhileFiltering); } So, when it comes to: backgroundWorker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args) { someViewModel.SomeProperty.Add((SomeObject)args.UserState);//Adding the found object to the Property in the VM }; On the line someViewModel.SomeProperty.Add((SomeObject)args.UserState);, the set on the Property is not firering and the UI just locks up. What am i doing wrong? Is this the correct way to update the UI thread?

    Read the article

  • Core Data Inferred Migration – Automatic "lightweight" vs Manual

    - by ohhorob
    I've updated the model of an existing iPhone app in some simple ways (remove attribute, add attribute, remove index), and can use automatic lightweight migration to migrate the persistent store. Due to the typical size of the data set, the processing time is not insignificant, and warrants feedback for the user. NSMigrationManager provides a simple but useful migrationProgress value that sends KVO notifications as the migration is performed. That forms the basis of providing feedback, however attempting to use an inferred model ([NSMappingModel inferredMappingModelForSourceModel:destinationModel:error:]) results in drastically different timing for the exact same dataset. Profile results on and original iPhone (2G) Automatic inferred lightweight migration PROFILE: CacheManager -migrateStore PROFILE: 0.6130 (+0.6130) models loaded PROFILE: 1.1759 (+0.5629) delegate -CacheManagerWillMigrate: PROFILE: 1.2516 (+0.0757) persistent store coordinator loaded PROFILE: 5.1436 (+3.8920) automatic lightweight migration completed PROFILE: 5.5435 (+0.3999) delegate -CacheManagerDidFinishMigration:withError: Manual inferred migration PROFILE: CacheManager -migrateStore PROFILE: 0.6660 (+0.6660) models loaded PROFILE: 1.1471 (+0.4811) inferred mapping model generated PROFILE: 1.4046 (+0.2574) delegate -CacheManagerWillMigrate: PROFILE: 1.5058 (+0.1013) persistent store coordinator loaded PROFILE: 22.6952 (+21.1894) manual migration completed PROFILE: 23.1478 (+0.4525) delegate -CacheManagerDidFinishMigration:withError: So, with an inferred model, the manual migration takes over 5 times longer than automatic! It's a big inconsistency, and the lightweight option that NSPersistentStoreCoordinator -addPersistentStoreWithType:configuration:URL:options:error: provides absolutely no indication of progress while processing. Can anybody provide a supported way to get the migrationProgress values during automatic migration, OR a way to configure an inferred mapping model to be as fast during manual processing as automatic?

    Read the article

  • Dynamic Method Creation

    - by TJMonk15
    So, I have been trying to research this all morning, and have had no luck. I am trying to find a way to dynamically create a method/delegate/lambda that returns a new instance of a certain class (not known until runtime) that inherits from a certain base class. I can guarantee the following about the unknown/dynamic class It will always inherit from one known Class (Row) It will have atleast 2 constructors (one accepting a long, and one accepting an IDataRecord) I plan on doign the following: Finding all classes that have a certain attribute on them Creating a delegate/method/lambda/whatever that creates a new instance of the class Storing the delegate/whatever along with some properties in a struct/class Insert the struct into a hashtable When needed, pull the info out of the hashtable and calling the delegate/whatever to get a new instance of the class and returning it/adding it to a list/etc. I need help only with #2 above!!! I have no idea where to start. I really just need some reference material to get me started, or some keywords to throw into google. This is for a compact/simple to use ORM for our office here. I understand the above is not simple, but once working, should make maintaining the code incredibly simple. Please let me know if you need any more info! And thanks in advance! :)

    Read the article

  • Inheritance issue with ivar on the iPhone

    - by Buffalo
    I am using the BLIP/MYNetwork library to establish a basic tcp socket connection between the iPhone and my computer. So far, the code builds and runs correctly in simulator but deploying to device yields the following error: error: property 'delegate' attempting to use ivar '_delegate' declared in super class of 'TCPConnection' @interface TCPConnection : TCPEndpoint { @private TCPListener *_server; IPAddress *_address; BOOL _isIncoming, _checkedPeerCert; TCPConnectionStatus _status; TCPReader *_reader; TCPWriter *_writer; NSError *_error; NSTimeInterval _openTimeout; } /** The delegate object that will be called when the connection opens, closes or receives messages. */ @property (assign) id<TCPConnectionDelegate> delegate; /** The delegate messages sent by TCPConnection. All methods are optional. */ @protocol TCPConnectionDelegate <NSObject> @optional /** Called after the connection successfully opens. */ - (void) connectionDidOpen: (TCPConnection*)connection; /** Called after the connection fails to open due to an error. */ - (void) connection: (TCPConnection*)connection failedToOpen: (NSError*)error; /** Called when the identity of the peer is known, if using an SSL connection and the SSL settings say to check the peer's certificate. This happens, if at all, after the -connectionDidOpen: call. */ - (BOOL) connection: (TCPConnection*)connection authorizeSSLPeer: (SecCertificateRef)peerCert; /** Called after the connection closes. You can check the connection's error property to see if it was normal or abnormal. */ - (void) connectionDidClose: (TCPConnection*)connection; @end @interface TCPEndpoint : NSObject { NSMutableDictionary *_sslProperties; id _delegate; } - (void) tellDelegate: (SEL)selector withObject: (id)param; @end Does anyone know how I would fix this? Would I simply declare _delegate as a public property of the base class "TCPEndPoint"? Thanks for the help ya'll!

    Read the article

  • Why the performance of following code is degrading when I use threads ?

    - by DotNetBeginner
    Why the performance of following code is degrading when I use threads ? **1.Without threads int[] arr = new int[100000000]; //Array elements - [0][1][2][3]---[100000000-1] addWithOutThreading(arr); // Time required for this operation - 1.16 sec Definition for addWithOutThreading public void addWithOutThreading(int[] arr) { UInt64 result = 0; for (int i = 0; i < 100000000; i++) { result = result + Convert.ToUInt64(arr[i]); } Console.WriteLine("Addition = " + result.ToString()); } **2.With threads int[] arr = new int[100000000]; int part = (100000000 / 4); UInt64 res1 = 0, res2 = 0, res3 = 0, res4 = 0; ThreadStart starter1 = delegate { addWithThreading(arr, 0, part, ref res1); }; ThreadStart starter2 = delegate { addWithThreading(arr, part, part * 2, ref res2); }; ThreadStart starter3 = delegate { addWithThreading(arr, part * 2, part * 3, ref res3); }; ThreadStart starter4 = delegate { addWithThreading(arr, part * 3, part * 4, ref res4); }; Thread t1 = new Thread(starter1); Thread t2 = new Thread(starter2); Thread t3 = new Thread(starter3); Thread t4 = new Thread(starter4); t1.Start(); t2.Start(); t3.Start(); t4.Start(); t1.Join(); t2.Join(); t3.Join(); t4.Join(); Console.WriteLine("Addition = "+(res1+res2+res3+res4).ToString()); // Time required for this operation - 1.30 sec Definition for addWithThreading public void addWithThreading(int[] arr,int startIndex, int endIndex,ref UInt64 result) { for (int i = startIndex; i < endIndex; i++) { result = result + Convert.ToUInt64(arr[i]); } }

    Read the article

  • ApplicationDelegate is not doing its own job here ! Can anyone help me??

    - by ahmet732
    (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { MaSystemGuiAppDelegate *appDelegate = (MaSystemGuiAppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.deneme = [tableData objectAtIndex:indexPath.row] ; NSLog(@"my row", appDelegate.deneme); // THIS IS NOT PRINTING NSLog(@"my row = %@", [tableData objectAtIndex:indexPath.row]); //THIS IS PRINTING THE VALUE ON CONSOLE NSInteger row = [indexPath row]; if(self.searchDetailViewController == nil){ SearchDetailViewController *asearchDetail = [[SearchDetailViewController alloc] initWithNibName:@"SearchDetailView" bundle:nil]; self.searchDetailViewController = asearchDetail; [asearchDetail release]; } searchDetailViewController.title = [NSString stringWithFormat:@"%@", [searchArray objectAtIndex:row]]; MaSystemGuiAppDelegate *delegate = [[UIApplication sharedApplication] delegate]; [delegate.searchNavController pushViewController:searchDetailViewController animated:YES]; } "deneme" is a NMUtableArray is identified in MaSystemGuiAppDelegate.h (I identified it as a variable and put its property there) and I wrote "deneme= [[NSMutableArray alloc]init]; in applicationDidFinishLaunching method in MaSystemGuiAppDelegate.m. In the code above, [tableData objectAtIndex:indexPath.row] is retrieving the one of the value touched on tableview. When I put that value in deneme (as u noticed in the code) it is printing nothing. What am i missing? (I imported MaSystemGuiAppDelegate.h)

    Read the article

  • How to manage large amounts of delegates and usercallbacks in C# async http library

    - by Tyler
    I'm coding a .NET library in C# for communicating with XBMC via its JSON RPC interface using HTTP. I coded and released a preliminary version but everything is done synchronously. I then recoded the library to be asynchronous for my own purposes as I was/am building an XBMC remote for WP7. I now want to release the new async library but want to make sure it's nice and tidy before I do. Due to the async nature a user initiates a request, supplies a callback method that matches my delegate and then handles the response once it's been received. The problem I have is that within the library I track a RequestState object for the lifetime of the request, it contains the http request/response as well as the user callback etc. as member variables, this would be fine if only one type of object was coming back but depending on what the user calls they may be returned a list of songs or a list of movies etc. My implementation at the moment uses a single delegate ResponseDataRecieved which has a single parameter which is a simple Object - As this has only be used by me I know which methods return what and when I handle the response I cast said object to the type I know it really is - List, List etc. A third party shouldn't have to do this though - The delegate signature should contain the correct type of object. So then I need a delegate for every type of response data that can be returned to the third party - The specific problem is, how do I handle this gracefully internally - Do I have a bunch of different RequestState objects that each have a different member variable for the different delegates? That doesn't "feel" right. I just don't know how to do this gracefully and cleanly.

    Read the article

  • Why null reference exception in SetMolePublicInstance?

    - by OldGrantonian
    I get a "null reference" exception in the following line: MoleRuntime.SetMolePublicInstance(stub, receiverType, objReceiver, name, null); The program builds and compiles correctly. There are no complaints about any of the parameters to the method. Here's the specification of SetMolePublicInstance, from the object browser: SetMolePublicInstance(System.Delegate _stub, System.Type receiverType, object _receiver, string name, params System.Type[] parameterTypes) Here are the parameter values for "Locals": + stub {Method = {System.String <StaticMethodUnitTestWithDeq>b__0()}} System.Func<string> + receiverType {Name = "OrigValue" FullName = "OrigValueP.OrigValue"} System.Type {System.RuntimeType} objReceiver {OrigValueP.OrigValue} object {OrigValueP.OrigValue} name "TestString" string parameterTypes null object[] I know that TestString() takes no parameters and returns string, so as a starter to try to get things working, I specified "null" for the final parameter to SetMolePublicInstance. As already mentioned, this compiles OK. Here's the stack trace: Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.ExtendedReflection.Collections.Indexable.ConvertAllToArray[TInput,TOutput](TInput[] array, Converter`2 converter) at Microsoft.Moles.Framework.Moles.MoleRuntime.SetMole(Delegate _stub, Type receiverType, Object _receiver, String name, MoleBindingFlags flags, Type[] parameterTypes) at Microsoft.Moles.Framework.Moles.MoleRuntime.SetMolePublicInstance(Delegate _stub, Type receiverType, Object _receiver, String name, Type[] parameterTypes) at DeqP.Deq.Replace[T](Func`1 stub, Type receiverType, Object objReceiver, String name) in C:\0VisProjects\DecP_04\DecP\DeqC.cs:line 38 at DeqPTest.DecCTest.StaticMethodUnitTestWithDeq() in C:\0VisProjects\DecP_04\DecPTest\DeqCTest.cs:line 28 at Starter.Start.Main(String[] args) in C:\0VisProjects\DecP_04\Starter\Starter.cs:line 14 Press any key to continue . . . To avoid the null parameter, I changed the final "null" to "parameterTypes" as in the following line: MoleRuntime.SetMolePublicInstance(stub, receiverType, objReceiver, name, parameterTypes); I then tried each of the following (before the line): int[] parameterTypes = null; // if this is null, I don't think the type will matter int[] parameterTypes = new int[0]; object[] parameterTypes = new object[0]; // this would allow for various parameter types All three attempts produce a red squiggly line under the entire line for SetMolePublicInstance Mouseover showed the following message: The best overloaded method match for 'Microsoft.Moles.Framework.Moles.MoleRuntime.SetMolePublicInstance(System.Delegate, System.Type, object, string, params System.Type[])' has some invalid arguments. I'm assuming that the first four arguments are OK, and that the problem is with the params array.

    Read the article

  • Invoking [SKProductsRequest start] hangs on iOS 4.0

    - by figelwump
    Encountering an issue with SKProductsRequest that is specific to iOS 4.0. The problematic code: - (void)requestProductData { NSSet *productIdentifiers = [NSSet setWithObjects:kLimitedDaysUpgradeProductId, kUnlimitedUpgradeProductId, nil]; self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers]; self.productsRequest.delegate = self; [self.productsRequest start]; } - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response { NSLog(@"didReceiveResponse"); } When [SKProductsRequest start] is invoked, the productsRequest:didReceiveResponse: delegate method is never invoked; further, the entire app hangs and is completely unresponsive to input. Obviously, this is a huge issue for our iOS 4.0 users as it not only breaks payments but makes the app completely unusable. Some other things to note: this only happens on iOS 4.0; iOS 4.2, 3.x are fine. Also: if the delegate is not set on the SKProductsRequest (i.e. comment out the line "self.productsRequest.delegate = self;"), the app doesn't hang (but of course in that case we have no way of getting the product info). Also, the problem still reproduces with everything stripped out of the productsRequest:didReceiveResponse: callback (that method never actually gets called). Finally, if the productIdentifiers NSSet object is initialized to an empty set, the hang doesn't occur. Has anybody else experienced this? Any ideas/thoughts on what could be going on here, and how we might be able to work around this?

    Read the article

  • C# Passing objects and list of objects by reference

    - by David Liddle
    I have a delegate that modifies an object. I pass an object to the delegate from a calling method, however the calling method does not pickup these changes. The same code works if I pass a List as the object. I thought all objects were passed by reference so any modifications would be reflected in the calling method? I can modify my code to pass a ref object to the delegate but am wondering why this is necessary? public class Binder { protected delegate int MyBinder<T>(object reader, T myObject); public void BindIt<T>(object reader, T myObject) { //m_binders is a hashtable of binder objects MyBinder<T> binder = m_binders["test"] as MyBinder<T>; int i = binder(reader, myObject); } } public class MyObjectBinder { public MyObjectBinder() { m_delegates["test"] = new MyBinder<MyObject>(BindMyObject); } private int BindMyObject(object reader, MyObject obj) { //make changes to obj in here } } ///calling method in some other class public void CallingMethod() { MyObject obj = new MyObject(); MyBinder binder = new MyBinder(); binder.BindIt(myReader, obj); //don't worry about myReader //obj should show reflected changes }

    Read the article

  • Code Contracts: Hiding ContractException

    - by DigiMortal
    It’s time to move on and improve my randomizer I wrote for an example of static checking of code contracts. In this posting I will modify contracts and give some explanations about pre-conditions and post-conditions. Also I will show you how to avoid ContractExceptions and how to replace them with your own exceptions. As a first thing let’s take a look at my randomizer. public class Randomizer {     public static int GetRandomFromRange(int min, int max)     {         var rnd = new Random();         return rnd.Next(min, max);     }       public static int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires(min < max, "Min must be less than max");           var rnd = new Random();         return rnd.Next(min, max);     } } We have some problems here. We need contract for method output and we also need some better exception handling mechanism. As ContractException as type is hidden from us we have to switch from ContractException to some other Exception type that we can catch. Adding post-condition Pre-conditions are contracts for method’s input interface. Read it as follows: pre-conditions make sure that all conditions for method’s successful run are met. Post-conditions are contracts for output interface of method. So, post-conditions are for output arguments and return value. My code misses the post-condition that checks return value. Return value in this case must be greater or equal to minimum value and less or equal to maximum value. To make sure that method can run only the correct value I added call to Contract.Ensures() method. public static int GetRandomFromRangeContracted(int min, int max) {     Contract.Requires(min < max, "Min must be less than max");       Contract.Ensures(         Contract.Result<int>() >= min &&         Contract.Result<int>() <= max,         "Return value is out of range"     );       var rnd = new Random();     return rnd.Next(min, max); } I think that the line I added does not need any further comments. Avoiding ContractException for input interface ContractException lives in hidden namespace and we cannot see it at design time. But it is common exception type for all contract exceptions that we do not switch over to some other type. The case of Contract.Requires() method is simple: we can tell it what kind of exception we need if something goes wrong with contract it ensures. public static int GetRandomFromRangeContracted(int min, int max) {     Contract.Requires<ArgumentOutOfRangeException>(         min < max,         "Min must be less than max"     );       Contract.Ensures(         Contract.Result<int>() >= min &&         Contract.Result<int>() <= max,         "Return value is out of range"     );       var rnd = new Random();     return rnd.Next(min, max); } Now, if we violate the input interface contract giving min value that is not less than max value we get ArgumentOutOfRangeException. Avoiding ContractException for output interface Output interface is more complex to control. We cannot give exception type there and hope that this type of exception will be thrown if something goes wrong. Instead we have to use delegate that gathers information about problem and throws the exception we expect to be thrown. From documentation you can find the following example about the delegate I mentioned. Contract.ContractFailed += (sender, e) => {     e.SetHandled();     e.SetUnwind(); // cause code to abort after event     Assert.Fail(e.FailureKind.ToString() + ":" + e.DebugMessage); }; We can use this delegate to throw the Exception. Let’s move the code to separate method too. Here is our method that uses now ContractException hiding. public static int GetRandomFromRangeContracted(int min, int max) {     Contract.Requires(min < max, "Min must be less than max");       Contract.Ensures(         Contract.Result<int>() >= min &&         Contract.Result<int>() <= max,         "Return value is out of range"     );     Contract.ContractFailed += Contract_ContractFailed;       var rnd = new Random();     return rnd.Next(min, max)+1000; } And here is the delegate that creates exception. public static void Contract_ContractFailed(object sender,     ContractFailedEventArgs e) {     e.SetHandled();     e.SetUnwind();       throw new Exception(e.FailureKind.ToString() + ":" + e.Message); } Basically we can do in this delegate whatever we like to do with output interface errors. We can even introduce our own contract exception type. As you can see later then ContractFailed event is very useful at unit testing.

    Read the article

  • Mocking the Unmockable: Using Microsoft Moles with Gallio

    - by Thomas Weller
    Usual opensource mocking frameworks (like e.g. Moq or Rhino.Mocks) can mock only interfaces and virtual methods. In contrary to that, Microsoft’s Moles framework can ‘mock’ virtually anything, in that it uses runtime instrumentation to inject callbacks in the method MSIL bodies of the moled methods. Therefore, it is possible to detour any .NET method, including non-virtual/static methods in sealed types. This can be extremely helpful when dealing e.g. with code that calls into the .NET framework, some third-party or legacy stuff etc… Some useful collected resources (links to website, documentation material and some videos) can be found in my toolbox on Delicious under this link: http://delicious.com/thomasweller/toolbox+moles A Gallio extension for Moles Originally, Moles is a part of Microsoft’s Pex framework and thus integrates best with Visual Studio Unit Tests (MSTest). However, the Moles sample download contains some additional assemblies to also support other unit test frameworks. They provide a Moled attribute to ease the usage of mole types with the respective framework (there are extensions for NUnit, xUnit.net and MbUnit v2 included with the samples). As there is no such extension for the Gallio platform, I did the few required lines myself – the resulting Gallio.Moles.dll is included with the sample download. With this little assembly in place, it is possible to use Moles with Gallio like that: [Test, Moled] public void SomeTest() {     ... What you can do with it Moles can be very helpful, if you need to ‘mock’ something other than a virtual or interface-implementing method. This might be the case when dealing with some third-party component, legacy code, or if you want to ‘mock’ the .NET framework itself. Generally, you need to announce each moled type that you want to use in a test with the MoledType attribute on assembly level. For example: [assembly: MoledType(typeof(System.IO.File))] Below are some typical use cases for Moles. For a more detailed overview (incl. naming conventions and an instruction on how to create the required moles assemblies), please refer to the reference material above.  Detouring the .NET framework Imagine that you want to test a method similar to the one below, which internally calls some framework method:   public void ReadFileContent(string fileName) {     this.FileContent = System.IO.File.ReadAllText(fileName); } Using a mole, you would replace the call to the File.ReadAllText(string) method with a runtime delegate like so: [Test, Moled] [Description("This 'mocks' the System.IO.File class with a custom delegate.")] public void ReadFileContentWithMoles() {     // arrange ('mock' the FileSystem with a delegate)     System.IO.Moles.MFile.ReadAllTextString = (fname => fname == FileName ? FileContent : "WrongFileName");       // act     var testTarget = new TestTarget.TestTarget();     testTarget.ReadFileContent(FileName);       // assert     Assert.AreEqual(FileContent, testTarget.FileContent); } Detouring static methods and/or classes A static method like the below… public static string StaticMethod(int x, int y) {     return string.Format("{0}{1}", x, y); } … can be ‘mocked’ with the following: [Test, Moled] public void StaticMethodWithMoles() {     MStaticClass.StaticMethodInt32Int32 = ((x, y) => "uups");       var result = StaticClass.StaticMethod(1, 2);       Assert.AreEqual("uups", result); } Detouring constructors You can do this delegate thing even with a class’ constructor. The syntax for this is not all  too intuitive, because you have to setup the internal state of the mole, but generally it works like a charm. For example, to replace this c’tor… public class ClassWithCtor {     public int Value { get; private set; }       public ClassWithCtor(int someValue)     {         this.Value = someValue;     } } … you would do the following: [Test, Moled] public void ConstructorTestWithMoles() {     MClassWithCtor.ConstructorInt32 =            ((@class, @value) => new MClassWithCtor(@class) {ValueGet = () => 99});       var classWithCtor = new ClassWithCtor(3);       Assert.AreEqual(99, classWithCtor.Value); } Detouring abstract base classes You can also use this approach to ‘mock’ abstract base classes of a class that you call in your test. Assumed that you have something like that: public abstract class AbstractBaseClass {     public virtual string SaySomething()     {         return "Hello from base.";     } }      public class ChildClass : AbstractBaseClass {     public override string SaySomething()     {         return string.Format(             "Hello from child. Base says: '{0}'",             base.SaySomething());     } } Then you would set up the child’s underlying base class like this: [Test, Moled] public void AbstractBaseClassTestWithMoles() {     ChildClass child = new ChildClass();     new MAbstractBaseClass(child)         {                 SaySomething = () => "Leave me alone!"         }         .InstanceBehavior = MoleBehaviors.Fallthrough;       var hello = child.SaySomething();       Assert.AreEqual("Hello from child. Base says: 'Leave me alone!'", hello); } Setting the moles behavior to a value of  MoleBehaviors.Fallthrough causes the ‘original’ method to be called if a respective delegate is not provided explicitly – here it causes the ChildClass’ override of the SaySomething() method to be called. There are some more possible scenarios, where the Moles framework could be of much help (e.g. it’s also possible to detour interface implementations like IEnumerable<T> and such…). One other possibility that comes to my mind (because I’m currently dealing with that), is to replace calls from repository classes to the ADO.NET Entity Framework O/R mapper with delegates to isolate the repository classes from the underlying database, which otherwise would not be possible… Usage Since Moles relies on runtime instrumentation, mole types must be run under the Pex profiler. This only works from inside Visual Studio if you write your tests with MSTest (Visual Studio Unit Test). While other unit test frameworks generally can be used with Moles, they require the respective tests to be run via command line, executed through the moles.runner.exe tool. A typical test execution would be similar to this: moles.runner.exe <mytests.dll> /runner:<myframework.console.exe> /args:/<myargs> So, the moled test can be run through tools like NCover or a scripting tool like MSBuild (which makes them easy to run in a Continuous Integration environment), but they are somewhat unhandy to run in the usual TDD workflow (which I described in some detail here). To make this a bit more fluent, I wrote a ReSharper live template to generate the respective command line for the test (it is also included in the sample download – moled_cmd.xml). - This is just a quick-and-dirty ‘solution’. Maybe it makes sense to write an extra Gallio adapter plugin (similar to the many others that are already provided) and include it with the Gallio download package, if  there’s sufficient demand for it. As of now, the only way to run tests with the Moles framework from within Visual Studio is by using them with MSTest. From the command line, anything with a managed console runner can be used (provided that the appropriate extension is in place)… A typical Gallio/Moles command line (as generated by the mentioned R#-template) looks like that: "%ProgramFiles%\Microsoft Moles\bin\moles.runner.exe" /runner:"%ProgramFiles%\Gallio\bin\Gallio.Echo.exe" "Gallio.Moles.Demo.dll" /args:/r:IsolatedAppDomain /args:/filter:"ExactType:TestFixture and Member:ReadFileContentWithMoles" -- Note: When using the command line with Echo (Gallio’s console runner), be sure to always include the IsolatedAppDomain option, otherwise the tests won’t use the instrumentation callbacks! -- License issues As I already said, the free mocking frameworks can mock only interfaces and virtual methods. if you want to mock other things, you need the Typemock Isolator tool for that, which comes with license costs (Although these ‘costs’ are ridiculously low compared to the value that such a tool can bring to a software project, spending money often is a considerable gateway hurdle in real life...).  The Moles framework also is not totally free, but comes with the same license conditions as the (closely related) Pex framework: It is free for academic/non-commercial use only, to use it in a ‘real’ software project requires an MSDN Subscription (from VS2010pro on). The demo solution The sample solution (VS 2008) can be downloaded from here. It contains the Gallio.Moles.dll which provides the here described Moled attribute, the above mentioned R#-template (moled_cmd.xml) and a test fixture containing the above described use case scenarios. To run it, you need the Gallio framework (download) and Microsoft Moles (download) being installed in the default locations. Happy testing…

    Read the article

  • Popping UIView crashes app

    - by Adun
    I'm basically pushing a UIView from a UITableViewController and all it contains is a UIWebView. However when I remove the UIView to return back to the UITableView the app crashes. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here. Create and push another view controller. if (indexPath.row == websiteCell) { NSString *urlPath = [NSString stringWithFormat:@"http://%@", exhibitor.website]; WebViewController *webViewController = [[WebViewController alloc] initWithURLString:urlPath]; // Pass the selected object to the new view controller. [self.parentViewController presentModalViewController:webViewController animated:YES]; [webViewController release]; } } If I comment out the [webViewController release] the app doesn't crash, but I know that this would be a leak. Below is the code for the Web Browser: #import "WebViewController.h" @implementation WebViewController @synthesize webBrowserView; @synthesize urlValue; @synthesize toolBar; @synthesize spinner; @synthesize loadUrl; -(id)initWithURLString:(NSString *)urlString { if (self = [super init]) { urlValue = urlString; } return self; } #pragma mark WebView Controls - (void)goBack { [webBrowserView goBack]; } - (void)goForward { [webBrowserView goForward]; } - (void)reload { [webBrowserView reload]; } - (void)closeBrowser { [self.parentViewController dismissModalViewControllerAnimated:YES]; } #pragma end // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; CGRect contentRect = self.view.bounds; //NSLog(@"%f", contentRect.size.height); float webViewHeight = contentRect.size.height - 44.0f; // navBar = 44 float toolBarHeight = contentRect.size.height - webViewHeight; // navigation bar UINavigationBar *navBar = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 20, contentRect.size.width, 44)] autorelease]; navBar.delegate = self; UIBarButtonItem *doneButton = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:nil action:@selector(closeBrowser)] autorelease]; UINavigationItem *item = [[[UINavigationItem alloc] initWithTitle:@"CEDIA10"] autorelease]; item.leftBarButtonItem = doneButton; [navBar pushNavigationItem:item animated:NO]; [self.view addSubview:navBar]; // web browser webBrowserView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, contentRect.size.width, webViewHeight)]; webBrowserView.delegate = self; webBrowserView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; webBrowserView.scalesPageToFit = YES; [self.view addSubview:webBrowserView]; // buttons UIBarButtonItem *backButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrowleft.png"] style:UIBarButtonItemStylePlain target:self action:@selector(goBack)] autorelease]; UIBarButtonItem *fwdButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrowright.png"] style:UIBarButtonItemStylePlain target:self action:@selector(goForward)] autorelease]; UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reload)] autorelease]; UIBarButtonItem *flexSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease]; UIBarButtonItem *fixSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil] autorelease]; [fixSpace setWidth: 40.0f]; spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease]; [spinner startAnimating]; UIBarButtonItem *loadingIcon = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease]; NSArray *toolBarButtons = [[NSArray alloc] initWithObjects: fixSpace, backButton, fixSpace, fwdButton, flexSpace, loadingIcon, flexSpace, refreshButton, nil]; // toolbar toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, webViewHeight, contentRect.size.width, toolBarHeight)]; toolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth; toolBar.items = toolBarButtons; [self.view addSubview:toolBar]; // load the request NSURL *requestString = [NSURL URLWithString:urlValue]; [webBrowserView loadRequest:[NSURLRequest requestWithURL: requestString]]; [toolBarButtons release]; } - (void)viewWillDisappear { if ([webBrowserView isLoading]) { [webBrowserView stopLoading]; webBrowserView.delegate = nil; } } #pragma mark UIWebView - (void)webViewDidStartLoad:(UIWebView*)webView { [spinner startAnimating]; } - (void)webViewDidFinishLoad:(UIWebView*)webView { [spinner stopAnimating]; } - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { loadUrl = [[request URL] retain]; if ([[loadUrl scheme] isEqualToString: @"mailto"]) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"CEDIA10" message:@"Do you want to open Mail and exit AREC10?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes",nil]; [alert show]; [alert release]; return NO; } [loadUrl release]; return YES; } - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { [spinner stopAnimating]; if (error.code == -1009) { // no internet connection UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"CEDIA10" message:@"You need an active Internet connection." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } } #pragma mark UIAlertView - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (buttonIndex == 1) { [[UIApplication sharedApplication] openURL:loadUrl]; [loadUrl release]; } } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. [webBrowserView release]; [urlValue release]; [toolBar release]; [spinner release]; [loadUrl release]; webBrowserView = nil; webBrowserView.delegate = nil; urlValue = nil; toolBar = nil; spinner = nil; loadUrl = nil; } - (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [webBrowserView release]; [urlValue release]; [toolBar release]; [spinner release]; [loadUrl release]; webBrowserView.delegate = nil; urlValue = nil; toolBar = nil; spinner = nil; loadUrl = nil; [super dealloc]; } @end Below this is the crash log that I am getting: Date/Time: 2010-05-13 11:58:20.023 +1000 OS Version: iPhone OS 3.1.3 (7E18) Report Version: 104 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x00000000, 0x00000000 Crashed Thread: 0 Thread 0 Crashed: 0 libSystem.B.dylib 0x00090b2c __kill + 8 1 libSystem.B.dylib 0x00090b1a kill + 4 2 libSystem.B.dylib 0x00090b0e raise + 10 3 libSystem.B.dylib 0x000a7e34 abort + 36 4 libstdc++.6.dylib 0x00066390 __gnu_cxx::__verbose_terminate_handler() + 588 5 libobjc.A.dylib 0x00008898 _objc_terminate + 160 6 libstdc++.6.dylib 0x00063a84 __cxxabiv1::__terminate(void (*)()) + 76 7 libstdc++.6.dylib 0x00063afc std::terminate() + 16 8 libstdc++.6.dylib 0x00063c24 __cxa_throw + 100 9 libobjc.A.dylib 0x00006e54 objc_exception_throw + 104 10 CoreFoundation 0x00095bf6 -[NSObject doesNotRecognizeSelector:] + 106 11 CoreFoundation 0x0001ab12 ___forwarding___ + 474 12 CoreFoundation 0x00011838 _CF_forwarding_prep_0 + 40 13 QuartzCore 0x0000f448 CALayerCopyRenderLayer + 24 14 QuartzCore 0x0000f048 CA::Context::commit_layer(_CALayer*, unsigned int, unsigned int, void*) + 100 15 QuartzCore 0x0000ef34 CALayerCommitIfNeeded + 336 16 QuartzCore 0x0000eedc CALayerCommitIfNeeded + 248 17 QuartzCore 0x00011ee8 CA::Context::commit_root(void*, void*) + 52 18 QuartzCore 0x00011e80 x_hash_table_foreach + 64 19 QuartzCore 0x00011e2c CA::Transaction::foreach_root(void (*)(void*, void*), void*) + 40 20 QuartzCore 0x0000bb68 CA::Context::commit_transaction(CA::Transaction*) + 1068 21 QuartzCore 0x0000b46c CA::Transaction::commit() + 276 22 QuartzCore 0x000135d4 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 84 23 CoreFoundation 0x0000f82a __CFRunLoopDoObservers + 466 24 CoreFoundation 0x00057340 CFRunLoopRunSpecific + 1812 25 CoreFoundation 0x00056c18 CFRunLoopRunInMode + 44 26 GraphicsServices 0x000041c0 GSEventRunModal + 188 27 UIKit 0x00003c28 -[UIApplication _run] + 552 28 UIKit 0x00002228 UIApplicationMain + 960 29 CEDIA10 0x00002e16 main (main.m:14) 30 CEDIA10 0x00002db8 start + 32 Any ideas on why the app is crashing?

    Read the article

  • Why is the Active Directory security setting for "Write Personal Information" automatically reset?

    - by Holistic Developer
    In my Small Business Server 2003 environment, I would like to be able to have users manage their own delegate permissions for their Exchange mailboxes. By default, the Outlook delegate feature will not work unless I go to the user object in Active Directory and grant Allow on "Write Personal Information" to SELF. This will work temporarily, but something seems to reset this value shortly afterword. What would cause this automatic reset?

    Read the article

  • SOLVED mwfeedparser integrating in my app gives EXC_BAD_ACCESS (code=1, address=0xa0040008)

    - by Pranoy C
    SOLVED- Got it! The problem was that since I am creating the DoParsingStuff *parseThisUrl object in the viewDidLoad method, it's scope was only within that method. So after the method finished, the object got deallocated. I changed it to an instance variable instead and now it works. It gives a different error but that it an entirely different issue. Issue was: I have been struggling with trying to integrate the mwfeedparser library in my app for parsing RSS and ATOM feeds. It throws a gives EXC_BAD_ACCESS error which I can't seem to troubleshoot. //My Class looks like - My interface looks like: #import <Foundation/Foundation.h> #import "MWFeedParser.h" #import "NSString+HTML.h" @protocol ParseCompleted <NSObject> -(void)parsedArray:(NSMutableArray *)parsedArray; @end @interface DoParsingStuff : NSObject<MWFeedParserDelegate> @property (nonatomic,strong) NSMutableArray *parsedItems; @property (nonatomic, strong) NSArray *itemsToDisplay; @property (nonatomic,strong) MWFeedParser *feedParser; @property (nonatomic,strong) NSURL *feedurl; @property (nonatomic,strong) id <ParseCompleted> delegate; -(id)initWithFeedURL:(NSURL *)url; @end //And Implementaion: #import "DoParsingStuff.h" @implementation DoParsingStuff @synthesize parsedItems = _parsedItems; @synthesize itemsToDisplay = _itemsToDisplay; @synthesize feedParser = _feedParser; @synthesize feedurl=_feedurl; @synthesize delegate = _delegate; -(id)initWithFeedURL:(NSURL *)url{ if(self = [super init]){ _feedurl=url; _feedParser = [[MWFeedParser alloc] initWithFeedURL:_feedurl]; _feedParser.delegate=self; _feedParser.feedParseType=ParseTypeFull; _feedParser.connectionType=ConnectionTypeAsynchronously; } return self; } -(void)doParsing{ BOOL y = [_feedParser parse]; } # pragma mark - # pragma mark MWFeedParserDelegate - (void)feedParserDidStart:(MWFeedParser *)parser { //Just tells what url is being parsed e.g. http://www.wired.com/reviews/feeds/latestProductsRss NSLog(@"Started Parsing: %@", parser.url); } - (void)feedParser:(MWFeedParser *)parser didParseFeedInfo:(MWFeedInfo *)info { //What is the Feed about e.g. "Product Reviews" NSLog(@"Parsed Feed Info: “%@”", info.title); //self.title = info.title; } - (void)feedParser:(MWFeedParser *)parser didParseFeedItem:(MWFeedItem *)item { //Prints current element's title e.g. “An Arthropod for Your iDevices” NSLog(@"Parsed Feed Item: “%@”", item.title); if (item) [_parsedItems addObject:item]; } - (void)feedParserDidFinish:(MWFeedParser *)parser {//This is where you can do your own stuff with the parsed items NSLog(@"Finished Parsing%@", (parser.stopped ? @" (Stopped)" : @"")); [_delegate parsedArray:_parsedItems]; //[self updateTableWithParsedItems]; } - (void)feedParser:(MWFeedParser *)parser didFailWithError:(NSError *)error { NSLog(@"Finished Parsing With Error: %@", error); if (_parsedItems.count == 0) { //self.title = @"Failed"; // Show failed message in title } else { // Failed but some items parsed, so show and inform of error UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Parsing Incomplete" message:@"There was an error during the parsing of this feed. Not all of the feed items could parsed." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; [alert show]; } //[self updateTableWithParsedItems]; } @end //I am calling this from my main viewcontroller as such: #import "DoParsingStuff.h" @interface ViewController : UIViewController <ParseCompleted> .... //And I have the following methods in my implementation: DoParsingStuff *parseThisUrl = [[DoParsingStuff alloc] initWithFeedURL:[NSURL URLWithString:@"http://www.theverge.com/rss/index.xml"]]; parseThisUrl.delegate=self; [parseThisUrl doParsing]; I have the method defined here as- -(void)parsedArray:(NSMutableArray *)parsedArray{ NSLog(@"%@",parsedArray); } //I stepped through breakpoints- When I try to go through the breakpoints, I see that everything goes fine till the very last [parseThisUrl doParsing]; in my delegate class. After that it starts showing me memory registers where I get lost. I think it could be due to arc as I have disabled arc on the mwfeedparser files but am using arc in the above classes. If you need the entire project for this, let me know. I tried it with NSZombies enabled and got a bit more info out of it: -[DoParsingStuff respondsToSelector:]: message sent to deallocated instance 0x6a52480 I am not using release/autorelease/retain etc. in this class...but it is being used in the mwfeedparser library.

    Read the article

  • Dealing with the lack of closures in Objective-C

    - by Sean Clark Hess
    Maybe it's just the fact that I've been using http://nodejs.org/ lately, but the lack of closures in Objective-C (iphone) has been really hard to work around. For example, I'm creating service classes. Each service class can have several methods, each of which makes a different URL request. I can use the delegate pattern, but that means that I have to create a new service each time I want to call a method on it (because it has to store the delegate and selector for that request, and new method calls would overwrite them). Even more difficult for me is the fact that I can't easily keep local variables around in the scope for a callback. I have to store anything I want to send back to the delegate on the service class itself, which makes it harder to have more than one method on each class. How do you pros do it? Should I just quit whining and do it another way?

    Read the article

  • Memory leak found with clang but cant release and autorelease crashes

    - by Rudiger
    I have a class that builds a request based on a few passed in variables. The class also has all the delegate methods to receive the data and stores it in a property for the calling class to retrieve. When the class initializes it creates a connection and then returns itself: NSURLConnection *connection; if (self = [super init]) { self.delegate = theDelegate; ...some code here... connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; } return self; So I can't release it normally and if I autorelease it crashes. Is it the job of the calling class to release? And if so does just releasing the initilised object also release connection or do you have to release it specifically? If so how would you? Thanks

    Read the article

  • Scope of variables inside anonymous functions in C#

    - by Vinod
    I have a doubt in scope of varibles inside anonymous functions in C#. Consider the program below: delegate void OtherDel(int x); public static void Main() { OtherDel del2; { int y = 4; del2 = delegate { Console.WriteLine("{0}", y);//Is y out of scope }; } del2(); } My VS2008 IDE gives the following errors: [Practice is a class inside namespace Practice] 1.error CS1643: Not all code paths return a value in anonymous method of type 'Practice.Practice.OtherDel' 2.error CS1593: Delegate 'OtherDel' does not take '0' arguments. It is told in a book: Illustrated C# 2008(Page 373) that the int variable y is inside the scope of del2 definition. Then why these errors.

    Read the article

  • C# XP Sound QuickFix

    - by ikurtz
    I have this: ThreadPool.QueueUserWorkItem(new WaitCallback(FireAttackProc), fireResult); and FireAttackProc: private void FireAttackProc(Object stateInfo) { // Process Attack/Fire (local) lock (_procLock) { // build status message String status = "(Away vs. Home)"; // get Fire Result state info FireResult fireResult = (FireResult)stateInfo; // update home grid with attack information GameModel.HomeCellStatusSet(fireResult.FireGridLocation, Cell.cellState.Lock); this.Invoke(new Action(delegate() { RefreshHomeGrid(); })); status = status + "(Attack Coordinate: (" + GameModel.alphaCoords(fireResult.FireGridLocation.Column) + "," + fireResult.FireGridLocation.Row + "))(Result: "; // play audio data if true if (audio) { String Letters; Stream stream; SoundPlayer player; Letters = GameModel.alphaCoords(fireResult.FireGridLocation.Column); stream = Properties.Resources.ResourceManager.GetStream("_" + Letters); player = new System.Media.SoundPlayer(stream); player.PlaySync(); Letters = fireResult.FireGridLocation.Row.ToString(); stream = Properties.Resources.ResourceManager.GetStream("__" + Letters); player = new System.Media.SoundPlayer(stream); player.PlaySync(); stream.Dispose(); player.Dispose(); } if (audio) { SoundPlayer fire = new SoundPlayer(Properties.Resources.fire); fire.PlaySync(); fire.Dispose(); } // deal with hit/miss switch (fireResult.Hit) { case true: this.Invoke(new Action(delegate() { GameModel.HomeCellStatusSet(fireResult.FireGridLocation, Cell.cellState.Hit); status = status + "(Hit)"; })); if (audio) { SoundPlayer hit = new SoundPlayer(Properties.Resources.firehit); hit.PlaySync(); hit.Dispose(); } break; case false: this.Invoke(new Action(delegate() { GameModel.HomeCellStatusSet(fireResult.FireGridLocation, Cell.cellState.Miss); status = status + "(Miss)"; })); GameModel.PlayerNextTurn = NietzscheBattleshipsGameModel.GamePlayers.Home; if (audio) { SoundPlayer miss = new SoundPlayer(Properties.Resources.firemiss); miss.PlaySync(); miss.Dispose(); } break; } // refresh home grid with updated data this.Invoke(new Action(delegate() { RefreshHomeGrid(); })); GameToolStripStatusLabel.Text = status + ")"; // deal with ship destroyed if (fireResult.ShipDestroyed) { status = status + "(Destroyed: " + GameModel.getShipDescription(fireResult.DestroyedShipType) + ")"; if (audio) { Stream stream; SoundPlayer player; stream = Properties.Resources.ResourceManager.GetStream("_home"); player = new System.Media.SoundPlayer(stream); player.PlaySync(); player.Dispose(); stream.Dispose(); string ShipID = fireResult.DestroyedShipType.ToString(); stream = Properties.Resources.ResourceManager.GetStream("_" + ShipID); player = new System.Media.SoundPlayer(stream); player.PlaySync(); player.Dispose(); stream.Dispose(); stream = Properties.Resources.ResourceManager.GetStream("_destroyed"); player = new System.Media.SoundPlayer(stream); player.PlaySync(); player.Dispose(); stream.Dispose(); } } // deal with win condition if (fireResult.Win) { if (audio) { Stream stream; SoundPlayer player; stream = Properties.Resources.ResourceManager.GetStream("_home"); player = new System.Media.SoundPlayer(stream); player.PlaySync(); player.Dispose(); stream = Properties.Resources.ResourceManager.GetStream("_loses"); player = new System.Media.SoundPlayer(stream); player.PlaySync(); player.Dispose(); } GameModel.gameContracts = new GameContracts(); } // update status message if (fireResult.Hit) { if (!fireResult.Win) { status = status + "(Turn: Away)"; LockGUIControls(); } } // deal with turn logic if (GameModel.PlayerNextTurn == NietzscheBattleshipsGameModel.GamePlayers.Home) { this.Invoke(new Action(delegate() { if (!fireResult.Win) { status = status + "(Turn: Home)"; AwayTableLayoutPanel.Enabled = true; } })); } // deal with win condition if (fireResult.Win) { this.Invoke(new Action(delegate() { status = status + "(Game: Home Loses)"; CancelToolStripMenuItem.Enabled = false; NewToolStripMenuItem.Enabled = true; LockGUIControls(); })); } // display completed status message GameToolStripStatusLabel.Text = status + ")"; } } The issue is this: Under Vista/win7 the sound clips in the FireAttackProc plays. But under XP the logic contained within FireAttackProc gets executed but none of the sound clips play. Is there a quick solution to this so the sound will play under XP? I ask for a quick solution because i am happy being able to execute fully in Vista/Win7 but would be great if there was a quick solution so it would be XP compitable also. Thank you.

    Read the article

  • How to conform to UITabBarControllerDelegate

    - by 4thSpace
    I have a tabbar based application and do the following to get a reference to the application delegate: MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; Which then gives this warning: warning: type 'id <UIApplicationDelegate>' does not conform to the 'UITabBarControllerDelegate' My application delegate header looks like this: #import <UIKit/UIKit.h> @interface MyAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> { UIWindow *window; UITabBarController *tabBarController; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UITabBarController *tabBarController; @end The only methods in the .m file are applicationDidFinishLaunching and dealloc. What else do I need to conform to the protocol?

    Read the article

  • Building a Universal iPad App - Where is the device recognition code?

    - by JustinXXVII
    I noticed that when I create a new project in XCode for a Universal iPad/iPhone application, the template comes with two separate App Delegate files, one for each device. I can't seem to locate the place in code where it tries to decide which app delegate to use. I have an existing iPhone project I'd like to port to iPad. My thinking was that if I went ahead and designed the iPad project, I could just import my iPhone classes and nibs, and then use the App Delegate and UIDevice to decide which MainWindow.xib to load. The process went like this: Create an iPad project coded as a split-view create brand new classes and nibs for the iPad import iPhone classes and nibs Change build/target settings in accordance with Universal Apps Use [[UIDevice currentDevice] model] in the AppDelegate to decide which MainWindow to load Will this work, or does the app just automatically know which device it's being deployed on? Thanks for any insight you can offer.

    Read the article

  • NSFetchedResultsControllerDelegate in a second view controller (not firing?)

    - by MTBPatriot
    I am running into an issue similar to the one described here: http://stackoverflow.com/questions/1319940/nsfetchedresultscontrollerdelegate-not-firing (the delegate for my NSFetchedResultsControllerDelegate are not being called on my second view controller) I can't seem to get the proposed solutions to work. I have a main view that loads information from Core Data just fine, but when it pushes a separate controller (and passes the managed object to it), the delegate methods won't fire. I've read about 'mergeChangesFromContextDidSaveNotification' but I don't understand how to synchronize the two manage objects and/or get the delegate methods to be called. Any help would be greatly appreciated. Thank you, Mike

    Read the article

  • NSOutlineView not refreshing when objects added to managed object context from NSOperations

    - by John Gallagher
    Background Cocoa app using core data Two processes - daemon and a main UI Daemon constantly writing to a data store UI process reads from same data store NSOutlineView in UI is bound to an NSTreeController which is bound to Application with key path of delegate.interpretedMOC What I want When the UI is activated, the outline view should update with the latest data inserted by the daemon. The Problem Main Thread Approach I fetch all the entities I'm interested in, then iterate over them, doing refreshObject:mergeChanges:YES. This works OK - the items get refreshed correctly. However, this is all running on the main thread, so the UI locks up for 10-20 seconds whilst it refreshes. Fine, so let's move these refreshes to NSOperations that run in the background instead. NSOperation Multithreaded Approach As soon as I move the refreshObject:mergeChanges: call into an NSOperation, the refresh no longer works. When I add logging messages, it's clear that the new objects are loaded in by the NSOperation subclass and refreshed. Not only that, but they are What I've tried I've messed around with this for 2 days solid and tried everything I can think of. Passing objectIDs to the NSOperation to refresh instead of an entity name. Resetting the interpretedMOC at various points - after the data refresh and before the outline view reload. I'd subclassed NSOutlineView. I discarded my subclass and set the view back to being an instance of NSOutlineView, just in case there was any funny goings on here. Added a rearrangeObjects call to the NSTreeController before reloading the NSOutlineView data. Made sure I had set the staleness interval to 0 on all managed object contexts I was using. I've got a feeling this problem is somehow related to caching core data objects in memory. But I've totally exhausted all my ideas on how I get this to work. I'd be eternally grateful of any ideas anyone else has. Code Main Thread Approach // In App Delegate -(void)applicationDidBecomeActive:(NSNotification *)notification { // Delay to allow time for the daemon to save [self performSelector:@selector(refreshTrainingEntriesAndGroups) withObject:nil afterDelay:3]; } -(void)refreshTrainingEntriesAndGroups { NSSet *allTrainingGroups = [[[NSApp delegate] interpretedMOC] fetchAllObjectsForEntityName:kTrainingGroup]; for(JGTrainingGroup *thisTrainingGroup in allTrainingGroups) [interpretedMOC refreshObject:thisTrainingGroup mergeChanges:YES]; NSError *saveError = nil; [interpretedMOC save:&saveError]; [windowController performSelectorOnMainThread:@selector(refreshTrainingView) withObject:nil waitUntilDone:YES]; } // In window controller class -(void)refreshTrainingView { [trainingViewTreeController rearrangeObjects]; // Didn't really expect this to have any effect. And it didn't. [trainingView reloadData]; } NSOperation Multithreaded Approach // In App Delegate -(void)refreshTrainingEntriesAndGroups { JGRefreshEntityOperation *trainingGroupRefresh = [[JGRefreshEntityOperation alloc] initWithEntityName:kTrainingGroup]; NSOperationQueue *refreshQueue = [[NSOperationQueue alloc] init]; [refreshQueue setMaxConcurrentOperationCount:1]; [refreshQueue addOperation:trainingGroupRefresh]; while ([[refreshQueue operations] count] > 0) { [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]]; [windowController performSelectorOnMainThread:@selector(refreshTrainingView) withObject:nil waitUntilDone:YES]; } // JGRefreshEntityOperation.m @implementation JGRefreshEntityOperation @synthesize started; @synthesize executing; @synthesize paused; @synthesize finished; -(void)main { [self startOperation]; NSSet *allEntities = [imoc fetchAllObjectsForEntityName:entityName]; for(id thisEntity in allEntities) [imoc refreshObject:thisEntity mergeChanges:YES]; [self finishOperation]; } -(void)startOperation { [self willChangeValueForKey:@"isExecuting"]; [self willChangeValueForKey:@"isStarted"]; [self setStarted:YES]; [self setExecuting:YES]; [self didChangeValueForKey:@"isExecuting"]; [self didChangeValueForKey:@"isStarted"]; imoc = [[NSManagedObjectContext alloc] init]; [imoc setStalenessInterval:0]; [imoc setUndoManager:nil]; [imoc setPersistentStoreCoordinator:[[NSApp delegate] interpretedPSC]]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mergeChanges:) name:NSManagedObjectContextDidSaveNotification object:imoc]; } -(void)finishOperation { saveError = nil; [imoc save:&saveError]; if (saveError) { NSLog(@"Error saving. %@", saveError); } imoc = nil; [self willChangeValueForKey:@"isExecuting"]; [self willChangeValueForKey:@"isFinished"]; [self setExecuting:NO]; [self setFinished:YES]; [self didChangeValueForKey:@"isExecuting"]; [self didChangeValueForKey:@"isFinished"]; } -(void)mergeChanges:(NSNotification *)notification { NSManagedObjectContext *mainContext = [[NSApp delegate] interpretedMOC]; [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:YES]; } -(id)initWithEntityName:(NSString *)entityName_ { [super init]; [self setStarted:false]; [self setExecuting:false]; [self setPaused:false]; [self setFinished:false]; [NSThread setThreadPriority:0.0]; entityName = entityName_; return self; } @end // JGRefreshEntityOperation.h @interface JGRefreshEntityOperation : NSOperation { NSString *entityName; NSManagedObjectContext *imoc; NSError *saveError; BOOL started; BOOL executing; BOOL paused; BOOL finished; } @property(readwrite, getter=isStarted) BOOL started; @property(readwrite, getter=isPaused) BOOL paused; @property(readwrite, getter=isExecuting) BOOL executing; @property(readwrite, getter=isFinished) BOOL finished; -(void)startOperation; -(void)finishOperation; -(id)initWithEntityName:(NSString *)entityName_; -(void)mergeChanges:(NSNotification *)notification; @end

    Read the article

  • Form gets disposed somehow

    - by mnn
    I have a client-server application, in which I use classic Sockets and threads for receiving/sending data and listening for clients. The application works fine, but after some random time I get the ObjectDisposedException: System.ObjectDisposedException: Cannot access a disposed object. Object name: 'MainForm'. at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous) at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args) at System.Windows.Forms.Control.Invoke(Delegate method) That code is called from client Socket thread and I use Invoke() method to run the code on UI thread. I'm sure that I don't manually dispose the form nor using Close() (form is closed by user clicking Close button), so I don't know what could cause its disposing.

    Read the article

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