Powered By Blogger

Sunday, January 08, 2023

Microsoft Visual Studio | Generate Class from JSON or XML

Microsoft Visual Studio | Generate Class from JSON or XML

I found an useful feature in visual studio to generate class from JSON or XML. In Visual Studio, you can copy JSON or XML text and then paste the text as classes in C#/VB.Net code file using following steps:
  1. Copy Your JSON: example:
    {
    "PersonId": 1,
    "GoalId": 111,
    "ActivityId": 1111,
    "Task": {
                  "Name": "Task-1",
                  "Description": "Task-1 desc",
                  "ActivityScope": 5,
                  "ActivityType": 1,
                  "isCustomized": true
               }
    }
  2. Select Edit > Paste Special and choose Paste JSON As Class:


    it will create class like this for the above JSON:



  3. Same can be done using XML Paste.

Monday, June 14, 2010

Localizing ASP.NET Web Pages By Using Resources

Resource Files:
A resource file is an XML file that contains the strings that you want to translate into different languages or paths to images. The resource file contains key/value pairs. Each pair is an individual resource. Key names are not case sensitive.
You create a separate resource file for each language (for example, English and French) or for a language and culture (for example English [U.K.], English [U.S.]). Each localized resource file has the same key/value pairs; the only difference is that a localized resource file can contain fewer resources than the default resource file.

List of Culters:
Resource files in ASP.NET have an .resx extension. At run time, the .resx file is compiled into an assembly, which is sometimes referred to as a satellite assembly. Because the .resx files are compiled dynamically, like ASP.NET Web pages, you do not have to create the resource assemblies. The compilation condenses several similar-language resource files into the same assembly.
When you create resource files, you start by creating a base .resx file. For each language that you want to support, create a new file that has the same file name. But in the name, include the language or the language and culture (culture name).
At run time, ASP.NET uses the resource file that is the best match for the setting of the CurrentUICulture property. The UI culture for the thread is set according to the UI culture of the page. For example, if the current UI culture is Spanish, ASP.NET uses the compiled version of the WebResources.es.resx file. If there is no match for the current UI culture, ASP.NET uses resource fallback. It starts by searching for resources for a specific culture. If those are not available, it searches for the resources for a neutral culture. If these are not found, ASP.NET loads the default resource file.

Globalization and Localization in ASP.NET



Globalization:
Globalization is the process of designing and developing applications that function for multiple cultures.
Globalization is defined as the process of developing an application so that it is usable across multiple cultures and regions, irrespective of the language and regional differences. For example, you have made a e-learning application and you live in a region where English is the main language. Now, if you want to sell your application in a different country, let’s say France, then you need to make sure that your program displays and takes input in French language.


Localization:
Localization is the process of customizing your application for a given culture and locale. Localization consists primarily of translating the user interface.
Localization is the process of creating content, input, and output data, in a region specific culture and language. Culture will decide date display settings (like, mm/dd/yyyy or dd/mm/yyyy), currency display formats etc. Now, the process by which we can make sure that our program will be localized is known as Internationalization or Globalization. In simpler terms, Globalization can be defined as the set of activities which will ensure that our program will run in regions with different languages and cultures.


So, globalization is related to intrinsic code changes to support such changes like using Resource files etc. Whereas, localization is the process of using a particular culture and regional info so that the program uses the local languages and culture. This means translating strings into a particular local language. This covers putting language specific strings in the resource files. Globalization starts in the main construction phase along with the code development. Localization generally comes later.

Tuesday, June 01, 2010

What’s New in Visual Basic.Net 2010


Auto-Implemented Properties:

Visual Basic 2010 introduces auto-implemented properties, which allow you to define a simple property using only one line of code:
                Property Country As String

When you declare an auto-implemented property, Visual Basic automatically creates a hidden private field called the backing field to contain the property value. The backing field name is the auto-implemented property name preceded by an underscore (_).The backing field also has the following characteristics:


