Hosting Article

ByAlexia Pamelov

Cheap Windows Hosting – Why We Need Social Login Integration In Our Website

CheapWindowsHosting.com | In this article you will learn why we need social login Integration in our website. Firstly, when I started working on a website I was confused about integrating social login into the website. Later, I got to know what are its benefits. Here in this article I would like to represent this to you.

Before (1990-2000) every person required 3 things to live a comfortable life.

1

But the emergence of internet and web applications has changed the world in such a way that, internet became a need for people now a day. Today, “Internet” is considered the fourth need of every human being.

2

This is the current need for every person. 

internet

Why Internet?

Actually for this demand and use of internet the credit goes to the “Web applications”. Now the web application plays a major role for this high use and demand of internet. We are now solving thousands of problems such as marketing, booking ticket, purchasing goods, selling goods, finding room on rent, booking cabs, etc using internet.

Now we have different websites for different purpose such as Flipkart for purchasing goods, Amazon for purchasing goods, OLA for booking cabs, etc…So one boring and uninteresting activity to use different website is to fill the long Registration form, which users don’t want.

Problems With Lot Of WebSites

Yes,  the boring and uninteresting activity to use different website is to fill the long Registration form and remember its userid and password for Login.

Secondly, if the user started remembering all user id password, then think what will be the situation.The situation is just like the following picture.

failled

The user also don’t want to expose all his personal details to all these websites and finally to remember his/her UserName and Password.

So to avoid situation like this now we are integrating social login to our web site. If any user want to visit our website without registration, no problem he/she can visit our website using any of his social login account such as Facebook, Google+, Twitter, etc. This is because every person today is mandatory to have these accounts. A survey states that these accounts have these many users now a day.

Social
So now if you want to test any site without registration, you can do it with these social logins if this has integrated on that website.

External login

Conclusion

As billions of people already have accounts on these services, Now users can login with existing Facebook, Google, Twitter or Microsoft Live login. Many of them don’t want to register on another website and remember yet another user name/password pair. It is much faster and easier for them to visit website using social login and check the new website functionality. So in my opinion every new website must integrate with social logins.

 

ByAlexia Pamelov

Cheap Windows Hosting – How To choose the best Drupal 8.0.5 hosting Provider ?

CheapWindowsHosting.com | Best and Cheap Drupal 8.0.5 hosting. Today we will talk about the choice of a host for the Drupal site. This is a very important aspect that affects the fate of the whole project.

drupal-diver-monochrome(darkblue)The host is a service for site layout on a server which works twenty-four hours a day. The more stable this server is, the better and faster your site will function. Choosing a host for website is not unlike buying an apartment – the better it is, the more pleasant it will be to live in it.

The worse the host, the more problems you will have. There will be errors and glitches that annoy the visitors and make your site difficult to promote. When regular malfunctions occur you should think about changing your host. But even the best host will not be immune to errors, DDOS-attacks and other problems.

What host is better for Drupal website

Many people want choose a free host for the site. Our answer is no. If you decide to create a serious site you should buy a host. Remember that there’s no such thing as a free lunch. Everything has a price one way or another. The main disadvantages of the free host are:

  • Mandatory and obtrusive advertising. You must somehow compensate for the free services, so the host uses ads to make money. So if the host decides to advertise on your website, you either have to deal with it or disable the advertising for a fee.
  • Low permissible load levels. Your creativeness attracted readers, and if a few people began to go to your site every day you may start receiving messages that the load exceeds the permitted limit. The host will be suggest that you move to the paid version. It is better to pay for a good quality host from the beginning.
  • Poor technical support. This is the most annoying aspect of a free host, but after all, you can’t expect to have free consulting.  Host technical support should be operational and work twenty-four hours a day. In the case of free host, you usually get a reply long after issue is no longer relevant.

How to choose a website host for the beginners

If you are a novice, then this article will help you find your first host.

  1. Understand how much information you want to post and how many sites would it require. Figure out how much it will cost and choose several options. Of course, you should not choose an expensive host for the first time, so find out where you can host the site at a low price.
  2. Find out the location of the server. Some people believe that it’s more reliable if the servers are located in America or Europe. In fact, it is simply that the closer they are to the visitor, the faster site will load.
  3. Learn the price of all the service batches. Companies often offer cheap initial rate but then raise the prices the longer you stay.
  4. When deciding the choice of host for the drupal site, you should choose the one where the modern CMS is working without mistakes. Its operation is assured by the support of the programming language PHP and the database management system MySQL.
  5. Firstly test the host. You will sometimes be offered a free trial period. During the testing you can evaluate how fast the technical support responds, the ergonomics of the management and the work speed. Ask the technical support to move your site to the new host – a good host provider will do this efficiently and in a timely manner.If you do not like something, feel free to look for another platform.
  6. Technical support fix issues quickly (within hours), work seven days a week and, of course, be professional and polite. Pay attention to the ways you can contact to them. This could not only be by email, but also social networks, ICQ, Skype, and others. A free telephone line is a good sign.
  7. Read the reviews – this is a universal rule for any initiative. Read the reviews about the host on different resources. On the Internet, people are willing to share experiences and information on how to choose a good host.
  8. Do not pay the host too far into the future. If you are unhappy with the service, they may not return your payment. Hosts usually charge per day,so that you can pay for just a few days at first.
  9. Buy a domain separate from the host. Do not accept a free domain, otherwise the domain will belong to the host provider and you will not be able to move it. Also, it will only be free for the first year, and then the next year you will have to pay much more than it cost initially.

How to choose a host on technical characteristics and functionality.

You already know what to do while choosing a host, consider the functional and technical characteristics of a good host. The interface of the control panel is a very important point. There are host areas for administrators that are very complicated, but good host should have a comfortable, modern interface that is intuitively understandable to everyone.

  • Backups. Any host should do backups daily, but not everyone does. Equally important is how easy it is to use these backups. Sometimes, for example, you can only recover the backup, but you cannot load them. This can be checked during the test period.
  • The number of sites and databases, use of subdomains. If you plan to put multiple sites on the host or your drupal site will be located on multiple subdomains, find out what the limitations are. Usually you can find it in the description of your plan.
  • The download of the files for host. A good host will have at least three options for uploading files to the server: FTP, SSH and a web-interface (file manager) that is comfortable and usable. Also, check whether the file manager is able to extract and pack archives.
  • The amount of the disk space. For a blog, 100MB is enough. But every day will your blog will be increasing in size and the host will be filled with new images and files. Of course, everything will depend on how you save a place, but I think 1000Mb is enough for anyone. Note also that when you have to do the backup version of the site, it is stored in the root site. The site will fail to backup if you do not have enough space on the host.
  • Operating System. I advise you to choose the servers that are running on the Unix-like operating systems (GNU/Linux, Free BSD). Some use Windows-host, but there may problems with it.
  • Traffic. Most providers do not have limited traffic (this is also stated in the tariff plan). But there are those who cap it — for example, the rate may be 50GB of traffic a day. There is nothing wrong with this, you just need to estimate how much data you need. To do this, multiply the average size of your page (on the average 100 KB) on the number of views per month (you get this from Yandex. Metrics), and add 700 megabytes for robots, download of the backups and more.
  • The load on the server (CP). Traffic may be unlimited, but the server load will certainly be counted. The load on the server reflects the time taken by a server to process php-scripts, and depends on the traffic and the functional site.
  • Uptime. An important characteristic of the server on which your website is stored is the server uptime, measured in percentiles. 99. 99% means that the server was not working only 50 minutes out of the year. The closer to this figure, the better.
  • As mentioned above, technical support, location and cost of the servers are also important considerations.

In general, choosing a host involves a lot of different criteria, and these are only some of them. The main rule, though, is to make the choice carefully because any host has its downsides  that can affect the site.

Best and Cheap Drupal 8.0.5 hosting

ASPHostPortal.com was one of our top performers, and is especially impressive considering the $5.00 price point for their startup Drupal 8.0.5 hosting plan. ASPHostPortal has been offering hosting services for more than 8 years and is a good option if you are looking for shared hosting. They offer great, reliable hosting at an incredibly good price that is hard to beat from a reputable company. Not only that ASPHostPortal also offers very reliable hosting with easy installation of Drupal 8.0.5, 24/7 support, and a long track record.

ByAlexia Pamelov

Cheap Windows Hosting – Tips to Improve Your ASP.NET MVC 6 Codebase

CheapWindowsHosting.com | Best and cheap windows ASP.NET MVC 6 hosting. I have an urge to write a quick list of tips for improving an ASP.NET MVC 6 application because I just got done reviewing some code for a support ticket at work. It’s still fresh in my mind and I wanted to get some of my thoughts down to share with others. If you have been doing MVC for a while, I don’t think much of this is news. It’s more for those of you that don’t do MVC often or are new to MVC.

Imagine this: you’ve been tasked to figure out why a web application is using 2GB of memory on the production web servers. You pull down the version that’s currently in production and run it locally to profile and debug.

After looking through the code, doing some profiling, maybe shaking your head a bit, you’ve figured out what the issue is and now you need to give some feedback.

That’s exactly what happened to me today and out of that experience, 5 tips you can follow to keep your ASP.NET MVC 6 codebase working as you’d expect.

1. Understand the queries in your problem domain

The root cause of the support ticket I received was a simple case of fetching too much data from the database, causing obscene amounts of memory usage.

It’s a common enough issue. You’re building a simple blog, it has posts and it has media (images, videos, attachments). You put a Media array onto your Post domain object. Your Media domain object has all the image data stored in a byte array. Since you’re using an ORM, there’s a certain way you need to design your domain model to play nice; we’ve all experienced this.

public class BlogPost { 
  public ICollection<BlogMedia> Media { get; set; }
}
public class BlogMedia {
  public byte[] Data { get; set; }
  public string Name { get; set; }
}

There’s nothing absolutely wrong with this design. You’ve modeled your domain accurately. The problem is, when you issue a query through your favorite ORM, it eagerly loads all the data associated with your blog post:

public IList<BlogPost> GetNewestPosts(int take) {
  return _db.BlogPosts.OrderByDescending(p => p.PostDate).Take(take).ToList();
}

A seemingly innocuous line (unless you’ve been bitten), a sneaky monster is lying in wait with big consequences if you haven’t disabled lazy loading or didn’t tell your ORM to ignore that big Data property on blog media.

It’s important to understand how your ORM queries and maps objects and make sure you only query what you need (for example using projection).

public IList<PostSummary> GetNewestPosts(int take) {
  return _db.BlogPosts.OrderByDescending(p => p.PostDate).Take(take).Select(p => new PostSummary() {
      Title = p.Title,
      Id = p.Id
  }).ToList();
}

This ensures we only grab the amount of data we really need for the task. If all you’re doing is using the title and ID to build a link on the homepage, just ask.

It’s OK to have more than 5 methods on a repository; be as granular as you need to be for your UI.

2. Don’t call your repositories from your views

This one’s a little sneaky. Consider this line in an MVC view:

@foreach(var post in Model.RelatedPosts) {
  ...
}

 It seems innocent enough. But if we take a look at what exactly that model property is hiding:

public class MyViewModel {
  public IList<BlogPost> RelatedPosts {
      get { return new BlogRepository().GetRelatedPosts(this.Tags); }
  }
}

Yikes! Your “view model” has business logic in it on top of calling a data access method directly. Now you’ve introduced data access code somewhere it doesn’t belong and hidden it inside a property. Move that into the controller so you can wrangle it in and populate the view model conciously.

This is a good opportunity to point out that implementing proper unit tests would uncover issues like this; because you definitely can’t intercept calls to something like that and then you’d realize injecting a repository into a view model is probably not something you want to be doing.

3. Use partials and child actions to your advantage

If you need to perform business logic in a view, that should be a sign you need to revisit your view model and logic. I don’t think it’s advisable to do this in your MVC Razor view:

@{
  var blogController = new BlogController();
}
<ul>
@foreach(var tag in blogController.GetTagsForPost(p.Id)) {
  <li>@tag.Name</li>
}
</ul>

Putting business logic in the view is a no-no, but on top of that you’re creating a controller! Move that into your action method and use that view model you made for what it’s intended for. You can also move that logic into a separate action method that only gets called inside views so you can cache it separately if needed.

//In the controller:

[ChildActionOnly]
[OutputCache(Duration=2000)]
public ActionResult TagsForPost(int postId) {
  return View();
}

//In the view:

@{Html.RenderAction("TagsForPost", new { postId = p.Id });}

 Notice the ChildActionOnly attribute.

Any method that is marked with ChildActionOnlyAttribute can be called only with the Action or RenderAction HTML extension methods.

This means people can’t see your child action by manipulating the URL (if you’re using the default route).

Partial views and child actions are useful tools in the MVC arsenal; use them to your advantage!

4. Cache what matters

Given the code smells above, what do you think will happen if you only cached your view model?

public ActionResult Index() {
  var homepageViewModel = HttpContext.Current.Cache["homepageModel"] as HomepageViewModel;
  if (homepageViewModel == null) {
      homepageViewModel = new HomepageViewModel();
      homepageViewModel.RecentPosts = _blogRepository.GetNewestPosts(5);
      HttpContext.Current.Cache.Add("homepageModel", homepageViewModel, ...);
  }
  return View(homepageViewModel);
}

Nothing! There will not be any performance gain because you’re accessing the data layer through a controller variable in the view and through a property in the view model… caching the view model won’t help anything.

Instead, consider caching the output of the MVC action instead:

[OutputCache(Duration=2000)]
public ActionResult Index() {
  var homepageViewModel = new HomepageViewModel();
  homepageViewModel.RecentPosts = _blogRepository.GetNewestPosts(5);
  return View(homepageViewModel);
}

Notice the handy OutputCache attribute. MVC supports ASP.NET Output Caching; use it to your advantage when it applies. If you are going to cache the model, your model needs to essentially be a POCO with automatic (and read-only) properties… not something that calls other repository methods.

As an added benefit, I haven’t ever done this but you can implement different output caching providers allowing you to cache on AppFabric/NoSQL/anywhere if you ever needed it. MVC is super extensible.

5. Don’t be afraid to leverage your ORM

If you’re not going to take advantage of your ORM’s feature set, you are missing out. In the codebase I was reviewing, they were using NHibernate but they weren’t using it. They were totally missing out on its advanced projection capabilities to solve some of these memory issues. Some of this stems from rigidity in using a “repository pattern” and some of it stems from lack of knowledge.

By taking advantage of EF or NHibernate’s features, your repositories can do a lot more than just use basic generic methods. They can shape and return the data you actually want in your controllers, greatly simplifying your controller logic. Do yourself a favor and read through the ORM’s documentation to get a handle on what it can offer.

I think when people adopt the repository pattern, it’s almost like they pull down a shade over the bright light shining in from their ORM window. When I started playing with RavenDB, I got rid of my repository layer (in fact, my entire data project) and went full-metal using Raven queries in my application service layer with a little bit of extension methods to reuse query logic. I found that a lot of my logic was really context-specific and benefited from simply taking advantage of Raven’s extensive features to project, shape, and batch my queries.

That’s just, like, your opinion man…

If you think you can abstract your ORM, I challenge you to think about it differently. The ORM is your abstraction and if you believe swapping out your existing ORM with another ORM will be a piece of cake because it’s “abstracted”, you’d be surprised. That’s what I thought too until I learned the hard way that switching to Raven really changed my entire codebase in ways I didn’t expect. Your ORM doesn’t only affect data access, it affects the domain and it affects your business logic, it even will have an effect on your UI. By removing the repository abstraction, I actually reduced the overall complexity of my data access code.

ByAlexia Pamelov

Cheap Windows Hosting – Tips to Make Your Web Content Work for You

CheapWindowsHosting.com | Best and  Cheap Windows ASP.NET Hosting , Today I wold like give you tips to make your web content Work for You From websites to blogs to social media, your content speaks for you. Without the advantage of in-person interaction and out-loud conversations, it can be hard to for businesses to communicate online.  Here are a few simple tips to keep your content fresh and working for your business:

web-content-management

1 . Get to the point

No one has time to wade through wordy pages just to find an answer to their question. Put vital information front and center where it’s easy to find, and design your content so that it’s easily “skim-able.”

  • Write descriptive headers
  • Put important topics in bold
  • Use bullet points

Providing a hierarchy of information is the perfect way to get to the point while also offering more information for those that want it. Let your readers decide how much detail they want to delve into.

2. Sound like a human

Verbose language and stiff wording will turn off your readers in no time (and you only have a few seconds to get their attention in the first place). Not to mention, Google now looks more favorably on well-written, unique content than keyword-stuffed paragraphs. It’s important to sound like a real person wrote your content, not a robot – especially on social media!

  • Contractions are your friends (It’s instead of It is, There’s instead of There is)
  • Keep your sentences short
  • Use simple language (Save the $5 dollar words for Scrabble!)

When your content is too formal sounding, it makes your business seem less approachable. Simple, conversational wording sounds like a human wrote it, which in turn makes your company seem more human.

3. Provide next steps

Don’t leave your readers hanging! Show them where to go next. What’s the point of filling up a website or writing a Facebook post if customers don’t know what to do from there?

  • Provide a clear Call to Action
  • Make contact information obvious
  • Offer links to learn more

Make it easy for customers to get in touch, learn more, or stay connected with your business.

From desktop websites to Twitter posts and everything in between, web content is your customers’ online connection to your business. No matter the medium, make the most of it with clear, simple wording that illustrates who you are, and convinces a casual reader to make the leap to becoming a customer.

ByAlexia Pamelov

Cheap Windows Hosting – Simple Tips Optimize Your WordPress Website

CheapWindowsHosting.com | Today, I would like to share with you thirteen quick tips on how you can optimize your website and decrease page loading times. If you follow these techniques and best practices, your website will load much quicker. The time it takes your website to load influences how successful it will be. If your website is slow, visitors will turn away in droves. They might even click the back button before your website loads. Website performance will also influence your rankings in search engines. In addition to being ranked higher, many website owners report seeing an increase in search engine spider crawling after speeding up their design.

Before applying these techniques to your website, I encourage you to check the speed of your website using a free performance service such as GTMetrix, YSlow or Google PageSpeed Insights. These services will inform you of your page loading time and the overall file size of your page. They also offer tips

[su_spoiler title=”Choose the Right Hosting Plan” style=”fancy” icon=”folder-2″]

The first step in optimizing your website correctly is to choose the right hosting plan. You are fighting a losing battle if your server is taking an age to process HTTP requests and MySQL commands. Performance services such as GTMetrix will advise you of the exact response time of your server. I recommend testing the response time of your own website against similar websites. For example, if you run a photography blog, see how your server response time compares to other photography blogs within your niche. Hosting companies are not always the cause. You may be with a great hosting company but see poor response times because your chosen hosting plan is underpowered. Customers using shared hosting plans, for example, are more likely to face slow loading times as hundreds of websites are hosted on the same server. However, any type of hosting plan will suffer from insufficient RAM and CPU throttling. Therefore, you need to pay attention to what your website needs to run smoothly. Do not be a cheapskate and go for the cheapest option. Choose a hosting plan that can handle traffic spikes efficiently.

[/su_spoiler]

[su_spoiler title=”Monitor Your Plugins” style=”fancy” icon=”folder-2″]

Before you install any plugin on your website, ask yourself “Is this plugin necessary?”. Plugins are one of the biggest causes of WordPress websites being slow. The more plugins you install without research, the more likely you will face performance issues; however the sheer number of plugins you have installed is not the reason a WordPress website can slow down. Certain plugins are known for causing websites to be slow. There are many reasons for this including bad coding, calls to external servers and persistent calls and updating of your WordPress database. Pay close attention to how much CPU plugins use too. Many plugins can bottleneck your CPU due to persistent processes. If this happens, your whole server could go down.

[/su_spoiler]

[su_spoiler title=”Empty Your Trash” style=”fancy” icon=”folder-2″]

WordPress 4.4.1 introduced the WordPress trash system. Whenever content is deleted, be it a comment, post, page, media etc; it is sent to trash. From here, the content can either be restored or deleted permanently. It is effectively a fail-safe system that helps you recover anything that was deleted accidentally (in much the same way the recycling bin works in your computer). Trash can take up a lot of unnecessary room in your website’s database. The bigger the database, the longer it is to retrieve information from it. By default, WordPress will automatically delete trash after thirty days. This can be reduced by modifying the wp-config.php file. For example, you could reduce this to seven days by adding the following:

define ('EMPTY_TRASH_DAYS', 7);

You can completely disable the trash system by adding this to your wp-config.php file.

define ('EMPTY_TRASH_DAYS', 0);

[/su_spoiler]

[su_spoiler title=”Optimize Your Images for the Web” style=”fancy” icon=”folder-2″]

Images can help break up long pieces of text and can help your articles be shared more frequently on social media services; however they also take up a lot of storage. Therefore, pages that contain many images can take a long time to load. It is therefore in your best interests to optimise your images for the internet before you upload them to your website. Most photo editing applications, such as Photoshop, allow you to do this via the “Save for Web” option. A good plugin to optimize images that have already been uploaded is WP Smush.it. It utitlizes the Smush.it API to optimize JPEG images, strip meta data from JPEGs and convert GIF images to PNG. You should however be aware that the plugin uses up a lot of resources when it is converting images, therefore your website may be slow whilst it is running. If you do not want to sacrifice image quality, check out Lazy Load. The plugin ensures that images are only loaded when the area becomes visible to the user. This will greatly reduce page loading times. [/su_spoiler]

[su_spoiler title=”Enable Browser Caching” style=”fancy” icon=”folder-2″]Some of the largest files on your website rarely change. This includes CSS files, Javascript files, your website logo etc. One way to take advantage of this is to enable browser caching. Browser caching allows internet users to speed up the loading time of their favourite websites by storing a cached copy of your website locally. This reduces calls to your server and saves the user from downloading the same files again. You can enable browser caching by adding the following code to your .htaccess file:

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##

The code above specifies how long a particular file type should be stored. Files will simply be downloaded again if they have expired.

[/su_spoiler]

[su_spoiler title=”Install a Cache Plugin” style=”fancy” icon=”folder-2″]

Caching plugins allow you to publish static HTML files instead of dynamic files. This greatly reduces the time a page takes to load as there are no PHP or MySQL commands to execute. Additional caching features include minification, caching of feeds, Gzipping, Content Delivery Network (CDN) support, and much more. Caching your pages is one of the most effective ways of improving your page loading times, with many plugins promising an improvement of at least ten times. Popular caching plugins include WP Super Cache, W3 Total Cache and WP Fastest Cache. All three plugins are available free. [/su_spoiler]

ASPHostPortal.com – Best and Cheap Web Hosting Recommendation

ASPHostPortal.com was launched in 2008. They are one of the best Windows Hosting in United States is ASPHostPortal.com. This company currently supports Windows Server 2012 hosting with ASP.NET 5/ 4.5 / 4.5.1 / 4.5.2, MVC 5.1 / 5.1.1 / 5.1.2/6, Visual Studio 2012, WebSockets, IIS 8.5, Wordpess 4.4.1 and support the latest Microsoft technology. All of its Windows hosting services are 100% compatible with ASP.NET 5. The price of ASPHostPortal.com ASP.NET 5 hosting packages is quite competitive, especially the Host One which we may recommend most here. Going through this promotional link directly and you will get FREE DOMAIN or DOUBLE SQL SPACE, the Host One Windows hosting package is $5.00/mo. This company offers money back guarantee if any of the clients fail to get the desired results. If the company does not work up to the expectations in a certain month, and the valid refund period is 30 days. In addition, the customer service is based on US and the representatives are working 24/7.

ByAlexia Pamelov

Cheap Windows Hosting – Entity Framework and handling Exceptions

CheapWindowsHosting.com | Cheap and affordable windows hosting. In this tutorial we will learn about Logging database operations in Entity Framework and handling Exceptions.

Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

If you are using the EF6 and want to log the database operations, analyze them, then, this is the right place for you.

When I was developing one WebApi project, what I was searching for is an output each query performed by Entity framework should be logged with time. Also, exception if there is any. So, in this section, you will learn how to log commands and queries to the database generated by Entity framework.

There are two ways using code

  • Simple Method
using (MyDatabaseEntities context = new MyDatabaseEntities())
     {
         context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
          // query the database using EF here.
      }

This will log the database operations in the output window. What it does is it writes the operations performed byEntityFramework to the output window. It gives awesome traces.

Have a look :

1

  • IDbCommandInterceptor

This uses the IDbCommandInterceptor Interface. This is in-built in Entity framework 6.

Note: This is available in Entityframework 6 and later.

Interface looks like this:

namespace System.Data.Entity.Infrastructure.Interception
{
  /// <summary>
  /// An object that implements this interface can be registered with 
  /// <see cref="T:System.Data.Entity.Infrastructure.Interception.DbInterception"/> to
  ///             receive notifications when Entity Framework executes commands.
  /// 
  /// </summary>
  /// 
  /// <remarks>
  /// Interceptors can also be registered in the config file of the application.
  ///             See http://go.microsoft.com/fwlink/?LinkId=260883 
  ///             for more information about Entity Framework configuration.
  /// 
  /// </remarks>
  public interface IDbCommandInterceptor : IDbInterceptor
  {
    /// <summary>
    /// This method is called before a call to 
    /// <see cref="M:System.Data.Common.DbCommand.ExecuteNonQuery"/> or
    ///             one of its async counterparts is made.
    /// 
    /// </summary>
    /// <param name="command">The command being executed.</param>
    /// <param name="interceptionContext">
    /// Contextual information associated with the call.</param>
    void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext);

    /// <summary>
    /// This method is called after a call to 
    /// <see cref="M:System.Data.Common.DbCommand.ExecuteNonQuery"/>  or
    /// one of its async counterparts is made. 
    /// The result used by Entity Framework can be changed by setting
    /// <see cref=
    /// "P:System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext`1.Result"/>.
    /// 
    /// </summary>
    /// 
    /// <remarks>
    /// For async operations this method is not called until after the async task has completed
    ///             or failed.
    /// 
    /// </remarks>
    /// <param name="command">The command being executed.</param>
    /// <param name=
    /// "interceptionContext">Contextual information associated with the call.</param>
    void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext);

    /// <summary>
    /// This method is called before a call to 
    /// <see cref="M:System.Data.Common.DbCommand.ExecuteReader(System.Data.CommandBehavior)"/> or
    /// one of its async counterparts is made.
    /// 
    /// </summary>
    /// <param name="command">The command being executed.</param>
    /// <param name="interceptionContext">Contextual information associated with the call.
    /// </param>
    void ReaderExecuting(DbCommand command, 
  DbCommandInterceptionContext<DbDataReader> interceptionContext);

    /// <summary>
    /// This method is called after a call to 
    /// <see cref="M:System.Data.Common.DbCommand.ExecuteReader(System.Data.CommandBehavior)"/> or
    /// one of its async counterparts is made. 
    /// The result used by Entity Framework can be changed by setting
    /// <see cref=
    /// "P:System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext`1.Result"/>.
    /// 
    /// </summary>
    /// 
    /// <remarks>
    /// For async operations this method is not called until after the async task has completed
    ///             or failed.
    /// 
    /// </remarks>
    /// <param name="command">The command being executed.</param>
    /// <param name="interceptionContext">
    /// Contextual information associated with the call.</param>
    void ReaderExecuted(DbCommand command, 
    	DbCommandInterceptionContext<DbDataReader> interceptionContext);

    /// <summary>
    /// This method is called before a call to 
    /// <see cref="M:System.Data.Common.DbCommand.ExecuteScalar"/> or
    ///             one of its async counterparts is made.
    /// 
    /// </summary>
    /// <param name="command">The command being executed.</param>
    /// <param name="interceptionContext">
    /// Contextual information associated with the call.</param>
    void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext);

    /// <summary>
    /// This method is called after a call to 
    /// <see cref="M:System.Data.Common.DbCommand.ExecuteScalar"/> or
    /// one of its async counterparts is made. 
    /// The result used by Entity Framework can be changed by setting
    /// <see cref=
    /// "P:System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext`1.Result"/>.
    /// 
    /// </summary>
    /// 
    /// <remarks>
    /// For async operations this method is not called until after the async task has completed
    ///             or failed.
    /// 
    /// </remarks>
    /// <param name="command">The command being executed.
    /// </param><param name="interceptionContext">
    /// Contextual information associated with the call.</param>
    void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext);
  }
}

Let’s derive this interface to the DatabaseLogger class.

FYI, I have added my log information into database. You may insert into file, Excel, anything you want.

You need not worry about the methods Interface itself is very self explanatory. It has 6 methods, which you can see I have derived and check comments to understand each scenario.

