Monday, 4 February 2019

Extension methods in C#

Extension methods in C#


public static void AllowWholeNumberOnly(this KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar)) e.Handled = true;
if (e.KeyChar == (char)8) e.Handled = false;
}

public static void AllowNumbericValueOnly(this KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar)) e.Handled = true;
if (e.KeyChar == (char)8) e.Handled = false;
if (e.KeyChar == (char)46) e.Handled = false;
}

public static bool AllowDecimalValueOnly(object sender, KeyPressEventArgs e)
{
var IsValid = false;
IsValid = (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46)) ? true : false;

// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
IsValid = ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1) ? true : false;
}

return IsValid;
}

public static void AllowAlphabeticalValueOnly(this KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar)) e.Handled = true;
if (e.KeyChar == (char)8) e.Handled = false;
if (e.KeyChar == (char)46) e.Handled = false;
}

Reverse the string

Reverse the string


Reverse the string by for Loop


using System;

namespace ConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string inputString = Console.ReadLine();
            string reverse = ReverseString(inputString);
            Console.WriteLine(string.Format("Reverse string of {0} is {1}", inputString, reverse));
            Console.ReadLine();
        }

        public static string ReverseString(string inputString)
        {
           string reveseString = "";
            char[] inputStringArr = inputString.ToCharArray();
            for (int i = inputStringArr.Length - 1; i <= inputStringArr.Length && i >= 0; i--)
            {
                reveseString += inputStringArr[i];
            }
            return reveseString;
        }
    }
}

Reverse the string by While Loop

using System;

namespace ConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string inputString = Console.ReadLine();
            string reverse = ReverseString(inputString);
            Console.WriteLine(string.Format("Reverse string of {0} is {1}", inputString, reverse));
            Console.ReadLine();
        }

        public static string ReverseString(string inputString)
        {
            string reveseString = "";
            char[] inputStringArr = inputString.ToCharArray();
            int j = inputStringArr.Length - 1;
            while (j >= 0)
            {
                reveseString += inputStringArr[j];
                j--;
            }
            return reveseString;
        }
    }

}



Minimum in SubArrays

Minimum in Sub Arrays


You are given an array A[] of size N and an integer K.
Your task is to print the Minimum element for each subarray of size 'k'.
In other words, for Each Valid Index i (1 <= i <= N - K)
You have to print min(A[i], A[i + 1], A[i + 2] .... A[i + k]).

Input Format
The First line will contain two Integers N and K.
The Second Line will contain N Integers denoting the elements of Array A[].

Constraints
1 <= N <= 10^5
1 <= K <= N
1 <= A[i] <= 10^6

Output Format
Print the Minimum elements for each subarray of Size K separated by space.


Sample TestCase 1

Input
5 2
10 0 3 2 5

Output
0 0 2 2

Code:

using System;
using System.Linq;

namespace ConsoleApp
{
    internal class DonNetTest
    {
        private static void Main(string[] args)
        {
            string inputFirstLine = System.Console.ReadLine();
            string[] firstLine_arr = inputFirstLine.Split(' ').ToArray();

            int n = Int32.Parse(firstLine_arr[0]);
            int k = Int32.Parse(firstLine_arr[1]);

            int[] arr = new int[k];

            string inputSecondLine = System.Console.ReadLine();
            string[] secondLine_arr = inputSecondLine.Split(' ').ToArray();
            arr = Array.ConvertAll(secondLine_arr, Int32.Parse);

            printMinimumArray(n, k, arr);
        }

        private static void printMinimumArray(int n, int k, int[] arr)
        {
            int j, min;

            for (int i = 0; i <= n - k; i++)
            {
                min = arr[i];

                for (j = 1; j < k; j++)
                {
                    if (arr[i + j] < min )
                        min = arr[i + j];
                }
                Console.Write(min + " ");
            }
        }
    }
}



Monday, 14 January 2019

Simple and Trick Question Answer SQL

Q.1 Below query will execute or give error.
     
       SELECT *,YEAR(CreatedOn) AS Yr FROM Customer WHERE YEAR(CreatedOn) > 2017;


Ans :-It will give records which year is greater than 2017.


Q.2 Below query will execute or give error.
 
SELECT CASE WHEN NULL=NULL THEN 'YES' ELSE 'NO' END

Ans :- Execute - NO

Q.3 What will be result?

    a)   SELECT COUNT(*);
    b)   SELECT SUM(NULL);

ANS :-  a) 1
             b) Operand data type NULL is invalid for sum operator.              

Q.4 Single query for update swap record?

       e.g  :- if customer table have one column i.e. Gender and some are Female & some Male then                update Female to Male & Male to Female.

