Tag Archives: .net courses in pune

Popular Error Logging Libraries For .NET

Part I

This article is in continuation with our previous article on the same. The article discuss some effective error handling strategies that you could use in your projects.

Common Error Logging libraries for .NET

For .NET framework, the most popular logging libraries are probably log4net and NLog.

Although, there are differences between the two, the main concepts are similar.

In NLog, for instance, you will basically create a static logger instance in every class that needs to write anything to the log:

private static Logger logger = LogManager.GetLogger(“LoggerName”);

To write to the log, you will simply call a method of that class:

logger.Error(exception.ToString());

As you have noticed, you have not yet specified where you want to log the errors. Instead of hard coding this information in the application, you will put it in the NLog.config configuration file:

<?xml version=”1.0″ encoding=”utf-8″ ?><nlog xmlns=http://www.nlog-project.org/schemas/NLog.xsdxmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”>

<targets>

<target name=”logfile” xsi:type=”File” fileName=”errors.log”

layout=”${date:format=yyyyMMddHHmmss} ${message}” />

</targets>

<rules>

<logger name=”*” minlevel=”Error” writeTo=”logfile” />

</rules>

</nlog>

The above configuration says that all errors will be logged to the errors.log file and accompanied with a timestamp.

But, you can easily specify a different type of target instead of a file or even add additional targets to log the errors to multiple locations.

With the layout feature, you can define which additional metadata you want to log along with the message. Different targets have different additional attributes to further control the logging process, e.g. archiving policy for log files and naming based on current date or other properties.

Using the rules section, you can even configure logging of different errors to different targets, based on the name of the logger that was used to emit the error.

Log levels can add additional flexibility to your logging.

Instead of only logging errors, you can log other information at different levels (warning, information, trace…) and use the minlevel attribute to specify which levels of log messages to write to the log and which to ignore.

You can log less information most of the time and selectively log more when troubleshooting a specific issue.

Analyze Production Log Files

Logging information about errors is the first step.

Based on the logged information, you can detect any problems with the application and act on them, i.e. fix them to ensure that the application runs without errors in the future.

In order to do effectively, the following tips could be helpful:

  • Receive notifications when errors happen
  • Collect similar errors in groups, so that you do not need to check each one of them individually.

As always, there are ready-made solutions for these problems available so that we do not need to develop them ourselves.

A common choice in .NET ecosystem is Application Insights. It is an Azure SaaS (Software as a Service) offering, with a free tier to get us started, and a usage based pricing model.

The product is integrated into VS. There is a wizard present to add Application Insights telemetry to a running project or to a newly created one. It will install the required NuGet package, create an accompanying resource in Azure and link the project to it with configuration entries.

Logged data can be analyzed in Azure Portal or inside Visual Studio.

If you want keep all the information on-premise, there is an open source alternative available: OneTrueError.

Before you start using it, you need to install the server application on your own device.

There is no wizard available for configuring OneTrueError in your application, but the process is simple:

- Install the NuGet package for your project type, e.g. OneTrueError.Client.AspNet for ASP.NET applications.

- Initialize automatic exception logging at application startup, e.g. in ASP.NET applications, add the following code to your Application_Start method (replace the server URL, app key and shared secret with data from your server, of course):

