Wednesday, November 27, 2019

Custom Exception Filter in mvc


Custom Exception Filter in mvc

Custom Exception Filter in MVC

Exception filter is used to get errors at runtime or unhandled exceptions. we have to try-catch to handle the errors.
if you use try-catch at any action method then the exception filter won't work. but we can use in some cases like to handle some errors at the global level then we can use this filter. any class that inherits the IExceptionFilter then we call it as exception filter.

Note:
  1. Try-Catch block is used to handle the exception at runtime.
  2. Controller class Exceptions can be handled in different ways.
       try-catch to each action method of the Controller.
       Using the override OnException method
       Handling Run time errors at the global level using FilterConfig.cs class


Using Try-Catch clock in the Action method

public ActionResult  CreateATG()
{
    try
    {
         int  q = 100;  
        int  z = 0;  
        int k = q / z;  
        return RedirectToAction("Index");
    }
    catch(Exception ex)
    {
     return View("Error",new HandleErrorInfo(ex,"EmployeeInfo","home"));
    }
}


 Using the override OnException method

Step 1:

public class ATGExceptionFilter: FilterAttribute, IExceptionFilter  
  
  {  
    public override void OnException(ExceptionContext   atgfilterContext)
    {  
        Exception exp = atgfilterContext.Exception;
         //Logging the Exception
         atgfilterContext.ExceptionHandled = true;


   var Result = this.View("Error", new HandleErrorInfo(exp,
       atgfilterContext.RouteData.Values["controller"].ToString(),
       atgfilterContext.RouteData.Values["action"].ToString()));

   atgfilterContext.Result = Result;  
    }  


Step 2: Consuming the filter

[ATGExceptionFilter]  
public class HomeController: Controller 
{  
    public ActionResult  ATGIndex() {  
        int  q = 100;  
        int  z = 0;  
        int k = q / z;  
        return View();  
    }  
    public ActionResult  ATGAbout() {  
        ViewBag.Message = "ATG About page here.";  
        return View();  
    }  
    public ActionResult  ATGContact() {  
        ViewBag.Message = "ATG Contact Page";  
        return View();  
    }  



Using global level using FilterConfig.cs class

we need to declare at filterconfig class in App_Start folder.
it will be applicable at gobal level
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection  filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}
Read More »

Tuesday, November 26, 2019

how to create a custom action filter in asp.net mvc

how to create a custom action filter in asp.net mvc

Action Filters are the attributes in asp.net and using for controller. it is derived from System.Attribute. The action filter has mainly three filters
  1. Output Cache
  2. Handle Error
  3. Authorize

Example for Output Cache :

public class AllTechGeeksController : Controller
 { 
   [HttpGet] 
   OutputCache(Duration = 20)] 
   
   public string resultView()
   { 
      return DateTime.Now.ToString("ATG");  
   } 
}


Example for Handle Error :

[HandleError
public class AllTechGeeksController : Controller
 { 
   public ActionResult HomeTest()
   { 
      throw new NullReferenceException(); 
   }  
   
   public ActionResult  Test()
   { 
      return View(); 
   } 
}


Example for Authorize :

public class AllTechGeeksController: Controller 

   [Authorize
   public ActionResult  TestAllTechGeeks()
  { 
      ViewBag.Message = "Authencated Users Only"; 
      return View(); 
   }  
   
   [Authorize(Roles="HR")] 
   public ActionResult  HRModule() { 
      ViewBag.Message = "Only for HR department"; 
      return View(); 
   } 
}


How to create a custom action filter in asp.net mvc

Custom filter inherits from ActionFilterAttribute Class in asp.net mvc.
and overrides minimum any one of the following method.
  1. OnActionExecuting
  2. OnActionExecuted
  3. OnResultExecuting
  4. OnResultExecuted
we can declare the custom action filters in 3 levels  
  1. At Global Levele
  2. At Controller Level
  3. At Action Level

Create a simple Custom Action Filter in Asp.net mvc


using System;
using System.Web.Mvc;
using System.Diagnostics;

namespace webAppAlltechGeeks
{
    public class AllTechGeeksFilter : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            //You may ot not fetch data from database here 
            context.Controller.ViewBag.GreetMesssage = "Hello All Tech Geeks";
            base.OnResultExecuting(context);
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var controllerName = context.RouteData.Values["controller"];
            var actionName = context.RouteData.Values["action"];
            var message = String.Format("{0} controller:{1} action:{2}", "onactionexecuting", controllerName, actionName);
            Debug.WriteLine(message, "Action Filter Log");
            base.OnActionExecuting(context);
        }

    public override void OnResultExecuting(ResultExecutingContext  context)
        {
            //Write your code here 

        }
    public override void OnResultExecuting(ResultExecutingContext  context)
        {
             //Write your code here     

        }

    }
}





Read More »

Thursday, November 21, 2019

Custom authentication filter in mvc

Filters in asp.net MVC Tutrials

Filters in asp.net MVC


Filter is used to creating custom logic to execute before and after action methods.
we can apply the Filters in Controller level or Action method level.
Asp.net MVC provides different types of filters
  1. Authorization Filter
  2. Action Filter
  3. Result Filter
  4. Exception Filter
The Filter Execution sequence is shown below.

    Authentication Filters ==>  Authorization filter ==> Action filter ==> Result filter ==> Exceptionfilter
  1. Authentication Filter executes before any other filters like Authorization, result, etc.
  2. The Result filter executes before and after the execution of any action result
  3. The exception filter executes only if any action methods, filters, or results throws an exception in the entire application
  4. The action filter executes before and after any action method in the controller
  5. The authorization filter executes after Authentication filter and action method, or before any other filter like Authorization, result, etc

1. Authentication Filters  example syntax:

public class AuthenticationCustomFilter : ActionFilterAttribute, IAuthenticationFilter
{
   public void OnAuthentication(AuthenticationContext  filterContext)
   {
        //Write Your Code
   }
   public void OnAuthenticationChallenge(AuthenticationChallenge    Context filterContext)
   {
        //Write Your Code
   }
}

we can apply this Custome Filter in Controller Level and Action Method Level or Globally 

At Controller Level :

[AuthenticationCustomFilter]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

At Action Method Level :

public class HomeController : Controller
{
    [AuthenticationCustomFilter]
    public ActionResult Index()
    {
                return View();
    }
}

We can apply at Globally:
  1. If you apply at the global level then it will be applied to all the controller and action methods of an application.
  2. Go to Application_Start event of Global.asax.cs file 
  3. By default you can write FilterConfig.RegisterGlobalFilters() mehtod. 
example :

in Golbal.aspx.cs
public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
          //  AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
           // RouteConfig.RegisterRoutes(RouteTable.Routes);
            //BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }

in App_Start Folder
// FilterConfig.cs located in App_Start folder 

  public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }

The [HandleError] filter Attribute is applied globally in MVC Application.
By default in every MVC application creates automatically.






Read More »

Difference between viewdata viewbag tempdata and session in asp net mvc

asp.net mvc tutorials ViewData

ViewData in Asp.net MVC
  1. ViewData is similar to ViewBag and also the same functionality as ViewBag
  2. it is used to transfer the values from Controller to View.
  3. it is valid during the current request only.
  4. The Value of ViewData Must be typecast before use
  5. ViewData derived from ViewDataDictionary.
  6. The syntax to store value looks like below in Controller

           ViewData["alltechgeeks"]="All Tech Geeks";

  1.  The value displayed as in UI

             @ViewData["alltechgeeks"]

Example:

public ActionResult Index()
{
    IList<Company>  CompanyList= new List<Company>();
    CompanyList.Add(new Company(){ CompanyName = "X" });
    CompanyList.Add(new Company(){ CompanyName = "Y" });
    CompanyList.Add(new Company(){ CompanyName = "Z" });

    ViewData["companies"] = CompanyList;
  
    return View();
}


What is VIewBag?
What is TempData?
What is ViewData?
Read More »

Difference between viewdata viewbag tempdata and session in asp net mvc

asp.net mvc tutorials tempdata

