Using Emit to Return a Value

Hello:

I am trying to write a piece of code that can implement an interface's
methods simply by returning a specified value. I am trying to see how
Mock libraries are written.

For instance, I have a piece of code that looks like this:

MockFactory.CreateMock<ISomething>().Setup(something =>
something.Foo()).Returns("abc");

What I want to be able to do is somehow implement ISomething.Foo so
that it returns "abc". However, I am having a hard time figuring out
the Emit code for taking an arbitrary object and incorporating it.

I've never wanted to do something like this before, so I need some
pointers. Also, I am wondering if there is a fast way in MSIL to
request the default value of a type (null or 0) in case no return
value is specified.

Any help would be appreciated.

Thanks,
Travis Parks
0
Jehu
4/26/2010 1:53:32 AM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

7 Replies
1100 Views

Similar Articles

[PageSpeed] 42

Does anyone know a way to quarantee a unique type name?
0
Jehu
4/26/2010 3:06:27 AM
Jehu Galeahsa wrote:
> Does anyone know a way to quarantee a unique type name?

Unique relative to what?  Assuming you put the type in your own specific 
namespace where all the types are ones you've defined, you can guarantee 
uniqueness however you like.

In other contexts, you may have to do some inspection of all the types 
in a given namespace that have been loaded, to determine what would be 
"unique".

In either case, a reasonably reliable way to create a type name that is 
very likely to be unique (i.e. even though you should still check for an 
already-existing type of the same name, it would be virtually impossible 
for there to be a collision) would be to use the System.Guid type and 
create a GUID to use in (or as) the type name.

Pete
0
Peter
4/26/2010 11:06:46 PM
On 25-04-2010 23:06, Jehu Galeahsa wrote:
> Does anyone know a way to quarantee a unique type name?

If you mean a unique name for classes that you generate yourself
at runtime, then one obvious approach is to use C1, C2, C3 ... !

Arne

0
ISO
4/27/2010 1:03:14 AM
On 26-04-2010 19:06, Peter Duniho wrote:
> Jehu Galeahsa wrote:
>> Does anyone know a way to quarantee a unique type name?
>
> Unique relative to what? Assuming you put the type in your own specific
> namespace where all the types are ones you've defined, you can guarantee
> uniqueness however you like.
>
> In other contexts, you may have to do some inspection of all the types
> in a given namespace that have been loaded, to determine what would be
> "unique".
>
> In either case, a reasonably reliable way to create a type name that is
> very likely to be unique (i.e. even though you should still check for an
> already-existing type of the same name, it would be virtually impossible
> for there to be a collision) would be to use the System.Guid type and
> create a GUID to use in (or as) the type name.

Note that only N formatting gives a valid type name.

Arne
0
ISO
4/27/2010 1:05:12 AM
On 26-04-2010 21:05, Arne Vajh�j wrote:
> On 26-04-2010 19:06, Peter Duniho wrote:
>> Jehu Galeahsa wrote:
>>> Does anyone know a way to quarantee a unique type name?
>>
>> Unique relative to what? Assuming you put the type in your own specific
>> namespace where all the types are ones you've defined, you can guarantee
>> uniqueness however you like.
>>
>> In other contexts, you may have to do some inspection of all the types
>> in a given namespace that have been loaded, to determine what would be
>> "unique".
>>
>> In either case, a reasonably reliable way to create a type name that is
>> very likely to be unique (i.e. even though you should still check for an
>> already-existing type of the same name, it would be virtually impossible
>> for there to be a collision) would be to use the System.Guid type and
>> create a GUID to use in (or as) the type name.
>
> Note that only N formatting gives a valid type name.

When prefixed with a letter.

Arne
0
ISO
4/27/2010 1:06:21 AM
On Apr 26, 7:06=A0pm, Arne Vajh=F8j <a...@vajhoej.dk> wrote:
> On 26-04-2010 21:05, Arne Vajh=F8j wrote:
>
>
>
>
>
> > On 26-04-2010 19:06, Peter Duniho wrote:
> >> Jehu Galeahsa wrote:
> >>> Does anyone know a way to quarantee a unique type name?
>
> >> Unique relative to what? Assuming you put the type in your own specifi=
c
> >> namespace where all the types are ones you've defined, you can guarant=
ee
> >> uniqueness however you like.
>
> >> In other contexts, you may have to do some inspection of all the types
> >> in a given namespace that have been loaded, to determine what would be
> >> "unique".
>
> >> In either case, a reasonably reliable way to create a type name that i=
s
> >> very likely to be unique (i.e. even though you should still check for =
an
> >> already-existing type of the same name, it would be virtually impossib=
le
> >> for there to be a collision) would be to use the System.Guid type and
> >> create a GUID to use in (or as) the type name.
>
> > Note that only N formatting gives a valid type name.
>
> When prefixed with a letter.
>
> Arne- Hide quoted text -
>
> - Show quoted text -