var url = new Uri(“http://yourServer/onetrueerror/”);OneTrue.Configuration.Credentials(url, “yourAppKey”, “yourSharedSecret”);OneTrue.Configuration.CatchAspNetExceptions();

Both Application Insights and OneTrueError solve another problem with log files: large modern applications which has multiple services and are installed on multiple machines for reliability and load balancing.

Each service on each machine creates its own log and to get the full picture, data from all these logs needs to be consolidated in a single place.

By logging to a centralized server, all logs will automatically be collected there with information about its origin.

Error handling specifics for Mobile Applications

Just like Application Insights and OneTrueError provide a complete solution for server application, there are dedicated products available for mobile applications.

Basically, they are not limited to error or crash reporting but also include support for usage metrics and (beta) application distribution.

Microsoft’s associate to Application Insights for mobile and desktop applications is HockeyApp, but there are other alternatives as well, like Raygun and Crashlytics. They have similar attribute set and differentiate themselves by varying support for specific development platforms and pricing models.

Most of them require only a couple of lines of code to get started.

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 Dot Net Course and excel yourself in Dot 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 the best Dot Net Course. Among many reputed institutes, CRB Tech has craved its niche among the best dot net institutes.

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

Best Practices In Error Handling in .NET Projects

This article talks about some effective error handling strategies that you can use in your projects.

Best Practices for Exception Handling

The best way to express error conditions in .NET framework is by putting exceptions. In C#, you could handle them using the try-catch-finally statement:

try

{

// code which can throw exceptions

}

catch

{

// code executed only if exception was thrown

}

finally

{

// code executed whether an exception was thrown or not

}

Whenever an exception is put inside the try block, the execution occurs in the catch block. The finally block executes after the try block is complete successfully. It also executes while exiting the catch block, either successfully or with an exception.

In the catch block, you need information about the exception we are handling. To do it, you use the following syntax:

catch (Exception e)

{

// code can find exception details in variables

}

The type used, specifies which exceptions will be caught by the catch block.

You can add multiple catch blocks to a single try block. In this case, the exception will be caught by the first catch block with matching exception type:

catch (FileNotFoundException e)

{

// code will only handle FileNotFoundException

}

catch (Exception e)

{

// code will handle all the other exceptions

}

This helps to handle different types of exceptions in multi ways. You can recover from expected exceptions in a very specific way, for instance:

  • If a user selects a non-existing or invalid file, he will be allowed to select a different file or cancel the action.
  • If a network operation timed out, he can retry it or invite the user to check his network connectivity.

For remaining unexpected exceptions, e.g. a NullReferenceExceptions caused by a bug in the code, you can show the user a generic error message, giving him an option to report the error, or log the error without any user intervention.

It is at times very important to avoid swallowing exceptions silently:

catch (Exception e)

{ }

Doing this is bad for either the user or the developer.

The user might assume that an action succeeded, where it silently failed or did not complete; whereas the developer will not get notified about the exception, and he would not know that he might need to fix something in the application.

Hiding errors silently are only appropriate in very rare scenarios, for instance, to catch exceptions put when attempting to log an error in the handler, for unexpected exceptions.

Centralized Exception Handling

When writing exception-handling code, it is essential to do it in the right place. You might be tempted to do it as close to the origin of the exception as possible, e.g. at the level of each individual function:

void MyFunction()

{

try

{

// actual function body

}

catch

{

// exception handling code

}

}

This is appropriate for exceptions which you can handle in programs, without any user interaction. This is in cases when your application can fully recover from the exception and still successfully complete the requested operation, and therefore the user does not require knowledge that the exception occurred at all.

But, if the requested action failed because of the exception, the user must know about it.

In a desktop application, it would be possible to show an error dialog from the same method where the exception occurred, but in the worst case, this could result in a cascade of error dialogs, because the functions might also fail

void UpdatePersonEntity(PersonModel model)

{

var person = GetPersonEntity(model.Id);

ApplyChanges(person, model);

Save(person);

}

Let’s assume an unrecoverable exception is thrown inside GetPersonEntity (e.g., there is no PersonEntity with the given Id):

  • GetPersonEntity will catch the exception and show an error dialog to the user.
  • Due to the previous failure, ApplyChanges will fail to update the PersonEntity with the value of null, as returned by the first function. According to the policy of handling the exception where it happens, it will show a second error dialog to the user.
  • Similarly, Save will also fail because of PersonEntity having null value, and will show a third error dialog in a row.

To avoid the above situations, you must handle unrecoverable exceptions and show error dialogs in functions invoked by a user action.

In a desktop application, these will typically be event handlers:

private void SaveButton_Click(object sender, RoutedEventArgs e)

{

try

{

UpdatePersonEntity(model);

}

catch

{

// show error dialog

}

}

In contrast, UpdatePersonEntity and any other functions must not catch any exceptions that they cannot handle properly.

This works as well in a web application.

In WPF, a global exception handler could be hooked to the application’s DispatcherUnhandledException event:

public partial class App : Application

{

public App()

{

DispatcherUnhandledException += App_DispatcherUnhandledException;

}

 

private void App_DispatcherUnhandledException(object sender,

DispatcherUnhandledExceptionEventArgs e)

{

var exception = e.Exception; // get exception

// … show the error to the user

e.Handled = true;// prevent the application from crashing

Shutdown();// quit the application in a controlled way

}

}

In ASP.NET, the global exception handler is convention based – a method named Application_Error in global.asax:

private void Application_Error(object sender, EventArgs e)

{

var exception = Server.GetLastError(); // get exception

Response.Redirect(“error”);// show error page to user

}

What must a global exception handler do?

From the user standpoint, it must display a friendly error dialog or error page with instructions on how to proceed, for a developer, it is important to log the exception details for further analysis:

File.AppendAllText(logPath, exception.ToString());

Calling ToString() on an exception will return all its details, including the description and call stack in a text format. This is the minimum amount of information you want to log.

To make later analysis easier, you could include additional information, like current time and any other useful information.

Use Of Exception Logging Libraries

Though writing errors to log files might appear simple, there are several challenges to address:

  • Where must files be located?
  • How to organize the log files?
  • How large may the log files grow?
  • Will the application write errors from multiple threads?

There are also alternatives to log files that might be more suitable in certain scenarios:

  • Windows Event Log was created for logging errors and other information from applications. It solves all the above challenges but needs dedicated tooling to access the log entries.
  • If your application already uses a database, it could also write error logs to the database. If the error is caused by the database that’s not accessible, the application will not be able to log that error to the database though.

You do not want to decide on the above choices before hand, but rather configure the behavior during the process of installation.

We conclude for now. We shall discuss some more details about the same, in our next article.

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 Dot Net Course and excel yourself in Dot 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 the best Dot Net Course. Among many reputed institutes, CRB Tech has carved its niche among the best dot net institutes.

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

What’s Brewing for .NET Developers

What is New and Exciting in Microsoft’s Open Dev Ecosystem

.NET Core 1.1

.NET Core 1.1 is the first and new minor version of .NET Core – a cross-platform, opens source, and modular .NET platform for creating modern .NET applications. Unlike the LTS version 1.0, .NET Core 1.1 is categorized as a “Current” release. While LTS releases have a 3-year support period from the original release or 1 year from the next LTS release, the “Current” releases are only eligible for support as long as their parent LTS release or 3 months after the next “Current” release, whichever comes first. The two versions could be safely installed side-by-side, such that individual applications on the same machine can make use of either.

The focus of this release was performance. The big news was that ASP.NET Core is now included in the TechEmpower web framework benchmarks, and is the most rapid mainstream full stack framework in the Plaintext category.

Various new features were added to ASP.NET Core 1.1:

  • MVC filters allow you apply middleware only to specific controllers or actions.
  • Two new middleware are included: URL rewriting and response caching.
  • Web Listener Server for Windows is available as an alternative to Kestrel. With it, you could take benefit of Windows specific features, such as Windows authentication, HTTP/2 over TLS, and others.
  • Compiling views during the publish process is supported.

Entity Framework Core 1. has built-in support for connection flexibility and SQL Server memory-optimized tables. Owing to improved LINQ translation, the database engines can successfully execute more queries than before. New APIs were added for explicit loading, mapping to fields and a few other features.

MSBuild tooling for .NET Core became available in preview. This means that standard .csproj project files can be used instead of project.json. To proper align the two formats, MSBuild now supports wildcard-based inclusion of files for folder based projects, and direct NuGet package references. A wizard for migrating project.json projects to .csproj is included as well.

Visual Studio 2017 Release Candidate

Visual Studio “15” now has its official name: Visual Studio 2017. You can now download Visual Studio 2017 Release Candidate and even use it in production with the exception of features marked as in preview, and are not yet supported.

The new version of Visual Studio comes with many productivity changes:

  • better filtering and default suggestions,
  • easy navigation with redesigned Find All References and Go To functionalities,
  • new Exception Helper dialog with support for filtering exceptions
  • quick reattaching and filtering by process name in the Attach to Process dialog,
  • continuous running of tests and coverage information for individual code lines with Live Unit Testing
  • additional code refactoring,
  • Configurable code style and many more.

Better performance is also a priority: Visual Studio 2017 starts faster, has shorter load times, and a faster, more componentized installer. To further speed-up initial loading of large solutions; lightweight solution loading can be enabled for them, which defers the full loading of projects to a later time when they are first needed.

Extensions can also largely affect the overall responsiveness of Visual Studio. The new performance-supervising feature will now warn the user about extensions which slow down Visual Studio. Other improvements to extensions include:

  • batched installs and updates,
  • built-in roaming extension manager, and
  • support for extensions to find out missing dependencies and trigger their installation in Visual Studio.

A few other new attributes in Visual Studio 2017 that are also worth mentioning:

  • New versions of C# and Visual Basic provide many new language features
  • A new Service Capabilities page is now the centralized location for adding cloud service dependencies to a project.
  • You can record tests for mobile applications using the new mobile test recorder and upload them directly to Xamarin Test Cloud.
  • A preview version of Visual Studio Tools for Unity 3 is now included in the installer. Among other improvements, it adds full syntax colouring and IntelliSense support for Unity event functions.

Visual Studio for Mac

The VS product family got a new member: Visual Studio for Mac. The preview is already available so get it download. The application is an evolved version of Xamarin Studio, more closely aligned to the Visual Studio experience on Windows. It supports development of Xamarin based mobile applications, and their cloud backend in .NET Core, using either C# or F#. It features the same Roslyn powered compiler, IntelliSense code completion and refactoring experience as Visual Studio. The same MSBuild project format allows for seamless sharing of projects between Visual Studio on Windows and Mac.

Visual Studio Tools for Samsung’s Tizen

Tizen is Samsung’s Linux-based open source operating system, used in over 50 million of their devices: smart TVs, wearables, smartphones and IoT devices. At the event, Samsung announced its intention on collaborating with Microsoft to bring .NET Core to ARM devices, and add Tizen support to Xamarin.Forms.

The first preview of Visual Studio Tools for Tizen is already available. It provides an alternative to existing C and HTML 5 based programming models for Tizen. Currently only mobile application development is supported, but other types of devices will follow in the future. All the development is done in C# with.NET Core, Xamarin.Forms for the user interface, and wrappers for many native APIs to access device specific functionalities – everything with full IntelliSense support. Debugging takes advantage of device emulators, which are included in the download.

The official release is planned for 2017, when the .NET Core runtime will also ship to devices.

Summary:

- Microsoft joins the Linux Foundation as Platinum member

- Google joins the .NET Foundation

- Samsung releases VS Tools for Tizen

- Microsoft announces VS 2017

- Visual Studio 2017 will have cross-platform support

- Microsoft announces Visual Studio for Mac

- Microsoft announces Visual Studio Mobile Center

- Microsoft has the most contributors on GitHub

- SQL Server for Linux is now publicly available. SQL Server 2016 Service Pack 1 available.

- Azure Data Lake Analytics and Store

- Azure Functions and N-Series available now. First Cloud Bot-as-a-Service announced.

Microsoft continues to provide a great set of benefits and tools for any developer, any app, and any platform. Since the first Connect(); event in 2014, Microsoft has been using it to announce many important development related releases. From VS 2017 Release Candidate with “go-live license” and VS for Mac Preview to new Xamarin tooling and new .NET Core version, there was something of interest for any developer already working with Microsoft tools or technologies. Microsoft also expands its focus from Windows to other platforms, these announcements have become increasingly interesting to developers who are not in Microsoft’s ecosystem yet.

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 swell-structuredam 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

Software Development Life Cycle Or SDLC

Software Development Life Cycle Or SDLC : Dot Net

SDLC is a process that must be followed for a software project, within an IT organization. It has a detailed plan that describes how to develop, maintain, replace and enhance the specific software. The life cycle defines a methodology for improving the quality of software and the overall development process.

A typical Software Development life cyclant and fundamental stage in SDLC.

It is done by senior members of the team with inputs from the customer, the sales department, and market analysis and domain experts in the sector. This information is next used to plan the basic project approach and to conduct product feasibility study in the economical, operational, and technical areas.

Stage 1: Stage 1: Planning and Requirement Analysis

Planning for the quality assurance needs and identification of the risks associated with the project is also done in the planning stage. The outcome of the technical feasibility study is to explain the various technical approaches that could be followed to implement the project successfully with minimum risks.

Stage 2: Explaining Requirements

Once the requirement analysis is finished, the next step is to clearly define and document the product requirements and get them approved by the customer. This is done through SRS. Software Requirement Specification document consists of all the product requirements to be developed and designed during the project life cycle.

Stage 3: Designing the product architecture

SRS is the reference for product architects to give the best architecture for the product to be designed. Based on the requirements specified in SRS, usually more, than one design approach for the product architecture is proposed and documented in a DDS – Design Document Specification.

This DDS is reviewed by the important stakeholders and based on several parameters like risk assessment, product hugeness, design modularity, budget and time constraints, the best design approach is selected for the product.

A design approach well defines all the architectural modules of the product along with its communication and data flow representation with the external modules.

Stage 4: Building the Product

In this stage the actual development begins and the product is developed. The programming code is generated as per DDS. If the design is performed in a detailed and organized manner, code generation couild be accomplished without much hassle.

Developers have to follow the coding guidelines given by their organization and programming tools like compilers, interpreters, debuggers etc are used to develop the code.

Different HLL like C, C++, Pascal, Java, and PHP are used for coding. The programming language is chosen based on the type of software being developed.

Stage 5: Test the Product

This stage is the subset of all the stages as in the modern SDLC models, the testing activities are mostly done in all the stages of SDLC. However, this stage refers to the testing only stage where defects are tracked, reported, fixed and retested, until the product gets the quality standard as defined in the SRS.

Stage 6: Deployment in the Market and Maintenance

Once the product is tested and ready to be deployed it is released in the market. Sometime product deployment happens in stages. The product might first be released in a limited segment and tested in the real business environment.

Then based on the feedback, the product might be released as it is or with suggested enhancements in the targeting market segment. After the product is released in the market, its maintenance is done for the existing customer base.

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 dot 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. and be a part of the best dot net institute in Pune. We offer best dot net course which is scientifically programmed and keep updating with time.

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

Important Interview questions and Answers For ASP.Net MVC

In this article, we shall discuss top ASP.Net MVC Interview questions and answers for fresher and experienced dot net developers. Among many questions, the most important or the ones often asked are discussed here.

1) Define MVC?

MVC is a pattern that is used to split the application’s implementation logic into 3 components: models, views, and controllers.

2) How do you explain Model, Controller and View in MVC?

  • Model – It’s a business entity and is used to represent the application data.
  • Controller – Request sent by a user scatters through the controller and its responsibility is to redirect to the specific view using View() method.
  • View – It’s the presentation layer of MVC.

3) Explain the new features in version 4 of MVC (MVC4)?

Following are the attributes added –

  • Mobile templates
  • Added ASP.NET Web API template to create REST based services.
  • Asynchronous controller task support.
  • To bundle the Java scripts.
  • Segregating the configurations for MVC routing, Web API, Bundle etc.

4) How do you explain the page life cycle of MVC?

Here we mention the processed flow of the sequence -

  • App initialization
  • Routing
  • Instantiate and execute controller
  • Locate and invoke controller action
  • Instantiate and render view.

5) Mention the advantages of MVC over ASP.NET?

  • It offers a clean separation of concerns among UI, model and Business Logic.
  • Easy for UNIT Test.
  • Improve reusability of model and views.
  • Improve structuring the code.

6) What is Separation of Concerns in ASP.NET MVC?

It’s is the method of breaking the program into various distinct attributes which overlaps in functionality as little as possible. MVC pattern concerns on separating the content from presentation and data-processing from content.

8) What is the meaning of Unobtrusive JavaScript?

This is a general term for conveying a general philosophy, similar to the term REST (Representational State Transfer).

Eg: Instead of using events like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by their ID or class based on the HTML5 data- attributes.

9) What is the uage of ViewModel in MVC?

ViewModel is a plain class with properties, that is used to bind it to strongly typed view. ViewModel can have the validation rules defined for its properties using data annotations.

10) What do you mean by Routing in MVC?

Routing is a pattern matching mechanism of incoming requests to the URL patterns which are registered in route table. Class – “UrlRoutingModule” is used for the same process.

11) What are Actions in MVC?

Actions are the process in Controller class which is for returning the view or json data. Action will mainly have return type – “ActionResult” and it will be invoked from method – “InvokeAction()” called by the controller.

12) What is Attribute Routing in MVC?

ASP.NET Web API supports this type of routing. This is introduced in MVC5. In this type of routing, features are used to define the routes. This type of routing gives more control over classic URI Routing. Attribute Routing can be defined at controller level or at Action level as mentioned below–

[Route(“{action = TestCategoryList}”)] – Controller Level

[Route(“customers/{TestCategoryId:int:min(10)}”)] – Action Level

13) How do you enable Attribute Routing?

Simply add the method – “MapMvcAttributeRoutes()” to enable attribute routing as given below:

public static void RegistearRoutes(RouteCollection routes)

{

routes.IgnoareRoute(“{resource}.axd/{*pathInfo}”);

//enabling attribute routing

routes.MapMvcAttributeRoutes();

//convention-based routing

routes.MapRoute

(

name: “Default”,

url: “{controller}/{action}/{id}”,

defaults: new { controller = “Customer”, action = “GetCustomerList”, id = UrlParameter.Optional }

);

}

14) Explain JSON Binding?

JavaScript Object Notation (JSON) binding support started from MVC3 onwards via the new JsonValueProviderFactory, which allows the action methods to accept and model-bind data in JSON format. This is useful in Ajax scenarios like client templates and data binding that need to post data back to the server.

15) Explain Dependency Resolution?

Dependency Resolver again has been introduced in MVC3 and it is greatly simplified the use of dependency injection in your applications. This makes easier and necessary for decoupling the application components and making them easier to test and more configurable.

16) What is Bundle.Config in MVC4?

“BundleConfig.cs” in MVC4 is taken in use to register the bundles by the bundling and minification system. Many bundles are added by default including jQuery libraries like – jquery.validate, Modernizr, and default CSS references.

17) How route table is created in ASP.NET MVC?

Method – “RegisterRoutes()” is used to register the routes which will be added in “Application_Start()” method of global.asax file, which gets fired when the application is loaded or began.

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

Interview Questions And Answers For .Net Framework

Define .NET Framework.

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

  • 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 helps a developer to create shareable components to be used in distributed computing architecture. NET Framework supports the object-oriented programming model for multiple languages, such as Visual Basic, Visual C#, and Visual C++.

.NET Framework supports several programming languages in a manner that helps language interoperability. This says that each language could use the code written in some other language.

Name the main components of .NET Framework?

.NET Framework offers enormous advantages to software developers in comparison to the advantages provided by other platforms. Microsoft has united various modern as well as existing technologies of software development in .NET Framework. These technologies are used by developers to develop highly efficient applications for modern as well as future business needs. 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
  • To do profiling
  • Side-by-Side Execution

Name the new attributes added in .NET Framework 4.0.

The following are the new attributes 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

Define an IL?

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

Define Manifest.

Assembly metadata is stored in Manifest. Manifest has all the metadata required to do the following things

  • The version of the assembly.
  • Security identity.
  • The scope of the assembly.
  • Resolve references to resources and classes.

Code contracts will 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 help you to improve testing by enabling run-time checking, static contract verification, and documentation generation.

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 dot 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. and be a part of the best dot net institute in Pune. We offer best dot net course which is scientifically programmed and keep updating with time.

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

ASP.Net Web API Interview Questions (Part 1)

In this article, we continue with several important ASP.Net interview questions and answers.

1) Differentiate between MVC Routing and Web API Routing?

There must be at least one route defined for MVC and Web API to run MVC and Web API application respectively. In Web API pattern you can find “api/” at the beginning which makes it distinct from MVC routing. In Web API routing “action” parameter is not mandatory but it can be a part of the routine.

2) What is Exception Filters

Exception filters will be executed whenever controller methods throw an exception which remains unhandled. Exception filters will implement “IExceptionFilter” interface.

3) Explain about the new attributes added in Web API 2.0 version?

Here is the list of attributes introduced in Web API 2.0 –

  • OWIN
  • Attribute Routing
  • External Authentication
  • Web API OData

4) How can we pass multiple complex types in Web API?

Here are mentioned the methods to pass the complex types in Web API –

  • Using ArrayList
  • Newtonsoft Jarray

5) Write a code snippet for passing arraylist in Web API?

ArrayList paramList = new ArrayList();

Category c = new Category { CategoryId = 1, CategoryName = “SmartPhones”};
Product p = new Product { ProductId = 1, Name = “Iphone”, Price = 500, CategoryID = 1 };

paramList.Add(c);
paramList.Add(p);

6) Give an example of Web API Routing?

config.Routes.MapHttpRoute(
name: “MyRoute”,//route name
routeTemplate: “api/{controller}/{action}/{id}”,//as you can see “api” is at the beginning.
defaults: new { id = RouteParameter.Optional }
);

7) Give an example of MVC Routing?

routes.MapRoute(
name: “MyRoute”, //route name
url: “{controller}/{action}/{id}”, //route pattern
defaults: new
{
controller = “a4academicsController”,
action = “a4academicsAction”,
id = UrlParameter.Optional
}
);

8) How we can handle errors in Web API?

Here are the lists of classes which could be used for error handling -

  • HttpResponseException
  • Exception Filters
  • Registering Exception Filters
  • HttpError

9) Explain how we can handle the error from “HttpResponseException”?

This returns the HTTP status code what you specify in the constructor. Eg :

public TestClass MyTestAction(int id)
{
TestClass c = repository.Get(id);
if (c == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return c;
}

10) How to register Web API exception filters?

Here are the options to register Web API exception filters –

  • From Action
  • From Controller
  • Global registration

11) Write a code snippet to register exception filters from action?

Here is the code snippet for registering exception filters from action –

[NotImplExceptionFilter]
public TestCustomer GetMyTestCustomer(int custid)
{
//Your code goes here
}

12) Write a code snippet to register exception filters from controller?

[NotImplExceptionFilter]
public class TestCustomerController : Controller
{
//Your code goes here
}

13) Write a code snippet to register exception filters globally?

Here is the code snippet for registering exception filters globally –

GlobalConfiguration.Configuration.Filters.Add( new MyTestCustomerStore.NotImplExceptionFilterAttribute());

14) How to handle error using HttpError?

HttpError will be used to throw the error info in the response body. “CreateErrorResponse” method is used along with this, which is an extension method defined in “HttpRequestMessageExtensions”.

15) Write a code snippet to show how we can return 404 errors from HttpError?

Here is the code snippet for returning 404 error from HttpError

string message = string.Format(“TestCustomer id = {0} not found”, customerid);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);

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 dot 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. and be a part of the best dot net institute in Pune. We offer best dot net course which is scientifically programmed and keep updating with time.

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

Most Asked ADO.NET Interview Questions And Answers

Part III

This article lists some of the latest ADO.Net Interview Questions and Answers for fresher and 2/3 years experienced .net developers with sample code and explanations. This is in continuation of the previous post.

9) Write a sample ADO.Net Connection to SQL Server?

Using System.Data.SqlClient;

Try with

{

// Open DB connection

string Connection = “server=localhost; uid = UserName ; pwd = Password ; database = DemoDB”;

SqlConnection conn = new SqlConnection(Connection);

conn.Open();

}

catch ( Exception ex )

{

// Log Exceptions

}

finally

{

conn.Close ( ) ; // Close the connection

}


10) Explain Transactions in ADO.Net?

When one or more SQL Commands are executed and if any one statement failed to execute, we need to rollback the entire related operations that has been executed. In such a scenario, Transactions are used.

using System.Data.SqlClient;

try

{

string Connection = “server=localhost; uid = UserName ; pwd = Password ; database = DemoDB”;

SqlConnection con = new SqlConnection(Connection);

con.Open();

SqlTransaction SqlTx = con.BeginTransaction();

// Execute SQL commands

tx.Commit(); // Commit Transaction

con.Close();

11) Define ReadCommitted and ReadUncommitted in Transactions ?

All simple Transactions are ReadCommitted by default. If two persons are accessing the same table and if one person executes an insert statement, another person will be able to access the newly inserted row only after the first person commits the transaction.If a transaction is set as ReadUncommited, in the 2 person scenario the second person will be able to read the information inserted by the first person before he commits the transaction.

12) Define SqlCommand Objects?

It is a collection of strings containing SQL statements which will be send to database for various operations. SQL Commands can be of type Select, Insert, Delete,Update or Stored procedures.

string Connection = “server=localhost; uid = UserName ; pwd = Password ; database = DemoDB”;

SqlConnection con = new SqlConnection(Connection);

con.Open();

string select = “Select * from Employee_Table”;

SqlCommand cmd = new SqlCommand(select, conn);

con.Close();


13) What are the different Command types in Commands?

They are Default, CommandType.StoredProcedure and CommandType.TableDirect .

For normal queries like select, command type is not specific.

string select = “Select * from Employee_Table”;

SqlCommand cmd = new SqlCommand(select, conn);

For Stored Procedures, command type should be specified as shown below

SqlCommand cmd = new SqlCommand(“Employee”, con);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(“@EmployeeID”, “EMP-761″);

For TableDirect (fetch all rows and columns from a table) , command type should be specified as shown below

OleDbCommand cmd = new OleDbCommand(“Employees”, conn);

cmd.CommandType = CommandType.TableDirect;

14) What are the different execution methods provided by the command object?

After creating an SQL or OLEDb Command, it needs to be executed. Following methods are used:

  • ExecuteNonQuery() –To execute the command which did not return any output
  • ExecuteReader() – Used to execute the command which returns a typed IDataReader
  • ExecuteScalar() – Used to execute the commands which return a single value
  • ExecuteXmlReader() – Used to execute the command that returns an XmlReader object. The object can be used to traverse the XML fragment returned from DB.

15) Define a Dataset object?

The DataSet is used to store data from a data source. It has a set of data tables. You could also specify the relation between the tables inside a dataset.

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 dot 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. and be a part of the best dot net institute in Pune. We offer best dot net course which is scientifically programmed and keep updating with time.

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

Most Asked ADO.NET Interview Questions And Answers

Part II

This article lists some of the latest ADO.Net Interview Questions and Answers for fresher and 2/3 years experienced .net developers with sample code and explanations.

1) Define ADO.NET ?

IT is one of the major components of .Net Framework, which is created to connect to databases like Oracle, SQL Server, MS Access etc. and work with stored data in them.

2) Explain Generic Features of ADO.Net ?

  • ADO.Net gives inbuilt classes to connect with Databases like Oracle, MySQL, SQL Server, MS Access etc.
  • Offersin built classes to do data manipulation operations like Insert, Update, Delete and Select data.
  • Offers data providers for specific databases for efficient interactions with DB. Example – ODP.Net provider for Oracle.
  • Tight integration with XML
  • Provides functionality to combine data from different data sources
  • Disconnected Data architecture for better performance


3)
What are the features of ADO.Net 2.0?

Huge Copy Operation from one Data Source to another Data Source.

  • Batch Update – To update a no of rows in a database table at a single time from a program thus by avoiding roundtrip to database.
  • Data Paging – To read data from an index
  • Connection Details – To get detailed info about connections like buffer information, cursor details etc.
  • DataSet.RemotingFormat Property – To make dataset serialized in Binary
  • DataTable’s Load and Save Methods – For XML interactions.

4) What are the namespaces used in ADO.NET for data access?

Namespaces used to access database are

  • System.Data – Contains all generic data access classes
  • System.Data.Common – Contains classes which are shared/overridden by data providers
  • System.Data.OleDb – OLE DB provider classes used to access databases such as Oracle, MySQL, SQL Server and MS Access.
  • System.Data.SqlClient – Contains classes for SQL Server
  • System.Data.SqlTypes – Contains SQL Server data types


5) What are differences between classic ADO and ADO.NET ?

ADO

  • ADO have record set
  • ADO communicate in binary mode
  • ADO supports connection oriented models
  • Since ADO derives information about data implicitly at run time based on metadata, it is an expensive process.
  • Only Client Side Cursors are allowed in ADO.

ADO.Net

  • ADO.Net have Data Adapter and Data set
  • ADO.NET uses XML for passing the data
  • ADO.Net works in Disconnected way
  • By leveraging known metadata at design time, ADO.Net provide better runtime performance and more consistent runtime behavior
  • ADO.Net Support both client side and server side cursors

6) What are the two fundamental objects in ADO.NET ?

Fundamental Objects of ADO.Net are DataReader and DataSet. DataSet Object can have a set of DataTables and relationships between these tables. DataSet can be used in disconnected connection with DB. DataReader is used to read the read-only data from a database.

