Tag Archives: .net jobs

Soap Request And Response Example In Asp.net

Every SOAP request and response are made of SOAPEnvelope. SOAPEnvelope has SOAPHeader, SOAPBody, SOAPFault.

SOAP uses Http Post method and the SOAPEnvelope is submitted as MessageBody.

A Webservice created in .Net could be used by an Http Client also. Here the method name is submitted as the PathInfo and the parameters are posted as a string of Name-Value pairs.

http:// ServerName/ApplicationName/ DemoService.asmx/ MethodName

SOAP Request

POST /DecWebServices/DemoService.asmx HTTP/1.1

Host: localhost

Content-Type: text/xml; charset=utf-8

Content-Length: length

SOAPAction: “http://tempuri.org/Add”

<?xml version=”1.0″ encoding=”utf-8″?>

<soap:Envelopexmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”>

<soap:Body>

<Add xmlns=”http://tempuri.org/”>

<a>int</a>

<b>int</b>

</Add>

</soap:Body>

</soap:Envelope>

SOAP Response

HTTP/1.1 200 OK

Content-Type: text/xml; charset=utf-8

Content-Length: length

<?xml version=”1.0″ encoding=”utf-8″?>

<soap:Envelopexmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/”>

<soap:Body>

<AddResponse xmlns=”http://tempuri.org/”>

<AddResult>int</AddResult>

</AddResponse>

</soap:Body>

</soap:Envelope>

Note: To view the WSDL document we can use the following URL

http://localhost/SepWebServices/Service.asmx?wsdl

Client Application: (In New Instance of VS.NET)

Step 3: File –> New Project –> Windows Application
Step 4: In the Solution Explorer –> References –> Right Click –> Add Service Reference –> In URL give the Url of Web Service(can copy from browser where we can see the webservice methods) –> Click on Go.
Step 5: In the same dialog:
Namespace = localhost (name of the domain on which the web service is hosted is used)


To note: When a WebService reference is added in VS.Net that is using add Web reference it automatically creates a proxy class in the current project using a utility program called as
WSDL.EXE. The same can be viewed by opening the file Reference.cs.

Step 6:
Use WebServiceClientAppName.localhost
private void btnDemo_Click(object sender, EventArgs e)
{
DemoServiceSoapClient ds = new DemoServiceSoapClient();
MessageBox.Show(ds.Add(20, 50).ToString());
}

Step 7: Run the Client Application


To note: If a new method is added to the webservice class, right click on web reference of the webservice and choose Update service Reference to reflect the new method in the proxy class.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well-structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

.NET Framework : Interview Questions and Answers

Here are a few important and frequently asked .NET based interview questions and answers:

What is .NET Framework?

.NET Framework is an environment that helps developers to develop, run, and deploy the following:

    • Console applications
    • Windows Forms applications
    • Windows Presentation Foundation (WPF) applications
    • Web applications (ASP.NET applications)
    • Web services
    • Windows services
    • Service-oriented applications using Windows Communication Foundation (WCF)
    • Workflow-enabled applications using Windows Workflow Foundation (WF)

.NET Framework also enables a developer to develop shareable components to be used in distributed computing architecture.

What are the components of .NET Framework?

.NET Framework offers several advantages to software developers. The following are the key components of .NET Framework:

    • .NET Framework Class Library
    • Common Language Runtime
    • Dynamic Language Runtimes (DLR)
    • Application Domains
    • Runtime Host
    • Common Type System
    • Metadata and Self-Describing Components
    • Cross-Language Interoperability
    • .NET Framework Security
    • Profiling
    • Side-by-Side Execution

List the new features added in .NET Framework 4.0.

The following are the new features of .NET Framework 4.0:

    • Improved Application Compatibility and Deployment Support
    • Dynamic Language Runtime
    • Managed Extensibility Framework
    • Parallel Programming framework
    • Improved Security Model
    • Networking Improvements
    • Improved Core ASP.NET Services
    • Improvements in WPF 4
    • Improved Entity Framework (EF)
    • Integration between WCF and WF

What is an IL?

Intermediate Language or IL is also known as Microsoft Intermediate Language or Common Intermediate Language. All .NET source code is compiled to it. IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time compiler.

Define Manifest.

Assembly metadata is stored in Manifest. This contains all the metadata needed to do the following:

    • Version of assembly.
    • Security identity.
    • Scope of the assembly.
    • Resolve references to resources and classes.