Or, in my case, an underscore. :-)
0
Jehu
4/27/2010 1:44:08 AM
On Apr 25, 7:53=A0pm, Jehu Galeahsa <jehugalea...@gmail.com> wrote:
> Hello:
>
> I am trying to write a piece of code that can implement an interface's
> methods simply by returning a specified value. I am trying to see how
> Mock libraries are written.
>
> For instance, I have a piece of code that looks like this:
>
> MockFactory.CreateMock<ISomething>().Setup(something =3D>
> something.Foo()).Returns("abc");
>
> What I want to be able to do is somehow implement ISomething.Foo so
> that it returns "abc". However, I am having a hard time figuring out
> the Emit code for taking an arbitrary object and incorporating it.
>
> I've never wanted to do something like this before, so I need some
> pointers. Also, I am wondering if there is a fast way in MSIL to
> request the default value of a type (null or 0) in case no return
> value is specified.
>
> Any help would be appreciated.
>
> Thanks,
> Travis Parks

After spending about two days searching for a way to stack an
arbitrary value using Emit, I decided that I would instead generate a
backing field for each return value. When I instantiate an instance of
my mock object, I simply loop through a list of methods and properties
and creating backing fields. After I create my type and instantiate an
instance, I loop through the return values and assign them to the
backing fields. It is kind of nasty, but it works. I suppose the next
challenge is finding performance boosts, throwing exceptions and
allowing hit counts to be evaluated. More importantly, there has to be
a way of making all of this emit code look a little less intimidating.
0
Jehu
4/27/2010 1:49:03 AM
Reply:

Similar Artilces:

Alternative to dynamic SQL in Table Valued Function?
Hi, I have the following SQL Server table valued function that I've written to use as a parameterised view. It takes a bunch of parameters and returns a table of results. Each of the parameters can contain a value or can be NULL. If the parameter is NULL then no rows will be filtered by that value. The function is called from an Excel spreadsheet (using VBA) against a SQL Server 2005 database. CREATE FUNCTION [dbo].[fnLoanData] ( @loan_start_date VARCHAR(8) = NULL , @loan_end_date VARCHAR(8) = NULL , @loan_currency VARCHAR(3) = NULL , @customer_number VARCHAR(8) = NULL ...

Help with counting user entered text values
Hi, Version: Excel 2000 Situation: In Column G, I will have testers entering in their initals. I would like to display the tester's initals in column H of another worksheet with the number of times that set of intals appeared in column G on column I of the other worksheet. The catch is that I do not have a list of the testers initals ahead of time, so I'll need to pull them from column H. Thanks for any and all help in advance, David Hi David, H10: DAL i10: =COUNTIF(G:G,H10) or if you don't want to see 0 if H10 is empty I10: =IF(H10="","",COU...

Using Publ;ic SSL Cert on CAS servers
Hello all, We've got 2x exchange 2007 front end servers configured to use CAS and HT roles setup in an NLB cluster. To secure PDA's and OWA we've purchased from Entrust 2x Public Certificates to install on both servers. We've installed one of the certs on one node to test but when connecting to the node to use OWA we have the same error regarding having a certificate error. Is there anything else required to make this work? Our SAN names on the certs have only FQDN names of the servers and NLB cluster, do we need a single label name on the cert for this to ...

Using Adobe 5 or higher with GP on terminal server
Has anyone run into a problem with print jobs not clearing the queue when using Adboe 5 with GP in a terminal server environment? Or has anyone successfully used a more current version of Adobe Writer with GP? We've tried Adobe 6 but could not get that to work consistently. Adobe 5 is working OK if you select that printer in that the pdf is created, however the jobs never clear the queue. Consequently if someone else tries to e-mail a pdf attachment from GP, Outlook times out because the related print job is stuck in the print queue. I've talked to Adobe support but as so...

Calculate Time Using Minutes and Seconds Only
I am trying to calculate a race time using just Mins and Secs to give the overall race time . How can I format my fields to show only mins and secs without Access trying to convert to Hour Mins and secs when the mins are 60 or more. Val@AGIS On Wed, 19 Mar 2008 07:21:06 -0700, Val@AGIS <ValAGIS@discussions.microsoft.com> wrote: >I am trying to calculate a race time using just Mins and Secs to give the >overall race time . How can I format my fields to show only mins and secs >without Access trying to convert to Hour Mins and secs when the mins are 60 >or more. >...

Specify which e-mail account to use to send a message #2
I've just installed Outlook 2003 on to my machine, I have multiple accounts set-up. but I can't seem to specify which e-mail account to use to send a message, as it always arrives from my default account even though I have selected an alternative account. Any ideas? It work on outlook express & incredimail Is all of the mail sent to one mailbox and downloaded with one username and password? if so, you'll need to create additional accounts in Outlook and use the accounts menu to change the account when you compose a reply. to send new messages on a secondary account, s...

