Thursday, 7 April 2016

Custom Directives- AngularJS

Custom Directives
Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using "directive" function. A custom directive simply replaces the element for which it is activated.

AngularJS provides support to create custom directives for following type of elements.

Element directives − Directive activates when a matching element is encountered.
Attribute − Directive activates when a matching attribute is encountered.
CSS − Directive activates when a matching css style is encountered.
Comment − Directive activates when a matching comment is encountered.

Create New Directives
In addition to all the built-in AngularJS directives, you can create your own directives.
New directives are created by using the .directive function.

To invoke the new directive, make an HTML element with the same tag name as the new directive.
When naming a directive, you must use a camel case name, w3TestDirective, but when invoking it, you must use - separated name, w3-test-directive:

<body ng-app="myApp">
<w3-test-directive></w3-test-directive>

<script>
    var app = angular.module("myApp", []);
    app.directive("w3TestDirective", function() {
        return {
            template : "<h1>Made by a directive!</h1>"
        };
    });
</script>

</body>



You can invoke a directive by using:
Element name
Attribute
Class
Comment

The examples below will all produce the same result:

Element name
<w3-test-directive></w3-test-directive>

Attribute
<div w3-test-directive></div>

Class
<div class="w3-test-directive"></div>

Comment
<!-- directive: w3-test-directive -->

Restrictions
You can restrict your directives to only be invoked by some of the methods.

Example
By adding a restrict property with the value "A", the directive can only be invoked by attributes:
    var app = angular.module("myApp", []);
    app.directive("w3TestDirective", function() {
        return {
            restrict : "A",
            template : "<h1>Made by a directive!</h1>"
        };
    });

The legal restrict values are:
E for Element name
A for Attribute
C for Class
M for Comment

By default the value is EA, meaning that both Element names and attribute names can invoke the directive.



Continue Reading →

Wednesday, 6 April 2016

HTML5 Local and Session Storage

HTML5 Local Storage

Local Storage is a web storage feature that allows you to store key-value pairs in a web browser. It’s part of the Web Storage API and provides a way to persist data across sessions without an expiration date, meaning the data will remain until explicitly deleted.

Key Features of Local Storage:

  1. Capacity: Generally allows around 5-10 MB of data per origin.
  2. Synchronous API: Access to data is synchronous, meaning it can block the main thread, so it's best for smaller amounts of data.
  3. Data Type: Only stores strings. You can use JSON to store objects or arrays.
  4. Persistence: Data persists even after the browser is closed and reopened.
  5. Scope: Data is scoped to the origin (protocol, host, and port), so different domains cannot access each other’s Local Storage.

Common Methods:

  • localStorage.setItem(key, value): Stores a value with the specified key.
  • localStorage.getItem(key): Retrieves the value associated with the specified key.
  • localStorage.removeItem(key): Removes the specified key and its value.
  • localStorage.clear(): Removes all key-value pairs from Local Storage.

Example Usage:

// Storing data
localStorage.setItem('username', 'JohnDoe');

// Retrieving data
const username = localStorage.getItem('username');
console.log(username); // Outputs: JohnDoe

// Removing data
localStorage.removeItem('username');

// Clearing all data
localStorage.clear();

Use Cases:

  • Storing user preferences.
  • Caching data for offline access.
  • Managing user sessions.

Keep in mind that sensitive information should not be stored in Local Storage due to security concerns, as it's accessible via JavaScript.

                                                            HTML5 Session Storage

Session storage is a type of web storage that allows you to store data for the duration of a page session. This means that the data persists as long as the browser tab is open. Once the tab is closed, the data is cleared.

Here are some key points about session storage:

  1. Scope: Data is limited to the window or tab where it was created. Different tabs or windows will not share the same session storage.

  2. Storage Limit: Typically, session storage can hold around 5-10MB of data, though this can vary by browser.

  3. Data Types: You can only store data as strings. To store objects, you'll need to convert them to strings using JSON.stringify() and parse them back using JSON.parse().

  4. API: You can access session storage using the window.sessionStorage object. Common methods include:

    • setItem(key, value): Store a value by key.
    • getItem(key): Retrieve a value by key.
    • removeItem(key): Remove a specific item by key.
    • clear(): Clear all session storage data.
  5. Use Cases: It's commonly used for temporary data, such as user preferences, form inputs during a session, or any data that should not persist beyond the tab being open.

Continue Reading →

Tuesday, 29 March 2016

Read Xls File Data To an Object

In this article you will learn to read Excel File Data to an Object.
I have a xls file named Employee.xls that contains three columns "Name","Address","Mobile".


Download File: Employee.xls

I have a Employee Object.

    public class Employee
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string Mobile { get; set; }
        public List<Employee> empList { get; set; }

    }

I need the Data from Excel file to my Employee Object.

First Add ExcelDataReader from Nuget in your Project Solution.

Install-Package ExcelDataReader

It'll add some dlls in your Project.

To Read data from xls, the Code is below:

public static void importDataFromXls()
        {
            Employee data = new Employee();
            data.empList = new List<Employee>();

            //Reading from a OpenXml Excel file (2007 format; *.xlsx)
            FileStream stream = new FileStream("C:\\Users\\surajm\\Documents\\Employee.xlsx", FileMode.Open);
            IExcelDataReader excelReader2007 = ExcelReaderFactory.CreateOpenXmlReader(stream);

            //DataSet - The result of each spreadsheet will be created in the result.Tables
            DataSet result = excelReader2007.AsDataSet();

            //Data Reader methods
            foreach (DataTable table in result.Tables)
            {
                for (int i = 1; i < table.Rows.Count; i++)
                {
                    //for (int j = 0; j < table.Columns.Count; j++)
                  
                        Employee emp = new Employee();
                        emp.Name = table.Rows[i].ItemArray[0].ToString();
                        emp.Address = table.Rows[i].ItemArray[1].ToString();
                        emp.Mobile = table.Rows[i].ItemArray[2].ToString();
                        data.empList.Add(emp);
                 
                }
            }

            //Free resources (IExcelDataReader is IDisposable)
            //excelReader2003.Close();
            excelReader2007.Close();
        }

Download the Project File ImportXlsDataToObject.cs
Continue Reading →

Thursday, 17 March 2016

Get the Elements and Attribute Value from XML

This article will learn you to read required element and attribute Value from Xml file to a List Object.

See XML File, that I am using for this Example: file.xml

XML file contains list of Airline names with their stops, fares and other information. I've to Read all the Airline Name with Their Fares,Stops and other respective information in a List Object.

See the Code Example:

   class TopDeals
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Stops { get; set; }
        public string Currency { get; set; }
        public List<TopDeals> lstDeals { get; set; }
    }

The above class contains the properties of TopDeals Type that contanis all the required properties.
The Code for reading the Elements Value is below.

class Program
    {
        static void Main(string[] args)
        {
            XElement root = XElement.Load(@"file.xml");
            var rootElem = root.Elements("Airlines").ToList();
            TopDeals obj = new TopDeals();
            obj.lstDeals = new List<TopDeals>();
            foreach (var item in rootElem)
            {
                TopDeals obj2 = new TopDeals();
                obj2.Name = item.Attribute("name").Value;
                obj2.Price = Convert.ToDecimal(item.Element("stops").Attribute("Fare").Value);
                obj2.Stops = item.Element("stops").Attribute("stop").Value.ToString();
                obj2.Currency = item.Element("stops").Attribute("Currency").Value.ToString();
                obj.lstDeals.Add(obj2);
            }
            var lstData = obj.lstDeals.OrderBy(a => a.Price);
        }
    }

In lstData object you will get the all Airlines Name with their other information.
Find the Complete Program : XmlElementReadProgram



Thanks-
Suraj Kumar


Continue Reading →

Wednesday, 30 December 2015

Validate Input & AllowHtml attribute .Net MVC

When you develop an app, sometimes your requirements could be you want to send HTML values (for example <h2>Hello World</h2>) from the view to the controller. Sometimes we use HTML Editors, to save some info into the database. By default ASP.NET MVC doesn't allow a user to submit the HTML content.

