Shalvin Interests

Sunday, February 1, 2026

Web API 10 Configure Swagger

Web API 10 doesn't come with default swagger support. It can be added by adding a reference to Swashbuckle.AspNetCode, registering the service, adding to middleware and making alterations to launchSettings.json.

 

image 

Program.cs
builder.Services.AddControllers();

builder.Services.AddOpenApi();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}
appsettings.json
"profiles": {
  "http": {
    ..
    "launchBrowser": true,
    "launchUrl": "swagger",
    "applicationUrl": "http://localhost:5172",
   ..
    }
  },

Tuesday, May 13, 2025

Ado .Net

ADO.NET Tutorial with Inline SQL Examples

1. Introduction to ADO.NET

ADO.NET is a data access technology in .NET that allows communication with relational databases using managed providers such as SqlClient and OleDb.

2. SqlConnection and SqlDataReader Example (C#)

This example demonstrates reading data using inline SQL:


<script runat="server">
using System.Data.SqlClient;

SqlConnection cnn;
SqlCommand cmd;
SqlDataReader dr;

protected void Page_Load(object sender, EventArgs e)
{
    cnn = new SqlConnection("Integrated Security=SSPI;Initial Catalog=Northwind");
    cnn.Open();
    cmd = new SqlCommand("SELECT * FROM Categories", cnn);
    dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        lstCategories.Items.Add(dr["CategoryName"].ToString());
    }
}
</script>

VB.NET Equivalent:


<script runat="server">
Imports System.Data.SqlClient

Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim dr As SqlDataReader

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    cnn = New SqlConnection("Integrated Security=SSPI;Initial Catalog=Northwind")
    cnn.Open()
    cmd = New SqlCommand("SELECT * FROM Categories", cnn)
    dr = cmd.ExecuteReader()
    While dr.Read()
        lstCategories.Items.Add(dr("CategoryName"))
    End While
End Sub
</script>

3. Inserting Records using Inline SQL


<script runat="server">
SqlCommand cmd;

protected void btnInsert_Click(object sender, EventArgs e)
{
    cmd = new SqlCommand("INSERT INTO Categories VALUES ('Condiments')", cnn);
    cmd.ExecuteNonQuery();
    MessageBox.Show("Record saved");
}
</script>

4. Inserting TextBox Values


<script runat="server">
protected void btnInsert_Click(object sender, EventArgs e)
{
    string strSql = "INSERT INTO Categories VALUES ('" + txtCategoryName.Text + "')";
    cmd = new SqlCommand(strSql, cnn);
    cmd.ExecuteNonQuery();
    MessageBox.Show("Record saved");
    txtCategoryName.Text = "";
    txtCategoryName.Focus();
}
</script>

5. Using DataAdapter and DataSet


<script runat="server">
using System.Data.SqlClient;

SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();

protected void Page_Load(object sender, EventArgs e)
{
    cnn = new SqlConnection("Integrated Security=SSPI;Initial Catalog=Northwind");
    da = new SqlDataAdapter("SELECT * FROM Categories", cnn);
    da.Fill(ds, "Categories");
    dataGridView1.DataSource = ds.Tables["Categories"];
}
</script>

6. Working with Multiple DataTables


<script runat="server">
SqlDataAdapter da;
DataSet ds = new DataSet();

protected void Page_Load(object sender, EventArgs e)
{
    cnn = new SqlConnection("Integrated Security=SSPI;Initial Catalog=Northwind");

    da = new SqlDataAdapter("SELECT CategoryId, CategoryName FROM Categories", cnn);
    da.Fill(ds, "Cat");

    da = new SqlDataAdapter("SELECT ProductId, ProductName FROM Products", cnn);
    da.Fill(ds, "Prod");

    dataGrid1.DataSource = ds;
}
</script>

7. Creating AutoIncrement Column in DataTable


<script runat="server">
DataTable dt = new DataTable("Purchase");
DataColumn dc;
DataRow dr;

protected void Page_Load(object sender, EventArgs e)
{
    dc = new DataColumn("ProductID", typeof(int));
    dc.AutoIncrement = true;
    dc.AutoIncrementSeed = 100;
    dc.AutoIncrementStep = 1;
    dt.Columns.Add(dc);

    dc = new DataColumn("ProductName");
    dt.Columns.Add(dc);

    dc = new DataColumn("Price");
    dt.Columns.Add(dc);

    dr = dt.NewRow();
    dr["ProductName"] = "Microsoft Mouse";
    dr["Price"] = 400;
    dt.Rows.Add(dr);

    dgPurchase.DataSource = dt;
}
</script>

