I did convert the VB code to below C# code, but error occurred. I am getting error in Strings.InStr and Strings.Mid.
sHeadingNm = ActiveDocument.Styles(wdStyleHeading1).NameLocal;
if (!string.IsNullOrEmpty(sHeadingNm)) {
nPos = Strings.InStr(1, sHeadingNm, "1");
if (nPos > 0)
sHeadingNm = Strings.Mid(sHeadingNm, 1, nPos - 1);
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: #telerik
//Facebook: facebook.com/telerik
//=======================================================
Please help me...
C# equivalents of method you've used:
Strings.InStr has equivalent of String.IndexOf
Strings.Mid has equivalent of String.Substring
You need to use the C# equivalent functions something like this:
nPos = sHeadingNm.IndexOf('1');
sHeadingNm = sHeadingNm.Substring( 1, nPos - 1);
Your problem must be that Strings.InStr and Strings.Mid are not standard methods in C#, but in VB.net. You should add probably using Microsoft.VisualBasic in order to use them, although i'd recommend to use C# equivalent methods.
Better stated, you let the Telerik converter convert the code. Code converters can't safely assume that library and function calls which exist in one language do not exist in the other; for all they know, your destination code has a custom library that mimics the behavior of functions only present in the source language. Additionally, most functions in VB that are VB-only are 1-based, not 0-based as in the rest of .Net.
For this reason, you don't get an automatic conversion of Strings.InStr to String.IndexOf. You also won't see Strings.Mid to String.Substring. Code looking for a "0" to return from Strings.Instr or Strings.Mid because nothing was found will break, as "0" is now the first index in a successful search. You actually need the ensuing errors to determine where you need to adjust your code to look for the proper response (i.e., -1 on a search with no results).
After installing Visual Studio 2015 and building my project I receive the error
"CSC : error CS7038: Failed to emit module".
However my solution is building fine in Visual Studio 2013.
It is an ASP.NET webforms project .NET 4.0
Anyone?
UPDATE: it looks like the problem has to do with Red Gate Smart Assembly in combination with method parameters with default values.
UPDATE: Smart Assembly 6.9 fixes the error for me.
Original Snippet:
private void radButton1_Click(object sender, EventArgs e)
{
string perp = radTextBox1.Text;
int i = 0;
DataRow arp = ale.Rows[i];
while (i <= ale.Rows.Count)
{
if (ale.Rows[i].Field<>("FullName") = perp)
{
arp = ale.Rows[i];
ale.Rows.Remove(arp);
}
}
i = ale.Rows.Count;
radLabel1.Text = i.ToString();
}
Changed this:
if (ale.Rows[i].Field<>("FullName") = perp)
To This:
if (ale.Rows[i].Field<String>("FullName") == perp)
Got the same error (fresh installation of the VS2015 Enterprise, ASP.NET webforms project .NET 4.0).
After some investigation I've found that there are two DLLs in references which causes this. Both are .Net 2.0 assemblies and both of them obfuscated by Red Gate Smart Assembly 6.5. And the real reason is... obfuscation.
Luckily, these assemblies are mine, so I've tried to build them without using of Smart Assembly - error is gone.
Interesting is that no any errors or warnings shown by Visual Studio before trying to build a project.
Good luck!
EDIT: Updating Smart Assembly to version 6.9 fixed an issue.
As #Andrey reported this does appear to be an issue with obfuscated assemblies that is causing some difficulty for Roslyn. Today I was able to get a live repro of this error and the root cause appears to be the obfuscator is invalidating / corrupting how default parameter values are stored in metadata. When run through ildasm the default values will be displayed as:
.param [3] /* Invalid default value for 0800001F: */
The previous version of the compiler handled this scenario by treating the invalid value as null or default(T). We will be fixing Roslyn to have the same behavior.
I also had this exception being thrown in VB.NET (Visual Studio 2015 - Pro), and isolated a single line that was causing the error.
In the line of code below, if you define model as an integer, as in:
Dim model as Integer = 2
and then use:
Const N As Integer = model
you will throw the exception.
However, when I modified this to:
Dim N As Integer = model
the exception was not thrown. The Const syntax was legacy code from another program that I rapidly added model to, and constants can't be set to pre-defined integer types.
I just had "Failed to emit module". I mistakenly put empty brackets in a call to a generic extension method, only when inside a ternary operator, like this:
var a = b == 6 ? 8 : x.Foo<>();
(Outside of a ternary op, I just get regular error CS7003: Unexpected use of an unbound generic name.)
Extending on the answer from #jony-adamit:
I also had this compilation error being thrown in C# (Visual Studio 2015). It came down to the differences in compiler output from .NET 4.5 and Roslyn the new compiler in VS2015. You can take the below code and run it yourself or use dotnetfiddle (https://dotnetfiddle.net/fa2rMs) and switch between compilers.
In .NET 4.5 compiler (C# compiler version 12.0 or earlier) you get this message:
Compilation error (line 16, col 7): The type or namespace name
'Select' does not exist in the namespace 'Tools.Weapons' (are you
missing an assembly reference?)
In the Roslyn 1.0.0 and 1.1.0 compiler versions you get this message:
Compilation error (line 1, col 1): Failed to emit module
'MyAssembly'.
Code to reproduce the error (notice the namespace):
public class Program
{
public static void Main()
{
Tools.Delegater.Work();
}
}
namespace Tools
{
public static class Delegater
{
public static System.Action Work = () =>
{
var query = from x in Weapons
select x;
};
}
}
namespace Tools.Weapons
{
public class Cannon { }
}
As you can tell from the compiler messages, Roslyn's message leaves you guessing as to the what and the where about the compiler error. And depending on the size of the application, the lack of details could take days or weeks to discover the root cause. Whereas the message in the previous compiler pointed you to the exact spot to start reviewing your code.
Another big difference is the previous compiler will show you a syntax error in Visual Studio for this scenario, but unfortunately Roslyn (atm) does not. However, if you knew where to look and you hovered your mouse over the 'x' variable in the linq to sql statement, then you would see that Rosyln doesn't understand how to interpret it.
I was getting a similar error: "BC36970. Failed to emit module 'Something.dll'." I realize the error code is not the same but it is also a "failed to emit" type issue so I thought I'd share my answer.
Problem: My problem was that I had a string that was a constant but I was trying to append another string to it, like so (using VB code):
Dim MyString1 As String = "Test1"
Const MyString2 As String = "Test2" & MyString1
Solution: I simply had to convert the second string from Const to Dim and the error disappeared:
Dim MyString1 As String = "Test1"
Dim MyString2 As String = "Test2" & MyString1
I got this error when using a generic method but failing to include the type.
This code gave the error:
example.GetValue<>(foo);
Correction simply was to specify the type:
example.GetValue<string>(foo);
I'm not sure if the erroring example is valid syntax or not: I would have expected a syntax error if it is not rather than this error, and Intellisense accepted the syntax.
There's another bug that can cause this exact error:
Happened to me after changing a property name without refactoring, which caused some linq code to call the namespace itself!
To see the bug in action all you have to do is run this piece of code:
public static int Test()
{
var x = from c in ConsoleApplication5
select 3;
return x.First();
}
Where ConsoleApplication5 is the namespace!
This only happens in VS2015.
Update:
There's an issue for this now on GitHub if anyone's interested.
I got this error when I was working with data table and did not provide a data type where it was required:
bool temp = dtTab.AsEnumerable().Any(row => row.Field<>("active") == 1);
Giving it a proper data type got rid of the error. I also had to convert it to string to be able to compare it correctly-
bool temp = dtTab.AsEnumerable().Any(row => row.Field<Boolean>("active").toString() == "1");
I got this error too, seems like there is some major reasons that cause this error.
I posted this answer to wrap up mentioned solutions and help other guys so they can solve this error quickly
Using obfuscated DLLs by Smart Assembly mentioned on marked answer Solution: Update Smart Assembly to version 6.9
Namespace issue mentioned here, also has open Github issue Here
In my case the problem was this one, Field is strongly-typed, not specifying it, mentioned here
Using Const keyword, mentioned here
Please read all answers here on this page carefully, I'm sure you can solve the issue using one of mentioned solutions, good luck :)
This answer is similar to that posted by #wrtsvkrfm
'Dim NEWLINE As String = "<BR/>"
Dim NEWLINE As String = vbCrLf
Const HT_QTC_VENDOR As String = "<B>some stuff {0}</B>" & NEWLINE
This will cause the DLL to be not emitted,
Change the top 2 lines to
'Const NEWLINE As String = "<BR/>"
Const NEWLINE As String = vbCrLf
and the error goes away.
This should be a compilation error.
A CONST clearly cant depend on a variable, which may..., well..., vary. :-)
I get the same "Failed to emit module" error with this code but changing the "Const" to "Dim" resolves the problem:
Dim userStatus1 As String = convAttrSet("user_status")
Dim userStatus2 As String = convAttrSet("user_status")
Const PENDING As Boolean = (userStatus1 = userStatus2)
I got this error when using linq to entities and my linq query had a syntax error in the join clause
For me the issue occured after adding a postbuild step that changes the assemblyinfo.cs (NetRevisionTool.exe).
Take care to not change the AssemblyInfo.cs between building and Edit and continue.
I also had this exception being thrown in VB.NET (Visual Studio 2015 - Pro), and isolated a single line that was causing the error
Faulty....
Dim i As Short
Dim j As Short = BancoCombienElement(LaChaine)
Const a = (22 / 60) * j
Dim TiTxt As String = ""
Dim S_8_10_12_14 As String = ""
Work good!!!!!!!!
Dim i As Short
Dim j As Short = BancoCombienElement(LaChaine)
Dim a As Short = (22 / 60) * j
Dim TiTxt As String = ""
Dim S_8_10_12_14 As String = ""
Reason:
This error seems to be introduced when we have something weird in our code.
For me I made a mistake while getting the current user from identity.
Error Code:
int currentUserId = User.Identity.GetUserId<>();
Fixed Code:
Please specify the data type after GetUserID<---------->();In this case I have specified int.
Note
Please try to undo your code step by step so that you can find this issue. But otherwise it was very difficult for me track that error.
Thanks
This can happen for any error that the compiler did not catch. Probably
either the compiler doesn't know what IL to emit, or
it knows but in the process of actually doing it, something unexpected happens or
the IL that it emits is invalid and some safety net at a lower level than the compiler itself produces an error that the compiler is not built to handle.
In any case, this CS7038 occurs because the C# is valid and there is a good chance the compiler encountered an error in such an unexpected place that it is no longer able to trace it to any source code line that you wrote. Hence the seemingly random errors that people report here to cause this.
I've used C# for decades and I arrive here now because this is the first time ever I get an error like this.
In my case the following code generates the error. Use <LangVersion>Preview</LangVersion> in the project file and use the C# 8 compiler in Visual Studio 2019 preview.
void FailToEmitDll(ReadOnlySpan<char> span) {
ReadOnlySpan<char> temp;
temp = 1 switch
{
_ => span
};
}
Odd enough, if you change the declaration and the assignment to read like var temp instead, all works well.
Adding to the list of possible causes, in VS2019 with C# 8, I got the "Failed to emit module" message when doing something like:
_ = someBool ? SomeVoid() : default;
I filed a bug report about it here: https://github.com/dotnet/roslyn/issues/41741
I got this error when I run a complex expression in Mock object, I fixed this by store the expression result to local variable.
this is really my first time asking here, but I'm facing a problem which I'm sure of I'm missing something simple.
I wrote a C# class library with a function that returns a List>. The function itself works fine if used from a console application that I created to test the DLL.
The ending part of the function is:
/* Sorto i risultati in base al ranking */
List<KeyValuePair<string, double>> SortedList = new List<KeyValuePair<string, double>>(matchIndexList_rank);
SortedList.Sort(delegate(KeyValuePair<string, double> firstPair,
KeyValuePair<string, double> secondPair)
{
return (-1) * firstPair.Value.CompareTo(secondPair.Value);
}
);
stopWatch.Stop();
response.success = true;
response.executionTime = stopWatch.ElapsedMilliseconds;
response.resultListKVPStrDoub = SortedList;
return response;
Here for example the double part of the first value in the list is 15.5796761265999 (sorry cannot include pictures yet!)
The problem rises if I include the DLL in a ASP.NET MVC Application that uses the function. In this case the double part of the List> is returned without the decimal part.
The corresponding value to the one presented above is returned as 155796761265999.0
Here is a little bit of code where i get the wrong value returned:
searchEngine.Core.search search = new searchEngine.Core.search(HttpContext.Current.Server.MapPath("~/index_" + oIdentity.comapanyId.ToString()));
searchEngine.Core.genericResponse response = search.doSearch(searchStr);
double maxScore = response.resultListKVPStrDoub.Count > 0 ? response.resultListKVPStrDoub[0].Value : 1;
In example maxScore get the 155796761265999.0 value, but also every other value in the List suffers the same problem.
If I inspect the variables from both sides Visual Studio 2013 states that the type is indeed a double.
Both projects are developed on the same machine which also is my test environment. I use .Net Framework 4.0 on both projects and all build parameters seems to be equal on both projects.
I'm sure I'm missing something simple, but just can't get.
I'd appreciate any help.
Thanks
Lorenzo
Hi, problem solved ! (sorry but I can't yet answer by own question before 8 hours from posting)
Thanks to Radu Pascal that put me on the right way: normally I always add a class library to a solution to debug it, but in this case I had it developed for another project and it was working fine so I ignored the obviuos.
Thanks to Marc Gravell, he spotted the problem: even if I forgot it at the base of my search engine there is a file based index. There is where i reed my values from text and there is where I do the reading wrong.
The real mystery is that the same DLL used in the console application used for testing and even on another ASP.NET MVC on the same machine works fine. I solved using double.parse instead of Convert.ToDouble and imposing an invariant culture.
idfDict[idItem] = double.Parse(s.Split('|')[1], System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberFormatInfo.InvariantInfo);
Thanks to all!
Lorenzo
Hi, problem solved !
Thanks to Radu Pascal that put me on the right way: normally I always add a class library to a solution to debug it, but in this case I had it developed for another project and it was working fine so I ignored the obviuos.
Thanks to Marc Gravell, he spotted the problem: even if I forgot it at the base of my search engine there is a file based index. There is where i reed my values from text and there is where I do the reading wrong.
The real mystery is that the same DLL used in the console application used for testing and even on another ASP.NET MVC on the same machine works fine. I solved using double.parse instead of Convert.ToDouble and imposing an invariant culture.
idfDict[idItem] = double.Parse(s.Split('|')[1], System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberFormatInfo.InvariantInfo);
Thanks to all!
Lorenzo
I'm trying to use ISpannable in a Monodroid project but am having problems with GetSpans. What I'm ultimately after is a Rich Text editor such as at:
https://code.google.com/p/android-richtexteditor/source/browse/?r=4#svn/trunk/src/net/sgoliver
However, the Xamarin documentation for GetSpans isn't particularly helpful. The line I'm trying to convert from Java to C# is:
StyleSpan[] ss = s.getSpans(styleStart, position, StyleSpan.class);
However, I don't know what to pass for the last parameter as writing StyleSpan.class in C# gives a compile error of "} expected". What can I pass in to the last parameter to get all spans, or all spans of a particular type?
The C# equivalent should be Java.Lang.Class.FromType(typeof(StyleSpan)).
What is the state of dynamic code evaluation in C#? For a very advanced feature of an app I'm working on, I'd like the users to be able to enter a line of C# code that should evaluate to a boolean.
Something like:
DateTime.Now.Hours > 12 && DateTime.Now.Hours < 14
I want to dynamically eval this string and capture the result as a boolean.
I tried Microsoft.JScript.Eval.JScriptEvaluate, and this worked, but it's technically deprecated and it only works with Javascript (not ideal, but workable). Additionally, I'd like to be able to push objects into the script engine so that they can be used in the evaluation.
Some resources I find mentioned dynamically compiling assemblies, but this is more overhead than I think I want to deal with.
So, what is the state of dynamic script evaluation in C#? Is it possible, or am I out of luck?
You use the DLR's ScriptEngine, here is an example:
http://www.codeproject.com/KB/codegen/ScriptEngine.aspx
The most informative link is this one:
Execute a string in C# 4.0
Expression Trees might also be of interest:
http://community.bartdesmet.net/blogs/bart/archive/2009/08/10/expression-trees-take-two-introducing-system-linq-expressions-v4-0.aspx
Alternatively these links:
http://www.codeproject.com/KB/dotnet/Expr.aspx
How can I evaluate a C# expression dynamically?
How can I evaluate C# code dynamically?