Tag Archives: C#

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# – 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}

 

 

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

A potentially dangerous Request.Form value was detected from the client – error in MVC4 in vb.net

In your Create Actions in a Controller in MVC4, if you try to save text with html tags then you get this annoying error.

A potentially dangerous Request.Form value was detected from the client

Description: ASP.NET has detected data in the request that is potentially dangerous because it might include HTML markup or script. The data might represent an attempt to compromise the security of your application, such as a cross-site scripting attack. If this type of input is appropriate in your application, you can include code in a web page to explicitly allow it. For more information, see http://go.microsoft.com/fwlink/?LinkID=212874.

This is a great protection if you do not want your client to save html text.

Here is how to get rid of this error

In the following example we have a create action which saves a new record. MVC4 controller will have two functions.

The first function is for GET ( this is the one which will render the page to save the new record

 

The second function is for POST. This function is responsible to receive the model
which has been populated by the data which the user has filled in on the form. We have to add the following text

<ValidateInput(False)>

 

for C# add

[ValidateInput(false)]

 

 

 

 

‘ GET: /admin/ManageAds/Create

Function Create() As ActionResult
Return View()
End Function

 

 

‘ POST: /admin/ManageAds/Create
<HttpPost()> _
<ValidateAntiForgeryToken()> _
<ValidateInput(False)>
Function Create(ByVal ad As Ad) As ActionResult
If ModelState.IsValid Then
db.Ads.Add(ad)
db.SaveChanges()
Return RedirectToAction(“Index”)
End If

Return View(ad)
End Function

 

How to add Nuget Packages

How to Add Packages using NUGET in Visual Studio

Step 1

In Visual Studio Go to Tools > Library Package Manager > Manage Nuget Packages for Solution.

 

How to add Nuget Packages
How to add Nuget Packages

 

Step 2

You would get the following screen, you can check the packages which you have already available in your solution, you can search for new packages and install them to your solution.

Remember:  These packages need to be downloaded , each time you create a new Visual Studio solution

 

Packages in NUGET
Packages in NUGET

How to fix : Ajax.BeginForm doing full postback instead of partial.

I realised that in my MVC5 project  in Visual Studio I could not get the Ajax.BeginForm to work properly. It will always do a full postback.

 

I was trying to complete a Video Rating Page, where there are buttons to rate a video and once the user presses one of the rating button, it should thank the user and display the new rating value. I wanted this to shown on the same page without reloading the page, So I considered using AJAX.BeginForm which will simply work fine.

 

In order to have this AJAX functionality you will have to download the AJAX from NUGET.

 

Step 1

Install the following two highlighted packages from NUGET. Click here to check how to load Packages from NUGET in Visual Studio

 

Nuget

 

Step 2

Once you have installed the above two packages through NUGET then do the following.

Go to the _Layout file in your _shared  folder in the Views. ( Note that I am using VB.NET but the example will work for C# also.

 

_Layout in the Shared Folder
_Layout in the Shared Folder

 

Open the _Layout.vbhtml file and browse to the bottom.

 

You will see the following two lines.

@Scripts.Render(“~/bundles/jquery”)
@Scripts.Render(“~/bundles/bootstrap”)

 

Now add the following line after the above two lines.
<script src=”~/Scripts/jquery.unobtrusive-ajax.min.js”></script>

 

I made a mistake of adding this script at the top of my page and my AJAX calls refused to work.

Then I realised that the AJAX has to be loaded after loading the jquery. So I added it at the last.

 

 

 

 

AjaxCallsinMVC5
Add the script at the exact position show.

 

 

Step 3

Run your application.

Your AJAX Calls should work fine.