8. ComboBox DisplayMember Binding


<script runat="server">
SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();

protected void Page_Load(object sender, EventArgs e)
{
    cnn = new SqlConnection("Integrated Security=SSPI;Initial Catalog=Northwind");
    da = new SqlDataAdapter("SELECT CategoryId, CategoryName FROM Categories", cnn);
    da.Fill(ds, "Cat");

    cboCategories.DataSource = ds.Tables["Cat"];
    cboCategories.DisplayMember = "CategoryName";
}
</script>

Sunday, October 28, 2018

React Native

React Native is a technology from Facebook to create native Android and iPhone applications. It uses the familiar JavaScript language and JSX syntax.

The easiest way to get started with React Native is to install Expo app in you mobile, going to https://snack.expo.io site and start coding. Setting up a development environment for React Native is a bit involved. We will take it up later.




>npm i -g create-react-native-app


>npm run android







Saturday, October 27, 2018

Node JS

Node is a JavaScript based Web Framework. Node's Non-blocking architecture makes it a very popular framework. V8 is the Virtual Machine of Node.


Node REPL
Once Node is installed, Node REPL can be invoked by typing node in the command prompt.



Typing tab tab in the prompt  displays  all Global command.

If you type a module name followed by tab tab it will display all the options pertaining to it.





Creating Http Server


const http = require('http');

const server = http.createServer((req, res) => {
  res.end('Hello World\n');
});

server.listen(4242, () => {
  console.log('Server is running...');
});


setTimeOut

setTimeout(
  () => {
    console.log('Hello after 4 seconds');
  },
  4 * 1000
);

Functions and Arguments
const consulting = who => {
  console.log(who + ' consulting');
};

setTimeout(consulting, 2 * 1000, 'Shalvin');

Thursday, October 25, 2018

Express JS

Hello Express


var express = require('express');

var app = express();

app.get('/', function (req, res) {
    res.send('Hello from Library app');
})

app.listen(3000, function () {
    console.log('listening ');
})


sendFile

In the previous example we just displayed some text. Now we are going to add an html file into the views folder and name it index.html.

var express = require('express');
var path = require('path');

var app = express();

app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, 'views', 'index.html'));
})

app.listen(3000, function(){
    console.log('listening');
})

Wednesday, February 28, 2018

React State Collection of Objects


import React, { Component } from 'react';
import Person from './Person/Person';



class App extends Component {
  state = {
    person: [{name:'Shalvin P D', location: 'Kakkanad'},
    {name:'Shibin', location: 'Trivandrum'}
  ]
  }

  render() {
    return (
      <div>
        <h2>State eg</h2>

        
        <Person name = {this.state.person[0].name} 
        location = {this.state.person[0].location}></Person>

      <Person name = {this.state.person[1].name} 
        location = {this.state.person[1].location}></Person>
      </div>
    );
  }
}

export default App;

Friday, June 23, 2017

Angular Routing

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { ContactComponent } from './contact/contact.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import {RouterModule, Routes} from '@angular/router';

@NgModule({
  declarations: [
    AppComponent,
    ContactComponent,
    DashboardComponent
  ],
  
   
  imports: [
    BrowserModule,
     RouterModule.forRoot([
       {path:'contact', component :ContactComponent},
       {path:'dashboard', component :DashboardComponent}
       ])
  ],
  providers: [],
  bootstrap: [AppComponent]
  
})
export class AppModule { }


app.component.ts

 <h1>{{title}}</h1>
 <a routerLink="/dashboard">Dashboard</a>
 <a routerLink="/contact">Contact</a>
   
  <router-outlet></router-outlet>

Wednesday, May 31, 2017

MVC 5 Code First with Existing Database - Training Management Project

Table Script
USE [TrainingManagement]