ANS :-

     UPDATE Customer
     SET Gender = (CASE WHEN Gender='Female' THEN 'Male' ELSE 'Female' END);

Q.5 How to get nth salary in sql?

ANS :-
             WITH ResultCTE AS
              (
                 SELECT Salary,DENSE_RANK() OVER (ORDER BY Salary DESC) as DeskRank
                 FROM Employee
               )
              SELECT Salary FROM ResultCTE  WHERE ResultCTE .DeskRank=nth;

Q.6 How to delete duplicate record from table?

ANS :-
             WITH ResultCTE AS
              (
                 SELECT *,Row_Number() OVER (Partition by Id ORDER BY Id) as RowNumber
                 FROM Employee
               ) 
              DELETE From ResultCTE WHERE RowNumber > 1;


Sunday, 10 June 2018

Access-Control-Allow-Origin Header in ASP.NET Core Web API


Add Setting in Startup Class.


 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();
            services.AddCors();
        }

        // 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();
            }
            app.UseCors(builder =>
            {
                builder.AllowAnyHeader()
                       .AllowAnyOrigin()
                       .AllowAnyMethod();
            });
            app.UseMvc();
        }
    }

Wednesday, 7 March 2018

allow only numbers or decimal in textbox

Allow only numbers or decimal in textbox



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RNDWithNumbers.aspx.cs"
    Inherits="TabFormWebApp.RNDWithNumbers" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Script/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        function isNumberWithDecimalKey(evt, obj) {
            var charCode = (evt.which) ? evt.which : event.keyCode
            var value = obj.value;
            var dotcontains = value.indexOf(".") != -1;
            if (dotcontains)
                if (charCode == 46) return false;
            if (charCode == 46) return true;
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
            return true;
        }

        function isNumber(evt) {
            evt = (evt) ? evt : window.event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                return false;
            }
            return true;
        }

    </script>
</head>
<body>
    <form id="frm" runat="server">
    <table>
        <tr>
            <td>
                Only Number
            </td>
            <td>
                <input type="text" id="txtAllowNumber" onkeypress="return isNumber(event)" />
            </td>
        </tr>
        <tr>
            <td>
                Only Number With Decimal
            </td>
            <td>
                <input type="text" id="txtAllowNumberWithDecimal" onkeypress="return isNumberWithDecimalKey(event,this)" />
            </td>
        </tr>
    </table>
    <br />
    </form>
</body>
</html>

Friday, 2 February 2018

MongoDB CRUD Operations

MongoDB CRUD Operations

 CREATE DATABASE IN mongoDB

  MongoDB use DATABASE_NAME is used to create database. The command will create a new database if it doesn't exist, otherwise it will return the existing database.

Syntax

syntax of create database is as follows - e.g. : use DataBaseName
Like :- use TestDB


Note :- CURD means  create, read, update, and delete

1 :- CREATE COLLECTION

MongoDB createCollection(name, options) is used to create collection.

e.g :- db.createCollection("Student", { size: 2147483648 } )



2 :- CREATE OPERATIONS
                       
syntax :- 1) db.collection.insertOne()
              2) db.collection.insertMany()  


Note:- (INSERT Data into Collection)

e.g :-1--) if insert one record

 db.Student.insertOne( { name: "mohan", class: "BCA", rollno :5} );

e.g :- 2--) if insert multiple record at one time

db.Student.insertMany( [
        { name: "mohan", class: "BCA", rollno :5},
        { name: "sohan", class: "MBA", rollno :15},
        { name: "ram", class: "BBA", rollno :10},
        { name: "shyam", class: "MCA", rollno :25},
   ] );


3 :- READ OPERATIONS

syntax : db.collection.find(query, projection)

e.g :- db.Student.find()

e.g :-1) db.Student.find({ name: "shyam" })

e.g :-2) db.Student.find( { rollno : 5 } )


4 :- UPDATE OPERATIONS


syntax :- db.collection.update(selectQuery, udateQuery)

e.g :-1 ) 

db.Student.update({'name':'shyam'},{$set:{'name':'shyam kumar'}})

db.Student.update({'id':'2'},{$set:{'name':'Mohan kumar'}})

e.g :-2) 

Note:- update class where rollno is greater than 10

db.Student.updateMany(
      { rollno : { $gt: 10 } },
      { $set: { "class" : 'PHD'} }
   );

5 :- DELETE OPERATIONS

syntax :-1 ) db.collection.deleteOne()
           :-2 ) db.collection.deleteMany()

e.g:- 1)

db.Student.deleteOne( { rollno : 4 } )




Factorial of a Number

Recently Viewed