Monday, 19 November 2018

.Netcore Api + angular 6 + EFCore Project Part - 2

.Netcore Api + angular 6 + EFCore Project Part - 1

 Important Configuration Need to be Done In AppSettins.json File And Startup file
==============================================================
=============================Startup file=======================
==============================================================
namespace DntAppApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

//Need To Add For Configuration Of  Connection String With DbContext
            services.AddDbContext<MPContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

//Need To Add Service And implementation To Use In Our Application
            services.AddScoped<IProduct_Repository, Product_Repository>();
     
  // Need To Add For Cross Origin Resourse Sharing Calls
   services.AddCors(
                options => {
                    options.AddPolicy(
                   "MAYUR", builder =>                                             builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
             });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request                    //pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            // Need To Add For Cross Origin Resourse Sharing Calls
            app.UseCors("MAYUR");
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}
==============================================================
==========================AppSettins.Json file==================
==============================================================
{
 //Add ConnectionStrings Like this To Use It In Application
  "ConnectionStrings": {
    "DefaultConnection": "data source=DESKTOP-4VG8BV2\\SQLEXPRESS; initial catalog=MP;Integrated Security=true;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}
==============================================================
=====================ValuesController==========================
==============================================================

namespace DntAppApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        IProduct_Repository _IProduct_Repository = new Product_Repository(new MPContext());

        [HttpGet]
        public IQueryable<TblProduct> Get()
        {
            return _IProduct_Repository.GetAll();
        }

        [HttpPost]
        public TblProduct Post(TblProduct obj)
        {
            _IProduct_Repository.Save(obj);
            return obj;
        }
        [HttpPut]
        public TblProduct Put(TblProduct obj)
        {
            _IProduct_Repository.Save(obj);
            return obj;
        }
        [HttpDelete]
        public int Delete(int Productid)
        {
            _IProduct_Repository.Remove(Productid);
            return 1;
        }
    }
}

.Netcore Api + angular 6 + EFCore Project Part - 1

Create .Net core api project using simple repository pattern Setup

1).  Create .Net Core Project  Name It DntAppApi
   
i). Select .Net core web application
ii).select api project

2).   Craete .Net core class library project Name it (DntAppApi.Core)
         i).  Add Microsoft.EntityFrameworkCore package From Nuget Package Manager
 ii).  Add Microsoft.EntityFrameworkCore.SqlServer package From Nuget Package Manager

3).   Craete Another .Net core class library project Name it (DntAppApi.Infrastructure)
        i).  Add Microsoft.EntityFrameworkCore package From Nuget Package Manager

ii). Open Tools > Nuget package Manager > Package Manager Console.

iii). In Package Manager Console Select  DntAppApi.Infrastructure Project's From Default                        Project Dropdown Selection

       iv). Fire Command :-
      Scaffold-DbContext "data source=DESKTOP-4VG8BV2\SQLEXPRESS; initial catalog=MP;Integrated Security=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir      Entities  -F

  Note* This will create entity folder containing all table of database as class.

4). Build  DntAppApi.Core Project And Add Reference of this Project To  DntAppApi.Infrastructure       Project

5). Now Build  DntAppApi.Infrastructure Project
      - Add Reference of  DntAppApi.Core And  DntAppApi.Infrastructure To  DntAppApi(Main)                Project

Now add two folders in DntAppApi.Infrastructure Project

1) Abstraction (Service) :- Contains All Interfaces

2).Implementation (Servicecontracts) :-  Contains All Class Which Implements Respective Interfaces.

Add an Interfaces in  Abstraction folder
==============================================================
=====================IProduct_Repository=======================
==============================================================
namespace DntAppApi
{
    public interface IProduct_Repository : IDisposable
    {
        IQueryable<TblProduct> GetAll();
        void Save(TblProduct obj);
        void Remove(int Productid);
    }
}

Add an Class in  Abstraction folder
==============================================================
=====================Product_Repository========================
==============================================================
namespace DntAppApi
{
    public class Product_Repository : IProduct_Repository
    {
        private MPContext context;
        public Product_Repository(MPContext _context)
        {
            context = _context;
        }

        public IQueryable<TblProduct> GetAll()
        {
            return context.TblProduct.AsQueryable();
        }
        public void Save(TblProduct obj)
        {
            if (obj.Productid == 0)
            {
                context.TblProduct.Add(obj);
                context.SaveChanges();
            }
            else
            {
                context.Entry<TblProduct>(obj).State = EntityState.Modified;
                context.SaveChanges();
            }
           
        }
        public void Remove(int Productid)
        {
            var obj = context.TblProduct.Find(Productid);
            context.Entry<TblProduct>(obj).State = EntityState.Deleted;
            context.SaveChanges();
        }
        // Flag: Has Dispose already been called?
        bool disposed = false;

        // Public implementation of Dispose pattern callable by consumers.
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        // Protected implementation of Dispose pattern.
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
                return;

            if (disposing)
            {
                context.Dispose();
            }

            // Free any unmanaged objects here.
            disposed = true;
        }
    }
}
Note :- Wherever you get compiler error put cursour over there press (Ctrl + dot) and add
Required Namespace

Till Now Project Setup Is Ready....

.Netcore Api + angular 6 + EFCore Project Part - 2









Sunday, 18 November 2018

Basics of angular routing

Basics of angular routing

Cli command :- ng generate module app-routing --flat --module=app

 Notes*

 1).
 imports: [ RouterModule.forRoot(routes) ],
 The method is called forRoot() because you configure the router at the application's root level.
 The forRoot() method supplies the service providers and directives needed for routing,
 and performs the initial navigation based on the current browser URL.


 2). The <router-outlet> tells the router where to display routed views.
        The RouterOutlet is one of the router directives that became available to the AppComponent because AppModule imports AppRoutingModule which exported RouterModule.

3). <a routerLink="/heroes">Heroes</a>
       Here routerLink is the selector for the RouterLink directive that turns user clicks into router navigations. It's another of the public directives in the RouterModule.
 

4). { path: '', redirectTo: '/dashboard', pathMatch: 'full' },


Angulr Part - 3

angular-part-2

Default startup & app.settings file in API Project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
//Default Startup File
namespace DntAppApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the 
        //container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP 
        //request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}




Angular Part - 2

Getting started default files(main.ts,app.component.ts,app.module,app,conponent.html,) notations.

1). ng g c home  -s --spec false

 2).ng g m account

 3).cd D:\DntApp\src\app\account 

 4).ng g c login -s --spec false

 5).ng g c register -s --spec false

 6).cd D:\DntApp\src\app

 7).ng generate module app-routing --flat --module=app 

 Notes*

 1).
 imports: [ RouterModule.forRoot(routes) ],
 The method is called forRoot() because you configure the router at the application's root level. 
 The forRoot() method supplies the service providers and directives needed for routing, 
 and performs the initial navigation based on the current browser URL.


 2). The <router-outlet> tells the router where to display routed views.
        The RouterOutlet is one of the router directives that became available to the AppComponent because AppModule imports AppRoutingModule which exported RouterModule.

3). <a routerLink="/heroes">Heroes</a>
       Here routerLink is the selector for the RouterLink directive that turns user clicks into router navigations. It's another of the public directives in the RouterModule.
   

4). { path: '', redirectTo: '/dashboard', pathMatch: 'full' },

Angular Part - 1

List of basic and commonly used CLI Commands

1).ng --version (cmd) -- See Angular Verion.
2).npm install -g @angular/cli -- install Angular Verion.
3).ng generate --help
4).cd D:
5).ng new DntApp :- ng new command creates an Angular workspace folder and generates a new app skeleton. A workspace can contain multiple apps and libraries.
6).cd DntApp
7).ng serve --o
==============================================================
==============================================================
1).ng generate  : - ng generate command to add new files for additional components and services, and code for new pipes, directives, and so on.
Commands such as add and generate, which create or operate on apps and libraries, must be executed from within a workspace or project folder.

2).ng g c --help :- for to configure options for generating new componnent
==============================================================
==============================================================
COMMAND ALIAS
DESCRIPTION

add NA Adds support for an external library to your project.

build b
Compiles an Angular app into an output directory named dist/ at the given output path. Must be executed from within a workspace directory.

config
Retrieves or sets Angular configuration values.

generate g
Generates and/or modifies files based on a schematic.

help
Lists available commands and their short descriptions.

new n
Creates a new workspace and an initial Angular app.

serve s
Builds and serves your app, rebuilding on file changes.

test t
Runs unit tests in a project.

update
Updates your application and its dependencies. See https://update.angular.io/

version v
Outputs Angular CLI version.

xi18n
Extracts i18n messages from source code.

Thursday, 7 June 2018

Simpe Captcha Code Verification Project

**********************CaptchaSelf.js**********************

function randomIntFromInterval(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}
function VerifyEBot(e) {
    _CaptchaFlag = e
    alert(e == true ? 'Looks like you are not a robot...' : 'You have selected wrong image...');
    return _CaptchaFlag;
}
var LoadCaptcha = function (eleId) {
    var aa = randomIntFromInterval(1, 90);
    var bb = aa + 1;
    var htmlStr = '';

    var _diffImgIndex = randomIntFromInterval(0, 4);
    var _sameImg = '<td onclick=VerifyEBot(false)><img src="/Captcha/icons/dark/icon-' + aa + '.png" alt="Alternate Text" /></td>';
    var _diffImg = '<td onclick=VerifyEBot(true)><img src="/Captcha/icons/dark/icon-' + bb + '.png" alt="Alternate Text" /></td>';
    switch (_diffImgIndex) {
        case 0:
            htmlStr += _diffImg
            htmlStr += _sameImg
            htmlStr += _sameImg
            htmlStr += _sameImg
            htmlStr += _sameImg
            break;
        case 1:
            htmlStr += _sameImg
            htmlStr += _diffImg
            htmlStr += _sameImg
            htmlStr += _sameImg
            htmlStr += _sameImg
            break;
        case 2:
            htmlStr += _sameImg
            htmlStr += _sameImg
            htmlStr += _diffImg
            htmlStr += _sameImg
            htmlStr += _sameImg
            break;
        case 3:
            htmlStr += _sameImg
            htmlStr += _sameImg
            htmlStr += _sameImg
            htmlStr += _diffImg
            htmlStr += _sameImg
            break;
        default:
            htmlStr += _sameImg
            htmlStr += _sameImg
            htmlStr += _sameImg
            htmlStr += _sameImg
            htmlStr += _diffImg
            break;
    };
    $('#' + eleId).append(htmlStr);
};



********************************Index.html*************************************


@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>app</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="~/Captcha/CaptchaSelf.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
    @*<script src="~/Captcha/js/script.js"></script>
        <link href="~/Captcha/style/css/style.css" rel="stylesheet" />*@
    <style>
        #ID_Captcha_Table {
            margin: 5px;
        }

        #ID_TD_Captcha td {
            border: 5px solid black !important;
            background-color: green;
            border-color: white;
            text-align: center;
            vertical-align: middle;
            cursor: pointer;
        }

            #ID_TD_Captcha td:hover {
                background-color: darkgray;
                border-color: white;
                text-align: center;
                vertical-align: middle;
                cursor: pointer;
                transition: border-width 0.2s ease-out;
            }
    </style>
</head>
<body>
    <div class="col-xl-12 col-lg-12">
        <div class="col-xl-4 col-lg-4">
            <label class="col-xl-4 col-lg-4 label-info form-control">name</label>
            <input id="id_name" class="col-xl-8 col-lg-8 form-control" type="text" name="name" />
        </div>
    </div>
    <div class="col-xl-12 col-lg-12">
        <div class="col-xl-4 col-lg-4">
            <label class="col-xl-4 col-lg-4 label-info form-control">password</label>
            <input id="id_password" class="col-xl-8 col-lg-8 form-control" type="password" name="password" />
        </div>
    </div>
    <div class="col-xl-12 col-lg-12">
        <div class="col-xl-4 col-lg-4">
            <label class="col-xl-4 col-lg-4 label-info form-control">Select an odd image from below</label>
        </div>
    </div>

    <div class="col-xl-4 col-lg-4">
        <div class="col-xl-4 col-lg-4">
            <table id="ID_Captcha_Table" class="table table-bordered">
                <tr id="ID_TD_Captcha"></tr>
            </table>
        </div>
    </div>
    <div class="col-xl-12 col-lg-12">
        <div class="col-xl-4 col-lg-4">
            <input id="ID_Save_Btn" type="button" name="name" value="Save" />
        </div>
    </div>
</body>
</html>
<script>
    var _CaptchaFlag = false;
    $(document).ready(function () {
        LoadCaptcha('ID_TD_Captcha', _CaptchaFlag);
    });
    $('#ID_Save_Btn').click(function () {
        console.log(document.getElementById('ID_TD_Captcha'))
        var _name = $('#id_name').val();
        var _password = $('#id_password').val();
        if (_name == undefined || _name == "") {
            alert('Please enter name');
            return;
        }
        if (_password == undefined || _password == "") {
            alert('Please enter password');
            return;
        }
        if (_CaptchaFlag == false) {
            alert('Please verify captch verification');
            return;
        }
        alert('Verified \nname : ' + _name + '\nPassword : ' + _password + '\nCaptchaFlag : ' + _CaptchaFlag);
    });
</script>


SQL STUFF Function and Get common grid data with pagination, filteration, sorting by sp & functions

========================================================================= STUFF FUNCTION ===================================================...