.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Reflection.Emit. How to generate a simple if statement.

Posted By:      Posted Date: October 19, 2010    Points: 0   Category :.NET Framework

I am trying to generate a simple C# function that takes in an object as a parameter and outputs it through Console.WriteLine.

Something like this:

        public void DesiredMethod(object input) {
            if (input != null) {

I was able to generate similar function but without the IF statement that checks for null. Here is the code:


        private static object GenerateObj() {

            AssemblyBuilder assmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new System.Reflection.AssemblyName() { Name = "MyAssembly" },

            ModuleBuilder moduleBuilder = assmBuilder.DefineDynamicModule("MainModule", true);

            TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", T

View Complete Post

More Related Resource Links

using reflection to emit properties to the top of the entity graph


I've got a class

  public class Criminal

public HouseholdMember[] LiedAboutFSHousehold { get; set; }

      public HouseholdMember[] FoodstampTrafficingHousehold { get; set; }
HouseholdMember inherits Person, as do many other classes.  

  public class HouseholdMember: Person


What I&#

how to generate an Xml pass Simple query structure like

1. My sql query is        SELECT a.HD, a.HEAD, a.SH, a.SUBHEAD, a.TRK, a.TRACK, a.TGT, a.TARGET, a.PDC, a.DT_RELEASE, a.STATUS, a.COFROM V_HIERARCHY1 a2, My Data is HR    HR    Rec    Records    Leave    Leave Records    HRL.0001    Policy and Process for leave record.    27.06.2010    30.06.2010    WIP    EdlinkHR    HR    Rec    Records    Leave    Leave Records    HRL.0002    Quarterly Review    01.07.2010    04.07.2010    Planned    EdlinkHR    HR    DB    Database    SAL    Salary    DDS.0001    Calculation of Monthly salary    08.08.2010    09.08.2010    WIP    EdlinkHR    HR    Rec    Records    Ind    Induction Records    HRI.0001    Completion of dossiers.    08.07.2010    10.07.2010    WIP   &nbs

generate xml in proper format; select statement


I have 4 tables ex.

dbo.beach --> which has info like
'beach_ID','beach_name', 'beach_description'

dbo.monitoring --> info like

dbo.monitoring_location --> info like

dbo.advisory --> info like

i want output is follwing format
    <Beachidentifier> xxx <Beachidentifier>
           <beach_name> XXX </>
                     <opendate> XXX </>

          <closedate> xxx </>

SSIS 2005 - Dynamically generate create table statement from source



I have a requirement where i had to migrate the table structure and data from ODBC database to SQL Server. I have dynamic source reader that uses sql query from variable to get the data and the next step is to get the create statement and create table and then to insert data. how can i get Create Statement the destination produces and use sql task to create the table and then insert the data using data flow task.

Please suggest



Clean and simple way to generate XPS document using WPF


Is there a simple way to generate XPS document using WPF ? Most of the code samples I see on the MSDN and internet websites are at least 2-3 years old and have some ugly code to generate the XPS document. Have things improved with .NET 3.5 SP1 or .NET 4.0 ?

I hope the Microsoft WPF experts can help the community by providing a good code sample that shows how to accomplish this task.


Strange time issue on simple select statement


Hi, I have a strange time out issue on a simple select statement.
This is my select statement:

Select * from DyGeJournal where ord>=4609635 and Fracsec>=31

The ord and Fracsec is the primary key.
When I ask for the actual excecution plan, he is using a an index seek.
It takes more than 1,5 minutes to get a result back.

When I shrink my database, everyting is running as expected, the query above runs in milliseconds.
After a while (2 weeks) it start agian running very slow.

I have the same logic on other tables, but I don't have the problem on those tables.
What can cause this problem?

Dynamically Generate a WCF Proxy class at runtime and Callling web methods via reflection



I'm busy writing an application where the user will have to specify the location of a ?wsdl file for asmx and/or svc type services.

My application will have to :

1. Deduce from the wsdl what methods (with parameters and return types) are available on the service.

2. Provide a way to either generate a Proxy class in memory to execute methods against with e.g: Reflection

    for instanse : genericProxy.Invoke("HelloWorldMethod",parameter1,parameter2);

    I want to avoid using something like this : notSoGenericProxy.HelloWorldMethod(parameter1,parameter2); seeing that my application will have no 

    idea what service it will have to work with at runtime.

Is there a way to achieve this?

Thank you for any help in advance!

Odd Behavior in System.Reflection.Emit APIs (.NET Framework 3.5 SP1)

I've noticed an issue during generation of a dynamic assembly to a secondary app domain. The code I'm using to start the assembly looks fairly typical, but it somehow allows the dynamic assembly to be loaded twice into the targeted app domain.

string assemblyName = "MyAssembly";
string moduleName = "MyAssembly.dll";
string typeName = "MyType";
AssemblyName assemblyFullName = new AssemblyName(assemblyName);
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyFullName, AssemblyBuilderAccess.Run);
ModuleBuilder module = assemblyBuilder.DefineDynamicModule(moduleName);
Upon further inspection, I used code to print the list of assemblies actually loaded into the current app domain (that was how I first noticed the issue above). Also, I inspected the condition of the domain using the AssemblyLoad event, and it confirmed that the assembly was loaded twice. Using that approach, I was able to step into the event handler for each load of the dynamic assembly on the AssemblyBuilder and ModuleBuilder lin

how to stop ScriptTransfer from generate "Create User" "Create Schema" sql statement?



I am using the following code to generate scripts, but no matter how i configure the options, it always generate create user statement




// Connection to Server
        Server srv = new Server(ConfigurationManager.AppSettings["Server"]);

        srv.ConnectionContext.LoginSecure = false;

Is there a way to generate the parse tree of an sql statement?


Is there a way for me to generate the parse tree of an sql statement?

Maybe by using some API that connects to the parser that SQL Server
uses or by using some sort of built in function or stored procedure.


I would like to take something like:
select * from foo where id = @theID

And turn it into something like
      <tables />
      <joins />

Its a very rough example but you get the idea.

Creating a Simple Class in C#

The second article in the C# Object-Oriented Programming tutorial describes how classes are created in C# and how behaviour, in the form of publicly visible and private, hidden methods can be added. This demonstrates some of the uses of encapsulation

A Simple and Extensible Radio Button Style GridView

The GridView is one of the significant controls in ASP.NET 2.0 and later versions. No doubt it reduces a lot of work time. However, customizing the GridView control is not an easy task. For example, it's hard to add a radio button column to the GridView. This article demonstrates the reason why a radio button column cannot act as normal and how to create a simple and extensible radio button GridView.

Silverlight Simple Animation

Silverlight has several built in techniques for animating controls. Many of these technologies are particularly useful for creating simple animations meant to decorate a web page with eye catching movement that draws the reader's attention. In this post I will skip over these decorative technologies, and instead show how to create a simple animation using a technique similar to those used in many games.

Generate thumbnails on the fly

There are many posts how to generate thumbnails using ASP.NET. Some good some less. Be sure to get distance from the versions that use Image.GetThumbnailImage method.

Generate Random Numbers

SQL Server has a built-in function that generates a random number, the RAND() mathematical function. The RAND math function returns a random float value from 0 through 1.

I thought this would be simple... Trying to create a login does an ajax check before submit


I have the standard .net login control that is working.  (Still learning .net after 15yrs of classic)

What I want to do is OnButtonClick run a javascript function (to do an ajax call to the db to check if login is valid or not) and if it returns true, then submit the form normally, else don't submit. The piece that I can't figure out, is how to correctly override the default click even to hit my JS routine and then submit the form properly afterwards.

Thanks ahead of time

Passing Linq Statement between master and content page


I usually work with windows forms, and am just starting to work with ASP.Net, so appologies if this is a dumb question!

I have a master page which has a search button on it. The results of this are built up using a Linq statement and if there are any results, I want to display the results in a contents page.

On the masterpage, I have the following code:

Private _res

    Public Overridable ReadOnly Property SearchRes()
            Return _res
        End Get
    End Property

 Private Sub DoSearch()
   'some code to get a linq result

    If res.Any Then
            _res = res
            Server.Transfer("SearchResults.aspx", True)
            'no results
            LabelNoRes.Visible = True
        End If
 End Sub

On the SearchResults.aspx page I have this code.

Dim m As pxSite = CType(Page.Master, MasterPage)
        If m.SearchRes IsNot Nothing Then
            Label1.Text = "Results found = " & m.SearchRes.Count
        End If

m.searchRes is always nothing. 

What am I doing wrong here?


ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend