Saturday, November 18, 2017

How to pass web configuraition value to angular controller/service via angular constant

In my appliction, there are few constant value need to pass the angular controllers . So I need to create angular constant and inject it everyware. So I have done the following steps to achived this,

Create the dynaic java script file .

01. In my case some of constant values has to fetch from the web config file. So I have create mvc conroller and return dynamically generated java scripts file when page is loading 

Asp.net Mvc Controller 

 public class ScriptsController : Controller
    {
        public ActionResult Constants()
        {
            var script = new StringBuilder();
            script.Append("(function () {");
            script.Append("angular.module('app')");
            script.Append(".constant('Settings', {");
            script.AppendFormat("AppUrl: '{0}',", ConfigurationManager.AppSettings["AppUrl"]);
            script.Append("});");
            script.Append("})();");
            return JavaScript(script.ToString());
        }
    }

In layout page call the url and load the dynamic java scripts file 

 "script type="text/javascript" src="@Url.Action("Constants", "Scripts")"

setting file is available to used everyware to used 

---settings file is injected and used web confile value inside java scripts controller. 

var app = angular.module('app', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $locationProvider, Settings) {

    var baseUrl = Settings.AppUrl;

    $urlRouterProvider.otherwise('/home');
    $stateProvider
        .state('home', {
            url: '/About',
            templateUrl: baseUrl+ '/Home/About'
        })
        .state('Contact', {
            url: '/Contact',
            templateUrl: baseUrl + '/Home/Contact' 
        })
   // $locationProvider.hashPrefix('!').html5Mode(true);
});








Friday, July 10, 2015

Excel Sheet Column Title






 public static string converToLetter(int n)
        {
            char[] letter = new char[10];
            int nextValue = n;
            int varBase = 26;
            int i = 0;
            while (nextValue > 0)
            {
                nextValue--;
                int reminder = nextValue % varBase;
                nextValue = nextValue / varBase;
                char id = (char)(65 + reminder);
                letter[i] = id;
                i++;
            }
            letter.Reverse();
            return   new string(letter.ToArray());
        }

Tuesday, June 25, 2013

MVC helper for jquery datePicker

MVC helper creation is very easy and its only requires static method which should return string. Below code is shown how to create textbox with attached jquery date time popup controller.  

public static MvcHtmlString DatePickerFor (this HtmlHelper htmlHelper, Expression<Func> expression, object htmlAttributes = null)
        {
            var body = (MemberExpression)expression.Body;
            var propertyName = body.Member.Name; // get controller id 
            string textbox = htmlHelper.EditorFor(expression).ToString();
           var script = "'<'script type=\"text/javascript\'>'"
$('#" + propertyName + "').datepicker();

            script += "'<'/script'>'"

            return MvcHtmlString.Create(textbox + "\n" + script);
        }

In the view you can access this helper as below

@Html.DatePickerFor (model => model.dateField)

 Above code is shown the basic steps of required html helper. Assume that want to add more html attributes, date format and other specific filter criteria inside the method and can be pass parameter from view page. This helper is useful you need to add business logic  and validation required before binding data to view. 

public static MvcHtmlString DatePickerFor(this HtmlHelper htmlHelper, Expression<Func> expression, object htmlAttributes = null)
        {
            var body = (MemberExpression)expression.Body;
            var propertyName = body.Member.Name; // get controller id 
            var attr = new RouteValueDictionary(htmlAttributes); // html attributes 

            string propertyDateFormat = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).DisplayFormatString;

// logic and validation 
            string dateFormat = "";

            if (propertyDateFormat == "{0:dd/MM/yyyy}")
                dateFormat = "dd/mm/yy";
            else               
                dateFormat = "dd/mm/yy";

            string textbox = htmlHelper.EditorFor(expression).ToString(); // render html text box 

                        var script = "'<'script type=\"text/javascript\"'>'$('#" + propertyName + "').datepicker({ dateFormat: '" + dateFormat + "' }); $('#" + propertyName + "').removeClass('text-box');";
            if (attr["style"] != null)
                script += "$('#" + propertyName + "').attr('style','" + attr["style"] + "');";
            if (attr["class"] != null)
                script += "$('#" + propertyName + "').addClass('" + attr["class"] + "');";
            script += "'<'/script'>'";


            return MvcHtmlString.Create(textbox + "\n" + script);        }

without above helper we can used jquery date picker but if need to add some server side validation and server side controlled then this way is more easy.  


Thursday, August 30, 2012

Dialog Popup with hyper link

Java script function for Dialog popup 

After click the link popup the data which is return form that link.

link
@Html.ActionLink("Name", "Action","Controller",new {//data need to pass as query string}, new {
// html attributes
class = "LinkClassName", dialog-title = "this is tiltle name ",  dialog-id  = "dailog id" ....
});

 $(".LinkClassName").live("click", function (e) {
            e.preventDefault();     
.append($loading) // this is for load image for fully loaded 
.addClass("dialog") // css class for loading 
.attr("id", $(this) // div id 
.attr("dialog-id")) // poup id
.attr("dialog-path", $(this).attr("data-dialog-path")) // after close page refresh 
.appendTo("body") // attached div content to the body 
.dialog({
   title: $(this).attr("data-dialog-title"), // popup dialog title 
   close: function () {  $(this).remove()   }, // close finction 
   modal: true, /
   resizable: false,
   width: '400px'
}).load(this.href); // href is the url
        });
