Search Results

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

Page 9/1512 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • C++ - dynamic pointer of array

    - by Eagle
    Hi to all, first i would like to say i am Newbie in C++. As part of my master thesis i am writing a program in C++ which also get as parameters the variables m and d (both integers). Were d is the power of 2 (this means 2^d elements). Parameter m define the number of possible interactions between one element and the total group (2^d elements). The number of possible interactions is computed as following: \kappa = \sum_{i=0}^m\binom{d}{i} (at present i generate vector of vectors for 2^d x \kappa, but my Prof. would like me to create different statistics to different m's. My first though was to to generate a dynamic array of m arrays of different sizes... Then i though of defining a 3-dim array with the biggest needed 2d array, but also program speed is important (e.g d = 20). i would like to ask for your advice how to define such kind of dynamic array that will also be fast. Regards

    Read the article

  • Static Website - Converting to Dynamic, need to import information from database on different host

    - by gvernold
    This seems really complicated to ask about so I hope someone can help: We have a long time running static website held with a hosting company that provide PHP, Ruby-on-Rails and Drupal/Joomla support. A little limited I know but we got reasonably decent search engine rankings and didn't want them to drop. We have two much more recently created sites on another host written in Python/Django. The original site is now too big to handle statically and we want to create a more dynamic site in its place without changing servers/webhosts. The data we want to provide the 'new' dynamic site is from the same database providing the Django sites. What is the best solution to build the new site with? Is it better to create PHP pages that connect to the database on the other host? Ruby-on-rails seems like a very fast development environment not too dissimilar to Django, would we be able to fetch data from the existing databases into a rails site and use similar urls to our old static pages?

    Read the article

  • "dynamic" keyword and JSON data

    - by Peter Perhác
    An action method in my ASP.NET MVC2 application returns a JsonResult object and in my unit test I would like to check that the returned JSON object indeed contains the expected values. I tried this: 1. dynamic json = ((JsonResult)myActionResult).Data; 2. Assert.AreEqual(JsonMessagesHelper.ErrorLevel.ERROR.ToString(), json.ErrorLevel); But I get a RuntimeBinderException "'object' does not contain a definition for 'ErrorLevel'". However, when I place a breakpoint on line 2 and inspect the json dynamic variable (see picture below), it obviously does contain the ErrorLevel string and it has the expected value, so if the runtime binder wasn't playing funny the test would pass. What am I not getting? What am I doing wrong and how can I fix this? How can I make the assertion pass?

    Read the article

  • Jquery cant get dynamic data

    - by Napoleon Wai Lun Wong
    i am a noob to using the jQuery i have a problem about the Uncaught SyntaxError: Unexpected token i am using the 1.9.0 version of jqery i am creating a dynamic number of record, each record would create a "tr" in a table ,also i want to add some dynamic coding into the textbox part of Html coding : <-tbody<-tr id="row_1"<-input id="1" name="collections[appearance][headersubcolor][entity_id1][name]" value="0" class="Root Catalog input-text" type="text" Click inside to change a color of each Category <-tr id="row_2"<-td class="label"<-td class="value"<-input id="2" name="collections[appearance][headersubcolor][entity_id2][name]" value="0" class="Default Category input-text" type="text".... jQuery coding : $('tr[id^="row_"]'.each(function(){ var rowid = parsInt(this.id.replace("row_","")); console.lof("id:"+ rowid); var ??? = new jscolor.color(document.getElementById('???'), {}) }); $('tr[id^="row_"]'.each(function() <--- i cant getting the DATA

    Read the article

  • Dot Game and Dynamic Programming

    - by Albert Diego
    I'm trying to solve a variant of the dot game with dynamic programming. The regular dot game is played with a line of dots. Each player takes either one or two dots at their respective end of the line and the person who is left with no dots to take wins. In this version of the game, each dot has a different value. Each player takes alternate turns and takes either dot at either end of the line. I want to come up with a way to use dynamic programming to find the max amount that the first player is guaranteed to win. I'm having problems grasping my head around this and trying to write a recurrence for the solution. Any help is appreciated, thanks!

    Read the article

  • Web SITE publishing, dynamic compilation, smoke & mirrors

    - by tbehunin
    When you publish a web SITE in Visual Studio, in the dialog box that follows, you are given an option to "Allow this precompiled site to be updatable". According to MSDN, checking this option "specifies that all program code is compiled into assemblies, but that .aspx files (including single-file ASP.NET Web pages) are copied as-is to the target folder". With this option checked, you can update existing .aspx files as well as add new ones without any issue. When a page, that has either been updated or newly created, is requested, the page gets dynamically compiled at run-time and is then processed and returned to the user. If, on the other hand, you didn't check that checkbox during the publish phase, the .aspx files get compiled, along with the code-behind and App_Code files in separate assemblies. The .aspx files are then completely overwritten with a line of text that says: This is a marker file generated by the precompilation tool, and should not be deleted! You obviously can't edit an existing page in this scenario. If you were to ADD a new .aspx file to this site, you would get a .Net run-time error saying that the file hasn't been precompiled. With that background, my questions are these: Something must be able to determine that this website was published to be updatable (allow dynamic compilation) or not. If it was published as updatable, it must also be able to determine whether a file was changed or added, so it can do a dynamic compile. Who makes those determinations? IIS? ASP.NET worker process? HOW does it make those determinations? If I had the same website published in both of those scenarios, could I make a visual determination that one is updatable and the other is not? Is there some bit I can look at in the assemblies using Reflector to make that determination myself? In addition to answering those questions, what also might be helpful would be information on the process flow from when a resource is requested to when it starts being processed, not necessarily the ASP.NET Page Lifecycle, but what happens BEFORE ASP.Net worker process starts processing the page and firing off events. The dynamic compilation appears to be smoke and mirrors. Can someone demystify this for me?

    Read the article

  • How to condense onclick code to be dynamic

    - by opbeta
    I am trying to get this onclick function code to be dynamic. I do not want to have 50 blocks of code for all the states. He is a quick snippet of the code var Ohio=function(){ document.getElementById('texas').style.display='none'; document.getElementById('florida').style.display='none'; document.getElementById('ohio').style.display='block'; } and so on and so forth..... How would I go about condensing this to make it smaller and dynamic?

    Read the article

  • System.Linq.Dynamic and DateTime

    - by Matthew Hood
    I am using System.Linq.Dynamic to do custom where clauses from an ajax call in .Net MVC 1.0. It works fine for strings, int etc but not for DateTime, I get the exception cannot compare String to DateTime. The very simple test code is items = items.Where(string.Format(@" {0} {1}{2}{1} ", searchField, delimiter, searchString)); Where searchField will be for example start_date and the data type is DateTime, delimiter is " (tried with nothing as well) and searchString will be 01-Jan-2009 (tried with 01/01/2009 as well) and items is an IQueryable from LinqToSql. Is there a way of specifying the data type in a dynamic where, or is there a better approach. It is currently already using some reflection to work out what type of delimiter is required.

    Read the article

  • Dynamic query to immediate execute?

    - by Curtis White
    I am using the MSDN Dynamic linq to sql package. It allows using strings for queries. But, the returned type is an IQueryable and not an IQueryable<T>. I do not have the ToList() method. How can I this immediate execute without manually enumerating over the IQueryable? My goal is to databind to the Selecting event on a linqtosql datasource and that throws a datacontext disposed exception. I can set the query as the Datasource on a gridview though. Any help greatly appreciated! Thanks. The dynamic linq to sql is the one from the samples that comes with visual studio.

    Read the article

  • c# marshaling dynamic-length string

    - by mitsky
    i have a struct with dynamic length [StructLayout(LayoutKind.Sequential, Pack = 1)] struct PktAck { public Int32 code; [MarshalAs(UnmanagedType.LPStr)] public string text; } when i'm converting bytes[] to struct by: GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); stru = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); handle.Free(); i have a error, because size of struct less than size of bytes[] and "string text" is pointer to string... how can i use dynamic strings? or i can use only this: [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]

    Read the article

  • How do I copy/clone a dynamic disk in Windows 7?

    - by PP
    I have some dynamic disks (or "partitions" but they are not really partitions) that I want to copy onto spare hard drives. I tried using gpartd (and fdisk for that matter) from a linux live disc. All it saw was hard drives with only one partition encasing the whole hard drive. So gpartd/fdisk is incapable of identifying the dynamic "partitions" and allowing me to copy them. Any tools that can be used to clone/copy a dynamic "partition"?

    Read the article

  • Generating a Call Hierarchy for dynamicly invoked method

    - by Maxim Veksler
    Hello, Today's world of dynamic invoke, reflection and runtime injection just doesn't play well with traditional tools such as ctags, doxygen and CDOC. I am searching for a method call hierarchy visualization tool that can display both static and dynamic method invocations. It should be easy to use, light during execution and provide helpful detailed information about the recorded runtime session. Now I guess Callgrind could be considered a valid solution for the family C. What tool / technique could you suggest to create a call graph for both static and dynamic method invocation for JVM based bytecode? The intended end result is a graphical display (preferably interactive) which can show path from main() to each method that was invoked. During research for this post I stumbled upon javashot, it seems that this is the kind of approach I'm aiming at, I would prefer that this would be integrated into a kind of profiler or alike which than can be used from within my IDE (Eclipse, IntelliJ, Netbeans and alike). Thank you, Maxim.

    Read the article

  • Create dynamic factory method in PHP (< 5.3)

    - by fireeyedboy
    How would one typically create a dynamic factory method in PHP? By dynamic factory method, I mean a factory method that will autodiscover what objects there are to create, based on some aspect of the given argument. Preferably without registering them first with the factory either. I'm OK with having the possible objects be placed in one common place (a directory) though. I want to avoid your typical switch statement in the factory method, such as this: public static function factory( $someObject ) { $className = get_class( $someObject ); switch( $className ) { case 'Foo': return new FooRelatedObject(); break; case 'Bar': return new BarRelatedObject(); break; // etc... } } My specific case deals with the factory creating a voting repository based on the item to vote for. The items all implement a Voteable interface. Something like this: Default_User implements Voteable ... Default_Comment implements Voteable ... Default_Event implements Voteable ... Default_VoteRepositoryFactory { public static function factory( Voteable $item ) { // autodiscover what type of repository this item needs // for instance, Default_User needs a Default_VoteRepository_User // etc... return new Default_VoteRepository_OfSomeType(); } } I want to be able to drop in new Voteable items and Vote repositories for these items, without touching the implementation of the factory.

    Read the article

  • Dynamic gridview columns event problem

    - by ropstah
    Hi, i have a GridView (selectable) in which I want to generate a dynamic GridView in a new row BELOW the selected row. I can add the row and gridview dynamically in the Gridview1 PreRender event. I need to use this event because: _OnDataBound is not called on every postback (same for _OnRowDataBound) _OnInit is not possible because the 'Inner table' for the Gridview is added after Init _OnLoad is not possible because the 'selected' row is not selected yet. I can add the columns to the dynamic GridView based on my ITemplate class. But now the button events won't fire.... Any suggestions? The dynamic adding of the gridview: Private Sub GridView1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.PreRender Dim g As GridView = sender g.DataBind() If g.SelectedRow IsNot Nothing AndAlso g.Controls.Count &gt; 0 Then Dim t As Table = g.Controls(0) Dim r As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal) Dim c As New TableCell Dim visibleColumnCount As Integer = 0 For Each d As DataControlField In g.Columns If d.Visible Then visibleColumnCount += 1 End If Next c.ColumnSpan = visibleColumnCount Dim ph As New PlaceHolder ph.Controls.Add(CreateStockGrid(g.SelectedDataKey.Value)) c.Controls.Add(ph) r.Cells.Add(c) t.Rows.AddAt(g.SelectedRow.RowIndex + 2, r) End If End Sub Private Function CreateStockGrid(ByVal PnmAutoKey As String) As GridView Dim col As Interfaces.esColumnMetadata Dim coll As New BLL.ViewStmCollection Dim entity As New BLL.ViewStm Dim query As BLL.ViewStmQuery = coll.Query Me._gridStock.AutoGenerateColumns = False Dim buttonf As New TemplateField() buttonf.ItemTemplate = New QuantityTemplateField(ListItemType.Item, "", "Button") buttonf.HeaderTemplate = New QuantityTemplateField(ListItemType.Header, "", "Button") buttonf.EditItemTemplate = New QuantityTemplateField(ListItemType.EditItem, "", "Button") Me._gridStock.Columns.Add(buttonf) For Each col In coll.es.Meta.Columns Dim headerf As New QuantityTemplateField(ListItemType.Header, col.PropertyName, col.Type.Name) Dim itemf As New QuantityTemplateField(ListItemType.Item, col.PropertyName, col.Type.Name) Dim editf As New QuantityTemplateField(ListItemType.EditItem, col.PropertyName, col.Type.Name) Dim f As New TemplateField() f.HeaderTemplate = headerf f.ItemTemplate = itemf f.EditItemTemplate = editf Me._gridStock.Columns.Add(f) Next query.Where(query.PnmAutoKey.Equal(PnmAutoKey)) coll.LoadAll() Me._gridStock.ID = "gvChild" Me._gridStock.DataSource = coll AddHandler Me._gridStock.RowCommand, AddressOf Me.gv_RowCommand Me._gridStock.DataBind() Return Me._gridStock End Function The ITemplate class: Public Class QuantityTemplateField : Implements ITemplate Private _itemType As ListItemType Private _fieldName As String Private _infoType As String Public Sub New(ByVal ItemType As ListItemType, ByVal FieldName As String, ByVal InfoType As String) Me._itemType = ItemType Me._fieldName = FieldName Me._infoType = InfoType End Sub Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn Select Case Me._itemType Case ListItemType.Header Dim l As New Literal l.Text = "&lt;b&gt;" & Me._fieldName & "</b>" container.Controls.Add(l) Case ListItemType.Item Select Case Me._infoType Case "Button" Dim ib As New Button() Dim eb As New Button() ib.ID = "InsertButton" eb.ID = "EditButton" ib.Text = "Insert" eb.Text = "Edit" ib.CommandName = "Edit" eb.CommandName = "Edit" AddHandler ib.Click, AddressOf Me.InsertButton_OnClick AddHandler eb.Click, AddressOf Me.EditButton_OnClick container.Controls.Add(ib) container.Controls.Add(eb) Case Else Dim l As New Label l.ID = Me._fieldName l.Text = "" AddHandler l.DataBinding, AddressOf Me.OnDataBinding container.Controls.Add(l) End Select Case ListItemType.EditItem Select Case Me._infoType Case "Button" Dim b As New Button b.ID = "UpdateButton" b.Text = "Update" b.CommandName = "Update" b.OnClientClick = "return confirm('Sure?')" container.Controls.Add(b) Case Else Dim t As New TextBox t.ID = Me._fieldName AddHandler t.DataBinding, AddressOf Me.OnDataBinding container.Controls.Add(t) End Select End Select End Sub Private Sub InsertButton_OnClick(ByVal sender As Object, ByVal e As EventArgs) Console.WriteLine("insert click") End Sub Private Sub EditButton_OnClick(ByVal sender As Object, ByVal e As EventArgs) Console.WriteLine("edit click") End Sub Private Sub OnDataBinding(ByVal sender As Object, ByVal e As EventArgs) Dim boundValue As Object = Nothing Dim ctrl As Control = sender Dim dataItemContainer As IDataItemContainer = ctrl.NamingContainer boundValue = DataBinder.Eval(dataItemContainer.DataItem, Me._fieldName) Select Case Me._itemType Case ListItemType.Item Dim fieldLiteral As Label = sender fieldLiteral.Text = boundValue.ToString() Case ListItemType.EditItem Dim fieldTextbox As TextBox = sender fieldTextbox.Text = boundValue.ToString() End Select End Sub End Class

    Read the article

  • Dynamically find the parameter to be passed as <T> to a generic method

    - by Codex
    A generic method is defined as follows: private static T GetComparisonObject<T>(ComparisonAttribute attribute, object objectToParse) { // Perform a some action return (T)resultObject; } The method is invoked as follows: var srcObjectToCompare = GetComparisonObject<DynamicType>(attributeToCompare, srcObject); The type for which the method needs to be invoked is configured in the config file as: <add attributename ="Count" attributetype ="MemberInformation" attributeparam ="Count" type="System.Int32" comparertype="ditCreditEMGTestAutomationDifferenceEngine.Comparers.TypeComparer, ditCreditEMGTestAutomationDifferenceEngine.dll" /> The token that is passed in < for the generic methods has to be the type for which the method is being invoked. From the type key configuration in the XML, an instance of Type represnting the type can be created{i.e. Type.GetType("System.Int32")}, but how can the Type Definition be generated which can then be passed to the the Generic method? Hope am not missing something elementary here!! :-O Thanks in advance.

    Read the article

  • Using Dynamic Proxies to centralize JPA code

    - by Daziplqa
    Hi All, Actually, This is not a question but really I need your opinions in a matter... I put his post here because I know you always active, so please don't consider this a bad question and share me your opinions. I've used Java dynamic proxies to Centralize The code of JPA that I used in a standalone mode, and Here's the dynamic proxy code: package com.forat.service; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import com.forat.service.exceptions.DAOException; /** * Example of usage : * <pre> * OnlineFromService onfromService = * (OnlineFromService) DAOProxy.newInstance(new OnlineFormServiceImpl()); * try { * Student s = new Student(); * s.setName("Mohammed"); * s.setNationalNumber("123456"); * onfromService.addStudent(s); * }catch (Exception ex) { * System.out.println(ex.getMessage()); * } *</pre> * @author mohammed hewedy * */ public class DAOProxy implements InvocationHandler{ private Object object; private Logger logger = Logger.getLogger(this.getClass().getSimpleName()); private DAOProxy(Object object) { this.object = object; } public static Object newInstance(Object object) { return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new DAOProxy(object)); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { EntityManagerFactory emf = null; EntityManager em = null; EntityTransaction et = null; Object result = null; try { emf = Persistence.createEntityManagerFactory(Constants.UNIT_NAME); em = emf.createEntityManager();; Method entityManagerSetter = object.getClass(). getDeclaredMethod(Constants.ENTITY_MANAGER_SETTER_METHOD, EntityManager.class); entityManagerSetter.invoke(object, em); et = em.getTransaction(); et.begin(); result = method.invoke(object, args); et.commit(); return result; }catch (Exception ex) { et.rollback(); Throwable cause = ex.getCause(); logger.log(Level.SEVERE, cause.getMessage()); if (cause instanceof DAOException) throw new DAOException(cause.getMessage(), cause); else throw new RuntimeException(cause.getMessage(), cause); }finally { em.close(); emf.close(); } } } And here's the link that contains more info (http://m-hewedy.blogspot.com/2010/04/using-dynamic-proxies-to-centralize-jpa.html) (plz don't consider this as adds, as I can copy and past the entire topic here if you want that) So, Please give me your opinions. Thanks.

    Read the article

  • Go - Concurrent method

    - by nevalu
    How to get a concurrent method? In my case, the library would be called from a program to get a value to each argument str --in method Get()--. When it's used Get() then it assigns a variable from type bytes.Buffer which it will have the value to return. The returned values --when it been concurrently called-- will be stored into a database or a file and it doesn't matter that its output been of FIFO way (from method). type test struct { foo uint8 bar uint8 } func NewTest(arg1 string) (*test, os.Error) {...} func (self *test) Get(str string) ([]byte, os.Error) { var format bytes.Buffer ... } I think that all code inner of method Get() should be put inner of go func() {...}(), and then to use a channel. Would there be a problem if it's called another method from Get()? Or would it also has to be concurrent?

    Read the article

  • A simple Dynamic Proxy

    - by Abhijeet Patel
    Frameworks such as EF4 and MOQ do what most developers consider "dark magic". For instance in EF4, when you use a POCO for an entity you can opt-in to get behaviors such as "lazy-loading" and "change tracking" at runtime merely by ensuring that your type has the following characteristics: The class must be public and not sealed. The class must have a public or protected parameter-less constructor. The class must have public or protected properties Adhere to this and your type is magically endowed with these behaviors without any additional programming on your part. Behind the scenes the framework subclasses your type at runtime and creates a "dynamic proxy" which has these additional behaviors and when you navigate properties of your POCO, the framework replaces the POCO type with derived type instances. The MOQ framework does simlar magic. Let's say you have a simple interface:   public interface IFoo      {          int GetNum();      }   We can verify that the GetNum() was invoked on a mock like so:   var mock = new Mock<IFoo>(MockBehavior.Default);   mock.Setup(f => f.GetNum());   var num = mock.Object.GetNum();   mock.Verify(f => f.GetNum());   Beind the scenes the MOQ framework is generating a dynamic proxy by implementing IFoo at runtime. the call to moq.Object returns the dynamic proxy on which we then call "GetNum" and then verify that this method was invoked. No dark magic at all, just clever programming is what's going on here, just not visible and hence appears magical! Let's create a simple dynamic proxy generator which accepts an interface type and dynamically creates a proxy implementing the interface type specified at runtime.     public static class DynamicProxyGenerator   {       public static T GetInstanceFor<T>()       {           Type typeOfT = typeof(T);           var methodInfos = typeOfT.GetMethods();           AssemblyName assName = new AssemblyName("testAssembly");           var assBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assName, AssemblyBuilderAccess.RunAndSave);           var moduleBuilder = assBuilder.DefineDynamicModule("testModule", "test.dll");           var typeBuilder = moduleBuilder.DefineType(typeOfT.Name + "Proxy", TypeAttributes.Public);              typeBuilder.AddInterfaceImplementation(typeOfT);           var ctorBuilder = typeBuilder.DefineConstructor(                     MethodAttributes.Public,                     CallingConventions.Standard,                     new Type[] { });           var ilGenerator = ctorBuilder.GetILGenerator();           ilGenerator.EmitWriteLine("Creating Proxy instance");           ilGenerator.Emit(OpCodes.Ret);           foreach (var methodInfo in methodInfos)           {               var methodBuilder = typeBuilder.DefineMethod(                   methodInfo.Name,                   MethodAttributes.Public | MethodAttributes.Virtual,                   methodInfo.ReturnType,                   methodInfo.GetParameters().Select(p => p.GetType()).ToArray()                   );               var methodILGen = methodBuilder.GetILGenerator();               methodILGen.EmitWriteLine("I'm a proxy");               if (methodInfo.ReturnType == typeof(void))               {                   methodILGen.Emit(OpCodes.Ret);               }               else               {                   if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum)                   {                       MethodInfo getMethod = typeof(Activator).GetMethod(/span>"CreateInstance",new Type[]{typeof((Type)});                                               LocalBuilder lb = methodILGen.DeclareLocal(methodInfo.ReturnType);                       methodILGen.Emit(OpCodes.Ldtoken, lb.LocalType);                       methodILGen.Emit(OpCodes.Call, typeofype).GetMethod("GetTypeFromHandle"));  ));                       methodILGen.Emit(OpCodes.Callvirt, getMethod);                       methodILGen.Emit(OpCodes.Unbox_Any, lb.LocalType);                                                              }                 else                   {                       methodILGen.Emit(OpCodes.Ldnull);                   }                   methodILGen.Emit(OpCodes.Ret);               }               typeBuilder.DefineMethodOverride(methodBuilder, methodInfo);           }                     Type constructedType = typeBuilder.CreateType();           var instance = Activator.CreateInstance(constructedType);           return (T)instance;       }   }   Dynamic proxies are created by calling into the following main types: AssemblyBuilder, TypeBuilder, Modulebuilder and ILGenerator. These types enable dynamically creating an assembly and emitting .NET modules and types in that assembly, all using IL instructions. Let's break down the code above a bit and examine it piece by piece                Type typeOfT = typeof(T);              var methodInfos = typeOfT.GetMethods();              AssemblyName assName = new AssemblyName("testAssembly");              var assBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assName, AssemblyBuilderAccess.RunAndSave);              var moduleBuilder = assBuilder.DefineDynamicModule("testModule", "test.dll");              var typeBuilder = moduleBuilder.DefineType(typeOfT.Name + "Proxy", TypeAttributes.Public);   We are instructing the runtime to create an assembly caled "test.dll"and in this assembly we then emit a new module called "testModule". We then emit a new type definition of name "typeName"Proxy into this new module. This is the definition for the "dynamic proxy" for type T                 typeBuilder.AddInterfaceImplementation(typeOfT);               var ctorBuilder = typeBuilder.DefineConstructor(                         MethodAttributes.Public,                         CallingConventions.Standard,                         new Type[] { });               var ilGenerator = ctorBuilder.GetILGenerator();               ilGenerator.EmitWriteLine("Creating Proxy instance");               ilGenerator.Emit(OpCodes.Ret);   The newly created type implements type T and defines a default parameterless constructor in which we emit a call to Console.WriteLine. This call is not necessary but we do this so that we can see first hand that when the proxy is constructed, when our default constructor is invoked.   var methodBuilder = typeBuilder.DefineMethod(                      methodInfo.Name,                      MethodAttributes.Public | MethodAttributes.Virtual,                      methodInfo.ReturnType,                      methodInfo.GetParameters().Select(p => p.GetType()).ToArray()                      );   We then iterate over each method declared on type T and add a method definition of the same name into our "dynamic proxy" definition     if (methodInfo.ReturnType == typeof(void))   {       methodILGen.Emit(OpCodes.Ret);   }   If the return type specified in the method declaration of T is void we simply return.     if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum)   {                               MethodInfo getMethod = typeof(Activator).GetMethod("CreateInstance",                                                         new Type[]{typeof(Type)});                               LocalBuilder lb = methodILGen.DeclareLocal(methodInfo.ReturnType);                                                     methodILGen.Emit(OpCodes.Ldtoken, lb.LocalType);       methodILGen.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"));       methodILGen.Emit(OpCodes.Callvirt, getMethod);       methodILGen.Emit(OpCodes.Unbox_Any, lb.LocalType);   }   If the return type in the method declaration of T is either a value type or an enum, then we need to create an instance of the value type and return that instance the caller. In order to accomplish that we need to do the following: 1) Get a handle to the Activator.CreateInstance method 2) Declare a local variable which represents the Type of the return type(i.e the type object of the return type) specified on the method declaration of T(obtained from the MethodInfo) and push this Type object onto the evaluation stack. In reality a RuntimeTypeHandle is what is pushed onto the stack. 3) Invoke the "GetTypeFromHandle" method(a static method in the Type class) passing in the RuntimeTypeHandle pushed onto the stack previously as an argument, the result of this invocation is a Type object (representing the method's return type) which is pushed onto the top of the evaluation stack. 4) Invoke Activator.CreateInstance passing in the Type object from step 3, the result of this invocation is an instance of the value type boxed as a reference type and pushed onto the top of the evaluation stack. 5) Unbox the result and place it into the local variable of the return type defined in step 2   methodILGen.Emit(OpCodes.Ldnull);   If the return type is a reference type then we just load a null onto the evaluation stack   methodILGen.Emit(OpCodes.Ret);   Emit a a return statement to return whatever is on top of the evaluation stack(null or an instance of a value type) back to the caller     Type constructedType = typeBuilder.CreateType();   var instance = Activator.CreateInstance(constructedType);   return (T)instance;   Now that we have a definition of the "dynamic proxy" implementing all the methods declared on T, we can now create an instance of the proxy type and return that out typed as T. The caller can now invoke the generator and request a dynamic proxy for any type T. In our example when the client invokes GetNum() we get back "0". Lets add a new method on the interface called DayOfWeek GetDay()   public interface IFoo      {          int GetNum();          DayOfWeek GetDay();      }   When GetDay() is invoked, the "dynamic proxy" returns "Sunday" since that is the default value for the DayOfWeek enum This is a very trivial example of dynammic proxies, frameworks like MOQ have a way more sophisticated implementation of this paradigm where in you can instruct the framework to create proxies which return specified values for a method implementation.

    Read the article

  • Error using Dynamic Data Filtering: missing datasource

    - by sebastiaan
    I am trying to use the ASP.NET Dynamic Data Filtering project, but I'm running into a problem during the configuration. I'm following the instructions on the author's blog, and everything works like described. Then it tells me to change the datasource using the designer view. I am told to select the "GridDataSource" in the "Configure data source" wizard. This option is not there though. I get all of the classes in my project, including the DataContext that was generated by Linq. When I choose "Show only DataContext objects", the dropdown ("Choose your context object:") is completely empty. When I turn of the checkbox and choose my DataContext class, I get asked which table I want and all that. But, as the whole purpose of a Dynamic Data site is NOT to use one single table, that's not much help. So I've looked at the instructions again and copied the resulting datasource from the example: <asp:DynamicLinqDataSource ID="GridDataSource" runat="server" EnableDelete="True" EnableUpdate="True"></asp:DynamicLinqDataSource> Which is exactly what I had, without the "WhereParameters" nodes in there. Now, when I run the list page however, I get an exception about a missing datasource from the filtering component. Of course when I remove the DynamicFilterRepeater, it works again. This is the meat of the exception: [InvalidOperationException: Missing DataSource] Catalyst.Web.DynamicData.DynamicFilterRepeater.GetTable() in D:\Catalyst\Projects\DynamicData\Project\Trunk\DynamicData\DynamicData\DynamicFilterRepeater.cs:74 Catalyst.Web.DynamicData.DynamicFilterRepeater.GetFilters() in D:\Catalyst\Projects\DynamicData\Project\Trunk\DynamicData\DynamicData\DynamicFilterRepeater.cs:81 Catalyst.Web.DynamicData.DynamicFilterRepeater.OnInit(EventArgs e) in D:\Catalyst\Projects\DynamicData\Project\Trunk\DynamicData\DynamicData\DynamicFilterRepeater.cs:106 How do I make the DynamicFilterRepeater recognize my datasource? I'm using VS2010 Pro, on a Win7 machine.

    Read the article

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