TempData in asp.net MVC
  • TemData is used to store the temporary data for the subsequent requests.
  • the main use of Tempdata is used to transfer the data from one Action Method to Another Action Method
  • TempData is derived from TempDataDictionary.
  • The Valu of TempaData must be Type Cast before use
  • TempData internally uses the session to store the data. so it is a short-lived session.

TempData has mainly two method

  1.  Keep
  2.  Peek
TempData.Keep() has mainly 2 overloaded methods

  1.  Void keep is used to all the data should not be deleted on current request completion
  2.   Void keep(string key) is used to persist specific item in TempData with help of name

TempData.Peek() has no overloaded methods

  1. it returns an object which contains an item with the specific key without making the key for deletion

Example :

public class HomeController: Controller
{
    // GET: company name
    public HomeController()
    {

    }
    public ActionResult Index()
    {
        TempData["name"] = "All Tech Geeks";
        TempData["city"] = "Mumbai";
        return View();
    }
    public ActionResult About()
    {
        string  Name;
        int  City;
        
        if(TempData.ContainsKey("name"))
            {
            Name = TempData["name"].ToString();
              }
        if(TempData.ContainsKey("city"))
             {
            City = int.Parse(TempData["city"].ToString());
              }
            return View();
    }
}


What is VIewBag?
What is TempData?

What is ViewData?



Read More »

Friday, September 6, 2019

ASP.NET Core Tutorial

We are going to consecrate below topics

  1. Asp.net Core
  2. Asp.net core MVC
  3.  Asp.net Core Identity and Security
  4. Entity Frame work core
Asp.net core is a redesigned Asp.net 4.x.

Advantages: 
  1. Asp.net is a Cross platform: we can develop the application and we can run the application across. different platforms like Windows, MacOS and Linux, we can Host the Application in IIS, Self-host, Docker and Apache etc.
  2. Single Unified Programming Model for Web API and MVC. it means MVC Controller and Web API. Controller Base class and return IActionResult. IActionResult is Interface with 2 several implementations like ViewResult and JsonResult.
  3. Dependency injection
  4. Open Source
  5.  Testability
  6. Asp.net core provides Modularity at Middleware technology. we have rich set of Middleware components and custom Middleware Components

What is InProcess and OutOfProcess


  1.  By default Visual studio uses IISExpress to host and Run the application
  2.  in production we use IIS


<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>

Kestrel Server uses for internal server
IIS, Nginx, Apache are used for External server

Note:

  1. if we run through CLI then application runs on Kestrel. execute dotnet.exe
  2. if we run through Visual studio then the application runs on IISExpress.exe


Read More »

Thursday, August 29, 2019

Google Apps Script For Developers

Google Apps Script Developers


Google Apps Script is nothing but Javascript. before start this article you should know the Javascript then you can easily understand the Google app script. The main moto of this article is to avoid the server side programming language to run the google product functionalities. for example if you want Google map, Youtube, API's, Drive and Gmail functionalities etc.

Once you creates the Javascript then you can run in google cloud without your own servers. so the maintenance burden reduces. you can develop your own code in local system. here i preferred the Visual Studio Code 2017 Editor. and i will write the code in ES6. i already developed some CRUD operation in Google App Script please check it. coming days. we will update the tutorials.

Please check Below App Script Projects
  1. Using Google spreadsheets as Database For Blog
  2. Sending Emails from Google Spreadsheet
Read More »

Monday, April 1, 2019

asp net mvc tutorial step by step for beginners with examples


asp.net mvc tutorials

Asp.net MVC tutorials sponsored by all tech geeks. this tutorial provides all articles in one container. it helps you like the index of the book. what is MVC ?. it is an architectural design pattern and stands for Model View and Controller. this container covers all topics of the asp.net MVC. it helps from freshers level to professional level. if you are starting level then you need basic knowledge of C#, Advanced OOPs, Visual Studio, and HTML.
it is an open source web development framework by Microsoft. it is alternate to asp.net and not the replacement of asp.net.

                                               Asp.Net MVC  - Get Started

  1. Asp.net MVC Tutorials- Get Started 
  2. Architecture
  3. First Application
  4. Folder Structure
  5. Controller
  6. Views
  7. Model
  8. Bundling
  9. View Bag
  10. Temp Data
  11. View Data
  12. Action Methods
  13. Action Selectors
  14. HTML Helpers
  15. Partial Views
  16. Layout View
  17. Filters
  18. Action Filters
  19. Validations
  20. Area
  21. What is Entity Framework and types  
  22. Creating Project in Database First Approach
  23. Creating Project in Code first approach
  24. Creating Project in Model Base First approach