The value of ESP was not properly saved across a function call
Our company has a big software. It runs very smoothly on my colleagues' machine. But If I copy the source codes to my machine, although it can be compiled successfully, there will be the following error message when the program is running: --------- File: i386\chkesp.c Line: 42 The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention --------- I can't understand the program can run on other's computer, but not mine? Is...

Using linked tables in forms
Hello, I have 3 tables. Stock Accesoires and a table to link them as a record in stock can have multiple accesoires. Now I want a form where I can see a record from the table Stock, with all the Accesoires that belong to that record. How can I do this? Is this possible? It doesn't matter in what kind of object the data is displayed, I just need it displayed. The relationship looks like this, for if it wasn't clear: Stock.ID -- linkTable.StockID linkTable.AccesoiresID -- Accesoires.ID I hope someone can help. I thought it would be Record -> accessories and put the stock ...

How to change drop down values based on another cell value?
My query is as follows: I want to change the drop down values in cell B1, based on the value entered in cell A1. The drop down values in B1 should dynamically change as A1 is changed. The range of drop down values allowed for a value of A1 will be stored in another sheet (for e.g.) Please help. Thanks ! Puneet Arora -- puneetarora_12 ------------------------------------------------------------------------ puneetarora_12's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=18406 View this thread: http://www.excelforum.com/showthread.php?threadid=473257 You ca...

How do I assign X = the value of 1 in a cell in Excell 2003?
How do I assign X = the value of 1 in a cell in Excell 2003? That need some explaining. Excel genially goes use variables but rather uses cell references. Cells can be given names (such as x) but it is not required. Tell use more about what you wish to accomplish best wishes -- Bernard Liengme www.stfx.ca/people/bliengme remove CAPS in e-mail address "Givens" <Givens@discussions.microsoft.com> wrote in message news:4ACE70A4-D4EC-4B79-8552-B7BA11BE9B38@microsoft.com... > How do I assign X = the value of 1 in a cell in Excell 2003? Put a 1 into any cell - let'...

PO Return processing
In our shop we often recieve goods that must be quality checked. When items are rejected by quality control we then process a return. The rejected parts need to be re-ordered so a new PO needs to be created. Is there any way for GP to automatically create a replacement PO? Not automatically. You can copy a PO to a new one. "TotalDoor" <TotalDoor@discussions.microsoft.com> wrote in message news:E532F805-9677-409A-BACA-BB0536C61058@microsoft.com... > In our shop we often recieve goods that must be quality checked. When > items > are rejected by quality control w...

Use of Monotype Sorts Font and Value 4
When I enter in a cell the value 4 and change font to Monotype Sorts instead of getting a single CHECK-MARK I get the Check mark plus 3 other characters that look like a pencil stub. I only want to Check Mark. Any suggestions? TIA I can't replicate your problem. I get only a check mark. Are you sure there is nothing else in the cell. In another cell, use a formula like =LEN(A1) to ensure that there is only one character in the cell. -- Cordially, Chip Pearson Microsoft MVP - Excel Pearson Software Consulting, LLC www.cpearson.com "JMay" <jmay@cox.net> wrote in ...

Is it possible to use a 'Clear Cell Contents' Macro without it cl.
Hi! I'm currently working on a sheet which contains a lot of different formulas in specific cells. What I want to do is to create a 'Clear Cells' Macro to clear the specific cells without it clearing the formulas in the cells. Is this possible ?????? I don't understand, what would you be clearing? Do you mean that yo would not want to see the formula or its result? If so, you could jus set the font color to white so it doesn't show up. Range("A1").Font.ColorIndex = 2 -- kkkni ----------------------------------------------------------------------- kkknie...

why im nt able to use outlook express
What happens when you try? Also, you might want to put content in your message as opposed to putting your whole request in the subject... "sneha" <sneha@discussions.microsoft.com> wrote in message news:9EC40E1F-20C4-4B47-A229-50760A88A746@microsoft.com... > In addition to what Vince has mentioned, you should try posting in a newsgroup that supports Outlook Express, like this one: http://www.microsoft.com/windows/ie/dgbrowser/en-us/default.mspx?dg=microsoft.public.windows.inetexplorer.ie6_outlookexpress&lang=en&cr=US This assumes you are using OE 6.0. Ou...

Table default value question
Can a table default value be the value from a loaded form? Here is my dilemma, whenever I create a new record via a form, I have codes to detect the user’s LAN ID and store this information in a field called CreatedBy. However, now I can collect data via e-mail and automatically upload the information into Access and you already know what there will not be a CreatedBy data. Therefore, I think if I could place the CreatedBy default value directly from the table to look up the user name already loaded in the database “Welcome Screen” that will save user LAN ID regardless how the da...

