Search Results

Search found 11449 results on 458 pages for 'dynamic languages'.

Page 17/458 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | 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

  • Is Python Interpreted or Compiled?

    - by crodjer
    This is just a wondering I had while reading about interpreted and compiled languages. Ruby is no doubt an interpreted language, since source code is compiled by an interpreter at the point of execution. On the contrary C is a compiled language, as one have to compile the source code first according to the machine and then execute. This results is much faster execution. Now coming to Python: A python code (somefile.py) when imported creates a file (somefile.pyc) in the same directory. Let us say the import is done in a python shell or django module. After the import I change the code a bit and execute the imported functions again to find that it is still running the old code. This suggests that *.pyc files are compiled python files similar to executable created after compilation of a C file, though I can't execute *.pyc file directly. When the python file (somefile.py) is executed directly ( ./somefile.py or python somefile.py ) no .pyc file is created and the code is executed as is indicating interpreted behavior. These suggest that a python code is compiled every time it is imported in a new process to crate a .pyc while it is interpreted when directly executed. So which type of language should I consider it as? Interpreted or Compiled? And how does its efficiency compare to interpreted and compiled languages? According to wiki's Interpreted Languages page it is listed as a language compiled to Virtual Machine Code, what is meant by that? Update Looking at the answers it seems that there cannot be a perfect answer to my questions. Languages are not only interpreted or only compiled, but there is a spectrum of possibilities between interpreting and compiling. From the answers by aufather, mipadi, Lenny222, ykombinator, comments and wiki I found out that in python's major implementations it is compiled to bytecode, which is a highly compressed and optimized representation and is machine code for a virtual machine, which is implemented not in hardware, but in the bytecode interpreter. Also the the languages are not interpreted or compiled, but rather language implementations either interpret or compile code. I also found out about Just in time compilation As far as execution speed is concerned the various benchmarks cannot be perfect and depend on context and the task which is being performed. Please tell if I am wrong in my interpretations.

    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

  • New functional languages

    - by AnnaR
    Functional programming has been around since at least 1958 (creation of Lisp), but is experiencing a renaissance now with old functional languages being dusted off and new functional languages being created. Which functional languages are there that are newly developed or are in the making? I realize that you can write purely functional programs in most high level languages, so with functional languages I imply languages that are specifically designed for functional programming such as F#. If you have links to tutorials, wikis or code examples I encourage you to add them to your answer!

    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

  • 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

  • dynamic naming of UIButtons within a loop - objective-c, iphone sdk

    - by von steiner
    Dear Members, Scholars. As it may seem obvious I am not armed with Objective C knowledge. Levering on other more simple computer languages I am trying to set a dynamic name for a list of buttons generated by a simple loop (as the following code suggest). Simply putting it, I would like to have several UIButtons generated dynamically (within a loop) naming them dynamically, as well as other related functions. button1,button2,button3 etc.. After googling and searching Stackoverlow, I haven't arrived to a clear simple answer, thus my question. - (void)viewDidLoad { // This is not Dynamic, Obviously UIButton *button0 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button0 setTitle:@"Button0" forState:UIControlStateNormal]; button0.tag = 0; button0.frame = CGRectMake(0.0, 0.0, 100.0, 100.0); button0.center = CGPointMake(160.0,50.0); [self.view addSubview:button0]; // I can duplication the lines manually in terms of copy them over and over, changing the name and other related functions, but it seems wrong. (I actually know its bad Karma) // The question at hand: // I would like to generate that within a loop // (The following code is wrong) float startPointY = 150.0; // for (int buttonsLoop = 1;buttonsLoop < 11;buttonsLoop++){ NSString *tempButtonName = [NSString stringWithFormat:@"button%i",buttonsLoop]; UIButton tempButtonName = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [tempButtonName setTitle:tempButtonName forState:UIControlStateNormal]; tempButtonName.tag = tempButtonName; tempButtonName.frame = CGRectMake(0.0, 0.0, 100.0, 100.0); tempButtonName.center = CGPointMake(160.0,50.0+startPointY); [self.view addSubview:tempButtonName]; startPointY += 100; } }

    Read the article

  • iis7 compress dynamic content from custom handler

    - by Malloc
    I am having trouble getting dynamic content coming from a custom handler to be compressed by IIS 7. Our handler spits out json data (Content-Type: application/json; charset=utf-8) and responds to url that looks like: domain.com/example.mal/OperationName?Param1=Val1&Param2=Val2 In IIS 6, all we had to do was put the edit the MetaBase.xml and in the IIsCompressionScheme element make sure that the HcScriptFileExtensions attribute had the custom extension 'mal' included in it. Static and Dynamic compression is turned out at the server and website level. I can confirm that normal .aspx pages are compressed correctly. The only content I cannot have compressed is the content coming from the custom handler. I have tried the following configs with no success: <handlers> <add name="MyJsonService" verb="GET,POST" path="*.mal" type="Library.Web.HttpHandlers.MyJsonServiceHandlerFactory, Library.Web" /> </handlers> <httpCompression> <dynamicTypes> <add mimeType="application/json" enabled="true" /> </dynamicTypes> </httpCompression> _ <httpCompression> <dynamicTypes> <add mimeType="application/*" enabled="true" /> </dynamicTypes> </httpCompression> _ <staticContent> <mimeMap fileExtension=".mal" mimeType="application/json" /> </staticContent> <httpCompression> <dynamicTypes> <add mimeType="application/*" enabled="true" /> </dynamicTypes> </httpCompression> Thanks in advance for the help.

    Read the article

  • C#, Linq, Dynamic Query: Code to filter a Dynamic query outside of the Repository

    - by Dr. Zim
    If you do something like this in your Repository: IQueryable<CarClass> GetCars(string condition, params object[] values) { return db.Cars.Where(condition, values); } And you set the condition and values outside of the repository: string condition = "CarMake == @Make"; object[] values = new string[] { Make = "Ford" }; var result = myRepo.GetCars( condition, values); How would you be able to sort the result outside of the repository with Dynamic Query? return View( "myView", result.OrderBy("Price")); Somehow I am losing the DynamicQuery nature when the data exits from the repository. And yes, I haven't worked out how to return the CarClass type where you would normally do a Select new Carclass { fieldName = m.fieldName, ... }

    Read the article

  • Dynamic Linq Property Converting to Sql

    - by Matthew Hood
    I am trying to understand dynamic linq and expression trees. Very basically trying to do an equals supplying the column and value as strings. Here is what I have so far private IQueryable<tblTest> filterTest(string column, string value) { TestDataContext db = new TestDataContext(); // The IQueryable data to query. IQueryable<tblTest> queryableData = db.tblTests.AsQueryable(); // Compose the expression tree that represents the parameter to the predicate. ParameterExpression pe = Expression.Parameter(typeof(tblTest), "item"); Expression left = Expression.Property(pe, column); Expression right = Expression.Constant(value); Expression e1 = Expression.Equal(left, right); MethodCallExpression whereCallExpression = Expression.Call( typeof(Queryable), "Where", new Type[] { queryableData.ElementType }, queryableData.Expression, Expression.Lambda<Func<tblTest, bool>>(e1, new ParameterExpression[] { pe })); // Create an executable query from the expression tree. IQueryable<tblTest> results = queryableData.Provider.CreateQuery<tblTest>(whereCallExpression); return results; } That works fine for columns in the DB. But fails for properties in my code eg public partial class tblTest { public string name_test { get { return name; } } } Giving an error cannot be that it cannot be converted into SQL. I have tried rewriting the property as a Expression<Func but with no luck, how can I convert simple properties so they can be used with linq in this dynamic way? Many Thanks

    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

  • Java and dynamic variables

    - by Arvanem
    Hi folks, I am wondering whether it is possible to make dynamic variables in Java. In other words, variables that change depending on my instructions. FYI, I am making a trading program. A given merchant will have an array of items for sale for various prices. The dynamism I am calling for comes in because each category of items for sale has its own properties. For example, a book item has two properties: int pages, and boolean hardCover. In contrast, a bookmark item has one property, String pattern. Here are skeleton snippets of code so you can see what I am trying to do: public class Merchants extends /* certain parent class */ { // only 10 items for sale to begin with Stock[] itemsForSale = new Stock[10]; // Array holding Merchants public static Merchants[] merchantsArray = new Merchants[maxArrayLength]; // method to fill array of stock goes here } and public class Stock { int stockPrice; int stockQuantity; String stockType; // e.g. book and bookmark // Dynamic variables here, but they should only be invoked depending on stockType int pages; boolean hardCover; String pattern; }

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >