Asp.net c# sql server jQuery sitemap java script linq outputcache cookieless session URL path Interview Questions Asp.net c# sql server jQuery sitemap java script linq outputcache cookieless session URL path Interview Questions

Chitika

Friday, July 3, 2020

Un Check radio button on second time selected

Radio button in general can't be un checked when we select for the second time.
We can do it using code.

Ex: if we have below radio buttons

<input type="radio" id="rbnEgg" name="rdNV" value="Egg" runat="server"  />
  <label for="rbnEgg">Egg</label>
  <input type="radio" id="rbnChicken" name="rdNV" value="Chicken" runat="server" />
  <label for="rbnChicken">Chicken</label>

Use below script to check and uncheck the selection

<script language="javascript">
 $(document).on("click", "input[name='rdNV']", function(){
    thisRadio = $(this);
    if (thisRadio.hasClass("imChecked")) {
        thisRadio.removeClass("imChecked");
        thisRadio.prop('checked', false);
    } else {
        thisRadio.prop('checked', true);
        thisRadio.addClass("imChecked");
        if (thisRadio.context.id == 'rbnEgg') {
            $('input[id=rbnChicken]').removeClass("imChecked");
            $('input[id=rbnChicken]').prop('checked', false);
        }
        else if (thisRadio.context.id == 'rbnChicken') {
           $('input[id=rbnEgg]').removeClass("imChecked");
           $('input[id=rbnEgg]').prop('checked', false);
        }
    };
        })

Here i am un-checking only one radio button, if there are multiple radio buttons uncheck all the radio buttons before the statement : thisRadio.prop('checked', true);

Monday, July 6, 2015

Read XML using XMLDocument class by tag / attribute / value in C#

We can read XML from C# in many ways, here is the easiest way to do that.

Let's take the below XML for reference,
<Regions>
  <Region name="ASIA" code="ASI">
    <Country name="India" code="IND"></Country>
    <Country>Pakistan</Country>
    <Country>Japan</Country>
    <Country>China</Country>
  </Region>
  <Region name="Europe" code="Eu">
    <Country name="Greece" code="GR"></Country>
    <Country>Russia</Country>
    <Country>Italy</Country>
    <Country>United Kingdom</Country>
  </Region>
</Regions>

We have Regions as root tag and Region as child nodes for that.
Each region will have multiple countries as child nodes to region tag.

First read the XML using XMLDocument class, which is under System.XML name space.

            var xmlDo = new XmlDocument();
            xmlDo.Load("d:\\Countries.xml");

I have hard coded the path above, but you can refer dynamically from project folder.

           To get all the xml nodes with tag name
            XmlNodeList itemNodes = xmlDo.SelectNodes("Regions/Region");
By using above statement we get two xml nodes, because we have two "Region" tags in xml.

We can get single region by providing any of the unique property for the region .
       To get all the xml nodes by filter with value
      XmlNodeList itemNodesbyValue = xmlDo.SelectNodes("Regions/Region[@name='ASIA']");
Here we have used ASIA as filter now we get only one region tag with name as "ASIA".

We can get single node by using "SelectSingleNode" method as below,

        XmlNode xnode = xmlDo.SelectSingleNode("Regions/Region[@name='ASIA']");

As we got the xml node we can find the values of the properties for that node using attributes as below,
         
            string nodeValue = xnode.Attributes["code"].Value;
From the above statement we can get value as "ASI" of attribute "code".
Like the one we can get any value of the attribute, once we get the XML node.

In the above you can observe the top-down approach, first we got all the XML nodes by using the tag, then we filtered using the property of the tags, then we got single node reading, then after we read the value of the property.

Happy coding ,,,

Tuesday, June 23, 2015

Unit Testing with Fakes( Shims & Stubs )

What is Fakes: 
Microsoft Fakes is a testing framework which helps us to test code and introduce fake object for external dependencies.  This framework is mostly useful in test driven development and also can be used in functional driven development.
We can create fakes using two ways
  • Shims
  • Stubs

Stub is that part of the code which gets executed instead of the actual code. When you run unit test against a unit of code and the code consist of objects that are reference by interfaces then we use stubs to create fake objects and execute that functionality. Stub should not be used for classes they are strictly for interfaces and abstract class.
Shims are another type of fakes that execute methods and return values so that actual method that is unit tested is not broken and testing is well under control.

Pre-requisites:
·         Visual Studio 2012 Premium or above

