Search Results

Search found 257 results on 11 pages for 'idisposable'.

Page 6/11 | < Previous Page | 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • Release resources in .Net C#

    - by zaidwaqi
    Hi, I'm new to C# and .NET, ,and have been reading around about it. I need to know why and when do I need to release resources? Doesn't the garbage collector take care of everything? When do I need to implement IDisposable, and how is it different from destructor in C++? Also, if my program is rather small i.e. a screensaver, do I need to care about releasing resources? Thanks.

    Read the article

  • Mulit-tenant ASP.NET MVC – Controllers

    - by zowens
    Part I – Introduction Part II – Foundation   The time has come to talk about controllers in a multi-tenant ASP.NET MVC architecture. This is actually the most critical design decision you will make when dealing with multi-tenancy with MVC. In my design, I took into account the design goals I mentioned in the introduction about inversion of control and what a tenant is to my design. Be aware that this is only one way to achieve multi-tenant controllers.   The Premise MvcEx (which is a sample written by Rob Ashton) utilizes dynamic controllers. Essentially a controller is “dynamic” in that multiple action results can be placed in different “controllers” with the same name. This approach is a bit too complicated for my design. I wanted to stick with plain old inheritance when dealing with controllers. The basic premise of my controller design is that my main host defines a set of universal controllers. It is the responsibility of the tenant to decide if the tenant would like to utilize these core controllers. This can be done either by straight usage of the controller or inheritance for extension of the functionality defined by the controller. The controller is resolved by a StructureMap container that is attached to the tenant, as discussed in Part II.   Controller Resolution I have been thinking about two different ways to resolve controllers with StructureMap. One way is to use named instances. This is a really easy way to simply pull the controller right out of the container without a lot of fuss. I ultimately chose not to use this approach. The reason for this decision is to ensure that the controllers are named properly. If a controller has a different named instance that the controller type, then the resolution has a significant disconnect and there are no guarantees. The final approach, the one utilized by the sample, is to simply pull all controller types and correlate the type with a controller name. This has a bit of a application start performance disadvantage, but is significantly more approachable for maintainability. For example, if I wanted to go back and add a “ControllerName” attribute, I would just have to change the ControllerFactory to suit my needs.   The Code The container factory that I have built is actually pretty simple. That’s really all we need. The most significant method is the GetControllersFor method. This method makes the model from the Container and determines all the concrete types for IController.  The thing you might notice is that this doesn’t depend on tenants, but rather containers. You could easily use this controller factory for an application that doesn’t utilize multi-tenancy. public class ContainerControllerFactory : IControllerFactory { private readonly ThreadSafeDictionary<IContainer, IDictionary<string, Type>> typeCache; public ContainerControllerFactory(IContainerResolver resolver) { Ensure.Argument.NotNull(resolver, "resolver"); this.ContainerResolver = resolver; this.typeCache = new ThreadSafeDictionary<IContainer, IDictionary<string, Type>>(); } public IContainerResolver ContainerResolver { get; private set; } public virtual IController CreateController(RequestContext requestContext, string controllerName) { var controllerType = this.GetControllerType(requestContext, controllerName); if (controllerType == null) return null; var controller = this.ContainerResolver.Resolve(requestContext).GetInstance(controllerType) as IController; // ensure the action invoker is a ContainerControllerActionInvoker if (controller != null && controller is Controller && !((controller as Controller).ActionInvoker is ContainerControllerActionInvoker)) (controller as Controller).ActionInvoker = new ContainerControllerActionInvoker(this.ContainerResolver); return controller; } public void ReleaseController(IController controller) { if (controller != null && controller is IDisposable) ((IDisposable)controller).Dispose(); } internal static IEnumerable<Type> GetControllersFor(IContainer container) { Ensure.Argument.NotNull(container); return container.Model.InstancesOf<IController>().Select(x => x.ConcreteType).Distinct(); } protected virtual Type GetControllerType(RequestContext requestContext, string controllerName) { Ensure.Argument.NotNull(requestContext, "requestContext"); Ensure.Argument.NotNullOrEmpty(controllerName, "controllerName"); var container = this.ContainerResolver.Resolve(requestContext); var typeDictionary = this.typeCache.GetOrAdd(container, () => GetControllersFor(container).ToDictionary(x => ControllerFriendlyName(x.Name))); Type found = null; if (typeDictionary.TryGetValue(ControllerFriendlyName(controllerName), out found)) return found; return null; } private static string ControllerFriendlyName(string value) { return (value ?? string.Empty).ToLowerInvariant().Without("controller"); } } One thing to note about my implementation is that we do not use namespaces that can be utilized in the default ASP.NET MVC controller factory. This is something that I don’t use and have no desire to implement and test. The reason I am not using namespaces in this situation is because each tenant has its own namespaces and the routing would not make sense in this case.   Because we are using IoC, dependencies are automatically injected into the constructor. For example, a tenant container could implement it’s own IRepository and a controller could be defined in the “main” project. The IRepository from the tenant would be injected into the main project’s controller. This is quite a useful feature.   Again, the source code is on GitHub here.   Up Next Up next is the view resolution. This is a complicated issue, so be prepared. I hope that you have found this series useful. If you have any questions about my implementation so far, send me an email or DM me on Twitter. I have had a lot of great conversations about multi-tenancy so far and I greatly appreciate the feedback!

    Read the article

  • Pluggable Rules for Entity Framework Code First

    - by Ricardo Peres
    Suppose you want a system that lets you plug custom validation rules on your Entity Framework context. The rules would control whether an entity can be saved, updated or deleted, and would be implemented in plain .NET. Yes, I know I already talked about plugable validation in Entity Framework Code First, but this is a different approach. An example API is in order, first, a ruleset, which will hold the collection of rules: 1: public interface IRuleset : IDisposable 2: { 3: void AddRule<T>(IRule<T> rule); 4: IEnumerable<IRule<T>> GetRules<T>(); 5: } Next, a rule: 1: public interface IRule<T> 2: { 3: Boolean CanSave(T entity, DbContext ctx); 4: Boolean CanUpdate(T entity, DbContext ctx); 5: Boolean CanDelete(T entity, DbContext ctx); 6: String Name 7: { 8: get; 9: } 10: } Let’s analyze what we have, starting with the ruleset: Only has methods for adding a rule, specific to an entity type, and to list all rules of this entity type; By implementing IDisposable, we allow it to be cancelled, by disposing of it when we no longer want its rules to be applied. A rule, on the other hand: Has discrete methods for checking if a given entity can be saved, updated or deleted, which receive as parameters the entity itself and a pointer to the DbContext to which the ruleset was applied; Has a name property for helping us identifying what failed. A ruleset really doesn’t need a public implementation, all we need is its interface. The private (internal) implementation might look like this: 1: sealed class Ruleset : IRuleset 2: { 3: private readonly IDictionary<Type, HashSet<Object>> rules = new Dictionary<Type, HashSet<Object>>(); 4: private ObjectContext octx = null; 5:  6: internal Ruleset(ObjectContext octx) 7: { 8: this.octx = octx; 9: } 10:  11: public void AddRule<T>(IRule<T> rule) 12: { 13: if (this.rules.ContainsKey(typeof(T)) == false) 14: { 15: this.rules[typeof(T)] = new HashSet<Object>(); 16: } 17:  18: this.rules[typeof(T)].Add(rule); 19: } 20:  21: public IEnumerable<IRule<T>> GetRules<T>() 22: { 23: if (this.rules.ContainsKey(typeof(T)) == true) 24: { 25: foreach (IRule<T> rule in this.rules[typeof(T)]) 26: { 27: yield return (rule); 28: } 29: } 30: } 31:  32: public void Dispose() 33: { 34: this.octx.SavingChanges -= RulesExtensions.OnSaving; 35: RulesExtensions.rulesets.Remove(this.octx); 36: this.octx = null; 37:  38: this.rules.Clear(); 39: } 40: } Basically, this implementation: Stores the ObjectContext of the DbContext to which it was created for, this is so that later we can remove the association; Has a collection - a set, actually, which does not allow duplication - of rules indexed by the real Type of an entity (because of proxying, an entity may be of a type that inherits from the class that we declared); Has generic methods for adding and enumerating rules of a given type; Has a Dispose method for cancelling the enforcement of the rules. A (really dumb) rule applied to Product might look like this: 1: class ProductRule : IRule<Product> 2: { 3: #region IRule<Product> Members 4:  5: public String Name 6: { 7: get 8: { 9: return ("Rule 1"); 10: } 11: } 12:  13: public Boolean CanSave(Product entity, DbContext ctx) 14: { 15: return (entity.Price > 10000); 16: } 17:  18: public Boolean CanUpdate(Product entity, DbContext ctx) 19: { 20: return (true); 21: } 22:  23: public Boolean CanDelete(Product entity, DbContext ctx) 24: { 25: return (true); 26: } 27:  28: #endregion 29: } The DbContext is there because we may need to check something else in the database before deciding whether to allow an operation or not. And here’s how to apply this mechanism to any DbContext, without requiring the usage of a subclass, by means of an extension method: 1: public static class RulesExtensions 2: { 3: private static readonly MethodInfo getRulesMethod = typeof(IRuleset).GetMethod("GetRules"); 4: internal static readonly IDictionary<ObjectContext, Tuple<IRuleset, DbContext>> rulesets = new Dictionary<ObjectContext, Tuple<IRuleset, DbContext>>(); 5:  6: private static Type GetRealType(Object entity) 7: { 8: return (entity.GetType().Assembly.IsDynamic == true ? entity.GetType().BaseType : entity.GetType()); 9: } 10:  11: internal static void OnSaving(Object sender, EventArgs e) 12: { 13: ObjectContext octx = sender as ObjectContext; 14: IRuleset ruleset = rulesets[octx].Item1; 15: DbContext ctx = rulesets[octx].Item2; 16:  17: foreach (ObjectStateEntry entry in octx.ObjectStateManager.GetObjectStateEntries(EntityState.Added)) 18: { 19: Object entity = entry.Entity; 20: Type realType = GetRealType(entity); 21:  22: foreach (dynamic rule in (getRulesMethod.MakeGenericMethod(realType).Invoke(ruleset, null) as IEnumerable)) 23: { 24: if (rule.CanSave(entity, ctx) == false) 25: { 26: throw (new Exception(String.Format("Cannot save entity {0} due to rule {1}", entity, rule.Name))); 27: } 28: } 29: } 30:  31: foreach (ObjectStateEntry entry in octx.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted)) 32: { 33: Object entity = entry.Entity; 34: Type realType = GetRealType(entity); 35:  36: foreach (dynamic rule in (getRulesMethod.MakeGenericMethod(realType).Invoke(ruleset, null) as IEnumerable)) 37: { 38: if (rule.CanDelete(entity, ctx) == false) 39: { 40: throw (new Exception(String.Format("Cannot delete entity {0} due to rule {1}", entity, rule.Name))); 41: } 42: } 43: } 44:  45: foreach (ObjectStateEntry entry in octx.ObjectStateManager.GetObjectStateEntries(EntityState.Modified)) 46: { 47: Object entity = entry.Entity; 48: Type realType = GetRealType(entity); 49:  50: foreach (dynamic rule in (getRulesMethod.MakeGenericMethod(realType).Invoke(ruleset, null) as IEnumerable)) 51: { 52: if (rule.CanUpdate(entity, ctx) == false) 53: { 54: throw (new Exception(String.Format("Cannot update entity {0} due to rule {1}", entity, rule.Name))); 55: } 56: } 57: } 58: } 59:  60: public static IRuleset CreateRuleset(this DbContext context) 61: { 62: Tuple<IRuleset, DbContext> ruleset = null; 63: ObjectContext octx = (context as IObjectContextAdapter).ObjectContext; 64:  65: if (rulesets.TryGetValue(octx, out ruleset) == false) 66: { 67: ruleset = rulesets[octx] = new Tuple<IRuleset, DbContext>(new Ruleset(octx), context); 68: 69: octx.SavingChanges += OnSaving; 70: } 71:  72: return (ruleset.Item1); 73: } 74: } It relies on the SavingChanges event of the ObjectContext to intercept the saving operations before they are actually issued. Yes, it uses a bit of dynamic magic! Very handy, by the way! So, let’s put it all together: 1: using (MyContext ctx = new MyContext()) 2: { 3: IRuleset rules = ctx.CreateRuleset(); 4: rules.AddRule(new ProductRule()); 5:  6: ctx.Products.Add(new Product() { Name = "xyz", Price = 50000 }); 7:  8: ctx.SaveChanges(); //an exception is fired here 9:  10: //when we no longer need to apply the rules 11: rules.Dispose(); 12: } Feel free to use it and extend it any way you like, and do give me your feedback! As a final note, this can be easily changed to support plain old Entity Framework (not Code First, that is), if that is what you are using.

    Read the article

  • Generic Repository with SQLite and SQL Compact Databases

    - by Andrew Petersen
    I am creating a project that has a mobile app (Xamarin.Android) using a SQLite database and a WPF application (Code First Entity Framework 5) using a SQL Compact database. This project will even eventually have a SQL Server database as well. Because of this I am trying to create a generic repository, so that I can pass in the correct context depending on which application is making the request. The issue I ran into is my DataContext for the SQL Compact database inherits from DbContext and the SQLite database inherits from SQLiteConnection. What is the best way to make this generic, so that it doesn't matter what kind of database is on the back end? This is what I have tried so far on the SQL Compact side: public interface IRepository<TEntity> { TEntity Add(TEntity entity); } public class Repository<TEntity, TContext> : IRepository<TEntity>, IDisposable where TEntity : class where TContext : DbContext { private readonly TContext _context; public Repository(DbContext dbContext) { _context = dbContext as TContext; } public virtual TEntity Add(TEntity entity) { return _context.Set<TEntity>().Add(entity); } } And on the SQLite side: public class ElverDatabase : SQLiteConnection { static readonly object Locker = new object(); public ElverDatabase(string path) : base(path) { CreateTable<Ticket>(); } public int Add<T>(T item) where T : IBusinessEntity { lock (Locker) { return Insert(item); } } }

    Read the article

  • Rx IObservable buffering to smooth out bursts of events

    - by Dan
    I have an Observable sequence that produces events in rapid bursts (ie: five events one right after another, then a long delay, then another quick burst of events, etc.). I want to smooth out these bursts by inserting a short delay between events. Imagine the following diagram as an example: Raw: --oooo--------------ooooo-----oo----------------ooo| Buffered: --o--o--o--o--------o--o--o--o--o--o--o---------o--o--o| My current approach is to generate a metronome-like timer via Observable.Interval() that signals when it's ok to pull another event from the raw stream. The problem is that I can't figure out how to then combine that timer with my raw unbuffered observable sequence. IObservable.Zip() is close to doing what I want, but it only works so long as the raw stream is producing events faster than the timer. As soon as there is a significant lull in the raw stream, the timer builds up a series of unwanted events that then immediately pair up with the next burst of events from the raw stream. Ideally, I want an IObservable extension method with the following function signature that produces the bevaior I've outlined above. Now, come to my rescue StackOverflow :) public static IObservable<T> Buffered(this IObservable<T> src, TimeSpan minDelay) PS. I'm brand new to Rx, so my apologies if this is a trivially simple question... 1. Simple yet flawed approach Here's my initial naive and simplistic solution that has quite a few problems: public static IObservable<T> Buffered<T>(this IObservable<T> source, TimeSpan minDelay) { Queue<T> q = new Queue<T>(); source.Subscribe(x => q.Enqueue(x)); return Observable.Interval(minDelay).Where(_ => q.Count > 0).Select(_ => q.Dequeue()); } The first obvious problem with this is that the IDisposable returned by the inner subscription to the raw source is lost and therefore the subscription can't be terminated. Calling Dispose on the IDisposable returned by this method kills the timer, but not the underlying raw event feed that is now needlessly filling the queue with nobody left to pull events from the queue. The second problem is that there's no way for exceptions or end-of-stream notifications to be propogated through from the raw event stream to the buffered stream - they are simply ignored when subscribing to the raw source. And last but not least, now I've got code that wakes up periodically regardless of whether there is actually any work to do, which I'd prefer to avoid in this wonderful new reactive world. 2. Way overly complex appoach To solve the problems encountered in my initial simplistic approach, I wrote a much more complicated function that behaves much like IObservable.Delay() (I used .NET Reflector to read that code and used it as the basis of my function). Unfortunately, a lot of the boilerplate logic such as AnonymousObservable is not publicly accessible outside the system.reactive code, so I had to copy and paste a lot of code. This solution appears to work, but given its complexity, I'm less confident that its bug free. I just can't believe that there isn't a way to accomplish this using some combination of the standard Reactive extensions. I hate feeling like I'm needlessly reinventing the wheel, and the pattern I'm trying to build seems like a fairly standard one.

    Read the article

  • CodePlex Daily Summary for Thursday, June 28, 2012

    CodePlex Daily Summary for Thursday, June 28, 2012Popular ReleasesDesigning Windows 8 Applications with C# and XAML: Chapters 1 - 7 Release Preview: Source code for all examples from Chapters 1 - 7 for the Release PreviewDataBooster - Extension to ADO.NET Data Provider: DataBooster Library for Oracle + SQL Server Beta2: This is a derivative library of dbParallel project http://dbparallel.codeplex.com. All above binaries releases require .NET Framework 4.0 or later. SQL Server support is always build-in (can't be unplugged). The first download (DLL) also requires ODP.NET to connect Oracle; The second download (DLL) also requires DataDirect(3.5) to connect Oracle; The third download (DLL) doesn't support Oracle. Please download the source code if the provider need to be replaced by others. For example ODP.NE...Microsoft Ajax Minifier: Microsoft Ajax Minifier 4.57: Fix for issue #18284: evaluating literal expressions in the pattern c1 * (x / c2) where c1/c2 is an integer value (as opposed to c2/c1 being the integer) caused the expression to be destroyed.Visual Studio ALM Quick Reference Guidance: v2 - Visual Studio 2010 (Japanese): Rex Tang (?? ??) http://blogs.msdn.com/b/willy-peter_schaub/archive/2011/12/08/introducing-the-visual-studio-alm-rangers-rex-tang.aspx, Takaho Yamaguchi (?? ??), Masashi Fujiwara (?? ??), localized and reviewed the Quick Reference Guidance for the Japanese communities, based on http://vsarquickguide.codeplex.com/releases/view/52402. The Japanese guidance is available in AllGuides and Everything packages. The AllGuides package contains guidances in PDF file format, while the Everything packag...Visual Studio Team Foundation Server Branching and Merging Guide: v1 - Visual Studio 2010 (Japanese): Rex Tang (?? ??) http://blogs.msdn.com/b/willy-peter_schaub/archive/2011/12/08/introducing-the-visual-studio-alm-rangers-rex-tang.aspx, Takaho Yamaguchi (?? ??), Hirokazu Higashino (?? ??), localized and reviewed the Branching Guidance for the Japanese communities, based on http://vsarbranchingguide.codeplex.com/releases/view/38849. The Japanese guidance is available in AllGuides and Everything packages. The AllGuides package contains guidances in PDF file format, while the Everything packag...SQL Server FineBuild: Version 3.1.0: Top SQL Server FineBuild Version 3.1.0This is the stable version of FineBuild for SQL Server 2012, 2008 R2, 2008 and 2005 Documentation FineBuild Wiki containing details of the FineBuild process Known Issues Limitations with this release FineBuild V3.1.0 Release Contents List of changes included in this release Please DonateFineBuild is free, but please donate what you think FineBuild is worth as everything goes to charity. Tearfund is one of the UK's leading relief and de...EasySL: RapidSL V2: Rewrite RapidSL UI Framework, Using Silverlight 5.0 EF4.1 Code First Ria Service SP2 + Lastest Silverlight Toolkit.SOLID by example: All examples: All solid examplesSiteMap Editor for Microsoft Dynamics CRM 2011: SiteMap Editor (1.1.1726.406): Use of new version of connection controls for a full support of OSDP authentication mechanism for CRM Online.StreamInsight Samples: StreamInsight Product Team Samples V2.1: These samples correspond to the new StreamInsight APIs introduced with V2.1.Umbraco CMS: Umbraco CMS 5.2: Development on Umbraco v5 discontinued After much discussion and consultation with leaders from the Umbraco community it was decided that work on the v5 branch would be discontinued with efforts being refocused on the stable and feature rich v4 branch. For full details as to why this decision was made please watch the CodeGarden 12 Keynote. What about all that hard work?!?? We are not binning everything and it does not mean that all work done on 5 is lost! we are taking all of the best and m...IIS Express Manager: IIS Express 0.31 B: V0.1B - 04 May, 2012 Initiated Project. V0.2B - 05May, 2012 1. Fixed small bug. Threw error when stop button was pressed in an already stopped application. 2. Removed start and stop button. Double clicking on list items will now stop / start the websites. 3. Improved code readability. 4. Changed Orientation of Buttons in UI. V0.3B - 06May, 2012 1. Complete modification of IISEM and process ID handling 2. IISEM is now capable of reflecting the existing IISExpress processes right from startup...CodeGenerate: CodeGenerate Alpha: The Project can auto generate C# code. Include BLL Layer、Domain Layer、IDAL Layer、DAL Layer. Support SqlServer And Oracle This is a alpha program,but which can run and generate code. Generate database table info into MS WordXDA ROM HUB: XDA ROM HUB v0.9: Kernel listing added -- Thanks to iONEx Added scripts installer button. Added "Nandroid On The Go" -- Perform a Nandroid backup without a PC! Added official Android app!ExtAspNet: ExtAspNet v3.1.8.2: +2012-06-24 v3.1.8 +????Grid???????(???????ExpandUnusedSpace????????)(??)。 -????MinColumnWidth(??????)。 -????AutoExpandColumn,???????????????(ColumnID)(?????ForceFitFirstTime??ForceFitAllTime,??????)。 -????AutoExpandColumnMax?AutoExpandColumnMin。 -????ForceFitFirstTime,????????????,??????????(????????????)。 -????ForceFitAllTime,????????????,??????????(??????????????????)。 -????VerticalScrollWidth,????????(??????????,0?????????????)。 -????grid/grid_forcefit.aspx。 -???????????En...AJAX Control Toolkit: June 2012 Release: AJAX Control Toolkit Release Notes - June 2012 Release Version 60623June 2012 release of the AJAX Control Toolkit. AJAX Control Toolkit .NET 4 – AJAX Control Toolkit for .NET 4 and sample site (Recommended). AJAX Control Toolkit .NET 3.5 – AJAX Control Toolkit for .NET 3.5 and sample site (Recommended). Notes: - The current version of the AJAX Control Toolkit is not compatible with ASP.NET 2.0. The latest version that is compatible with ASP.NET 2.0 can be found here: 11121. - Pages using ...WPF Application Framework (WAF): WPF Application Framework (WAF) 2.5.0.5: Version: 2.5.0.5 (Milestone 5): This release contains the source code of the WPF Application Framework (WAF) and the sample applications. Requirements .NET Framework 4.0 (The package contains a solution file for Visual Studio 2010) The unit test projects require Visual Studio 2010 Professional Changelog Legend: [B] Breaking change; [O] Marked member as obsolete WAF: Add IsInDesignMode property to the WafConfiguration class. WAF: Introduce the IModuleController interface. WAF: Add ...Windows 8 Metro RSS Reader: Metro RSS Reader.v7: Updated for Windows 8 Release Preview Changed background and foreground colors Used VariableSizeGrid layout to wrap blog posts with images Sort items with Images first, text-only last Enabled Caching to improve navigation between framesXDesigner.Development: First release: First releaseBlackJumboDog: Ver5.6.5: 2012.06.22 Ver5.6.5  (1) FTP??????? EPSV ?? EPRT ???????New ProjectsAzure Log Viewer: Simple viewer for Windows Azure Diagnostics logs table.ChsoftDemo: chsoftDemoCodeDDD: CodeDDD is a set of lightweight Application Blocks with the goal of help on the development of Nlayered DDD ApplicationsCOM32: Serial communication componentCustom Email Template SharePoint: This solution customizes the Email text (Subject and the Message) sent to users on granting permssions to various sites.DBD::IngresII: DBD::IngresII is Ingres database driver for Perl.Dure: just for simplifying developments....FormAbstraction: FormAbstration allows you to add data objects to the session variable. You just have to name your fields the same as your properties and you're editing data.HD44780 Protocol Analyzer: HD44780 Protocol Analyzer for the Saleae Logic and Logic 16 analyzers. Supports 8 and 4 bit data transfer modes.IDisposable Azure Service Bus: A utility class that wraps interaction with a ServicBus inside an IDisposable object.IonoWumpus 2012: It's an awesome project! For the Hunt the Wumpus competition!Its My Story: It is All About Me and My Relatives, friends and followers..Kinect Gestures for Mayhem: Kinect Gesture for Mayhem is a module written for Mayhem. It implements hand gestures as events.KinectComposite: Using advanced Image Processing techniques along with environment information collected by Kinect this project attempt to create real-time composites.Lm.Common: aaaaaaOrBUO SVN: OrBUO SA/HS SVN ProjectOutlook Contact Category Correction Tool: Corrects contacts where the categories have been removed and you have a backup of your contacts at a time when your categories were still intact.Persian (Jalali-Shamsi) Calendar for Windows 8: This project is a Persian calendar for Metro UI on windows 8. It is a sample of using live tile on Metro UI.Schwazzle: New activity feed based on MS' famous CMSSDLGmud: ...SimpleWorkflow: Yet another simple workflow in .Net. The primary goal is to provide a quick lightweight dynamically constructed & reusable workflow API. SmartMeterParamSetting: Thread WPF UDPSPWikiTree 0.1.0.a: Purpose: Create an implementation of a JQuery Tree View Derive tree view content from wiki page library NOT rely on installed feature. (Created client-side)Sucdri: This is an Project Management ProjectUltimate Awesomeness, Inc.: It's cool!WallpaperDeleter: Simple program to delete the current background wallpaper image.zwp: wwww

    Read the article

  • Optimization ended up in casting an object at each method call

    - by Aybe
    I've been doing some optimization for the following piece of code : public void DrawLine(int x1, int y1, int x2, int y2, int color) { _bitmap.DrawLineBresenham(x1, y1, x2, y2, color); } After profiling it about 70% of the time spent was in getting a context for drawing and disposing it. I ended up sketching the following overload : public void DrawLine(int x1, int y1, int x2, int y2, int color, BitmapContext bitmapContext) { _bitmap.DrawLineBresenham(x1, y1, x2, y2, color, bitmapContext); } Until here no problems, all the user has to do is to pass a context and performance is really great as a context is created/disposed one time only (previously it was a thousand times per second). The next step was to make it generic in the sense it doesn't depend on a particular framework for rendering (besides .NET obvisouly). So I wrote this method : public void DrawLine(int x1, int y1, int x2, int y2, int color, IDisposable bitmapContext) { _bitmap.DrawLineBresenham(x1, y1, x2, y2, color, (BitmapContext)bitmapContext); } Now every time a line is drawn the generic context is casted, this was unexpected for me. Are there any approaches for fixing this design issue ? Note : _bitmap is a WriteableBitmap from WPF BitmapContext is from WriteableBitmapEx library DrawLineBresenham is an extension method from WriteableBitmapEx

    Read the article

  • Monitoring settings in a configsection of your app.config for changes

    - by dotjosh
    The usage:public static void Main() { using(var configSectionAdapter = new ConfigurationSectionAdapter<ACISSInstanceConfigSection>("MyConfigSectionName")) { configSectionAdapter.ConfigSectionChanged += () => { Console.WriteLine("File has changed! New setting is " + configSectionAdapter.ConfigSection.MyConfigSetting); }; Console.WriteLine("The initial setting is " + configSectionAdapter.ConfigSection.MyConfigSetting); Console.ReadLine(); } }  The meat: public class ConfigurationSectionAdapter<T> : IDisposable where T : ConfigurationSection { private readonly string _configSectionName; private FileSystemWatcher _fileWatcher; public ConfigurationSectionAdapter(string configSectionName) { _configSectionName = configSectionName; StartFileWatcher(); } private void StartFileWatcher() { var configurationFileDirectory = new FileInfo(Configuration.FilePath).Directory; _fileWatcher = new FileSystemWatcher(configurationFileDirectory.FullName); _fileWatcher.Changed += FileWatcherOnChanged; _fileWatcher.EnableRaisingEvents = true; } private void FileWatcherOnChanged(object sender, FileSystemEventArgs args) { var changedFileIsConfigurationFile = string.Equals(args.FullPath, Configuration.FilePath, StringComparison.OrdinalIgnoreCase); if (!changedFileIsConfigurationFile) return; ClearCache(); OnConfigSectionChanged(); } private void ClearCache() { ConfigurationManager.RefreshSection(_configSectionName); } public T ConfigSection { get { return (T)Configuration.GetSection(_configSectionName); } } private System.Configuration.Configuration Configuration { get { return ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); } } public delegate void ConfigChangedHandler(); public event ConfigChangedHandler ConfigSectionChanged; protected void OnConfigSectionChanged() { if (ConfigSectionChanged != null) ConfigSectionChanged(); } public void Dispose() { _fileWatcher.Changed -= FileWatcherOnChanged; _fileWatcher.EnableRaisingEvents = false; _fileWatcher.Dispose(); } }

    Read the article

  • Resource Acquisition is Initialization in C#

    - by codeWithoutFear
    Resource Acquisition Is Initialization (RAII) is a pattern I grew to love when working in C++.  It is perfectly suited for resource management such as matching all those pesky new's and delete's.  One of my goals was to limit the explicit deallocation statements I had to write.  Often these statements became victims of run-time control flow changes (i.e. exceptions, unhappy path) or development-time code refactoring. The beauty of RAII is realized by tying your resource creation (acquisition) to the construction (initialization) of a class instance.  Then bind the resource deallocation to the destruction of that instance.  That is well and good in a language with strong destructor semantics like C++, but languages like C# that run on garbage-collecting runtimes don't provide the same instance lifetime guarantees. Here is a class and sample that combines a few features of C# to provide an RAII-like solution: using System; namespace RAII { public class DisposableDelegate : IDisposable { private Action dispose; public DisposableDelegate(Action dispose) { if (dispose == null) { throw new ArgumentNullException("dispose"); } this.dispose = dispose; } public void Dispose() { if (this.dispose != null) { Action d = this.dispose; this.dispose = null; d(); } } } class Program { static void Main(string[] args) { Console.Out.WriteLine("Some resource allocated here."); using (new DisposableDelegate(() => Console.Out.WriteLine("Resource deallocated here."))) { Console.Out.WriteLine("Resource used here."); throw new InvalidOperationException("Test for resource leaks."); } } } } The output of this program is: Some resource allocated here. Resource used here. Unhandled Exception: System.InvalidOperationException: Test for resource leaks. at RAII.Program.Main(String[] args) in c:\Dev\RAII\RAII\Program.cs:line 40 Resource deallocated here. Code without fear! --Don

    Read the article

  • NHibernate, and odd "Session is Closed!" errors

    - by Sekhat
    Note: Now that I've typed this out, I have to apologize for the super long question, however, I think all the code and information presented here is in some way relevant. Okay, I'm getting odd "Session Is Closed" errors, at random points in my ASP.NET webforms application. Today, however, it's finally happening in the same place over and over again. I am near certain that nothing is disposing or closing the session in my code, as the bits of code that use are well contained away from all other code as you'll see below. I'm also using ninject as my IOC, which may / may not be important. Okay, so, First my SessionFactoryProvider and SessionProvider classes: SessionFactoryProvider public class SessionFactoryProvider : IDisposable { ISessionFactory sessionFactory; public ISessionFactory GetSessionFactory() { if (sessionFactory == null) sessionFactory = Fluently.Configure() .Database( MsSqlConfiguration.MsSql2005.ConnectionString(p => p.FromConnectionStringWithKey("QoiSqlConnection"))) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<JobMapping>()) .BuildSessionFactory(); return sessionFactory; } public void Dispose() { if (sessionFactory != null) sessionFactory.Dispose(); } } SessionProvider public class SessionProvider : IDisposable { ISessionFactory sessionFactory; ISession session; public SessionProvider(SessionFactoryProvider sessionFactoryProvider) { this.sessionFactory = sessionFactoryProvider.GetSessionFactory(); } public ISession GetCurrentSession() { if (session == null) session = sessionFactory.OpenSession(); return session; } public void Dispose() { if (session != null) { session.Dispose(); } } } These two classes are wired up with Ninject as so: NHibernateModule public class NHibernateModule : StandardModule { public override void Load() { Bind<SessionFactoryProvider>().ToSelf().Using<SingletonBehavior>(); Bind<SessionProvider>().ToSelf().Using<OnePerRequestBehavior>(); } } and as far as I can tell work as expected. Now my BaseDao<T> class: BaseDao public class BaseDao<T> : IDao<T> where T : EntityBase { private SessionProvider sessionManager; protected ISession session { get { return sessionManager.GetCurrentSession(); } } public BaseDao(SessionProvider sessionManager) { this.sessionManager = sessionManager; } public T GetBy(int id) { return session.Get<T>(id); } public void Save(T item) { using (var transaction = session.BeginTransaction()) { session.SaveOrUpdate(item); transaction.Commit(); } } public void Delete(T item) { using (var transaction = session.BeginTransaction()) { session.Delete(item); transaction.Commit(); } } public IList<T> GetAll() { return session.CreateCriteria<T>().List<T>(); } public IQueryable<T> Query() { return session.Linq<T>(); } } Which is bound in Ninject like so: DaoModule public class DaoModule : StandardModule { public override void Load() { Bind(typeof(IDao<>)).To(typeof(BaseDao<>)) .Using<OnePerRequestBehavior>(); } } Now the web request that is causing this is when I'm saving an object, it didn't occur till I made some model changes today, however the changes to my model has not changed the data access code in anyway. Though it changed a few NHibernate mappings (I can post these too if anyone is interested) From as far as I can tell, BaseDao<SomeClass>.Get is called then BaseDao<SomeOtherClass>.Get is called then BaseDao<TypeImTryingToSave>.Save is called. it's the third call at the line in Save() using (var transaction = session.BeginTransaction()) that fails with "Session is Closed!" or rather the exception: Session is closed! Object name: 'ISession'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ObjectDisposedException: Session is closed! Object name: 'ISession'. And indeed following through on the Debugger shows the third time the session is requested from the SessionProvider it is indeed closed and not connected. I have verified that Dispose on my SessionFactoryProvider and on my SessionProvider are called at the end of the request and not before the Save call is made on my Dao. So now I'm a little stuck. A few things pop to mind. Am I doing anything obviously wrong? Does NHibernate ever close sessions without me asking to? Any workarounds or ideas on what I might do? Thanks in advance

    Read the article

  • Cleanup vs Dispose(bool) in MVVM-light

    - by Budda
    In the lastest version of MVVM-light (V3 SP1) both "Dispose()" and "Dipose(bool)" methods in ViewModel class are marked Do not use this method anymore, it will be removed in a future version. Use ICleanup.Cleanup() instead Does this mean that IDisposable interface must not be implemented in all ViewModel classes that are derived from GalaSoft.MvvmLight.ViewModelBase (and cleanup must be overrided)? If yes, using can't be used for view-model instances... Probably I didn't understand something... Please clarify... What are the benefits of such cleaning up? Thanks.

    Read the article

  • When and where to call the RemoveHandler in VB.NET?

    - by marco.ragogna
    I am working to a VB.NET windows forms projet in .NET 1.1. And I have this type of architecture, very simplified. Public MustInherit Class BaseTestLogic Private _TimerPoll As Timer Public Sub New(ByVal sym As SymbolFileMng, ByVal cfg As LampTestConfig, ByVal daas As DaasManager, ByVal mcf As Elux.Wg.Lpd.MCFs.VMCF) AddHandler _TimerPoll.Tick, AddressOf TimerPoll_Tick End Sub End Class Public Class SpecificTestLogic Inherits BaseTestLogic End Class Depending of the type of test I am doing I create an instance of a specific test derived from BaseTestLogic. But I found that after hundreds of object creations I can have StackOverflow exception. I checked my code and saw that I forgot to remove the handler to Timer Tick. The question is, where and when is it correct to remove hadler? Do I need to implement the IDisposable interface in the base class and RemoveHandler in Dispose?

    Read the article

  • Strange thing about .NET 4.0 filesystem enumeratation functionality

    - by codymanix
    I just read a page of "Whats new .NET Framework 4.0". I have trouble understanding the last paragraph: To remove open handles on enumerated directories or files Create a custom method (or function in Visual Basic) to contain your enumeration code. Apply the MethodImplAttribute attribute with the NoInlining option to the new method. For example: [MethodImplAttribute(MethodImplOptions.NoInlining)] Private void Enumerate() Include the following method calls, to run after your enumeration code: * The GC.Collect() method (no parameters). * The GC.WaitForPendingFinalizers() method. Why the attribute NoInlining? What harm would inlining do here? Why call the garbage collector manually, why not making the enumerator implement IDisposable in the first place? I suspect they use FindFirstFile()/FindNextFile() API calls for the imlementation, so FindClose() has to be called in any case if the enumeration is done.

    Read the article

  • working with generic lifetime managers in unity config section

    - by Martin Bailey
    I have the following generic lifetime manager public class RequestLifetimeManager<T> : LifetimeManager, IDisposable { public override object GetValue() { return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName]; } public override void RemoveValue() { HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName); } public override void SetValue(object newValue) { HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue; } public void Dispose() { RemoveValue(); } } How do I reference this in the unity config section. Creating a type alias <typeAlias alias="requestLifeTimeManager`1" type=" UI.Common.Unity.RequestLifetimeManager`1, UI.Common" /> and specifying it as a lifetime manager <types> <type type="[interface]" mapTo="[concretetype]" > <lifetime type="requestLifeTimeManager`1" /> </type> </types> causes the following error Cannot create an instance of UI.Common.Unity.RequestLifetimeManager`1[T] because Type.ContainsGenericParameters is true. How do you reference generic lifetime managers ?

    Read the article

  • Wanted a tool for decompiling obfuscated .NET code

    - by Shrike
    Hello. I need a tool to decompile obfuscated .NET code. Yes, I know about Reflector and its plugins (FileDisassemble, FileGenerator). But they create VS project which won't compile. For an example the decompiled code contains: private sealed class d__0 : IEnumerator, IEnumerator, IDisposable { private int <1__state; private int <2__current; I need a tool which could rename automatically such name into readable (read "compilable") form. Thnx.

    Read the article

  • Using WeakReference to resolve issue with .NET unregistered event handlers causing memory leaks.

    - by Eric
    The problem: Registered event handlers create a reference from the event to the event handler's instance. If that instance fails to unregister the event handler (via Dispose, presumably), then the instance memory will not be freed by the garbage collector. Example: class Foo { public event Action AnEvent; public void DoEvent() { if (AnEvent != null) AnEvent(); } } class Bar { public Bar(Foo l) { l.AnEvent += l_AnEvent; } void l_AnEvent() { } } If I instantiate a Foo, and pass this to a new Bar constructor, then let go of the Bar object, it will not be freed by the garbage collector because of the AnEvent registration. I consider this a memory leak, and seems just like my old C++ days. I can, of course, make Bar IDisposable, unregister the event in the Dispose() method, and make sure to call Dispose() on instances of it, but why should I have to do this? I first question why events are implemented with strong references? Why not use weak references? An event is used to abstractly notify an object of changes in another object. It seems to me that if the event handler's instance is no longer in use (i.e., there are no non-event references to the object), then any events that it is registered with should automatically be unregistered. What am I missing? I have looked at WeakEventManager. Wow, what a pain. Not only is it very difficult to use, but its documentation is inadequate (see http://msdn.microsoft.com/en-us/library/system.windows.weakeventmanager.aspx -- noticing the "Notes to Inheritors" section that has 6 vaguely described bullets). I have seen other discussions in various places, but nothing I felt I could use. I propose a simpler solution based on WeakReference, as described here. My question is: Does this not meet the requirements with significantly less complexity? To use the solution, the above code is modified as follows: class Foo { public WeakReferenceEvent AnEvent = new WeakReferenceEvent(); internal void DoEvent() { AnEvent.Invoke(); } } class Bar { public Bar(Foo l) { l.AnEvent += l_AnEvent; } void l_AnEvent() { } } Notice two things: 1. The Foo class is modified in two ways: The event is replaced with an instance of WeakReferenceEvent, shown below; and the invocation of the event is changed. 2. The Bar class is UNCHANGED. No need to subclass WeakEventManager, implement IWeakEventListener, etc. OK, so on to the implementation of WeakReferenceEvent. This is shown here. Note that it uses the generic WeakReference that I borrowed from here: http://damieng.com/blog/2006/08/01/implementingweakreferencet I had to add Equals() and GetHashCode() to his class, which I include below for reference. class WeakReferenceEvent { public static WeakReferenceEvent operator +(WeakReferenceEvent wre, Action handler) { wre._delegates.Add(new WeakReference<Action>(handler)); return wre; } public static WeakReferenceEvent operator -(WeakReferenceEvent wre, Action handler) { foreach (var del in wre._delegates) if (del.Target == handler) { wre._delegates.Remove(del); return wre; } return wre; } HashSet<WeakReference<Action>> _delegates = new HashSet<WeakReference<Action>>(); internal void Invoke() { HashSet<WeakReference<Action>> toRemove = null; foreach (var del in _delegates) { if (del.IsAlive) del.Target(); else { if (toRemove == null) toRemove = new HashSet<WeakReference<Action>>(); toRemove.Add(del); } } if (toRemove != null) foreach (var del in toRemove) _delegates.Remove(del); } } public class WeakReference<T> : IDisposable { private GCHandle handle; private bool trackResurrection; public WeakReference(T target) : this(target, false) { } public WeakReference(T target, bool trackResurrection) { this.trackResurrection = trackResurrection; this.Target = target; } ~WeakReference() { Dispose(); } public void Dispose() { handle.Free(); GC.SuppressFinalize(this); } public virtual bool IsAlive { get { return (handle.Target != null); } } public virtual bool TrackResurrection { get { return this.trackResurrection; } } public virtual T Target { get { object o = handle.Target; if ((o == null) || (!(o is T))) return default(T); else return (T)o; } set { handle = GCHandle.Alloc(value, this.trackResurrection ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak); } } public override bool Equals(object obj) { var other = obj as WeakReference<T>; return other != null && Target.Equals(other.Target); } public override int GetHashCode() { return Target.GetHashCode(); } } It's functionality is trivial. I override operator + and - to get the += and -= syntactic sugar matching events. These create WeakReferences to the Action delegate. This allows the garbage collector to free the event target object (Bar in this example) when nobody else is holding on to it. In the Invoke() method, simply run through the weak references and call their Target Action. If any dead (i.e., garbage collected) references are found, remove them from the list. Of course, this only works with delegates of type Action. I tried making this generic, but ran into the missing where T : delegate in C#! As an alternative, simply modify class WeakReferenceEvent to be a WeakReferenceEvent, and replace the Action with Action. Fix the compiler errors and you have a class that can be used like so: class Foo { public WeakReferenceEvent<int> AnEvent = new WeakReferenceEvent<int>(); internal void DoEvent() { AnEvent.Invoke(5); } } Hopefully this will help someone else when they run into the mystery .NET event memory leak!

    Read the article

  • Invoke "internal extern" constructor using reflections

    - by Riz
    Hi, I have following class (as seen through reflector) public class W : IDisposable { public W(string s); public W(string s, byte[] data); // more constructors [MethodImpl(MethodImplOptions.InternalCall)] internal extern W(string s, int i); public static W Func(string s, int i); } I am trying to call "internal extern" constructor or Func using reflections MethodInfo dynMethod = typeof(W).GetMethod("Func", BindingFlags.Static); object[] argVals = new object[] { "hi", 1 }; dynMethod.Invoke(null, argVals); and Type type = typeof(W); Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) }; ConstructorInfo cInfo = type.GetConstructor(BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, argTypes, null); object[] argVals = new object[] { "hi", 1 }; dynMethod.Invoke(null, argVals); unfortunantly both variants rise NullReferenceException when trying to Invoke, so, I must be doing something wrong?

    Read the article

  • FxCop CA2000 Warning in UserControls

    - by esjr
    Running FxCop on a WebProject that contains a UserControl will result in a CA2000 Warning (Call System.IDisposable.Dispose on object) for every ServerControl (Label, TextBox,...) in that UserControl. I understand why this would happen. Replacing the 'offending' ServerControls with a PlaceHolder and then adding the Controls in code (Using...End Using) might be a way around that, but it is not always an option.But, if they are not 'kosher' why have ServerControls you can drop in your ascx/aspx in the first place ?Am I missing something ? If, like in my case, you inherit a sizeable collection of fairly complex UserControls, do I now add every 'offending' Control to the GlobalSupperssions file (that's a lot of mind numbing right-clicking) ?I do not want to suppress all CA2000 warnings since it makes perfect sense to fix them, but not in the case of ServerControls in UserControls.

    Read the article

  • Disposing of Objects with long living dependencies

    - by Ray Booysen
    public class ABC { public ABC(IEventableInstance dependency) { dependency.ANewEvent += MyEventHandler; } private void MyEventHandler(object sender, EventArgs e) { //Do Stuff } } Let us say that an instance of ABC is a long living object and that my dependency is an even longer running object. When an instance of ABC needs to be cleaned up, I have two options. One I could have a Cleanup() method to unsubscribe from the ANewEvent event or I could implement IDisposable and in the Dispose unwire the event. Now I have no control over whether the consumer will call the dispose method or even the Cleanup method should I go that route. Should I implement a Finaliser and unsubscribe then? It feels dirty but I do not want hanging instances of ABC around. Thoughts?

    Read the article

  • How do I handle all the exceptions in a C# class where both ctor and finalizer throw exceptions?

    - by Frank
    How can I handle all exceptions for a class similar to the following under certain circumstances? class Test : IDisposable { public Test() { throw new Exception("Exception in ctor"); } public void Dispose() { throw new Exception("Exception in Dispose()"); } ~Test() { this.Dispose(); } } I tried this but it doesn't work: static void Main() { Test t = null; try { t = new Test(); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } // t is still null } I have also tried to use "using" but it does not handle the exception thrown from ~Test(); static void Main() { try { using (Test t = new Test()) { } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } Any ideas how can I work around?

    Read the article

  • C# how to correctly dispose of an SmtpClient?

    - by JL
    VS 2010 code analysis reports the following: Warning 4 CA2000 : Microsoft.Reliability : In method 'Mailer.SendMessage()', object 'client' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'client' before all references to it are out of scope. My code is : public void SendMessage() { SmtpClient client = new SmtpClient(); client.Send(Message); client.Dispose(); DisposeAttachments(); } How should I correctly dispose of client? Update: to answer Jons question, here is the dispose attachments functionality: private void DisposeAttachments() { foreach (Attachment attachment in Message.Attachments) { attachment.Dispose(); } Message.Attachments.Dispose(); Message = null; }

    Read the article

  • Strange thing about .NET 4.0 filesystem enumeration functionality

    - by codymanix
    I just read a page of "Whats new .NET Framework 4.0". I have trouble understanding the last paragraph: To remove open handles on enumerated directories or files Create a custom method (or function in Visual Basic) to contain your enumeration code. Apply the MethodImplAttribute attribute with the NoInlining option to the new method. For example: [MethodImplAttribute(MethodImplOptions.NoInlining)] Private void Enumerate() Include the following method calls, to run after your enumeration code: * The GC.Collect() method (no parameters). * The GC.WaitForPendingFinalizers() method. Why the attribute NoInlining? What harm would inlining do here? Why call the garbage collector manually, why not making the enumerator implement IDisposable in the first place? I suspect they use FindFirstFile()/FindNextFile() API calls for the imlementation, so FindClose() has to be called in any case if the enumeration is done.

    Read the article

  • overriding protected internal with protected!

    - by Asad Butt
    This is an extension for this question asked an hour ago. We cannot modify the access modifiers, when overriding a virtual method in derived class. Consider Control class in System.Web.UI namespace public class Control : IComponent, IDisposable,... { protected internal virtual void CreateChildControls() { } . . } Now Consider This public class someClass : System.Web.UI.Control { // This should not compile but it does protected override void CreateChildControls() { } // This should compile but it does not protected internal override void CreateChildControls() { } } can any body explain this ? Thanks

    Read the article

  • C#, weird optimization

    - by Snake
    Hi, I'm trying to read my compiled C# code. this is my code: using(OleDbCommand insertCommand = new OleDbCommand("...", connection)) { // do super stuff } But! We all know that a using gets translated to this: { OleDbCommand insertCommand = new OleDbCommand("...", connection) try { //do super stuff } finally { if(insertCommand != null) ((IDisposable)insertCommand).Dispose(); } } (since OleDbCommand is a reference type). But when I decompile my assembly (compiled with .NET 2.0) I get this in Resharper: try { insertCommand = new OleDbCommand("", connection); Label_0017: try { //do super stuff } finally { Label_0111: if ((insertCommand == null) != null) { goto Label_0122; } insertCommand.Dispose(); Label_0122:; } I'm talking about this line: if ((insertCommand == null) != null). True is not null, it never is, nor is false. So how is my object disposed properly? WTF? Thanks! -Kristof

    Read the article

  • How to determine whether a .NET exception is being handled?

    - by romkyns
    We're investigating a coding pattern in C# in which we'd like to use a "using" clause with a special class, whose Dispose() method does different things depending on whether the "using" body was exited normally or with an exception. To the best of my understanding, the CLR keeps track of the current exception being handled until it's been consumed by a "catch" handler. However it's not entirely clear whether this information is exposed in any way for the code to access. Do you know whether it is, and if so, how to access it? For example: using (var x = new MyObject()) { x.DoSomething(); x.DoMoreThings(); } class MyObject : IDisposable { public void Dispose() { if (ExceptionIsBeingHandled) Rollback(); else Commit(); } } This looks almost like System.Transactions.TransactionScope, except that success/failure is not determined by a call to x.Complete(), but rather based on whether the using body was exited normally.

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11  | Next Page >