Tuesday 23 July 2019

MSSQL - How to exit stored procedure

Watch this example on YouTube


 
Replace

ALTER PROCEDURE spTestExit
AS
BEGIN
    SET NOCOUNT ON;

    Select * from TestTable
END
GO

exec spTestExit 'sss'
exec spTestExit null

With

ALTER PROCEDURE spTestExit
    @Name varchar(50)
AS
BEGIN
    SET NOCOUNT ON;

    if @Name Is null
    Begin
        Return
    End


    Select * from TestTable
END
GO

exec spTestExit 'sss'
exec spTestExit null

Saturday 20 July 2019

MSSQL - Fix Error - - Unable to modify table. Cannot insert the value NULL into column 'Address', table 'Company.dbo.Tmp_TestTable'; column does not allow nulls. INSERT fails. The statement has been terminated.


Watch this example on YouTube



'TestTable' table
- Unable to modify table. 
Cannot insert the value NULL into column 'IsActive', table 'Company.dbo.Tmp_TestTable'; column does not allow nulls. INSERT fails.
The statement has been terminated.


to fix it do it manually
Update TestTable Set IsActive = 1 where  IsActive is null

Alter Table TestTable
Alter Column IsActive bit Not Null

MSSQL - Fix Error - There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.


Watch this example on YouTube



There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.

To fix it replace
  Insert Into TestTable (ID, Name) Values (1, 'aaa', 'bbb')
with  
  Insert Into TestTable (ID, Name) Values (1, 'aaa')

C# - Convert DateTime to Month Year - like December 2019

Watch this example on YouTube


  


 string ConvertedDT = DateTime.Now.ToString("MMMM") + " " + DateTime.Now.Year.ToString();
     

C# - Fix Error - Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type

Watch this example on YouTube


To Fix it replace
  Decimal Rate = 1.0000;
with
 Decimal Rate = 1.0000M;

C# - Fix Error - Index and length must refer to a location within the string. - Check against string length

Watch this example on YouTube


Fix error

An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code

Additional information: Index and length must refer to a location within the string.

To fix it replace 

  string s1 = "ab";
  string s2 = s1.Substring(0, 100);
          
with

  string s1 = "ab";
  string s2 = s1.Substring(0, s1.Length> 100 ? 100: s1.Length);

Friday 28 June 2019

MVC - WCF - Create and consume WCF Service with data from EF

Watch this example on YouTube


1. SQL 