more details available here.(http://jqueryui.com/)


Form submit using Ajax 


var form = $("#yourFormId");
$.ajax({
                url: '@Url.Action("ActionName","ControllerName")',
                data: form.serialize(),
                type: 'POST',
                success: function (data) {
                    $("#targetUpdateDiv").html(data);
                }
            });

Tuesday, June 26, 2012


ASP.net MVC3 Date Formats validation Issued (dd/mm/yyyy vs mm/dd/yyyy) 


Client side  passing date format as "dd/mm/yyyy" format. but model is return format is incorrect its cheeking mm/dd/yyyy. i have found that issue in mvc web application. 
solution

Reason is that web server culture info is used as "en-us" its validate format "mm/dd/yyyy".  then i found that we can change the culture dynamically in the following way .

Option 1: Page level

The Culture used by the individual Page can be set via the Culture property.
<%@ Page Culture="en-SG" Language="C#" %>

Option 2: Application wide (web.Config)

The Culture can be set Application wide by adding the  node to the web.Config file. The  node must be placed inside .
<system.web>
  <globalization culture="en-SG"/>

Option 3: Thread level

The Culture of the current Thread can be changed programatically be setting the System.Threading.Thread.CurrentThread.CurrentCulture property.
The following example demonstrates how to get the user-agent(browsers) preferred UserLanguage property on each Request and set the Threads CurrentCulture during the Application_BeginRequest Event.
protected void Application_BeginRequest(Object sender, EventArgs e)
{
    CultureInfo requestCulture;
    try
    {        
        requestCulture = CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]);
    }
    catch
    {
        // Return server Culture if none available in HttpHeaders.
        requestCulture = CultureInfo.CurrentCulture;
    }
    System.Threading.Thread.CurrentThread.CurrentCulture = requestCulture;
}

Thursday, May 19, 2011

Mapping SQL Data Base Table with LINQ (Linq to Sql)

Here are Show step to mapping linq query and retrieve data from sql data base

Step 01 : mapping linq collection class with sql dataTabel
i.) import following namespace
using System.Data.Linq;
using System.Data.Linq.Mapping;
ex :- [Table(Name = "D01_Invoice")] //data table Name
public class Invoice
{
private int _invoiceID;
[Column(IsPrimaryKey = true, Storage = "_invoiceID", Name = "D01_id")] //data mapping column Name
public int InvoiceID
{
get
{ return this._invoiceID; }
set { this._invoiceID = value; }
}

private string _invoiceNumber;
[Column(Storage = "_invoiceNumber", Name = "D01_InvoiceNumber", DbType = "numeric(18, 0)")]
public string InvoiceNumber
{
get
{
return this._invoiceNumber;
}
set
{
this._invoiceNumber = value;
}
}
}

step 2:
Create "DataContex" object . so that u have to give connection string or file store path
//string ConnSQL = ConfigurationManager.ConnectionStrings["ConnSQL"].ToString();
// SqlConnection sqlConnection = new SqlConnection(ConnSQL);
//sqlConnection.Open();
DataContext dataContex = new DataContext(sqlConnection);

step 3:
call linq query
IEnumerable invoice = dataContex.GetTable(); //it can be list
those are the basic step to mapping data table and getting data table using linq

step 4 :
if u need select data from linq data collection use following way
select query
IEnumerable empQuery =
from emp in Invoice
select emp;

filter Query
IEnumerable empQuery =
from emp in employees
where emp.Department == "IT Department" &&
emp.City == "Redmond"
select emp;

Order Query
IEnumerable empQuery =
from emp in employees
orderby emp.Department
select emp;

Sample code for Group

Sample of C# Code

Sample Code for Join

IEnumerable invoice = dataContex.GetTable();
IEnumerable invoiceDetails = dataContex.GetTable();

var invo = from inv in invoice
join details in invoiceDetails on inv.InvoiceNumber equals details.InvoiceNumberDetails into invDetails
select new { id= inv.InvoiceID,
invoiceNum = inv.InvoiceNumber,
invoiceDetails = invDetails};
foreach (var inv in invo)
{
Console.WriteLine(inv.invoiceNum);
foreach (var indetails in inv.invoiceDetails)
{
Console.WriteLine(indetails.InvoiceNumberDetails + indetails.ItemCode);
}
}

Monday, January 11, 2010

How to configure IIS to make it aware of ASP.NET

I was Install IIS but I couldn't Deploy ASp.net web Site in my IIS sever. It will show error massage it couldn't know ASP.net tag. But i already installed .net frame work and SDK in my machine. Error is is not enable ASP.net to the web server, follow the following step to enable that

Search aspnet_regiis.exe this file and double click it will automatically configure IIS to make aware of ASP.Net. this exe file include inside the C:\WINDOWS\Microsoft.NET\Framework folder,