Search Results

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

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

  • iphone OCMockObject and unit-testing a class that inherits from NSURLConnection

    - by Justin Galzic
    I want to unit test the custom init method of a class that inherits from NSURLConnection -- how would I do this if the init of my testable class invokes NSURLConnection's initWithRequest? I'm using OCMock and normally, I can mock objects that are contained within my test class. For this inheritance scenario, what's the best approach to do this? - (void)testInit { id urlRequest = [OCMockObject mockForClass:[NSURLRequest class]]; MyURLConnectionWrapper *conn = [[MyURLConnectionWrapper alloc] initWithRequest:urlRequest delegate:self someData:extraneousData]; } My class is implemented like this: @interface MyURLConnectionWrapper : NSURLConnection { } - (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate someData:(NSString *)fooData @end @implementation MyURLConnectionWrapper - (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate someData:(NSString *)fooData { if (self = [super initWithRequest:request delegate:delegate]) { // do some additional work here } return self; } Here's the error I get: OCMockObject[NSURLRequest]: unexpected method invoked: _CFURLRequest

    Read the article

  • how do i add two delegates to a ui element at run time?

    - by Michael Xu
    Hi everyone, im trying to implement some behaviors when a mapview element scrolls... by coding a delegate for the scrollview inside of a mapview. so, right now, i got a pointer to the scroll view used by the map view in my code. however, i wish to set the delegate of this scroll view inside the map view, but the issue is that the mapview already sets up a default delegate for this scroll view inside the map view. can i make my delegate implement all of the messages of the protocol, explicitly sending them to the mapview's default delegate while also implementing my own behaviors? how else can i go about adding my own delegate behavior, to an already existing default delegate....? thanks everyone, michael

    Read the article

  • Lambda&rsquo;s for .NET made easy&hellip;

    - by mbcrump
    The purpose of my blog is to explain things for a beginner to intermediate c# programmer. I’ve seen several blog post that use lambda expressions always assuming the audience is familiar with them. The purpose of this post is to make them simple and easily understood. Let’s begin with a definition. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. So anonymous function… delegates or expression tree types? I don’t get it??? Confused yet?   Lets break this into a few definitions and jump right into the code. anonymous function – is an "inline" statement or expression that can be used wherever a delegate type is expected. delegate - is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value. Expression trees - represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.   Don’t worry if this still sounds confusing, lets jump right into the code with a simple 3 line program. We are going to use a Function Delegate (all you need to remember is that this delegate returns a value.) Lambda expressions are used most commonly with the Func and Action delegates, so you will see an example of both of these. Lambda Expression 3 lines. using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace ConsoleApplication7 {     class Program     {          static void Main(string[] args)         {             Func<int, int> myfunc = x => x *x;             Console.WriteLine(myfunc(6).ToString());             Console.ReadLine();         }       } } Is equivalent to Old way of doing it. using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace ConsoleApplication7 {     class Program     {          static void Main(string[] args)         {               Console.WriteLine(myFunc(6).ToString());             Console.ReadLine();         }            static int myFunc(int x)          {              return x * x;            }       } } In the example, there is a single parameter, x, and the expression is x*x. I’m going to stop here to make sure you are still with me. A lambda expression is an unnamed method written in place of a delegate instance. In other words, the compiler converts the lambda expression to either a : A delegate instance An expression tree All lambda have the following form: (parameters) => expression or statement block Now look back to the ones we have created. It should start to sink in. Don’t get stuck on the => form, use it as an identifier of a lambda. A Lamba expression can also be written in the following form: Lambda Expression. using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace ConsoleApplication7 {     class Program     {          static void Main(string[] args)         {             Func<int, int> myFunc = x =>             {                 return x * x;             };               Console.WriteLine(myFunc(6).ToString());             Console.ReadLine();         }       } } This form may be easier to read but consumes more space. Lets try an Action delegate – this delegate does not return a value. Action Delegate example. using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace ConsoleApplication7 {     class Program     {          static void Main(string[] args)         {             Action<string> myAction = (string x) => { Console.WriteLine(x); };             myAction("michael has made this so easy");                                   Console.ReadLine();         }       } } Lambdas can also capture outer variables (such as the example below) A lambda expression can reference the local variables and parameters of the method in which it’s defined. Outer variables referenced by a lambda expression are called captured variables. Capturing Outer Variables using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace ConsoleApplication7 {     class Program     {          static void Main(string[] args)         {             string mike = "Michael";             Action<string> myAction = (string x) => {                 Console.WriteLine("{0}{1}", mike, x);          };             myAction(" has made this so easy");                                   Console.ReadLine();         }       } } Lamba’s can also with a strongly typed list to loop through a collection.   Used w a strongly typed list. using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace ConsoleApplication7 {     class Program     {          static void Main(string[] args)         {             List<string> list = new List<string>() { "1", "2", "3", "4" };             list.ForEach(s => Console.WriteLine(s));             Console.ReadLine();         }       } } Outputs: 1 2 3 4 I think this will get you started with Lambda’s, as always consult the MSDN documentation for more information. Still confused? Hopefully you are not.

    Read the article

  • Random Access Violation Exception in WPF Application

    - by PT1984
    Hi, I am facing weird problem while running regression tests on my WPF Application. I am getting AccessViolationException with different stacktraces each time. First : Message :Attempted to read or write protected memory. This is often an indication that other memory is corrupt. StackTrace : at MS.Win32.PresentationCore.UnsafeNativeMethods.MILUnknown.Release(IntPtr pIUnkown) at MS.Win32.PresentationCore.UnsafeNativeMethods.MILUnknown.ReleaseInterface(IntPtr& ptr) at System.Windows.Media.SafeMILHandle.ReleaseHandle() at System.Runtime.InteropServices.SafeHandle.InternalFinalize() at System.Runtime.InteropServices.SafeHandle.Dispose(Boolean disposing) at System.Runtime.InteropServices.SafeHandle.Finalize() Source :PresentationCore Type : System.AccessViolationException. Second : Message :Attempted to read or write protected memory. This is often an indication that other memory is corrupt. StackTrace : at MS.Win32.PresentationCore.UnsafeNativeMethods.IMILBitmapEffect.GetOutput(SafeHandle THIS_PTR, UInt32 uiIndex, SafeMILHandle pContext, BitmapSourceSafeMILHandle& ppBitmapSource) at System.Windows.Media.Effects.BitmapEffect.GetOutput(SafeHandle unmanagedEffect, Int32 index, BitmapEffectRenderContext context) at System.Windows.Media.Effects.BitmapEffect.GetOutput(BitmapEffectInput input) at System.Windows.Media.Effects.BitmapEffectState.GetEffectOutput(Visual visual, RenderTargetBitmap& renderBitmap, Matrix worldTransform, Rect windowClip, Matrix& finalTransform) at System.Windows.Media.Effects.BitmapEffectVisualState.RenderBitmapEffect(Visual visual, Channel channel) at System.Windows.Media.Effects.BitmapEffectContent.ExecuteRealizationsUpdate() at System.Windows.Media.RealizationContext.RealizationUpdateSchedule.Execute() at System.Windows.Media.MediaContext.Render(ICompositionTarget resizedCompositionTarget) at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget) at System.Windows.Media.MediaContext.AnimatedRenderMessageHandler(Object resizedCompositionTarget) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.Run() at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run() at Main() Source :PresentationCore Type :System.AccessViolationException In Application Event Log I found following entries : Dispatcher processing has been suspended, but messages are still being processed. Faulting application **.exe, version 1.0.0.*, stamp 4c08d288, faulting module wpfgfx_v0300.dll, version 3.0.6920.1427, stamp 488f3056, debug? 0, fault address 0x0012ec36. My Application uses Dispatcher from another thread, to change the values of the controls , enable - disable those, change visibility etc., the thred is run multiple times in a second. Please let me know if anybody has faced this problem? Thanks in advance, -Prasad

    Read the article

  • xamlparser error after clickonce deployment.Application crashing after installation

    - by black sensei
    Hello Good People, I've built an WPF application with visual studio 2008 and created an installer for it.Works fine so far.I realized it lacks the automatic updates feature, and after trying several solutions, i decided to give a try to clickonce deployment.After a successful deployment on a network server, i 've noticed that the application crashes after installation of the downloaded app.It complains about this: Cannot create instance of 'Login' defined in assembly 'MyApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Exception has been thrown by the target of an invocation. Error in markup file 'MyApplication;component/login.xaml' Line 1 Position 9. here is the stacktrace at System.Windows.Markup.XamlParseException.ThrowException(String message, Exception innerException, Int32 lineNumber, Int32 linePosition, Uri baseUri, XamlObjectIds currentXamlObjectIds, XamlObjectIds contextXamlObjectIds, Type objectType) at System.Windows.Markup.XamlParseException.ThrowException(ParserContext parserContext, Int32 lineNumber, Int32 linePosition, String message, Exception innerException) at System.Windows.Markup.BamlRecordReader.ThrowExceptionWithLine(String message, Exception innerException) at System.Windows.Markup.BamlRecordReader.CreateInstanceFromType(Type type, Int16 typeId, Boolean throwOnFail) at System.Windows.Markup.BamlRecordReader.GetElementAndFlags(BamlElementStartRecord bamlElementStartRecord, Object& element, ReaderFlags& flags, Type& delayCreatedType, Int16& delayCreatedTypeId) at System.Windows.Markup.BamlRecordReader.BaseReadElementStartRecord(BamlElementStartRecord bamlElementRecord) at System.Windows.Markup.BamlRecordReader.ReadElementStartRecord(BamlElementStartRecord bamlElementRecord) at System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord) at System.Windows.Markup.BamlRecordReader.Read(Boolean singleRecord) at System.Windows.Markup.TreeBuilderBamlTranslator.ParseFragment() at System.Windows.Markup.TreeBuilder.Parse() at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream) at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc) at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties) at System.Windows.Application.DoStartup() at System.Windows.Application.<.ctorb__0(Object unused) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.Run() at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run() at myApplication.App.Main() here is just the region the debugger is pointing to <Window x:Class="MyApplication.Login" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:src="clr-namespace:MyApplication" xmlns:UI="clr-namespace:UI;assembly=UI" Title="My Application" Height="400" Width="550" ResizeMode="NoResize" WindowStyle="ThreeDBorderWindow" WindowStartupLocation="CenterScreen" Name="Logine" Loaded="Logine_Loaded" Closed="Logine_Closed" Icon="orLogo.ico"> But the installer version as in the msi from setup project works fine.so i cannot see where the error is comming from since i can have design view. Question 1 : Does any one have a similar issue, or is that a known issue? Question 2 : If it's a known issue then what are alternative.I might give up on the clickonce but then i my automatic update feature will be lost (as in there is none which is not ovekill or seriously outdated that i can find right now). thanks for reading this and for pointing me to the right direction.

    Read the article

  • .Net - Whats the difference between a Session Facade and Business Delegate?

    - by KP65
    What I understand so far: Business Delegate - In the presentation tier, as an ASP component, provides an interface for ASP views to access business components without exposing their API, therefore reducing coupling between the two. Session Facade - In the business tier, as a com+ component, encapsulates business objects, provides a course grain interface for views to access business components. Reduces coupling, hides complex business component interaction from views. So what is the actual difference? They seem pretty similar to me..

    Read the article

  • How to disable the delete button for the particular row when we are using the table view delegate me

    - by monish
    Hi guys, Here I need a help from ur side that Im using the tableview delegate method commitEditing sytle to get the delete button for every cell when we swipe.But my problem here is I dont want the delete button for the first row in the tableview and swipe should not work and I dnt have any idea how to implemet this. Anyone's help will be much appreciated. Thank You, Monish.

    Read the article

  • Is there a downside to adding an anonymous empty delegate on event declaration?

    - by serg10
    I have seen a few mentions of this idiom (including on SO): // Deliberately empty subscriber public event EventHandler AskQuestion = delegate {}; The upside is clear - it avoids the need to check for null before raising the event. However, I am keen to understand if there are any downsides. For example, is it something that is in widespread use and is transparent enough that it won't cause a maintenance headache? Is there any appreciable performance hit of the empty event subscriber call?

    Read the article

  • How does one make the camera on the iphone appear from the app delegate? Is it possible?

    - by K-RAN
    I'm just playing around with a simple program that opens the camera. That's literally all that I want to do. I'm a beginner and I believe that I have the basics down in terms of UI management for the iPhone so I decided to give this one a whirl. What I'm trying to do right now is... - (BOOL) application:(UIApplication*) application didFinishLaunchingWithOptions:(NSDictionary*) launchOptions { UIImagePickerController * camera = [[UIImagePickerController alloc] init]; camera.delegate = self; camera.sourceType = UIImagePickerControllerSourceTypeCamera; camera.allowsEditing = NO; camera.showsCameraControls = NO; [viewController presentModalViewController:camera animated:NO]; [window addSubview:viewController.view]; [window makeKeyAndVisible]; return YES: } So basically, initialize the camera, set some things and show it in the main view. I set the camera's delegate to self because this code is placed in the delegate class (and yes, the delegate class is conforming to UIImagePickerControllerDelegate && UINavigationControllerDelegate). Main problem right now is that nothing is appearing on the screen. I have absolutely no idea what I'm doing wrong, especially since the program is building correctly with no errors or warnings... Any help is appreciated! Thanks a lot :D

    Read the article

  • Can I reverse the order of a multicast delegate event?

    - by Neil Barnwell
    When you subscribe to an event in .NET, the subscription is added to a multicast delegate. When the event is fired, the delegates are called in the order they were subscribed. I'd like to override the subscription somehow, so that the subscriptions are actually fired in the reverse order. Can this be done, and how? I think something like this might be what I need?: public event MyReversedEvent { add { /* magic! */ } remove { /* magic! */ } }

    Read the article

  • Showing login view controller before main tab bar controller

    - by Padawan
    I'm creating an iPad app with a tab bar controller that requires login. So on launch, I want to show a LoginViewController and if login is successful, then show the tab bar controller. This is how I implemented an initial test version (left out some typical header stuff, etc)... AppDelegate.h: @interface AppDelegate_Pad : NSObject <UIApplicationDelegate, LoginViewControllerDelegate> { UIWindow *window; UITabBarController *tabBarController; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UITabBarController *tabBarController; @end AppDelegate.m: @implementation AppDelegate_Pad @synthesize window; @synthesize tabBarController; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { LoginViewController_Pad *lvc = [[LoginViewController_Pad alloc] initWithNibName:@"LoginViewController_Pad" bundle:nil]; lvc.delegate = self; [window addSubview:lvc.view]; //[lvc release]; [window makeKeyAndVisible]; return YES; } - (void)loginViewControllerDidFinish:(LoginViewController_Pad *)loginViewController { [window addSubview:tabBarController.view]; } - (void)dealloc {...} @end LoginViewController_Pad.h: @protocol LoginViewControllerDelegate; @interface LoginViewController_Pad : UIViewController { id<LoginViewControllerDelegate> delegate; } @property (nonatomic, assign) id <LoginViewControllerDelegate> delegate; - (IBAction)buttonPressed; @end @protocol LoginViewControllerDelegate -(void)loginViewControllerDidFinish:(LoginViewController_Pad *)loginViewController; @end LoginViewController_Pad.m: @implementation LoginViewController_Pad @synthesize delegate; ... - (IBAction)buttonPressed { [self.view removeFromSuperview]; [self.delegate loginViewControllerDidFinish:self]; } ... @end So the app delegate adds the login view controller's view on launch and waits for login to call "did finish" using a delegate. The login view controller calls removeFromSuperView before it calls didFinish. The app delegate then calls addSubView on the tab bar controller's view. If you made it up to this point, thanks, and I have three questions: MAIN QUESTION: Is this the right way to show a view controller before the app's main tab bar controller is displayed? Even though it seems to work, is it a proper way to do it? If I comment out the "lvc release" in the app delegate then the app crashes with EXC_BAD_ACCESS when the button on the login view controller is pressed. Why? With the "lvc release" commented out everything seems to work but on the debugger console it writes this message when the app delegate calls addSubView for the tab bar controller: Using two-stage rotation animation. To use the smoother single-stage animation, this application must remove two-stage method implementations. What does that mean and do I need to worry about it?

    Read the article

  • Can I "inherit" a delegate? Looking for ways to combine Moq and MSpec without conflicts around It...

    - by Tomas Lycken
    I have started to use MSpec for BDD, and since long ago I use Moq as my mocking framework. However, they both define It, which means I can't have using Moq and using Machine.Specifications in the same code file without having to specify the namespace explicitly each time I use It. Anyone who's used MSpec knows this isn't really an option. I googled for solutions to this problem, and this blogger mentions having forked MSpec for himself, and implemented paralell support for Given, When, Then. I'd like to do this, but I can't figure out how to declare for example Given without having to go through the entire framework looking for references to Establish, and changing code there to match that I want either to be OK. For reference, the Establish, Because and It are declared in the following way: public delegate void Establish(); public delegate void Because(); public delegate void It(); What I need is to somehow declare Given, so that everywhere the code looks for an Establish, Given is also OK.

    Read the article

  • Subjective question...would you use the Action delegate to avoid duplication of code?

    - by Seth Spearman
    Hello, I just asked a question that helps about using generics (or polymorphism) to avoid duplication of code. I am really trying to follow the DRY principle. So I just ran into the following code... Sub OutputDataToExcel() OutputLine("Output DataBlocks", 1) OutputDataBlocks() OutputLine("") OutputLine("Output Numbered Inventory", 1) OutputNumberedInventory() OutputLine("") OutputLine("Output Item Summaries", 1) OutputItemSummaries() OutputLine("") End Sub Should I rewrite this code to be as follows using the Action delegate... Sub OutputDataToExcel() OutputData("Output DataBlocks", New Action(AddressOf OutputDataBlocks)) OutputData("Output Numbered Inventory", New Action(AddressOf OutputNumberedInventory)) OutputData("Output Item Summaries", New Action(AddressOf OutputItemSummaries)) End Sub Sub OutputData(ByVal outputDescription As String, ByVal outputType As Action) OutputLine(outputDescription, 1) outputType() OutputLine("") End Sub I realize this question is subjective. I am just wondering about how religiously you follow DRY. Would you do this? Seth

    Read the article

  • How can I access data that's stored in my App Delegate from my various view controllers?

    - by BeachRunnerJoe
    This question is similar to this other post, but I'm new to iPhone development and I'm getting used to the good practices for organizing my data throughout my app. I understand the ApplicationDelegate object to be the best place to manage data that is global to my app, correct? If so, how can I access data that's stored in my App Delegate from various view controllers? Specifically, I have an array of table section titles for my root table view controller created as such... appdelegate.m sectionTitles = [[NSArray alloc] initWithObjects: @"Title1", @"Title2", @"Title3", nil]; rootViewController.appDelegate = self; and I need to access it throughout the different views of my app, like such... rootviewcontroller.m NSUInteger numSections = [self.appDelegate.sectionTitles count]; Is this the best way to do it or are there any reasons I should organize my data a better way? Thanks so much in advance for your help!

    Read the article

  • Does Visual Studio 2010 support something like Eclipse's "Generate delegate methods"?

    - by devoured elysium
    Eclipse allows us to define a class as: interface MyInterface { void methodA(); int methodB(); } class A : MyInterface { MyInterface myInterface; } and then with this "Generate delegate methods", it will implement all needed methods for the interface, redirecting their logic to myInterface's methods: class A : MyInterface { MyInterface myInterface; public void methodA() { myInterface.methodA(); } public int methodB() { return myInterface.methodB(); } } Is it possible to accomplish the same with VS2010? And with R#? Thanks

    Read the article

  • Is there a way in C# 4.0 to have a method take a delegate with the parameters baked in?

    - by Rob Packwood
    I have this code for reporting on a simple demo app I am writing: private static void ReportOnTimedProcess(Action process) { var stopwatch = new Stopwatch(); stopwatch.Start(); process(); stopwatch.Stop(); Console.WriteLine("Process took {0} seconds", stopwatch.ElapsedMilliseconds*1000); } I basically want to track the time of any process. I am trying to have this method take a delegate as a parameter that can have any number of varying parameters. Is there some way an Expression can do this?

    Read the article

  • Parallelism in .NET – Part 13, Introducing the Task class

    - by Reed
    Once we’ve used a task-based decomposition to decompose a problem, we need a clean abstraction usable to implement the resulting decomposition.  Given that task decomposition is founded upon defining discrete tasks, .NET 4 has introduced a new API for dealing with task related issues, the aptly named Task class. The Task class is a wrapper for a delegate representing a single, discrete task within your decomposition.  We will go into various methods of construction for tasks later, but, when reduced to its fundamentals, an instance of a Task is nothing more than a wrapper around a delegate with some utility functionality added.  In order to fully understand the Task class within the new Task Parallel Library, it is important to realize that a task really is just a delegate – nothing more.  In particular, note that I never mentioned threading or parallelism in my description of a Task.  Although the Task class exists in the new System.Threading.Tasks namespace: Tasks are not directly related to threads or multithreading. Of course, Task instances will typically be used in our implementation of concurrency within an application, but the Task class itself does not provide the concurrency used.  The Task API supports using Tasks in an entirely single threaded, synchronous manner. Tasks are very much like standard delegates.  You can execute a task synchronously via Task.RunSynchronously(), or you can use Task.Start() to schedule a task to run, typically asynchronously.  This is very similar to using delegate.Invoke to execute a delegate synchronously, or using delegate.BeginInvoke to execute it asynchronously. The Task class adds some nice functionality on top of a standard delegate which improves usability in both synchronous and multithreaded environments. The first addition provided by Task is a means of handling cancellation via the new unified cancellation mechanism of .NET 4.  If the wrapped delegate within a Task raises an OperationCanceledException during it’s operation, which is typically generated via calling ThrowIfCancellationRequested on a CancellationToken, or if the CancellationToken used to construct a Task instance is flagged as canceled, the Task’s IsCanceled property will be set to true automatically.  This provides a clean way to determine whether a Task has been canceled, often without requiring specific exception handling. Tasks also provide a clean API which can be used for waiting on a task.  Although the Task class explicitly implements IAsyncResult, Tasks provide a nicer usage model than the traditional .NET Asynchronous Programming Model.  Instead of needing to track an IAsyncResult handle, you can just directly call Task.Wait() to block until a Task has completed.  Overloads exist for providing a timeout, a CancellationToken, or both to prevent waiting indefinitely.  In addition, the Task class provides static methods for waiting on multiple tasks – Task.WaitAll and Task.WaitAny, again with overloads providing time out options.  This provides a very simple, clean API for waiting on single or multiple tasks. Finally, Tasks provide a much nicer model for Exception handling.  If the delegate wrapped within a Task raises an exception, the exception will automatically get wrapped into an AggregateException and exposed via the Task.Exception property.  This exception is stored with the Task directly, and does not tear down the application.  Later, when Task.Wait() (or Task.WaitAll or Task.WaitAny) is called on this task, an AggregateException will be raised at that point if any of the tasks raised an exception.  For example, suppose we have the following code: Task taskOne = new Task( () => { throw new ApplicationException("Random Exception!"); }); Task taskTwo = new Task( () => { throw new ArgumentException("Different exception here"); }); // Start the tasks taskOne.Start(); taskTwo.Start(); try { Task.WaitAll(new[] { taskOne, taskTwo }); } catch (AggregateException e) { Console.WriteLine(e.InnerExceptions.Count); foreach (var inner in e.InnerExceptions) Console.WriteLine(inner.Message); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Here, our routine will print: 2 Different exception here Random Exception! Note that we had two separate tasks, each of which raised two distinctly different types of exceptions.  We can handle this cleanly, with very little code, in a much nicer manner than the Asynchronous Programming API.  We no longer need to handle TargetInvocationException or worry about implementing the Event-based Asynchronous Pattern properly by setting the AsyncCompletedEventArgs.Error property.  Instead, we just raise our exception as normal, and handle AggregateException in a single location in our calling code.

    Read the article

  • Posting source code in blogger- fails with C# containers

    - by Lirik
    I tried the solutions that are posted in this related SO question and for the most part the code snippets are working, but there are some cases that are still getting garbled by Blogger when it publishes the blog. In particular, declaring generic containers seems to be most troublesome. Please see the code examples on my blog and in particular the section where I define the dictionary (http://mlai-lirik.blogspot.com/). I want to display this: static Dictionary<int, List<Delegate>> _delegate = new Dictionary<int,List<Delegate>>(); But blogger publishes this: static Dictionary<int, list=""><delegate>> _delegate = new Dictionary<int, list=""><delegate>>(); And it caps the end of my code section with this: </delegate></delegate></int,></delegate></int,> Apparently blogger thinks that the <int and <delegate> portion of the dictionary are some sort of HTML tags and it automatically attempts to close them at the end of the code snippet. Does anybody know how to get around this problem?

    Read the article

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