Search Results

Search found 37788 results on 1512 pages for 'dynamic method'.

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

  • C# 4.0 'dynamic' and foreach statement

    - by ControlFlow
    Not long time before I've discovered, that new dynamic keyword doesn't work well with the C#'s foreach statement: using System; sealed class Foo { public struct FooEnumerator { int value; public bool MoveNext() { return true; } public int Current { get { return value++; } } } public FooEnumerator GetEnumerator() { return new FooEnumerator(); } static void Main() { foreach (int x in new Foo()) { Console.WriteLine(x); if (x >= 100) break; } foreach (int x in (dynamic)new Foo()) { // :) Console.WriteLine(x); if (x >= 100) break; } } } I've expected that iterating over the dynamic variable should work completely as if the type of collection variable is known at compile time. I've discovered that the second loop actually is looked like this when is compiled: foreach (object x in (IEnumerable) /* dynamic cast */ (object) new Foo()) { ... } and every access to the x variable results with the dynamic lookup/cast so C# ignores that I've specify the correct x's type in the foreach statement - that was a bit surprising for me... And also, C# compiler completely ignores that collection from dynamically typed variable may implements IEnumerable<T> interface! The full foreach statement behavior is described in the C# 4.0 specification 8.8.4 The foreach statement article. But... It's perfectly possible to implement the same behavior at runtime! It's possible to add an extra CSharpBinderFlags.ForEachCast flag, correct the emmited code to looks like: foreach (int x in (IEnumerable<int>) /* dynamic cast with the CSharpBinderFlags.ForEachCast flag */ (object) new Foo()) { ... } And add some extra logic to CSharpConvertBinder: Wrap IEnumerable collections and IEnumerator's to IEnumerable<T>/IEnumerator<T>. Wrap collections doesn't implementing Ienumerable<T>/IEnumerator<T> to implement this interfaces. So today foreach statement iterates over dynamic completely different from iterating over statically known collection variable and completely ignores the type information, specified by user. All that results with the different iteration behavior (IEnumarble<T>-implementing collections is being iterated as only IEnumerable-implementing) and more than 150x slowdown when iterating over dynamic. Simple fix will results a much better performance: foreach (int x in (IEnumerable<int>) dynamicVariable) { But why I should write code like this? It's very nicely to see that sometimes C# 4.0 dynamic works completely the same if the type will be known at compile-time, but it's very sadly to see that dynamic works completely different where IT CAN works the same as statically typed code. So my question is: why foreach over dynamic works different from foreach over anything else?

    Read the article

  • Static method , Abstract method , Interface method comparision ?

    - by programmerist
    When i choose these methods? i can not decide which one i must prefer or when will i use one of them?which one give best performance? First Type Usage public abstract class _AccessorForSQL { public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType); public virtual bool Update(); public virtual bool Delete(); public virtual DataSet Select(); } class GenAccessor : _AccessorForSQL { DataSet ds; DataTable dt; public override bool Save(string sp, ListDictionary ld, CommandType cmdType) { } public override bool Update() { return true; } public override bool Delete() { return true; } public override DataSet Select() { DataSet dst = new DataSet(); return dst; } Second Type Usage Also i can write it below codes: public class GenAccessor { public Static bool Save() { } public Static bool Update() { } public Static bool Delete() { } } Third Type Usage Also i can write it below codes: public interface IAccessorForSQL { bool Delete(); bool Save(string sp, ListDictionary ld, CommandType cmdType); DataSet Select(); bool Update(); } public class _AccessorForSQL : IAccessorForSQL { private DataSet ds; private DataTable dt; public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType) { } } } I can use first one below usage: GenAccessor gen = New GenAccessor(); gen.Save(); I can use second one below usage: GenAccessor.Save(); Which one do you prefer? When will i use them? which time i need override method ? which time i need static method?

    Read the article

  • Converting dynamic to basic disk

    - by Josip Medved
    I converted basic disk to dynamic on my laptop. However, now I cannot install Windows 7 on another partition. I just get message that installing them on dynamic disk is not supported. Is there a way to convert dynamic disk to basic without losing data on already existing partition?

    Read the article

  • The Template Method Design Pattern using C# .Net

    - by nijhawan.saurabh
    First of all I'll just put this pattern in context and describe its intent as in the GOF book:   Template Method: Define the skeleton of an algorithm in an operation, deferring some steps to Subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the Algorithm's Structure.    Usage: When you are certain about the High Level steps involved in an Algorithm/Work flow you can use the Template Pattern which allows the Base Class to define the Sequence of the Steps but permits the Sub classes to alter the implementation of any/all steps.   Example in the .Net framework: The most common example is the Asp.Net Page Life Cycle. The Page Life Cycle has a few methods which are called in a sequence but we have the liberty to modify the functionality of any of the methods by overriding them.   Sample implementation of Template Method Pattern:   Let's see the class diagram first:            Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:8.0pt; mso-para-margin-left:0in; line-height:107%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt; mso-ligatures:standard;}   And here goes the code:EmailBase.cs     1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public abstract class EmailBase    10     {    11     12         public bool SendEmail()    13         {    14             if (CheckEmailAddress() == true) // Method1 in the sequence    15             {    16                 if (ValidateMessage() == true) // Method2 in the sequence    17                 {    18                     if (SendMail() == true) // Method3 in the sequence    19                     {    20                         return true;    21                     }    22                     else    23                     {    24                         return false;    25                     }    26     27                 }    28                 else    29                 {    30                     return false;    31                 }    32     33             }    34             else    35             {    36                 return false;    37     38             }    39     40     41         }    42     43         protected abstract bool CheckEmailAddress();    44         protected abstract bool ValidateMessage();    45         protected abstract bool SendMail();    46     47     48     }    49 }    50    EmailYahoo.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public class EmailYahoo:EmailBase    10     {    11     12         protected override bool CheckEmailAddress()    13         {    14             Console.WriteLine("Checking Email Address : YahooEmail");    15             return true;    16         }    17         protected override bool ValidateMessage()    18         {    19             Console.WriteLine("Validating Email Message : YahooEmail");    20             return true;    21         }    22     23     24         protected override bool SendMail()    25         {    26             Console.WriteLine("Semding Email : YahooEmail");    27             return true;    28         }    29     30     31     }    32 }    33   EmailGoogle.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public class EmailGoogle:EmailBase    10     {    11     12         protected override bool CheckEmailAddress()    13         {    14             Console.WriteLine("Checking Email Address : GoogleEmail");    15             return true;    16         }    17         protected override bool ValidateMessage()    18         {    19             Console.WriteLine("Validating Email Message : GoogleEmail");    20             return true;    21         }    22     23     24         protected override bool SendMail()    25         {    26             Console.WriteLine("Semding Email : GoogleEmail");    27             return true;    28         }    29     30     31     }    32 }    33   Program.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     class Program    10     {    11         static void Main(string[] args)    12         {    13             Console.WriteLine("Please choose an Email Account to send an Email:");    14             Console.WriteLine("Choose 1 for Google");    15             Console.WriteLine("Choose 2 for Yahoo");    16             string choice = Console.ReadLine();    17     18             if (choice == "1")    19             {    20                 EmailBase email = new EmailGoogle(); // Rather than newing it up here, you may use a factory to do so.    21                 email.SendEmail();    22     23             }    24             if (choice == "2")    25             {    26                 EmailBase email = new EmailYahoo(); // Rather than newing it up here, you may use a factory to do so.    27                 email.SendEmail();    28             }    29         }    30     }    31 }    32    Final Words: It's very obvious that why the Template Method Pattern is a popular pattern, everything at last revolves around Algorithms and if you are clear with the steps involved it makes real sense to delegate the duty of implementing the step's functionality to the sub classes. Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:8.0pt; mso-para-margin-left:0in; line-height:107%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt; mso-ligatures:standard;}

    Read the article

  • What is common case for @dynamic usage ?

    - by Forrest
    There is previous post about difference of @synthesize and @dynamic. I wanna to know more about dynamic from the perspective of how to use @dynamic usually. Usually we use @dynamic together with NSManagedObject // Movie.h @interface Movie : NSManagedObject { } @property (retain) NSString* title; @end // Movie.m @implementation Movie @dynamic title; @end Actually there are no generated getter/setter during compiler time according to understanding of @dynamic, so it is necessary to implement your own getter/setter. My question is that in this NSManagedObject case, what is the rough implementation of getter/setter in super class NSManagedObject ? Except above case, how many other cases to use @dynamic ? Thanks,

    Read the article

  • Ajax method within a added method in jQuery validator

    - by nikospkrk
    Hi, I'm kind of stuck with this pretty simple (I'm sure) jQuery/Javascript issue. Here's the code : jQuery.validator.addMethod("emailExists", function(value, element, param) { var email = value || ''; var valid = 0; $.ajax({ type: "POST", url: param, data: "email=" + email, success: function(msg) { if (msg != '' && msg) { valid = 0; } else { valid = 1; } } }); return valid; }, "* Email address already registered, please login."); This function is called where a user type his email address in a registration form, and everything seems to work perfectly, except that my valid variable returned isn't updated, whereas when I use an alert box it is properly done! It looks like it return the value before the AJAX is done, any idea? Cheers, Nicolas.

    Read the article

  • Dynamic JSON Parsing in .NET with JsonValue

    - by Rick Strahl
    So System.Json has been around for a while in Silverlight, but it's relatively new for the desktop .NET framework and now moving into the lime-light with the pending release of ASP.NET Web API which is bringing a ton of attention to server side JSON usage. The JsonValue, JsonObject and JsonArray objects are going to be pretty useful for Web API applications as they allow you dynamically create and parse JSON values without explicit .NET types to serialize from or into. But even more so I think JsonValue et al. are going to be very useful when consuming JSON APIs from various services. Yes I know C# is strongly typed, why in the world would you want to use dynamic values? So many times I've needed to retrieve a small morsel of information from a large service JSON response and rather than having to map the entire type structure of what that service returns, JsonValue actually allows me to cherry pick and only work with the values I'm interested in, without having to explicitly create everything up front. With JavaScriptSerializer or DataContractJsonSerializer you always need to have a strong type to de-serialize JSON data into. Wouldn't it be nice if no explicit type was required and you could just parse the JSON directly using a very easy to use object syntax? That's exactly what JsonValue, JsonObject and JsonArray accomplish using a JSON parser and some sweet use of dynamic sauce to make it easy to access in code. Creating JSON on the fly with JsonValue Let's start with creating JSON on the fly. It's super easy to create a dynamic object structure. JsonValue uses the dynamic  keyword extensively to make it intuitive to create object structures and turn them into JSON via dynamic object syntax. Here's an example of creating a music album structure with child songs using JsonValue:[TestMethod] public void JsonValueOutputTest() { // strong type instance var jsonObject = new JsonObject(); // dynamic expando instance you can add properties to dynamic album = jsonObject; album.AlbumName = "Dirty Deeds Done Dirt Cheap"; album.Artist = "AC/DC"; album.YearReleased = 1977; album.Songs = new JsonArray() as dynamic; dynamic song = new JsonObject(); song.SongName = "Dirty Deeds Done Dirt Cheap"; song.SongLength = "4:11"; album.Songs.Add(song); song = new JsonObject(); song.SongName = "Love at First Feel"; song.SongLength = "3:10"; album.Songs.Add(song); Console.WriteLine(album.ToString()); } This produces proper JSON just as you would expect: {"AlbumName":"Dirty Deeds Done Dirt Cheap","Artist":"AC\/DC","YearReleased":1977,"Songs":[{"SongName":"Dirty Deeds Done Dirt Cheap","SongLength":"4:11"},{"SongName":"Love at First Feel","SongLength":"3:10"}]} The important thing about this code is that there's no explicitly type that is used for holding the values to serialize to JSON. I am essentially creating this value structure on the fly by adding properties and then serialize it to JSON. This means this code can be entirely driven at runtime without compile time restraints of structure for the JSON output. Here I use JsonObject() to create a new object and immediately cast it to dynamic. JsonObject() is kind of similar in behavior to ExpandoObject in that it allows you to add properties by simply assigning to them. Internally, JsonValue/JsonObject these values are stored in pseudo collections of key value pairs that are exposed as properties through the DynamicObject functionality in .NET. The syntax gets a little tedious only if you need to create child objects or arrays that have to be explicitly defined first. Other than that the syntax looks like normal object access sytnax. Always remember though these values are dynamic - which means no Intellisense and no compiler type checking. It's up to you to ensure that the values you create are accessed consistently and without typos in your code. Note that you can also access the JsonValue instance directly and get access to the underlying type. This means you can assign properties by string, which can be useful for fully data driven JSON generation from other structures. Below you can see both styles of access next to each other:// strong type instance var jsonObject = new JsonObject(); // you can explicitly add values here jsonObject.Add("Entered", DateTime.Now); // expando style instance you can just 'use' properties dynamic album = jsonObject; album.AlbumName = "Dirty Deeds Done Dirt Cheap"; JsonValue internally stores properties keys and values in collections and you can iterate over them at runtime. You can also manipulate the collections if you need to to get the object structure to look exactly like you want. Again, if you've used ExpandoObject before JsonObject/Value are very similar in the behavior of the structure. Reading JSON strings into JsonValue The JsonValue structure supports importing JSON via the Parse() and Load() methods which can read JSON data from a string or various streams respectively. Essentially JsonValue includes the core JSON parsing to turn a JSON string into a collection of JsonValue objects that can be then referenced using familiar dynamic object syntax. Here's a simple example:[TestMethod] public void JsonValueParsingTest() { var jsonString = @"{""Name"":""Rick"",""Company"":""West Wind"",""Entered"":""2012-03-16T00:03:33.245-10:00""}"; dynamic json = JsonValue.Parse(jsonString); // values require casting string name = json.Name; string company = json.Company; DateTime entered = json.Entered; Assert.AreEqual(name, "Rick"); Assert.AreEqual(company, "West Wind"); } The JSON string represents an object with three properties which is parsed into a JsonValue object and cast to dynamic. Once cast to dynamic I can then go ahead and access the object using familiar object syntax. Note that the actual values - json.Name, json.Company, json.Entered - are actually of type JsonPrimitive and I have to assign them to their appropriate types first before I can do type comparisons. The dynamic properties will automatically cast to the right type expected as long as the compiler can resolve the type of the assignment or usage. The AreEqual() method oesn't as it expects two object instances and comparing json.Company to "West Wind" is comparing two different types (JsonPrimitive to String) which fails. So the intermediary assignment is required to make the test pass. The JSON structure can be much more complex than this simple example. Here's another example of an array of albums serialized to JSON and then parsed through with JsonValue():[TestMethod] public void JsonArrayParsingTest() { var jsonString = @"[ { ""Id"": ""b3ec4e5c"", ""AlbumName"": ""Dirty Deeds Done Dirt Cheap"", ""Artist"": ""AC/DC"", ""YearReleased"": 1977, ""Entered"": ""2012-03-16T00:13:12.2810521-10:00"", ""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/61kTaH-uZBL._AA115_.jpg"", ""AmazonUrl"": ""http://www.amazon.com/gp/product/B00008BXJ4/ref=as_li_ss_tl?ie=UTF8&tag=westwindtechn-20&linkCode=as2&camp=1789&creative=390957&creativeASIN=B00008BXJ4"", ""Songs"": [ { ""AlbumId"": ""b3ec4e5c"", ""SongName"": ""Dirty Deeds Done Dirt Cheap"", ""SongLength"": ""4:11"" }, { ""AlbumId"": ""b3ec4e5c"", ""SongName"": ""Love at First Feel"", ""SongLength"": ""3:10"" }, { ""AlbumId"": ""b3ec4e5c"", ""SongName"": ""Big Balls"", ""SongLength"": ""2:38"" } ] }, { ""Id"": ""67280fb8"", ""AlbumName"": ""Echoes, Silence, Patience & Grace"", ""Artist"": ""Foo Fighters"", ""YearReleased"": 2007, ""Entered"": ""2012-03-16T00:13:12.2810521-10:00"", ""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/41mtlesQPVL._SL500_AA280_.jpg"", ""AmazonUrl"": ""http://www.amazon.com/gp/product/B000UFAURI/ref=as_li_ss_tl?ie=UTF8&tag=westwindtechn-20&linkCode=as2&camp=1789&creative=390957&creativeASIN=B000UFAURI"", ""Songs"": [ { ""AlbumId"": ""67280fb8"", ""SongName"": ""The Pretender"", ""SongLength"": ""4:29"" }, { ""AlbumId"": ""67280fb8"", ""SongName"": ""Let it Die"", ""SongLength"": ""4:05"" }, { ""AlbumId"": ""67280fb8"", ""SongName"": ""Erase/Replay"", ""SongLength"": ""4:13"" } ] }, { ""Id"": ""7b919432"", ""AlbumName"": ""End of the Silence"", ""Artist"": ""Henry Rollins Band"", ""YearReleased"": 1992, ""Entered"": ""2012-03-16T00:13:12.2800521-10:00"", ""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/51FO3rb1tuL._SL160_AA160_.jpg"", ""AmazonUrl"": ""http://www.amazon.com/End-Silence-Rollins-Band/dp/B0000040OX/ref=sr_1_5?ie=UTF8&qid=1302232195&sr=8-5"", ""Songs"": [ { ""AlbumId"": ""7b919432"", ""SongName"": ""Low Self Opinion"", ""SongLength"": ""5:24"" }, { ""AlbumId"": ""7b919432"", ""SongName"": ""Grip"", ""SongLength"": ""4:51"" } ] } ]"; dynamic albums = JsonValue.Parse(jsonString); foreach (dynamic album in albums) { Console.WriteLine(album.AlbumName + " (" + album.YearReleased.ToString() + ")"); foreach (dynamic song in album.Songs) { Console.WriteLine("\t" + song.SongName ); } } Console.WriteLine(albums[0].AlbumName); Console.WriteLine(albums[0].Songs[1].SongName);}   It's pretty sweet how easy it becomes to parse even complex JSON and then just run through the object using object syntax, yet without an explicit type in the mix. In fact it looks and feels a lot like if you were using JavaScript to parse through this data, doesn't it? And that's the point…© Rick Strahl, West Wind Technologies, 2005-2012Posted in .NET  Web Api  JSON   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • C# String.format extension method

    - by Paul Roe
    With the addtion of Extension methods to C# we've seen a lot of them crop up in our group. One debate revolves around extension methods like this one: public static class StringExt { /// <summary> /// Shortcut for string.Format. /// </summary> /// <param name="str"></param> /// <param name="args"></param> /// <returns></returns> public static string Format(this string str, params object[] args) { if (str == null) return null; return string.Format(str, args); } } Does this extension method break any programming best practices that you can name? Would you use it anyway, if not why? If I renamed the function to "F" but left the xml comments would that be epic fail or just a wonderful savings of keystrokes?

    Read the article

  • Why setter method when getter method enough in PHP OOP

    - by phphunger
    I am practicing OOP with PHP, and I am struck at setter and getter methods. I can directly access the class properties and methods with getter method then what's the use of setter method? See my example. <?php class MyClass{ public $classVar = "Its a class variable"; public function Getter(){ return $this -> classVar; } } $obj = new MyClass; echo $obj -> Getter(); ?>

    Read the article

  • How to make that the LanguageBinder take precedence over the DynamicBinder

    - by rudimenter
    Hi I Have a class which implement IDynamicMetaObjectProvider I implement the BindGetMember Method from DynamicMetaObject. Now when i Generate a dynamic Object and Access a property every call gets implicit passed through the BindGetMember Method. I want that at first the language Binder get his chance before my code comes in. It is somehow doable with "binder.FallbackGetMember" but i am not sure how the expression has to look like. I call here dynamic com=CommandFactory.GetCommand(); com.testprop; //expected: "test"; but "test2" comes back public class Command : System.Dynamic.IDynamicMetaObjectProvider { public string testprop { get { return "test"; } } public object GetValue(string name) { return "test2"; } System.Dynamic.DynamicMetaObject System.Dynamic.IDynamicMetaObjectProvider.GetMetaObject(System.Linq.Expressions.Expression parameter) { return new MetaCommand(parameter, this); } private class MetaCommand : System.Dynamic.DynamicMetaObject { public MetaCommand(Expression expression, Command value) : base(expression, System.Dynamic.BindingRestrictions.Empty, value) { } public override System.Dynamic.DynamicMetaObject BindGetMember(System.Dynamic.GetMemberBinder binder) { var self = this.Expression; var bag = (Command)base.Value; Expression target; target = Expression.Call( Expression.Convert(self, typeof(Command)), typeof(Command).GetMethod("GetValue"), Expression.Constant(binder.Name) ); var restrictions = BindingRestrictions .GetInstanceRestriction(self, bag); return new DynamicMetaObject(target, restrictions); } #endregion } }

    Read the article

  • Better solution then simple factory method when concrete implementations have different attributes

    - by danip
    abstract class Animal { function eat() {..} function sleep() {..} function isSmart() } class Dog extends Animal { public $blnCanBark; function isSmart() { return $this->blnCanBark; } } class Cat extends Animal { public $blnCanJumpHigh; function isSmart() { return $this->blnCanJumpHigh; } } .. and so on up to 10-20 animals. Now I created a factory using simple factory method and try to create instances like this: class AnimalFactory { public static function create($strName) { switch($strName) { case 'Dog': return new Dog(); case 'Cat': return new Cat(); default: break; } } } The problem is I can't set the specific attributes like blnCanBark, blnCanJumpHigh in an efficient way. I can send all of them as extra params to create but this will not scale to more then a few classes. Also I can't break the inheritance because a lot of the basic functionality is the same. Is there a better pattern to solve this?

    Read the article

  • C# 4.0: casting dynamic to static

    - by Kevin Won
    This is an offshoot question that's related to another I asked here. I'm splitting it off because it's really a sub-question: I'm having difficulties casting an object of type dynamic to another (known) static type. I have an ironPython script that is doing this: import clr clr.AddReference("System") from System import * def GetBclUri(): return Uri("http://google.com") note that it's simply newing up a BCL System.Uri type and returning it. So I know the static type of the returned object. now over in C# land, I'm newing up the script hosting stuff and calling this getter to return the Uri object: dynamic uri = scriptEngine.GetBclUri(); System.Uri u = uri as System.Uri; // casts the dynamic to static fine Works no problem. I now can use the strongly typed Uri object as if it was originally instantiated statically. however.... Now I want to define my own C# class that will be newed up in dynamic-land just like I did with the Uri. My simple C# class: namespace Entity { public class TestPy // stupid simple test class of my own { public string DoSomething(string something) { return something; } } } Now in Python, new up an object of this type and return it: sys.path.append(r'C:..path here...') clr.AddReferenceToFile("entity.dll") import Entity.TestPy def GetTest(): return Entity.TestPy(); // the C# class then in C# call the getter: dynamic test = scriptEngine.GetTest(); Entity.TestPy t = test as Entity.TestPy; // t==null!!! here, the cast does not work. Note that the 'test' object (dynamic) is valid--I can call the DoSomething()--it just won't cast to the known static type string s = test.DoSomething("asdf"); // dynamic object works fine so I'm perplexed. the BCL type System.Uri will cast from a dynamic type to the correct static one, but my own type won't. There's obviously something I'm not getting about this...

    Read the article

  • When should method overloads be refactored?

    - by Ben Heley
    When should code that looks like: DoThing(string foo, string bar); DoThing(string foo, string bar, int baz, bool qux); ... DoThing(string foo, string bar, int baz, bool qux, string more, string andMore); Be refactored into something that can be called like so: var doThing = new DoThing(foo, bar); doThing.more = value; doThing.andMore = otherValue; doThing.Go(); Or should it be refactored into something else entirely? In the particular case that inspired this question, it's a public interface for an XSLT templating DLL where we've had to add various flags (of various types) that can't be embedded into the string XML input.

    Read the article

  • Sort method versus OrderBy LINQ extension method

    - by nmarun
    I have a class Product with an Id and a Name as properties. There are multiple ways of getting a list of products to display in sorted/ordered fashion, say, by the Name of the product. The two I’m concerned about here are the Sort and the OrderBy extension method through LINQ and the difference between them. 1: public class Product 2: { 3: public int Id { get; set; } 4: public string Name { get; set; } 5: } Below is the list of products that I’ll be using and is defined somewhere in the Program.cs...(read more)

    Read the article

  • MAKE CROSS THREAD METHOD CALLS USING INVOKE METHOD OF THE CONTROL

    Cross threading is a phenomina normally happening in any of application debug session. Developer may not able to understand what's this all about. He may not actually coded for any such scenario like Threading. But this exception may raise especially in side a method where you are accessing any of the GUI control menthod. One natural scenaio will happen, once you are handling with FielSystemWatcher class. But here 1st I will create a sceanrio and then will give you 2 way resolution too.

    Read the article

  • Dynamic VPN tunneling technologies

    - by Adam
    Ok, so I'm asking a more specific question this time. I'm writing a paper about Cisco's DMVPN and one of the tasks I have is to make the analysis of available network solutions which use dynamic VPN tunnels. Because the paper is about DMVPN, I have to compare those solutions to it. I know there are a lot of dynamic tunneling technologies but I'm looking for ones that can be compared to DMVPN. So the question is: are there any technologies which use dynamic VPN tunnels (not necessarily using crypto) that can be compared to DMVPN? What are those technologies?

    Read the article

  • LibGDX onTouch() method Array and flip method

    - by johnny-b
    How can I add this on my application. i want to use the onTouch() method from the implementation of the InputProcessor to kill the enemies on screen. how do i do that? do i have to do anything to the enemy class? also i am trying to add a Array of enemies and it keeps throwing exceptions or the bullet now is facing LEFT <--- again after I used the flip method in the bullet class. All the code is below so please anyone feel free to have a look thanks. please help Thank you M // This is the bullet class. public class Bullet extends Sprite { public static final float BULLET_HOMING = 6000; public static final float BULLET_SPEED = 300; private Vector2 velocity; private float lifetime; private Rectangle bul; public Bullet(float x, float y) { velocity = new Vector2(0, 0); setPosition(x, y); AssetLoader.bullet1.flip(true, false); AssetLoader.bullet2.flip(true, false); setSize(AssetLoader.bullet1.getWidth(), AssetLoader.bullet1.getHeight()); bul = new Rectangle(); } public void update(float delta) { float targetX = GameWorld.getBall().getX(); float targetY = GameWorld.getBall().getY(); float dx = targetX - getX(); float dy = targetY - getY(); float distToTarget = (float) Math.sqrt(dx * dx + dy * dy); dx /= distToTarget; dy /= distToTarget; dx *= BULLET_HOMING; dy *= BULLET_HOMING; velocity.x += dx * delta; velocity.y += dy * delta; float vMag = (float) Math.sqrt(velocity.x * velocity.x + velocity.y * velocity.y); velocity.x /= vMag; velocity.y /= vMag; velocity.x *= BULLET_SPEED; velocity.y *= BULLET_SPEED; bul.set(getX(), getY(), getOriginX(), getOriginY()); Vector2 v = velocity.cpy().scl(delta); setPosition(getX() + v.x, getY() + v.y); setOriginCenter(); setRotation(velocity.angle()); } public Rectangle getBounds() { return bul; } public Rectangle getBounds1() { return this.getBoundingRectangle(); } } // This is the class where i load all the images from public class AssetLoader { public static Texture texture; public static TextureRegion bg, ball1, ball2; public static Animation bulletAnimation, ballAnimation; public static Sprite bullet1, bullet2; public static void load() { texture = new Texture(Gdx.files.internal("SpriteN1.png")); texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest); bg = new TextureRegion(texture, 80, 421, 395, 30); bg.flip(false, true); ball1 = new TextureRegion(texture, 0, 321, 32, 32); ball1.flip(false, true); ball2 = new TextureRegion(texture, 32, 321, 32, 32); ball2.flip(false, true); bullet1 = new Sprite(texture, 380, 350, 45, 20); bullet1.flip(false, true); bullet2 = new Sprite(texture, 425, 350, 45, 20); bullet2.flip(false, true); TextureRegion[] balls = { ball1, ball2 }; ballAnimation = new Animation(0.16f, balls); ballAnimation.setPlayMode(Animation.PlayMode.LOOP); } Sprite[] bullets = { bullet1, bullet2 }; bulletAnimation = new Animation(0.06f, aims); bulletAnimation.setPlayMode(Animation.PlayMode.LOOP); } public static void dispose() { texture.dispose(); } // This is for the rendering or drawing onto the screen/canvas. public class GameRenderer { private Bullet bullet; private Ball ball; public GameRenderer(GameWorld world) { myWorld = world; cam = new OrthographicCamera(); cam.setToOrtho(true, 480, 320); batcher = new SpriteBatch(); // Attach batcher to camera batcher.setProjectionMatrix(cam.combined); shapeRenderer = new ShapeRenderer(); shapeRenderer.setProjectionMatrix(cam.combined); // Call helper methods to initialize instance variables initGameObjects(); initAssets(); } private void initGameObjects() { ball = GameWorld.getBall(); bullet = myWorld.getBullet(); scroller = myWorld.getScroller(); } private void initAssets() { ballAnimation = AssetLoader.ballAnimation; bulletAnimation = AssetLoader.bulletAnimation; } public void render(float runTime) { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT); batcher.begin(); batcher.disableBlending(); batcher.enableBlending(); batcher.draw(AssetLoader.ballAnimation.getKeyFrame(runTime), ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight()); batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY(), bullet.getOriginX(), bullet.getOriginY(), bullet.getWidth(), bullet.getHeight(), 1.0f, 1.0f, bullet.getRotation()); // End SpriteBatch batcher.end(); } } // this is to load the image etc on the screen i guess public class GameWorld { public static Ball ball; private Bullet bullet; private ScrollHandler scroller; public GameWorld() { ball = new Ball(480, 273, 32, 32); bullet = new Bullet(10, 10); scroller = new ScrollHandler(0); } public void update(float delta) { ball.update(delta); bullet.update(delta); scroller.update(delta); } public static Ball getBall() { return ball; } public ScrollHandler getScroller() { return scroller; } public Bullet getBullet() { return bullet; } } //This is the input handler class public class InputHandler implements InputProcessor { private Ball myBall; private Bullet bullet; private GameRenderer aims; // Ask for a reference to the Soldier when InputHandler is created. public InputHandler(Ball ball) { myBall = ball; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { return false; } @Override public boolean keyDown(int keycode) { return false; } @Override public boolean keyUp(int keycode) { return false; } @Override public boolean keyTyped(char character) { return false; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return false; } @Override public boolean mouseMoved(int screenX, int screenY) { return false; } @Override public boolean scrolled(int amount) { return false; } } i am rendering all graphics in a GameRender class and a gameworld class if you need more info please let me know I am trying to make the array work but keep finding that when an array is initialized then the bullet fips back to the original and ends up being backwards???? and if I create an array I keep getting Exceptions throw??? Thank you for any help given.

    Read the article

  • Win 8: Adding a boot volume to an MBR dynamic disk [NOT about changing to basic disks]

    - by Stilez
    (This is NOT aiming to convert to basic disk. In this question, the disk stays dynamic but becomes bootable) There doesn't seem to be a clear, well stated answer I can find, for the question "What are the criteria for Windows 8 to successfully boot from an MBR dynamic disk", or "how do I fix a dynamic MBR partition that's failing boot"? I've tried to educate myself but can't find crucial information to clear it all up. My existing HDD/SSD setup: DISK 0 ~ 60GB SSD/MBR/basic: (350MB recovery)(60GB windows 8 bootable) DISK 1 ~ 512GB SSD/MBR/dynamic: (350MB recovery)(60GB unallocated)(410GB mirrored data) DISK 2 ~ 512GB SSD/MBR/dynamic: (350MB recovery)(60GB unallocated)(410GB mirrored data) DISKS 3, 4, 5: (ignored for simplicity: 2xHDD RAID1 + caching SSD) I'm heavy duty on data crunching and virtualisation, just maxxed out 32GB RAM @ 2133 and moved to 4960X + 64GB. Disk 0 is a pure system disk of little value, and virtualisations runs off mirrored SSDs (Samsung 840 Pro 512 x 2) for double speed reading and so they snapshot in reasonable time. I'm using 4 SATA3 ports and the board only has two decent Intel ports (onboard Marvell are poorer quality). I'm wary of choosing between LSI, HighPoint and other 3rd party controllers as I'm unfamiliar with the maze of decent RAID cards (that's a whole other issue!). I want to cut down my SSD needs by moving the boot volume and caching volume to the 840 pros, giving a setup with 2 fewer SSDs: DISK 0 ~ 512GB SSD/MBR/dynamic: (350MB recovery)(60GB boot)(410GB mirrored data) DISK 1 ~ 512GB SSD/MBR/dynamic: (350MB recovery)(30GB cache for the ICH10R mirror)(30GB temp)(410GB mirrored data) DISKS 2, 3: (2xHDD RAID1) Intel's RST allows this, Win 8 allows booting off a MBR/dynamic disk, and the two 60GB SSDs are hardly the fastest SSDs anyway, they'll get repurposed. Moving the caching volume is easy. Moving the boot volume has me stumped. The difficulty is, I'm hitting a wall of knowledge here. I have a UEFI Asus motherboard with an previous traditional MBR/basic boot disk, and I want it to boot from a disk and volume that's MBR/dynamic. The disk copy is physically ok (Partition Wizard Server will copy to dynamic volumes) but then hits a light blue 0xc000000e boot error. No real surprise, I expected to have some boot fixing, but had expected Windows to boot-fix it (all drivers exist), or the usual manual fixes to work. Specifically, I don't know enough, to know what's got to be manually checked and perhaps corrected for the disk to boot (legacy/uefi/bios, odd partitions, boot tables, disk IDs, hidden boot files, oh my!), or if I need to change any of this secure boot/UEFI/legacy stuff in the bios, convert a 512 SSD to basic and then back to dynamic when working, or if the issue is pure OS config using "diskpart", "bootsect" and "bootrec" from the Win8 DVD. The old system disk still boots but I don't know enough to figure what to fix, to make the system boot as I want. The answers probably aren't hard but the real issue is my confusion and missing information. Thanks for helping!

    Read the article

  • An Epic Question "How to call a method when the page loads"

    - by Arunkumar Ramamoorthy
    Quite often, there comes a question in OTN, with different subjects, all meaning "How to call a method when my ADF page loads?". More often, people tend to take the approach of ADF Phase Listener by overriding before/afterPhase methods.In this blog, we will go through different options in achieving it.1. Method Call Activity as default activity in Taskflow :If the application is built with taskflows, then this is the best suited approach to take. 1.a. Calling a Data Control Method :To call a Data Control method (ex: A method in AMImpl exposed as client interface), simply Drag and Drop the method as Default Method Call Activity, then draw a control flow case from the method to your page. Once after this, drop the taskflow as region in main page. When we run the main page, the Method Call Activity would be called first, and then the page will be rendered.1.b. Calling a Method in Backing Bean: To call a method in the backing bean before pageload, we can follow the similar approach as above. Instead of binding the Method Call Activity to an action/method binding in pagedef, we bind to the method. Insert a Method Call Activity (and make it as default) from the Component Palette. Double click on to select a method to bind. This approach can also be used, to perform some action in backing bean along with calling a method Data Control (just need to add bindings code in backing bean to execute DC method). 2. Using invokeAction Executable :If the application is built with pages and no taskflows are involved, then this option can be taken into consideration.In the page definition of the page, add an invokeAction Executable and bind it to the method needed to be executed. 3. Using combination of Server and Client Listeners : If the page does not have any page definition, then to call a method in backing bean, this approach can be taken. In this, a serverListener would be added at the document level, which would be calling the method in backing bean. Along with this, a clientListener would be added with "load" type (i.e will be triggered when the page loads), which would queue a serverEvent to trigger the method. 4. Using Page Phase Listener :This should be the last resort. Care should be taken when using this approach since the Phase Listener would be called for each request sent by the client.Zeeshan Baig's blog covers this scenario.

    Read the article

  • An Epic Question "How to call a method when the page loads"

    - by Arunkumar Ramamoorthy
    Quite often, there comes a question in OTN, with different subjects, all meaning "How to call a method when my ADF page loads?". More often, people tend to take the approach of ADF Phase Listener by overriding before/afterPhase methods.In this blog, we will go through different options in achieving it.1. Method Call Activity as default activity in Taskflow :If the application is built with taskflows, then this is the best suited approach to take. 1.a. Calling a Data Control Method :To call a Data Control method (ex: A method in AMImpl exposed as client interface), simply Drag and Drop the method as Default Method Call Activity, then draw a control flow case from the method to your page. Once after this, drop the taskflow as region in main page. When we run the main page, the Method Call Activity would be called first, and then the page will be rendered.1.b. Calling a Method in Backing Bean: To call a method in the backing bean before pageload, we can follow the similar approach as above. Instead of binding the Method Call Activity to an action/method binding in pagedef, we bind to the method. Insert a Method Call Activity (and make it as default) from the Component Palette. Double click on to select a method to bind. This approach can also be used, to perform some action in backing bean along with calling a method Data Control (just need to add bindings code in backing bean to execute DC method). 2. Using invokeAction Executable :If the application is built with pages and no taskflows are involved, then this option can be taken into consideration.In the page definition of the page, add an invokeAction Executable and bind it to the method needed to be executed. 3. Using combination of Server and Client Listeners : If the page does not have any page definition, then to call a method in backing bean, this approach can be taken. In this, a serverListener would be added at the document level, which would be calling the method in backing bean. Along with this, a clientListener would be added with "load" type (i.e will be triggered when the page loads), which would queue a serverEvent to trigger the method. 4. Using Page Phase Listener :This should be the last resort. Care should be taken when using this approach since the Phase Listener would be called for each request sent by the client.Zeeshan Baig's blog covers this scenario.

    Read the article

  • How Do I Implement parameterMaps for ADF Regions and Dynamic Regions?

    - by david.giammona
    parameterMap objects defined by managed beans can help reduce the number of child <parameter> elements listed under an ADF region or dynamic region page definition task flow binding. But more importantly, the parameterMap approach also allows greater flexibility in determining what input parameters are passed to an ADF region or dynamic region. This can be especially helpful when using dynamic regions where each task flow utilized can provide an entirely different set of input parameters. The parameterMap is specified within an ADF region or dynamic region page definition task flow binding as shown below: <taskFlow id="checkoutflow1" taskFlowId="/WEB-INF/checkout-flow.xml#checkout-flow" activation="deferred" xmlns="http://xmlns.oracle.com/adf/controller/binding" parametersMap="#{pageFlowScope.userInfoBean.parameterMap}"/> The parameter map object must implement the java.util.Map interface. The keys it specifies match the names of input parameters defined by the task flows utilized within the task flow binding. An example parameterMap object class is shown below: import java.util.HashMap; import java.util.Map; public class UserInfoBean { private Map<String, Object> parameterMap = new HashMap<String, Object>(); public Map getParameterMap() { parameterMap.put("isLoggedIn", getSecurity().isAuthenticated()); parameterMap.put("principalName", getSecurity().getPrincipalName()); return parameterMap; }

    Read the article

  • NGINX: dynamic locations stored in DB

    - by chimpanzee
    Is there a possibility to store nginx locations in DB instead of the config to serve them dynamically? The task is to create dynamic URLs for video files based on user's IP and video ID. The idea is when the user visits my website such an dynamic URL is created and added to the db as a new nginx location that exists just for this user and not for others. Or nginx doesn't fit my task and I need to use another tool? Thanks.

    Read the article

  • SSH dynamic port forwarding, "Connection refused"

    - by crodjer
    I am trying to do dynamic portforwarding using openssh through a remote computer following this command: ssh -D 6789 rohan@<remote_ip> -p <remote_port> This should set up a socks server on my comp as I assume. I am able to use this for normal browsing but can't connect to IRC or remote ssh (through proxychains). I get this error: channel 3: open failed: connect failed: Connection refused A high verbosity level output of the error: $ debug1: Connection to port 6789 forwarding to socks port 0 requested. debug2: fd 9 setting TCP_NODELAY debug2: fd 9 setting O_NONBLOCK debug3: fd 9 is O_NONBLOCK debug1: channel 3: new [dynamic-tcpip] debug2: channel 3: pre_dynamic: have 0 debug2: channel 3: pre_dynamic: have 4 debug2: channel 3: decode socks5 debug2: channel 3: socks5 auth done debug2: channel 3: pre_dynamic: need more debug2: channel 3: pre_dynamic: have 0 debug2: channel 3: pre_dynamic: have 10 debug2: channel 3: decode socks5 debug2: channel 3: socks5 post auth debug2: channel 3: dynamic request: socks5 host 4.2.2.2 port 53 command 1 debug3: Wrote 96 bytes for a total of 3335 channel 3: open failed: connect failed: Connection refused debug2: channel 3: zombie debug2: channel 3: garbage collecting debug1: channel 3: free: direct-tcpip: listening port 6789 for 4.2.2.2 port 53, connect from 127.0.0.1 port 33694, nchannels 4 debug3: channel 3: status: The following connections are open: #2 client-session (t4 r0 i0/0 o0/0 fd 6/7 cfd -1) debug3: channel 3: close_fds r 9 w 9 e -1 c -1 I googled for this too, but couldn't find any solutions.

    Read the article

  • SQLite3's dynamic typing

    - by Bradford Larsen
    SQLite3 uses dynamic typing rather than static typing, in contrast to other flavors of SQL. The SQLite website reads: Most SQL database engines (every SQL database engine other than SQLite, as far as we know) uses static, rigid typing. With static typing, the datatype of a value is determined by its container - the particular column in which the value is stored. SQLite uses a more general dynamic type system. In SQLite, the datatype of a value is associated with the value itself, not with its container. It seems to me that this is exactly what you don't want, as it lets you store, for example, strings in integer columns. The page continues: ...the dynamic typing in SQLite allows it to do things which are not possible in traditional rigidly typed databases. I have two questions: The use case question: What are some examples where sqlite3's dynamic typing is, in fact, beneficial? The historical/design question: What was the motivation for implementing sqlite with dynamic typing?

    Read the article

  • Creating dynamic generics at runtime using Reflection

    - by MPhlegmatic
    I'm trying to convert a Dictionary< dynamic, dynamic to a statically-typed one by examining the types of the keys and values and creating a new Dictionary of the appropriate types using Reflection. If I know the key and value types, I can do the following: Type dictType = typeof(Dictionary<,>); newDict = Activator.CreateInstance(dictType.MakeGenericType(new Type[] { keyType, valueType })); However, I may need to create, for example, a Dictionary< MyKeyType, dynamic if the values are not all of the same type, and I can't figure out how to specify the dynamic type, since typeof(dynamic) isn't viable. How would I go about doing this, and/or is there a simpler way to accomplish what I'm trying to do?

    Read the article

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