Thursday 28 January 2016

MVC - How to fix error - An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code

Watch this example on YouTube:




An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.


this line is causing this error:
emp = emp.Where(s => s.HireDate.ToString().Trim().Equals("1/1/2015"));

to fix it replace
   var emp = from s in db.Employees
                      select s;
with
 
    var rawData = (from s in db.Employees
                           select s).ToList();

            var emp = from s in rawData
                      select s;

Wednesday 27 January 2016

C# - fix the following error - The best overloaded method match for 'string.Split(params char[])' has some invalid arguments

Watch this on YouTube:


The best overloaded method match for 'string.Split(params char[])' has some invalid arguments  
Argument 1: cannot convert from 'string' to 'char[]'


To fix it, replace
         string test = "";
         string test2 = test.Split("|")[0];

with
         string test = "";
            string test2 = test.Split('|')[0];






Saturday 23 January 2016

MVC - Sorting and filtering by each column - add drop down list to the header

Watch this example on YouTube:
1. create new MVC project
2. add Entity Model to it with 1 table - here is my simple table




3. Rebuild project
4. Add controller
5. Change route config to the new controller, run project to test
6. modify header in Index file, add html.actionlinks to it
@model IEnumerable<MVCSortAndFilter.Models.Employee>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    @using (Html.BeginForm("Index", "Employee", FormMethod.Get))
    {
        <tr>
            <th>
                @Html.ActionLink("First Name", "Index",
                new { SortOrder =ViewBag.FirstName})
            </th>
            <th>
                @Html.ActionLink("Last Name", "Index",
                new { SortOrder = ViewBag.LastName})
            </th>
            <th></th>
        </tr>
7. Modify controller index, ensure it looks like this
        public ActionResult Index(string SortOrder, string SelectedFirstName, string SelectedLastName)
        {
            ViewBag.FirstName = String.IsNullOrEmpty(SortOrder) ? "FirstName_desc" : "";
            ViewBag.LastName = SortOrder == "LastName" ? "LastName_desc" : "LastName";

            var emp = from s in db.Employees
                      select s;

            switch (SortOrder)
            {
                case "FirstName_desc" :
                    emp = emp.OrderByDescending(s => s.FirstName);
                    break;
                case "LastName":
                    emp = emp.OrderBy(s => s.LastName);
                    break;
                case "LastName_desc":
                    emp = emp.OrderByDescending(s => s.LastName);
                    break;
                default:
                    emp = emp.OrderBy(s => s.FirstName);
                    break;
            }

            return View(emp.ToList());
        }

8. Now we have sorting completed.  Run the project to test
Now - let's add filtering
Ensure Index view looks like this:
@model IEnumerable<MVCSortAndFilter.Models.Employee>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    @using (Html.BeginForm("Index", "Employee", FormMethod.Get))
    {
        <tr>
            <th>
                @Html.ActionLink("First Name", "Index",
                new { SortOrder =ViewBag.FirstName,
                    SelectedFirstName = ViewBag.SelectedFirstName, SelectedLastName = ViewBag.SelectedLastName})
            </th>
            <th>
                @Html.ActionLink("Last Name", "Index",
                new { SortOrder = ViewBag.LastName,
                      SelectedFirstName = ViewBag.SelectedFirstName,
                      SelectedLastName = ViewBag.SelectedLastName
                })
            </th>
            <th></th>
        </tr>
        <tr>
            <th>
                @Html.DropDownList("SelectedFirstName",
                new SelectList(ViewBag.UniqueFirstNames, "Value", "Text", "ViewBag.SelectedFirstName"),
                "All", new {onchange = "form.submit();"})
            </th>
            <th>
                @Html.DropDownList("SelectedLastName",
                new SelectList(ViewBag.UniqueLastNames, "Value", "Text", "ViewBag.SelectedLastName"),
             "All", new { onchange = "form.submit();"})
            </th>
        </tr>
    }


@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>
9. Modify controller, ensure it looks like this:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCSortAndFilter.Models;

namespace MVCSortAndFilter.Controllers
{
    public class EmployeeController : Controller
    {
        private TESTEntities db = new TESTEntities();

        //
        // GET: /Employee/

        public ActionResult Index(string SortOrder, string SelectedFirstName, string SelectedLastName)
        {
            ViewBag.FirstName = String.IsNullOrEmpty(SortOrder) ? "FirstName_desc" : "";
            ViewBag.LastName = SortOrder == "LastName" ? "LastName_desc" : "LastName";

            var rawData = (from s in db.Employees
                           select s).ToList();
            var emp = from s in rawData
                      select s;

            if (!String.IsNullOrEmpty(SelectedFirstName))
            {
                emp = emp.Where(s => s.FirstName.Trim().Equals(SelectedFirstName.Trim()));
            }
            if (!String.IsNullOrEmpty(SelectedLastName))
            {
                emp = emp.Where(s => s.LastName.Trim().Equals(SelectedLastName.Trim()));
            }

            var UniqueFirstNames = from s in emp
                                   group s by s.FirstName into newGroup
                                   where newGroup.Key != null
                                   orderby newGroup.Key
                                   select new { FirstName = newGroup.Key };
            ViewBag.UniqueFirstNames = UniqueFirstNames.Select(m => new SelectListItem { Value = m.FirstName, Text = m.FirstName }).ToList();

            var UniqueLastNames = from s in emp
                                  group s by s.LastName into newGroup
                                  where newGroup.Key != null
                                  orderby newGroup.Key
                                  select new { LastName = newGroup.Key };
            ViewBag.UniqueLastNames = UniqueLastNames.Select(m => new SelectListItem { Value = m.LastName, Text = m.LastName }).ToList();

            ViewBag.SelectedFirstName = SelectedFirstName;
            ViewBag.SelectedLastName = SelectedLastName;

            switch (SortOrder)
            {
                case "FirstName_desc" :
                    emp = emp.OrderByDescending(s => s.FirstName);
                    break;
                case "LastName":
                    emp = emp.OrderBy(s => s.LastName);
                    break;
                case "LastName_desc":
                    emp = emp.OrderByDescending(s => s.LastName);
                    break;
                default:
                    emp = emp.OrderBy(s => s.FirstName);
                    break;
            }

            return View(emp.ToList());
        }

        //
        // GET: /Employee/Details/5

        public ActionResult Details(int id = 0)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        //
        // GET: /Employee/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Employee/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(employee);
        }

        //
        // GET: /Employee/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        //
        // POST: /Employee/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Entry(employee).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        //
        // GET: /Employee/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        //
        // POST: /Employee/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Employee employee = db.Employees.Find(id);
            db.Employees.Remove(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

Run to test

Thursday 21 January 2016

MVC - create button with action link


Watch this example on YouTube

<button type="button" onclick="location.href='@Url.Action("Register","Account")'">REGISTER</button>

the code above will call register method in Account controller

Wednesday 20 January 2016

MVC - Error Handling - How to create default custom error page

Watch this example on YouTube:


here are the steps from the video above
1. Rename Shared\Error.cshtml to Shared\_Error.cshtml
2. add the following method to global.asax.cs file
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exc = Server.GetLastError();
            Server.ClearError();
            Response.Redirect("/ErrorPage/ErrorMessage");
        }
3. create new controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication3.Controllers
{
    public class ErrorPageController : Controller
    {
        //
        // GET: /ErrorPage/

        public ActionResult ErrorMessage()
        {
            return View();
        }

    }
}
4. create new view
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication3.Controllers
{
    public class ErrorPageController : Controller
    {
        //
        // GET: /ErrorPage/

        public ActionResult ErrorMessage()
        {
            return View();
        }

    }
}
5. add the following code to home controller to cause error
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            int x = 2;
            if (x == 2)
            {
                throw new Exception("test");
            }
           
            return View();
        }

How to fix error - JavaScript runtime error: Unable to set property 'className' of undefined or null reference


Watch this example on YouTube:

To illustrate the issue here are my components involved in it
1. CSS
.ShowForm{
    border: 2px;
    visibility: visible;
    background-color: red;
    width:100px;
    top:200px;
    height:100px;
    left:100px;
}
.HideForm {
    visibility:hidden;
}


2. Html

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="JavaScriptPopup.aspx.vb" Inherits="VBTest.JavaScriptPopup" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="Styles/StyleSheet1.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
        <div class="HideForm" id="showDiv">
        </div>

        <div><asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click" >Show Form</asp:LinkButton></div>
    </form>
</body>
</html>

3.Code Behind

Public Class JavaScriptPopup
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub LinkButton1_Click(sender As Object, e As EventArgs) Handles LinkButton1.Click
        Dim sbTest As New StringBuilder()
        sbTest.Append("<script type=""text/javascript"">")
        sbTest.Append("document.getElementById('showDIV').className='ShowForm';")
        sbTest.Append("</script>")
        Page.ClientScript.RegisterStartupScript(Page.[GetType](), "show me", sbTest.ToString(), False)
    End Sub
End Class





to fix it replace
  sbTest.Append("document.getElementById('showDIV').className='ShowForm';")
with
  sbTest.Append("document.getElementById('showDiv').className='ShowForm';")

Tuesday 19 January 2016

JavaScript runtime error: Unable to get property 'TextBox1' of undefined or null reference

watch this example on YouTube:



to fix this error replace

    <script lang="javascript" type="text/javascript">
        function ValidateTextBox() {
            alert(document.Form1.TextBox1.value);
        }
    </script>
with:
    <script lang="javascript" type="text/javascript">
        function ValidateTextBox() {
            alert(document.getElementById('TextBox1').value);
        }
    </script>

Friday 15 January 2016

MSSQL - How to check if stored procedure exists, and if exists display its definition

Watch this example on YouTube:


If Exists(Select * from sys.objects where type = 'P' and name = 'spTest')
select OBJECT_DEFINITION (Object_Id(N'spTest'));

MVC - How to get Yahoo financial data

watch this example on YouTube:


1. Modify Web.Config, add:
  <system.net>
    <defaultProxy useDefaultCredentials="true"></defaultProxy>
  </system.net>

2. add StockInfo class to Models folder:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _MvcApplicationYahooTest2.Models
{
    public class StockInfo
    {
        public string Symbol { get; set; }
        public decimal AverageVolume { get; set; }
        public decimal LastTradePrice { get; set; }
    }
    public static class YahooFinance
    {
        public static List<StockInfo> Parse(string csvData)
        {
            try
            {
                List<StockInfo> stocks = new List<StockInfo>();
                string[] rows = csvData.Replace("r", "").Replace("\"", "").Split('\n');
                foreach (string row in rows)
                {
                    if (string.IsNullOrEmpty(row)) continue;
                    string[] cols = row.Split(',');
                    StockInfo s = new StockInfo();
                    s.Symbol = cols[0].Trim();
                    s.AverageVolume = Convert.ToDecimal((cols[1] == "N/A") ? "0" : cols[1]);
                    s.LastTradePrice = Convert.ToDecimal((cols[2] == "N/A") ? "0" : cols[2]);
                    stocks.Add(s);
                }
                return stocks;
            }
            catch (Exception ex)
            {
                //handle error
                string error = ex.Message.ToString();
            }
            return null;
        }
    }
}
3. View will look like this:

@model List<_MvcApplicationYahooTest2.Models.StockInfo>
          
<table>
    <tr>
        <th>---------SYMBOL-----------------------</th>
        <th>---------AVG VOLUME-------------------</th>
        <th>---------LAST TRADE PRICE-------------</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.Symbol)</td>
            <td>@Html.DisplayFor(modelItem => item.AverageVolume)</td>
            <td>@Html.DisplayFor(modelItem => item.LastTradePrice)</td>
        </tr>
    }
