I always work in C#, but I've been asked to work on a legacy VB.Net solution. In the legacy code, I am seeing this:
Private transactionListField() As TransactionInfoForStatement
This makes no sense to me! If it was C#, I'd expect this:
private List<Transaction> _transactions;
Can someone please explain to me what that VB code does? The parenthesis after the name makes me think it is calling a method, but when I Go To Definition in Visual Studio, I just end up on the same line!
That's an array declaration, you could also use this syntax that i prefer:
TransactionListField As TransactionInfoForStatement() ' array which is declared but Nothing
Arrays or indexers always use () in VB.NET as opposed to C# where you use [].
There's one advantage if you use the braces-first-syntax, you can specify the size:
TransactionListField(10) As TransactionInfoForStatement ' array that contains 11 Nothing
Related
VS 2013, MVC 5, VB, Entity Framework
This is part of my Class:
Public Class Order
....
Private mFirstName As String
<Required(ErrorMessage:="First name required - hard coded")>
Public Property FirstName() As String
Get
Return mFirstName
End Get
Set(ByVal value As String)
mFirstName = value
End Set
End Property
....
I want to setup a resource file to allow error messages to change with different countries. What would I write to have the error message pulled from a resource file named ErrorMessages.resx?
The examples for doing this are mostly in C#, and finding the VB equivalent was difficult, at least for me, and I thought other VB programmers might appreciate the proper syntax.
The C# answer is:
[Required(ErrorMessageResourceType=typeof(ErrorMessages),ErrorMessageResourceName="FirstNameRequired")]
What was difficult was to find the proper VB operator to apply for the C# "typeof" operator. In VB the line above is:
<Required(ErrorMessageResourceName:="FirstNameRequired", ErrorMessageResourceType:=GetType(Resources.ErrorMessages))>
in the lines above, the Name/Value pairs are stored in ErrorMessages.resx (see how to create below), and "FirstNameRequired" is the Name of the string that will hold the actual text to be displayed.
Just to cover the bases:
What's pretty neat is that VS2013 automatically creates the Class and type definitions for the resource file and they show up in Intellisense, as in the VB line above 'Resources.ErrorMessages'.
It's also important to note the Data Annotation operators can have only one or the other of the two error message string properties, so the property "ErrorMessage" had to be removed as seen in the code lines in this answer post.
To use a Global Resource file (local files are possible), on the project node do an Add > Add ASP.NET Folder > Add App_GlobalResources. Then inside that folder Add > New Item > Resources File. After that the Name-Value pairs can be added, and then later additional country-culture resource files can be added, and online documentation for this process is fairly plentiful. ASP.NET, and MSDN for the country-culture.
The MSDN page that lists all of the data annotations is here; But I didn't find enough code samples to readily explain how to take advantage of the properties listed.
Hope this is helpful for someone else.
Best Regards,
Alan
I have an application which was built a few years ago. I came across a section of code that baffled me as the functionality this provides throughout the ASP .Net application is great but i just dont understand it. Perhaps its the [] throwing me off but i think it could be some C# code converted to VB .Net.... Not sure but wondered if anyone understands this and if so could they share what its doing
The code in an NotInheritable class
Public Overloads Function [Get](Of B)() As B
Dim myType = GetType(B)
Return DirectCast([Get](myType), B)
End Function
I understand it overloads a function but
Why are the [] there for and what do they mean? When would you use them? If i remove them i have a compiler error.
Get in VB .Net is used in properties so is this some shortcut access to a property somewhere? Or
where could i view which method its overloading?
I've used code similar to List(Of Customer), IQueryable(of Customer) but how has (Of B) allowed in this manner?
I have read up on MSDN and researched around. The only thing that comes to mind is either some C# syntax conversion or some old VB6 syntax which the original developer must have used whilst creating the application.
Appreciate any clarification on this.
Because Get is part of Visual Basic Language Keywords. You need the bracket to indicate you want to use them as a method/property name.
Here is an excerpt from Microsoft on Keywords as Element Names in Code (Visual Basic):
Any program element — such as a variable, class, or member — can have
the same name as a restricted keyword. For example, you can create a
variable named Loop. However, to refer to your version of it — which
has the same name as the restricted Loop keyword — you must either
precede it with a full qualification string or enclose it in square
brackets ([ ]), as the following example shows.
1) Brackets allow you to use reserved words as identifiers (like the ampersand in c#).
2) It appears to be a bad naming decision. If they wanted to hide an existing member they could have used the Shadows keyword.
3) You'll need to examine the inheritance hierarchy. Start with the most recent parent.
4) It is calling a different overload of Get in the implementation but the Of B is trying to contrain it to B for some reason.
I have a custom user control (ascx) that contains a textbox and a Javascript-based counter to let the user know many characters they have left to type. In this control is the following:
function GetTextBox() {
return document.getElementById("<%=txNotes.ClientID %>");
}
This worked fine when we only had one instance of this user control on the page, but now we have to support multiple. As you know, having multiple instances of this control on a page will result in multiple GetTextBox() functions, only the last of which will be called no matter what. To support multiple instances, I use this:
if (!string.IsNullOrEmpty(TextBoxName) && !Page.ClientScript.IsClientScriptBlockRegistered(TextBoxName))
{
string Script = string.Format("function Get{0}Notes() {{ return document.getElementById(\"{1}\"); }}",
TextBoxName, txNotes.ClientID);
Page.ClientScript.RegisterClientScriptBlock(GetType(), TextBoxName, Script, true);
}
TextBoxName is a public usercontrol property, so if the developer passes Employee through, it will generate a Javascript function called GetEmployeeNotes(). This works greate because now we can have a unique GetNotes() function.
However, I don't like how it's hardcoded into the codebehind. I would like a markup-based solution for this, something that doesn't require a rebuild of the project in case I want to change the Javascript. Does anyone know of a way to do this?
Edit: I've already thought of creating a separate .js file that I could read with a text reader, but that sounds a bit hacky and I'd like to avoid that if at all possible.
Edit 2: Guard's answer below would work, but I don't want to go that route for the reason I gave beneath his answer. If no one can offer another way to do what I want to do, I will most likely mark his as the answer since it technically does exactly what I am asking.
I'm not a .NET specialist, but isn't it working as a preprocessor?
Isn't it legal to write
function Get<%=Name %>Notes() {...}
?
Why not use a generic function and just pass the id of the corresponding textbox? As in: GetNotes(thisTextBoxId) {...}. Not only would that deal with your problem but also is more DRY.
I am trying to achieve this but this is not working. I am sure i am missing something, please help me where i am wrong. I hope this is achievable. We should able to pass a string from ASP Page (using vbscript) to c# dll ( have this dll stored in gac and i have already registered it using regasm utility).
Below is my code:
Function GetObj()
Set Obj = Server.CreateObject("namespace.classname")
Set inputStr = Nothing
inputStr = "myString"
Set GetObj = Obj.dotnetMethod(inputStr)
SET Obj = NOTHING
End Function
The problem that i am facing is that when i passs inputStr to the obj.dotnetMethod, it is not recognising the string that i am passing from the asp page and it doesn't return to me any result which it should.
Could be a unicode problem--.Net expects unicode strings. ASP, I believe, does not.
But if you aren't even sure the method is registered, well then you have to make sure that dll is COM visible. ASP is a world that doesn't know anything about managed code or .Net. You have to use COM. You know, old school regsvr32, or ASP won't find it.
I can guess at a couple of things the might be going wrong (your question really needs more detail)
Set GetObj = Obj.dotnetMethod(inputStr)
dotnetMethod returns a String, DateTime or a primitive type such Int32 in which case you should remove the Set keyword.
dotnetMethod is return an object that isn't ComVisible itself.
BTW,
Set inputStr = Nothing
inputStr = "myString"
Why set inputStr to Nothing and then assign a string to it??
I have one JSON that is coming in a string format. I need to store it in a key-pair value or something like that. I am using asp.net 2.0 and can not use 3rd party DLL like Newtonsoft.Json.dll. I guess last option will be to use regular expression.
Can anybody please help me in this?
If you go to http://www.json.org/ and look towards the bottom of the page there are dozens of json libraries most of them open source, I believe they list 8 for C#. If you can not reference one of these libraries, I think your best bet would be to find one with a permissive license and simply add the code to your project.
Another idea is to look at the diagrams, grammer, and syntax at http://www.json.org/ and just write your own parser, but regex is NOT the way to do it. If you dont know how to write a parser you could look at one of the open source json libraries or start with something less complicated like a good CSV parser, here is a paper that looks pretty good: http://www.boyet.com/Articles/CsvParser.html
It is possible to serialize JSON using JScript in C# into key/value pairs. You need to add a few references to your project. They're part of the .NET framework, you just need to add the references to your project. You'll need:
Microsoft.JSript
Microsoft.Vsa
First, the usings at the top of your class:
using Microsoft.JScript;
using Microsoft.JScript.Vsa;
Then the Engine that will execute the script needs to be initialized somewhere in your 'Page' code-behind:
VsaEngine Engine = VsaEngine.CreateEngine();
Then you just create this method and call it by passing in your JSON object:
object EvalJScript(string JScript)
{
object result = null;
try
{
result = Microsoft.JScript.Eval.JScriptEvaluate(JScript, Engine);
}
catch (Exception ex)
{
return ex.Message;
}
return result;
}
The type of object returned (if JSON is passed in) is a 'JSObject'. You can access its values as key/value pairs. Read the MSDN documentation for more details on this object.
Here's an example of using the code:
string json = "({Name:\"Dan\",Occupation:\"Developer\"})";
JSObject o = EvalJScript(json) as JSObject;
string name = o["Name"] as string; // Value of 'name' will be 'Dan'
Could you use JScript.NET?
If so, should be easy enough with eval() - then just loop through the objects returned and translate into KeyValuePair's or whatever
You will need to use jscript.net as the code behind language, but other pages of your site should be fine to stay as c# if thats what you prefer.
As mentioned in previous comment, you will need to be aware of the security aspects and risks - only use eval if you trust the JSON you're parsing!