public static class ExtNumbers
{
public static decimal ToDecimal(this string value)
decimal result = Con.D0000m;
if (String.IsNullOrEmpty(value))
return result;
}
decimal.TryParse(value, out result);
The Reflector class below generates an HTML document outlining the public API for a given assembly.
First, an XML document is emitted in memory (see Emit*()).
The document captures the relevant aspects of the assembly's metadata.
Next, an HTML document is extracted from the XML document (see Extract*()).
I love Linq.
Public Class Reflector Public document As XDocument Public Sub Reflect(ByVal assemblyFile As String) Dim Assembly As Assembly = Assembly.LoadFrom(assemblyFile) document = New XDocument(EmitAssembly(Assembly)) End Sub Public Sub Transform(ByVal writer As XmlWriter) If document Is Nothing Then Return Dim assembly As XElement = document.Element("assembly") Dim transform As New XDocument(ExtractAssembly(assembly)) transform.Save(writer) End Sub Public Function EmitAssembly(ByVal assembly As Assembly) As XElement Return End Function Public Function EmitNamespace(ByVal ns As String, ByVal types As IEnumerable(Of Type)) As XElement Return End Function Public Function EmitType(ByVal type As Type) As XElement Return < name=> > End Function Public Function EmitGenericArguments(ByVal args As IEnumerable(Of Type)) As IEnumerable(Of XElement) Return From arg In args _ Select End Function Public Function EmitModifiers(ByVal type As Type) As XElement Dim builder As StringBuilder = New StringBuilder() If type.IsPublic Then builder.Append("public") ElseIf type.IsNestedPublic Then builder.Append("public") ElseIf type.IsNestedFamily Then builder.Append("protected") ElseIf type.IsNestedFamANDAssem Then builder.Append("protected internal") End If If type.IsSealed Then builder.Append(" sealed") If type.IsAbstract Then builder.Append(" abstract") Return End Function Public Function EmitExtends(ByVal baseType As Type) As XElement If baseType Is Nothing Or baseType Is GetType(Object) Or baseType Is GetType(ValueType) Or baseType Is GetType(System.Enum) Then Return Nothing Return End Function Public Function EmitImplements(ByVal ifaces As IEnumerable(Of Type)) As IEnumerable(Of XElement) Return From iface In ifaces _ Select End Function Public Function EmitDeclaringType(ByVal declaringType As Type) As XElement If declaringType Is Nothing Then Return Nothing Return End Function Public Function EmitNestedTypes(ByVal ntypes As IEnumerable(Of Type)) As IEnumerable(Of XElement) Return From ntype In ntypes _ Where GetVisible(ntype) _ Select EmitType(ntype) End Function Public Function EmitMethods(ByVal metds As IEnumerable(Of MethodBase)) As IEnumerable(Of XElement) Return From metd In metds _ Where GetVisible(metd) _ Select End Function Public Function EmitProperties(ByVal props As IEnumerable(Of PropertyInfo)) As IEnumerable(Of XElement) Return From prop In props _ Where GetVisible(prop.GetGetMethod()) Or _ GetVisible(prop.GetSetMethod()) _ Select End Function Public Function EmitReference(ByVal type As Type) As IEnumerable(Of Object) If (Not type.IsGenericType) Then Return New Object() {New XAttribute("name", type.Name), _ New XAttribute("namespace", GetNamespace(type))} Else Return New Object() {New XAttribute("name", type.Name), _ New XAttribute("namespace", GetNamespace(type)), _ EmitGenericArguments(type.GetGenericArguments())} End If End Function Public Function EmitModifiers(ByVal metd As MethodBase) As XElement Dim builder As StringBuilder = New StringBuilder() If metd.IsPublic Then builder.Append("public") ElseIf metd.IsFamily Then builder.Append("protected") ElseIf metd.IsFamilyAndAssembly Then builder.Append("protected internal") End If If metd.IsAbstract Then builder.Append(" abstract") If metd.IsStatic Then builder.Append(" static") If metd.IsVirtual Then builder.Append(" virtual") Return New XElement("modifiers", builder.ToString()) End Function Public Function EmitReturnType(ByVal metd As MethodBase) As XElement Dim metdInfo As MethodInfo = TryCast(metd, MethodInfo) If metdInfo Is Nothing Then Return Nothing Return End Function Public Function EmitExtension(ByVal metd As MethodBase) As XElement Return End Function Public Function EmitParameters(ByVal parms As IEnumerable(Of ParameterInfo)) As IEnumerable(Of XElement) Return From parm In parms _ Select End Function Public Shared Function GetNamespace(ByVal type As Type) As String Dim ns As String = type.Namespace Return If(ns IsNot Nothing, ns, String.Empty) End Function Public Shared Function GetVisible(ByVal type As Type) As Boolean Return type.IsPublic Or type.IsNestedPublic Or type.IsNestedFamily Or type.IsNestedFamANDAssem End Function Public Shared Function GetVisible(ByVal metd As MethodBase) As Boolean Return metd IsNot Nothing AndAlso (metd.IsPublic Or metd.IsFamily Or metd.IsFamilyAndAssembly) End Function Public Function ExtractAssembly(ByVal assembly As XElement) As XElement Return Assembly: End Function Public Function ExtractNamespace(ByVal ns As XElement) As XElement Return Namespace: End Function Public Function ExtractType(ByVal type As XElement) As XElement Return End Function Public Function ExtractModifiers(ByVal element As XElement) As String Return element.Element("modifiers").Value End Function Public Function ExtractName(ByVal element As XElement) As String Dim name As String = element.Attribute("name").Value Dim i As Integer = name.LastIndexOf("`") If i > 0 Then name = name.Substring(0, i) ' fix generic name Return name End Function Public Function ExtractGenericArguments(ByVal element As XElement) As String If Not element.Elements("genericArgument").Any() Then Return String.Empty Dim builder As StringBuilder = New StringBuilder("<") For Each genericArgument As XElement In element.Elements("genericArgument") If builder.Length <> 1 Then builder.Append(", ") builder.Append(ExtractReference(genericArgument)) Next builder.Append(">") Return builder.ToString() End Function Public Function ExtractReference(ByVal element As XElement) As String Return ExtractName(element) + ExtractGenericArguments(element) End Function Public Function ExtractInherits(ByVal type As XElement) As String If Not type.Elements("extends").Concat(type.Elements("implements")).Any() Then Return String.Empty Dim builder As New StringBuilder() For Each [inherits] As XElement In type.Elements("extends").Concat(type.Elements("implements")) If builder.Length = 0 Then builder.Append(" : ") Else builder.Append(", ") End If builder.Append(ExtractReference([inherits])) Next Return builder.ToString() End Function Public Function ExtractConstructors(ByVal type As XElement) As XElement Dim ctors = From ctor In type.Elements("method") _ Where ExtractName(ctor) = ".ctor" _ Select
You want to return a string, just a string, from an HTTP POST call.
You code it like this:
Response.Write("Hello World")
The HTTP POST returns:
All you wanted was “Hello World”.
You should have coded it like this:
Response.Write("Hello World") ' The Response.End method causes the Web server to stop processing the script and return the current result. The remaining contents of the file are not processed. Response.End()
The VisualBasic 2012 Async feature makes it simpler to make code asynchronous.
With it you can call into asynchronous methods WITHOUT callbacks and WITHOUT splitting your code into different methods.
The following example shows a Visual Basic async method.
' Add an Imports statement and a reference for System.Net.Http
Imports System.Net.Http Class MainWindow ' Mark the event handler with async so you can use Await in it. Private Async Sub StartButton_Click(sender As Object, e As RoutedEventArgs) ' Call and await separately. 'Task<int> getLengthTask = AccessTheWebAsync(); '' You can do independent work here. 'int contentLength = await getLengthTask; Dim contentLength As Integer = Await AccessTheWebAsync() ResultsTextBox.Text &= String.Format(vbCrLf & "Length of the downloaded string: {0}." & vbCrLf, contentLength) End Sub ' Three things to note in the signature: ' - The method has an Async modifier. ' - The return type is Task or Task(Of T). (See "Return Types" section.) ' Here, it is Task(Of Integer) because the return statement returns an integer. ' - The method name ends in "Async." Async Function AccessTheWebAsync() As Task(Of Integer) ' You need to add a reference to System.Net.Http to declare client. Dim client As HttpClient = New HttpClient() ' GetStringAsync returns a Task(Of String). That means that when you await the ' task you'll get a string (urlContents). Dim getStringTask As Task(Of String) = client.GetStringAsync("http://msdn.microsoft.com") ' You can do work here that doesn't rely on the string from GetStringAsync. DoIndependentWork() ' The Await operator suspends AccessTheWebAsync. ' - AccessTheWebAsync can't continue until getStringTask is complete. ' - Meanwhile, control returns to the caller of AccessTheWebAsync. ' - Control resumes here when getStringTask is complete. ' - The Await operator then retrieves the string result from getStringTask. Dim urlContents As String = Await getStringTask ' The return statement specifies an integer result. ' Any methods that are awaiting AccessTheWebAsync retrieve the length value. Return urlContents.Length End Function Sub DoIndependentWork() ResultsTextBox.Text &= "Working . . . . . . ." & vbCrLf End Sub End Class ' Sample Output: ' Working . . . . . . . ' Length of the downloaded string: 41763.
Imports System.Net.Http
Class MainWindow
' Mark the event handler with async so you can use Await in it.
Private Async Sub StartButton_Click(sender As Object, e As RoutedEventArgs)
' Call and await separately.
'Task<int> getLengthTask = AccessTheWebAsync();
'' You can do independent work here.
'int contentLength = await getLengthTask;
Dim contentLength As Integer = Await AccessTheWebAsync()
ResultsTextBox.Text &=
String.Format(vbCrLf & "Length of the downloaded string: {0}." & vbCrLf, contentLength)
End Sub
' Three things to note in the signature:
' - The method has an Async modifier.
' - The return type is Task or Task(Of T). (See "Return Types" section.)
' Here, it is Task(Of Integer) because the return statement returns an integer.
' - The method name ends in "Async."
Async Function AccessTheWebAsync() As Task(Of Integer)
' You need to add a reference to System.Net.Http to declare client.
Dim client As HttpClient = New HttpClient()
' GetStringAsync returns a Task(Of String). That means that when you await the
' task you'll get a string (urlContents).
Dim getStringTask As Task(Of String) = client.GetStringAsync("http://msdn.microsoft.com")
' You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork()
' The Await operator suspends AccessTheWebAsync.
' - AccessTheWebAsync can't continue until getStringTask is complete.
' - Meanwhile, control returns to the caller of AccessTheWebAsync.
' - Control resumes here when getStringTask is complete.
' - The Await operator then retrieves the string result from getStringTask.
Dim urlContents As String = Await getStringTask
' The return statement specifies an integer result.
' Any methods that are awaiting AccessTheWebAsync retrieve the length value.
Return urlContents.Length
End Function
Sub DoIndependentWork()
ResultsTextBox.Text &= "Working . . . . . . ." & vbCrLf
End Class
' Sample Output:
' Working . . . . . . .
' Length of the downloaded string: 41763.
To learn more click: Asynchronous Programming with Async and Await
Below is a class and enum that together provide a flexible way to return an action result to a caller.
It can be used to return error or success results.
It contains multiple constructors that give the flexibility of instantiating the ActionResult object in the context of the called method and possible actions that will take place.
Instantiate before making a call to pass it into a method call or instantiate within a method.
namespace aZSoftware { public enum ActionResultEnum { Unknown = 0, Success = 1, Failure = 2 } public class ActionResult { public ActionResultEnum ActionResultEnum { get; set; } public string Message { get; set; } public object ResultObject { get; set; } public string ErrorLog { get; set; } public ActionResult(ActionResultEnum actionResult) { this.ActionResultEnum = actionResult; Message = string.Empty; ResultObject = null; ErrorLog = string.Empty; } public ActionResult(ActionResultEnum actionResult,string message) { this.ActionResultEnum = actionResult; Message = message; ResultObject = null; ErrorLog = string.Empty; } public ActionResult(ActionResultEnum actionResult, string message,object resultObject) { this.ActionResultEnum = actionResult; Message = message; ResultObject = resultObject; ErrorLog = string.Empty; } public ActionResult(ActionResultEnum actionResult, string message, object resultObject,string errorLog) { this.ActionResultEnum = actionResult; Message = message; ResultObject = resultObject; ErrorLog = errorLog; } } }
The recommended way to create a Windows Communication Foundation (WCF) contract is with an interface. Acontract specifies the collection and structure of messages required to access the operations the service offers.
The ServiceContractAttribute class is used to indicate that an interface or a class defines a service contract in a Windows Communication Foundation (WCF) application.
A class can support multiple contracts by deriving and implementing multiple interfaces decorated with the ServiceContract attribute.
<ServiceContract> _ Interface IMyContract <OperationContract> _ Function MyMethod() As String End Interface <ServiceContract> _ Interface IMyOtherContract <OperationContract> _ Sub MyOtherMethod() End Interface Class MyService Implements IMyContract Implements IMyOtherContract Public Function MyMethod() As String Implements IMyContract.MyMethod End Function Public Sub MyOtherMethod() Implements IMyOtherContract.MyOtherMethod End Sub End Class
New in Visual Basic 2012 is the caller information feature. This feature enables you to obtain information about the caller of a method.
By using Caller Info attributes, you can obtain information about the caller to a method. You can obtain file path of the source code, the line number in the source code, and the member name of the caller. This information is helpful for tracing, debugging, and creating diagnostic tools.
To obtain this information, you use attributes that are applied to optional parameters, each of which has a default value.
For more information about using the Caller Information feature click:
Caller Information (C# and Visual Basic)
Sample Use
' Imports System.Runtime.CompilerServices ' Imports System.Diagnostics Private Sub DoProcessing() TraceMessage("Something happened.") End Sub Public Sub TraceMessage(message As String, <CallerMemberName> Optional memberName As String = Nothing, <CallerFilePath> Optional sourcefilePath As String = Nothing, <CallerLineNumber()> Optional sourceLineNumber As Integer = 0) Trace.WriteLine("message: " & message) Trace.WriteLine("member name: " & memberName) Trace.WriteLine("source file path: " & sourcefilePath) Trace.WriteLine("source line number: " & sourceLineNumber) End Sub ' Sample output: ' message: Something happened. ' member name: DoProcessing ' source file path: C:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoVB\CallerInfoVB\Form1.vb ' source line number: 15