GO
CREATE TABLE [dbo].[Attendance](
    [AttendanceId] [int] IDENTITY(1,1) NOT NULL,
    [BatchId] [int] NULL,
    [FacultyId] [int] NULL,
    [Date] [date] NULL,
    [HoursTaken] [int] NULL,
    [CoveredModules] [varchar](200) NULL,
    [Remarks] [varchar](200) NULL,
 CONSTRAINT [PK_BatchSchedule] PRIMARY KEY CLUSTERED 
(
    [AttendanceId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Batch]    Script Date: 5/29/2017 8:23:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Batch](
    [BatchId] [int] IDENTITY(1,1) NOT NULL,
    [CourseId] [int] NULL,
    [BatchName] [varchar](40) NULL,
    [StartDate] [date] NULL,
    [TentativeEndDate] [date] NULL,
    [BatchTiming] [varchar](100) NULL,
    [Hours] [int] NULL,
    [HoursTaken] [int] NULL,
    [Fees] [int] NULL,
    [FeesPaid] [int] NULL,
    [Status] [varchar](15) NULL,
    [Remarks] [varchar](300) NULL,
 CONSTRAINT [PK__Batch__5D55CE58980177C0] PRIMARY KEY CLUSTERED 
(
    [BatchId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Course]    Script Date: 5/29/2017 8:23:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Course](
    [CourseId] [int] IDENTITY(1,1) NOT NULL,
    [CourseName] [varchar](40) NULL,
    [DurationInHours] [int] NULL,
    [Fees] [int] NULL,
    [Remarks] [varchar](200) NULL,
PRIMARY KEY CLUSTERED 
(
    [CourseId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Faculty]    Script Date: 5/29/2017 8:23:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Faculty](
    [FacultyId] [int] IDENTITY(1,1) NOT NULL,
    [FacultyName] [varchar](40) NULL,
    [Specialization] [varchar](40) NULL,
    [Phone] [varchar](15) NULL,
    [Email] [varchar](40) NULL,
PRIMARY KEY CLUSTERED 
(
    [FacultyId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Fees]    Script Date: 5/29/2017 8:23:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Fees](
    [FeesId] [int] IDENTITY(1,1) NOT NULL,
    [BatchId] [int] NULL,
    [Date] [date] NULL,
    [Amout] [numeric](8, 2) NULL,
    [Description] [varchar](200) NULL,
 CONSTRAINT [PK_Fees] PRIMARY KEY CLUSTERED 
(
    [FeesId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Student]    Script Date: 5/29/2017 8:23:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Student](
    [StudentId] [int] IDENTITY(1,1) NOT NULL,
    [BatchId] [int] NULL,
    [StudentName] [varchar](50) NULL,
    [YearsOfExperience] [int] NULL,
    [TechnologiesKnown] [varchar](100) NULL,
    [Location] [varchar](50) NULL,
    [Phone] [varchar](50) NULL,
    [Email] [varchar](200) NULL,
 CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED 
(
    [StudentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Attendance] ON 

INSERT [dbo].[Attendance] ([AttendanceId], [BatchId], [FacultyId], [Date], [HoursTaken], [CoveredModules], [Remarks]) VALUES (1, 1, 2, NULL, 2, N'JQuery Ajax', NULL)
INSERT [dbo].[Attendance] ([AttendanceId], [BatchId], [FacultyId], [Date], [HoursTaken], [CoveredModules], [Remarks]) VALUES (2, 1, 1, NULL, 5, N'Angular Service', N'Given enough assignments for two weeks.')
INSERT [dbo].[Attendance] ([AttendanceId], [BatchId], [FacultyId], [Date], [HoursTaken], [CoveredModules], [Remarks]) VALUES (3, 1, 1, NULL, 5, NULL, NULL)
INSERT [dbo].[Attendance] ([AttendanceId], [BatchId], [FacultyId], [Date], [HoursTaken], [CoveredModules], [Remarks]) VALUES (4, 2, 1, NULL, 3, NULL, NULL)
INSERT [dbo].[Attendance] ([AttendanceId], [BatchId], [FacultyId], [Date], [HoursTaken], [CoveredModules], [Remarks]) VALUES (5, 2, 1, NULL, 3, NULL, NULL)
INSERT [dbo].[Attendance] ([AttendanceId], [BatchId], [FacultyId], [Date], [HoursTaken], [CoveredModules], [Remarks]) VALUES (6, 2, 1, CAST(0xB03C0B00 AS Date), 5, N'Entity Framework', N'Entity Framework Database First')
INSERT [dbo].[Attendance] ([AttendanceId], [BatchId], [FacultyId], [Date], [HoursTaken], [CoveredModules], [Remarks]) VALUES (7, 5, 1, NULL, 5, NULL, NULL)
SET IDENTITY_INSERT [dbo].[Attendance] OFF
SET IDENTITY_INSERT [dbo].[Batch] ON 

INSERT [dbo].[Batch] ([BatchId], [CourseId], [BatchName], [StartDate], [TentativeEndDate], [BatchTiming], [Hours], [HoursTaken], [Fees], [FeesPaid], [Status], [Remarks]) VALUES (1, 2, N'Gemini Softwares ', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[Batch] ([BatchId], [CourseId], [BatchName], [StartDate], [TentativeEndDate], [BatchTiming], [Hours], [HoursTaken], [Fees], [FeesPaid], [Status], [Remarks]) VALUES (2, 2, N'.Net Morning', CAST(0x843C0B00 AS Date), CAST(0x46BD0B00 AS Date), N'Mornings 6.30 - 8.30 am and Sundays', 60, 38, 15000, 4, N'Ongoing', N'Slow batch')
INSERT [dbo].[Batch] ([BatchId], [CourseId], [BatchName], [StartDate], [TentativeEndDate], [BatchTiming], [Hours], [HoursTaken], [Fees], [FeesPaid], [Status], [Remarks]) VALUES (3, 3, N'State Syllabus', NULL, NULL, NULL, 60, NULL, 6000, NULL, NULL, NULL)
INSERT [dbo].[Batch] ([BatchId], [CourseId], [BatchName], [StartDate], [TentativeEndDate], [BatchTiming], [Hours], [HoursTaken], [Fees], [FeesPaid], [Status], [Remarks]) VALUES (4, 2, N'Technobay ', CAST(0x6C3C0B00 AS Date), NULL, N'Sundays', 60, 30, 15000, 4000, N'Ongoing', NULL)
INSERT [dbo].[Batch] ([BatchId], [CourseId], [BatchName], [StartDate], [TentativeEndDate], [BatchTiming], [Hours], [HoursTaken], [Fees], [FeesPaid], [Status], [Remarks]) VALUES (5, 1, N'Palnar Transmedia', NULL, NULL, NULL, 60, 0, 70000, NULL, NULL, NULL)
SET IDENTITY_INSERT [dbo].[Batch] OFF
SET IDENTITY_INSERT [dbo].[Course] ON 

INSERT [dbo].[Course] ([CourseId], [CourseName], [DurationInHours], [Fees], [Remarks]) VALUES (1, N'Asp .Net MVC', 60, 10000, N'Asp  .Net MVC 5')
INSERT [dbo].[Course] ([CourseId], [CourseName], [DurationInHours], [Fees], [Remarks]) VALUES (2, N'Asp .Net MVC and Angular', 100, 15000, N'Asp .Net MVC 5, Angular and TypeScript')
INSERT [dbo].[Course] ([CourseId], [CourseName], [DurationInHours], [Fees], [Remarks]) VALUES (3, N'State Plus 2', 60, 60000, N'State Syllabus Plus 2')
INSERT [dbo].[Course] ([CourseId], [CourseName], [DurationInHours], [Fees], [Remarks]) VALUES (5, N'Asp .Net Core', 60, 10000, N'If the candidates already know asp .Net MVC, then only 40 hours is required')
INSERT [dbo].[Course] ([CourseId], [CourseName], [DurationInHours], [Fees], [Remarks]) VALUES (6, NULL, NULL, NULL, NULL)
SET IDENTITY_INSERT [dbo].[Course] OFF
SET IDENTITY_INSERT [dbo].[Faculty] ON 

INSERT [dbo].[Faculty] ([FacultyId], [FacultyName], [Specialization], [Phone], [Email]) VALUES (1, N'Shalvin', N'MVC, Angular, TypeScript, C#', N'974580051w', N'shalvin@gmail.com')
INSERT [dbo].[Faculty] ([FacultyId], [FacultyName], [Specialization], [Phone], [Email]) VALUES (2, N'Mahin', N'MVC, Angular, TypeScript, C#, JQuery', N'78787878787', N'mahinna@gmail.com')
SET IDENTITY_INSERT [dbo].[Faculty] OFF
SET IDENTITY_INSERT [dbo].[Fees] ON 

INSERT [dbo].[Fees] ([FeesId], [BatchId], [Date], [Amout], [Description]) VALUES (1, 1, CAST(0xDD3C0B00 AS Date), CAST(20000.00 AS Numeric(8, 2)), N'Fees paid')
SET IDENTITY_INSERT [dbo].[Fees] OFF
SET IDENTITY_INSERT [dbo].[Student] ON 

INSERT [dbo].[Student] ([StudentId], [BatchId], [StudentName], [YearsOfExperience], [TechnologiesKnown], [Location], [Phone], [Email]) VALUES (1, 2, N'arun', 3, N'asp.net,sql,html', N'alappuzha', N'8943781437', NULL)
SET IDENTITY_INSERT [dbo].[Student] OFF
ALTER TABLE [dbo].[Attendance]  WITH CHECK ADD  CONSTRAINT [FK_BatchSchedule_Batch] FOREIGN KEY([BatchId])
REFERENCES [dbo].[Batch] ([BatchId])
GO
ALTER TABLE [dbo].[Attendance] CHECK CONSTRAINT [FK_BatchSchedule_Batch]
GO
ALTER TABLE [dbo].[Attendance]  WITH CHECK ADD  CONSTRAINT [FK_BatchSchedule_Faculty] FOREIGN KEY([FacultyId])
REFERENCES [dbo].[Faculty] ([FacultyId])
GO
ALTER TABLE [dbo].[Attendance] CHECK CONSTRAINT [FK_BatchSchedule_Faculty]
GO
ALTER TABLE [dbo].[Batch]  WITH CHECK ADD  CONSTRAINT [FK_Batch_Course] FOREIGN KEY([CourseId])
REFERENCES [dbo].[Course] ([CourseId])
GO
ALTER TABLE [dbo].[Batch] CHECK CONSTRAINT [FK_Batch_Course]
GO
ALTER TABLE [dbo].[Fees]  WITH CHECK ADD  CONSTRAINT [FK_Fees_Batch] FOREIGN KEY([BatchId])
REFERENCES [dbo].[Batch] ([BatchId])
GO
ALTER TABLE [dbo].[Fees] CHECK CONSTRAINT [FK_Fees_Batch]
GO
ALTER TABLE [dbo].[Student]  WITH CHECK ADD  CONSTRAINT [FK_Student_Batch] FOREIGN KEY([BatchId])
REFERENCES [dbo].[Batch] ([BatchId])
GO
ALTER TABLE [dbo].[Student] CHECK CONSTRAINT [FK_Student_Batch]
GO


DbContext
namespace TrainingManagementExistingDBCodeFirstShalvin.Models
{
    using System.Data.Entity;

    public partial class TrainingManagementContext : DbContext
    {
        public Model1()
            : base("name=Model1")
        {
        }

        public virtual DbSet<Attendance> Attendances { get; set; }
        public virtual DbSet<Batch> Batches { get; set; }
        public virtual DbSet<Course> Courses { get; set; }
        public virtual DbSet<Faculty> Faculties { get; set; }
        public virtual DbSet<Fee> Fees { get; set; }
        public virtual DbSet<Student> Students { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Attendance>()
                .Property(e => e.CoveredModules)
                .IsUnicode(false);

            modelBuilder.Entity<Attendance>()
                .Property(e => e.Remarks)
                .IsUnicode(false);

            modelBuilder.Entity<Batch>()
                .Property(e => e.BatchName)
                .IsUnicode(false);

            modelBuilder.Entity<Batch>()
                .Property(e => e.BatchTiming)
                .IsUnicode(false);

            modelBuilder.Entity<Batch>()
                .Property(e => e.Status)
                .IsUnicode(false);

            modelBuilder.Entity<Batch>()
                .Property(e => e.Remarks)
                .IsUnicode(false);

            modelBuilder.Entity<Course>()
                .Property(e => e.CourseName)
                .IsUnicode(false);

            modelBuilder.Entity<Course>()
                .Property(e => e.Remarks)
                .IsUnicode(false);

            modelBuilder.Entity<Faculty>()
                .Property(e => e.FacultyName)
                .IsUnicode(false);

            modelBuilder.Entity<Faculty>()
                .Property(e => e.Specialization)
                .IsUnicode(false);

            modelBuilder.Entity<Faculty>()
                .Property(e => e.Phone)
                .IsUnicode(false);

            modelBuilder.Entity<Faculty>()
                .Property(e => e.Email)
                .IsUnicode(false);

            modelBuilder.Entity<Fee>()
                .Property(e => e.Amout)
                .HasPrecision(8, 2);

            modelBuilder.Entity<Fee>()
                .Property(e => e.Description)
                .IsUnicode(false);

            modelBuilder.Entity<Student>()
                .Property(e => e.StudentName)
                .IsUnicode(false);

            modelBuilder.Entity<Student>()
                .Property(e => e.TechnologiesKnown)
                .IsUnicode(false);

            modelBuilder.Entity<Student>()
                .Property(e => e.Location)
                .IsUnicode(false);

            modelBuilder.Entity<Student>()
                .Property(e => e.Phone)
                .IsUnicode(false);

            modelBuilder.Entity<Student>()
                .Property(e => e.Email)
                .IsUnicode(false);
        }
    }
}



Course Model Class
namespace TrainingManagementExistingDBCodeFirstShalvin.Models
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    [Table("Course")]
    public partial class Course
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Course()
        {
            Batches = new HashSet<Batch>();
        }

        public int CourseId { get; set; }

        [StringLength(40, ErrorMessage ="Course name should not exceed 40 characters")]
        [Required(ErrorMessage = "Course is required")]
        [Display(Name = "Course")]
        public string CourseName { get; set; }

        [Display(Name ="Duration")]
        [RegularExpression("([0-9]+)", ErrorMessage ="Hours should be numeric")]
        public int? DurationInHours { get; set; }

        public int? Fees { get; set; }

        [StringLength(200)]
        public string Remarks { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Batch> Batches { get; set; }
    }
}


Batcch Model Class

namespace TrainingManagementExistingDBCodeFirstShalvin.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    [Table("Batch")]
    public partial class Batch
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Batch()
        {
            Attendances = new HashSet<Attendance>();
            Fees1 = new HashSet<Fee>();
            Students = new HashSet<Student>();
        }

        public int BatchId { get; set; }

        public int? CourseId { get; set; }

        [StringLength(40)]
        public string BatchName { get; set; }

        [Column(TypeName = "date")]
        public DateTime? StartDate { get; set; }

        [Column(TypeName = "date")]
        public DateTime? TentativeEndDate { get; set; }

        [StringLength(100)]
        public string BatchTiming { get; set; }

        public int? Hours { get; set; }

        public int? HoursTaken { get; set; }

        public int? Fees { get; set; }

        public int? FeesPaid { get; set; }

        [StringLength(15)]
        public string Status { get; set; }

        [StringLength(300)]
        public string Remarks { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Attendance> Attendances { get; set; }

        public virtual Course Course { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Fee> Fees1 { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Student> Students { get; set; }
    }
}


Attendance Model Class
namespace TrainingManagementExistingDBCodeFirstShalvin.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    [Table("Attendance")]
    public partial class Attendance
    {
        public int AttendanceId { get; set; }

        public int? BatchId { get; set; }

        public int? FacultyId { get; set; }

        [Column(TypeName = "date")]
        public DateTime? Date { get; set; }

        public int? HoursTaken { get; set; }

        [StringLength(200)]
        public string CoveredModules { get; set; }

        [StringLength(200)]
        public string Remarks { get; set; }

        public virtual Batch Batch { get; set; }

        public virtual Faculty Faculty { get; set; }
    }
}

Attendance Module
[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "AttendanceId,BatchId,FacultyId,Date,HoursTaken,CoveredModules,Remarks")] Attendance attendance)
        {
            if (ModelState.IsValid)
            {
                db.Attendances.Add(attendance);
                int intBatchId = Convert.ToInt32(Request.Form["BatchId"]);

                var Batch = (db.Batches.Where(b => b.BatchId == intBatchId)).FirstOrDefault();
                int intBatchHoursTaken = (int)Batch.HoursTaken;
                int intHoursTaken = Convert.ToInt32(Request.Form["HoursTaken"]);
                int intUpdatedHours = intBatchHoursTaken + intHoursTaken;
                Batch.HoursTaken = intUpdatedHours;
                 

                db.SaveChanges();
                return RedirectToAction("Index");
            }

Sunday, March 26, 2017

SharePoint Online AddIns


protected void Page_Load(object sender, EventArgs e)
        {
 
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                clientContext.Load(clientContext.Site);
                clientContext.Load(clientContext.Web, web => web);
                clientContext.Load(clientContext.Web.Lists);
                clientContext.ExecuteQuery();
                ListBox1.Items.Add(clientContext.Site.Url);
                ListBox1.Items.Add(clientContext.Web.Title);
                ListBox1.Items.Add(clientContext.Web.Url);
            }
        }



Thursday, February 2, 2017

Angular 2 Contact Management: Part 1 Getting Started

appmodule.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

import { AppComponent }  from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }


main.ts


import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

appcomponent.ts
import { Component } from '@angular/core';

export class Contact {
  id: number;
  name: string;
  spec:string;
}

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>{{contact.name}} details!</h2>
    <div><label>id: </label>{{contact.id}}</div>
    
    <div>
      <label>name: </label>
      <input [(ngModel)]="contact.name" placeholder="name">
    </div>
     <div>
      <label>specialization: </label>
      <input [value]="contact.spec" placeholder="name">
    </div>
   
    `
})
export class AppComponent {
  title = 'Contact Management';
  contact: Contact = {
    id: 1,
    name: 'Shalvin',
    spec: 'Angular'
  };
  
  
}

index.html

  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

Monday, January 30, 2017

Angular 2 Contact Management Part 3: Components


contact.ts
export class Contact {
  id: number;
  name: string;
  specialization:string;
}

app.component.ts
import { Component } from '@angular/core';
import {Contact} from './contact';


const CONTACTS: Contact[] = [
  { id: 11, name: 'Shalvin', specialization : '.Net' },
  { id: 12, name: 'Praveen', specialization : 'Big Data' },
  { id: 13, name: 'Anuraj', specialization : 'Asp .Net Core' },
  { id: 14, name: 'Praseed', specialization :'C++' },
  { id: 14, name: 'Yaneesh', specialization :'.Net' }
];

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>My Contacts</h2>
    <ul class="Contactes">
      <li  *ngFor="let Contact of Contacts"
        [class.selected]="Contact === selectedContact"
        (click)="onSelect(Contact)">
         {{Contact.name}}
      </li>
    </ul>
    <my-hero-detail [contact]="selectedContact"></my-hero-detail>
  `
})
export class AppComponent {
  title = 'Contact Management 2';
  Contacts = CONTACTS;
  selectedContact: Contact;

  onSelect(contact: Contact): void {
    this.selectedContact = contact;
  }
}
hero-detail.component.ts
import { Component, Input } from '@angular/core';

import { Contact } from './contact';
@Component({
  selector: 'my-contact-detail',
  template: `
    <div *ngIf="contact">
      <h2>{{contact.name}} details!</h2>
      <div><label>id: </label>{{contact.id}}</div>
      <div>
        <label>name: </label>
        <input [(ngModel)]="contact.name" placeholder="name"/>
      </div>
     
    </div>
     
  `
})
export class HeroDetailComponent {
  @Input()
  contact: Contact;
}

app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { AppComponent }  from './app.component';
import { HeroDetailComponent } from './contact-detail.component';
@NgModule({
    imports: [
    BrowserModule,
    FormsModule
    ],
      declarations: [
        AppComponent,
        HeroDetailComponent
      ],
      bootstrap: [ AppComponent ]
    })
    export class AppModule { }


Sunday, January 29, 2017

Angular 2 Contact Management Part 2 :Binding to Array of Class


app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

import { AppComponent }  from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }




On to the existing app.module.ts import FormModule which is essential for implementing two way data binding.

app.component.ts

import { Component } from '@angular/core';

export class Contact {
  id: number;
  name: string;
  specialization:string;
}

const CONTACTS: Contact[] = [
  { id: 11, name: 'Shalvin', specialization : '.Net' },
  { id: 12, name: 'Praveen', specialization : 'Big Data' },
  { id: 13, name: 'Anuraj', specialization : 'Asp .Net Core' },
  { id: 14, name: 'Praseed', specialization :'C++' },
  { id: 14, name: 'Yaneesh', specialization :'.Net' }
];

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>My Contacts</h2>
    <ul>
      <li  *ngFor="let Contact of Contacts"
         (click)="onSelect(Contact)">
         {{Contact.name}}
      </li>
    </ul>
    <div *ngIf="selectedContact">
      <h2>{{selectedContact.name}} details!</h2>
      <div><label>id: </label>{{selectedContact.id}}</div>
      <div>
        <label>name: </label>
        <input [(ngModel)]="selectedContact.name" placeholder="name"/>
      </div>
       <div>
        <label>Specailization: </label>
        <input [(ngModel)]="selectedContact.specialization" placeholder="specialization"/>
      </div>
    </div>
  `
})
export class AppComponent {
  title = 'Contact Management';
  Contacts = CONTACTS;
  selectedContact: Contact;

  onSelect(Contact: Contact): void {
    this.selectedContact = Contact;
  }
}

 

 Clicking on a Contact it's details will be displayed below.

Wednesday, January 18, 2017

TypeScript Part 2 : Classes


TypeScript class

class Contact{
    constructor(
        public name: string, public location: string)
    {

    }
}

var aPerson: Contact = new Contact("Shalvin", "Kochi")
alert('I am ' + aPerson.name + ' from '+ aPerson.location);

ES5
var Contact = (function () {
    function Contact(name, location) {
        this.name = name;
        this.location = location;
    }
    return Contact;
}());
var aPerson = new Contact("Shalvin", "Kochi");
alert('I am ' + aPerson.name + ' from ' + aPerson.location);




TypeScript Part 1: DataTypes and Array

TypeScript is an open source, cross platform and  strongly typed super set of  JavaScript. TypeScript can be  transcompiled into ES5, so that it can be used along with HTML.

TypeScript Data Types

var sName: string = 'Shalvin';
alert(sName);

ES5
var sName = 'Shalvin';
alert(sName);



let
let can also be use to declare memory variable. let can be used to circumvent “hoisting”.



let sName: string = 'Shalvin';
alert(sName);

Tryout


TypeScript Array

var myArr: Array<number> = [1, 2, 3];
for (let n of myArr) {
    alert(n);
}

JavaScript
var myArr = [1, 2, 3];
for (var _i = 0, myArr_1 = myArr; _i < myArr_1.length; _i++) {
    var n = myArr_1[_i];
    alert(n);
}

Tuesday, August 30, 2016

Bootstrap MVC Layout with Left navigation bar


<!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")

</head>
<body>
        
    <div class="nav navbar-fixed-top">
        @Html.ActionLink("Shalvin Institute Management", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
    </div>

    <div class="row">
        <div class="row col-md-2">
            <div class="navbar navbar-inverse">
                <div class="container">
                    <div class="navbar-header">
                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                       
                    </div>

                    <div class="row">
                        <ul class="nav">
                            <li>@Html.ActionLink("Home", "Index", "Home")</li>
                            <li>@Html.ActionLink("About", "About", "Home")</li>
                            <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <div class="row col-md-10">
            @RenderBody()
        </div>
    </div>
    
    <div class="container body-content">
       
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - Shalvin P D</p>
        </footer>
    </div>

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



Bootstrap TextBox with DropDown


<div>Name <div class ="dropdown">
     <input type="text" data-toggle="dropdown"/>
           <ul class ="dropdown-menu">
               <li>Shalvin</li>
               <li>Bibbin</li>
           </ul>
</div> 


Thursday, August 25, 2016

Abstract Class C#

An Abstract class is a class with incomplete functionality.
It shall or shall not have abstract methods. As in the case with Interface you can't create an object of Abstract class.



abstract class Person
{
        public abstract void Print();
        public void Blog()
        {
            Console.WriteLine("ShalvinPD.blogspot.com");
        }
}

class Shalvin : Person
{
        public override void Print()
        {
            Console.WriteLine("Shalvin P D");
        }
}
   
class Program
{
        static void Main(string[] args)
        {
            //Error cannot create an object of Abstract Class
            //Person p = new Person();

            Shalvin s = new Shalvin();
            s.Print();
            s.Blog();
            Console.ReadLine();
        }
}

Here I am having an Abstract class called person with an abstract method called Print and an ordinary method called blog. In the sub class I am overriding the abstract Print method.


Method overriding C#




class  Person
    {
        public virtual  void Print()
        {
            Console.WriteLine("Hello Person");
        }
    }

    class Shalvin : Person
    {
        public override void Print()
        {
            Console.WriteLine("Hello Shalvin");
        }
        
    }

   class ShalvinPD : Shalvin
    {

    }
    class Reshma : Person
    {
        public override void Print()
        {
            Console.WriteLine("Hello Reshma");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.Print();

            Shalvin s = new Shalvin();
            s.Print();

            ShalvinPD spd = new ShalvinPD();
            spd.Print();

            Reshma r = new Reshma();
            r.Print();

            Console.ReadLine();
        }
    }
}


Sunday, June 26, 2016

Android SQLite Database Connnectivity



import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void btnAddClick(View view) {

        EditText editText = (EditText)findViewById(R.id.etName);
        String strExpense = editText.getText().toString();
        SQLiteDatabase sqLiteDatabase = openOrCreateDatabase("ExpenseDB",  MODE_PRIVATE, null);

        String create = "CREATE Table IF NOT EXISTS Expenses (ExpenseId integer primary key autoincrement, ExpenseName varchar(40));";
        sqLiteDatabase.execSQL(create);

        String insert = "INSERT INTO Expenses (ExpenseName) values ('" + strExpense + "');";
        sqLiteDatabase.execSQL(insert);
        Toast.makeText(MainActivity.this, "Record Saved", Toast.LENGTH_SHORT).show();
        editText.setText("");

        }

    public void btnShowClick(View view) {
        SQLiteDatabase sqLiteDatabase = openOrCreateDatabase("ExpenseDB",  MODE_PRIVATE, null);

        String strSelect  = "select * from Expenses;";
        Cursor cursor = sqLiteDatabase.rawQuery(strSelect, null);
        TextView textView = (TextView)findViewById(R.id.tvExpense);
        if(cursor.getCount() > 0)
        {
            cursor.moveToFirst();
            do {
                String expense = cursor.getString(1);
                textView.setText(textView.getText() + "\n" + expense);
            }while (cursor.moveToNext());
        }
    }
}


Android WebView


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView webView = (WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("http://shalvinpd.blogspot.com");
    }