What are code contracts?

Code contracts help you to express the code assumptions and statements stating the behavior of your code in a language-neutral way. The contracts are included in the form of pre-conditions, post-conditions and object-invariants. The contracts assist you to improve-testing by enabling run-time checking, static contract verification, and documentation generation.

TheSystem.Diagnostics.Contracts namespace contains static classes that are used to express contracts in your code.

Name the classes that are introduced in the System.Numerics namespace.

The following two new classes are introduced in the System.Numerics namespace:

  • BigInteger
  • Complex

What is managed extensibility framework?

Managed extensibility framework or MEF is a new library that is introduced as a part of .NET 4.0 and Silverlight 4. It extends your application by giving greater reuse of applications and components. MEF offers a way for the host application to consume external extensions without any configuration requirement.

Explain memory-mapped files.

Memory-mapped files (MMFs) helps you map the content of a file to the logical address of an application. These files enable the multiple processes running on the same machine to share data with each Other. The MemoryMappedFile.CreateFromFile() method is used to obtain a MemoryMappedFile object that represents a persisted memory-mapped file from a file on disk.

What is Common Type System (CTS)?

CTS are the component of CLR via which .NET Framework offers support for multiple languages as it contains a type system that is common in all the languages.

Two CTS-compliant languages do not require type conversion when calling the code written in one language from within the code written in another language. CTS provide a base set of data types for all the languages supported by.NET Framework.

This means that the size of integer and long variables are same across all .NET-compliant programming languages. However, each language uses aliases for the base data types provided by CTS. For example, CTS uses the data type system.

Give a brief introduction on side-by-side execution. Can two applications, one using private assembly and the other using the shared assembly be stated as side-by-side executables?

Side-by-side execution makes you run multiple versions of an application or component and CLR on the same computer at the same time. As versioning is applicable only to shared assemblies and not to private assemblies, two applications, one using a private assembly and other using a shared assembly, cannot be stated as side-by-side executables.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Also Read:Top 15 ASP.Net Interview Questions and Answers 
Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Distributed Computing Framework In .Net

Proxy is a client side way to represent the actual object on server. It puts the same set of interfaces as the actual object implements.

When the client asks for an example of a remote object, the underlying services creates the actual object in the server process and the proxy object in the client process, the client gets the reference to the local proxy object.

Along the actual object a “stub” object is created on server. The proxy and stub are connected over a socket and communicates with each other with the help of a common protocol.

Whenever the client requests the method of the proxy, the implementation in Proxy serializes all the parameters of the method and transports them to Stub i.e. proxy marshals the request to stub.

On Server, Stub de-serializes the call and passes the references of the objects as parameters to the actual method in actual object.

Server method returns data to Stub, which serializes the data and return to proxy, proxy next dserializes and return the data to the client object.

Terminologies