• The access modifier for the backing field is always Private, even when the property itself has a different access level, such as Public.
• If the property is marked as Shared, the backing field also is shared.
• Attributes specified for the property do not apply to the backing field.
• The backing field can be accessed from code within the class and from debugging tools such as the Watch window. However, the backing field does not show in an IntelliSense word completion list.

You cannot initialize an auto-implemented property that is a member of an Interface, or one that is marked MustOverride.
When you declare an auto-implemented property as a member of a Structure, you can only initialize the auto-implemented property if it is marked as Shared.
 When you declare an auto-implemented property as an array, you cannot specify explicit array bounds. However, you can supply a value by using an array initializer, as shown in the following examples:

                    Property Grades As Integer() = {90, 73}
                    Property Temperatures As Integer() = New Integer() {68, 54, 71}

The equivalent code for the previous auto-implemented property:
      Private _ Country As String
      Property Country As String
      Get
             Return _ Country
      End Get
      Set(ByVal value As String)
             _ Country = value
       End Set
       End Property

In this case, the compiler will go ahead and generate the Getter, Setter and backing fields automatically. The name of the backing field will always be an underscore followed by the name of the property: _Countryin this case. This naming convention ensures binary serialization compatibility should an auto-implemented property be changed to a regular one. As long as the name of the backing field is the same, binary serialization will continue to work.


One of the cool things you can do with auto-implemented properties is specify initializers that set the property’s default value when the constructor runs. A common scenario with entity classes, for example, sets the primary key to something like -1 to indicate that it’s in an unsaved state.
              Property ID As Integer = -1

When the constructor runs, the backing field (_ID) will be set to the value -1 automatically. The initializer syntax also works for reference types:

            Property OrderList As List(Of Order) = New List(Of Order)
OR
            Property OrderList As New List(Of Order) ‘’New in VS2010

You can even combine this with Object Initializers to allow setting additional properties:
            Property OrderList As New List(Of Order) With {.Capacity = 100}

People often remark that the new property syntax is almost identical to the syntax for a public field, so why not use a public field instead? Well, for a few reasons:

• Much of the .NET data-binding infrastructure works against properties but not fields.
• An interface can’t enforce the existence of a field; it can enforce that of a property.
• Properties provide more long-term flexibility for changing business rules. For example, suppose someone introduces the rule that a phone number must be 10 digits. There’s no way to perform this validation when assigning to a public field. Changing a public field to a property is a breaking change for scenarios such as binary serialization and reflection.

Property Definitions That Require Standard Syntax:
You have to use expanded property-definition syntax if you want to do any one of the following:

• Add code to the Get or Set procedure of a property, such as code to validate incoming values in the Set procedure. For example, you might want to verify that a string that represents a telephone number contains the required number of numerals before setting the property value.
• Specify different accessibility for the Get and Set procedure. For example, you might want to make the Set procedure Private and the Get procedure Public.
• Create properties that are WriteOnly or ReadOnly.
• Use parameterized properties (including Default properties). You must declare an expanded property in order to specify a parameter for the property, or to specify additional parameters for the Set procedure.
• Place an attribute on the backing field.
• Provide XML comments for the backing field.

Expanding an Auto-Implemented Property: If you have to convert an auto-implemented property to an expanded property that contains a Get or Set procedure, the Visual Basic Code Editor can automatically generate the Get and Set procedures and End Property statement for the property. The code is generated if you put the cursor on a blank line following the Property statement, type a G (for Get) or an S (for Set) and press ENTER. The Visual Basic Code Editor automatically generates the Get or Set procedure for read-only and write-only properties when you press ENTER at the end of a Property statement.

Collection Initializers
Collection initializers provide a shortened syntax that enables you to create a collection and populate it with an initial set of values. Collection initializers are useful when you are creating a collection from a set of known values, for example, a list of menu options or categories.


Collection initializers provide a shortened syntax that enables you to create a collection and populate it with an initial set of values. Collection initializers are useful when you are creating a collection from a set of known values, for example, a list of menu options or categories, an initial set of numeric values, a static list of strings such as day or month names, or geographic locations such as a list of states that is used for validation. You identify a collection initializer by using the From keyword followed by braces ({}).

             ' Create an array of type String().
             Dim winterMonths = {"December", "January", "February"}

             ' Create an array of type Integer()
             Dim numbers = {1, 2, 3, 4, 5}

             ' Create a list of menu options. (Requires an extension method named Add for List(Of MenuOption)
             Dim menuOptions = New List(Of MenuOption) From {{1, "Home"},
                                                {2, "Products"},
                                                {3, "News"},
                                                {4, "Contact Us"}}

A collection initializer consists of a list of comma-separated values that are enclosed in braces ({}), preceded by the From keyword, as shown in the following code:
               Dim names As New List(Of String) From {"Christa", "Brian", "Tim"}

When you create a collection, such as a List<(Of <(T>)>) or a Dictionary<(Of <(TKey, TValue>)>), you must supply the collection type before the collection initializer, as shown in the following code:

     Public Class AppMenu

              Public Property Items As List(Of String) = New List(Of String) From {"Home", "About", "Contact"}

     End Class

When you create a collection by using a collection initializer, each value that is supplied in the collection initializer is passed to the appropriate Add method of the collection. For example, if you create a List<(Of <(T>)>) by using a collection initializer, each string value in the collection initializer is passed to the Add method. If you want to create a collection by using a collection initializer, the specified type must be valid collection type. Examples of valid collection types include classes that implement the IEnumerable<(Of <(T>)>) interface or inherit the CollectionBase class. The specified type must also expose an Add method that meets the following criteria:

• The Add method must be available from the scope in which the collection initializer is being called. The Add method does not have to be public if you are using the collection initializer in a scenario where non-public methods of the collection can be accessed.

• The Add method must be an instance member or Shared member of the collection class, or an extension method.

• An Add method must exist that can be matched, based on overload resolution rules, to the types that are supplied in the collection initializer.

