Category Archives: Visual Studio 2013

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

 

Generate RSS Feed in MVC4 using VB.NET

Here is a simple function to generate the RSS feeds.
This article assumes that you are using MVC4 project with Entity Framework. Just iterate through

the relevant table to pick your data which you want to show in the RSS feed.

Remember to add the following import statements at the top of your controller
Imports System.Xml
Imports System.IO

In your controller create a function as shown below. There is no need to create a corresponding View for it

as the function will write to the RESPONSE and the XML output will be provided by the XMLTextWriter.

Function RSSNewArticles() As Action

Response.Clear()
Response.ContentType = “text/xml”
Dim objX As New XmlTextWriter(Response.OutputStream, Encoding.UTF8)
objX.WriteStartDocument()
objX.WriteStartElement(“rss”)
objX.WriteAttributeString(“version”, “2.0”)
objX.WriteStartElement(“channel”)
objX.WriteElementString(“title”, “MyWebsite.com RSS Feed“)
objX.WriteElementString(“link”, “http://mywebsite.com“)
objX.WriteElementString(“description”, “My website New Articles Feed“)
‘ objX.WriteElementString(“copyright”, “(c) 2014, best-answer.net“)
objX.WriteElementString(“ttl”, “10”)

‘Populate record for the RSS feed

For Each item In db.MyDataTable
objX.WriteStartElement(“item”)
objX.WriteElementString(“title”, item.CatName)
objX.WriteElementString(“link”, “http://mywebsite/” & item.RecordID & “/” & item.TitleName)
objX.WriteElementString(“pubDate”, Now)
objX.WriteEndElement()
Next

objX.WriteEndElement()
objX.WriteEndElement()
objX.WriteEndDocument()
objX.Flush()
objX.Close()
Response.End()
End Function

How to download a file in MVC4 using VB.NET

How to allow File Downloads in MVC4 using VB.NET

We are using an ActionResult instead of FileResult.

Function download(id as Integer) As ActionResult

The reason is that if use the FileResult and your file does not exist then it will show a blank page, instead of this

we are using an ActionResult which is more versatile.
We can return the actual FileResult if the file exists
and in case of an error we can return a View (if we used a FileResult

Function download(id as Integer) As ActionResult

‘ In this example we are using the id to pick up the actual file from a model

Dim SoundFile as SoundFile = db.SoundFiles.Find(id)

Dim path As String = Server.MapPath(“~/myLocation/” & SoundFile.MP3File)

‘get file object as FileInfo
Dim fileinfo As System.IO.FileInfo = New System.IO.FileInfo(path)

‘– if the file exists on the server

If fileinfo.Exists Then
rep.IncrementDownloadCount(id) ‘This is my routine to count the downloads, you will not need it
Return File(path, “application/octet-stream”, fileinfo.Name)
Else
Return View(“Error”)
End If

End Function

Area not working in MVC4 project in VB.NET

If you have had experience this problem then read ahead it is a simple fix.

 

Here are the step to reproduce this problem in Visual Studio

 

Here is what happened, I had a MVC4 project which was working fine. I created a new area called Admin.

Created a new controller and a view in the admin area. But when calling this view, it would give 404 error.

Tried few things and did some research on the net as usual.

 

Here is the simple fix which seems to work.

Go to your controller and add the namespace at the top . Just after the imports. Note that admin is the name of my area.

Change it according to your area name

 

Step 1

Imports System.Data.Entity

Namespace Areas.admin

You controller code is here

End Namespace

 

Step 2

Go to your Area and look for a file called

adminAreaRegistration.vb ( again admin is my area name, if your area is called sales then you should have a file called sales
AreaRegistration.vb. And your namespace will be Areas.sales.)

Ensure that the name space which you have in your controller  and the adminAreaRegistrarion.vb is the same

Namespace Areas.admin
Public Class adminAreaRegistration
Inherits AreaRegistration

Public Overrides ReadOnly Property AreaName() As String
Get
Return “admin”
End Get
End Property

Public Overrides Sub RegisterArea(ByVal context As System.Web.Mvc.AreaRegistrationContext)
context.MapRoute( _
“admin_default”, _
“admin/{controller}/{action}/{id}”, _
New With {.action = “Index”, .id = UrlParameter.Optional} _
)
End Sub
End Class
End Namespace

How to loop through records in LINQ using VB.NET in Entity Framework

Here is a simple code snippet to loop through the records in VB.NET using LINQ

 

The following code example takes the records from an Entity Framework Model named as Video and then allows to loop through each record.

 

 

Dim List As List(Of Video)

List = (From video In db.Videos Order By video.ID Descending).ToList
For Each item In List
Debug.Print(item.CategoryID)
Debug.Print(item.VideoName)
Next

Programatically fill DataGridView using Entity Framework in VB.NET

It is quite easy to fill the DataGridView programatically in VB.NET.

There is no need to use the dataset, Data navigator and other such controls.

Here is an example/

There is a Model called Video already defined in my project and I need to display them in a datagrid view.

For the purpose of demonstrating I have kept it simple but we can use LINQ to build a complex query and then return that and display in the DataGridView.

 

 Private Sub frmVideoBrowse_Load(sender As Object, e As EventArgs) Handles MyBase.Load

Me.DataGridView1.DataSource = GetVideos()

End Sub
Function GetVideos() As List(Of Video)
Dim db As New Entities
Dim resultlist As List(Of Video)
resultlist = db.Videos.ToList()
Return resultlist
End Function

How to use PagedList.MVC in MVC5 using VB.NET

Installed the PagedList.MVC  in your project using the NuGET

This is the ASP.NET Syntax

In your Controller

Here

At the top of the Controller add the following two imports

Imports PagedList
Imports PagedList.Mvc

 

Here is a sample ViewResult

Function NewVideos(Optional ByVal Page As Integer = 1) As ViewResult
Dim videos = rep.GetNewVideos.ToPagedList(Page, 10)  ‘ Code to get your data  use your own

ViewBag.CurrentSort = videos
Return View(videos)

End Function

 

In your View

At the top of the page add the following imports

<%@ import Namespace=”PagedList” %>
<%@ import NameSPace=”PagedList.Mvc” %>

 

Where you want the Pager to appear add the following code. Customize it according to your need.

 

<%: Html.PagedListPager(DirectCast(ViewBag.CurrentSort, IPagedList), Function(page) Url.Action(“newvideo“, New With {.page = page}), PagedListRenderOptions.OnlyShowFivePagesAtATime)%>

How to embed a YouTube Video in MVC5 in ASP.NET

Here is one simple way of embedding the Youtube Video in your MVC5 Page in Visual Studio.

Infact this method will work on any HTML Page.

 

1. First you need a YouTube Video. Go to YouTube and find a Video which you want to display. Copy the URL which is displayed in the browser address bar.

You would have a URL like the following one

https://www.youtube.com/watch?v=dwqDGLQIINY

 

 

2.You can simply embed this video on your page using the following script

           <iframe width=”560″
height=”315″
src=”http://www.youtube.com/embed/dwqDGLQIINY
frameborder=”0″
allowfullscreen>

</iframe>

 

 

3. If you would also like to display the default image of the YouTube Video then you can use the following script.

 

<img src=”http://i3.ytimg.com/vi/dwqDGLQIINY/mqdefault.jpg”/>

If you are displaying a number of videos or a video gallery then simply replace the Video IDs (shown in red) for each of the video.

 

 

There are so many other ways to embed the YouTube videos, but I find this is the easiest and suitable for my needs.

 

 

 

 

How to pass a variable from one winform to another in vb.net

There is often a need to pass a variable from one Winform to another.

There are two scenarios

Let us say you have two forms

1. You opened Form1 and then you want to open a new form called Form2 and you would want to carry some information from Form 1 to Form2.

The user has typed the Employee name  JOHN in the text box on the first form and then clicked on the Lookup Dept. This openes the second lookup form (Form2) where the user can select a Dept Name.

Notice that on the Form2 we have the Employee Name shown ( form1 opened  form2 and passed the value of EmployeeName)

SendVariablefromForm1ToForm2

2. You  have Form1 and Form2 already open and you want to pass a variable from Form2 to Form1

 

Once we select the Dept B on the Form 2 we click on Select and close. The second form (Form2) closes and the value of the selected department Dept B is passed back to the First form (Form1)

 

SendVariablefromForm2toForm1

 

Here is the code for the Form1

 

Public Class Form1
WithEvents fr As New Form2   ‘ Declare the new form using WithEvents
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
fr.lblEmployeeName.Text = Me.TextBox1.Text  ‘ Send the value of Textbox1 to the second Form
fr.Show()
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub fr_GetDepartment() Handles fr.GetDepartment   ‘ This is the new Event which has been declared and raised from Second Form

Me.TextBox2.Text = fr.ListBox1.SelectedItem.ToString  ‘ The Listbox selected item value has been received from the second form

End Sub
End Class

Here is the code for Form2

 

 

Public Class Form2
Event GetDepartment()   ‘ You declare this Event for this Form which can be trapped from Form1
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With Me.ListBox1
.Items.Add(“Dept A”)
.Items.Add(“Dept B”)
.Items.Add(“Dept C”)
End With
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RaiseEvent GetDepartment()   ‘ We raise the event here in Form2 which will provide you an opportunity to trap it in Form1
Me.Close()
End Sub
End Class