SUN (Stanford University Network

RMI (Remote Method Invocation)

JRMP(Java RMI Protocol)

OMG (Object Management Group)

CORBA Common Object Request Broker Arch.

IIOP (Internet Interoperable Protocol MS (Microsoft)

DCOM (Distributed Component Object Model)

Problem: Due to the proxy and the stub are tightly joined to each other they must use the common protocol for communication. As the protocols used by RMI, COBRA and DCOM are native protocols they lack Interoperability.

WebService

A WebService is a business object that runs on a Web Server and providing its functionality to any type of application / client which supports “SOAP” (Simple Object Access Protocol) protocol.

SOAP = XML + HTTP. SOAP is a specification by W3C. – It’s an architectural neutral protocol.

In .Net WebSevices are maintained by ASP.NET Framework. They are mostly used for developing B-B (Business to Business) services/application. Any kind of application which we could develop in MS.NET can be a client to WebService.

WSDL (Web Service Description Language):

An XML based document containing complete information of the web service including methods and their parameters, the URL etc…

For every web service developed, the corresponding WSDL document is distributed to the clients. The clients using a native utility program generates a proxy class from a WSDL document. This proxy class then can be used by client application for invoking the functionality / methods of the web service without worrying about the existence of SOAP protocol.

Steps for Creating WebService:

File–> ASP.NET Web Service and rename Service.asmx to emoService.asmxNew Web Site

In DemoService.asmx:

  • A webservice class auto generated by studio has the feature [WebService] and is also inherited from System.Web.Services.WebService class. Both are needs. i.e. any public class linked via file with extension ASMX and deployed in the webapplication can treated as a WebService.
  • All the methods of a webservice class to be used by the clients on internet must be marked as “WebMethod” ( attribute)

Step 2 [WebMethod]
public int Add(int a, int b)
{
return a + b;
}

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Implementation Of .NET Core CSV Writer

This blog topic discuss how to implement Generic CSV Writer which might take an input from any list and return a CSV string or write to a certain file, if specified. Although, this is a generic C# implementation and could be used in any .NET Framework supporting generics. Yet, we shall discuss this with .NET Core. We shall use .NET Core Console Application here.

How to add new Class in DotNetCore.ConsoleApplication

We shall add a new class CsvWriter in DotNetCore.ConsoleApplication.

  • Open existing solution in VS 2015.
  • Now, add a new class CsvWriter.cs.
    • Open Add New Item Screen through DotNetCore.ConsoleApplication Context Menu of Common folder >> Add >> Class >> Installed >> .NET Core >> Class.
    • Name it CsvWriter.cs.
    • Click OK button.
  • Add CsvWriter implementation.
    • Write<T> (IList<T> list, bool includeHeader = true).
    • Creates and returns the generated CSV.
    • Write<T> (IList<T> list, string fileName, bool includeHeader = true)
      Creates and returns the generated CSV and saves the generated CSV to the specified path.
    • CreateCsvHeaderLine
    • Creates CSV header line, if includeHeader is set true.
    • CreateCsvLine<T>(T item, PropertyInfo[] properties).
      Creates a CSV line for the given type of the object.
    • CreateCsvLine(IList<string> list).
      Creates a CSV line for the given list of the string by joining them, demarcated by comma.
    • CreateCsvItem
      Adds the provided value item to the processed list, used to create CSV line.
    • CreateCsvStringListItem
      Adds the provided string list as a single item to the processed list, which is used to create CSV line.
    • CreateCsvStringArrayItem
      Adds the provided string array as a single item to the processed list, which is used to create CSV line.
    • CreateCsvStringItem
      Adds the provided string value item to the processed list, used to create CSV line.
    • ProcessStringEscapeSequence
      Processes the provided data to handle double quotes and comma value. If we do not apply escape sequences, they can corrupt the data.
    • WriteFile
      Writes the generated CSV data to the file.

Add Test Model Class in DotNetCore.ConsoleApplication

Next we shall add a new class TestVM in DotNetCore.ConsoleApplication.

  • Open the existing Solution in VS 2015.
  • Then add a new class TestVM.cs.
    • Open Add New Item Screen through DotNetCore.ConsoleApplication Context Menu of Common folder >> Add >> Class >> Installed >> .NET Core >> Class.
    • Name it TestVM.cs.
    • Click OK button.
  • Add TestVM implementation.
  • Update Program.cs to initialize List<TestVM> with the dummy data and call CsvWriter.

 

publicclassTestVM{

[Display(Name=”TestId”)]

publicintTestId{

get;

set;

}

[Display(Name=”Name”)]

publicstringTestName{

get;

set;

}

}

publicclassProgram{

publicstaticvoidMain(string[]args){

Console.WriteLine(“Welcometo.NETCoreConsoleApplication”);

List<TestVM>tests=newList<TestVM>{

newTestVM{

TestId=1,TestName=”BillGates”

},

newTestVM{

TestId=2,TestName=”WarrenBuffett”

},newTestVM{

TestId=3,TestName=”AmancioOrtega”

},newTestVM{

TestId=4,TestName=”CarlosSlimHelu”

}

};

stringstringfileName=string.Format(“{0}\\test.csv”,System.AppContext.BaseDirectory);

CsvWritercsvWriter=newCsvWriter();

csvWriter.Write(tests,fileName,true);

Console.WriteLine(“{0}hasbeencreated.”,fileName);

Console.ReadKey();

}

}

Run Application in Debug Mode

  • Press F5 or Debug Menu >> Initiate Debugging or Start Console Application button on the toolbar to start the Application in the debugging mode. It will begin an Application Console in the debug mode.
  • It will yield test.csv at given path. Hence at C:\ASP.NET Core\CSV Writer\DotNetCore\ConsoleApplication.NetCore\bin\Debug\netcoreapp1.0.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net. Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

POCO Classes in Entity FrameWork

A Plain Old CLR Objects or POCO is a class, which do not depend on any framework-specific base class. It is like any other normal .NET class. Owing to this, they are called Plain Old CLR Objects.

These POCO entities (also known popularly known as persistence-ignorant objects) support most of the same LINQ queries as Entity Object derived entities. These classes (POCO classes) puts only the domain business logic of the Application.

Some developers use Data Transfer Objects (DTOs) with the classes to pass the data between the layers because POCOs are also used to pass the data between the layers, but they become heavy. Hence they use DTOs, which are also the classes.

The main difference between DTO and POCO is that DTOs doesn’t contain any methods. They only has public members. Hence, sending the data, using a DTO is easy because they are lightweight objects.

If you want to create POCO classes instead of the entity classes or as a default entity object, then you can create POCO entity classes.

To create POCO classes, you will first need to disable auto create classes or auto create code generation, which produces Context classes’ entity code in Model1.designer.cs. To disable this generation of code, right-click on model1.edmx (ADO.NET data modal) and click property Now, you will see the value of “Custom Tool” as EntityModelCodeGenerator and you need to remove this value.


After removing the value Custom tool, you will see that in modal1.edmx, there is no Model1.designer class. Now, we must create properties (Context and Entities), so for this, we need to create POCOs classes.

Now, double-click on Modal1.edmx and right-click on the designer surface and click on the code generation Items. A screen will pop open from where you have to select ADO.NET POCO Entity Generator and click Add.


After clicking the Add button, you will see 2 classes, where one is modal1.context.tt and another is modal1.tt.

Model1.Context.tt is a context file and Model1.tt is an entity file. You can modify this file, if you want to generate your template. The Model1.Context.cs file has a context class and .cs files under Model1.tt are the entity classes.

Entity classes do have all the properties as Virtual. In other words, these entities fulfil the needs of POCO Proxy entities. These entities can be used as POCO entities or POCO Proxy entities. By default, it will behave as POCO Proxy entities, but you can disable proxy creation by setting a property “ObjectContext.ContextOptions.ProxyCreationEnabled = false”.

To be noted:

  • If you want to write a unit test for the context, then replace ObjectSet<> to IObjectSet<>.
  • If you are not able to see ADO.NET POCO Entity Generator, then you must get installed NuGet Package Library.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Developers Uses Case For .NET API Browser

ASP.NET Web API is a framework that makes it easy to create HTTP services that reaches a wide range of clients, that include browsers and mobile devices. ASP.NET Web API is an ideal platform for building restful applications on the .NET Framework

At times, developers needs to know, if a technology or a feature is supported by a specific .NET version. For instance, how to see if that .NET Core has Linux support or not. Well, there are chances that you can Google that but won’t it be better, if this need is supported by a “one stop search” and the results were genuine.

Accessing .NET API Browser

.NET API Browser can be accessed by https://docs.microsoft.com/en-us/dotnet/api/

.NET API Browser permits you to search a wide range of features across the following.

  • .NET Framework
  • .NET Standard
  • .NET Core
  • Xamarin
  • Azure

Let’s search in .NET Framework

An open API Browser and filter it to .NET Framework and choose a version from the middle dropdown.
.NET Framework allows searching only for .NET 4.5 – 4.7 I.e. you can’t search features prior to .NET 4.5 in .NET API Browser.

With the release of .NET 4.6, a new overload was introduced for System.GC.Collect().

When the Framework Version was switched to 4.6; then the new overload can be observed.

Let’s Search in .NET Standard

.NET Standard is a specification of .NET API, which is found across all .NET Runtimes. .NET Standards gives and supports uniformity within the entire .NET ecosystem. You can refer to the list of .NET Standard libraries at https://www.nuget.org/packages/NETStandard.Library

As the name says by it-self; this becomes evident that the entire core APIs like System, System.Collections, System.Diagnostics and System.IO etc. are the natural candidates for .NET Standard, as shown below.

Let’s search in .NET Core

.NET Core is a brand new and well accepted framework in Microsoft and non-Microsoft world.

A well-known fact about .NET Core is that .NET Core has a support for Linux.

Summary

.NET API Browser is a great attribute and can become very handy to identify supported features by the various platforms. You might want to use .NET API Browser to search and learn about other APIs related to Xamarin and Azure as well. Remember, it’s a one stop .NET API Browser.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Enable Response Compression in ASP.NET Core in 5 Easy Steps

ASP.NET Core

It is a new open-source and cross-platform framework for creating modern cloud based internet connected applications, such as web apps, IoT apps and mobile backends. ASP.NET Core apps run on .NET Core or on the full .NET Framework. It was created to provide an optimized development framework for apps that are deployed to the cloud or run on-premises

The first preview release of ASP.NET was done about 15 years ago as part of the .NET Framework. Since then millions of developers have used it to build and run great web apps, and over the years we have added and evolved many capabilities to it.

ASP.NET Core has a number of architectural changes that yields in a much leaner and modular framework. ASP.NET Core is no longer based on System.Web.dll. It is based on a set of granular and well factored NuGet packages.

As an ASP.NET developer you must be aware that IIS comes with its own compression module that can well compress the response content. This can dramatically lower the network bytes giving good performance benefits. However, what if you aren’t using IIS at all? ASP.NET Core gives you a middleware which can compress the response content for you. In this article you will learn to configure the ASP.NET Core response compression middleware in your web application.

1. Create a new ASP.NET Core web application

Develop by creating a new ASP.NET Core web application. You can use the Web Application template so that the basic start-up configuration is already made for you.

2. Add ASP.NET Core Response Compression NuGet package

Once the web application is developed you need to add a NuGet package that performs the compression for you. To do that, press right click on the References folder and pick Manage NuGet packages shortcut menu option. This will open the NuGet packages tab. Search for Response Compression and you will see this entry :

The Microsoft.AspNetCore.ResponseCompression package is what you need to make the response compression. Press the Install button and install the package.

3. Add the Response Compression service to the application

Next, open the Startup.cs file and modify the ConfigureServices() method as shown below :

public void ConfigureServices(IServiceCollection services)

{

services.Configure<GzipCompressionProviderOptions>

(options => options.Level = CompressionLevel.Optimal);

services.AddResponseCompression(options =>

{

options.Providers.Add<GzipCompressionProvider>();

});

services.AddMvc();

}

Here, you first do the GzipCompressionProviderOptions such that highest level of compression is used. Then you ad the response compression service using the AddResponseCompression() method. While calling the AddResponseCompression() method you specify Gzip compression in the options.

4. Add the Response Compression middleware to the request pipeline

Then go to the Configure() method and add the response compression middleware to the request pipeline.

public void Configure(IApplicationBuilder app,

IHostingEnvironment env, ILoggerFactory loggerFactory)

{

app.UseResponseCompression();

app.UseStaticFiles();

app.UseMvc(routes =>

{

routes.MapRoute(

name: “default”,

template: “{controller=Home}/{action=Index}/{id?}”);

});

}

Note that the UseResponseCompression() method that sums up the middleware is called before any of the other UseXXXXX() methods. This way this middleware gets a chance to compress the response.

5. Verify that the response is compressed

This completes the entire process. Run the application and observe the response in F12 tools You will find that the Content-Encoding header is set to gzip as expected.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

10 Entity Framework: 7 Features That You Should Know


EF7 or Entity Framework 7 is quite powerful and has significant changes over Entity Framework 6.x. Rowan Miller has announced a new release of Entity Framework 7 beta 8 on his blog. A number of features are yet missing in the current release.


EF 7 will give you friendly developer experience to previous versions of EF, the user could still work with DbContext, DbSet, etc. EF7 is of lightweight compared toprevious versions and is built from the ground up to work great in the cloud on devices as well as in traditional .NET scenarios.

This article gives a brief introduction to top 10 important features of EF 7:

Lightweight and extensible

You can use that extensions which are useful to your project. The pattern and concept will remain same to use EF. You can use DbContext/DbSet same way as you are doing currently. The advantage of extensible is you can replace and extend it.

New Platforms

EF is most popular ORM that currently includes applications built with technologies such as WPF, WinForms and ASP.NET. After seeing at future Microsoft decided to support remaining platforms where .NET development is common. This includes Windows Store, Windows Phone and the Cloud Optimized .NET.

New Data Stores

EF was tied with relational data stores. The EF provides great support to non relational data stores also.


Optimized Query generation

Based on people’s higher request on EF uservoice “
Improved SQL Generation“, Diego Vega responded positively and start working on this feature. In their next or might be final release they will include this feature. EF7 will produce much simpler SQL queries than EF6 for most of the scenarios.

Code first only

Finally MS Team retired EDMX in EF 7. If you still love edmx, you would like to read What about EDMX when EF7 arrives?


Batch Update

No longer need to use EF batch update utilities to perform batch operations because EF7 has inbuilt support for that. EF 7 no longer send individual command for every insert/update/delete statement.


Unique Constraints

EF 7 permits you to identify additional unique keys within your entities in addition to the primary key. You can next use these alternate keys as the target of foreign key relationships.


How it appears?

The index and constraint, introduced for an alternate key will be
namedAK_<type name>_<property name>. For composite alternate keys <property name> becomes an underscore separated list of property names.


How to use it

You need to use fluent API because a unique constraint cannot be configured using Data annotations.

classMyContext:DbContext

{

publicDbSet<Employee>Employees

{

get;

set;

}

protectedoverridevoidOnModelCreating(ModelBuildermodelBuilder)

{

modelBuilder.Entity<Employee>()

.HasAlternateKey(e=>e.EmployeeCode)

.HasName(“AlteranteKey_EmployeeCode”);

}

}

classEmployee

{

[Key]

publicintEmployeeId

{

get;

set;

}

publicstringName

{

get;

set;

}

publicstringEmployeeCode

{

get;

set;

}

publicDateTimeDateOfBirth

{

get;

set;

}

}

In-Memory provider


To test Entity Framework DB operations, you must mock out DbContext which is not an easy task. In-memory store will behave like a real data store. You can do the same operations as In-memory providers.

Logging

Capture all interaction with the database using EF7 inbuilt Logging feature. EF7 logging feature is powered by Microsoft.Framework.Logging and Microsoft implemented ILogingFactory that might support all .NET platforms.

Shadow Properties

Shadow properties do not exist in entity class, but considered as part of it. The value and state of these properties is maintained purely in the Change Tracker. They can participate in all database operations, but must not be exposed via entity class to the rest of the application. At present, you can declare shadow properties using fluent API only.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

How To Access Identity And HttpContext Info Using Dependency Injection In .NET Core

If you use .NET Core, then you know that Dependency Injection is quite important in this ecosystem. Grateful to them, the development team made it significantly easy to use.

One common scenario that you must have seen arise from its time of release, is:

“How could I inject Identity or User information via D.I. in .NET Core?”

This could be a common use case for systems that need identity information for server-level transactions (e.g. when you create a new entity, you might want to know who performed this action or likewise if you wanted to audit who approached a particular record in your system).

This blog will cover implementing such services that you can use or extend within your applications; which you have probably tried already, but didn’t work.

The most common place that you’ll see developers go to reach out the current user might be as simple as the User.Identity property that is exposed from the HttpContext. However, if you are reading this blog, sure that you have attempted something like this:

//Exampleofacontroller

publicFooController(FooContextcontext)

{

//Injectingyourdatacontext(acommon-usecase)

_context=context;

//Attemptingtoresolvethecurrentuser

_user=HttpContext.User?.Identity?.Name;

}

You’ll find that the actual HttpContext doesn’t exist within the constructor for the Controller.

So, to actually access anything within the HttpContext, you will need to inject it. To mention, that isn’t difficult.

Build a Service to Inject the HttpContext

For D.I. to work, you will need to vreate a service that can inject the HttpContext that we need in the pipeline so that we can access the properties of it.

You can do this by designing a simple class that already injects that information, behind the scenes through a IHttpContextAccessor object, as given below.

publicclassUserResolverService

{

privatereadonlyIHttpContextAccessor_context;

publicUserResolverService(IHttpContextAccessorcontext)

{

_context=context;

}

publicstringGetUser()

{

returnawait_context.HttpContext.User?.Identity?.Name;

}

}

What this will do is inject the HttpContext object from a request into this UserResolverService, which will store the context and expose a method called GetUser() that will return the current name of the user.

This could be used within a repository if you required to store the username that was accessing a particular record.

publicclassFooRepository:IFooRepository

{

privateFooContext_context;

privatestring_currentUser;

publicFooRepository(FooContextcontext,UserResolverServiceuserService)

{

_context=context;

_currentUser=userService.GetUser();

}

publicvoidDoWork()

{

varwidget=newWidget(){

Id=42,

Title=”TheAnswer”,

Author=”Deepthought”,

CreatedBy=_currentUser

};

_context.Widgets.Add(widget);

_context.SaveChanges();

}

} And, that it is basically.


How To Extend the Service

If you have some additional properties that existed on the ApplicationUserobject, then you might need to extend this service to pass along the entire object itself.

Doing this would require a very minor change, as you would simply need to inject your UserManager object into this new service.

publicclassUserResolverService

{

privatereadonlyIHttpContextAccessor_context;

privatereadonlyUserManager<ApplicationUser>_userManager;

publicUserResolverService(IHttpContextAccessorcontext,UserManager<ApplicationUser>userManager)

{

_context=context;

_userManager=userManager;

}

publicasyncTask<ApplicationUser>GetUser()

{

returnawait_userManager.FindByEmailAsync(_context.HttpContext.User?.Identity?.Name);

}

}

This is definitely just a beginning point for developing a service that upgrads the existing context, but hopefully it will increaseyour interest in creating your own services to pass around.

Since .NET Core is a cross-platform tool, you should think about looking into both of them.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimisation and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Command Line Interface Tools In .NET Core

CLI or Command Line Interface is a new cross-platform tool for developing .NET Core applications. It is also a basic tool because it is a primary layer on which other tools like IDE build the application and run it.

CLI tools are available in DEB packages for Ubuntu and MSI bundles for Windows. This installer will install the tool and setup the environment required to run CLI tool. There are availabilities of multiple versions of CLI tools installed on a single machine.

All CLI commands are run from command prompt. The CLI command mainly has three parts -

  1. The driver
  2. Command
  3. Command Argument

Driver

The verb “.net” is used as driver. The following two are the main responsibilities.

  • Execute IL (Intermediate Language) code
  • Execute the Command

The driver finds the version of the tool that we want to use. If the specified version of CLI tool is unavailable, driver uses the latest version of the tools. The driver starts to execute the command once the tool version is found.

Command

It is the action which needs to be performed by the driver.


Arguments

They are passed with the command. The arguments are helpers of the command and they provide user input to the command

Built-in supported Commands

Following commands are installed during installation.

  • new
  • restore
  • run
  • build
  • test
  • publish
  • pack

CLI tool gives the way to import more commands on the basis of need in project. You can add our own command as well.

“.net” commands

The .net is a generic driver for the CLI tool and is used to run the command-line commands. The .net is itself used as command; and with this command, it has the following options.
 

 Options  Description
 –version   Display current version of the CLI tool
 -v or –verbose  Does verbose output
 –info  Display details about the CLI tool like name and version of the OS, SHA-1 information etc.
 –help or-h  Display short help and list down current supported command


E.g.

Run the following commands in command window

>dotnet –version
>dotnet –info
>dotnet –v
>dotnet –help

“.net new” command

It is used for developing new .NET core project. It provides nicer way to initialize a valid .NET Core project and sample source code. When we run this command, two main files will be created – Program.cs and Project.json. We can edit these files as per our need.

Syntax

.net new [arguments/options]
 

 Options  Description
 -l Or –lang  Develop specified language project in present directory. Currently it ables to create C# and F# project
  -tor –type  Develop specified type of project in current directory. The supported values are console, web, lib and xunittest


E.g.
I have run the following commands in command window.

>dotnet new
>dotnet new -l F#
>dotnet new – t web

“.net restore” command

This is used to restore the dependencies to the project. It uses NuGet to restore dependencies which are mentioned in project.json file.

The configuration file “NuGet.config” provides the feeds where packages are located. When you installed CLI tools, by default one feed is present. You could specify more feeds by creating your own NuGet.config file in the project directory.

Syntax

.net restore [arguments/options]

 Options   Description
 -s Or –source [Source]  Specifies a source during the operation to restore. This will override all sources specified by nuget.config files.
 –packages [DIR]   Makes directory to restored packages placed in.
 –disable-parallel  Disable restoring multiple projects in parallel.
 -f Or –fallbacksource [FEED]  Specifies a fallback source which could be used in restore operation if main source can’t be restored.
 –configfile [FILE]  Specify the configuration of file NuGet.config that is used to perform restore operation.
 –verbosity [LEVEL]  Specifies which level of logging to use. Available options are Debug, Verbose, Information, Minimal, Warning and Error.


E.g.
I have run the following commands in command window.

>dotnet restore -s “D:\packages”
>dotnet restore –packages “Mypackages”

“.net build” command

It builds a project and its dependencies. It develops multiple source files from the project and its dependencies into binary and binary are in IL (Intermediate Language) and it has a DLL extension. This command needs lock file to be present in current directory, it means that we must run “.net restore” command prior to building a command.

Syntax

>.net build [arguments/options]

 Options   Description
 -o Or –output [DIR]  Build binaries are placed into specific directory.
 -b Or –build-base-path [DIR]  Temporary outputs are desugned in specified directory.
 -f Or –framework [FRAMEWORK]   Build compiles for the specific folder.
 -c Or –configuration [Debug|Release]   Defines build configuration. Default value of configuration is “Debug”.
 -r Or –runtime [RUNTIME_IDENTIFIER]  Defines target runtime to build.
 –version-suffix [VERSION_SUFFIX]  It defines what would be replaced with the version field in to the project.json file.
 –build-profile   It defines the incremental safety check which user needs to turn on automatically incremental compilation.
 –no-incremental  This will ensure the build as unsafe for incremental build. It turns off incremental compilation and forces rebuild of project dependency graph
 –no-dependencies   Only build the root project and ignore the build reference project.


E.g.
I have run the following commands in command window

>dotnet build
>dotnet build -c release
>dotnet build –no-dependencies

“.net run” command

This command is used to run our application from the source code. The main responsibilities are to compile source code, produce output program and run this program. This command depends on “.net build” command to build source code. The build command writes the output files in “bin” folder. It also develops this folder if it does not exist. The “obj” folder is used to write temporary files.

Syntax

.net run [arguments/options]

 Options   Description
 -f Or –framework [framework identifier]   Run the application under mentioned framework
 -c Or –configuration [Debug|Release]  Use the mentioned configuration when publishing application. The default value of configuration is “debug”
 -p Or –project [Path]  This command runs project specified in Path argument. It by default takes current directory if path is not specified.


E.g.
I have run the following commands in command window

>dotnet run
>dotnet run -c release
>dotnet run -p “C:\CoreAppTest”

“.net test” command

It runs unit test case under the configured test runner. Unit tests are class library type projects which have dependencies of unit test frameworks like xUnit or NUnit. The project.json file must contain the information about the test runner.

Following is sample project.json file.

 Options  Description
  - [project]  It decides the path of the project. By default it looks into current directory.
 -c Or –configuration[Debug|Release]  Use the mentioned configuration when test application. The default value of configuration is “release”
 -o Or –output [DIR]   Binaries are found in specified directory.
 -b Or –build-base-path [DIR]  Temporary outputs put in specified folder.
 -f Or –framework[FRAMEWORK]  Specify the version of the framework used for test binaries.
 -r Or –runtime [RUNTIME_IDENTIFIER]   Define the target runtime to test.
 –no-build   It does not build project prior to running test.
 –parentProcessId   It used by IDE to specify process ID.
 –port   It used by IDE to define a port number for listen for a connection


“.net publish” command

This compiles the application and publishes the application with the project dependencies (specified in project.json file) and puts it into specified folder.

 Options   Description
 - [project]  It defines the path of the project. By default it looks into current directory.
 -c Or –configuration [Debug|Release]  Use the configuration when to publish application. The default value of configuration is “debug”
 -o Or –output [DIR]  Binaries are found in to specified directory. Default path:
./bin/[configuration]/[framework]/ for portable applications
./bin/[configuration]/[framework]/[runtime] for self-contained applications.
 
-b Or –build-base-path [DIR]
 
Temporary outputs put in specified folder.
 -f Or –framework [FRAMEWORK]  Define the version of the framework used for publishing the application
 -r Or –runtime [RUNTIME_IDENTIFIER]  Define the target runtime to publish the application.
 –version-suffix [VERSION_SUFFIX]  It defines what must be replaced with the version field in to the project.json file.


E.g.
I have run the following commands in command window,

>dotnet publish
>dotnet publish -c release

“.net pack” commands

It packs your code into the NuGet package. This command builds your project and creates NuGet packages and as a result of this; you have two packages with nupkg extension. One contains the code and the other contains debug symbols.

 Options  Description
 - [project]  It can be either path of project directory or project.json file.
 -c Or –configuration [Debug|Release]  Use the configuration when developing the application. The default value of configuration is “debug”.
 -o Or –output [DIR]  Create packages in the specified directory
 –build-base-path [DIR]  Temporary outputs placed in specified folder.
 –no-build  It will skip build the application while creating pack.
 –version-suffix [VERSION_SUFFIX]   It defines what would be replaced with the version field in to the project.json file.


E.g.

Run the following commands in command window.

>dotnet pack

Summary

The .NET Core is supporting CLI. Using CLI, you can perform various tasks, like creating application, buildong application, publishing the application from command prompt. The higher-level tools like IDE also use this CLI internally, so you can get the same behaviour as with IDE in command prompt.

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr