European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFEASP.NET :: Showing Data Changes Using SQLDependency With SignalR In ASP.NET MVC

clock March 18, 2022 07:37 by author Peter

Here, I am using SQLDependency which notifies us when any changes are done to the data in the database. First, you have to add an empty MVC project and after that, add the SignalR Package which can be added by using NuGet Package Manager.

Add a Controller in your project.
public class HomeController : Controller  
    {  
        // GET: Home  
        public ActionResult Index()  
        {  
            return View();  
        }  
        public JsonResult GetMessages()  
        {  
            List<data> messages = new List<data>();  
            Repository r = new Repository();  
            messages = r.GetAllMessages();  
            return Json(messages,JsonRequestBehavior.AllowGet);  
        }  
    }

Now, add a new class and name it as Repository.
public class Repository  
    {  
        SqlConnection co = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["con"].ConnectionString);  
        public List<data> GetAllMessages()  
        {  
            var messages = new List<data>();  
            using (var cmd = new SqlCommand(@"SELECT [id],   
                [name],[adres] FROM [dbo].[userdata]", co))  
            {  
                SqlDataAdapter da = new SqlDataAdapter(cmd);  
                var dependency = new SqlDependency(cmd);  
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);  
                DataSet ds = new DataSet();  
                da.Fill(ds);  
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)  
                {  
                    messages.Add(item: new data  
                    {  
                        id = int.Parse(ds.Tables[0].Rows[i][0].ToString()),  
                        name = ds.Tables[0].Rows[i][1].ToString(),  
                        adres = ds.Tables[0].Rows[i][2].ToString()  
                    });  
                }  
            }  
            return messages;  
        }  
 
        private void dependency_OnChange(object sender, SqlNotificationEventArgs e) //this will be called when any changes occur in db table.
        {  
            if (e.Type == SqlNotificationType.Change)  
            {  
                MyHub.SendMessages();  
            }  
        }  
    }

In Models folder, add a class and name it as data.
public class data  
   {  
       public int id { get; set; }  
       public string name { get; set; }  
       public string adres { get; set; }  
   }


Here, you have to add a SignalR Hub Class to you project and name it as MyHub.
[HubName("MyHub")]  
   public class MyHub : Hub  
   {  
 
       [HubMethodName("sendMessages")]  
       public static void SendMessages()  
       {  
           IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();  
           context.Clients.All.updateMessages();  
       }  
   }

Again, you have to add another class named OWIN Startup Class.
public class Startup  
   {  
       public void Configuration(IAppBuilder app)  
       {  
          // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888  
         app.MapSignalR();  
       }  
   }


View(Index)
@{  
    Layout = null;  
}  
 
<!DOCTYPE html>  
 
<html>  
<head>  
    <meta name="viewport" content="width=device-width" />  
    <title>Index</title>  
    <script type="text/javascript" src="~/Scripts/jquery-1.6.4.min.js"></script>  
    <script type="text/javascript" src="~/Scripts/jquery.signalR-2.2.2.js"></script>  
    <script type="text/javascript" src="/signalr/hubs"></script>  
    <script type="text/javascript">  
    $(function () {  
        // Declare a proxy to reference the hub.  
        var notifications = $.connection.MyHub;  
 
        //debugger;  
        // Create a function that the hub can call to broadcast messages.  
        notifications.client.updateMessages = function () {  
            getAllMessages()  
 
        };  
        // Start the connection.  
        $.connection.hub.start().done(function () {  
            alert("connection started")  
            //notifications.onconn();  
            getAllMessages();  
        }).fail(function (e) {  
            alert(e);  
        });  
    });  
 
    function getAllMessages()  
    {  
        var tbl = $('#messagesTable');  
        $.ajax({  
            url: '/Home/GetMessages',  
            contentType: 'application/html ; charset:utf-8',  
            type: 'GET',  
            dataType: 'html'  
        }).success(function (result) {  
            var a2 = JSON.parse(result);  
            tbl.empty();  
            $.each(a2, function (key, value)  
            {  
                tbl.append('<tr>' + '<td>' +value.id + '</td>' + '<td>' + value.name + '</td>' + '<td>' + value.adres + '</td>' + '</tr>');  
            });  
        })  
    }  
    </script>  
</head>  
<body>  
    <div>   
        <table id="tab">  
             
        </table>  
    </div><br/>  
    <div class="row">  
        <div class="col-md-12">  
            <div >  
                <table border="1">  
                    <thead>  
                        <tr>  
                            <th>id</th>  
                            <th>name</th>  
                            <th>address</th>  
                        </tr>  
                    </thead>  
                    <tbody id="messagesTable">  
 
                    </tbody>  
                </table>  
            </div>  
        </div>  
    </div>  
</body>  
</html>   




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Could Not Find A Part Of The Path... bin\roslyn\csc.exe

clock March 15, 2022 09:20 by author Peter

A fix to Roslyn issue when compiling in .NET Code.

Introduction
This is long existing issue, at least since VS 2015.  There are two possible fixes, one is updating the Roslyn to make the code work, another one is deleting Roslyn.  I prefer the latter and will introduce my solution.

The structure of this article:
    Introduction
    Problem
    Two Possible Fixes
        Update the Roslyn compiler
        Delete the Roslyn compiler
    My Fix

Problem
When running a MVC web application, we got this error message:

Possible Fixes
Search online, we saw two possible solutions in one thread: Could not find a part of the path ... bin\roslyn\csc.exe, the suggestions as below:
Update the Roslyn compiler 


Delete the Roslyn compiler,


 

My Fix
I prefer the latter one. This is my solution:
Search entire solution for Microsoft.CodeDom.Providers.DotNetCompilerPlatform


Search entire solution for Microsoft.Net.Compilers

Open Package Manager Console in Visual Studio:

Run the following command if any one of the above existing,
PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
PM> Uninstall-package Microsoft.Net.Compilers


For ours, we run the first,

Recheck the result,

Microsoft.CodeDom.Providers.DotNetCompilerPlatform is gone,


Recompile and run, the app works.
Check the changes. In Packages.config,

In Web.config,



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Customer Error page In MVC 5.0

clock March 2, 2022 07:25 by author Peter

In this article, we will look at how to manually customize an error page in ASP.NET MVC 5.


MCV Introduction

The MVC architectural pattern separates the user interface (UI) of an application into three main parts.

Model

A set of classes that describes the data you are working with as well as the business logic.

View
Defines how the application’s UI will be displayed. It is pure HTML, which decides how the UI is going to look.

Controller
A set of classes that handles communication from the user, overall application flow, and application-specific logic

When an HTTP request arrives for an MVC application, that request gets routed to a controller, and then it is up to the controller to talk to either the database, the file system, or the model.

Why do we need a Custom Error Page?

We would just configure our custom error pages in one place and it would just work, no matter how/where the error was raised. In order to handle exceptions thrown by your action methods, you need to mark your method with the HandleError attribute. The HandleError attribute also allows you to use a custom page for this error.
Steps to be Followed

Step 1
Create a MVC application named “Http500Test”. For this demo, I have used VS 2019 and .NET version 4.7.2


The solution looks like this

Step 2
Create a Controller class file named “CustomerErrorUserController.cs”

[HandleError] attribute provided built-in exception filters. This attribute can be applied over the action method as well as the controller or at the global level.

At CustomerErrorUser/Index, this application will show error.cshtml as the view not found in Index but in the web.config file. The error statusCode="404" means that the file is not found and it means the controller name or controller action method name is the issue.

[HandleError] //If I put in this attribute and run, it will go to the Customized by a Default error page.

Step 3

Create a controller class named “ErrorController.cs”

I have added two action methods – NotFound() and UnhandledException().

Step 4
Go to View/Shared Folder; create two views named “NotFound.cshtml” and “UnhandledException.cshtml”


Put your own code in the NotFound.cshtml file by removing the existing code.

Put your own code in the UnhandledException.cshtml file by removing the existing code.

Step 5
Go to Web.config and. Add some code for “File Not Found” and “UnhandledException”

Output
http://localhost:63217/CustomeErrorUser

How to display UnhandledException?
I have added two lines of code in the About() action method in HomeController.cs

Now run this MVC app and click on “About”

Instead of redirecting to “UnhandledException.cshtml”, the app is showing error.cshtml file
How to show UnhandledException.cshtml?

Visual Studio, by default, is creating two cshtml files, i.e. _Layout.cshtml and Error.cshtml inside the Shared folder.

Since we are using [HanldeError] attribute, all the unhandled exceptions will be redirected to by default error page (Error.cshtml).

There was some boilerplate code left in the FilterConfig.cs when creating the project.

This creates a new instance of HandleErrorAttribute, which is applied globally to all of my views. With no customization, if a view throws an error while utilizing this attribute, MVC will display the default Error.cshtml file in the Shared folder.

Commenting this line out solved the problem and allowed me to use custom error pages for 500 errors.

Again run the application and click on “About”

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in