</table>

4. finally - controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Net;
using _MvcApplicationYahooTest2.Models;
using System.Text;
using System.IO;

namespace _MvcApplicationYahooTest2.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            string csvData;
            string symbols = "GOOG, IBM, FB";
            using (WebClient web = new WebClient())
            {
                csvData = web.DownloadString("http://finance.yahoo.com/d/quotes/csv?s=" + symbols + "&f=sa2l1");
                List<StockInfo> stocks = YahooFinance.Parse(csvData);
                return View(stocks);
            }
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

Wednesday 13 January 2016

Javascript - How to open default mail client using ScriptManager


Watch this example on YouTube:


the following code will open default mail client on local computer and will prepare email to
somename@somename.com

ScriptManager.RegisterStartupScript(Me.Page, Me.Page.[GetType](), "some status",
                        "javascript:window.location.href = 'mailto:somename@somename.com';", True)

JavaScript - How to fix (remove) syntax error in .Net 4.0 in comments


Watch this example on YouTube:



recently, after converting some code from older version to .Net 4.0 I noticed the following error











to fix it replace

      <title></title>
    <script type="text/javascript"> <!--
        DoSomething();

        function DoSomething() {
            alert("doing something");
        }
   --></script>
</head>

with

    <title></title>
    <script type="text/javascript"> <!--
        DoSomething();

        function DoSomething() {
            alert("doing something");
        }
 //  --></script>
</head>