Sunday 26 May 2024

C# Custom Data Data Annotation - Validators with Example

 (1) What is Custom Data Annotations in C# model class? 

       When Custom Data Annotation useful? 

Ans : You have learn and regular and basic Data Annotation for validaion.

We  can apply validation at Model (POCO) class by using appropriate attribute.
Like Required, StringLength, MaxLength, EmailAddress and many more.

Now add following code for UI side
@model WebAppCustomDataAnnotation.Models.Student
<h2>Create</h2>

@using (Html.BeginForm()) 
{    
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
}


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

In this post we focus on custom Data Annotation.


When default attribute not sufficient to achieve our validation.
When validation is not achievable by Microsoft provided attribute


For example - We have a Student table in Data base.


Before saving record, We need to check EMail value must be unique.

But this is not achievable my available basic attribute.
But to tackle this limitation, we have Custom Data Annotation.
Assume system already contain email - "name@company.com"
If user try to insert same value again then validation must be there.
and error message will be prompt.

Create new class :

UniqueEmailAttribute and inherit ValidationAttribute.

public class UniqueEmailAttribute : ValidationAttribute { protected override ValidationResult IsValid(object _value, ValidationContext validationContext) { if (_value != null && _value.ToString() == "name@company.com") { return new ValidationResult(ErrorMessage = "Email address already exist"); } return ValidationResult.Success; } }


Here we have create Custom Data Annotation. 
It contain IsValid() method.
We have override this method and added logic to check existing value.

Provided Email value come at first parameter : object _value

If input email value is "name@company.com" then
it will return Error message.

Otherwise will return Success.(Validation passed)

You can provide error message as per your requirement.

This Method return ValidationResult.

Final Step :
Now add this created custom data annotation as attribute 
at Email property in Student class.
[Required(ErrorMessage = "Email address is required.")]
[UniqueEmail]
public string Email { get; set; }


Here error message is hard coded. but in real scenario it never happen.
So error message must be dynamicaly need to set.
In Student model - along with custom attribute "UniqueEmail", 
need to add ErrorMessage as shown in bellow.


As Error message set in Attribute, will show in bellow display 
when in Email field value added and "Create" button clicked as shown bellow.








Saturday 26 August 2023

SQL interview question Part-2

 Note :  All sql related question related to SQL Server.

(1) In SQL : How to swap column values​​ ?










Ans : 
update #tempSwap set EMPNAME = DEPT,DEPT = EMPNAME;
















Tuesday 1 August 2023

SQL interview question Part-1

Note :  All sql related question related to SQL Server.

(1) How to get current Age based on BirthDate ?

SELECT top 5 BirthDate,  DATEDIFF ( YEAR ,BirthDate , getdate() )  as age,LoginID

  FROM [HumanResources].[Employee]






(2)  What is the output when you concate two null value using plus '+'  operator ?
        SELECT NULL +  NULL;

Ans : It will resturn single null value.












(3)  What is the output when you concate two null value using CONCATE function ?
        SELECT CONCAT (NULL, NULL)

Ans : It will resturn empty string/ blank value.





(4)  What is the output of the following code ?
        
DECLARE @TempVariable AS NVARCHAR(50)
SET @TempVariable = 'Hello World'

PRINT @TempVariable

Ans : "Hello World"


(5)  What is the output of the following code ?

DECLARE @TempVariable AS NVARCHAR(50)
SET @TempVariable = 'Hello World'

GO
PRINT @TempVariable

Ans : It will gices error. - Must declare the scalar variable "@PurchaseName".
Reason is local variable scope expires at the end of the batch once "Go" statement came.

(6)  Teacher table have 6 records, contain LastName valiues as shown in bellow.











 What is the output of the following code ?

declare @tempLastName nvarchar(50);

select @tempLastName = LastName from [EF_Demo_DB].[dbo].Teacher;

select @tempLastName;

Ans : Jena

Explanation : Value of LastName from last record will be set in local variable @tempLastName.


(7)  What is output of following code snipet.

print null;

Ans : Blank 
Explanation : We cant print null value in sql server.



