Tuesday, August 1, 2023

Python 2 Functions

Functions

 def hello():  
   print("Hello functions")  
 hello()  
Functions with Parameters
 def add(i, j):  
   return i + j  
 print(add(12, 23))  
Exception Handling
 try:  
   i = int(input("Enter value 1 : "))  
   j = int(input("Enter value 2 : "))  
   res = i / j  
   print(res)  
 except ValueError:  
   print("Invalid Input")  
 except ZeroDivisionError:  
   print("Cannot divide by zero")  
 def divide():  
   try:  
     i = int(input("Enter value 1 : "))  
     j = int(input("Enter value 2 : "))   
     res = i / j  
     print(res)  
   except ValueError:  
     print("Invalid Input")  
   except ZeroDivisionError:  
     print("Cannot divide by zero")  

divide()

Python

print

 print("Hello Python")  
Memory Variable
 name = "Shalvin P D"  
 print("Hello ", name)  
Multiple assignments
 name, passion = "Shalvin", "IT"  
 print(f"{name} - {passion}")  
input
 name = input("Enter your name : ")  
 print("Hello ", name)  
int()
 i = int(input("Enter value 1 : "))  
 j = int(input("Enter value 2 : "))  
 res = i + j  
 print(res)  
float()
 i = float(input("Enter value 1 : "))  
 j = float(input("Enter value 2 : "))  
 res = i + j  
 print(res)  
Lists
 technologies = [".Net", "Python", "Angular"]  
 for tech in technologies:  
   print(tech)  
Lists append()
 technologies = [".Net", "Python", "Angular"]  
 technologies.append("C#")  
 for tech in technologies:  
   print(tech)  
Lists remove()
 technologies = [".Net", "Python", "Angular", "C#", "PHP"]  
 technologies.remove("PHP")  
 for tech in technologies:  
   print(tech)  
Lists Concatenation

technologies1 = [".Net", "Python", "Angular", "C#"]

technologies2 = ["DevOps", "Jenkins"]

technologies = technologies1 + technologies2

for tech in technologies:
    print(tech)
Dictionary
 contact = {"name" : "Shalvin", "location": "Kochi"}  
 print(contact)  
 print(contact["name"])  
 print(f'{contact["name"]} : {contact["location"]}')  
List of Dictionaries
 contacts = [{"name" : "Shalvin", "location": "Kochi"},  
       {"name": "Praseed", "location": "UK"}]  
 print(contacts)  
 first_contact = contacts[0]  
 print(first_contact)  
 print(f"{first_contact['name']} - {first_contact['location']}")  
 
print("Listing all contacts") for contact in contacts: print(f"{contact['name']} - {contact['location']}")

Monday, May 29, 2023

Blazor I : Blazor Server Getting Started

Blazor is a free and open-source web framework that enables developers to create web apps using C# and HTML developed by Microsoft. Previously creating such apps required the knowledge of JavaScript Libraries/Frameworks like Angular, React, VueJS, JQuery, etc. Now it is possible for .Net developers to use their familiar tools and language (C#) to create compelling UIs. Blazor has different variants like Blazor Server, Blazor Web Assembly, Blazor United aka Full Stack Blazor (.Net 8), etc. In this article we will be concentrating on Blazor Server.

Blazor Server
Blazor Server is a Server Side technology for creating highly responsive Single Page Application (SPA). It uses SignalR web sockets to push the UI udates to browser. A persistent connection between Web Server and Client Browser is required for Blazor Server to work. So it is not possible to create Progressive Web Apps (PWA) with Blazor Server. Since Blazor is a Server Side technology it can access all the server resources including database access. No need of an exta Web API layer. Blazor Server works even on old Browsers.
Prerequisites
.Net (Core) 3 or later is required for building Blazor. Visual Studio is recommended by not mandatory. .Net CLI in combination with any editor can be used for creating Blazor Application which we will see later. .Net Core is platform independent so you can develop Blazor application in any platform you like. I am starting out with Visual Studio Community which is a freeware from Microsoft. I am selecting Blazor Server App as the project template.
L6g47FyqpZpu1hQbMYyZu7oWqKmuuifh_TbAeTzfrsOt5DtYY3pItgKrm5DiDCyvQGQLS7jc4Ie5Yq1dA1xEGxbp98b3MBhHs5jRgL4-ZFnBzyblpjyerLPAhnu72g/s480/Blazor%20New%20Project.png" style="display: block; padding: 1em 0; text-align: center; ">

Thursday, January 26, 2023

Creational Design Patterns

 

Creational design patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. They increase flexibility in deciding which objects need to be created for a given use case. Some of the most commonly used creational design patterns include:

  • Abstract Factory: Creates an instance of several families of classes.

  • Builder: Separates object construction from its representation, always creates the same type of object.

  • Factory Method: Creates an instance of several derived classes.

  • Prototype: A fully initialized instance to be copied or cloned.

  • Singleton: A class of which only a single instance can exist.

  • Abstract factory pattern: This pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

  • Builder pattern: This pattern separates the construction of a complex object from its representation, allowing the same construction process to create various representations.

  • Factory method pattern: This pattern defines an interface for creating an object, but allows subclasses to alter the type of objects that will be created.

  • Prototype pattern: This pattern specifies the kind of objects to create using a prototypical instance, and creates new objects by copying this prototype.

  • Singleton pattern: This pattern ensures that a class has only one instance and provides a global point of access to it.