Dim customers = New List(Of Customer) From
{
     New Customer("City Power & Light", http://www.cpandl.com/),
     New Customer("Wide World Importers", http://www.wideworldimporters.com/),
     New Customer("Lucerne Publishing", http://www.lucernepublishing.com/)
}

Implicit Line Continuation

In many cases, implicit line continuation enables you to continue a statement on the next consecutive line without using the underscore character (_).A statement in Visual Basic is a complete instruction. It can contain keywords, operators, variables, constants, and expressions. Each statement belongs to one of the following categories:

• Declaration Statements, which name a variable, constant, or procedure, and can also specify a data type.

• Executable Statements, which initiate actions. These statements can call a method or function, and they can loop or branch through blocks of code. Executable statements include Assignment Statements, which assign a value or expression to a variable or constant.

Multiline Lambda Expressions and Subroutines (Statement Lambdas)

A lambda is simply a function defined inside another function. Visual Basic 2010 introduces support for statement lambdas, which are lambdas that can contain one or more statements.

Lambda Expression

A lambda expression is a function or subroutine without a name that can be used wherever a delegate is valid. Lambda expressions can be functions or subroutines and can be single-line or multi-line. You can pass values from the current scope to a lambda expression.

The RemoveHandler statement is an exception. You cannot pass a lambda expression in for the delegate parameter of RemoveHandler.

You create lambda expressions by using the Function or Sub keyword, just as you create a standard function or subroutine. However, lambda expressions are included in a statement.

The following example is a lambda expression that increments its argument and returns the value. The example shows both the single-line and multi-line lambda expression syntax for a function:

          Dim increment1 = Function(x) x + 1
          Dim increment2 = Function(x)
                                          Return x +
                                     End Function

' Write the value 2.
Console.WriteLine(increment1(1))

' Write the value 4.
Console.WriteLine(increment2(2))

The syntax of a lambda expression resembles that of a standard function or subroutine. The differences are as follows:

• A lambda expression does not have a name.

• Lambda expressions cannot have modifiers, such as Overloads or Overrides.

• Single-line lambda functions do not use an As clause to designate the return type. Instead, the type is inferred from the value that the body of the lambda expression evaluates to. For example, if the body of the lambda expression is cust.City = "London", its return type is Boolean.

• In multi-line lambda functions, you can either specify a return type by using an As clause, or omit the As clause so that the return type is inferred. When the As clause is omitted for a multi-line lambda function, the return type is inferred to be the dominant type from all the Return statements in the multi-line lambda function. The dominant type is a unique type that all other types in the array literal can widen to. If this unique type cannot be determined, the dominant type is the unique type that all other types in the array can narrow to. If neither of these unique types can be determined, the dominant type is Object. For example, if the list of values supplied to the array literal contains values of type Integer, Long, and Double, the resulting array is of type Double. Both Integer and Long widen to Double and only Double. Therefore, Double is the dominant type.

• The body of a single-line function must be an expression that returns a value, not a statement. There is no Return statement for single-line functions. The value returned by the single-line function is the value of the expression in the body of the function.
• The body of a single-line subroutine must be single-line statement.
• Single-line functions and subroutines do not include an End Function or End Sub statement.
• You can specify the data type of a lambda expression parameter by using the As keyword, or the data type of the parameter can be inferred. Either all parameters must have specified data types or all must be inferred.
• Optional and Paramarray parameters are not permitted.
• Generic parameters are not permitted


Context: A lambda expression shares its context with the scope within which it is defined. It has the same access rights as any code written in the containing scope. This includes access to member variables, functions and subs, Me, and parameters and local variables in the containing scope. Access to local variables and parameters in the containing scope can extend beyond the lifetime of that scope. As long as a delegate referring to a lambda expression is not available to garbage collection, access to the variables in the original environment is retained.
A lambda expression can be implicitly converted to a compatible delegate type.


Type Equivalence Support

You can now deploy an application that has embedded type information instead of type information that is imported from a Primary Interop Assembly (PIA). With embedded type information, your application can use types in a runtime without requiring a reference to the runtime assembly. If various versions of the runtime assembly are published, the application that contains the embedded type information can work with the various versions without having to be recompiled.

Dynamic Support
Visual Basic binds to objects from dynamic languages such as IronPython and IronRuby.


Covariance and Contravariance

Covariance enables you to use a more derived type than that specified by the generic parameter, whereas contravariance enables you to use a less derived type. This allows for implicit conversion of classes that implement variant interfaces and provides more flexibility for matching method signatures with variant delegate types. You can create variant interfaces and delegates by using the new In and Out language keywords. The .NET Framework also introduces variance support for several existing generic interfaces and delegates, including the IEnumerable<(Of <(T>)>) interface and the Func<(Of <(TResult>)>) and Action<(Of <(T>)>) delegates.

Covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments. Covariance preserves assignment compatibility and contravariance reverses it.

The following code demonstrates the difference between assignment compatibility, covariance, and contravariance:
' Assignment compatibility.
Dim str As String = "test"

' An object of a more derived type is assigned to an object of a less derived type.
Dim obj As Object = str
' Covariance.
Dim strings As IEnumerable(Of String) = New List(Of String)()
' An object that is instantiated with a more derived type argument
' is assigned to an object instantiated with a less derived type argument.
' Assignment compatibility is preserved.

Dim objects As IEnumerable(Of Object) = strings
' Contravariance.
' Assume that there is the following method in the class:
' Shared Sub SetObject(ByVal o As Object)
' End Sub

Dim actObject As Action(Of Object) = AddressOf SetObject
' An object that is instantiated with a less derived type argument
' is assigned to an object instantiated with a more derived type argument.
' Assignment compatibility is reversed.

Dim actString As Action(Of String) = actObject

*********************************************************************************************************************************