Friday 19 March 2021

MVC - Simplest Extension Method example

 Watch this example on YouTube


 1. Model

   public interface IExtensionTest
    {
         void DoSomething();
    }
    public class ExtensionTest: IExtensionTest
    {
        public void DoSomething() { }
    }
    public static class SomethingElse {
        public static string ReturnSomething(this IExtensionTest t, string s)
        {
            return "returning: " + s;
        }
    }


2. Controller

        public ActionResult Index()
        {
            IExtensionTest e = new ExtensionTest();
            var res = e.ReturnSomething("bbbbb");
            return View();
        }

MVC - C# - Check if DateTime is today

 Watch this example on YouTube


            DateTime d = Convert.ToDateTime("1/1/2000");
            if (d != DateTime.Today)
            {
                // do something here.
            }

MVC - C# - Check if time is greater than something

 Watch this example on YouTube


 

            TimeSpan startSomething = new TimeSpan(8, 0, 0);
            TimeSpan endSomething = new TimeSpan(16, 0, 0);
            TimeSpan now = DateTime.Now.TimeOfDay;
            if ((now > startSomething) && (now < endSomething))
            {
                //do something here
            } 

MVC - C# - Check if today is Friday (check todays day name)

 Watch this example on YouTube


         if (System.DateTime.Now.DayOfWeek == DayOfWeek.Friday)
            {
                // do somehting here
            }

MVC - C# - Convert Now to Universal Time UTC

 

 Watch this example on YouTube


 

           String t = Convert.ToDateTime(DateTime.Now).ToUniversalTime().ToString("yyyy/MM/dd HH:mm UTC");
 

 

MVC - C# - Format Date

Watch this example on YouTube

 

 

MVC - C# - Format Date

Thursday 18 March 2021

Bat file to execute PowerShell

Watch this example on YouTube


 1. PowerShell File

$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("Hello World", 0, "Done", 0x1)


2. Bat file

Powershell.exe -executionpolicy remotesigned -File "C:\Temp\PopupTest.ps1"

Wednesday 17 March 2021

MVC - How to call async method from controller

 

Watch this example on YouTube

 

 

 

1. Task

using System.Web.Mvc;
using System.Threading.Tasks;

namespace ValidateOnDbSide.Controllers
{
    public class BusinessController : Controller
    {
        public async Task<string> DoSomething()
        {
           return await Task.Run(() => test());
        }
        public string test()
        {
            return "test";
        }        
    }
}

2. Controller


using System.Threading.Tasks;

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

       

        public async Task<ActionResult> Index()
        {
            BusinessController b = new BusinessController();
            //Task c = b.DoSomething();
            string res = await b.DoSomething();

            return View();
        }

MVC - Fix Error - Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

 Watch this example on YouTube


 Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.   


To fix it replace

        public ActionResult Index()
        {
            BusinessController b = new BusinessController();
            b.DoSomething();

            return View();
        }

with

using System.Threading.Tasks;

        public async Task< ActionResult> Index()
        {
            BusinessController b = new BusinessController();
            await b.DoSomething();

            return View();
        }



MVC - Add scrollbar to @Html.DisplayFor

 Watch this example on YouTube


 

1.CSS

 .LongText{
    word-wrap:break-word;
    height: 10em;
    width: 20em;
    overflow-y: scroll;
}

2.View 

    <div class="LongText">
        @Html.DisplayFor(x => x.Description)
    </div>

Tuesday 16 March 2021

MVC - Prevent Double clicking

 Watch this example on YouTube


 

1. View


@{
    ViewBag.Title = "Home Page";
}
<input type="submit" value="SUBMIT" />
<input type="submit" value="CANCEL" />

@section Scripts{
    <script type="text/javascript">

    $(document).ready(function () {
        var clickNum = 0;
        jQuery('input[type=submit]').click(function (event) {
            if (this.value == 'CANCEL') {
                clickNum = 0;
                return false;
            }
            if (clickNum > 0) {
                alert("Wait!!!!!");
                return false;
            }
            else {
                clickNum++;
            }
        });


    });
</script>
}
 

2. Controller

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

        [HttpPost]
        public ActionResult Index(string test = "")
        {
            System.Timers.Timer t = new System.Timers.Timer(2000);
            return View();
        }

 

Monday 15 March 2021

MVC - Create simple WebApiConfig

 Watch this example on YouTube


1. Install NuGet

PM> Install-Package Microsoft.AspNet.WebApi.WebHost

PM> Install-Package Microsoft.AspNet.WebApi


2. Add to App_Start folder

using System.Web.Http;

namespace WebApplication17
{
    public static class WebAppConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });
        }
    }
}


3. Modify Global.asax

using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;

namespace WebApplication17
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            WebAppConfig.Register(GlobalConfiguration.Configuration);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

4. Modify Layout file

    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
</head>


5. Create empty controller


namespace WebApplication17.Controllers
{
    public class TestController : System.Web.Http.ApiController
    {
        public string Get()
        {
            return "returning something";
        }
    }
}


6. Modify Home\Index file

@{
    ViewBag.Title = "Home Page";
}
<script>
    var url = '/api/test';
    $(document).ready(function () {
        $.ajax({
            url: url,
            async: true,
            success: function (data) {
                alert(data);
            }
        });
    });
</script>

MVC - Fix error - JavaScript runtime error: '$' is undefined

 Watch this example on YouTube


To fix it replace layout file

    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>


with 


    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
</head>

Thursday 11 March 2021

MVC - WebApiConfing - Controller not called - Fix Error - The resource cannot be found

 

 Watch this example on YouTube


1. View - add error

<script>
    var uri = '/api/test';
    $(document).ready(function () {

        $.ajax({
            url: 'api/test',
            async: true,
            success: function(data){
                alert(data);
            },
            error: function (xhr, status, error) {
                debugger
            }

        });
      
    });
</script> 


2. Global replace

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            WebApiConfig.Register(GlobalConfiguration.Configuration);
        }


with 

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
           
        }

 

MVC - WebApiConfing - Fix Error - The requested resource does not support http method 'GET'

 Watch this example on YouTube


 to fix it add to the controller


        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpGet]


so it looks like

using System.Web.Mvc;

namespace WebApplication11.Controllers
{
    [RoutePrefix("api/Device")]
    public class TestController : System.Web.Http.ApiController
    {
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpGet]

        public string f1()
        {
            return "hello world";
        }
        public string f1(int a)
        {
            return (a + 1).ToString();
        }
    }
}

Wednesday 10 March 2021

MVC - C# - Check if valid email address

 Watch this example on YouTube


 

       public ActionResult Index()
        {
            var b1 = IsValidEmailAddress("bob@boc.com");
            var b2 = IsValidEmailAddress("Bob@bob@bob");
            return View();
        }

        private bool IsValidEmailAddress(string email)
        {
            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                return addr.Address == email;
            }
            catch
            {
                return false;
            }
        }

Saturday 6 March 2021

MVC - Remote Validation - Passing multiple additional fiels for validation

 Watch this example on YouTube


 

Replace

   [Remote(action: "ValidateSalary", controller: "Home",  ErrorMessage ="will never be displayed - it will display message returned by stored procedure")]
        public int Salary { get; set; }

with

  [Remote(action: "ValidateSalary", controller: "Home", AdditionalFields = "FirstName,LastName",  ErrorMessage ="will never be displayed - it will display message returned by stored procedure")]
        public int Salary { get; set; }

MVC - Validation - Allow all characters except specified ones

   Watch this example on YouTube

 

 

 

 

 [RegularExpression (@"^[^*<>a]*$", ErrorMessage = " invalid")]
        public string LastName { get; set; }

MVC - Validation - Display proper name in error message

Watch this example on YouTube

 

 

  [RegularExpression(@"^([0-9]\d*)(?:\.[05]0?)?$", ErrorMessage = " {0} contains invalid characters")]
        [Display(Name = "Salary abc...")]
        public Decimal Salary { get; set; }

MVC - Validation - Allow half deciamals - 0.5

 Watch this example on YouTube



        [RegularExpression(@"^([0-9]\d*)(?:\.[05]0?)?$", ErrorMessage = " {0} contains invalid characters")]
        public Decimal Salary { get; set; }

MVC - Custom Validator - Fix Error - 0x800a138f - JavaScript runtime error: Unable to get property 'unobtrusive' of undefined or null reference

Watch this example on YouTube

 

 

 

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

 

 

In Layout replace

 

 

    @Scripts.Render("~/bundles/jqueryval")

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/Scripts/CustomValidation.js")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

 

with

 
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")

    @Scripts.Render("~/Scripts/CustomValidation.js")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

MVC - Custom Validation - Validate on each checkbox click

 Watch this example on YouTube


 

@model WebApplication10.Models.Customer

@{ Html.EnableClientValidation();}
@using(Html.BeginForm(null, null, FormMethod.Post))
{
    @Html.AntiForgeryToken();
    @Html.CheckBoxFor(x => x.IsActive)
    @Html.TextBoxFor(x => x.FirstName)
    @Html.ValidationMessageFor(x => x.FirstName)

    @Html.TextBoxFor(x => x.LastName)

    <input type="submit" value="SUBMIT" />
}

@section Scripts{
    <script type="text/javascript">
        $("#IsActive").change(function (evt) {
            var validator = $("#FirstName").validate();
            var IsValid = $("#FirstName").valid();

        });
    </script>
}

MVC - Remote Validation - Button not included in POST data in Controller

 Watch this example on YouTube


 Button value lost in Remote Validator

 

to fix it replace

 @model ValidateOnDbSide.Models.Customer


@{ Html.EnableClientValidation();}
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "UserID" }))
{

    @Html.AntiForgeryToken()

    // @Html.CheckBoxFor(x => x.IsActive)
    @Html.DisplayNameFor(x => x.FirstName)
    @Html.TextBoxFor(x => x.FirstName)
    @Html.ValidationMessageFor(x => x.FirstName)
    <br />
    @Html.DisplayNameFor(x => x.LastName)
    @Html.TextBoxFor(x => x.LastName)
    @Html.ValidationMessageFor(x => x.LastName)
    <br />

     @Html.DisplayNameFor(x => x.Salary)
    @Html.TextBoxFor(x => x.Salary)
    @Html.ValidationMessageFor(x => x.Salary)
    <br />
    <input type="submit" value="Submit" name="btn" />
}

with 


@model ValidateOnDbSide.Models.Customer


@{ Html.EnableClientValidation();}
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "UserID" }))
{

    @Html.AntiForgeryToken()

    // @Html.CheckBoxFor(x => x.IsActive)
    @Html.DisplayNameFor(x => x.FirstName)
    @Html.TextBoxFor(x => x.FirstName)
    @Html.ValidationMessageFor(x => x.FirstName)
    <br />
    @Html.DisplayNameFor(x => x.LastName)
    @Html.TextBoxFor(x => x.LastName)
    @Html.ValidationMessageFor(x => x.LastName)
    <br />

     @Html.DisplayNameFor(x => x.Salary)
    @Html.TextBoxFor(x => x.Salary)
    @Html.ValidationMessageFor(x => x.Salary)
    <br />
    <input type="submit" value="Submit" name="btn" />
}

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $('input[type="submit"]').click(function () {
                var hidden = $("<input type='hidden' />").attr("name", this.name).val(this.value).appendTo($(this).closest("form"));
            });
        });
    </script>    
    
}