Search Results

Search found 2166 results on 87 pages for 'obj'.

Page 11/87 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Objective-c memory management

    - by Chris
    I have a method which runs this: Track* track = [[Track alloc] init:[obj objectForKey:@"PersistentID"] :[obj objectForKey:@"Name"] :[obj objectForKey:@"Artist"] :(NSInteger*)[obj objectForKey:@"Total Time"] :(NSInteger*)[obj objectForKey:@"Play Count"]]; [self setCurrentTrack:(Track*) track]; [track release]; Do I have to release track?

    Read the article

  • Having trouble with a small example from school

    - by Kalec
    The example is from a course, it's for comparing two objects in java: public class Complex { ... public boolean equals (Object obj) { if (obj instanceof Complex) { // if obj is "Complex" (complex number) Complex c = (Complex) obj // No idea return (real == c.real) && (imag == c.imag); // I'm guessing real means [this].real } return false; } } So, my question is: "what does this: Complex c = (Complex) obj actually mean" ? Also I've worked with python and c++, java is new for me.

    Read the article

  • Pick random property from a Javascript object

    - by Bemmu
    Suppose you have a Javascript object like {'cat':'meow','dog':'woof' ...} Is there a more concise way to pick a random property from the object than this long winded way I came up with: function pickRandomProperty(obj) { var prop, len = 0, randomPos, pos = 0; for (prop in obj) { if (obj.hasOwnProperty(prop)) { len += 1; } } randomPos = Math.floor(Math.random() * len); for (prop in obj) { if (obj.hasOwnProperty(prop)) { if (pos === randomPos) { return prop; } pos += 1; } } }

    Read the article

  • VBScript: Passing Object to Function?

    - by ioplex
    The below example generates an error: VBScript compilation error: Cannot use parentheses when calling a Sub This error does not occur if all parameters are not objects. Is there a special way to pass object parameters to VBScript functions? Option Explicit Dim obj Function TestFunc(obj) WScript.Echo "Why doesn't this work?" End Function Set obj = CreateObject("Scripting.Dictionary") obj.Add("key", "val") TestFunc(obj) ' Error here!

    Read the article

  • How can a JSON object refer to values in itself?

    - by Erin Drummond
    Hi, Lets say I have the following javascript: var obj = { key1 : "it ", key2 : key1 + " works!" }; alert(obj.key2); This errors with "key1 is not defined". I have tried this.key1 this[key1] obj.key1 obj[key1] this["key1"] obj["key1"] and they never seem to be defined. How can I get key2 to refer to key1's value?

    Read the article

  • What is wrong with this code? [closed]

    - by rajesh
    function checkLength(obj,url){ //alert("URL="+url+" OBJ="+obj); if(obj) { var params = 'query='+obj; var myAjax = new Ajax.Request(url, { method: 'post', parameters: params, onComplete: loadResponse }); } } The code isn't working, but I don't know why. I think I need to include other files, but I don't know which

    Read the article

  • ajax functionality not working ???

    - by rajesh
    the problem is that 1)how can i come to know that the ajax is working properly?. 2)and how can i retrieve this sent data in controller in cakephp? function checkLength(obj,url){ alert("URL="+url+" OBJ="+obj); if(obj) { var params = 'query='+obj; var myAjax = new Ajax.Request(url,{method: 'post',parameters:params,onSuccess: loadResponse}); }

    Read the article

  • what is the wrong in the code ???

    - by rajesh
    function checkLength(obj,url){ //alert("URL="+url+" OBJ="+obj); if(obj) { var params = 'query='+obj; var myAjax = new Ajax.Request(url, { method: 'post', parameters: params, onComplete: loadResponse }); } } is nor working why i think there is requirement of include some files in it.which is that??/

    Read the article

  • LINQ: Enhancing Distinct With The SelectorEqualityComparer

    - by Paulo Morgado
    On my last post, I introduced the PredicateEqualityComparer and a Distinct extension method that receives a predicate to internally create a PredicateEqualityComparer to filter elements. Using the predicate, greatly improves readability, conciseness and expressiveness of the queries, but it can be even better. Most of the times, we don’t want to provide a comparison method but just to extract the comaprison key for the elements. So, I developed a SelectorEqualityComparer that takes a method that extracts the key value for each element. Something like this: public class SelectorEqualityComparer<TSource, Tkey> : EqualityComparer<TSource> where Tkey : IEquatable<Tkey> { private Func<TSource, Tkey> selector; public SelectorEqualityComparer(Func<TSource, Tkey> selector) : base() { this.selector = selector; } public override bool Equals(TSource x, TSource y) { Tkey xKey = this.GetKey(x); Tkey yKey = this.GetKey(y); if (xKey != null) { return ((yKey != null) && xKey.Equals(yKey)); } return (yKey == null); } public override int GetHashCode(TSource obj) { Tkey key = this.GetKey(obj); return (key == null) ? 0 : key.GetHashCode(); } public override bool Equals(object obj) { SelectorEqualityComparer<TSource, Tkey> comparer = obj as SelectorEqualityComparer<TSource, Tkey>; return (comparer != null); } public override int GetHashCode() { return base.GetType().Name.GetHashCode(); } private Tkey GetKey(TSource obj) { return (obj == null) ? (Tkey)(object)null : this.selector(obj); } } Now I can write code like this: .Distinct(new SelectorEqualityComparer<Source, Key>(x => x.Field)) And, for improved readability, conciseness and expressiveness and support for anonymous types the corresponding Distinct extension method: public static IEnumerable<TSource> Distinct<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IEquatable<TKey> { return source.Distinct(new SelectorEqualityComparer<TSource, TKey>(selector)); } And the query is now written like this: .Distinct(x => x.Field) For most usages, it’s simpler than using a predicate.

    Read the article

  • fmod VS2008 unresolved externals in dependant project

    - by Tom J Nowell
    Im currently trying to use the latest stable fmod ex in my project. I have a main executable in a project called engine4, and a project named DX9Platform in the solution as well which ti depends on. All the fmod code is in this DX9Platform project, which generates a lib file. DX9Platform includes fmodex_vc.lib and builds fine. However buildign Engien4 results in unresolved external symbol messages referencing files that use fmod in the DX9Platform project I have tried adding fmodex_vc.lib to the Engine4 project, with no success, how do I fix this? Heres the linker output: 3>------ Build started: Project: Engine4, Configuration: Release Direct3D9 Win32 ------ 3>Linking... 3>DX9PlatformLib.lib(CFmodSound.obj) : error LNK2001: unresolved external symbol _FMOD_System_Create 3>DX9PlatformLib.lib(CFmodSound.obj) : error LNK2001: unresolved external symbol "public: enum FMOD_RESULT __thiscall FMOD::System::createSound(char const *,unsigned int,struct FMOD_CREATESOUNDEXINFO *,class FMOD::Sound * *)" (?createSound@System@FMOD@@QAE?AW4FMOD_RESULT@@PBDIPAUFMOD_CREATESOUNDEXINFO@@PAPAVSound@2@@Z) 3>DX9PlatformLib.lib(CFmodSound.obj) : error LNK2001: unresolved external symbol "public: enum FMOD_RESULT __thiscall FMOD::System::getVersion(unsigned int *)" (?getVersion@System@FMOD@@QAE?AW4FMOD_RESULT@@PAI@Z) 3>DX9PlatformLib.lib(CFmodSound.obj) : error LNK2001: unresolved external symbol "public: enum FMOD_RESULT __thiscall FMOD::System::init(int,unsigned int,void *)" (?init@System@FMOD@@QAE?AW4FMOD_RESULT@@HIPAX@Z) 3>DX9PlatformLib.lib(CFModAudioObject.obj) : error LNK2001: unresolved external symbol "public: enum FMOD_RESULT __thiscall FMOD::System::playSound(enum FMOD_CHANNELINDEX,class FMOD::Sound *,bool,class FMOD::Channel * *)" (?playSound@System@FMOD@@QAE?AW4FMOD_RESULT@@W4FMOD_CHANNELINDEX@@PAVSound@2@_NPAPAVChannel@2@@Z) 3>DX9PlatformLib.lib(CFModAudioObject.obj) : error LNK2001: unresolved external symbol "public: enum FMOD_RESULT __thiscall FMOD::Channel::getPaused(bool *)" (?getPaused@Channel@FMOD@@QAE?AW4FMOD_RESULT@@PA_N@Z) 3>DX9PlatformLib.lib(CFModAudioObject.obj) : error LNK2001: unresolved external symbol "public: enum FMOD_RESULT __thiscall FMOD::Channel::setPaused(bool)" (?setPaused@Channel@FMOD@@QAE?AW4FMOD_RESULT@@_N@Z) 3>DX9PlatformLib.lib(CFModAudioObject.obj) : error LNK2001: unresolved external symbol "public: virtual class IAudioObject * __thiscall CFModAudioObject::LoadFile(char const *)" (?LoadFile@CFModAudioObject@@UAEPAVIAudioObject@@PBD@Z) 3>D:\media\desktop\engine4\Engine4\Output\Release Direct3D9\Engine4.exe : fatal error LNK1120: 8 unresolved externals 3>Build log was saved at "file://d:\media\desktop\engine4\Engine4\Engine4\intermediate\Release Direct3D9\BuildLog.htm" 3>Engine4 - 9 error(s), 0 warning(s) ========== Build: 1 succeeded, 1 failed, 0 up-to-date, 1 skipped ==========

    Read the article

  • FLTK Images (Using Cmake)

    - by Cenoc
    I'm trying to load and manipulate a jpeg file using FLTK compiled using cmake... but I get the following errors: 2LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_read_scanlines referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_start_decompress referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_calc_output_dimensions referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_read_header referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_stdio_src referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_CreateDecompress referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_destroy_decompress referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_finish_decompress referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) I hate these linking errors..... can anyone help? Thank you in advance.

    Read the article

  • Self referencing userdata and garbage collection

    - by drtwox
    Because my userdata objects reference themselves, I need to delete and nil a variable for the garbage collector to work. Lua code: obj = object:new() -- -- Some time later obj:delete() -- Removes the self reference obj = nil -- Ready for collection C Code: typedef struct { int self; // Reference to the object // Other members and function references removed } Object; // Called from Lua to create a new object static int object_new( lua_State *L ) { Object *obj = lua_newuserdata( L, sizeof( Object ) ); // Create the 'self' reference, userdata is on the stack top obj->self = luaL_ref( L, LUA_REGISTRYINDEX ); // Put the userdata back on the stack before returning lua_rawgeti( L, LUA_REGISTRYINDEX, obj->self ); // The object pointer is also stored outside of Lua for processing in C return 1; } // Called by Lua to delete an object static int object_delete( lua_State *L ) { Object *obj = lua_touserdata( L, 1 ); // Remove the objects self reference luaL_unref( L, LUA_REGISTRYINDEX, obj->self ); return 0; } Is there some way I can set the object to nil in Lua, and have the delete() method called automatically? Alternatively, can the delete method nil all variables that reference the object? Can the self reference be made 'weak'?

    Read the article

  • call back function set by JS settimeout doesn't work in IE8....

    - by NAG
    <html <head <script function addEvent( obj, type, fn ) { if ( obj.attachEvent ) { obj['e'+type+fn] = fn; obj[type+fn] = function(){obj['e'+type+fn]( window.event );} obj.attachEvent( 'on'+type, obj[type+fn] ); } else obj.addEventListener( type, fn, false ); } </script </head <body <!-- HTML for example event goes here -- <div id="mydiv" style="border: 1px solid black; width: 100px; height: 100px; margin-top: 10px;"</div <script // Script for example event goes here addEvent(document.getElementById('mydiv'), 'contextmenu', function(event) { display_short('right-clicked (contextmenu)'); }); function display_short(str) { clearTimeout(); document.getElementById('mydiv').innerHTML = str; if (str != '') alert("hello"); setTimeout("display_short('abcd')", 1000); } </script </body </html Behaves diffrently in IE and FF when you right click on the div area. In ff display_short will be called for evry 1 sec eventhough you dont release right click but in IE it will not call display_short if you dont release right click. But i expect in IE it should call display_short for every 1 sec if you dont release also. Is there any solution for this?

    Read the article

  • C#. Saving information about events and event handlers and removing handlers using this information

    - by Philipp
    I have an object which is creating several event handlers using lambda expressions, and I need to remove all handlers created in that object in one time. I'm trying to create some unified static object which will 'know' which handler relates to which object and event if event handler was created through this static object. I tried something like code below, but I don't understand how to save events and event handlers objects, to be able remove handlers in one time. class Program { static void Main(string[] args) { var EventSender = new EventSender(); var EventReceiver = new EventReceiver(EventSender); EventSender.Invoke(" some var "); LinkSaver.RemoveEvent(EventReceiver); // ?? Console.ReadKey(); } } public class ObjLink{ public object Event; public object Action; } public static class LinkSaver { public static void SetEvent<T>(object obj, Action<T> Event, T Action) { Event(Action); var objLink = new ObjLink{Event = Event, Action = Action}; if (!Links.ContainsKey(obj)) Links.Add(obj, new List<ObjLink>{objLink}); else Links[obj].Add(objLink); } static Dictionary<object,List<ObjLink>> Links = new Dictionary<object, List<ObjLink>>(); public static void RemoveEvent(object obj){ foreach(var objLink in Links[obj]){ // objLink.Event -= objLink.Action; ??? } } } public class EventReceiver { public EventReceiver(EventSender obj) { LinkSaver.SetEvent<EventSender.TestDelegate>(this, obj.SetEvent, str => Console.WriteLine(str + " test event!")); } } public class EventSender { public void Invoke(string var) { if (eventTest != null) eventTest(var); } public void SetEvent(TestDelegate Action) { eventTest += Action; } public delegate void TestDelegate(string var); private event TestDelegate eventTest; // by the way public void RemoveFromEvent() { foreach (var handler in eventTest.GetInvocationList()) eventTest -= (TestDelegate)handler; } }

    Read the article

  • NHibernate Entity code conversion from #C to VB.Net

    - by CoderRoller
    Hello and thanks for your help in advance. I am starting on the NHibernate world and i am experimenting with the NHibernate CookBook recipes, i am trying to set a base entity class for my entities and this is the C# code for this. I would like to know whats the VB.NET version so i can implement it in my sample project. This is the C# code: public abstract class Entity<TId> { public virtual TId Id { get; protected set; } public override bool Equals(object obj) { return Equals(obj as Entity<TId>); } private static bool IsTransient(Entity<TId> obj) { return obj != null && Equals(obj.Id, default(TId)); } private Type GetUnproxiedType() { return GetType(); } public virtual bool Equals(Entity<TId> other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; if (!IsTransient(this) && !IsTransient(other) && Equals(Id, other.Id)) { var otherType = other.GetUnproxiedType(); var thisType = GetUnproxiedType(); return thisType.IsAssignableFrom(otherType) || otherType.IsAssignableFrom(thisType); } return false; } public override int GetHashCode() { if (Equals(Id, default(TId))) return base.GetHashCode(); return Id.GetHashCode(); } } I tried using an online converter but puts a Nothing reference in place of default(TId) that doesn't seem right to me that's why I request for help: Private Shared Function IsTransient(obj As Entity(Of TId)) As Boolean Return obj IsNot Nothing AndAlso Equals(obj.Id, Nothing) End Function I Would appreciate the insight you may give me on the subject.

    Read the article

  • Why unhandled exceptions are useful

    - by Simon Cooper
    It’s the bane of most programmers’ lives – an unhandled exception causes your application or webapp to crash, an ugly dialog gets displayed to the user, and they come complaining to you. Then, somehow, you need to figure out what went wrong. Hopefully, you’ve got a log file, or some other way of reporting unhandled exceptions (obligatory employer plug: SmartAssembly reports an application’s unhandled exceptions straight to you, along with the entire state of the stack and variables at that point). If not, you have to try and replicate it yourself, or do some psychic debugging to try and figure out what’s wrong. However, it’s good that the program crashed. Or, more precisely, it is correct behaviour. An unhandled exception in your application means that, somewhere in your code, there is an assumption that you made that is actually invalid. Coding assumptions Let me explain a bit more. Every method, every line of code you write, depends on implicit assumptions that you have made. Take this following simple method, that copies a collection to an array and includes an item if it isn’t in the collection already, using a supplied IEqualityComparer: public static T[] ToArrayWithItem( ICollection<T> coll, T obj, IEqualityComparer<T> comparer) { // check if the object is in collection already // using the supplied comparer foreach (var item in coll) { if (comparer.Equals(item, obj)) { // it's in the collection already // simply copy the collection to an array // and return it T[] array = new T[coll.Count]; coll.CopyTo(array, 0); return array; } } // not in the collection // copy coll to an array, and add obj to it // then return it T[] array = new T[coll.Count+1]; coll.CopyTo(array, 0); array[array.Length-1] = obj; return array; } What’s all the assumptions made by this fairly simple bit of code? coll is never null comparer is never null coll.CopyTo(array, 0) will copy all the items in the collection into the array, in the order defined for the collection, starting at the first item in the array. The enumerator for coll returns all the items in the collection, in the order defined for the collection comparer.Equals returns true if the items are equal (for whatever definition of ‘equal’ the comparer uses), false otherwise comparer.Equals, coll.CopyTo, and the coll enumerator will never throw an exception or hang for any possible input and any possible values of T coll will have less than 4 billion items in it (this is a built-in limit of the CLR) array won’t be more than 2GB, both on 32 and 64-bit systems, for any possible values of T (again, a limit of the CLR) There are no threads that will modify coll while this method is running and, more esoterically: The C# compiler will compile this code to IL according to the C# specification The CLR and JIT compiler will produce machine code to execute the IL on the user’s computer The computer will execute the machine code correctly That’s a lot of assumptions. Now, it could be that all these assumptions are valid for the situations this method is called. But if this does crash out with an exception, or crash later on, then that shows one of the assumptions has been invalidated somehow. An unhandled exception shows that your code is running in a situation which you did not anticipate, and there is something about how your code runs that you do not understand. Debugging the problem is the process of learning more about the new situation and how your code interacts with it. When you understand the problem, the solution is (usually) obvious. The solution may be a one-line fix, the rewrite of a method or class, or a large-scale refactoring of the codebase, but whatever it is, the fix for the crash will incorporate the new information you’ve gained about your own code, along with the modified assumptions. When code is running with an assumption or invariant it depended on broken, then the result is ‘undefined behaviour’. Anything can happen, up to and including formatting the entire disk or making the user’s computer sentient and start doing a good impression of Skynet. You might think that those can’t happen, but at Halting problem levels of generality, as soon as an assumption the code depended on is broken, the program can do anything. That is why it’s important to fail-fast and stop the program as soon as an invariant is broken, to minimise the damage that is done. What does this mean in practice? To start with, document and check your assumptions. As with most things, there is a level of judgement required. How you check and document your assumptions depends on how the code is used (that’s some more assumptions you’ve made), how likely it is a method will be passed invalid arguments or called in an invalid state, how likely it is the assumptions will be broken, how expensive it is to check the assumptions, and how bad things are likely to get if the assumptions are broken. Now, some assumptions you can assume unless proven otherwise. You can safely assume the C# compiler, CLR, and computer all run the method correctly, unless you have evidence of a compiler, CLR or processor bug. You can also assume that interface implementations work the way you expect them to; implementing an interface is more than simply declaring methods with certain signatures in your type. The behaviour of those methods, and how they work, is part of the interface contract as well. For example, for members of a public API, it is very important to document your assumptions and check your state before running the bulk of the method, throwing ArgumentException, ArgumentNullException, InvalidOperationException, or another exception type as appropriate if the input or state is wrong. For internal and private methods, it is less important. If a private method expects collection items in a certain order, then you don’t necessarily need to explicitly check it in code, but you can add comments or documentation specifying what state you expect the collection to be in at a certain point. That way, anyone debugging your code can immediately see what’s wrong if this does ever become an issue. You can also use DEBUG preprocessor blocks and Debug.Assert to document and check your assumptions without incurring a performance hit in release builds. On my coding soapbox… A few pet peeves of mine around assumptions. Firstly, catch-all try blocks: try { ... } catch { } A catch-all hides exceptions generated by broken assumptions, and lets the program carry on in an unknown state. Later, an exception is likely to be generated due to further broken assumptions due to the unknown state, causing difficulties when debugging as the catch-all has hidden the original problem. It’s much better to let the program crash straight away, so you know where the problem is. You should only use a catch-all if you are sure that any exception generated in the try block is safe to ignore. That’s a pretty big ask! Secondly, using as when you should be casting. Doing this: (obj as IFoo).Method(); or this: IFoo foo = obj as IFoo; ... foo.Method(); when you should be doing this: ((IFoo)obj).Method(); or this: IFoo foo = (IFoo)obj; ... foo.Method(); There’s an assumption here that obj will always implement IFoo. If it doesn’t, then by using as instead of a cast you’ve turned an obvious InvalidCastException at the point of the cast that will probably tell you what type obj actually is, into a non-obvious NullReferenceException at some later point that gives you no information at all. If you believe obj is always an IFoo, then say so in code! Let it fail-fast if not, then it’s far easier to figure out what’s wrong. Thirdly, document your assumptions. If an algorithm depends on a non-trivial relationship between several objects or variables, then say so. A single-line comment will do. Don’t leave it up to whoever’s debugging your code after you to figure it out. Conclusion It’s better to crash out and fail-fast when an assumption is broken. If it doesn’t, then there’s likely to be further crashes along the way that hide the original problem. Or, even worse, your program will be running in an undefined state, where anything can happen. Unhandled exceptions aren’t good per-se, but they give you some very useful information about your code that you didn’t know before. And that can only be a good thing.

    Read the article

  • Silverlight Recruiting Application Part 5 - Jobs Module / View

    Now we starting getting into a more code-heavy portion of this series, thankfully though this means the groundwork is all set for the most part and after adding the modules we will have a complete application that can be provided with full source. The Jobs module will have two concerns- adding and maintaining jobs that can then be broadcast out to the website. How they are displayed on the site will be handled by our admin system (which will just poll from this common database), so we aren't too concerned with that, but rather with getting the information into the system and allowing the backend administration/HR users to keep things up to date. Since there is a fair bit of information that we want to display, we're going to move editing to a separate view so we can get all that information in an easy-to-use spot. With all the files created for this module, the project looks something like this: And now... on to the code. XAML for the Job Posting View All we really need for the Job Posting View is a RadGridView and a few buttons. This will let us both show off records and perform operations on the records without much hassle. That XAML is going to look something like this: 01.<Grid x:Name="LayoutRoot" 02.Background="White"> 03.<Grid.RowDefinitions> 04.<RowDefinition Height="30" /> 05.<RowDefinition /> 06.</Grid.RowDefinitions> 07.<StackPanel Orientation="Horizontal"> 08.<Button x:Name="xAddRecordButton" 09.Content="Add Job" 10.Width="120" 11.cal:Click.Command="{Binding AddRecord}" 12.telerik:StyleManager.Theme="Windows7" /> 13.<Button x:Name="xEditRecordButton" 14.Content="Edit Job" 15.Width="120" 16.cal:Click.Command="{Binding EditRecord}" 17.telerik:StyleManager.Theme="Windows7" /> 18.</StackPanel> 19.<telerikGrid:RadGridView x:Name="xJobsGrid" 20.Grid.Row="1" 21.IsReadOnly="True" 22.AutoGenerateColumns="False" 23.ColumnWidth="*" 24.RowDetailsVisibilityMode="VisibleWhenSelected" 25.ItemsSource="{Binding MyJobs}" 26.SelectedItem="{Binding SelectedJob, Mode=TwoWay}" 27.command:SelectedItemChangedEventClass.Command="{Binding SelectedItemChanged}"> 28.<telerikGrid:RadGridView.Columns> 29.<telerikGrid:GridViewDataColumn Header="Job Title" 30.DataMemberBinding="{Binding JobTitle}" 31.UniqueName="JobTitle" /> 32.<telerikGrid:GridViewDataColumn Header="Location" 33.DataMemberBinding="{Binding Location}" 34.UniqueName="Location" /> 35.<telerikGrid:GridViewDataColumn Header="Resume Required" 36.DataMemberBinding="{Binding NeedsResume}" 37.UniqueName="NeedsResume" /> 38.<telerikGrid:GridViewDataColumn Header="CV Required" 39.DataMemberBinding="{Binding NeedsCV}" 40.UniqueName="NeedsCV" /> 41.<telerikGrid:GridViewDataColumn Header="Overview Required" 42.DataMemberBinding="{Binding NeedsOverview}" 43.UniqueName="NeedsOverview" /> 44.<telerikGrid:GridViewDataColumn Header="Active" 45.DataMemberBinding="{Binding IsActive}" 46.UniqueName="IsActive" /> 47.</telerikGrid:RadGridView.Columns> 48.</telerikGrid:RadGridView> 49.</Grid> I'll explain what's happening here by line numbers: Lines 11 and 16: Using the same type of click commands as we saw in the Menu module, we tie the button clicks to delegate commands in the viewmodel. Line 25: The source for the jobs will be a collection in the viewmodel. Line 26: We also bind the selected item to a public property from the viewmodel for use in code. Line 27: We've turned the event into a command so we can handle it via code in the viewmodel. So those first three probably make sense to you as far as Silverlight/WPF binding magic is concerned, but for line 27... This actually comes from something I read onDamien Schenkelman's blog back in the day for creating an attached behavior from any event. So, any time you see me using command:Whatever.Command, the backing for it is actually something like this: SelectedItemChangedEventBehavior.cs: 01.public class SelectedItemChangedEventBehavior : CommandBehaviorBase<Telerik.Windows.Controls.DataControl> 02.{ 03.public SelectedItemChangedEventBehavior(DataControl element) 04.: base(element) 05.{ 06.element.SelectionChanged += new EventHandler<SelectionChangeEventArgs>(element_SelectionChanged); 07.} 08.void element_SelectionChanged(object sender, SelectionChangeEventArgs e) 09.{ 10.// We'll only ever allow single selection, so will only need item index 0 11.base.CommandParameter = e.AddedItems[0]; 12.base.ExecuteCommand(); 13.} 14.} SelectedItemChangedEventClass.cs: 01.public class SelectedItemChangedEventClass 02.{ 03.#region The Command Stuff 04.public static ICommand GetCommand(DependencyObject obj) 05.{ 06.return (ICommand)obj.GetValue(CommandProperty); 07.} 08.public static void SetCommand(DependencyObject obj, ICommand value) 09.{ 10.obj.SetValue(CommandProperty, value); 11.} 12.public static readonly DependencyProperty CommandProperty = 13.DependencyProperty.RegisterAttached("Command", typeof(ICommand), 14.typeof(SelectedItemChangedEventClass), new PropertyMetadata(OnSetCommandCallback)); 15.public static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) 16.{ 17.DataControl element = dependencyObject as DataControl; 18.if (element != null) 19.{ 20.SelectedItemChangedEventBehavior behavior = GetOrCreateBehavior(element); 21.behavior.Command = e.NewValue as ICommand; 22.} 23.} 24.#endregion 25.public static SelectedItemChangedEventBehavior GetOrCreateBehavior(DataControl element) 26.{ 27.SelectedItemChangedEventBehavior behavior = element.GetValue(SelectedItemChangedEventBehaviorProperty) as SelectedItemChangedEventBehavior; 28.if (behavior == null) 29.{ 30.behavior = new SelectedItemChangedEventBehavior(element); 31.element.SetValue(SelectedItemChangedEventBehaviorProperty, behavior); 32.} 33.return behavior; 34.} 35.public static SelectedItemChangedEventBehavior GetSelectedItemChangedEventBehavior(DependencyObject obj) 36.{ 37.return (SelectedItemChangedEventBehavior)obj.GetValue(SelectedItemChangedEventBehaviorProperty); 38.} 39.public static void SetSelectedItemChangedEventBehavior(DependencyObject obj, SelectedItemChangedEventBehavior value) 40.{ 41.obj.SetValue(SelectedItemChangedEventBehaviorProperty, value); 42.} 43.public static readonly DependencyProperty SelectedItemChangedEventBehaviorProperty = 44.DependencyProperty.RegisterAttached("SelectedItemChangedEventBehavior", 45.typeof(SelectedItemChangedEventBehavior), typeof(SelectedItemChangedEventClass), null); 46.} These end up looking very similar from command to command, but in a nutshell you create a command based on any event, determine what the parameter for it will be, then execute. It attaches via XAML and ties to a DelegateCommand in the viewmodel, so you get the full event experience (since some controls get a bit event-rich for added functionality). Simple enough, right? Viewmodel for the Job Posting View The Viewmodel is going to need to handle all events going back and forth, maintaining interactions with the data we are using, and both publishing and subscribing to events. Rather than breaking this into tons of little pieces, I'll give you a nice view of the entire viewmodel and then hit up the important points line-by-line: 001.public class JobPostingViewModel : ViewModelBase 002.{ 003.private readonly IEventAggregator eventAggregator; 004.private readonly IRegionManager regionManager; 005.public DelegateCommand<object> AddRecord { get; set; } 006.public DelegateCommand<object> EditRecord { get; set; } 007.public DelegateCommand<object> SelectedItemChanged { get; set; } 008.public RecruitingContext context; 009.private QueryableCollectionView _myJobs; 010.public QueryableCollectionView MyJobs 011.{ 012.get { return _myJobs; } 013.} 014.private QueryableCollectionView _selectionJobActionHistory; 015.public QueryableCollectionView SelectedJobActionHistory 016.{ 017.get { return _selectionJobActionHistory; } 018.} 019.private JobPosting _selectedJob; 020.public JobPosting SelectedJob 021.{ 022.get { return _selectedJob; } 023.set 024.{ 025.if (value != _selectedJob) 026.{ 027._selectedJob = value; 028.NotifyChanged("SelectedJob"); 029.} 030.} 031.} 032.public SubscriptionToken editToken = new SubscriptionToken(); 033.public SubscriptionToken addToken = new SubscriptionToken(); 034.public JobPostingViewModel(IEventAggregator eventAgg, IRegionManager regionmanager) 035.{ 036.// set Unity items 037.this.eventAggregator = eventAgg; 038.this.regionManager = regionmanager; 039.// load our context 040.context = new RecruitingContext(); 041.this._myJobs = new QueryableCollectionView(context.JobPostings); 042.context.Load(context.GetJobPostingsQuery()); 043.// set command events 044.this.AddRecord = new DelegateCommand<object>(this.AddNewRecord); 045.this.EditRecord = new DelegateCommand<object>(this.EditExistingRecord); 046.this.SelectedItemChanged = new DelegateCommand<object>(this.SelectedRecordChanged); 047.SetSubscriptions(); 048.} 049.#region DelegateCommands from View 050.public void AddNewRecord(object obj) 051.{ 052.this.eventAggregator.GetEvent<AddJobEvent>().Publish(true); 053.} 054.public void EditExistingRecord(object obj) 055.{ 056.if (_selectedJob == null) 057.{ 058.this.eventAggregator.GetEvent<NotifyUserEvent>().Publish("No job selected."); 059.} 060.else 061.{ 062.this._myJobs.EditItem(this._selectedJob); 063.this.eventAggregator.GetEvent<EditJobEvent>().Publish(this._selectedJob); 064.} 065.} 066.public void SelectedRecordChanged(object obj) 067.{ 068.if (obj.GetType() == typeof(ActionHistory)) 069.{ 070.// event bubbles up so we don't catch items from the ActionHistory grid 071.} 072.else 073.{ 074.JobPosting job = obj as JobPosting; 075.GrabHistory(job.PostingID); 076.} 077.} 078.#endregion 079.#region Subscription Declaration and Events 080.public void SetSubscriptions() 081.{ 082.EditJobCompleteEvent editComplete = eventAggregator.GetEvent<EditJobCompleteEvent>(); 083.if (editToken != null) 084.editComplete.Unsubscribe(editToken); 085.editToken = editComplete.Subscribe(this.EditCompleteEventHandler); 086.AddJobCompleteEvent addComplete = eventAggregator.GetEvent<AddJobCompleteEvent>(); 087.if (addToken != null) 088.addComplete.Unsubscribe(addToken); 089.addToken = addComplete.Subscribe(this.AddCompleteEventHandler); 090.} 091.public void EditCompleteEventHandler(bool complete) 092.{ 093.if (complete) 094.{ 095.JobPosting thisJob = _myJobs.CurrentEditItem as JobPosting; 096.this._myJobs.CommitEdit(); 097.this.context.SubmitChanges((s) => 098.{ 099.ActionHistory myAction = new ActionHistory(); 100.myAction.PostingID = thisJob.PostingID; 101.myAction.Description = String.Format("Job '{0}' has been edited by {1}", thisJob.JobTitle, "default user"); 102.myAction.TimeStamp = DateTime.Now; 103.eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 104.} 105., null); 106.} 107.else 108.{ 109.this._myJobs.CancelEdit(); 110.} 111.this.MakeMeActive(this.regionManager, "MainRegion", "JobPostingsView"); 112.} 113.public void AddCompleteEventHandler(JobPosting job) 114.{ 115.if (job == null) 116.{ 117.// do nothing, new job add cancelled 118.} 119.else 120.{ 121.this.context.JobPostings.Add(job); 122.this.context.SubmitChanges((s) => 123.{ 124.ActionHistory myAction = new ActionHistory(); 125.myAction.PostingID = job.PostingID; 126.myAction.Description = String.Format("Job '{0}' has been added by {1}", job.JobTitle, "default user"); 127.myAction.TimeStamp = DateTime.Now; 128.eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 129.} 130., null); 131.} 132.this.MakeMeActive(this.regionManager, "MainRegion", "JobPostingsView"); 133.} 134.#endregion 135.public void GrabHistory(int postID) 136.{ 137.context.ActionHistories.Clear(); 138._selectionJobActionHistory = new QueryableCollectionView(context.ActionHistories); 139.context.Load(context.GetHistoryForJobQuery(postID)); 140.} Taking it from the top, we're injecting an Event Aggregator and Region Manager for use down the road and also have the public DelegateCommands (just like in the Menu module). We also grab a reference to our context, which we'll obviously need for data, then set up a few fields with public properties tied to them. We're also setting subscription tokens, which we have not yet seen but I will get into below. The AddNewRecord (50) and EditExistingRecord (54) methods should speak for themselves for functionality, the one thing of note is we're sending events off to the Event Aggregator which some module, somewhere will take care of. Since these aren't entirely relying on one another, the Jobs View doesn't care if anyone is listening, but it will publish AddJobEvent (52), NotifyUserEvent (58) and EditJobEvent (63)regardless. Don't mind the GrabHistory() method so much, that is just grabbing history items (visibly being created in the SubmitChanges callbacks), and adding them to the database. Every action will trigger a history event, so we'll know who modified what and when, just in case. ;) So where are we at? Well, if we click to Add a job, we publish an event, if we edit a job, we publish an event with the selected record (attained through the magic of binding). Where is this all going though? To the Viewmodel, of course! XAML for the AddEditJobView This is pretty straightforward except for one thing, noted below: 001.<Grid x:Name="LayoutRoot" 002.Background="White"> 003.<Grid x:Name="xEditGrid" 004.Margin="10" 005.validationHelper:ValidationScope.Errors="{Binding Errors}"> 006.<Grid.Background> 007.<LinearGradientBrush EndPoint="0.5,1" 008.StartPoint="0.5,0"> 009.<GradientStop Color="#FFC7C7C7" 010.Offset="0" /> 011.<GradientStop Color="#FFF6F3F3" 012.Offset="1" /> 013.</LinearGradientBrush> 014.</Grid.Background> 015.<Grid.RowDefinitions> 016.<RowDefinition Height="40" /> 017.<RowDefinition Height="40" /> 018.<RowDefinition Height="40" /> 019.<RowDefinition Height="100" /> 020.<RowDefinition Height="100" /> 021.<RowDefinition Height="100" /> 022.<RowDefinition Height="40" /> 023.<RowDefinition Height="40" /> 024.<RowDefinition Height="40" /> 025.</Grid.RowDefinitions> 026.<Grid.ColumnDefinitions> 027.<ColumnDefinition Width="150" /> 028.<ColumnDefinition Width="150" /> 029.<ColumnDefinition Width="300" /> 030.<ColumnDefinition Width="100" /> 031.</Grid.ColumnDefinitions> 032.<!-- Title --> 033.<TextBlock Margin="8" 034.Text="{Binding AddEditString}" 035.TextWrapping="Wrap" 036.Grid.Column="1" 037.Grid.ColumnSpan="2" 038.FontSize="16" /> 039.<!-- Data entry area--> 040. 041.<TextBlock Margin="8,0,0,0" 042.Style="{StaticResource LabelTxb}" 043.Grid.Row="1" 044.Text="Job Title" 045.VerticalAlignment="Center" /> 046.<TextBox x:Name="xJobTitleTB" 047.Margin="0,8" 048.Grid.Column="1" 049.Grid.Row="1" 050.Text="{Binding activeJob.JobTitle, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 051.Grid.ColumnSpan="2" /> 052.<TextBlock Margin="8,0,0,0" 053.Grid.Row="2" 054.Text="Location" 055.d:LayoutOverrides="Height" 056.VerticalAlignment="Center" /> 057.<TextBox x:Name="xLocationTB" 058.Margin="0,8" 059.Grid.Column="1" 060.Grid.Row="2" 061.Text="{Binding activeJob.Location, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 062.Grid.ColumnSpan="2" /> 063. 064.<TextBlock Margin="8,11,8,0" 065.Grid.Row="3" 066.Text="Description" 067.TextWrapping="Wrap" 068.VerticalAlignment="Top" /> 069. 070.<TextBox x:Name="xDescriptionTB" 071.Height="84" 072.TextWrapping="Wrap" 073.ScrollViewer.VerticalScrollBarVisibility="Auto" 074.Grid.Column="1" 075.Grid.Row="3" 076.Text="{Binding activeJob.Description, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 077.Grid.ColumnSpan="2" /> 078.<TextBlock Margin="8,11,8,0" 079.Grid.Row="4" 080.Text="Requirements" 081.TextWrapping="Wrap" 082.VerticalAlignment="Top" /> 083. 084.<TextBox x:Name="xRequirementsTB" 085.Height="84" 086.TextWrapping="Wrap" 087.ScrollViewer.VerticalScrollBarVisibility="Auto" 088.Grid.Column="1" 089.Grid.Row="4" 090.Text="{Binding activeJob.Requirements, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 091.Grid.ColumnSpan="2" /> 092.<TextBlock Margin="8,11,8,0" 093.Grid.Row="5" 094.Text="Qualifications" 095.TextWrapping="Wrap" 096.VerticalAlignment="Top" /> 097. 098.<TextBox x:Name="xQualificationsTB" 099.Height="84" 100.TextWrapping="Wrap" 101.ScrollViewer.VerticalScrollBarVisibility="Auto" 102.Grid.Column="1" 103.Grid.Row="5" 104.Text="{Binding activeJob.Qualifications, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 105.Grid.ColumnSpan="2" /> 106.<!-- Requirements Checkboxes--> 107. 108.<CheckBox x:Name="xResumeRequiredCB" Margin="8,8,8,15" 109.Content="Resume Required" 110.Grid.Row="6" 111.Grid.ColumnSpan="2" 112.IsChecked="{Binding activeJob.NeedsResume, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 113. 114.<CheckBox x:Name="xCoverletterRequiredCB" Margin="8,8,8,15" 115.Content="Cover Letter Required" 116.Grid.Column="2" 117.Grid.Row="6" 118.IsChecked="{Binding activeJob.NeedsCV, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 119. 120.<CheckBox x:Name="xOverviewRequiredCB" Margin="8,8,8,15" 121.Content="Overview Required" 122.Grid.Row="7" 123.Grid.ColumnSpan="2" 124.IsChecked="{Binding activeJob.NeedsOverview, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 125. 126.<CheckBox x:Name="xJobActiveCB" Margin="8,8,8,15" 127.Content="Job is Active" 128.Grid.Column="2" 129.Grid.Row="7" 130.IsChecked="{Binding activeJob.IsActive, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 131. 132.<!-- Buttons --> 133. 134.<Button x:Name="xAddEditButton" Margin="8,8,0,10" 135.Content="{Binding AddEditButtonString}" 136.cal:Click.Command="{Binding AddEditCommand}" 137.Grid.Column="2" 138.Grid.Row="8" 139.HorizontalAlignment="Left" 140.Width="125" 141.telerik:StyleManager.Theme="Windows7" /> 142. 143.<Button x:Name="xCancelButton" HorizontalAlignment="Right" 144.Content="Cancel" 145.cal:Click.Command="{Binding CancelCommand}" 146.Margin="0,8,8,10" 147.Width="125" 148.Grid.Column="2" 149.Grid.Row="8" 150.telerik:StyleManager.Theme="Windows7" /> 151.</Grid> 152.</Grid> The 'validationHelper:ValidationScope' line may seem odd. This is a handy little trick for catching current and would-be validation errors when working in this whole setup. This all comes from an approach found on theJoy Of Code blog, although it looks like the story for this will be changing slightly with new advances in SL4/WCF RIA Services, so this section can definitely get an overhaul a little down the road. The code is the fun part of all this, so let us see what's happening under the hood. Viewmodel for the AddEditJobView We are going to see some of the same things happening here, so I'll skip over the repeat info and get right to the good stuff: 001.public class AddEditJobViewModel : ViewModelBase 002.{ 003.private readonly IEventAggregator eventAggregator; 004.private readonly IRegionManager regionManager; 005. 006.public RecruitingContext context; 007. 008.private JobPosting _activeJob; 009.public JobPosting activeJob 010.{ 011.get { return _activeJob; } 012.set 013.{ 014.if (_activeJob != value) 015.{ 016._activeJob = value; 017.NotifyChanged("activeJob"); 018.} 019.} 020.} 021. 022.public bool isNewJob; 023. 024.private string _addEditString; 025.public string AddEditString 026.{ 027.get { return _addEditString; } 028.set 029.{ 030.if (_addEditString != value) 031.{ 032._addEditString = value; 033.NotifyChanged("AddEditString"); 034.} 035.} 036.} 037. 038.private string _addEditButtonString; 039.public string AddEditButtonString 040.{ 041.get { return _addEditButtonString; } 042.set 043.{ 044.if (_addEditButtonString != value) 045.{ 046._addEditButtonString = value; 047.NotifyChanged("AddEditButtonString"); 048.} 049.} 050.} 051. 052.public SubscriptionToken addJobToken = new SubscriptionToken(); 053.public SubscriptionToken editJobToken = new SubscriptionToken(); 054. 055.public DelegateCommand<object> AddEditCommand { get; set; } 056.public DelegateCommand<object> CancelCommand { get; set; } 057. 058.private ObservableCollection<ValidationError> _errors = new ObservableCollection<ValidationError>(); 059.public ObservableCollection<ValidationError> Errors 060.{ 061.get { return _errors; } 062.} 063. 064.private ObservableCollection<ValidationResult> _valResults = new ObservableCollection<ValidationResult>(); 065.public ObservableCollection<ValidationResult> ValResults 066.{ 067.get { return this._valResults; } 068.} 069. 070.public AddEditJobViewModel(IEventAggregator eventAgg, IRegionManager regionmanager) 071.{ 072.// set Unity items 073.this.eventAggregator = eventAgg; 074.this.regionManager = regionmanager; 075. 076.context = new RecruitingContext(); 077. 078.AddEditCommand = new DelegateCommand<object>(this.AddEditJobCommand); 079.CancelCommand = new DelegateCommand<object>(this.CancelAddEditCommand); 080. 081.SetSubscriptions(); 082.} 083. 084.#region Subscription Declaration and Events 085. 086.public void SetSubscriptions() 087.{ 088.AddJobEvent addJob = this.eventAggregator.GetEvent<AddJobEvent>(); 089. 090.if (addJobToken != null) 091.addJob.Unsubscribe(addJobToken); 092. 093.addJobToken = addJob.Subscribe(this.AddJobEventHandler); 094. 095.EditJobEvent editJob = this.eventAggregator.GetEvent<EditJobEvent>(); 096. 097.if (editJobToken != null) 098.editJob.Unsubscribe(editJobToken); 099. 100.editJobToken = editJob.Subscribe(this.EditJobEventHandler); 101.} 102. 103.public void AddJobEventHandler(bool isNew) 104.{ 105.this.activeJob = null; 106.this.activeJob = new JobPosting(); 107.this.activeJob.IsActive = true; // We assume that we want a new job to go up immediately 108.this.isNewJob = true; 109.this.AddEditString = "Add New Job Posting"; 110.this.AddEditButtonString = "Add Job"; 111. 112.MakeMeActive(this.regionManager, "MainRegion", "AddEditJobView"); 113.} 114. 115.public void EditJobEventHandler(JobPosting editJob) 116.{ 117.this.activeJob = null; 118.this.activeJob = editJob; 119.this.isNewJob = false; 120.this.AddEditString = "Edit Job Posting"; 121.this.AddEditButtonString = "Edit Job"; 122. 123.MakeMeActive(this.regionManager, "MainRegion", "AddEditJobView"); 124.} 125. 126.#endregion 127. 128.#region DelegateCommands from View 129. 130.public void AddEditJobCommand(object obj) 131.{ 132.if (this.Errors.Count > 0) 133.{ 134.List<string> errorMessages = new List<string>(); 135. 136.foreach (var valR in this.Errors) 137.{ 138.errorMessages.Add(valR.Exception.Message); 139.} 140. 141.this.eventAggregator.GetEvent<DisplayValidationErrorsEvent>().Publish(errorMessages); 142. 143.} 144.else if (!Validator.TryValidateObject(this.activeJob, new ValidationContext(this.activeJob, null, null), _valResults, true)) 145.{ 146.List<string> errorMessages = new List<string>(); 147. 148.foreach (var valR in this._valResults) 149.{ 150.errorMessages.Add(valR.ErrorMessage); 151.} 152. 153.this._valResults.Clear(); 154. 155.this.eventAggregator.GetEvent<DisplayValidationErrorsEvent>().Publish(errorMessages); 156.} 157.else 158.{ 159.if (this.isNewJob) 160.{ 161.this.eventAggregator.GetEvent<AddJobCompleteEvent>().Publish(this.activeJob); 162.} 163.else 164.{ 165.this.eventAggregator.GetEvent<EditJobCompleteEvent>().Publish(true); 166.} 167.} 168.} 169. 170.public void CancelAddEditCommand(object obj) 171.{ 172.if (this.isNewJob) 173.{ 174.this.eventAggregator.GetEvent<AddJobCompleteEvent>().Publish(null); 175.} 176.else 177.{ 178.this.eventAggregator.GetEvent<EditJobCompleteEvent>().Publish(false); 179.} 180.} 181. 182.#endregion 183.} 184.} We start seeing something new on line 103- the AddJobEventHandler will create a new job and set that to the activeJob item on the ViewModel. When this is all set, the view calls that familiar MakeMeActive method to activate itself. I made a bit of a management call on making views self-activate like this, but I figured it works for one reason. As I create this application, views may not exist that I have in mind, so after a view receives its 'ping' from being subscribed to an event, it prepares whatever it needs to do and then goes active. This way if I don't have 'edit' hooked up, I can click as the day is long on the main view and won't get lost in an empty region. Total personal preference here. :) Everything else should again be pretty straightforward, although I do a bit of validation checking in the AddEditJobCommand, which can either fire off an event back to the main view/viewmodel if everything is a success or sent a list of errors to our notification module, which pops open a RadWindow with the alerts if any exist. As a bonus side note, here's what my WCF RIA Services metadata looks like for handling all of the validation: private JobPostingMetadata() { } [StringLength(2500, ErrorMessage = "Description should be more than one and less than 2500 characters.", MinimumLength = 1)] [Required(ErrorMessage = "Description is required.")] public string Description; [Required(ErrorMessage="Active Status is Required")] public bool IsActive; [StringLength(100, ErrorMessage = "Posting title must be more than 3 but less than 100 characters.", MinimumLength = 3)] [Required(ErrorMessage = "Job Title is required.")] public bool JobTitle; [Required] public string Location; public bool NeedsCV; public bool NeedsOverview; public bool NeedsResume; public int PostingID; [Required(ErrorMessage="Qualifications are required.")] [StringLength(2500, ErrorMessage="Qualifications should be more than one and less than 2500 characters.", MinimumLength=1)] public string Qualifications; [StringLength(2500, ErrorMessage = "Requirements should be more than one and less than 2500 characters.", MinimumLength = 1)] [Required(ErrorMessage="Requirements are required.")] public string Requirements;   The RecruitCB Alternative See all that Xaml I pasted above? Those are now two pieces sitting in the JobsView.xaml file now. The only real difference is that the xEditGrid now sits in the same place as xJobsGrid, with visibility swapping out between the two for a quick switch. I also took out all the cal: and command: command references and replaced Button events with clicks and the Grid selection command replaced with a SelectedItemChanged event. Also, at the bottom of the xEditGrid after the last button, I add a ValidationSummary (with Visibility=Collapsed) to catch any errors that are popping up. Simple as can be, and leads to this being the single code-behind file: 001.public partial class JobsView : UserControl 002.{ 003.public RecruitingContext context; 004.public JobPosting activeJob; 005.public bool isNew; 006.private ObservableCollection<ValidationResult> _valResults = new ObservableCollection<ValidationResult>(); 007.public ObservableCollection<ValidationResult> ValResults 008.{ 009.get { return this._valResults; } 010.} 011.public JobsView() 012.{ 013.InitializeComponent(); 014.this.Loaded += new RoutedEventHandler(JobsView_Loaded); 015.} 016.void JobsView_Loaded(object sender, RoutedEventArgs e) 017.{ 018.context = new RecruitingContext(); 019.xJobsGrid.ItemsSource = context.JobPostings; 020.context.Load(context.GetJobPostingsQuery()); 021.} 022.private void xAddRecordButton_Click(object sender, RoutedEventArgs e) 023.{ 024.activeJob = new JobPosting(); 025.isNew = true; 026.xAddEditTitle.Text = "Add a Job Posting"; 027.xAddEditButton.Content = "Add"; 028.xEditGrid.DataContext = activeJob; 029.HideJobsGrid(); 030.} 031.private void xEditRecordButton_Click(object sender, RoutedEventArgs e) 032.{ 033.activeJob = xJobsGrid.SelectedItem as JobPosting; 034.isNew = false; 035.xAddEditTitle.Text = "Edit a Job Posting"; 036.xAddEditButton.Content = "Edit"; 037.xEditGrid.DataContext = activeJob; 038.HideJobsGrid(); 039.} 040.private void xAddEditButton_Click(object sender, RoutedEventArgs e) 041.{ 042.if (!Validator.TryValidateObject(this.activeJob, new ValidationContext(this.activeJob, null, null), _valResults, true)) 043.{ 044.List<string> errorMessages = new List<string>(); 045.foreach (var valR in this._valResults) 046.{ 047.errorMessages.Add(valR.ErrorMessage); 048.} 049.this._valResults.Clear(); 050.ShowErrors(errorMessages); 051.} 052.else if (xSummary.Errors.Count > 0) 053.{ 054.List<string> errorMessages = new List<string>(); 055.foreach (var err in xSummary.Errors) 056.{ 057.errorMessages.Add(err.Message); 058.} 059.ShowErrors(errorMessages); 060.} 061.else 062.{ 063.if (this.isNew) 064.{ 065.context.JobPostings.Add(activeJob); 066.context.SubmitChanges((s) => 067.{ 068.ActionHistory thisAction = new ActionHistory(); 069.thisAction.PostingID = activeJob.PostingID; 070.thisAction.Description = String.Format("Job '{0}' has been edited by {1}", activeJob.JobTitle, "default user"); 071.thisAction.TimeStamp = DateTime.Now; 072.context.ActionHistories.Add(thisAction); 073.context.SubmitChanges(); 074.}, null); 075.} 076.else 077.{ 078.context.SubmitChanges((s) => 079.{ 080.ActionHistory thisAction = new ActionHistory(); 081.thisAction.PostingID = activeJob.PostingID; 082.thisAction.Description = String.Format("Job '{0}' has been added by {1}", activeJob.JobTitle, "default user"); 083.thisAction.TimeStamp = DateTime.Now; 084.context.ActionHistories.Add(thisAction); 085.context.SubmitChanges(); 086.}, null); 087.} 088.ShowJobsGrid(); 089.} 090.} 091.private void xCancelButton_Click(object sender, RoutedEventArgs e) 092.{ 093.ShowJobsGrid(); 094.} 095.private void ShowJobsGrid() 096.{ 097.xAddEditRecordButtonPanel.Visibility = Visibility.Visible; 098.xEditGrid.Visibility = Visibility.Collapsed; 099.xJobsGrid.Visibility = Visibility.Visible; 100.} 101.private void HideJobsGrid() 102.{ 103.xAddEditRecordButtonPanel.Visibility = Visibility.Collapsed; 104.xJobsGrid.Visibility = Visibility.Collapsed; 105.xEditGrid.Visibility = Visibility.Visible; 106.} 107.private void ShowErrors(List<string> errorList) 108.{ 109.string nm = "Errors received: \n"; 110.foreach (string anerror in errorList) 111.nm += anerror + "\n"; 112.RadWindow.Alert(nm); 113.} 114.} The first 39 lines should be pretty familiar, not doing anything too unorthodox to get this up and running. Once we hit the xAddEditButton_Click on line 40, we're still doing pretty much the same things except instead of checking the ValidationHelper errors, we both run a check on the current activeJob object as well as check the ValidationSummary errors list. Once that is set, we again use the callback of context.SubmitChanges (lines 68 and 78) to create an ActionHistory which we will use to track these items down the line. That's all? Essentially... yes. If you look back through this post, most of the code and adventures we have taken were just to get things working in the MVVM/Prism setup. Since I have the whole 'module' self-contained in a single JobView+code-behind setup, I don't have to worry about things like sending events off into space for someone to pick up, communicating through an Infrastructure project, or even re-inventing events to be used with attached behaviors. Everything just kinda works, and again with much less code. Here's a picture of the MVVM and Code-behind versions on the Jobs and AddEdit views, but since the functionality is the same in both apps you still cannot tell them apart (for two-strike): Looking ahead, the Applicants module is effectively the same thing as the Jobs module, so most of the code is being cut-and-pasted back and forth with minor tweaks here and there. So that one is being taken care of by me behind the scenes. Next time, we get into a new world of fun- the interview scheduling module, which will pull from available jobs and applicants for each interview being scheduled, tying everything together with RadScheduler to the rescue. Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Custom Model binder not firing

    - by mare
    This is my custom model binder. I have my breakpoint set at BindModel but does not get fired with this controller action: public ActionResult Create(TabGroup tabGroup) ... public class BaseContentObjectCommonPropertiesBinder : DefaultModelBinder { public new object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (controllerContext == null) { throw new ArgumentNullException("controllerContext"); } if (bindingContext == null) { throw new ArgumentNullException("bindingContext"); } BaseContentObject obj = (BaseContentObject)base.BindModel(controllerContext, bindingContext); obj.Modified = DateTime.Now; obj.Created = DateTime.Now; obj.ModifiedBy = obj.CreatedBy = controllerContext.HttpContext.User.Identity.Name; return obj; } My registration: // tried both of these two lines ModelBinders.Binders[typeof(TabGroup)] = new BaseContentObjectCommonPropertiesBinder(); ModelBinders.Binders.Add(typeof(TabGroup), new BaseContentObjectCommonPropertiesBinder());

    Read the article

  • iPhone/Obj-C: Accessing a UIScrollView from a View displayed within it.

    - by Daniel I-S
    I'm writing a simple iPhone app which lets a user access a series of calculators. It consists of the following: UITableViewController (RootViewController), with the list of calculators. UIViewController + UIScrollView (UniversalScroller), which represents an empty scroll view - and has a 'displayedViewController' property. UIViewController (Calculators 1-9), each of which contains a view with controls that represents a particular calculator. Each calculator takes 3-5 values via UITextFields and UISliders, and has a 'calculate' button. They can potentially be taller than 460px(iPhone screen height). The idea is: User taps on a particular menu item in the RootViewController. This loads and inits UniversalScroller, ALSO loads and inits the UIViewcontroller for the particular calculator that was selected, sets the displayedViewController property of UniversalScroller to the newly loaded calculator UIViewcontroller, and pushes the UniversalScroller to the front. When the UniversalScroller hits its 'viewDidLoad' event, it sets its contentSize to the view frame size of its 'displayedViewController' object. It then adds the displayedViewController's view as a subview to itself, and sets its own title to equal that of the displayedViewController. It now displays the calculator, along with the correct title, in a scrollable form. Conceptually (and currently; this stuff has all been implemented already), this works great - I can design the calculators how I see fit, as tall as they end up being, and they will automatically be accommodated and displayed in an appropriately configured UIScrollView. However, there is one problem: The main reason I wanted to display things in a UIScrollView was so that, when the on-screen-keyboard appeared, I could shift the view up to focus on the control that is currently being edited. To do this, I need access to the UniversalScroller object that is holding the current calculator's view. On the beganEditing: event of each control, I intended to use the [UniversalScroller.view scrollRectToVisible: animated:] method to move focus to the correct control. However, I am having trouble accessing the UniversalScroller. I tried assigning a reference to it as a property of each calculator UIViewController, but did't seem to have much luck. I've read about using Delegates but have had trouble working out exactly how they work. I'm looking for one of three things: Some explanation of how I can access the methods of a UIScrollView from a UIViewController whose view is contained within it. or Confirmation of my suspicions that making users scroll on a data entry form is bad, and I should just abandon scrollviews altogether and move the view up and down to the relevant position when the keyboard appears, then back when it disappears. or Some pointers on how I could go about redesigning the calculators (which are basically simple data entry forms using labels, sliders and textfields) to be contained within UITableViewCells (presumably in a UITableView, which I understand is a scrollview deep down) - I read a post on SO saying that that's a more pleasing way to make a data entry form, but I couldn't find any examples of that online. Screenshots would be nice. Anything to make my app more usable and naturally 'iPhone-like', since shuffling labels and textboxes around makes me feel like I am building a winforms app! I've only recently started with this platform and language, and despite being largely an Apple skeptic I definitely see the beauty in the way that it works. Help me solve this problem and I might fall in love completely. Dan

    Read the article

  • Using memcache to store obj's in google app engine.

    - by fredrik
    Hi, I'm trying to use memcache to cache data retrevied from the datastore. Storing stings works fine. But can't one store an object? I get an error "TypeError: 'str' object is not callable" when trying to store with this: pageData = PageType(page) memcache.add(memcacheid, pageData, 60) I've read in the documentation that it requires "The value type can be any value supported by the Python pickle module for serializing values." But don't really understand what that is. Or how to convert pageData to it. Any ideas? ..fredrik

    Read the article

  • Can't import obj in Python on OS X 10.6.3 Snow Leopard - libiconv.2.dylib?

    - by James
    on OS X 10.6.3 Snow Leopard % python Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. import objc Traceback (most recent call last): File "", line 1, in File "/Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/objc/__init__.py", line 22, in _update() File "/Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/objc/__init__.py", line 19, in _update import _objc ImportError: dlopen(/Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/objc/_objc.so, 2): Library not loaded: /opt/local/lib/libiconv.2.dylib Referenced from: /Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/objc/_objc.so Reason: Incompatible library version: _objc.so requires version 8.0.0 or later, but libiconv.2.dylib provides version 7.0.0 -- what do I need to do?

    Read the article

  • How to test a class that makes HTTP request and parse the response data in Obj-C?

    - by GuidoMB
    I Have a Class that needs to make an HTTP request to a server in order to get some information. For example: - (NSUInteger)newsCount { NSHTTPURLResponse *response; NSError *error; NSURLRequest *request = ISKBuildRequestWithURL(ISKDesktopURL, ISKGet, cookie, nil, nil); NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (!data) { NSLog(@"The user's(%@) news count could not be obtained:%@", username, [error description]); return 0; } NSString *regExp = @"Usted tiene ([0-9]*) noticias? no leídas?"; NSString *stringData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSArray *match = [stringData captureComponentsMatchedByRegex:regExp]; [stringData release]; if ([match count] < 2) return 0; return [[match objectAtIndex:1] intValue]; } The things is that I'm unit testing (using OCUnit) the hole framework but the problem is that I need to simulate/fake what the NSURLConnection is responding in order to test different scenarios and because I can't relay on the server to test my framework. So the question is Which is the best ways to do this?

    Read the article

  • How would I write the following applescript in Obj-C AppScript? ASTranslate was of no help =(

    - by demonslayer319
    The translation tool isn't able to translate this working code. I copied it out of a working script. set pathToTemp to (POSIX path of ((path to desktop) as string)) -- change jpg to pict tell application "Image Events" try launch set albumArt to open file (pathToTemp & "albumart.jpg") save albumArt as PICT in file (pathToTemp & "albumart.pict") --the first 512 bytes are the PICT header, so it reads from byte 513 --this is to allow the image to be added to an iTunes track later. set albumArt to (read file (pathToTemp & "albumart.pict") from 513 as picture) close end try end tell The code is taking a jpg image, converting it to a PICT file, and then reading the file minus the header (the first 512 bytes). Later in the script, albumArt will be added to an iTunes track. I tried translating the code (minus the comments), but ASTranslate froze for a good 2 minutes before giving me this: Untranslated event 'earsffdr' #import "IEGlue/IEGlue.h" IEApplication *imageEvents = [IEApplication applicationWithName: @"Image Events"]; IELaunchCommand *cmd = [[imageEvents launch] ignoreReply]; id result = [cmd send]; #import "IEGlue/IEGlue.h" IEApplication *imageEvents = [IEApplication applicationWithName: @"Image Events"]; IEReference *ref = [[imageEvents files] byName: @"/Users/Doom/Desktop/albumart.jpg"]; id result = [[ref open] send]; #import "IEGlue/IEGlue.h" IEApplication *imageEvents = [IEApplication applicationWithName: @"Image Events"]; IEReference *ref = [[imageEvents images] byName: @"albumart.jpg"]; IESaveCommand *cmd = [[[ref save] in: [[imageEvents files] byName: @"/Users/Doom/Desktop/albumart.pict"]] as: [IEConstant PICT]]; id result = [cmd send]; 'crdwrread' Traceback (most recent call last): File "objcrenderer.pyc", line 283, in renderCommand KeyError: 'crdwrread' 'cascrgdut' Traceback (most recent call last): File "objcrenderer.pyc", line 283, in renderCommand KeyError: 'cascrgdut' 'crdwrread' Traceback (most recent call last): File "objcrenderer.pyc", line 283, in renderCommand KeyError: 'crdwrread' Untranslated event 'rdwrread' OK I have no clue how to make sense of this. Thanks for any and all help!

    Read the article

  • Need to calculate offsetRight in javascript

    - by Dan Bailiff
    I need to calculate the offsetRight of a DOM object. I already have some rather simple code for getting the offsetLeft, but there is no javascript offsetRight property. If I add the offsetLeft and offsetWidth, will that work? Or is there a better way? function getOffsetLeft(obj) { if(obj == null) return 0; var offsetLeft = 0; var tmp = obj; while(tmp != null) { offsetLeft += tmp.offsetLeft; tmp = tmp.offsetParent; } return offsetLeft; } function getOffsetRight(obj) { if (obj == null) return 0; var offsetRight = 0; var tmp = obj; while (tmp != null) { offsetRight += tmp.offsetLeft + tmp.offsetWidth; tmp = tmp.offsetParent; } return offsetRight; }

    Read the article

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