Read More »

Tuesday, March 26, 2019

Sending Emails from Google Spreadsheet

google sheets are more popular nowadays. day by day the use of Apps script is increasing.
we can write the javascript to do anything like a NetSuite.Netsuite is a cloud ERP. it has only javascript development. same as google apps script also will use for all Google products (Apps) in the cloud.
google compute is the best IAAS cloud in the IT industry.

The main points in this article are to "send emails from google sheet". its very simple. and single step to do the above task.
Step 1: Login into Gmail.
Step 2: Go to google drive
Step 3: select the new button and select the spreadsheet
Step 4: type Email and name columns in the spreadsheet.
Step 5: go to tools and select the Script editor
Step 6: write the below script use where ever you want it

                                 MailApp.sendMail(to, subject, body) ;

Sending Emails from Google Spreadsheet

in the above image, you can find the function. the function name is myFunction(){}.

       myFunction()  
                   {
         MailApp.sendMail("alltechgeekz@gmail.com","Hello test mail","Hello from All Tech Geeks");
       
            }

But we need to pick email from the spreadsheet and send the mail from the sheet.

function Send Email() {

                  var sheet =SpreadsheetApp.getActiveSheet();
                  var r   = sheet.getRange("A1:B2");
                   var  customerdata=range.getValues();
for(j in customerdata)
      {
           var row=customerdata[i];
           var Email =row[0];
           MailApp.sendMail(row[1],"Email id is"+Email+,"this is test email");
      }
}

how to get data from the browser to the spreadsheet or how to use the google sheet as a database.
if we get the data from the website or anywhere. then we can do anything with that data.


Read More »

Wednesday, March 20, 2019

bind Dropdown list in asp.net

 public void bindcus()
    {
        ddlcustomer.Items.Clear();
        ddlcustomer.Items.Add(new ListItem("--SELECT--","0"));
        ddlcustomer.AppendDataBoundItems = true;
        dao.type = "CUSTOMER";
        DataTable dt= new DataTable();
        dt = bl.report(dao);
        if (dt.Rows.Count > 0)
        {
            ddlcustomer.DataSource = dt;
            ddlcustomer.DataTextField = "name";
            ddlcustomer.DataValueField = "code";
            ddlcustomer.DataBind();
        }

 
    }
Read More »

Using Google spreadsheets as Database For Blog


What is “Google spreadsheets as database”. nowadays every one using the website if they want a website then needs to buy the space for the website and for storing purpose need to buy the space so in both cases we need to buy the spaces from third parties like GoDaddy, Bluehost etc. So to avoid these type of problems you need to know some knowledge in “google apps script”.


Everyone has a Gmail account. Drive also free. Google drive has so many free applications like Docs, sheet, slides, forms, apps script, Jamboards, blog etc. By using these applications we can do amazing things without a database like My SQL, SQL Server, DB2 etc.

Here I will teach you how to use Google spreadsheets as a database for your web application. But I am not using web application. Instead of that, I am going to use google blog.
Pre-requirements

Step 1: Open Gmail account
Step 2: create a blog after login into your Gmail account and name it.
Step 3: go to google drive click on the new button and create a new google spreadsheet.
Step 4: Give the name for google spreadsheets
Step 5: Go to blog create a new blog account
Step 6: create a page insert_values.
Step 7: publish the blog test it you will surprise.


google spreadsheets as database for your blog


Now open Google spreadsheets and name it as "insert values"  and given 5 column names as shown below image
 Time_stamp, Id, Name, State, City, Country.

