Category Archives: Visual Studio 2013

Populate DataGridView with MongoDB Data using Entity in c#

How to populate a DataGridView in Winforms application using C# and data from MongoDB database

Assuming that you already have a model mapped to a collection in MongoDB.

You would like to populate the data in a DataGridView in c#.

We have a model called QuestionBank

 

We will fetch all the records from Mongodb collection using the Filter.Empty

 

 

 

Here is the code

   var documents =  db.QuestionBanks.Find(Builders<QuestionBank>.Filter.Empty).ToListAsync();
   this.dataGridView1.DataSource = documents.Result;

 

 

There is absolutely no need to do any loops to achieve it.

 

 

 

[C# and VB.Net] How to close a form after confirmation in Winforms

How to close a form in c#  after confirming

 

 

You can put the following code in any button

 

          if (MessageBox.Show("Are you sure you want to exit?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                               this.Close();
            }

 

In VB.NET you can use the following code

 

 If MsgBox("Are you sure you want to close", MsgBoxStyle.YesNo, "Close Application") = MsgBoxResult.Yes Then

            Me.Close()
        End If

c# – new GUID() returns 0

GUID stands for globally unique identifier.

GUIDs are usually stored as 128-bit values, and are commonly displayed as 32 hexadecimal digits with groups separated by hyphens.

Here is an example {21EC2020-3AEA-4069-A2DD-08002B30309D}.

They may or may not be generated from random (or pseudo-random) numbers.

GUIDs generated from random numbers normally contain 6 fixed bits (these indicate that the GUID is random) and 122 random bits; the total number of unique such GUIDs is 222 (approximately 5.3×1036).

The probability of the same number being generated randomly twice is negligible;

Assuming uniform probability for simplicity, the probability of one duplicate would be about 50% if every person on earth as of 2014 owned 600 million GUIDs.

 

 

WARNING

—————————————–

Do not use this way as it will only return with all zeros as shown below.

Guid  g1 = new Guid();       // g1 will return 00000000-0000-0000-0000-000000000000

 

——————————————–

 

Here is the correct way
Guid g1 = Guid.NewGuid();  //   g1 will return a proper GUID like {21EC2020-3AEA-4069-A2DD-08002B30309D}

 

 

Could not load file or assembly ‘System.Web.Http.WebHost, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′ or one of its dependencies. The system cannot find the file specified.

Could not load file or assembly ‘System.Web.Http.WebHost, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′ or one of its dependencies. The system cannot find the file specified.

 

Scenario

I had a Visual Studio 2013 project using MVC4. The application was working fine in my local machine. But when I deployed the application using FileSystem( in this method all the files for the project gets copied to a folder on your local machine, then you can copy all these files to your webhost and your application should start working.)

 

I got the following error when I deployed the application using this method.

Could not load file or assembly ‘System.Web.Http.WebHost, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′ or one of its dependencies. The system cannot find the file specified.

 

How to Fix it?

I searched on the web for  some time to get the answer and in the end I discovered that the System.Web.HTTP.WebHost.DLL file was not being copied to my published folder and hence the error.

1. Go to the solution Explorer in Visual Studio

2. Go to the References

3. Right Mouse Click on the System.Web.HTTP.WebHost entry  to check its prooperties and I found that COPY LOCAL proeprty was set to false and hence the file was not being copied to my published folder.

4. I changed the COPY LOCAL to true and then the file gets copied to  my published folder and gets deployed correctly.

My Best-Answer.net

C#- Creating Custom HTML Helpers – Full Example

Custom HTML Helpers can help seperation of code and html and avoid repetion.

What is a HTML Helper ?

It is just a method that will return a string which can contain any content you wan from a simple string to a table of data.

Why are HTML Helpers useful ?

method that returns a string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input> and <img> tags. In ASP.NET we have many standard HTML Helpers

  • Html.ActionLink()
  • Html.BeginForm()
  • Html.CheckBox()
  • Html.DropDownList()
  • Html.EndForm()
  • Html.Hidden()
  • Html.ListBox()
  • Html.Password()
  • Html.RadioButton()
  • Html.TextArea()
  • Html.TextBox()

 

 

Let us think of a situation.

In a  web page we need to list the features of a product.

If the feature is present then show a Tick

If the feature is missing then show a Cross

As shown below.

 

 

Capture

 

 

This is achieved by using two different CSS classes which will render the Tick or the Cross

When I use my CSS class “plain” it will render a Cross

When I use the class “checked” it shows a Tick.

Capture2

 

 

Now in razor view you would typically use the

@Html.DisplayFor(model => model.Alarm)   which would render a standard check box ( if true then the checkbox will be ticked and if false the checkbox will be empty) But we want a better display hence we want to make use of our CSS classes.

In order to show the customised CSS we will have to write some logic in the Razor view which is not preferred at all as we would like to keep the logic out from the views and secondly it will need a lot of code as for each item we will have to use some kind of If loop as shown below.

 

Not recommended

@if (Model.AirConditioning == true)
{
<li class=”ticked”>@Html.LabelFor(model => model.AirConditioning)</li> }
else
{
<li class=”plain”>@Html.LabelFor(model => model.AirConditioning)</li> }

 

 

Better Alternative is to write a Custom HTMLHelper

Let us write a Custom HTML Helper for it.

 

Create a Class

I created a folder called HTMLHelpers in my project and then created a class called myHTMLHelpers.cs as shown below

Capture3

The content of the class is as below

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace myapplication.Helpers
{
    public static class myHTMLHelpers
    {


    
          public static IHtmlString TickOrCross(bool content)
            {
                string htmlString = "";
              
         
                if(content==true)
                    {
                        htmlString = String.Format("checked");  // if content is true then we want the CSS class checked

                    }
                    else
                    {

                        htmlString = String.Format("plain"); // if content is falsethen we want the CSS class plain
                    }

                return new HtmlString(htmlString);

            }
          }
    }

How te make use of this HTML Helper ?

Go to your Razor View

 

at the top of the page add the namespace under which we created our helper class

@using myapplication.Helpers

 

 

at the right place in your razor view I have  made use of our custom html helper.

We pass the model value to it and it will set the class name accordingly to display a Tick or a Cross

                                    <ul class=”span2″>
<li class=”@myHTMLHelpers.TickOrCross(Model.AirConditioning)“>Air Conditioning</li>
<li class=”@myHTMLHelpers.TickOrCross(Model.Alarm)“>Alarm</li>

</ul>

The other way would have been to put the logic into the view using the if block in our code,. which is not a good practice.

@if (Model.AirConditioning == true)
{
<li class=”ticked”>Air Conditioning</li> }
else
{
<li class=”plain”>Air Conditioning</li>
}

How to render @html.actionlink as a button in MVC in Razor

How to render  @HTML.Actionlink  in MVC and using it as a button

Background of @HTML.ACTIONLINK in MVC

The easiest way to render an HTML link in is to use the HTML.ActionLink() helper.

With MVC, the Html.ActionLink() does not link to a view. It creates a link to a controller action.

Razor Syntax:

@Html.ActionLink(“About this Website”, “About”)

ASP Syntax:

<%=Html.ActionLink(“About this Website”, “About”)%>

The first parameter is the link text, and the second parameter is the name of the controller action.

The Html.ActionLink() helper above, outputs the following HTML:

<a href=”/Home/About”>About this Website</a>

 

 

When using  @html.actionlink it normally renders it like a hyperlink. But there is a simple way to render it as a button.

 

Simple example of  @HTML.Actionlink

@Html.ActionLink("Register,"Register")

 

and it will render it as a  Hyperlink

 

 

How to render  @HTML.Actionlink as a button

 

I am using Boostrap so I have the CSS class called “btn” available. Otherwise you can use your own CSS which can create a button

 

 Here is your Answer below

C# Syntax

@Html.ActionLink("Register", "Register" ,null,  new { @class = "btn" })

 

VB.NET Syntax

@Html.ActionLink("Register", "Register" ,null,  new  with {.class = "btn" })   



the null is for the Routevalues ( in the example we are using any route values hence null)

 

Hope this helps you

VB.NET – You must call the “WebSecurity.InitializeDatabaseConnection” method before you call any other method of the “WebSecurity” class.

Problem description:

If you are getting the error while running your MVC4 application in VB.NET

You must call the “WebSecurity.InitializeDatabaseConnection” method before you call any other method of the “WebSecurity” class.

Solution

Add the following line in the GLOBAL.ASX

Capture

 

Ensure that you are using the correct connection string and other information as per your own application as  shown in the highlighted line above.

VB.NET – ASP NET MVC Area routing/multiple routes issue in VB.NET

Scenario: If you have two controllers with the same name in different areas, then you would end up with errors as shown below, while there are numerous examples available on the web but it took me a while to figure out the correct solution for VB.

Hope it help you and saves you time.

Problem Description

I have a HOME controller in my MVC4 application and then I created a new AREA called SUPERADMIN. I then created a HOME controller in that area as well.I received the following error.

Error with duplicate controller names

 

 

 

Solution:

 

 

1. Fix the Route.Config in your MVC4 project under APP_Start folder. See the yellow coloured text,

 

vbnull is for constraints( so we are not adding special constraints

the next one “RealEstateVB” is the namespace , RealEstateVB is the name of my application and is taken as the default namespace.

Adding Namespace in ROUTE

2. Now Go to your AREA. I had an area called SUPERADMIN.

See the highlighted text. You have to define the namespace. eg. I have used “RealEstateVB.Areas.Superadmin for my SuperAdmin area.

Also make a note how I have added superadmin in front of the /{controller}/{action}/{id}

Adding namespace in Area

 

 

This should get your project going without any errors. For each area you have you will need to fix the xxxAreaRegistration.vb file as described in the above step(2)