(8)  What is output of following code snipet.

Declare @localvariable nvarChar(50) =  NULL;

PRINT @localvariable + 'Tech for Boost';

Ans : Blank 
Explanation : concate with null value return blank value.



(9)  What is output of following code snipet.

declare @localvariable nvarchar(50) =  NULL;

PRINT 'Tech for Boost' + @localvariable;

Ans : Blank 
Explanation : concate with null value return blank value.

Null value containted variable in concation using '+' operator is first or second pposition does not matter.

but concation of null value using CONCAT function gives different result. Let's see with example.


(10)  What is output of following code snipet.

declare @localvariable nvarchar(50) =  NULL;

print CONCAT('Tech for Boost', @localvariable);

-- or
print CONCAT(@localvariable, 'Tech for Boost');

Ans Tech for Boost


(11)  Can we use GROUP BY clause without aggregate function ?

Ans Yes, let's see with example. We have table EmployeeSalary






















Monday 31 May 2021

C# interview question Part-1

(1) C# default access modifier

namespace :    public        
enum        :    public
interface :    public
class     :   private

struct           :   private

delegate         :   private  

constructor      :   private (note if no constructor is explicitly defined, 
                            a public default constructor will be automatically defined)
    
method           :   private
field :  
private
enum member      :  public
cinterface memberpublic
For example
namespace AccessDemo
{
    class OuterClass
    {
        void MethodA() {}
        class InnerClass {}
    }
}


is equivalent to

namespace AccessDemo
{
    internal class OuterClass
    {
        private void MethodA() {}
private class InnerClass {}
} }
(2)In Console Application, how to get input from the user ?
 Console.Write("Enter a string - ");
Console.Write("Enter input : ");
string userinput = Console.ReadLine();
Console.WriteLine("You entered '{0}'", userinput
);

output :

Enter input : test input
You entered 'test input'
'

Sunday 10 January 2021

Angular MCQ : Angular Fundamentals : Part 5

(1) When filtering data, why should you create a copy of the data being filtered?

• To improve performance

• To improve performance

• In case you want to make edits to the data

• To maintain the order between page refreshes

• Otherwise you will lose data


(2) How do you specify where your routed components will appear in your application?

• They always appear just inside the <body> tag of your index.html.

• Use the <router-view> component.

• Use the <router-outlet> component.


(3) Once you have defined routes, how do make the router aware of them?

• Use RouterModule.forRoot or RouterModule.forChild in your Angular module.

• You don't need to make the router aware of them, declaring them as the data type "Routes" is sufficient.

• Import your routes file using a <script> tag in your index.html.

• Add the routes array to the declarations section of your module.


(4) What is the TestBed used for?

• Creating utilities for mocking services

• Integrating HTTP with Tests

• Creating mock child components

• Mimicking a Live Environment for Components


(5) What is Tree Shaking?

• An Optimization algorithm for binary searches

• A way to put multiple pieces of code together

• Automated removal of unused code


(6) When bootstrapping an Angular app, how do you specify the main Angular app module to load?

• Angular discovers the module based on the component that was bootstrapped.

• You load your module directly in your index.html file.

• You add your Angular module as a package in your SystemJs config.

• In your main SystemJs package (e.g. main.ts), you pass your app module into the platformBrowserDynamic.bootstrapModule() method,.


(7) When would you create a custom pipe?

• If you need to format an absolutely positioned node

• If you need to sort and filter your data

• If you need to have some business-specific formatting


(8) Which of the following is used as a container for components, services, directives, etc.?

• Dependency Injection

• An Angular Modules

• SystemJS


(9) Why would you use a setter on an @Input directive?

• To created a derived value on an Input value

• To validate the value of an Input

• To create a read-only input value


(10) How do you specify the html tag (e.g. <event-details>) to use for a component?

• You set the selector property in the component meta-data config.

• You set the tag property in the component meta-data config.

• You name the file that contains your component to match the tag name you want.

• You specify the tag name when declaring the component in your Angular module.


<<Angular Fundamentals part-4