google spreadsheet as database 
Now click on tools click on script editor. In script editor you can write the code in javascript

google spreadsheet as database

The name is as insert values  and the extension is “.gs” means google script it is nothing but javascript.
In the editor, you can write the script.

google spreadsheet as database


Next, go to google spreadsheets and copy the link and paste in as shown below image.
It is a “SpreadsheetApp.openByUrl”. it means while running the program it opens the URL works as per requirement.

google sheet as database for blog


Finally, publish the script for anyone and save the script_url. It will consume it anywhere.
Click Deploy à deploy as Web app à select “who has access to the app as anyone”.
Save the script URL.
google sheet as database for your website

Select the Anyone as shown above image and Click on deploy button.
After the click, it asks to need permission to click on it. Select your Gmail account and go to advance click on insert value(unsafe).  Finally, click on allow button copy the URL.
below is the script.
Now goto blog. Create a new blog  and create a new page in the blog
google sheets api


Now go to notepad++ write javascript and paste the URL as shown below.
And create the required fields in the body tag
google sheets api

 Finally, copy all the above script  and paste in blogger page publish it
Open in the browser then it looks like below image. these all values will insert into google spreadsheets after the button click
google sheets api for your website

Click on insert button then the data goes and sits in insert_values google spreadsheets as shown below image. After insert button, it shows as successfully inserted.
google sheets api for your website

Now go and check the google spreadsheets. All value you can find in google spreadsheets.
google sheets api for your website


the above article only for insert values into google spreadsheets. in next article, you can find the Update, delete and view the values from "google spreadsheets as database"




Read More »

Wednesday, January 2, 2019

Learn Angular 7 from Scratch

What is Angular And Why?

Angular is a framework to build client-side applications. it is great for Single page applications (SPA) developed by Google. it provides built-in features like services, HTTP services, Materials etc.

1. Coming to History :
 it was released in 2010 --> Angular JS
                             2016  --> Angular 2
                             2016  -->  Angular  4 (December)
                             2017  --> Angular   5 (November )
                             2018   --> Angular 6 (May)
                             2018  --> Angular 7 (Oct)

About This Course ?
It is a crash course for all beginners from scratch. before going to this course. the prerequisites are HTML, CSS, Basics of Type Script, Java Scripts and Bootstrap.

2. Environment Setup
  1. Node
  2. Npm
  3. Angular CLI
  4. Text Editor to develop the code (Visual Studio Code (VS Code))
 Node :
 Install the Node JS. go to website select required OS and install it.   https://nodejs.org/en/download/

 Check the Node JS Version :
  go to command prompt and type as node -v like below
       
                                            [ C: \ > node -v ]
Npm :
Npm installed automatically while install Node JS. to check the Npm then go to command prompt and type npm -v as below
                                           [ C: \ > npm -v ]
Angular CLI :
Now to go https://cli.angular.io/ copy the command as shown below and execute it

                                          [npm install -g @angular/cli ]
                                           [ ng -v]  to check version   
Visual studio Code :
 go to visual studio website and download it.  (https://code.visualstudio.com/).


3. Create a Angular Project :

 method 1: Go to command prompt type as below
                                         [ ng new helloworld]
                                          [ cd helloworld]
                                          [ ng serve] 
method 2 : Go to View in VS code create a Folder and name it as Angular click on Folder--> Now go to Integrated Terminal
                          type as   [ ng new helloworld]
                                         [ cd helloworld]
                                         [ ng serve] 
All installation and creating project is completed now run the angular application in browser.
Now go to Browser and type localhost:4200
angular app is running in browser.

4. Architecture of Angular

Angular contains the one or more modules. every module contains the one or more components or services. components is nothing but HTML template + Class to control the business logic for render the particular View.
Coming to the services. if you want to re-use the code in different components then services are the best concept. here you can write the business logic for your application.








Coming soooooooooooooooooooooooooooonnnnnnnnnnnn










           
Read More »

Sunday, December 30, 2018

what is the difference between viewdata viewbag tempdata and session

in this Asp.netMVCc tutorials explains Viewbag is used to shares the small amount of data from the controller to view. the Viewbag is a Dynamic type which means no need to typecasting and downcasting. the lifespan of Viewbag is the last current HTTP request.

Example :

 namespace Alltechgeeks.Controllers
{
  public class TestController  : Controller
   {
       IList <Test> testList  = new List<Test>()
                                             {
                                               new Test(){id=1, name="Murali"},
                                               new Test(){id=2, name="Sathwiq"},
                                               new Test(){id=3, name="Siri"},
                                               new Test(){id=4, name="Krishna"}
                                              };
           public ActionResult Index()
                {
                  Viewbag.totaltest   = testList.Count();
                   return View();
               }

    }

}

Go to Index.cshtml page consume the viewbag.totaltest in view

 <htm>
     <h1>
        Total Test : @Viewbag.totaltest
   </h1>
</html>

we can assign any number of values and properties to Viewbag.




                                               Asp.Net MVC  - Get Started

  1. Asp.net MVC Tutorials- Get Started 
  2. Architecture
  3. First Application
  4. Folder Structure
  5. Controller
  6. Views
  7. Model
  8. Bundling
  9. View Bag
  10. Temp Data
  11. View Data
  12. Action Methods
  13. Action Selectors
  14. HTML Helpers
  15. Partial Views
  16. Layout View
  17. Filters
  18. Action Filters
  19. Validations
  20. Area
  21. What is Entity Framework and types  
  22. Creating Project in Database First Approach
  23. Creating Project in Code first approach
  24. Creating Project in Model Base First approach


What is VIewBag?
What is TempData?
What is ViewData?



Read More »

Samsung Galaxy j7 (2018)


samsung galaxy j7 (2018)

  1. Samsung Galaxy j7 was launched in June 2018.
  2. The size of the phone is 5.5 inches touchscreen
  3.  resolution of the Samsung j7 (2018) phone is 720 X 1080 pixels
  4.  OS operating system is Android
  5. Front Cames is 13 MP megapixels
  6. The rare camera is 13 MP megapixels
  7. it released in black color
  8. the aspect ratio is 16:9
  9. the processor is Dual Core
  10. it supports the 3G / 4G / LTE
  11. The accelerometer is enabled: yes
  12. Sim type is Nano Sim
  13. number of sims are 2
  14. Headphones are 3.5 mm
  15. expandable storage is up to 256 GB
Read More »

Bundling in Asp.net MVC Tutorials

Asp.net MVC Tutorials explains the Bundling and minification is a technique to improve the request load time and introduced in asp.net MVC 4. bundlings has some following bundle classes in System.Web.Optimization namespace.

  1. ScriptBundle
  2. StyleBundle
  3. DynamicFolderBundle

the above bundles are included in MVC 5 and the namespace is System.Web.Optimization.Bundle.
it is a process of grouping the CSS/javascript files.
the most important of bundling is to reduce the number of request from the browsers to the server, while minification reduces the size of requested assets.
Minification reduces the unnecessary white spaces and comments

Without Minification :

 allTechGeeks =function(city){
                                                   //this is comment
                                                   var test = "Hello World" + city ;
                                                   alert(test) ;
                                                }
After Minification :
  allTechGeeks =function(city){var test = "Hello World" + city ;alert(test) ;}

in without minification, the javascript file has spaces and comments but after minification, we can't find the spaces and comments. So automatically the size of the file reduces but for development needs the without minification. in production minification file is good.



                                               Asp.Net MVC  - Get Started

  1. Asp.net MVC Tutorials- Get Started 
  2. Architecture
  3. First Application
  4. Folder Structure
  5. Controller
  6. Views
  7. Model
  8. Bundling
  9. View Bag
  10. Temp Data
  11. View Data
  12. Action Methods
  13. Action Selectors
  14. HTML Helpers
  15. Partial Views
  16. Layout View
  17. Filters
  18. Action Filters
  19. Validations
  20. Area
  21. What is Entity Framework and types  
  22. Creating Project in Database First Approach
  23. Creating Project in Code first approach
  24. Creating Project in Model Base First approach


Read More »