Extract Unique Values, Then Extract Again to Remove Suffixes
I have a list of builders where I want to extract all the unique values. Using =IF(COUNTIF($A$1:A1,A1)=1,A!,"") works fine to get the first set of unique values, but I need to extract it a bit further. The builder names may be Ryan 50, Ryan 60 or just Ryan. I need to combine those values to come up with the final list of unique builders that just says Ryan. I'm not sure if I can strip off anything from the end as some are Ryan - Greenbrier. I thought maybe removing everything to the right of a blank space, but those entries have 2 blanks. Any help would be greatly appr...

negative values causing column title problem
How do I get the Column titles x axis lables at he bottom of the chart field when have negative values It s friday and this is killing me. Select the axis Choose Format>Selected axis On the Patterns tab, for Tick Mark Labels, select Low TFrisch wrote: > How do I get the Column titles x axis lables at he bottom > of the chart field when have negative values > > It s friday and this is killing me. -- Debra Dalgleish Excel FAQ, Tips & Book List http://www.contextures.com/tiptech.html hey thanks - boy was thaqt annoying >-----Original Message----- >Select th...

Unable to set the Values property of the Series class #2
I'm working on a macro to get a chart from a dynamic range of cells (selected according to the date introduced for the user in the worksheet). The problem is that I store the selected range of values in variant vectors (1D arrays), as decimal types. In the below code these arrays are called PVAC, SRDM, ISRM and TimeData. With some range the code works, but with the most of them it doesn't it. Any idea? thank you '------------------------------- 'To put the Chosen Range of Data in arrays 'Selected Data into vectors RangeSize = endRow - starRow + 1 'Size of the Ra...

A program is trying to send mail using Item.Send
I have a VBA macro which does various things but also sends the worksheet. When it performs this task the message: A program is trying to automatically send e0mail on your behalf. Do you want to allow this? The user then has to click yes or no. I dont want this prompt to appear. Anyone know how to stop this? Thanks Adam ...

Link between values on two axis
Hi, How can I create a link between values on primary and secondary Y-axis? These values should not be set manually since there are many sheets and the values will cahnge. For example, if I want that the values of left Y-axis (from 0 to 200 and from 0 to 500) are always the values of right Y-axis divided by 2 (from 0 to 400 and from 0 to 1000). If you're willing to use macros, you can link the scales to each axis to worksheet cells. Jon's site provides the code and shows how this can be done. http://peltiertech.com/Excel/Charts/AxisScaleLinkToSheet.html -- John Mansfield...

ODBC Query param: Weird access violation setting param value
Hello, If I could once again ask your indulgence, here is a problem setting the input parameter for a stored procedure of an Access database called from MFC. The CRecordset-derived class for the Query is named CQueryWorkDaysSet, and the parameter variable is named m_DateParam. There is an Access Violation when the user tries to set the parameter just prior to a Requery() call. (Note that contrary to the documentation, it was not necessary to splice together this class from 2 other Tables. The ClassWizard found the Query as another Table in the database. I simply clicked it rather than one of...

Data labels: Making the value currency & use % in a chart?
Is is possible to have in a pie chart BOTH the value with a currency format and the 1,000 comma option on, with the percentage checked as well? You might have to construct your own labels in an extra worksheet range, using a formula like this: =TEXT(B2,"$#,000.00")&CHAR(10)&TEXT(B2/SUM($B$2:$B$10),"0.0%") then use a utility like those below to assign these labels to the pie wedges: Rob Bovey's Chart Labeler, http://appspro.com John Walkenbach's Chart Tools, http://j-walk.com - Jon ------- Jon Peltier, Microsoft Excel MVP Peltier Technical ...

earn value management
Right after I baseline my project, if I run a Earn Value Management report, my EV, AC and PV are different. I would have expect that all those values would be the same. Why is it not? It may be a function with your status date including the first day of the project, but not having any progress booked. Try messing with the Status Date to see if that changes anything. What numbers are you expecting? - Andrew Lavinsky Blog: http://blogs.catapultsystems.com/epm > Right after I baseline my project, if I run a Earn Value Management > report, my EV, AC and PV are differe...

How to use MGetDelHandle
I not understand this function: MGetDelHandle I am using VBTools for Solomon 6, and I need returnd the deleted items for array memory, but I don't understand MGetDelHandle. Thanks. ...

Using EUR instead of the euro sign in Money 2000?
How can one change the euro sign into "EUR" within Microsoft Money 2000 Standard Edition (8.0)? I prefer to use ISO (3-letter) format for currencies, and I was able to change all the currencies I use into this format (instead of their respective "traditional" signs) - even USD for dollars. However, euro seems to switch from EUR into the euro sign each time I start the program. How can I convince it to keep "EUR" instead of the sign? ...