//this file is used to log the database operations it checks
//the query execution time and than insert if it takes more than one second.
 //to disable it remove its registry from TeamPassDbContext default constructor
 public class DatabaseLogger : IDbCommandInterceptor
 {
     static readonly ConcurrentDictionary<DbCommand,
     DateTime> MStartTime = new ConcurrentDictionary<DbCommand, DateTime>();

     public void NonQueryExecuted(DbCommand command,
     DbCommandInterceptionContext<int> interceptionContext)
     {
         //executed state
         Log(command, interceptionContext);
     }

     public void NonQueryExecuting(DbCommand command,
     DbCommandInterceptionContext<int> interceptionContext)
     {
         //executing state
         OnStart(command);
     }

     public void ReaderExecuted(DbCommand command,
     DbCommandInterceptionContext<DbDataReader> interceptionContext)
     {
         //reader executed state
         Log(command,interceptionContext);
     }

     public void ReaderExecuting(DbCommand command,
     DbCommandInterceptionContext<DbDataReader> interceptionContext)
     {
         //reader executing state
         OnStart(command);
     }

     private static void Log<T>(DbCommand command,
     DbCommandInterceptionContext<T> interceptionContext)
     {
         DateTime startTime;
         TimeSpan duration;
         //Removing from dictionary and calculating time
         MStartTime.TryRemove(command, out startTime);
         if (startTime != default(DateTime))
         {
             duration = DateTime.Now - startTime;
         }
         else
             duration = TimeSpan.Zero;

         const int requestId = -1;

         var parameters = new StringBuilder();
         foreach (DbParameter param in command.Parameters)
         {
             parameters.AppendLine(param.ParameterName + " " +
             param.DbType + " = " + param.Value);
         }

         var message = interceptionContext.Exception == null ?
         $"Database call took {duration.TotalSeconds.ToString("N3")} sec.
         RequestId {requestId} \r\nCommand:\r\n{parameters + command.CommandText}" :
         $"EF Database call failed after {duration.TotalSeconds.ToString("N3")} sec.
         RequestId {requestId} \r\nCommand:\r\n{parameters.ToString() +
         command.CommandText}\r\nError:{interceptionContext.Exception} ";

         //Ignoring some queries which runs perfectly
         if (duration.TotalSeconds>1 || message.Contains("EF Database call failed after "))
         {
             //The time taken is more or it contains error so adding that to database
             using (DbContext dbContext = new DbContext())
             {
                 //using error model class
                 Error error = new Error
                 {
                     TotalSeconds = (decimal)duration.TotalSeconds,
                     Active = true,
                     CommandType = Convert.ToString(command.CommandType),
                     CreateDate = DateTime.Now,
                     Exception = Convert.ToString(interceptionContext.Exception),
                     FileName = "",
                     InnerException = interceptionContext.Exception == null ?
                     "" : Convert.ToString(interceptionContext.Exception.InnerException),
                     Parameters = parameters.ToString(),
                     Query = command.CommandText,
                     RequestId = 0
                 };
                 //Adding to database
                 dbContext.Errors.Add(error);
                 dbContext.SaveChanges();
             }

             //var errorFileUrl = ;
             //File.WriteAllLines(, message);
         }
     }

     public void ScalarExecuted
     (DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
     {
         //Log and calculate after executed
         Log(command, interceptionContext);
     }

     public void ScalarExecuting
     (DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
     {
         //adding to dictionary when executing
         OnStart(command);
     }
     private static void OnStart(DbCommand command)
     {
         //adding to dictionary when executing
         MStartTime.TryAdd(command, DateTime.Now);
     }
 }

Now, I am registering this class to dbcontext. What it does is, It tells entity framework to use this class for logging database operations.

public DbContext(): base("name=connectionstring")
       {
           //TODO remove this when don't need to log anything
           DbInterception.Add(new DatabaseLogger());
       }

Everything is set up now. You can make an Error model class like this. (This is the code-first model class.)

public class Error
  {
      [Key]
      [Required]
      public int ErrorId { get; set; }
      public string Query { get; set; }
      public string Parameters { get; set; }
      public string CommandType { get; set; }
      public decimal TotalSeconds { get; set; }
      public string Exception { get; set; }
      public string InnerException { get; set; }
      public int RequestId { get; set; }
      public string FileName { get; set; }
      public DateTime CreateDate { get; set; }
      public bool Active { get; set; }
  }

You can see the error logs here

2

Technically, there are many approaches to log your database operations. But, I think this should be centralized to reduce the load. That is why I used this approach.