Shim Example:
  1. Create new project, then select “Unit Test Project” under Test Category 
 

  1. Assume that you have code as below in in your project
namespace HRMS
{
    public class Employee
    {// Business Layer
        public Emp GetEmployeeDetails(int id)
        {
            DataLayer dlData = new DataLayer();
            return dlData.GetEmployeeData(id);
        }
    }

    public class Emp
    {// Model
        public int ID;
        public string Name;
        public String Location;
    }

    class DataLayer
    {// Data Layer
        internal Emp GetEmpData(int id)
        {
            return new Emp { Location = "HYD", Name = "Jhon" };
        }
    }
}

Now we will test “GetEmployeeDetails” method.
  1. Add your testable project dll to unit test project. Here “HRMS.dll” will be added to our “UnitTestWithFakes” project.
  2. Now Right click on HRMS.dll and click on “Add Fakes Assembly”,


  1. After adding it will create HRMS.Fakes.dll and HRMS.Fakes files in your project,

  1. Add using statement of your fakes dll as using HRMS.Fakes;
  2. Now create a test method as below in your test project,
        [TestMethod]
        public void GetEmployeeDetailsTest()
        {
// Everything should be under the context of Shim only by using shimsContext
            using (ShimsContext.Create())
            {
//Method to give the fake data using delegates
                ShimDataLayer.AllInstances.GetEmployeeDataInt32 = (instance, empid) =>
                    {
                        return new Emp { Location = "Bangalore", Name = "Scott" };
                    };

                Employee employeeObj = new Employee();
                Emp response = employeeObj.GetEmployeeDetails(101);
                Assert.AreSame("Scott",response.Name);
            }
        }
In the above example we are calling “GetEmployeeDetails” in that it is internally calling “GetEmployeeData”, we shim that method to replace the database call and provide dummy data.
While executing when the process reach “GetEmployee”, it will come to our delegate and whatever we pass from that it will take and return.
Now if you observe the class name will be shimmed and we get all the methods in the “AllInstances” of that class, by appending the parameters to the method, in the above case “GetEmployeeData” is the method and Parameter type is “Int32”. I.e. it is “GetEmployeeDataInt32”.
Parameters for the delegate is MethodParametersCount+1.
For testing purpose, I have tested with employee name.

Stub Example:
  1. Prepare an interface as below , in this case “IEmployee” is interface and  method is “CheckEmployeeExist
public interface IEmployee
    {
        bool CheckEmployeeExist(int EmpID);
    }
  1. Implement the interface, we can have multiple methods as well, I have taken one for sample,
    public class DataLayer : IEmployee
    {// Data Layer
        public bool CheckEmployeeExist(int id)
        {// In real time we check with data base here
            return true;
        }
    }
  1. Unit test method in test project,
      [TestMethod()]
        public void isEmployeeExist()
        {
     IEmployee iEmp = new HRMS.Fakes.StubIEmployee()
            {
                CheckEmployeeExistInt32 = (empid) =>
            {
                return false;
            }// Interface methods which are stubbed
            };

            bool response = iEmp.CheckEmployeeExist(101);

            Assert.IsFalse(response);        }
In the above the interface having the methods, which are stubbed.
We can have multiple methods with Comma (,) separation.
The base implementation of the method returns “True”, but to check we return “false” in stub method.
Shim Property:
You can shim the property of a class like below,
string name = "TestProperty";
ShimEmp.AllInstances.NameGet = (stri) => { return name; };
      The property must have get setter to make shim.


When to Use What:
Use Shims
Use Stubs
To fake the class members
To fake the interface or abstract members
To refer external referenced assemblies
Within the solution calls
When performance is not required
When performance is required
When you have static, non-virtual , sealed virtual methods
When you don’t have static, non-virtual , sealed virtual 
Not possible, when we don’t have testable methods
When we don’t have testable methods
It can fail while testing the code
It will never fail
No need of strong type
When we want strongly typed
To replace calls to .Net assemblies
Can’t be used for .Net assemblies


Note: To create fakes, the dll must have property “Copy Local: True”.

Code Samples for Redis Cache 


For Redis Cache StringGet ()  

For Cloud Configuration


Saturday, March 23, 2013

Validate email using regular expression in javascript

Validate email using JavaScript is mandatory when we are developing any web application.
Checking the entered email id is valid using JavaScript(Client Side) will give good performance to the application .

 Take one text box and one button as,
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
  <asp:Button ID="btnSubmit" runat="server" Text="Save" OnClientClick="return validateEmail(txtEmail);" />

To use HTML controls use
     <input type="submit" value="Submit" onclick="return validateEmail(txtEmail);" />

 Write the JavaScript to validate the entered email as,
 <script type="text/javascript">
        function validateEmail(id) {          
            var email = id.value;
            var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
            // var emailPattern = /^[a-zA-Z0-9._-]+@gmail.com+$/;
            if (emailPattern.test(email)) {
                alert("Entered email Id is : " + email);
                return true;
            } else {
                alert("Enter valid email Id.");
                return false;
            }
        }
    </script>

The above code is used to check any email , weather it is valid or not.
If you want to validate only specific domain emails we need to write separately.
For example , if we want to allow only gmail email id's then use below,
 var emailPattern = /^[a-zA-Z0-9._-]+@gmail.com+$/;
instead of   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

Observe that here we are using regular expression to validate email id.

Info: Regular expressions are one of the best and easiest way to check any format you want.
If you observe the jquery files which has validations, that can be achieved using regular expressions.
By using regular expressions we can minimize the number of lines code we need to write.

See more articles on  JavaScript 







Restrict user to enter past/previous dates using javascript

When we are working with dates by taking input from the user it is always required to restrict the user to enter the past/previous dates.
We can achieve this by using JavaScript.

Now first take one input box and button, in asp.net we use text box and button as below,

<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
 <asp:Button ID="btnSubmit" runat="server" Text="Save" OnClientClick="return checkdate(txtDate);" />

If you want to use HTML controls use below code,
 <input type="text" name="txtDate" />
  <input type="submit" value="Submit" onclick="return checkdate(txtDate);" />

Next we need to write the JavaScript to check the date, see the script below,

 <script type="text/javascript">
        function checkdate(txt) {
            var selectedDate = new Date(txt.value);
            var today = new Date();
            today.setHours(0, 0, 0, 0);
            if (selectedDate < today) {
                alert('Past Dates are not allowed.');
                txt.value = '';
            }
        } 
    </script>

You can observe the above code we are checking the entered date on button click.
You can also write the same in onblur or onchange of the textbox .

In the above example we are restricting the user to enter the date less than today's date.
It depends on the your requirement up to which date we need to restrict.

See more articles on  JavaScript 

Thursday, January 31, 2013

Stored Procedure vs Function in SQL Server

Stored Procedure:- Stored procedure in sql server can be defined as the set of logically group of sql statement which are grouped to perform a specific task. 

Function:- Functions in programming languages are subroutines used to encapsulate frequently performed logic. Any code that must perform the logic incorporated in a function can call the function rather than having to repeat all of the function logic.

In the same way there are many differences between a stored procedure and function as below ,

Stored Procedure
Function
Can return output parameters
Can’t return parameters
Can be used to read and modify data
Can only read data, cannot modify the database
To run an SP Execute or Exec is used, cannot be used with SELECT statement
Can only be used with SELECT statement, JOINS & APPLY (CROSS & OUTER)
Cannot JOIN a SP in a SELECT statement
Can JOIN a UDF in a SELECT statement
Can use Table Variables as well as Temporary Tables inside an SP
Cannot use a Temporary Table, only Table Variables can be used
Can create and use Dynamic SQL
Cannot use a Dynamic SQL inside a UDF
Can use transactions inside (BEGIN TRANSACTION, COMMIT, ROLLBACK) an SP
Cannot use transactions inside a UDF
Support RAISEERROR and @@ERROR
No support for error
Can use used with XML FOR clause
Cannot be used with XML FOR clause
Can use a UDF inside a SP in SELECT statement
Cannot execute an SP inside a UDF
Cannot be used to create constraints while creating a table
Can be used to create Constraints while creating a table
Can execute all kinds of functions, be it deterministic or non-deterministic
Cannot execute some non-deterministic built-in functions, like GETDATE()
Returns multiple result sets
Can’t returns multiple result sets
Syntax: CREATE PROCEDURE usp_MyProcedure
AS
BEGIN
-- SELECT * FROM <Table>
END
GO
Syntax: CREATE FUNCTION dbo.FunctionName
    (parameter_name data_type [=default] [, n])
RETURNS scalar_data_type
[WITH function_option]
AS BEGIN
-- Function_body
-- RETURN scalar_expression

END

 
Keep learning,,,,,,