USE [Company]
GO
/****** Object:  Table [dbo].[Product]    Script Date: 2019-06-28 9:34:42 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Product](
    [ProductID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL
) ON [PRIMARY]

GO
SET IDENTITY_INSERT [dbo].[Product] ON

GO
INSERT [dbo].[Product] ([ProductID], [Name]) VALUES (1, N'Table')
GO
INSERT [dbo].[Product] ([ProductID], [Name]) VALUES (2, N'Something Else')
GO
INSERT [dbo].[Product] ([ProductID], [Name]) VALUES (3, N'Sofa')
GO
INSERT [dbo].[Product] ([ProductID], [Name]) VALUES (4, N'Chair')
GO
INSERT [dbo].[Product] ([ProductID], [Name]) VALUES (5, N'Laptop')
GO
INSERT [dbo].[Product] ([ProductID], [Name]) VALUES (6, N'Mouse')
GO
INSERT [dbo].[Product] ([ProductID], [Name]) VALUES (7, N'Keyboard')
GO
INSERT [dbo].[Product] ([ProductID], [Name]) VALUES (8, N'Monitor')
GO
SET IDENTITY_INSERT [dbo].[Product] OFF
GO

2. IService1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService2
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        [OperationContract]
        List<Product> GetAllProducts();
        [OperationContract]
        string GetSomething();
    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}
3. Service1.svc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService2
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        public string GetSomething()
        {
            return "something";
        }
        public List<Product> GetAllProducts()
        {
            List<Product> prodList = new List<Product>();
            CompanyEntities db = new CompanyEntities();
            var res = from p in db.Products select p;
            foreach(var item in res)
            {
                Product pr = new Product();
                pr.Name = item.Name;
                pr.ProductID = item.ProductID;
                prodList.Add(pr);

            }
            return prodList;
        }
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}
4. Consumer (home controller)

        public ActionResult Index()
        {
            List<Product> lstProd = new List<Product>();
            ServiceReference1.Service1Client s = new ServiceReference1.Service1Client();
            var res2 = s.GetSomething();
            var res = s.GetAllProducts();
            foreach(var item in res)
            {
                Product pr = new Product();
                pr.ProductID = item.ProductID;
                pr.Name = item.Name;
                lstProd.Add(pr);
            }
            return View(lstProd);
        }

Thursday 20 June 2019

MVC - Consume Web Service (Service Reference, WCF)

Watch this example on YouTube


1. Services:
http://www.dneonline.com/calculator.asmx
http://services.aonaware.com/DictService/DictService.asmx

2. Home Controller

  MyServiceRefrence.CalculatorSoapClient ws = new MyServiceRefrence.CalculatorSoapClient();
            var res = ws.Add(2, 4);

Microsoft Internet Explorer - Fix Issue with XML not showing in proper format or not showing all data

Watch this example on YouTube

to fix it replace

<root>
<name>
    <first>Bob</first>
    <last>Doe</last>
</name>
<name>
    <first>John</first>
    <last>Lennon</last>
</name>
<name>
    <first>Bob</first>
    <last>Doe</last>
</name>
<name>
    <first>John</first>
    <last>Lennon</last>
</name>
</root>

with

<root>
<name>
    <first>Bob</first>
    <last>Doe</last>
</name>
<name>
    <first>John</first>
    <last>Lennon</last>
</name>
<name>
    <first>Bob</first>
    <last>Doe</last>
</name>
<name>
    <first>John</first>
    <last>Lennon</last>
</name>
</root>

Wednesday 19 June 2019

Opera - Fix error - Extra content at the end of the document Below is a rendering of the page up to the first error.


Watch this example on YouTube

This page contains the following errors:

error on line 5 at column 1: Extra content at the end of the document

Below is a rendering of the page up to the first error.

 

To fix it replace


<name>
<first>Bob</first>
<last>Doe</last>
</name>
<name>
<first>John</first>
<last>Lennon</last>
</name>

 

with

 <root>
<name>
<first>Bob</first>
<last>Doe</last>
</name>
<name>
<first>John</first>
<last>Lennon</last>
</name>

</root>

C# - Fix Error - Guid.NewGuid()' is a method, which is not valid in the given context


Watch this example on YouTube


Guid.NewGuid()' is a method, which is not valid in the given context
also
The name 'guid' does not exist in the current context

To fix it replace

string test = guid.NewGuid.ToString();
wtih
string test = Guid.NewGuid().ToString();

Tuesday 18 June 2019

Mozilla Firefox - Fix Error - XML Parsing Error junk after document element with comments

Watch this example on YouTube


 
to fix it replace

<name>
    <first>Bob</first>
    <last>Doe</last>
</name>
<name>
    <first>John</first>
    <last>Lennon</last>
</name>

with

<root>
<name>
    <first>Bob</first>
    <last>Doe</last>
</name>
<name>
    <first>John</first>
    <last>Lennon</last>
</name>
</root>

Friday 14 June 2019

MVC - Web Service - Create Web Service - Pass XML file (not string) as Parameter and Receive XML file (not string) in Web Service

Watch this example on YouTube



1. Web Service

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

namespace WebApplication15
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public string XMLTest(XmlDocument doc)
        {
            var xmlString = doc.InnerText;
            return "success";
        }

    }
}

2. Consumer

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

namespace WebApplication16.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            XmlDocument doc = new XmlDocument();
            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(docNode);

            XmlNode usersNode = doc.CreateElement("Users");
            doc.AppendChild(usersNode);

            XmlNode userNode = doc.CreateElement("User");
            XmlAttribute userAttribute = doc.CreateAttribute("ID");
            userAttribute.Value = "1";
            userNode.Attributes.Append(userAttribute);
            usersNode.AppendChild(userNode);

            XmlNode nameNode = doc.CreateElement("Name");
            nameNode.AppendChild(doc.CreateTextNode("Frank"));
            userNode.AppendChild(nameNode);
            XmlNode addressNode = doc.CreateElement("Address");
            addressNode.AppendChild(doc.CreateTextNode("1 Main St."));
            userNode.AppendChild(addressNode);

            localhost.WebService1 testService = new localhost.WebService1();
            var res = testService.XMLTest(doc);

            return View();
        }

MVC - Add simple java script to MVC View

Watch this example on YouTube


@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>
            ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
            enables a clean separation of concerns and gives you full control over markup
            for enjoyable, agile development.
        </p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Get more libraries</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p>
    </div>
</div>

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            alert("here you go!!!");
        });

    </script>   
}

MVC - Web Service - Catch Timeout exception

Watch this example on YouTube


 

  localhost.WebService1 test = new localhost.WebService1();
            test.Timeout = 1000;
            try
            {
                var res = test.HelloWorld();
            }
            catch (System.Net.WebException e) when (e.Status == System.Net.WebExceptionStatus.SecureChannelFailure)
            {
                string error = e.Message;
            }

            catch(Exception e)
            {
                string error = e.Message;
            }

MVC - Web Service - Increase time limit on response from a web service


Watch this example on YouTube

  

            localhost.WebService1 test = new localhost.WebService1();
            test.Timeout = 4000;
            var res = test.TestMethod("Some String");

            return View();

Thursday 13 June 2019

MVC - Web Service - Create Web Service - Pass XML as Parameter and Receive XML in Web Service


Pass xml file (created on the fly) to web service

Watch this example on YouTube


 
1. Publisher

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

namespace WebApplication13
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public string TextXML(string xmlFile)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlFile);
            // here do whatever you want with xml file
            return "success";
        }
    }
}

2. Subscriber

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

namespace WebApplication14.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            XmlDocument doc = new XmlDocument();
            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(docNode);

            XmlNode usersNode = doc.CreateElement("Users");
            doc.AppendChild(usersNode);
            XmlNode userNode = doc.CreateElement("User");
            XmlAttribute userAttribute = doc.CreateAttribute("ID");
            userAttribute.Value = "1";
            usersNode.AppendChild(userNode);

            XmlNode nameNode = doc.CreateElement("Name");
            nameNode.AppendChild(doc.CreateTextNode("Frank"));
            userNode.AppendChild(nameNode);
            XmlNode addressNode = doc.CreateElement("Address");
            addressNode.AppendChild(doc.CreateTextNode("1 Main St."));
            userNode.AppendChild(addressNode);

            var XMLString = doc.InnerXml;

            localhost.WebService1 test = new localhost.WebService1();
            var res = test.TextXML(XMLString);

            return View();
        }

MVC - Simple Web Service Example - Create and Consume web service in less then 4 minutes

Watch this example on YouTube



1. Publisher

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

namespace WebApplication11
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public int Add2Numbers(int n1, int n2)
        {
            return n1 + n2;
        }
    }
}
2. Consumer
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            localhost.WebService1 test = new localhost.WebService1();
            var res = test.Add2Numbers(2, 5);
            return View();
        }

Wednesday 12 June 2019

C# - Remove all commas

Watch this example on YouTube

       


string a = "a,a a,,d,";
            a = a.Replace(",", "");

Tuesday 11 June 2019

Visual Studio - Find empty lines

Watch this solution on YouTube


 
 
Select Regular expressions and search for: 
^(?([^\r\n])\s)*\r?$\r?\n

ASP.NET - JavaScript - Fix Error - JavaScript runtime error: Unable to set property 'IsValid' of undefined or null reference

0x800a138f - JavaScript runtime error: Unable to set property 'IsValid' of undefined or null reference

Watch this example on YouTube




to fix it replace

   <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Validate();" />

with

   <asp:Button ID="Button1" runat="server" Text="Button" />

Whole code:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ASPApplication._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem>Test 1</asp:ListItem>
        <asp:ListItem>Test 2</asp:ListItem>
    </asp:DropDownList>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Validate();" />

    <asp:ValidationSummary runat="server" HeaderText="Fix the following:" ShowMessageBox="true"
         ValidationGroup="MyValidationGroup" />
    <asp:CustomValidator runat="server" ErrorMessage="Something went wrong"
         ClientValidationFunction="Validate" ValidationGroup="MyValidationGroup" >

    </asp:CustomValidator>

    <script lang="javascript" type="text/javascript">
        function Validate(source, args) {
            var e = document.getElementById('<%= DropDownList1.ClientID %>')
            var str = e.options[e.selectedIndex].text;
            if (str != "") {
                args.IsValid = true;
            }
            else {
                args.IsValid = false;
            }
        }
    </script>
</asp:Content>

Monday 10 June 2019

C# - Check if string is an integer and if yes - assign it's value to int variable

Watch this example on YouTube

     

  string SomeValue = "33";
            int Result;
            string Message;
            if (int.TryParse(SomeValue, out Result))
            {
                Message = "it is integer";
            }
            else
            {
                Message = "no it is not";
            }

ASP.NET - Javascript - Fix Error 'Page_ClientValidate' is undefined

Watch this example on YouTube




To fix it replace

   <script lang="javascript" type="text/javascript">
        function Validate() {
            debugger;
            try {
                var result = Page_ClientValidate('Test');
                return result;
            }
            catch (Error) {
                return true;
            }
        }
    </script>

with


    <title></title>
        <script lang="javascript" type="text/javascript">
        function Validate() {
            debugger;
            try {
                if (typeof (Page_ClientValidate) === 'function') {
                    var result = Page_ClientValidate('Test');
                    return result;
                }
                else {
                    return true;
                }

            }
            catch (Error) {
                return true;
            }
        }
    </script>


whole code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ASPApplication.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        <script lang="javascript" type="text/javascript">
        function Validate() {
            debugger;
            try {
                if (typeof (Page_ClientValidate) === 'function') {
                    var result = Page_ClientValidate('Test');
                    return result;
                }
                else {
                    return true;
                }
            }
            catch (Error) {
                return true;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server" onsubmit="return Validate();">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" />
   
    </div>
    </form>
</body>
</html>

MSSQL - Fix Error - ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'SomeNewColumn' cannot be added to non-empty table 'Product' because it does not satisfy these conditions.

Msg 4901, Level 16, State 1, Line 1
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'SomeNewColumn' cannot be added to non-empty table 'Product' because it does not satisfy these conditions.


Watch this example on YouTube

 


To fix it replace

Alter Table [Product]
ADD SomeNewColumn bit Not Null
GO


with

Alter Table [Product]
ADD SomeNewColumn bit Not Null Default 0
GO 

Saturday 8 June 2019

MVC - Chart.js - Create Simple Bar Chart

Watch this example on YouTube

 


1. Download Chart.min.js from

https://www.jsdelivr.com/package/npm/chart.js


2. Common.js

jQuery.extend({
    getValues: function (url) {
        var result = null;
        $.ajax({
            url: url,
            type: 'post',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (data) {
                result = data;
            }
        });
        return result;
    }
});

3. Add to _Layout

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
    @Scripts.Render("~/Scripts/Chart.min.js")
    @Scripts.Render("~/Scripts/Common.js")
</head>

4. Chart Model

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

namespace MVCChart.Models
{
    public class Chart
    {
        public string[] labels { get; set; }
        public List<Datasets> datasets { get; set; }
    }
    public class Datasets
    {
        public string label { get; set; }
        public string[] backgroundColor { get; set; }
        public string[] borderColor { get; set; }
        public string borderWidth { get; set; }
        public int[] data { get; set; }
    }
}

5. Home Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCChart.Models;

namespace MVCChart.Controllers
{
    public class HomeController : Controller
    {
        public JsonResult BarChartData()
        {
            Chart _chart = new Chart();
            _chart.labels = new string[] { "Jan", "Feb", "Mar" };
            _chart.datasets = new List<Datasets>();
            List<Datasets> _dataSet = new List<Datasets>();
            _dataSet.Add(new Datasets()
            {
                label = "This Year",
                data = new int[] { 40, 60, 20 },
                backgroundColor = new string[] { "800000", "#E9967C", "#FF0000" },
                borderColor = new string[] { "800000", "#E9967C", "#FF0000" },
                borderWidth = "1"
            });
            _chart.datasets = _dataSet;
            return Json(_chart, JsonRequestBehavior.AllowGet);
        }

6. Index.cshtml

@{
    ViewBag.Title = "Home Page";
}

<canvas id="barChart" width="300" height="100"></canvas>

<script>
    var c = document.getElementById("barChart");
    var ctx = c.getContext("2d");
    var tData = $.getValues("/Home/BarChartData");
    var myBarChart = new Chart(ctx, {
        type: 'bar',
        data: tData
    });
</script>

C# - DropDownList - Get selected value in code behind


Watch this example on YouTube


1. HTML

   <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
        OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
        <asp:ListItem> Test 1</asp:ListItem>
        <asp:ListItem> Test 2</asp:ListItem>
    </asp:DropDownList>

2. Code Behind

string selectedValue = DropDownList1.SelectedValue.ToString();

Thursday 6 June 2019

Visual Studio - Find double empty lines

 
Watch on YouTube
 
 
 
 
Select Regular expressions and search for: 
^(?([^\r\n])\s)*\r?\n(?([^\r\n])\s)*\r?\n

MSSQL - Join the same table multiple times in one simple query

Watch this example on YouTube



1. Table

USE [Company]
GO
/****** Object:  Table [dbo].[TestJoin]    Script Date: 2019-06-06 7:02:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TestJoin](
    [Name] [varchar](50) NULL,
    [Manager] [varchar](50) NULL
) ON [PRIMARY]

GO
INSERT [dbo].[TestJoin] ([Name], [Manager]) VALUES (N'Bob', NULL)
GO
INSERT [dbo].[TestJoin] ([Name], [Manager]) VALUES (N'Frank', N'Bob')
GO
INSERT [dbo].[TestJoin] ([Name], [Manager]) VALUES (N'Ann', N'Bob')
GO
INSERT [dbo].[TestJoin] ([Name], [Manager]) VALUES (N'Rob', N'Frank')
GO
INSERT [dbo].[TestJoin] ([Name], [Manager]) VALUES (N'Eddy', N'Frank')
GO
INSERT [dbo].[TestJoin] ([Name], [Manager]) VALUES (N'John', N'Rob')
GO

2. Query

Select TestJoin.Name As Boss ,
TestJoin2.Name As Director,
TestJoin3.Name As Manager,
TestJoin4.Name As Nobody


From TestJoin
Left Outer Join TestJoin As TestJoin2 On TestJoin.Name = TestJoin2.Manager
Left Outer Join TestJoin As TestJoin3 On TestJoin2.Name = TestJoin3.Manager
Left Outer Join TestJoin As TestJoin4 On TestJoin3.Name = TestJoin4.Manager

Where TestJoin.Name = 'Bob'

C# - Fix Error - There is no argument given that corresponds to the required formal parameter

  There is no argument given that corresponds to the required formal parameter 'r'

watch solution on YouTube

Wednesday 5 June 2019

C# - Check if string is double and if yes assign value to variable


Watch this example on YouTube

           

double test;
            string SomeValue = "333";
            bool res = false;
            if(Double.TryParse(SomeValue, out test))
            {
                res = true;
            }

C# - Check if string is palindrome - if it reads the same backward as forward


watch this example on YouTube


string Test = "ANNA";
bool res = Test.SequenceEqual(Test.Reverse());

ASP.NET - JavaScript - OK/Cancel example in one line in button code

Watch this example on YouTube



 <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"
        OnClientClick="return confirm('Please Confirm you want to proceed');" />

ASP NET Fix Drop Down List Selected Index Changed not executed

Watch this example on YouTube


To fix it replace

    <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
        <asp:ListItem> Test 1</asp:ListItem>
        <asp:ListItem> Test 2</asp:ListItem>
    </asp:DropDownList>

wtih

    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
        <asp:ListItem> Test 1</asp:ListItem>
        <asp:ListItem> Test 2</asp:ListItem>
    </asp:DropDownList>

Saturday 1 June 2019

C# - Form Application - Show console window in forms application


Watch this example on YouTube


1. Go to Project Properties -> Application -> Output Type -> Console Application

2. then the following code will be executed:
Console.WriteLine("button clicked");

C# - Convert Decimal? to 0 (zero) if null


Watch this example on YouTube

           

Decimal? z;
z = null;
Decimal zz = Convert.ToDecimal(z);

Thursday 30 May 2019

MSSQL - Load records only if all specified columns are null


Watch this example on YouTube


Select * From TableWithNulls
Where Coalesce(FName, LName, Address) is null

MSSQL - Load records only if 1 of the specified columns is not null


Watch this example on YouTube


Check if at least 1 column is not null

Select * From TableWithNulls
WHERE Coalesce(FName, LName, Address) is not null

Wednesday 29 May 2019

MVC - Chart - Display multiple charts in one View



Watch this example on YouTube


 

1. Controller

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


namespace WebApplication7.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Chart1()
        {
            var key = new Chart(width: 300, height: 300)
                .AddTitle("Employee 1")
                .AddSeries(
                    chartType: "Bubble",
                    name: "Emp1",
                    xValue: new[] { "Peter", "Frank", "Bob", "Ann" },
                    yValues: new[] { "2", "4", "3", "7" }
                );
            return File(key.ToWebImage().GetBytes(), "image/jpeg");
        }
        public ActionResult Chart2()
        {
            var key = new Chart(width: 300, height: 300)
                .AddTitle("Employee 2")
                .AddSeries(
                    chartType: "Column",
                    name: "Emp2",
                    xValue: new[] { "Peter", "Frank", "Bob", "Ann" },
                    yValues: new[] { "2", "4", "3", "7" }
                );
            return File(key.ToWebImage().GetBytes(), "image/jpeg");
        }

2. View

@{
    ViewBag.Title = "Home Page";
}


<img src="@Url.Action("Chart1")" />
<img src="@Url.Action("Chart2")" />

Monday 27 May 2019

MVC - Chart - Display Multiple Series

Watch this example on YouTube


1. Add to Home Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Web.Helpers;

namespace WebApplication3.Controllers
{
    public class HomeController : Controller
    {
      
        public ActionResult ChartWithMultipleValues()
        {
            Chart key = new Chart(width: 500, height: 500)
                .AddTitle("Employee Chart")
                .AddLegend("Some legend")
                .SetYAxis("Percentage Value", 0, 100)
                .AddSeries(
                    chartType: "Column",
                    name: "January",
                    xValue: new[] { "Bob", "Ivan", "Frank", "Anna" },
                    yValues: new[] { "33", "44", "22", "88" }
                )
                .AddSeries(
                    name: "February",
                    yValues: new[] { "99", "78", "88", "33" }
                );
            return File(key.ToWebImage().GetBytes(), "image/jpeg");
        }

2. View

@{
    ViewBag.Title = "Home Page";
}

<img src="@Url.Action("ChartWithMultipleValues")" />

MVC - C# - How to remove duplicates from the array


Watch this example on YouTube


   
        int[] a = { 1, 2, 3, 2, 3, 1, 5, 5, 6 };
        int[] b = a.Distinct().ToArray();

or 

        int[] a = { 1, 2, 3, 2, 3, 1, 5, 5, 6 };
        a = a.Distinct().ToArray();

Saturday 25 May 2019

MVC - Chart - Create Simple Chart and load data from DB - Entity Framework



Watch this example on YouTube


 

1. Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication7.Models;
using System.Collections;
using System.Web.Helpers;


namespace WebApplication7.Controllers
{
    public class HomeController : Controller
    {
        CompanyEntities db = new CompanyEntities();

        public ActionResult GetChartImage()
        {
            ArrayList xValue = new ArrayList();
            ArrayList yValue = new ArrayList();
            var results = db.GetProducts().ToList();
            results.ToList().ForEach(rs => xValue.Add(rs.Month));
            results.ToList().ForEach(rs => yValue.Add(rs.Amount));
            var key = new Chart(width: 300, height: 300)
                .AddTitle("Months")
                .AddSeries(chartType: "Pie",
                name: "Some Name",
                xValue: xValue,
                yValues: yValue);
            return File(key.ToWebImage().GetBytes(), "image/jpeg");
        }

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

2. View

@{
    ViewBag.Title = "Home Page";
}


<img src="@Url.Action("GetChartImage")" />

MVC - Create simple Chart


Watch this example on YouTube


 
1. Home Controller

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

namespace WebApplication7.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult GetChartImage()
        {
            var key = new Chart(width: 300, height: 300)
                .AddTitle("Employee Chart")
                .AddSeries(
                chartType: "Bubble",
                name: "Employee",
                xValue: new[] {"Frank", "John", "Bob", "Ann"},
                yValues: new[] {"33", "22", "55", "44"}
                );
            return File(key.ToWebImage().GetBytes(), "image/jpeg");
        }

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


2. View

@{
    ViewBag.Title = "Home Page";
}


<img src="@Url.Action("GetChartImage")" />

MSSQL - Fix Error - The server principal 'LIVING\Administrator' already exists.

Msg 15025, Level 16, State 2, Line 1
The server principal 'LIVING\Administrator' already exists.


Watch this example on YouTube

Fix Error - The type or namespace name 'Chart' could not be found (are you missing a using directive or an assembly reference?)


Error    CS0246    The type or namespace name 'Chart' could not be found (are you missing a using directive or an assembly reference?)  

Watch this example on YouTube


To fix it add
using System.Web.Helpers;

Wednesday 22 May 2019

Microsoft Excel - Remove duplicates from colum row or cell


Watch this example on YouTube


1. select column row or cell
2. Go to Data -> Data Tools -> Remove Duplicates

Microsoft Excel - How to setup column or cell or row that allows only positive numbers


Watch this example on YouTube


1. Highlight column or row or cell
2. Go to Data -> Data Tools -> Data Validation
3. Data Validation -> settings -> Allow: Decimal, Greater Than, Minimum:0
4. Error Alert -> error message -> enter error message here

Tuesday 21 May 2019

Microsoft Excel - Compare if 2 cells are the same



Watch this example on YouTube

This formula will check if 2 cells are the same:
=IF(EXACT(A1, B1), "Yes", "No")

Monday 20 May 2019

MVC - Charting - Display multiple series using data from SqlServer( Entity Framework)



Watch this example on YouTube


1. Table 

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ChartTest](
    [ProductName] [varchar](50) NULL,
    [Month] [varchar](50) NULL,
    [Amount] [int] NULL
) ON [PRIMARY]

GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount]) VALUES (N'Apple', N'Jan', 20)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount]) VALUES (N'Apple', N'Feb', 40)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount]) VALUES (N'Apple', N'Mar', 22)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount]) VALUES (N'Apple', N'Apr', 44)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount]) VALUES (N'Orange', N'Jan', 55)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount]) VALUES (N'Orange', N'Feb', 22)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount]) VALUES (N'Orange', N'Mar', 33)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount]) VALUES (N'Orange', N'Apr', 88)
GO

2. Stored Procedure

CREATE PROCEDURE [dbo].[GetProducts]

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT * FROM ChartTest
END


3. Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.DataVisualization.Charting;
using System.IO;
using System.Text;
using System.Drawing;
using WebApplication4.Models;

namespace WebApplication4.Controllers
{
    public class HomeController : Controller
    {
        CompanyEntities db = new CompanyEntities();

        public ActionResult ChartMultiColumns()
        {
            var dataAll = db.GetProducts().ToList();
            var months = from d in dataAll orderby d.Month group d by d.Month into m select m.Key;
            var chart = new Chart();
            foreach(var mn in months)
            {
                var data = from d in dataAll where d.Month == mn select d;
                var area = new ChartArea();
                chart.ChartAreas.Add(area);
                var series = new Series();
                foreach(var item in data)
                {
                    series.Points.AddXY(item.ProductName, item.Amount);
                }
                series.ChartType = SeriesChartType.Column;
                series.Name = data.First().Month;
                chart.Series.Add(series);
            }
            Legend chartLegend = new Legend();
            chartLegend.Name = "Result";
            chartLegend.LegendStyle = LegendStyle.Column;
            chart.Legends.Add(chartLegend);

            var returnStream = new MemoryStream();
            chart.ImageType = ChartImageType.Png;
            chart.SaveImage(returnStream);
            returnStream.Position = 0;
            return new FileStreamResult(returnStream, "image/png");
        }


4. View

@{
    ViewBag.Title = "ChartMultiColumns";
}

<h2>ChartMultiColumns</h2>

<img src="@Url.Action("ChartMultiColumns")" />

Saturday 18 May 2019

MVC - Charting - Create simple chart from database using Entity Framework - Step By Step

Watch this example on YouTube:



1. Table

USE [Company]
GO

/****** Object:  Table [dbo].[ChartTest]    Script Date: 2019-05-18 3:31:57 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[ChartTest](
    [ProductName] [varchar](50) NULL,
    [Month] [varchar](50) NULL,
    [Amount] [int] NULL
) ON [PRIMARY]

GO

2. Stored Procedure

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
CREATE PROCEDURE GetProducts

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT * FROM ChartTest
END
GO

3. Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication3.Models;
using System.Web.UI.DataVisualization.Charting;
using System.IO;
using System.Text;
using System.Drawing;

namespace WebApplication3.Controllers
{
    public class HomeController : Controller
    {
        CompanyEntities db = new CompanyEntities();

        public ActionResult ChartFromEF()
        {
            var data = db.GetProducts().ToList();
            var chart = new Chart();
            var area = new ChartArea();
            chart.ChartAreas.Add(area);
            var series = new Series();
            foreach(var item in data)
            {
                series.Points.AddXY(item.ProductName, item.Amount);
            }
            series.Label = "#PERCENT{P0}";
            series.Font = new Font("Arial", 8.0f, FontStyle.Bold);
            series.ChartType = SeriesChartType.Column;
            series["PieLabelStyle"] = "Outside";
            chart.Series.Add(series);
            var returnStream = new MemoryStream();
            chart.ImageType = ChartImageType.Png;
            chart.SaveImage(returnStream);
            returnStream.Position = 0;
            return new FileStreamResult(returnStream, "image/png");
        }

4. View

@{
    ViewBag.Title = "ChartFromEF";
}

<h2>ChartFromEF</h2>

<img src="@Url.Action("ChartFromEF")" />

Monday 13 May 2019

MVC - Charting - Create simple chart


Watch this example on YouTube











Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.DataVisualization.Charting;
using System.IO;
using System.Text;
using System.Drawing;

namespace MVCCharting.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Chrt1()
        {
            var data = new Dictionary<string, float>
            {
                {"test1", 10.1f },
                {"test2", 1.1f },
                {"test3", 22.3f },
                 {"test4", 30.1f },
                {"test5", 13.1f },
                {"test6", 82.3f }
            };
            var chart = new Chart();
            var area = new ChartArea();
            chart.ChartAreas.Add(area);
            var series = new Series();
            foreach (var item in data)
            {
                series.Points.AddXY(item.Key, item.Value);
            }
            series.Label = "Some Label";
            series.Font = new Font("Arial", 10.0f, FontStyle.Bold);
            series.ChartType = SeriesChartType.Column;
            series["PieLabelStyle"] = "Outside";
            chart.Series.Add(series);
            var returnStream = new MemoryStream();
            chart.ImageType = ChartImageType.Png;
            chart.SaveImage(returnStream);
            returnStream.Position = 0;
            return new FileStreamResult(returnStream, "image/png");
        }

View

@{
    ViewBag.Title = "Chrt1";
}

<h2>Chrt1</h2>

<img src="@Url.Action("Chrt1")" />