It's important to note that, the best pattern to use depends on the specific situation, and it's important to weigh the trade-offs between the different options before implementing one.

Design Patterns

Design patterns are a set of best practices and solutions to common problems that occur in software design. They provide a way to structure code in a way that is easy to understand, maintain, and extend. 

There are several types of design patterns, including: 

Creational patterns, which deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. 

Structural patterns, which deal with object composition, creating relationships between objects to form larger structures. 

Behavioral patterns, which deal with communication between objects, what goes on between objects and how they operate together. 

 

 Some of the most well-known design patterns include: Singleton pattern, which ensures that a class has only one instance and provides a global point of access to it. Factory pattern, which creates objects without specifying the exact class of object that will be created. Observer pattern, which allows objects to be notified of changes to other objects. Decorator pattern, which allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. Strategy pattern, which allows an algorithm's behavior to be selected at runtime. Design patterns are not specific to any programming language, but they are often implemented in object-oriented languages like C# or Java. It's important to note that, while design patterns are a great way to solve common problems, they should be used judiciously, as overuse can lead to code that is hard to understand and maintain.

Sunday, April 24, 2022

ReactJS Part 9 : Fetch API POST

Fetch API is using for fetching resources over the internet.

 

import React, { useState } from 'react';

export function CreateGroup2(props) {
    const [nameValue, setNameValue] = useState("");
    const [detailsValue, setDetailsValue] = useState("");

    const createGroupData = async (event) => {
        event.preventDefault();
        let postData = {
            groupName: nameValue,
            description: detailsValue
        };
        let response = await fetch('api/groups', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(postData)
        });

    }

    return (
            <div>
                <form onSubmit={createGroupData}>
                     <div className="form-group">
                          <label htmlFor="name">Name</label>
                          <input
                                type="text"
                                className="form-control"
                                id="name"
                                onChange={(e) => setNameValue(e.target.value)} />
                     </div>
                     <div className="form-group">
                           <label htmlFor="description">Description</label>
                           <input
                               type="text"
                               className="form-control"                                    id="description"
                               onChange={(e) => setDetailsValue(e.target.value)} />
                     </div>
                     <button type="submit" className="btn btn-primary"  id="create-group">Submit</button>                   </form>

                </div>
    );
}


Saturday, April 23, 2022

ReactJS Part 8 .Net Core React - Connecting to Web API - Fetch API GET

The blog is a continuation of ReactJS Part 7 .Net Core React Project.

 In the blog Angular with .Net Core 3 and Visual Studio Code I have discussed creating Web API with .Net 5 CLI. 

Program.cs

using corereact.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();
builder.Services.AddScoped<ContactManagementContext>();
Scaffolded Web API Core Controller code.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using corereact2.Models;

namespace corereact2.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class GroupsController : ControllerBase
    {
        private readonly ContactManagementContext _context;

        public GroupsController(ContactManagementContext context)
        {
            _context = context;
        }

        // GET: api/Groups
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Group>>> GetGroups()
        {
            return await _context.Groups.ToListAsync();
        }

        // GET: api/Groups/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Group>> GetGroup(int id)
        {
            var @group = await _context.Groups.FindAsync(id);

            if (@group == null)
            {
                return NotFound();
            }

            return @group;
        }

        // PUT: api/Groups/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutGroup(int id, Group @group)
        {
            if (id != @group.GroupId)
            {
                return BadRequest();
            }

            _context.Entry(@group).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GroupExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Groups
        [HttpPost]
        public async Task<ActionResult<Group>> PostGroup(Group @group)
        {
            _context.Groups.Add(@group);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetGroup", new { id = @group.GroupId }, @group);
        }

        // DELETE: api/Groups/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteGroup(int id)
        {
            var @group = await _context.Groups.FindAsync(id);
            if (@group == null)
            {
                return NotFound();
            }

            _context.Groups.Remove(@group);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool GroupExists(int id)
        {
            return _context.Groups.Any(e => e.GroupId == id);
        }
    }
}

ReactJS Home.js
import React, {useState, useEffect } from 'react';

export function Home(){
  let [groupsData, setGroupsData] = useState([]);

  const populateGroupData = async () => {
    const response = await fetch('api/groups');
    const data = await response.json();
    return data;
}

useEffect(() => {
  populateGroupData()
      .then(data => setGroupsData(data));
}, []);

  return (
      <div>
        <h1>Groups</h1>
        <table className='table table-striped'>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Details</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    {groupsData.map(group =>
                        <tr key={group.groupId}>
                            <td>{group.groupName}</td>
                            <td>{group.description}</td>
                        </tr>
                    )}
                    
                </tbody>
            </table>
      </div>
    );
  }



ReactJS Part 7 .Net Core React Project

 Create-React-App is an excellent option for creating a new React application. Other options also exist. .Net React project can be considered if .Net Core Web API is the REST option for React. It handles a lot of plumbing issues for the developer. The routing is also configured.

 

In this blog I am going to handle the .Net CLI way of creating an .Net Core React application. My favorite editor is Visual Studio Code which comes with a good collection of useful extension. Any editor can be used.  The same is possible with Visual Studio also which I will handle on another blog. 


dotnet new react -o corereact


Inside the ClientApp folder is the ReactJS project.

 


 The .Net Core React Project comes packed with a few components. Notably the NavMenu.js comes with reacter-router.