So let's see how to submit your form with HTML content.
  1. Open Visual Studio then select "New Project" then select "ASP.NET MVC 4 Application".

  1. Provide a project name then click "OK".
  2. Select "Internet Application" then click "OK"


  1. Create a New Model.

    ValidateModel.cs
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    namespace ValidateInputDemo.Models
    {
        public class ValidateModel
        {
            public string description { get; set; }
        }
    }
  2. Add a new method to your Controller.

    HomeController.cs
    public ActionResult ValidateInput()
    {
        
    return View();
    }
    [
    HttpPost]public ActionResult  ValidateInput(string description)
    {
        
    ValidateModel validateInputModel = new ValidateModel();
        validateInputModel.description = description;
        
    return View(validateInputModel);
    }
    ValidateInput.cshtml
    @model ValidateInputDemo.Models.ValidateModel
    @{
           ViewBag.Title = "ValidateInput";
    }
    @using (@Html.BeginForm("ValidateInput","Home", FormMethod.Post, new { @id = "form1", @enctype ="multipart/form-data" }))
    {
        <label id="lblDescription">Description</label>
         @Html.TextAreaFor(m=>m.description, new {@id="txtDescription",@name="description" })
        <input type="submit" id="bttn_Submit" />
    }
You can see in the code above, there is a text area and a submit button, have a look in the browser. Press F5. 


You can see in the preceding screen, if you type something into the description and press Submit then  nothing happens.

Now check the following example. Add HTML content into text area.


Now press the "Submit" button.


You will get the error above. This error comes because this is the security from ASP.NET MVC. For applications, a user cannot send HTML values to the controller, but sometimes we want to send values to the controller.

For resolving this issue we have the ValidateInput(false) attribute.

Just put this into your controller and have a look.
[HttpPost]
[ValidateInput(false)]
public ActionResult  ValidateInput(string description)
{
   ValidateModel validateInputModel = new ValidateModel();
   validateInputModel.description = description;
   return View(validateInputModel);
}
Now press F5. After filling in the HTML attribute press the submit button, you will never get an error. So when you want to work with HTML attributes in your app text area or textboxes, don't forget to use validateinpute(false) in your ActionMethod.

Limitation of ValidateInput attribute
This attribute also has the issue since this allow the Html input for all the properties and that is unsafe. Since you have enable Html input for only one-two properties then how to do this. To allow Html input for a single property, you should use AllowHtml attribute.

AllowHtml Attribute
This is the best way to allow the submission of HTML for a particular property. This attribute will be added to the property of a model to bypass input validation for that property only. This explicit declaration is more secure than the ValidateInput attribute.

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

public class BlogModel
{
 [Required]
 [Display(Name = "Title")]
 public string Title { get; set; }

 [AllowHtml]
 [Required]
 [Display(Name = "Description")]
 public string Description{ get; set; }
}


Make sure, you have removed the ValidateInput attribute from Conroller or Action method. Now, the user can submit Html only for the Description property successfully.
Continue Reading →

Friday, 16 October 2015

How to Get Selected CheckBox Values

This Article will Teach you How you can get Selected Checkbox Values with Comma Seperated in a Variable using Jquery.

Create a new Html File Named test.html and add the below code in that file.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>

    <input type="checkbox" class="form" value="E001" />
    <input type="checkbox" class="form" value="E002" />
    <input type="checkbox" class="form" value="E003" />
    <input type="checkbox" class="form" value="E004" />

    <input name="searchDonor" type="button" class="button" value="Get Value" onclick="getvalue()" />
    <script>
        function getvalue() {

            var boxesValue = [];
            $('input:checkbox.form:checked').each(function () {
                var value = (this.checked ? $(this).val() : "");
                boxesValue.push(value);
            });

            var str = boxesValue.join(",");
            alert(str);
        }
    </script>

</body>
</html>

Now Run This html file.
Click the checkboxes and Click on Get Value Button.
You will get Selected Check box Value.

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives