Search Results

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

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

  • Mocking HttpContext with JustMock

    - by mehfuzh
    In post , i will show a test code that will mock the various elements needed to complete a HTTP page request and  assert the expected page cycle steps. To begin, i have a simple enumeration that has my predefined page steps: public enum PageStep {     PreInit,     Load,     PreRender,     UnLoad } Once doing so, i  first created the page object [not mocking]. Page page = new Page(); Here, our target is to fire up the page process though ProcessRequest call, now if we take a look inside method though reflector, we will find calls stack like : ProcessRequest –> ProcessRequestWithNoAssert –> SetInstrinsics –> Finallly ProcessRequest. Inside SetIntrinsics , where it requires calls from HttpRequest, HttpResponse and HttpBrowserCababilities. With this , we can easily know what are classes / calls  we need to mock in order to get though the expected call. Accordingly, for  HttpBrowserCapabilities our required test code will look like: Mock.Arrange(() => browser.PreferredRenderingMime).Returns("text/html"); Mock.Arrange(() => browser.PreferredResponseEncoding).Returns("UTF-8"); Mock.Arrange(() => browser.PreferredRequestEncoding).Returns("UTF-8"); Now, HttpBrowserCapabilities is get though [Instance]HttpRequest.Browser. Therefore, we create the HttpRequest mock: var request = Mock.Create<HttpRequest>(); Then , add the required get call : Mock.Arrange(() => request.Browser).Returns(browser); As, [instance]Browser.PerferrredResponseEncoding and [instance]Browser.PreferredResponseEncoding  are also set to the request object and to make that they are set properly, we can add the following lines as well [not required though]. bool requestContentEncodingSet = false; Mock.ArrangeSet(() => request.ContentEncoding = Encoding.GetEncoding("UTF-8")).DoInstead(() =>  requestContentEncodingSet = true); Similarly, for response we can write:  var response = Mock.Create<HttpResponse>();    bool responseContentEncodingSet = false;  Mock.ArrangeSet(() => response.ContentEncoding = Encoding.GetEncoding("UTF-8")).DoInstead(() => responseContentEncodingSet = true); Finally , I created a mock of HttpContext and set the Request and Response properties that will returns the mocked version. var context = Mock.Create<HttpContext>();   Mock.Arrange(() => context.Request).Returns(request); Mock.Arrange(() => context.Response).Returns(response); As, Page internally calls RenderControl method , we just need to replace that with our one and optionally we can check if  invoked properly: bool rendered = false; Mock.Arrange(() => page.RenderControl(Arg.Any<HtmlTextWriter>())).DoInstead(() => rendered = true); That’s  it, the rest of the code is simple,  where  i asserted the page cycle with the PageSteps that i defined earlier: var pageSteps = new Queue<PageStep>();    page.PreInit +=      delegate      {          pageSteps.Enqueue(PageStep.PreInit);      };  page.Load +=      delegate      {          pageSteps.Enqueue(PageStep.Load);      };    page.PreRender +=      delegate      {          pageSteps.Enqueue(PageStep.PreRender);      };    page.Unload +=      delegate      {          pageSteps.Enqueue(PageStep.UnLoad);      };    page.ProcessRequest(context);    Assert.True(requestContentEncodingSet);  Assert.True(responseContentEncodingSet);  Assert.True(rendered);    Assert.Equal(pageSteps.Dequeue(), PageStep.PreInit);  Assert.Equal(pageSteps.Dequeue(), PageStep.Load);  Assert.Equal(pageSteps.Dequeue(), PageStep.PreRender);  Assert.Equal(pageSteps.Dequeue(), PageStep.UnLoad);    Mock.Assert(request);  Mock.Assert(response);   You can get the test class shown in this post here to give a try by yourself with of course JustMock. Enjoy!!

    Read the article

  • Playing with http page cycle using JustMock

    - by mehfuzh
    In this post , I will cover a test code that will mock the various elements needed to complete a HTTP page request and  assert the expected page cycle steps. To begin, i have a simple enumeration that has my predefined page steps: public enum PageStep {     PreInit,     Load,     PreRender,     UnLoad } Once doing so, i  first created the page object [not mocking]. Page page = new Page(); Here, our target is to fire up the page process through ProcessRequest call, now if we take a look inside the method with reflector.net,  the call trace will go like : ProcessRequest –> ProcessRequestWithNoAssert –> SetInstrinsics –> Finallly ProcessRequest. Inside SetInstrinsics ,  it requires calls from HttpRequest, HttpResponse and HttpBrowserCababilities. With this clue at hand, we can easily know the classes / calls  we need to mock in order to get through the expected call. Accordingly, for  HttpBrowserCapabilities our required test code will look like: Mock.Arrange(() => browser.PreferredRenderingMime).Returns("text/html"); Mock.Arrange(() => browser.PreferredResponseEncoding).Returns("UTF-8"); Mock.Arrange(() => browser.PreferredRequestEncoding).Returns("UTF-8"); Now, HttpBrowserCapabilities is get though [Instance]HttpRequest.Browser. Therefore, we create the HttpRequest mock: var request = Mock.Create<HttpRequest>(); Then , add the required get call : Mock.Arrange(() => request.Browser).Returns(browser); As, [instance]Browser.PerferrredResponseEncoding and [instance]Browser.PreferredResponseEncoding  are also set to the request object and to make that they are set properly, we can add the following lines as well [not required though]. bool requestContentEncodingSet = false; Mock.ArrangeSet(() => request.ContentEncoding = Encoding.GetEncoding("UTF-8")).DoInstead(() =>  requestContentEncodingSet = true); Similarly, for response we can write:  var response = Mock.Create<HttpResponse>();    bool responseContentEncodingSet = false;  Mock.ArrangeSet(() => response.ContentEncoding = Encoding.GetEncoding("UTF-8")).DoInstead(() => responseContentEncodingSet = true); Finally , I created a mock of HttpContext and set the Request and Response properties that will returns the mocked version. var context = Mock.Create<HttpContext>();   Mock.Arrange(() => context.Request).Returns(request); Mock.Arrange(() => context.Response).Returns(response); As, Page internally calls RenderControl method , we just need to replace that with our one and optionally we can check if  invoked properly: bool rendered = false; Mock.Arrange(() => page.RenderControl(Arg.Any<HtmlTextWriter>())).DoInstead(() => rendered = true); That’s  it, the rest of the code is simple,  where  i asserted the page cycle with the PageSteps that i defined earlier: var pageSteps = new Queue<PageStep>();   page.PreInit +=      delegate      {          pageSteps.Enqueue(PageStep.PreInit);      }; page.Load +=      delegate      {          pageSteps.Enqueue(PageStep.Load);      };   page.PreRender +=      delegate      {          pageSteps.Enqueue(PageStep.PreRender);      };   page.Unload +=      delegate      {          pageSteps.Enqueue(PageStep.UnLoad);      };   page.ProcessRequest(context);    Assert.True(requestContentEncodingSet);  Assert.True(responseContentEncodingSet);  Assert.True(rendered);    Assert.Equal(pageSteps.Dequeue(), PageStep.PreInit);  Assert.Equal(pageSteps.Dequeue(), PageStep.Load);  Assert.Equal(pageSteps.Dequeue(), PageStep.PreRender);  Assert.Equal(pageSteps.Dequeue(), PageStep.UnLoad);    Mock.Assert(request);  Mock.Assert(response);   You can get the test class shown in this post here to give a try by yourself with of course JustMock :-).   Enjoy!!

    Read the article

  • Clone an Azure VM using Powershell

    - by jamiet
    In a few months time I will, in association with Technitrain, be running a training course entitled Introduction to SQL Server Data Tools. I am currently working on putting together some hands-on lab material for the course delegates and have decided that in order to save time in asking people to install software during the course I am simply going to prepare a virtual machine (VM) containing all the software and lab material for each delegate to use. Given that I am an MSDN subscriber it makes sense to use Windows Azure to host those VMs given that it will be close to, if not completely, free to do so. What I don’t want to do however is separately build a VM for each delegate, I would much rather build one VM and clone it for each delegate. I’ve spent a bit of time figuring out how to do this using Powershell and in this blog post I am sharing a script that will: Prompt for some information (Azure credentials, Azure subscription name, VM name, username & password, etc…) Create a VM on Azure using that information Prompt you to sysprep the VM and image it (this part can’t be done with Powershell so has to be done manually, a link to instructions is provided in the script output) Create three new VMs based on the image Remove those three VMs Simply download the script and execute it within Powershell, assuming you have an Azure account it should take about 20minutes to execute (spinning up VMs and shutting the down isn’t instantaneous). If you experience any issues please do let me know. There are additional notes below. Hope this is useful! @Jamiet  Notes: Obviously there isn’t a lot of point in creating some new VMs and then instantly deleting them. However, this demo script does provide everything you need should you want to do any of these operations in isolation. The names of the three VMs that get created will be suffixed with 001, 002, 003 but you can edit the script to call them whatever you like. The script doesn’t totally clean up after itself. If you specify a service name & storage account name that don’t already exist then it will create them however it won’t remove them when everything is complete. The created image file will also not be deleted. Removing these items can be done by visiting http://manage.windowsazure.com. When creating the image, ensure you use the correct name (the script output tells you what name to use): Here are some screenshots taken from running the script: When the third and final VM gets removed you are asked to confirm via this dialog: Select ‘Yes’

    Read the article

  • A Basic Thread

    - by Joe Mayo
    Most of the programs written are single-threaded, meaning that they run on the main execution thread. For various reasons such as performance, scalability, and/or responsiveness additional threads can be useful. .NET has extensive threading support, from the basic threads introduced in v1.0 to the Task Parallel Library (TPL) introduced in v4.0. To get started with threads, it's helpful to begin with the basics; starting a Thread. Why Do I Care? The scenario I'll use for needing to use a thread is writing to a file.  Sometimes, writing to a file takes a while and you don't want your user interface to lock up until the file write is done. In other words, you want the application to be responsive to the user. How Would I Go About It? The solution is to launch a new thread that performs the file write, allowing the main thread to return to the user right away.  Whenever the file writing thread completes, it will let the user know.  In the meantime, the user is free to interact with the program for other tasks. The following examples demonstrate how to do this. Show Me the Code? The code we'll use to work with threads is in the System.Threading namespace, so you'll need the following using directive at the top of the file: using System.Threading; When you run code on a thread, the code is specified via a method.  Here's the code that will execute on the thread: private static void WriteFile() { Thread.Sleep(1000); Console.WriteLine("File Written."); } The call to Thread.Sleep(1000) delays thread execution. The parameter is specified in milliseconds, and 1000 means that this will cause the program to sleep for approximately 1 second.  This method happens to be static, but that's just part of this example, which you'll see is launched from the static Main method.  A thread could be instance or static.  Notice that the method does not have parameters and does not have a return type. As you know, the way to refer to a method is via a delegate.  There is a delegate named ThreadStart in System.Threading that refers to a method without parameters or return type, shown below: ThreadStart fileWriterHandlerDelegate = new ThreadStart(WriteFile); I'll show you the whole program below, but the ThreadStart instance above goes in the Main method. The thread uses the ThreadStart instance, fileWriterHandlerDelegate, to specify the method to execute on the thread: Thread fileWriter = new Thread(fileWriterHandlerDelegate); As shown above, the argument type for the Thread constructor is the ThreadStart delegate type. The fileWriterHandlerDelegate argument is an instance of the ThreadStart delegate type. This creates an instance of a thread and what code will execute, but the new thread instance, fileWriter, isn't running yet. You have to explicitly start it, like this: fileWriter.Start(); Now, the code in the WriteFile method is executing on a separate thread. Meanwhile, the main thread that started the fileWriter thread continues on it's own.  You have two threads running at the same time. Okay, I'm Starting to Get Glassy Eyed. How Does it All Fit Together? The example below is the whole program, pulling all the previous bits together. It's followed by its output and an explanation. using System; using System.Threading; namespace BasicThread { class Program { static void Main() { ThreadStart fileWriterHandlerDelegate = new ThreadStart(WriteFile); Thread fileWriter = new Thread(fileWriterHandlerDelegate); Console.WriteLine("Starting FileWriter"); fileWriter.Start(); Console.WriteLine("Called FileWriter"); Console.ReadKey(); } private static void WriteFile() { Thread.Sleep(1000); Console.WriteLine("File Written"); } } } And here's the output: Starting FileWriter Called FileWriter File Written So, Why are the Printouts Backwards? The output above corresponds to Console.Writeline statements in the program, with the second and third seemingly reversed. In a single-threaded program, "File Written" would print before "Called FileWriter". However, this is a multi-threaded (2 or more threads) program.  In multi-threading, you can't make any assumptions about when a given thread will run.  In this case, I added the Sleep statement to the WriteFile method to greatly increase the chances that the message from the main thread will print first. Without the Thread.Sleep, you could run this on a system with multiple cores and/or multiple processors and potentially get different results each time. Interesting Tangent but What Should I Get Out of All This? Going back to the main point, launching the WriteFile method on a separate thread made the program more responsive.  The file writing logic ran for a while, but the main thread returned to the user, as demonstrated by the print out of "Called FileWriter".  When the file write finished, it let the user know via another print statement. This was a very efficient use of CPU resources that made for a more pleasant user experience. Joe

    Read the article

  • What are the best practices to use NHiberante sessions in asp.net (mvc/web api) ?

    - by mrt181
    I have the following setup in my project: public class WebApiApplication : System.Web.HttpApplication { public static ISessionFactory SessionFactory { get; private set; } public WebApiApplication() { this.BeginRequest += delegate { var session = SessionFactory.OpenSession(); CurrentSessionContext.Bind(session); }; this.EndRequest += delegate { var session = SessionFactory.GetCurrentSession(); if (session == null) { return; } session = CurrentSessionContext.Unbind(SessionFactory); session.Dispose(); }; } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var assembly = Assembly.GetCallingAssembly(); SessionFactory = new NHibernateHelper(assembly, Server.MapPath("/")).SessionFactory; } } public class PositionsController : ApiController { private readonly ISession session; public PositionsController() { this.session = WebApiApplication.SessionFactory.GetCurrentSession(); } public IEnumerable<Position> Get() { var result = this.session.Query<Position>().Cacheable().ToList(); if (!result.Any()) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); } return result; } public HttpResponseMessage Post(PositionDataTransfer dto) { //TODO: Map dto to model IEnumerable<Position> positions = null; using (var transaction = this.session.BeginTransaction()) { this.session.SaveOrUpdate(positions); try { transaction.Commit(); } catch (StaleObjectStateException) { if (transaction != null && transaction.IsActive) { transaction.Rollback(); } } } var response = this.Request.CreateResponse(HttpStatusCode.Created, dto); response.Headers.Location = new Uri(this.Request.RequestUri.AbsoluteUri + "/" + dto.Name); return response; } public void Put(int id, string value) { //TODO: Implement PUT throw new NotImplementedException(); } public void Delete(int id) { //TODO: Implement DELETE throw new NotImplementedException(); } } I am not sure if this is the recommended way to insert the session into the controller. I was thinking about using DI but i am not sure how to inject the session that is opened and binded in the BeginRequest delegate into the Controllers constructor to get this public PositionsController(ISession session) { this.session = session; } Question: What is the recommended way to use NHiberante sessions in asp.net mvc/web api ?

    Read the article

  • iPhone - archiving array of custom objects

    - by Dylan
    I've been trying for hours and I cannot solve this problem. I'm making an app that saves unfinished Chess Games, so I'm trying to write an array to a file. This is what the array is, if it makes sense: -NSMutableArray savedGames --GameSave a ---NSMutableArray board; ----Piece a, b, c, etc. -----some ints ---NSString whitePlayer, blackPlayer; ---int playerOnTop, turn; --GameSave b ---NSMutableArray board; ----Piece a, b, c, etc. -----some ints ---NSString whitePlayer, blackPlayer; ---int playerOnTop, turn; etc. And these are my NSCoding methods: GameSave.m - (void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:whitePlayer forKey:@"whitePlayer"]; [coder encodeObject:blackPlayer forKey:@"blackPlayer"]; [coder encodeInt:playerOnTop forKey:@"playerOnTop"]; [coder encodeInt:turn forKey:@"turn"]; [coder encodeObject:board forKey:@"board"]; } - (id)initWithCoder:(NSCoder *)coder { self = [[GameSave alloc] init]; if (self != nil) { board = [coder decodeObjectForKey:@"board"]; whitePlayer = [coder decodeObjectForKey:@"whitePlayer"]; blackPlayer = [coder decodeObjectForKey:@"blackPlayer"]; playerOnTop = [coder decodeIntForKey:@"playerOnTop"]; turn = [coder decodeIntForKey:@"turn"]; } return self; } Piece.m - (void)encodeWithCoder:(NSCoder *)coder { [coder encodeInt:color forKey:@"color"]; [coder encodeInt:piece forKey:@"piece"]; [coder encodeInt:row forKey:@"row"]; [coder encodeInt:column forKey:@"column"]; } - (id)initWithCoder:(NSCoder *)coder { self = [[Piece alloc] init]; if (self != nil) { color = [coder decodeIntForKey:@"color"]; piece = [coder decodeIntForKey:@"piece"]; row = [coder decodeIntForKey:@"row"]; column = [coder decodeIntForKey:@"column"]; } return self; } And this is the code that tries to archive and save to file: - (void)saveGame { ChessSaverAppDelegate *delegate = (ChessSaverAppDelegate *) [[UIApplication sharedApplication] delegate]; [[delegate gameSave] setBoard:board]; NSMutableArray *savedGames = [NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]]; if (savedGames == nil) { [NSKeyedArchiver archiveRootObject:[delegate gameSave] toFile:[self dataFilePath]]; } else { [savedGames addObject:[delegate gameSave]]; [NSKeyedArchiver archiveRootObject:savedGames toFile:[self dataFilePath]]; } } - (NSString *)dataFilePath { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; return [documentsDirectory stringByAppendingPathComponent:@"gameSaves.plist"]; } Sorry, here's the problem: After setting some breakpoints, an error is reached after this line from -saveGame: [NSKeyedArchiver archiveRootObject:savedGames toFile:[self dataFilePath]]; And this is what shows up in the console: 2010-05-11 17:04:08.852 ChessSaver[62065:207] *** -[NSCFType encodeWithCoder:]: unrecognized selector sent to instance 0x3d3cd30 2010-05-11 17:04:08.891 ChessSaver[62065:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFType encodeWithCoder:]: unrecognized selector sent to instance 0x3d3cd30' 2010-05-11 17:04:08.908 ChessSaver[62065:207] Stack: ( 32339035, 31077641, 32720955, 32290422, 32143042, 238843, 25827, 238843, 564412, 342037, 238843, 606848, 17686, 2733061, 4646817, 2733061, 3140430, 3149167, 3144379, 2837983, 2746312, 2773089, 41684313, 32123776, 32119880, 41678357, 41678554, 2777007, 9884, 9738 ) If it matters, -saveGame is called from a UIBarButton in a navigation controller. Any help is appreciated, thanks.

    Read the article

  • Why does IHttpAsyncHandler leak memory under load?

    - by Anton
    I have noticed that the .NET IHttpAsyncHandler (and the IHttpHandler, to a lesser degree) leak memory when subjected to concurrent web requests. In my tests, the development web server (Cassini) jumps from 6MB memory to over 100MB, and once the test is finished, none of it is reclaimed. The problem can be reproduced easily. Create a new solution (LeakyHandler) with two projects: An ASP.NET web application (LeakyHandler.WebApp) A Console application (LeakyHandler.ConsoleApp) In LeakyHandler.WebApp: Create a class called TestHandler that implements IHttpAsyncHandler. In the request processing, do a brief Sleep and end the response. Add the HTTP handler to Web.config as test.ashx. In LeakyHandler.ConsoleApp: Generate a large number of HttpWebRequests to test.ashx and execute them asynchronously. As the number of HttpWebRequests (sampleSize) is increased, the memory leak is made more and more apparent. LeakyHandler.WebApp TestHandler.cs namespace LeakyHandler.WebApp { public class TestHandler : IHttpAsyncHandler { #region IHttpAsyncHandler Members private ProcessRequestDelegate Delegate { get; set; } public delegate void ProcessRequestDelegate(HttpContext context); public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { Delegate = ProcessRequest; return Delegate.BeginInvoke(context, cb, extraData); } public void EndProcessRequest(IAsyncResult result) { Delegate.EndInvoke(result); } #endregion #region IHttpHandler Members public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { Thread.Sleep(10); context.Response.End(); } #endregion } } LeakyHandler.WebApp Web.config <?xml version="1.0"?> <configuration> <system.web> <compilation debug="false" /> <httpHandlers> <add verb="POST" path="test.ashx" type="LeakyHandler.WebApp.TestHandler" /> </httpHandlers> </system.web> </configuration> LeakyHandler.ConsoleApp Program.cs namespace LeakyHandler.ConsoleApp { class Program { private static int sampleSize = 10000; private static int startedCount = 0; private static int completedCount = 0; static void Main(string[] args) { Console.WriteLine("Press any key to start."); Console.ReadKey(); string url = "http://localhost:3000/test.ashx"; for (int i = 0; i < sampleSize; i++) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.BeginGetResponse(GetResponseCallback, request); Console.WriteLine("S: " + Interlocked.Increment(ref startedCount)); } Console.ReadKey(); } static void GetResponseCallback(IAsyncResult result) { HttpWebRequest request = (HttpWebRequest)result.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result); try { using (Stream stream = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(stream)) { streamReader.ReadToEnd(); System.Console.WriteLine("C: " + Interlocked.Increment(ref completedCount)); } } response.Close(); } catch (Exception ex) { System.Console.WriteLine("Error processing response: " + ex.Message); } } } }

    Read the article

  • NSUserDefaults loses 3 rows each time it's called

    - by Jeff Decker
    Hello Everyone! Brand new programmer here, so off-topic help/constructive criticism welcome. I am saving a default state (such as "New York") in a UIPickerView which is in a FlipSideView. It certainly saves for the first and second time I check to make sure it's the same state (I am clicking "done" and then "info" repeatedly), but on the third check the picker has moved up three states (to "New Hampshire") and then every time I check the picker progresses three more states. Here's the .h and .m files of the FlipSideViewController: #import <UIKit/UIKit.h> import "Calculator.h" @protocol FlipsideViewControllerDelegate; @interface FlipsideViewController : UIViewController { id delegate; UIPickerView *myPickerView; NSArray *pickerViewArray; } @property (nonatomic, assign) id delegate; @property (nonatomic, retain) UIPickerView *myPickerView; @property (nonatomic, retain) NSArray *pickerViewArray; (IBAction)done; @end @protocol FlipsideViewControllerDelegate - (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller; @end import "FlipsideViewController.h" @implementation FlipsideViewController @synthesize delegate; @synthesize myPickerView, pickerViewArray; -(CGRect)pickerFrameWithSize:(CGSize)size;{ CGRect screenRect = [[UIScreen mainScreen] applicationFrame]; CGRect pickerRect = CGRectMake( 0.0, screenRect.size.height - size.height, size.width, size.height); return pickerRect; } (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor]; [self createPicker]; } -(void)viewWillAppear:(BOOL)animated;{ [super viewWillAppear:NO]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [myPickerView selectRow:[defaults integerForKey:@"pickerRow"] inComponent:0 animated:NO]; } -(void)createPicker;{ pickerViewArray = [[NSArray arrayWithObjects: @"Alabama",@"Alaska", @"Arizona",@"Arkansas",@"California",@"Colorado",@"Connecticut",@"Delaware", @"District of Columbia",@"Florida",@"Georgia",@"Hawaii",@"Idaho",@"Illinois",@"Indiana",@"Iowa", @"Kansas",@"Kentucky",@"Louisiana",@"Maine",@"Maryland",@"Massachusetts",@"Michigan", @"Minnesota",@"Mississippi",@"Missouri",@"Montana",@"Nebraska",@"Nevada",@"New Hampshire",@"New Jersey", @"New Mexico",@"New York",@"North Carolina",@"North Dakota",@"Ohio",@"Oklahoma", @"Oregon",@"Pennsylvania",@"Rhode Island",@"South Carolina",@"South Dakota",@"Tennessee", @"Texas",@"Utah",@"Vermont",@"Virginia",@"Washington",@"West Virginia",@"Wisconsin",@"Wyoming", nil] retain]; myPickerView = [[UIPickerView alloc] initWithFrame:CGRectZero]; CGSize pickerSize = [myPickerView sizeThatFits:CGSizeZero]; myPickerView.frame = [self pickerFrameWithSize:pickerSize]; myPickerView.autoresizingMask = UIViewAutoresizingFlexibleWidth; myPickerView.showsSelectionIndicator = YES; myPickerView.delegate = self; myPickerView.dataSource = self; [self.view addSubview:myPickerView]; } (IBAction)done { [self.delegate flipsideViewControllerDidFinish:self]; } pragma mark - pragma mark UIPickerViewDataSource (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setInteger:row forKey:@"pickerRow"]; [defaults setObject:[pickerViewArray objectAtIndex:row] forKey:@"pickerString"]; return [pickerViewArray objectAtIndex:row]; } (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setInteger:row forKey:@"pickerRow"]; [defaults setObject:[pickerViewArray objectAtIndex:row] forKey:@"pickerString"]; } (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component { return 240.0; } (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component { return 40.0; } (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { return [pickerViewArray count]; } (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 1; } call me mystified! Thanks for any help. Please let me know if I can make myself more clear...

    Read the article

  • Async networking + threading problem

    - by randallmeadows
    I kick off a network request, assuming no login credentials are required to talk to the destination server. If they are required, then I get an authentication challenge, at which point I display a view requesting said credentials from the user. When they are supplied, I restart the network request, using those credentials. That's all fine and dandy, as long as I only do one request at a time. But I'm not, typically. When both requests are kicked off, I get the first challenge, and present the prompt (using -presentModalViewController:). Then the 2nd challenge comes in. And I crash when it tries to display the 2nd prompt. I have the bulk of this wrapped in an @synchronized() block, but this has no effect because these delegate methods are all being called on the same (main) thread. The docs say the delegate methods are called on the same thread in which the connection was started. OK, no problem; I'll just write a method that I run on a background thread using -performSelectorInBackground: NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO]; [connections addObject:connection]; [self performSelectorInBackground:@selector(startConnection:) withObject:connection]; [connection release]; - (void)startConnection:(NSURLConnection *)connection { NSAutoreleasePool *pool = [NSAutoreleasePool new]; [connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [connection start]; [pool drain]; } which should put every network request, and its callbacks, on its own thread, and then my @synchronized() blocks will take effect. The docs for -initWithRequest:... state "Messages to the delegate will be sent on the thread that calls this method. By default, for the connection to work correctly the calling thread’s run loop must be operating in the default run loop mode." Ok, I'm doing that. They also state "If you pass NO [for startImmediately], you must schedule the connection in a run loop before starting it." OK, I'm doing that, too. Furthermore, the docs for NSRunLoop state "Each NSThread object, including the application’s main thread, has an NSRunLoop object automatically created for it as needed. If you need to access the current thread’s run loop, you do so with the class method currentRunLoop." I'm assuming this applies to the background thread created by the call -performSelectorInBackground... (which does appear to be the case, when I execute 'po [NSClassFromString(@"NSRunLoop") currentRunLoop]' in the -startConnection: method). The -startConnection: method is indeed being called. But after kicking off the connection, I now never get any callbacks on it. None of the -connectionDid… delegate methods. (I even tried explicitly starting the thread's run loop, but that made no difference; I've used threads like this before, and I've never had to start the run loop manually before--but I'm now grasping at straws...) I think I've come up with a workaround such that I only handle one request at a time, but it's kludgy and I'd like to do this the Right Way. But, what am I missing here? Thanks! randy

    Read the article

  • Lambda expressions as CLR (.NET) delegates / event handlers in Visual C++ 2010

    - by absence
    Is it possible to use the new lambda expressions in Visual C++ 2010 as CLR event handlers? I've tried the following code: SomeEvent += gcnew EventHandler( [] (Object^ sender, EventArgs^ e) { // code here } ); It results in the following error message: error C3364: 'System::EventHandler' : invalid argument for delegate constructor; delegate target needs to be a pointer to a member function Am I attempting the impossible, or is simply my syntax wrong?

    Read the article

  • My UITabBarController's didSelectViewController method is not getting called?

    - by mobibob
    Here is my code stub for my app-delegate.m -- it never gets called. - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController { NSLog(@"%s", __FUNCTION__); } It is defined in this app-delegate.h @interface OrioleAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> { UIWindow *window; UITabBarController *tabBarController; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UITabBarController *tabBarController; @end

    Read the article

  • UISplitView: how to access instance?

    - by chpwn
    I have a navigation controller in my left portion of my split view, and in the right portion. But sometimes, for example when an item is tapped, my left side must manually set the view controller on the right side. Where is the best place to store the split view controller instance? Pass it around to each view controller on the left side, like I do with the navigation controller? Store it in my App Delegate and then access it via a property with [[UIApplication sharedApplication] delegate].splitView?

    Read the article

  • Memory management for NSURLConnection

    - by eman
    Sorry if this has been asked before, but I'm wondering what the best memory management practice is for NSURLConnection. Apple's sample code uses -[NSURLConnection initWithRequest:delegate:] in one method and then releases in connection:didFailWithError: or connectionDidFinishLoading:, but this spits out a bunch of analyzer warnings and seems sort of dangerous (what if neither of those methods is called?). I've been autoreleasing (using +[NSURLConnection connectionWithRequest:delegate:]), which seems cleaner, but I'm wondering--in this case, is it at ever possible for the NSURLConnection to be released before the connection has closed?

    Read the article

  • iPhone simulator and applicationWillTerminate()

    - by firstresponder
    When my app is run in the iPhone simulator, the delegate method - (void)applicationWillTerminate:(UIApplication *)application is only called the first time I hit the iPhone simulator's home button. After the home button is pressed and the app is launched again, hitting the home button does not call the delegate method. What is going on here? Am I misunderstanding something fundamental?

    Read the article

  • UIWebView leak? Can someone confirm?

    - by Shaggy Frog
    I was leak-testing my current project and I'm stumped. I've been browsing like crazy and tried everything except chicken sacrifice. I just created a tiny toy project app from scratch and I can duplicate the leak in there. So either UIWebView has a leak or I'm doing something really silly. Essentially, it boils down to a loadRequest: call to a UIWebView object, given an URLRequest built from an NSURL which references a file URL, for a file in the app bundle, which lives inside a folder that Xcode is including by reference. Phew. The leak is intermittent but still happens ~75% of the time (in about 20 tests it happened about 15 times). It only happens on the device -- this does not leak in the simulator. I am testing targeting both iPhone OS 3.1.2 and 3.1.3, on an original (1st Gen) iPod Touch that is using iPhone OS 3.1.3. To reproduce, just create a project from scratch. Add a UIWebView to the RootViewController's .xib, hook it up via IBOutlet. In the Finder, create a folder named "html" inside your project's folder. Inside that folder, create a file named "dummy.html" that has the word "Test" in it. (Does not need to be valid HTML.) Then add the html folder to your project in Xcode by choosing "Create Folder References for any added folders" Add the following to viewDidLoad NSString* resourcePath = [[NSBundle mainBundle] resourcePath]; NSString* filePath = [[resourcePath stringByAppendingPathComponent:@"html"] stringByAppendingPathComponent:@"dummy.html"]; NSURL* url = [[NSURL alloc] initFileURLWithPath:filePath]; NSURLRequest* request = [NSURLRequest requestWithURL:url]; // <-- this creates the leak! [browserView loadRequest:request]; [url release]; I've tried everything from setting delegate for the UIWebView and implementing UIWebViewDelegate, to not setting a delegate in IB, to not setting a delegate in IB and explicitly setting the web view's delegate property to nil, to using alloc/init instead of getting autoreleased NSURLRequests (and/or NSURLs)... I tried the answer to a similar question (setting the shared URL cache to empty) and that did not help. Can anyone help?

    Read the article

  • Putting two picker control on single UIView.

    - by Amit Jain
    Hi I am having to picker controls on a single view with two outlets for each. Now when I select any of them same delegate methods are get called. How should we distinguish between which picker control has called the delegate ? Another question is can we change the frame size of the pickers to fit in one view? Thanks Amit

    Read the article

  • Problem dismissing multiple modal view controllers

    - by Sheehan Alam
    I am having trouble getting my modal view controllers to display properly. I have a parent view controller that is the delegate for modal view A. In modal view A I am presenting modal view B, and having the delegate dimiss modal view A. When modal view B appears it seems to display but the screen dims, and the UI locks up, but the app doesn't crash. I set animation settings to NO and I am still getting the same issue.

    Read the article

  • I get EXC_BAD_ACCESS when MaxConcurrentOperationCount > 1

    - by kudorgyozo
    Hello i am using NSOperationQueue to download images in the background. I have created a custom NSOperation to download the images. I put the images in table cells. The problem is if I do [operationQueue setMaxConcurrentOperationCount: 10] and i scroll down several cells the program crashes with EXC_BAD_ACCESS. Every time it crashes at the same place in the table. There are 3 cells one after the other which are for the same company and have the same logo so basically it should download the images 3 times. Every other time it works fine. - (void) main { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSURL *url = [[NSURL alloc] initWithString:self.imageURL]; debugLog(@"downloading image: %@", self.imageURL); //NSError *error = nil; NSData *data = [[NSData alloc] initWithContentsOfURL:url]; [url release]; UIImage *image = [[UIImage alloc] initWithData:data]; [data release]; if (image) { if (image.size.width != ICONWIDTH && image.size.height != ICONHEIGHT) { UIImage *resizedImage; CGSize itemSize = CGSizeMake(ICONWIDTH, ICONHEIGHT); UIGraphicsBeginImageContext(itemSize); CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height); [image drawInRect:imageRect]; resizedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); self.theImage = resizedImage; } else { self.theImage = image; } [image release]; } [delegate didFinishDownloadingImage: self]; [pool release]; } This is how i handle downloading the images. If i comment out [delegate didFinishDownloadingImage: self]; in the function above it doesn't crash but of course it is useless. -(void) didFinishDownloadingImage:(ImageDownloadOperation *) imageDownloader { [self performSelectorOnMainThread: @selector(handleDidFinishDownloadingImage:) withObject: imageDownloader waitUntilDone: FALSE]; } -(void) handleDidFinishDownloadingImage:(ImageDownloadOperation *)imageDownloadOperation { NSArray *visiblePaths = [self.myTableView indexPathsForVisibleRows]; CompanyImgDownloaderState *stateObject = (CompanyImgDownloaderState *)[imageDownloadOperation stateObject]; if ([visiblePaths containsObject: stateObject.indexPath]) { //debugLog(@"didFinishDownloadingImage %@ %@", imageDownloader.theImage); UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath: stateObject.indexPath]; UIImageView *imageView = (UIImageView *)[cell viewWithTag: 1]; if (imageDownloadOperation.theImage) { imageView.image = imageDownloadOperation.theImage; stateObject.company.icon = imageDownloadOperation.theImage; } else { imageView.image = [(TestWebServiceAppDelegate *)[[UIApplication sharedApplication] delegate] getCylexIcon]; stateObject.company.icon = [(TestWebServiceAppDelegate *)[[UIApplication sharedApplication] delegate] getCylexIcon]; } } }

    Read the article

  • Overload Anonymous Functions

    - by Nissan Fan
    Still wrapping my head around Delegates and I'm curious: Is it possible to overload anonymous functions? Such that: delegate void Output(string x, int y); Supports: Output show = (x, y) => Console.WriteLine("{0}: {1}", x.ToString(), y.ToString()); And: delegate void Output(string x, string y); Allowing: show( "ABC", "EFG" ); And: show( "ABC", 123 );

    Read the article

  • UIScrollView strange zoom behavior when content is a UIView subclass

    - by sigsegv
    Hi, I'm experiencing the following: I created a UIView subclass with a CATiledLayer as backing layer by overriding the layerClass method. The layer properties (delegate, tileSize, etc) are set in the initWithFrame: method of the subclass. +(Class)layerClass { return [CATiledLayer class]; } -(id)initWithFrame:(CGRect)frame { if(self = [super initWithFrame:frame]) { renderer = [[MFPDFRenderer alloc]init]; tiledLayer = (CATiledLayer *)[self layer]; [tiledLayer setFrame:frame]; [tiledLayer setLevelsOfDetail:2]; [tiledLayer setLevelsOfDetailBias:3]; [tiledLayer setTileSize:CGSizeMake(512, 512)]; [tiledLayer setDelegate:renderer]; } return self; } Then I add an instance of said class as the content of an UIScrollView and set UIScrollView properties and implement the required delegate's methods. Everything works fine but when zooming the scroll view keep repositioning itself on its center. It's hardly noticeable when zooming in the center of the content, but unbearable otherwise. The same scroll view works fine when I use as (zoomable) content any other view such as an UIImageView or even a normal UIView with a CATiledLayer with the same properties and delegate of the subclass implementation as sublayer. When I check layer bounds and frame in the drawLayer:inContext: method of the delegate I get the following result as the zoom increase UIView with CATiledLayer as sublayer: 2010-04-03 21:05:33.499 Renderer[89293:4903] Layer: (0.000, 0.000) 320.000 x 460.000 2010-04-03 21:05:33.500 Renderer[89293:4903] Bounds: (0.000, 0.000) 320.000 x 460.000 2010-04-03 21:05:33.529 Renderer[89293:4903] Layer: (0.000, 0.000) 320.000 x 460.000 2010-04-03 21:05:33.534 Renderer[89293:4903] Bounds: (0.000, 0.000) 320.000 x 460.000 Custom subclass: 2010-04-03 21:04:15.969 Renderer[88957:4903] Layer: (0.000, 0.000) 657.910 x 945.746 2010-04-03 21:04:15.970 Renderer[88957:4903] Bounds: (0.000, 0.000) 320.000 x 460.000 2010-04-03 21:04:17.428 Renderer[88957:4903] Layer: (-0.000, 0.000) 766.964 x 1102.510 2010-04-03 21:04:17.429 Renderer[88957:4903] Bounds: (0.000, 0.000) 320.000 x 460.000 [...] 2010-04-03 21:19:10.388 Renderer[92573:4903] Layer: (-0.000, 0.000) 905.680 x 1301.916 2010-04-03 21:19:10.388 Renderer[92573:4903] Bounds: (0.000, 0.000) 320.000 x 460.000 I suppose that's the culprit or at least another symptom. I can add that I get the same erratic behavior if my subclass is built over a standard CALayer with the same renderer. Any suggestion will be appreciated!

    Read the article

  • MapKit/Location Manager crashes app when unloading view

    - by AppGolfer
    I has a bug where my application crashed "EXC_BAD_ACCESS" when I hit the back key on my navigation bar and the view unloaded that had a MapKit (mapView) and used the Location Manager. Tried for days to fix the bug and finally came up with a fix for anyone that comes across this problem: Add this code to your dealloc (void)dealloc { mapView.delegate = nil; locationManager.delegate = nil; [mapView release]; [locationManager release];

    Read the article

  • willSendRequest redirectResponse doesn't work in iPhone SDK2.0

    - by WholeIphone
    I use the delegate method connection:willSendRequest:redirectResponse: in SDK 2.2, the code like below: - (NSURLRequest *)connection:(NSURLConnection *)con willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse { if(redirectResponse) { if(!self.autoRedirect) { NSLog(@"response will redirect"); request = nil; } } return request; if the request is returned to nil ,it seems it hangs up here, and delegate didReceiveData will not get called. but it works in SDK 3. Any suggestions about this?

    Read the article

  • View hide problem

    - by Ajeet Kumar Yadav
    Hello, I am using a Xib (tab bar controller with navigation bar). when i use navigation bar in app delegate then Xib slides little bit bellow.Actually i want a navigation bar on enter page so it is compulsory to define navigation bar in app delegate. Please help me how i solve this problem.

    Read the article

  • What kind of events should be created for a CRUD application?

    - by Mohit Deshpande
    I have an application that is centered around a database (ORM is LINQ-SQL) that has a table called Assignment. I am using the repository pattern to manipulate the database. My application is basically going to perform CRUD operations. I am new to delegates and events and I am asking you what events I should create (like maybe AssignmentCreating, AssignmentCreated) and what kind of delegate to use (like maybe a custom delegate or just an EventHandler)?

    Read the article

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