Search Results

Search found 57 results on 3 pages for 'dlr'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • IronPython memory leak?

    - by Mike Gates
    Run this: for i in range(1000000000): a = [] It looks like the list objects being created never get marked for garbage collection. From a memory profiler, it looks like the interpreter's stack frame is holding onto all the list objects, so GC can never do anything about it. Is this by design?

    Read the article

  • C# 4.0: Dynamic Programming

    - by Paulo Morgado
    The major feature of C# 4.0 is dynamic programming. Not just dynamic typing, but dynamic in broader sense, which means talking to anything that is not statically typed to be a .NET object. Dynamic Language Runtime The Dynamic Language Runtime (DLR) is piece of technology that unifies dynamic programming on the .NET platform, the same way the Common Language Runtime (CLR) has been a common platform for statically typed languages. The CLR always had dynamic capabilities. You could always use reflection, but its main goal was never to be a dynamic programming environment and there were some features missing. The DLR is built on top of the CLR and adds those missing features to the .NET platform. The Dynamic Language Runtime is the core infrastructure that consists of: Expression Trees The same expression trees used in LINQ, now improved to support statements. Dynamic Dispatch Dispatches invocations to the appropriate binder. Call Site Caching For improved efficiency. Dynamic languages and languages with dynamic capabilities are built on top of the DLR. IronPython and IronRuby were already built on top of the DLR, and now, the support for using the DLR is being added to C# and Visual Basic. Other languages built on top of the CLR are expected to also use the DLR in the future. Underneath the DLR there are binders that talk to a variety of different technologies: .NET Binder Allows to talk to .NET objects. JavaScript Binder Allows to talk to JavaScript in SilverLight. IronPython Binder Allows to talk to IronPython. IronRuby Binder Allows to talk to IronRuby. COM Binder Allows to talk to COM. Whit all these binders it is possible to have a single programming experience to talk to all these environments that are not statically typed .NET objects. The dynamic Static Type Let’s take this traditional statically typed code: Calculator calculator = GetCalculator(); int sum = calculator.Sum(10, 20); Because the variable that receives the return value of the GetCalulator method is statically typed to be of type Calculator and, because the Calculator type has an Add method that receives two integers and returns an integer, it is possible to call that Sum method and assign its return value to a variable statically typed as integer. Now lets suppose the calculator was not a statically typed .NET class, but, instead, a COM object or some .NET code we don’t know he type of. All of the sudden it gets very painful to call the Add method: object calculator = GetCalculator(); Type calculatorType = calculator.GetType(); object res = calculatorType.InvokeMember("Add", BindingFlags.InvokeMethod, null, calculator, new object[] { 10, 20 }); int sum = Convert.ToInt32(res); And what if the calculator was a JavaScript object? ScriptObject calculator = GetCalculator(); object res = calculator.Invoke("Add", 10, 20); int sum = Convert.ToInt32(res); For each dynamic domain we have a different programming experience and that makes it very hard to unify the code. With C# 4.0 it becomes possible to write code this way: dynamic calculator = GetCalculator(); int sum = calculator.Add(10, 20); You simply declare a variable who’s static type is dynamic. dynamic is a pseudo-keyword (like var) that indicates to the compiler that operations on the calculator object will be done dynamically. The way you should look at dynamic is that it’s just like object (System.Object) with dynamic semantics associated. Anything can be assigned to a dynamic. dynamic x = 1; dynamic y = "Hello"; dynamic z = new List<int> { 1, 2, 3 }; At run-time, all object will have a type. In the above example x is of type System.Int32. When one or more operands in an operation are typed dynamic, member selection is deferred to run-time instead of compile-time. Then the run-time type is substituted in all variables and normal overload resolution is done, just like it would happen at compile-time. The result of any dynamic operation is always dynamic and, when a dynamic object is assigned to something else, a dynamic conversion will occur. Code Resolution Method double x = 1.75; double y = Math.Abs(x); compile-time double Abs(double x) dynamic x = 1.75; dynamic y = Math.Abs(x); run-time double Abs(double x) dynamic x = 2; dynamic y = Math.Abs(x); run-time int Abs(int x) The above code will always be strongly typed. The difference is that, in the first case the method resolution is done at compile-time, and the others it’s done ate run-time. IDynamicMetaObjectObject The DLR is pre-wired to know .NET objects, COM objects and so forth but any dynamic language can implement their own objects or you can implement your own objects in C# through the implementation of the IDynamicMetaObjectProvider interface. When an object implements IDynamicMetaObjectProvider, it can participate in the resolution of how method calls and property access is done. The .NET Framework already provides two implementations of IDynamicMetaObjectProvider: DynamicObject : IDynamicMetaObjectProvider The DynamicObject class enables you to define which operations can be performed on dynamic objects and how to perform those operations. For example, you can define what happens when you try to get or set an object property, call a method, or perform standard mathematical operations such as addition and multiplication. ExpandoObject : IDynamicMetaObjectProvider The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember, instead of more complex syntax like sampleObject.GetAttribute("sampleMember").

    Read the article

  • Edd strikes again &ndash; IronRuby for Rubyists on InfoQ

    - by Eric Nelson
    Colleague, friend and generally top guy on IronRuby Edd Morgan has just been published over on InfoQ. To wet the appetite… a snippet or three. IronRuby for Rubyists IronRuby is Microsoft's implementation of the Ruby language we all know and love with the added bonus of interoperability with the .NET framework — the Iron in the name is actually an acronym for 'Implementation running on .NET'. It's supported by the .NET Common Language Runtime as well as, albeit unofficially, the Mono project. You'd be forgiven for harbouring some question in your mind about running a dynamic language such as Ruby atop the CLR - that's where the DLR (Dynamic Language Runtime) comes in. The DLR is Microsoft's way of providing dynamic language capability on top of the CLR. Both IronRuby and the DLR are, as part of Microsoft's commitment to open source software, available as part of the Microsoft Public License on GitHub and CodePlex respectively… And Metaprogramming with IronRuby The art and science of metaprogramming — especially in Ruby, where it's an absolute joy — is something that could very easily span an entire article. As you would hope, IronRuby code is fully able to manipulate itself allowing you to bend your classes to your whim just as you would expect with a good dynamic language… And Riding the irails? So let's get to the point. I think it's a solid bet to make that a large proportion of Ruby programmers are familiar with the Rails framework - perhaps it's even safe to assume that most were first led to the Ruby language by the siren song of the Rails framework itself. Long story short, IronRuby is compatible enough to run your Rails app… Now… get yourself over to the full article and also check out some of Edds other work below. Related Links: 5 Steps to getting started with IronRuby Mini Book Review of IronRuby Unleashed by Shay Friedman Guest Post: Using IronRuby and .NET to produce the ‘Hello World of WPF’ – also by Edd Getting PhP and Ruby working on Windows Azure and SQL Azure Guest Post: What's IronRuby, and how do I put it on Rails? – also by Edd

    Read the article

  • Most wanted feature for C# 4.0 ?

    - by Romain Verdier
    Some blogs on the Internet give us several clues of what C# 4.0 would be made of. I would like to know what do you really want to see in C# 4.0. Here are some related articles: C# 4 tag on Jon Skeet's blog 4 features for C# 4 What do you want in C# 4 Future Focus - I: Dynamic Lookup .NET 4, C# 4 and the DLR Channel 9 also hosts a very interesting video where Anders Hejlsberg and the C# 4.0 design team talk about the upcoming version of the language. I'm particularly excited about dynamic lookup and AST. I hope we would be able to leverage - at some level - the underlying DLR mechanisms from C#-the-static-language. What about you ?

    Read the article

  • HTTP request failed! HTTP/1.1 505 HTTP Version Not Supported error

    - by shyam
    I'm trying to use file_get_contentsO() to get the response from a server and this error was encountered. Could someone tell me what is the reason and how to fix it? The portion of the code is: $api = "http://smpp5.routesms.com:8080/bulksms/sendsms?username=$username&password=$password&source=$source&destination=$destin&dlr=$dlr&type=$type&message=$message"; $resp = file_get_contents($api); The server responded correctly while I pasted the url in the browser. I learned that this is caused by the server rejecting the client's HTTP version, but I have no idea why that is happening in my case. Any help is much appreciated. Thanks in advance

    Read the article

  • Impromptu-interface

    - by Sean Feldman
    While trying to solve a problem of removing conditional execution from my code, I wanted to take advantage of .NET 4.0 and it’s dynamic capabilities. Going with DynamicObject or ExpandoObject initially didn’t get me any success since those by default support properties and indexes, but not methods. Luckily, I have a reply for my post and learned about this great OSS library called impromptu-interface. It based on DLR capabilities in .NET 4.0 and I have to admit that it made my code extremely simple – no more if :)

    Read the article

  • PCLinuxOS 2010 (KDE) Review

    <b>Desktop Linux Reviews:</b> "The last time I looked at PCLinuxOS was back in 2009 when I was working full-time for ExtremeTech. There's a new release out and it's a good time for a review of it here on DLR."

    Read the article

  • Windows8, JavaScript and HTML5 - A good thing?

    - by Albers
    Most of us have seen the Windows 8 news regarding support for native HTML5/JavaScript applications. The press has pushed this as a potential threat to the .NET developer community because JavaScript and HTML5 were called "our new developer platform". The press release refers to "Web-connected and Web-powered apps built using HTML5 and JavaScript that have access to the full power of the PC.".Microsoft has also been hush on details related to these comments. Before we buy the hype and start worrying about a world where we drop our Visual Studio licenses and buy DreamWeaver - let's think about how Windows 8 HTML/JavaScript applications would be implemented. The HTML5 spec offers support for offline applications, but this won't offer the OS-integrated experience the press release refers to. MS has to be planning a way to extend access beyond the traditional JavaScript feature set. Microsoft has a similar option today: HTML Applications or HTAs. They come close to required features, but HTAs need ActiveX or Java integration to provide the promised OS-level access. I'm guessing that Microsoft's future OS strategy isn't built on developers cranking out ActiveX controls or Java applets. So where is Microsoft headed? One possibility is that MS builds a new JavaScript framework from the ground up outside their current APIs. Another idea would be for Microsoft to add support for JavaScript as a first class .NET language using the Dynamic Language Runtime. A solution based on the DLR could be integrated into an HTA-like model to provide the promised access, along with the full range of features in .NET Framework. Security comes included in the Framework. And the work necessary to support this integration would tie in nicely with the effort MS has recently made providing better JavaScript and HTML5 support in Visual Studio 2010. As a bonus, a full-fledged JavaScript DLR implementation would allow single language web solutions across client and server (think node.js) and would appeal to developers who are familiar with JavaScript but have less experience with the Microsoft tech stack. We will all get a better picture after the Build conference in September. But in the mean time we know that Microsoft has a reputation for providing strong developer support. We might want to reserve our harshest judgement and consider that the press release could hint at new opportunities for .NET development.

    Read the article

  • Getting Rails Application Running Under IronRuby Rack

    - by NotMyself
    Anyone else playing with ironruby? I have successfully got the IronRuby.Rails.Example project running on my local machine under IIS 5.1. I am now attempting to get my own demo rails site running in the same way. My web.config is slightly different from the example project. I am attempting to only use what was distributed with IronRuby 1.0 and what I have installed using gems. I am getting the following error which doesn't give me a lot to go on: D:/demo/config/boot.rb:66:in `exit': exit (SystemExit) After trying many different things, I think it is having a problem finding gems. I have attached my web config and ironrack.log. Does anyone have pointers on what I am doing wrong? Thanks! <?xml version="1.0"?> <configuration> <configSections> <!-- custom configuration section for DLR hosting --> <section name="microsoft.scripting" type="Microsoft.Scripting.Hosting.Configuration.Section, Microsoft.Scripting" requirePermission="false"/> </configSections> <system.webServer> <handlers> <!-- clear all other handlers first. Don't do this if you have other handlers you want to run --> <clear/> <!-- This hooks up the HttpHandler which will dispatch all requests to Rack --> <add name="IronRuby" path="*" verb="*" type="IronRuby.Rack.HttpHandlerFactory, IronRuby.Rack" resourceType="Unspecified" requireAccess="Read" preCondition="integratedMode"/> </handlers> </system.webServer> <system.web> <!-- make this true if you want to debug any of the DLR code, IronRuby.Rack, or your own managed code --> <compilation debug="true"/> <httpHandlers> <!-- clear all other handlers first. Don't do this if you have other handlers you want to run --> <clear/> <!-- This hooks up the HttpHandler which will dispatch all requests to Rack --> <add path="*" verb="*" type="IronRuby.Rack.HttpHandlerFactory, IronRuby.Rack" /> </httpHandlers> </system.web> <!-- DLR configuration. Set debugMode to "true" if you want to debug your dynamic language code with VS --> <microsoft.scripting debugMode="false"> <options> <!-- Library paths: make sure these paths are correct --> <!--<set option="LibraryPaths" value="..\..\..\Languages\Ruby\libs\; ..\..\..\..\External.LCA_RESTRICTED\Languages\Ruby\ruby-1.8.6p368\lib\ruby\site_ruby\1.8\; ..\..\..\..\External.LCA_RESTRICTED\Languages\Ruby\ruby-1.8.6p368\lib\ruby\1.8\"/>--> <set option="LibraryPaths" value="C:\IronRuby\lib\IronRuby;C:\IronRuby\lib\ruby\1.8;C:\IronRuby\lib\ruby\site_ruby;C:\IronRuby\lib\ruby\site_ruby\1.8"/> </options> </microsoft.scripting> <appSettings> <add key="AppRoot" value="."/> <add key="Log" value="ironrack.log"/> <!-- <add key="GemPath" value="..\..\..\..\External.LCA_RESTRICTED\Languages\Ruby\ruby-1.8.6p368\lib\ruby\gems\1.8"/> --> <add key="GemPath" value="C:\IronRuby\Lib\ironruby\gems\1.8\gems"/> <add key="RackEnv" value="production"/> </appSettings> </configuration> === Booting ironruby-rack at 4/15/2010 1:27:12 PM [DEBUG] >>> TOPLEVEL_BINDING = binding => Setting GEM_PATH: 'C:\\IronRuby\\Lib\\ironruby\\gems\\1.8\\gems' => Setting RACK_ENV: 'production' => Loading RubyGems [DEBUG] >>> require 'rubygems' => Loading Rack >=1.0.0 [DEBUG] >>> gem 'rack', '>=1.0.0';require 'rack' => Loaded rack-1.1 => Application root: 'D:\\demo' => Loading Rack application [DEBUG] >>> Rack::Builder.new { ( require "config/environment" ENV['RAILS_ENV'] = 'development' use Rails::Rack::LogTailer use Rails::Rack::Static run ActionController::Dispatcher.new ) }.to_app exit D:/demo/config/boot.rb:66:in `exit': exit (SystemExit) from D:/demo/config/boot.rb:66:in `load_rails_gem' from D:/demo/config/boot.rb:54:in `load_initializer' from D:/demo/config/boot.rb:38:in `run' from D:/demo/config/boot.rb:11:in `boot!' from D:/demo/config/boot.rb:110 from C:/IronRuby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from C:/IronRuby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from D:/demo/config/environment.rb:7 from C:/IronRuby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from C:/IronRuby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from (eval):1 from C:/IronRuby/lib/ironruby/gems/1.8/gems/rack-1.1.0/lib/rack/builder.rb:46:in `instance_eval' from C:/IronRuby/lib/ironruby/gems/1.8/gems/rack-1.1.0/lib/rack/builder.rb:46:in `initialize' from (eval):0 from D:\Dev\ironruby\ironruby-ironruby-20bc41b\Merlin\Main\Hosts\IronRuby.Rack\RubyEngine.cs:52:in `Execute' from D:\Dev\ironruby\ironruby-ironruby-20bc41b\Merlin\Main\Hosts\IronRuby.Rack\RubyEngine.cs:45:in `Execute' from D:\Dev\ironruby\ironruby-ironruby-20bc41b\Merlin\Main\Hosts\IronRuby.Rack\Application.cs:68:in `Rackup' from D:\Dev\ironruby\ironruby-ironruby-20bc41b\Merlin\Main\Hosts\IronRuby.Rack\Application.cs:32:in `.ctor' from D:\Dev\ironruby\ironruby-ironruby-20bc41b\Merlin\Main\Hosts\IronRuby.Rack\HttpHandlerFactory.cs:37:in `GetHandler' from System.Web:0:in `MapHttpHandler' from System.Web:0:in `System.Web.HttpApplication.IExecutionStep.Execute' from System.Web:0:in `ExecuteStep' from System.Web:0:in `ResumeSteps' from System.Web:0:in `System.Web.IHttpAsyncHandler.BeginProcessRequest' from System.Web:0:in `ProcessRequestInternal' from System.Web:0:in `ProcessRequestNoDemand' from System.Web:0:in `ProcessRequest'

    Read the article

  • Write your Tests in RSpec with IronRuby

    - by kazimanzurrashid
    [Note: This is not a continuation of my previous post, treat it as an experiment out in the wild. ] Lets consider the following class, a fictitious Fund Transfer Service: public class FundTransferService : IFundTransferService { private readonly ICurrencyConvertionService currencyConvertionService; public FundTransferService(ICurrencyConvertionService currencyConvertionService) { this.currencyConvertionService = currencyConvertionService; } public void Transfer(Account fromAccount, Account toAccount, decimal amount) { decimal convertionRate = currencyConvertionService.GetConvertionRate(fromAccount.Currency, toAccount.Currency); decimal convertedAmount = convertionRate * amount; fromAccount.Withdraw(amount); toAccount.Deposit(convertedAmount); } } public class Account { public Account(string currency, decimal balance) { Currency = currency; Balance = balance; } public string Currency { get; private set; } public decimal Balance { get; private set; } public void Deposit(decimal amount) { Balance += amount; } public void Withdraw(decimal amount) { Balance -= amount; } } We can write the spec with MSpec + Moq like the following: public class When_fund_is_transferred { const decimal ConvertionRate = 1.029m; const decimal TransferAmount = 10.0m; const decimal InitialBalance = 100.0m; static Account fromAccount; static Account toAccount; static FundTransferService fundTransferService; Establish context = () => { fromAccount = new Account("USD", InitialBalance); toAccount = new Account("CAD", InitialBalance); var currencyConvertionService = new Moq.Mock<ICurrencyConvertionService>(); currencyConvertionService.Setup(ccv => ccv.GetConvertionRate(Moq.It.IsAny<string>(), Moq.It.IsAny<string>())).Returns(ConvertionRate); fundTransferService = new FundTransferService(currencyConvertionService.Object); }; Because of = () => { fundTransferService.Transfer(fromAccount, toAccount, TransferAmount); }; It should_decrease_from_account_balance = () => { fromAccount.Balance.ShouldBeLessThan(InitialBalance); }; It should_increase_to_account_balance = () => { toAccount.Balance.ShouldBeGreaterThan(InitialBalance); }; } and if you run the spec it will give you a nice little output like the following: When fund is transferred » should decrease from account balance » should increase to account balance 2 passed, 0 failed, 0 skipped, took 1.14 seconds (MSpec). Now, lets see how we can write exact spec in RSpec. require File.dirname(__FILE__) + "/../FundTransfer/bin/Debug/FundTransfer" require "spec" require "caricature" describe "When fund is transferred" do Convertion_Rate = 1.029 Transfer_Amount = 10.0 Initial_Balance = 100.0 before(:all) do @from_account = FundTransfer::Account.new("USD", Initial_Balance) @to_account = FundTransfer::Account.new("CAD", Initial_Balance) currency_convertion_service = Caricature::Isolation.for(FundTransfer::ICurrencyConvertionService) currency_convertion_service.when_receiving(:get_convertion_rate).with(:any, :any).return(Convertion_Rate) fund_transfer_service = FundTransfer::FundTransferService.new(currency_convertion_service) fund_transfer_service.transfer(@from_account, @to_account, Transfer_Amount) end it "should decrease from account balance" do @from_account.balance.should be < Initial_Balance end it "should increase to account balance" do @to_account.balance.should be > Initial_Balance end end I think the above code is self explanatory, treat the require(line 1- 4) statements as the add reference of our visual studio projects, we are adding all the required libraries with this statement. Next, the describe which is a RSpec keyword. The before does exactly the same as NUnit's Setup or MsTest’s TestInitialize attribute, but in the above we are using before(:all) which acts as ClassInitialize of MsTest, that means it will be executed only once before all the test methods. In the before(:all) we are first instantiating the from and to accounts, it is same as creating with the full name (including namespace)  like fromAccount = new FundTransfer.Account(.., ..), next, we are creating a mock object of ICurrencyConvertionService, check that for creating the mock we are not using the Moq like the MSpec version. This is somewhat an interesting issue of IronRuby or maybe the DLR, it seems that it is not possible to use the lambda expression that most of the mocking tools uses in arrange phase in Iron Ruby, like: currencyConvertionService.Setup(ccv => ccv.GetConvertionRate(Moq.It.IsAny<string>(), Moq.It.IsAny<string>())).Returns(ConvertionRate); But the good news is, there is already an excellent mocking tool called Caricature written completely in IronRuby which we can use to mock the .NET classes. May be all the mocking tool providers should give some thought to add the support for the DLR, so that we can use the tool that we are already familiar with. I think the rest of the code is too simple, so I am skipping the explanation. Now, the last thing, how we are going to run it with RSpec, lets first install the required gems. Open you command prompt and type the following: igem sources -a http://gems.github.com This will add the GitHub as gem source. Next type: igem install uuidtools caricature rspec and at last we have to create a batch file so that we can execute it in the Notepad++, create a batch like in the IronRuby bin directory like my previous post and put the following in that batch file: @echo off cls call spec %1 --format specdoc pause Next, add a run menu and shortcut in the Notepad++ like my previous post. Now when we run it it will show the following output: When fund is transferred - should decrease from account balance - should increase to account balance Finished in 0.332042 seconds 2 examples, 0 failures Press any key to continue . . . You will complete code of this post in the bottom. That's it for today. Download: RSpecIntegration.zip

    Read the article

  • Most Up-To-Date C# Duck-Typing Library

    - by Anton Gogolev
    The title says it all, basically. What is the current state of the art on duck typing for C# below version 4.0? I know about Duck Typing Project, I know that BLTookit has something to that end, but I'd like to know if I'm missing something really wicked apart from DLR languages and C# 4.0. The inevitable:

    Read the article

  • What do I need to develop an Iron Python web app in Visual Studio 2010

    - by Greg
    Hi, I've got Visual Studio 2010. To develop a web app in Iron Python (i.e. to use a Ruby like language not C#) what downloads to I need? e.g. is the DLR already in VS2010, Iron Python itself Once setup would I actually be still developing an ASP.net MVC web app but just using Ruby for the language, or is the model something different to this? thanks

    Read the article

  • Creating a Dynamic DataRow for easier DataRow Syntax

    - by Rick Strahl
    I've been thrown back into an older project that uses DataSets and DataRows as their entity storage model. I have several applications internally that I still maintain that run just fine (and I sometimes wonder if this wasn't easier than all this ORM crap we deal with with 'newer' improved technology today - but I disgress) but use this older code. For the most part DataSets/DataTables/DataRows are abstracted away in a pseudo entity model, but in some situations like queries DataTables and DataRows are still surfaced to the business layer. Here's an example. Here's a business object method that runs dynamic query and the code ends up looping over the result set using the ugly DataRow Array syntax:public int UpdateAllSafeTitles() { int result = this.Execute("select pk, title, safetitle from " + Tablename + " where EntryType=1", "TPks"); if (result < 0) return result; result = 0; foreach (DataRow row in this.DataSet.Tables["TPks"].Rows) { string title = row["title"] as string; string safeTitle = row["safeTitle"] as string; int pk = (int)row["pk"]; string newSafeTitle = this.GetSafeTitle(title); if (newSafeTitle != safeTitle) { this.ExecuteNonQuery("update " + this.Tablename + " set safeTitle=@safeTitle where pk=@pk", this.CreateParameter("@safeTitle",newSafeTitle), this.CreateParameter("@pk",pk) ); result++; } } return result; } The problem with looping over DataRow objecs is two fold: The array syntax is tedious to type and not real clear to look at, and explicit casting is required in order to do anything useful with the values. I've highlighted the place where this matters. Using the DynamicDataRow class I'll show in a minute this code can be changed to look like this:public int UpdateAllSafeTitles() { int result = this.Execute("select pk, title, safetitle from " + Tablename + " where EntryType=1", "TPks"); if (result < 0) return result; result = 0; foreach (DataRow row in this.DataSet.Tables["TPks"].Rows) { dynamic entry = new DynamicDataRow(row); string newSafeTitle = this.GetSafeTitle(entry.title); if (newSafeTitle != entry.safeTitle) { this.ExecuteNonQuery("update " + this.Tablename + " set safeTitle=@safeTitle where pk=@pk", this.CreateParameter("@safeTitle",newSafeTitle), this.CreateParameter("@pk",entry.pk) ); result++; } } return result; } The code looks much a bit more natural and describes what's happening a little nicer as well. Well, using the new dynamic features in .NET it's actually quite easy to implement the DynamicDataRow class. Creating your own custom Dynamic Objects .NET 4.0 introduced the Dynamic Language Runtime (DLR) and opened up a whole bunch of new capabilities for .NET applications. The dynamic type is an easy way to avoid Reflection and directly access members of 'dynamic' or 'late bound' objects at runtime. There's a lot of very subtle but extremely useful stuff that dynamic does (especially for COM Interop scenearios) but in its simplest form it often allows you to do away with manual Reflection at runtime. In addition you can create DynamicObject implementations that can perform  custom interception of member accesses and so allow you to provide more natural access to more complex or awkward data structures like the DataRow that I use as an example here. Bascially you can subclass DynamicObject and then implement a few methods (TryGetMember, TrySetMember, TryInvokeMember) to provide the ability to return dynamic results from just about any data structure using simple property/method access. In the code above, I created a custom DynamicDataRow class which inherits from DynamicObject and implements only TryGetMember and TrySetMember. Here's what simple class looks like:/// <summary> /// This class provides an easy way to turn a DataRow /// into a Dynamic object that supports direct property /// access to the DataRow fields. /// /// The class also automatically fixes up DbNull values /// (null into .NET and DbNUll to DataRow) /// </summary> public class DynamicDataRow : DynamicObject { /// <summary> /// Instance of object passed in /// </summary> DataRow DataRow; /// <summary> /// Pass in a DataRow to work off /// </summary> /// <param name="instance"></param> public DynamicDataRow(DataRow dataRow) { DataRow = dataRow; } /// <summary> /// Returns a value from a DataRow items array. /// If the field doesn't exist null is returned. /// DbNull values are turned into .NET nulls. /// /// </summary> /// <param name="binder"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { result = null; try { result = DataRow[binder.Name]; if (result == DBNull.Value) result = null; return true; } catch { } result = null; return false; } /// <summary> /// Property setter implementation tries to retrieve value from instance /// first then into this object /// </summary> /// <param name="binder"></param> /// <param name="value"></param> /// <returns></returns> public override bool TrySetMember(SetMemberBinder binder, object value) { try { if (value == null) value = DBNull.Value; DataRow[binder.Name] = value; return true; } catch {} return false; } } To demonstrate the basic features here's a short test: [TestMethod] [ExpectedException(typeof(RuntimeBinderException))] public void BasicDataRowTests() { DataTable table = new DataTable("table"); table.Columns.Add( new DataColumn() { ColumnName = "Name", DataType=typeof(string) }); table.Columns.Add( new DataColumn() { ColumnName = "Entered", DataType=typeof(DateTime) }); table.Columns.Add(new DataColumn() { ColumnName = "NullValue", DataType = typeof(string) }); DataRow row = table.NewRow(); DateTime now = DateTime.Now; row["Name"] = "Rick"; row["Entered"] = now; row["NullValue"] = null; // converted in DbNull dynamic drow = new DynamicDataRow(row); string name = drow.Name; DateTime entered = drow.Entered; string nulled = drow.NullValue; Assert.AreEqual(name, "Rick"); Assert.AreEqual(entered,now); Assert.IsNull(nulled); // this should throw a RuntimeBinderException Assert.AreEqual(entered,drow.enteredd); } The DynamicDataRow requires a custom constructor that accepts a single parameter that sets the DataRow. Once that's done you can access property values that match the field names. Note that types are automatically converted - no type casting is needed in the code you write. The class also automatically converts DbNulls to regular nulls and vice versa which is something that makes it much easier to deal with data returned from a database. What's cool here isn't so much the functionality - even if I'd prefer to leave DataRow behind ASAP -  but the fact that we can create a dynamic type that uses a DataRow as it's 'DataSource' to serve member values. It's pretty useful feature if you think about it, especially given how little code it takes to implement. By implementing these two simple methods we get to provide two features I was complaining about at the beginning that are missing from the DataRow: Direct Property Syntax Automatic Type Casting so no explicit casts are required Caveats As cool and easy as this functionality is, it's important to understand that it doesn't come for free. The dynamic features in .NET are - well - dynamic. Which means they are essentially evaluated at runtime (late bound). Rather than static typing where everything is compiled and linked by the compiler/linker, member invokations are looked up at runtime and essentially call into your custom code. There's some overhead in this. Direct invocations - the original code I showed - is going to be faster than the equivalent dynamic code. However, in the above code the difference of running the dynamic code and the original data access code was very minor. The loop running over 1500 result records took on average 13ms with the original code and 14ms with the dynamic code. Not exactly a serious performance bottleneck. One thing to remember is that Microsoft optimized the DLR code significantly so that repeated calls to the same operations are routed very efficiently which actually makes for very fast evaluation. The bottom line for performance with dynamic code is: Make sure you test and profile your code if you think that there might be a performance issue. However, in my experience with dynamic types so far performance is pretty good for repeated operations (ie. in loops). While usually a little slower the perf hit is a lot less typically than equivalent Reflection work. Although the code in the second example looks like standard object syntax, dynamic is not static code. It's evaluated at runtime and so there's no type recognition until runtime. This means no Intellisense at development time, and any invalid references that call into 'properties' (ie. fields in the DataRow) that don't exist still cause runtime errors. So in the case of the data row you still get a runtime error if you mistype a column name:// this should throw a RuntimeBinderException Assert.AreEqual(entered,drow.enteredd); Dynamic - Lots of uses The arrival of Dynamic types in .NET has been met with mixed emotions. Die hard .NET developers decry dynamic types as an abomination to the language. After all what dynamic accomplishes goes against all that a static language is supposed to provide. On the other hand there are clearly scenarios when dynamic can make life much easier (COM Interop being one place). Think of the possibilities. What other data structures would you like to expose to a simple property interface rather than some sort of collection or dictionary? And beyond what I showed here you can also implement 'Method missing' behavior on objects with InvokeMember which essentially allows you to create dynamic methods. It's all very flexible and maybe just as important: It's easy to do. There's a lot of power hidden in this seemingly simple interface. Your move…© Rick Strahl, West Wind Technologies, 2005-2011Posted in CSharp  .NET   Tweet (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

  • DevDays ‘00 The Netherlands day #2

    - by erwin21
    Day 2 of DevDays 2010 and again 5 interesting sessions at the World Forum in The Hague. The first session of the today in the big world forum theater was from Scott Hanselman, he gives a lap around .NET 4.0. In his way of presenting he talked about all kind of new features of .NET 4.0 like MEF, threading, parallel processing, changes and additions to the CLR and DLR, WPF and all new language features of .NET 4.0. After a small break it was ready for session 2 from Scott Allen about Tips, Tricks and Optimizations of LINQ. He talked about lazy and deferred executions, the difference between IQueryable and IEnumerable and the two flavors of LINQ syntax. The lunch was again very good prepared and delicious, but after that it was time for session 3 Web Vulnerabilities and Exploits from Alex Thissen. This was no normal session but more like a workshop, we decided what kind of subjects we discussed, the subjects where OWASP, XSS and other injections, validation, encoding. He gave some handy tips and tricks how to prevent such attacks. Session 4 was about the new features of C# 4.0 from Alex van Beek. He talked about Optional- en Named Parameters, Generic Co- en Contra Variance, Dynamic keyword and COM Interop features. He showed how to use them but also when not to use them. The last session of today and also the last session of DevDays 2010 was about WCF Best Practices from Gerben van Loon. He talked about 7 best practices that you must know when you are going to use WCF. With some quick demos he showed the problem and the solution for some common issues. It where two interesting days and next year i sure will be attending again.

    Read the article

  • Is there a literal notation for decimal in IronPython?

    - by jeroenh
    suppose I have the following IronPython script: def Calculate(input): return input * 1.21 When called from C# with a decimal, this function returns a double: var python = Python.CreateRuntime(); dynamic engine = python.UseFile("mypythonscript.py") decimal input = 100M; // input is of type Decimal // next line throws RuntimeBinderException: // "cannot implicitly convert double to decimal" decimal result = engine.Calculate(input); I seem to have two options: First, I could cast at the C# side: seems like a no-go as I might loose precision. decimal result = (decimal)engine.Calculate(input); Second option is to use System.Decimal in the python script: works, but pollutes the script, which should be understandable for my users... import clr import System def CalculateVAT(amount): return amount * System.Decimal(1.21) Is there a way to tell the DLR that the number 1.21 should be interpreted as a Decimal, much like I would use the '1.21M' notation in C#?

    Read the article

  • Combining GPL with MPL and BSD

    - by thr
    I have a software project I want to release under GPLv3, it uses two pieces of code that other parties have developed (one is the DLR by Microsoft, which is under the Microsoft Public License and the other piece of code is under the New BSD License). The BSD licensed code is compiled into the same binary as my code (but none of it is changed) The Ms-PL licensed code is compiled into another assembly next to my code and linked at runtime (and none of it is changed what so ever). Can I release my software under GPLv3 and without any legal problems?

    Read the article

  • Retrieving accessors in IronRuby

    - by rsteckly
    I'm trying to figure out how to retrieve the value stored in the Person class. The problem is just that after I define an instance of the Person class, I don't know how to retrieve it within the IronRuby code because the instance name is in the .NET part. /*class Person attr_accessor :name def initialize(strname) self.name=strname end end*/ //We start the DLR, in this case starting the Ruby version ScriptEngine engine = IronRuby.Ruby.CreateEngine(); ScriptScope scope = engine.ExecuteFile("c:\\Users\\ron\\RubymineProjects\\untitled\\person.rb"); //We get the class type object person = engine.Runtime.Globals.GetVariable("Person"); //We create an instance object marcy = engine.Operations.CreateInstance(person, "marcy");

    Read the article

  • [dynamic] Different behaviours between .NET 4.0 beta 2 and last release of .NET 4.0 !

    - by yogi4ever
    Hi. I've identified a difference of DLR between .NET 4.0 Beta 2 and the last release of .NET 4.0. In .NET 4.0 Beta 2, this code perfectly works at runtime : var dateTimeList = new List(); dynamic myDynamicObject = dateTimeList; object value = DateTime.Now; myDynamicObject.Add(value); Now, with last release of .NET 4.0, I have an exception at run time (to solve myDynamicObject.Add(value);) :-( In my real code, 'myDynamicObject' is a dynamic (but I know that it is always an ObservableCollection where T can be anything). 'value' is an instance which was got by some reflexions. As 'value' can have any type, the type of 'value' is Object. Do you see how can I solve this new limitation of .NET 4.0 ? Thanks

    Read the article

  • playsms sent sms to queue

    - by user512213
    i install playsms in my system as below mentioned way https://github.com/antonraharja/playSMS/wiki/Web-User-Interface-Installation i use kannel as a gateway and kannel running fine i get the following status while i check kannel status in browser. Kannel bearerbox version `1.4.3'. Build `Nov 24 2011 08:02:18', compiler `4.6.2'. System Linux, release 3.2.0-23-generic-pae, version #36-Ubuntu SMP Tue Apr 10 22:19:09 UTC 2012, machine i686. Hostname MSSRF-INCOIS, IP 127.0.1.1. Libxml version 2.7.8. Using OpenSSL 1.0.0e 6 Sep 2011. Compiled with MySQL 5.5.17, using MySQL 5.5.24. Using SQLite 3.7.9. Using native malloc. Status: running, uptime 0d 1h 8m 27s WDP: received 0 (0 queued), sent 0 (0 queued) SMS: received 0 (0 queued), sent 0 (0 queued), store size -1 SMS: inbound (0.00,0.00,0.00) msg/sec, outbound (0.00,0.00,0.00) msg/sec DLR: 0 queued, using internal storage Box connections: wapbox, IP 127.0.0.1 (on-line 0d 1h 8m 2s) wapbox, IP 127.0.0.1 (on-line 0d 0h 18m 11s) SMSC connections: unknown AT2[/dev/ttyS0] (online 4106s, rcvd 0, sent 0, failed 0, queued 0 msgs) But when i try to send sms in playsms means it shows "Your SMS has been delivered to queue " but sms not received .Any thing we missed out while configuration.any one advice me to proceed.

    Read the article

  • BindingFlags.DeclaredOnly alternative to avoid ambiguous properties of derived classes

    - by JoeBilly
    I'am looking for a solution to access 'flatten' (lowest) properties values of a class and its derived via reflection by property names. ie access either Property1 or Property2 from the ClassB or ClassC type : public class ClassA { public virtual object Property1 { get; set; } public object Property2 { get; set; } } public class ClassB : ClassA { public override object Property1 { get; set; } } public class ClassC : ClassB { } Using simple reflection works until you have virtual properties that are overrired (ie Property1 from ClassB). Then you get a AmbiguousMatchException because the searcher don't know if you want the property of the main class or the derived. Using BindingFlags.DeclaredOnly avoid the AmbiguousMatchException but unoverrided virtual properties or derived classes properties are ommited (ie Property2 from ClassB). Is there an alternative to this poor workaround : // Get the main class property with the specified propertyName PropertyInfo propertyInfo = _type.GetProperty(propertyName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); // If not found, get the property wherever it is if (propertyInfo == null) propertyInfo = _type.GetProperty(propertyName); Furthermore, this workaround not resolve the reflection of 2nd level properties : getting Property1 from ClassC and AmbiguousMatchException is back. My thoughts : I have no choice except loop... Erk... ?? I'am open to Emit, Lambda (is the Expression.Call can handle this?) even DLR solution. Thanks !

    Read the article

  • Execute JavaScript from within a C# assembly

    - by ScottKoon
    I'd like to execute JavaScript code from within a C# assembly and have the results of the JavaScript code returned to the calling C# code. It's easier to define things that I'm not trying to do: I'm not trying to call a JavaScript function on a web page from my code behind. I'm not trying to load a WebBrowser control. I don't want to have the JavaScript perform an AJAX call to a server. What I want to do is write unit tests in JavaScript and have then unit tests output JSON, even plain text would be fine. Then I want to have a generic C# class/executible that can load the file containing the JS, run the JS unit tests, scrap/load the results, and return a pass/fail with details during a post-build task. I think it's possible using the old ActiveX ScriptControl, but it seems like there ought to be a .NET way to do this without using SilverLight, the DLR, or anything else that hasn't shipped yet. Anyone have any ideas? update: From Brad Abrams blog namespace Microsoft.JScript.Vsa { [Obsolete("There is no replacement for this feature. Please see the ICodeCompiler documentation for additional help. http://go.microsoft.com/fwlink/?linkid=14202")] Clarification: We have unit tests for our JavaScript functions that are written in JavaScript using the JSUnit framework. Right now during our build process, we have to manually load a web page and click a button to ensure that all of the JavaScript unit tests pass. I'd like to be able to execute the tests during the post-build process when our automated C# unit tests are run and report the success/failure alongside of out C# unit tests and use them as an indicator as to whether or not the build is broken.

    Read the article

  • Scott Guthrie in Glasgow

    - by Martin Hinshelwood
    Last week Scott Guthrie was in Glasgow for his new Guathon tour, which was a roaring success. Scott did talks on the new features in Visual Studio 2010, Silverlight 4, ASP.NET MVC 2 and Windows Phone 7. Scott talked from 10am till 4pm, so this can only contain what I remember and I am sure lots of things he discussed just went in one ear and out another, however I have tried to capture at least all of my Ohh’s and Ahh’s. Visual Studio 2010 Right now you can download and install Visual Studio 2010 Candidate Release, but soon we will have the final product in our hands. With it there are some amazing improvements, and not just in the IDE. New versions of VB and C# come out of the box as well as Silverlight 4 and SharePoint 2010 integration. The new Intellisense features allow inline support for Types and Dictionaries as well as being able to type just part of a name and have the list filter accordingly. Even better, and my personal favourite is one that Scott did not mention, and that is that it is not case sensitive so I can actually find things in C# with its reasonless case sensitivity (Scott, can we please have an option to turn that off.) Another nice feature is the Routing engine that was created for ASP.NET MVC is now available for WebForms which is good news for all those that just imported the MVC DLL’s to get at it anyway. Another fantastic feature that will need some exploring is the ability to add validation rules to your entities and have them validated automatically on the front end. This removes the need to add your own validators and means that you can control an objects validation rules from a single location, the object. A simple command “GridView.EnableDynamicData(gettype(product))“ will enable this feature on controls. What was not clear was wither there would be support for this in WPF and WinForms as well. If there is, we can write our validation rules once and use everywhere. I was disappointed to here that there would be no inbuilt support for the Dynamic Language Runtime (DLR) with VS2010, but I think it will be there for .vNext. Because I have been concentrating on the Visual Studio ALM enhancements to VS2010 I found this section invaluable as I now know at least some of what I missed. Silverlight 4 I am not a big fan of Silverlight. There I said it, and I will probably get lynched for it. My big problem with Silverlight is that most of the really useful things I leaned from WPF do not work. I am only going to mention one thing and that is “x:Type”. If you are a WPF developer you will know how much power these 6 little letters provide; the ability to target templates at object types being the the most magical and useful. But, and this is a massive but, if you are developing applications that MUST run on platforms other than windows then Silverlight is your only choice (well that and Flash, but lets just not go there). And Silverlight has a huge install base as well.. 60% of all internet connected devices have Silverlight. Can Adobe say that? Even though I am not a fan of it my current project is a Silverlight one. If you start your XAML experience with Silverlight you will not be disappointed and neither will the users of the applications you build. Scott showed us a fantastic application called “Silverface” that is a Silverlight 4 Out of Browser application. I have looked for a link and can’t find one, but true to form, here is a fantastic WPF version called Fish Bowl from Microsoft. ASP.NET MVC 2 ASP.NET MVC is something I have played with but never used in anger. It is definitely the way forward, but WebForms is not dead yet. there are still circumstances when WebForms are better. If you are starting from greenfield and you are using TDD, then MVC is ultimately the only way you can go. New in version 2 are Dynamic Scaffolding helpers that let you control how data is presented in the UI from the Entities. Adding validation rules and other options that make sense there can help improve the overall ease of developing the UI. Also the Microsoft team have heard the cries of help from the larger site builders and provided “Areas” which allow a level of categorisation to your Controllers and Views. These work just like add-ins and have their own folder, but also have sub Controllers and Views. Areas are totally pluggable and can be dropped onto existing sites giving the ability to have boxed products in MVC, although what you do with all of those views is anyone's guess. They have been listening to everyone again with the new option to encapsulate UI using the Html.Action or Html.ActionRender. This uses the existing  .ascx functionality in ASP.NET to render partial views to the screen in certain areas. While this was possible before, it makes the method official thereby opening it up to the masses and making it a standard. At the end of the session Scott pulled out some IIS goodies including the IIS SEO Toolkit which can be used to verify your own site is “good” for search engine consumption. Better yet he suggested that you run it against your friends sites and shame them with how bad they are. note: make sure you have fixed yours first. Windows Phone 7 Series I had already seen the new UI for WP7 and heard about the developer story, but Scott brought that home by building a twitter application in about 20 minutes using the emulator. Scott’s only mistake was loading @plip’s tweets into the app… And guess what, it was written in Silverlight. When Windows Phone 7 launches you will be able to use about 90% of the codebase of your existing Silverlight application and use it on the phone! There are two downsides to the new WP7 architecture: No, your existing application WILL NOT work without being converted to either a Silverlight or XNA UI. NO, you will not be able to get your applications onto the phone any other way but through the Marketplace. Do I think these are problems? No, not even slightly. This phone is aimed at consumers who have probably never tried to install an application directly onto a device. There will be support for enterprise apps in the future, but for now enterprises should stay on Windows Phone 6.5.x devices. Post Event drinks At the after event drinks gathering Scott was checking out my HTC HD2 (released to the US this month on T-Mobile) and liked the Windows Phone 6.5.5 build I have on it. We discussed why Microsoft were not going to allow Windows Phone 7 Series onto it with my understanding being that it had 5 buttons and not 3, while Scott was sure that there was more to it from a hardware standpoint. I think he is right, and although the HTC HD2 has a DX9 compatible processor, it was never built with WP7 in mind. However, as if by magic Saturday brought fantastic news for all those that have already bought an HD2: Yes, this appears to be Windows Phone 7 running on a HTC HD2. The HD2 itself won't be getting an official upgrade to Windows Phone 7 Series, so all eyes are on the ROM chefs at the moment. The rather massive photos have been posted by Tom Codon on HTCPedia and they've apparently got WiFi, GPS, Bluetooth and other bits working. The ROM isn't online yet but according to the post there's a beta version coming soon. Leigh Geary - http://www.coolsmartphone.com/news5648.html  What was Scott working on on his flight back to the US?   Technorati Tags: VS2010,MVC2,WP7S,WP7 Follow: @CAMURPHY, @ColinMackay, @plip and of course @ScottGu

    Read the article

  • MVC 3 AdditionalMetadata Attribute with ViewBag to Render Dynamic UI

    - by Steve Michelotti
    A few months ago I blogged about using Model metadata to render a dynamic UI in MVC 2. The scenario in the post was that we might have a view model where the questions are conditionally displayed and therefore a dynamic UI is needed. To recap the previous post, the solution was to use a custom attribute called [QuestionId] in conjunction with an “ApplicableQuestions” collection to identify whether each question should be displayed. This allowed me to have a view model that looked like this: 1: [UIHint("ScalarQuestion")] 2: [DisplayName("First Name")] 3: [QuestionId("NB0021")] 4: public string FirstName { get; set; } 5: 6: [UIHint("ScalarQuestion")] 7: [DisplayName("Last Name")] 8: [QuestionId("NB0022")] 9: public string LastName { get; set; } 10: 11: [UIHint("ScalarQuestion")] 12: [QuestionId("NB0023")] 13: public int Age { get; set; } 14: 15: public IEnumerable<string> ApplicableQuestions { get; set; } At the same time, I was able to avoid repetitive IF statements for every single question in my view: 1: <%: Html.EditorFor(m => m.FirstName, new { applicableQuestions = Model.ApplicableQuestions })%> 2: <%: Html.EditorFor(m => m.LastName, new { applicableQuestions = Model.ApplicableQuestions })%> 3: <%: Html.EditorFor(m => m.Age, new { applicableQuestions = Model.ApplicableQuestions })%> by creating an Editor Template called “ScalarQuestion” that encapsulated the IF statement: 1: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 2: <%@ Import Namespace="DynamicQuestions.Models" %> 3: <%@ Import Namespace="System.Linq" %> 4: <% 5: var applicableQuestions = this.ViewData["applicableQuestions"] as IEnumerable<string>; 6: var questionAttr = this.ViewData.ModelMetadata.ContainerType.GetProperty(this.ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(QuestionIdAttribute), true) as QuestionIdAttribute[]; 7: string questionId = null; 8: if (questionAttr.Length > 0) 9: { 10: questionId = questionAttr[0].Id; 11: } 12: if (questionId != null && applicableQuestions.Contains(questionId)) { %> 13: <div> 14: <%: Html.Label("") %> 15: <%: Html.TextBox("", this.Model)%> 16: </div> 17: <% } %> You might want to go back and read the full post in order to get the full context. MVC 3 offers a couple of new features that make this scenario more elegant to implement. The first step is to use the new [AdditionalMetadata] attribute which, so far, appears to be an under appreciated new feature of MVC 3. With this attribute, I don’t need my custom [QuestionId] attribute anymore - now I can just write my view model like this: 1: [UIHint("ScalarQuestion")] 2: [DisplayName("First Name")] 3: [AdditionalMetadata("QuestionId", "NB0021")] 4: public string FirstName { get; set; } 5:   6: [UIHint("ScalarQuestion")] 7: [DisplayName("Last Name")] 8: [AdditionalMetadata("QuestionId", "NB0022")] 9: public string LastName { get; set; } 10:   11: [UIHint("ScalarQuestion")] 12: [AdditionalMetadata("QuestionId", "NB0023")] 13: public int Age { get; set; } Thus far, the documentation seems to be pretty sparse on the AdditionalMetadata attribute. It’s buried in the Other New Features section of the MVC 3 home page and, after showing the attribute on a view model property, it just says, “This metadata is made available to any display or editor template when a product view model is rendered. It is up to you to interpret the metadata information.” But what exactly does it look like for me to “interpret the metadata information”? Well, it turns out it makes the view much easier to work with. Here is the re-implemented ScalarQuestion template updated for MVC 3 and Razor: 1: @{ 2: object questionId; 3: ViewData.ModelMetadata.AdditionalValues.TryGetValue("QuestionId", out questionId); 4: if (ViewBag.applicableQuestions.Contains((string)questionId)) { 5: <div> 6: @Html.LabelFor(m => m) 7: @Html.TextBoxFor(m => m) 8: </div> 9: } 10: } So we’ve gone from 17 lines of code (in the MVC 2 version) to about 7-8 lines of code here. The first thing to notice is that in MVC 3 we now have a property called “AdditionalValues” that hangs off of the ModelMetadata property. This is automatically populated by any [AdditionalMetadata] attributes on the property. There is no more need for me to explicitly write Reflection code to GetCustomAttributes() and then check to see if those attributes were present. I can just call TryGetValue() on the dictionary to see if they were present. Secondly, the “applicableQuestions” anonymous type that I passed in from the calling view – in MVC 3 I now have a dynamic ViewBag property where I can just “dot into” the applicableQuestions with a nicer syntax than dictionary square bracket syntax. And there’s no problems calling the Contains() method on this dynamic object because at runtime the DLR has resolved that it is a generic List<string>. At this point you might be saying that, yes the view got much nicer than the MVC 2 version, but my view model got slightly worse.  In the previous version I had a nice [QuestionId] attribute but now, with the [AdditionalMetadata] attribute, I have to type the string “QuestionId” for every single property and hope that I don’t make a typo. Well, the good news is that it’s easy to create your own attributes that can participate in the metadata’s additional values. The key is that the attribute must implement that IMetadataAware interface and populate the AdditionalValues dictionary in the OnMetadataCreated() method: 1: public class QuestionIdAttribute : Attribute, IMetadataAware 2: { 3: public string Id { get; set; } 4:   5: public QuestionIdAttribute(string id) 6: { 7: this.Id = id; 8: } 9:   10: public void OnMetadataCreated(ModelMetadata metadata) 11: { 12: metadata.AdditionalValues["QuestionId"] = this.Id; 13: } 14: } This now allows me to encapuslate my “QuestionId” string in just one place and get back to my original attribute which can be used like this: [QuestionId(“NB0021”)]. The [AdditionalMetadata] attribute is a powerful and under-appreciated new feature of MVC 3. Combined with the dynamic ViewBag property, you can do some really interesting things with your applications with less code and ceremony.

    Read the article

< Previous Page | 1 2 3  | Next Page >