7) What is the difference between dataset and data reader?

Data Reader is used to get data from a database in a much faster way. Since the rows are fetched one at a time, the load on the network will be low. Since Data Reader is read only, transactions are not allowed. Since it supports forward only data iteration, random data fetch is not supported.

DataSet is an in-memory portrayal of a table in a database. Dataset takes a lot of application memory compared to DataReader. It is slower compared to DataReader. But the user can do transactions using DataSet. It also supports querying.

8) What is the use of connection object?

Connection Objects is used to establish a connection between an application and databases like Oracle, MySQl, SQL Server etc. Once the connection is made, SQL Commands like insert, update, delete and select can be executed. The scope of a connection object can be local or global. If a local connection object is used, it should be closed after SQL commands are executed.

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 dot 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. and be a part of the best dot net institute in Pune. We offer best dot net course which is scientifically programmed and keep updating with time.

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

Most Asked ADO.NET Interview Questions And Answers

Part I

Here are a few important ADO.NET based interview questions and answers as follows:

1: Define ADO.NET?

Ans: ADO stands for Active Data Object and ADO.NET is a collection of .NET libraries for ADO.

ADO.NET is a set of managed libraries used by .NET applications for data source communication using a driver or provider:

  • Enterprise applications manage a large amount of data. This data is first stored in relational databases, such as Oracle, SQL Server, and Access and so on. These databases use Structured Query Language (SQL) for retrieval of data.
  • To access the data from a .NET application, an interface was required. This interface is a bridge between an RDBMS system and a .NET application. ADO.NET is such an interface that is created to connect .NET applications to RDBMS systems.
  • In the .NET Framework, Microsoft introduced a new version of Active X Data Objects (ADO) called ADO.NET. Any .NET application can interact with the database using a rich group of classes of the ADO.NET library. Data could be accessed from any database using connected or disconnected architecture.

ADO.NET offers mainly the following two types of architectures:

  • Connected Architecture.
  • Disconnected Architecture.

2: What are the ADO.NET components?

Ans: They categorized in three modes: disconnected, common or shared and the .NET data providers.

The components build the basic ADO.NET architecture. You could use these classes with or without data providers. For instance, you could use a DataTable object with or without providers and share common components are the base classes for data providers. Common components are the base classes for data providers and shared by all data providers. The data provider components are specifically designed to work with different kinds of data sources.

3: How can you define the DataSet structure?

Ans: A DataSet object falls in disconnected components series. The DataSet consists of a collection of tables, rows, columns and relationships.

DataSet contains a collection of DataTables and the DataTable contains a collection of DataRows, DataRelations, and DataColumns. A DataTable maps to a table in the database.

4: What do you mean by Connection Pooling in ADO.NET?

Ans: This is the ability to reuse your connection to the database. This says if you enable Connection pooling in the connection object, actually you enable the re-use of the connection to more than one user.

ADO.NET uses a technique called connection pooling, which lowers the cost of repeatedly opening and closing connections. Connection pooling reuses the presently active connections with the same connection string instead of creating new connections when a request is made to the database. It makes use of a connection manager that is responsible for maintaining a list, or pool, of available connections for a given connection string.

Several pools exist if different connection strings ask for connection pooling.

Example of Pooling:

  1. connection.ConnectionString=sqlConnectString+”ConnectionTimeout=30;ConnectionLifetime=0;MinPoolSize=0;MaxPoolSize=100;Pooling=true;”;
  2. //Openconnection

A Connection String in the Web.Config file with connection pooling option:

  1. <connectionStrings>
  2. <clear/>
  3. <addname=”sqlConnectionString”connectionString=”DataSource=mySQLServer;InitialCatalog=myDatabase;IntegratedSecurity=True;ConnectionTimeout=15;ConnectionLifetime=0;MinPoolSize=0;MaxPoolSize=100;Pooling=true;”/>
  4. </connectionStrings>

SQL Server connection string pooling attributes:

  • Connection Lifetime: Length of time in seconds after creation next which a connection is destroyed. The default is 0, this indicates that connection will have the maximum timeout.
  • Connection Reset: This says whether the connection is reset when removed from the pool. The default is true.
  • Load Balance Timeout: Length of time in seconds that a connection could remain idle in a connection pool before getting removed.
  • Max Pool Size: Maximum number of connections in the pool. The default is 100.
  • Min Pool Size: Minimum number of connections in the pool. The default is 0.
  • Pooling: The connection is drawn from the appropriate pool, or if necessary, created and added to the appropriate pool. The default is true.

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.

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.

For becoming technically strong, dot net training would be of great help. Opt for the best dot net course.

Our institute, CRB Tech Solutions which happens to be amongst the best dot net institutes provides an intensive ASP.NET training program. 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