Wednesday, September 3, 2014

Serialize list of Objects in XML

public static class SerializeUtil
    {
        public static string XmlSerialize<T>(List<T> sourceCollection)
        {
            XmlSerializer xmlSer = new XmlSerializer(typeof(List<T>));
            StringWriter textWriter = new StringWriter();
            xmlSer.Serialize(textWriter, sourceCollection);
            xmlSer = null;
            return textWriter.ToString();
        }
    }

Convert from String to Datetime

DateTime dt= DateTime.ParseExact(value, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)

Read a comma separated file and populate a dictionary

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FileParsing
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader("D:/ID.txt");

            //Dictionary<string, string> dict = new Dictionary<string, string>();
            Dictionary<string, object> dict = new Dictionary<string, object>();

            Player player = new Player();
            while (reader.Peek() >= 0)
            {
                string line = reader.ReadLine();
                string[] data = line.Split(';');

                if (line != String.Empty)
                {
                    for (int i = 0; i < data.Length - 1; i++)
                    {
                        string key = data[i].Trim().Split('=')[0];
                        string value = data[i].Trim().Split('=')[1];
                        string dictKey=string.Empty;
                        switch (key)
                        {
                            case "FNAME": dictKey="FirstName"; break;
                            case "LNAME": dictKey = "LastName"; break;
                            case "MNAME": dictKey="MiddleName"; break;
                            case "ADD": dictKey="Add"; break;
                            case "CITY": dictKey="City"; break;
                            case "ST": dictKey="State"; break;
                            case "ZIP": dictKey="Zip"; break;
                            case "DOB": dictKey = "DOB"; break;
                            case "DOE": dictKey="DOE"; break;
                            case "DOI": dictKey="DOI"; break;
                            case "DLNO": dictKey="DLNo"; break;
                            case "SEX": dictKey="Sex"; break;
                            default:
                                break;
                        }
                        if(!dict.ContainsKey(dictKey))
                            dict.Add(dictKey, value);
                     
                    }
                   
                    //dict.Add(playerCount, player);
                }
            }
        }
    }

    class Player
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string MiddleName { get; set; }
        public string Add { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public DateTime DOB { get; set; }
        public string DOE { get; set; }
        public string DOI { get; set; }
        public string DLNo { get; set; }
        public string Sex { get; set; }
    }
}

Validate Number in MVC

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


@Html.TextBoxFor(model => model.Vendor.FaxNumber, new { @class = "form-control", @maxlength = "15", onkeydown = "return ValidateNumber(event);" })

Monday, July 28, 2014

MVC numeric text box

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

And to call the function in the text box
@Html.TextBoxFor(model => model.Vendor.Mobile, new { @class = "form-control", @maxlength = "10",onkeydown="return ValidateNumber(event);"})

Thursday, July 24, 2014

3 dropdown list to choose the date of birth.

<%= Html.DropDownList("month", Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i)}), "-- Month --") %>

          <%= Html.DropDownList("day", Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString()}), "-- Day --") %>

                    <%= Html.DropDownList("year", Enumerable.Range(1920, n+1).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString()}), "-- Year --")%>

Monday, July 21, 2014

Trigger Example


Create trigger [dbo].[trgDeleteStagingProducts]
on [dbo].[Vendor_Product]
after insert
as
begin
 DECLARE @VendorProductGUID varchar(50)    
   
    SELECT @VendorProductGUID = I.VendorProductGUID        
      FROM INSERTED I
Delete from Vendor_Product_Stagging where VendorProductGUID = @VendorProductGUID;
end

Saving List of Object in SqlServer by XML

CREATE proc [dbo].[BCKUP_usp_AddUserProducts]
@ProductXml xml

as

insert into dbo.Vendor_Product
(
VendorProductGUID
,ProductGUID
,ProductName
,MRP
,SellingPrice
,Description
,UnitValue
,UnitId
,BarCode
,VendorId
,AddedDate
,ProductImage
,Active
)

SELECT
   Product.value('(VendorProductGUID)[1]', 'varchar(50)') AS 'VendorProductGUID',
   Product.value('(ProductGUID)[1]', 'uniqueidentifier') AS 'ProductGUID',
   Product.value('(ProductName)[1]', 'varchar(50)') AS 'ProductName',
   Product.value('(MRP)[1]', 'money') AS 'MRP',
   Product.value('(SellingPrice)[1]', 'money') AS 'SellingPrice',
   Product.value('(Description)[1]', 'varchar(max)') AS 'Description',
   Product.value('(UnitValue)[1]', 'float') AS 'UnitValue',
   Product.value('(UnitId)[1]', 'tinyint') AS 'UnitId',
   Product.value('(BarCode)[1]', 'varchar(50)') AS 'BarCode',
   Product.value('(VendorId)[1]', 'uniqueidentifier') AS 'VendorId',
   Product.value('(AddedDate)[1]', 'DateTime') AS 'AddedDate',
   Product.value('(ProductImage)[1]', 'int') AS 'ProductImage',
   Product.value('(Active)[1]', 'bit') AS 'Active'
FROM
   @ProductXml.nodes('/ArrayOfVendorProduct/VendorProduct') AS AOC(Product)


/* Following statement is for removing entries from other table , not relevant*/

delete from Vendor_Product_Stagging where VendorProductGUID in
(
SELECT
  Product.value('(VendorProductGUID)[1]', 'varchar(50)') AS 'VendorProductGUID'
  FROM  @ProductXml.nodes('/ArrayOfVendorProduct/VendorProduct') AS AOC(Product)
)




Tuesday, June 24, 2014

Error Logging in a File

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;

namespace DEParser.Logger
{
    public class FileLogger
    {
        #region Public Functions

        public  void Log(string exception)
        {
            string date = DateTime.Today.ToString("yyyy-MM-dd");
            String FilePath = ConfigurationManager.AppSettings["logPath"] + date + @"-ErorLog.txt";
            bool fileExists = File.Exists(FilePath);
            if (fileExists)
            {
                using (StreamWriter w = File.AppendText(FilePath))
                {
                    MakeLog(exception, w);
                }
            }
            else
            {
                using (StreamWriter w = File.CreateText(FilePath))
                {
                    MakeLog(exception, w);
                }
            }
           
            //using (StreamReader r = File.OpenText(ConfigurationSetting.LOG_FILEPATH))
            //{
            //    DumpLog(r);
            //}
        }

        #endregion

        #region Private Functions

        private void MakeLog(string logMessage, TextWriter w)
        {
            w.Write("\r\nLog Entry : ");
            w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                DateTime.Now.ToLongDateString());
            w.WriteLine("  :");
            w.WriteLine("  :{0}", logMessage);
            w.WriteLine("-------------------------------");
        }

        private void DumpLog(StreamReader r)
        {
            string line;
            while ((line = r.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }

        #endregion
    }

}


try
                        {
                           
                        }
                        catch (Exception ex)
                        {
                           
                            new Logger.FileLogger().Log(ex.ToString());
                        }

Wednesday, June 11, 2014

Validation in Angular JS

For validation in Angular Js, first of all use 'required' attribute in the input control like..

Now restrict the save button so that it is clickable only when all the validation succeeds. Use  
ng-disabled="myform.$invalid" where myform is the name of the form. Placing the input controls and save button under form tag is must

Doing this is sufficient to validate the form. If you want to give the user a required message then use a span like this..



So * will be shown when you leave a required field empty


One thing to remember is that for this required message will be shown only when the input control (textbox) should have a name attribute and name in 'ng-show' attribute of the span should also be there.


Wednesday, June 4, 2014

Binding to an Array

What if you want to bind to an array and have html elements repeated for each item in the array? This is easy with ng-repeat. Before that we need to initialize some data in our model. Although we’d do this in a controller, but as an initial demo we’re going to use the rarely used ng-init directive to add an array to our model. ng-init lets you execute angular expressions when the page first loads. Doing this with controller will be discussed after this

Advanced Tangent: Notice that we have a “user” on our model from the Hello World sample above, and yet inside the ng-repeat, the correct “user” object–from the users array–was used even though there was some ambiguous use of the term user. This is because the ng-model directive uses it’s own isolated scope. Don’t worry too much about this, just keep it in the back of your mind.

First Step to AngularJs

Just Create a simple Html page like the following..


<html>

<head>
<script src="~/Scripts/Angularjs/angular.min.js"></script>
</head>
<body>
<form>
<input type="number" required />
<input type="submit" />
Hello {{1 + 1}} the World!
</form>
</body>
</html>

If u see this code in browser then you will see the output like







Now if u add  ng-app anywhere so that the Hello {{1 + 1}} the World! becomes the child of that element, what happens then?

There is your first Angular magic! You can see that the {{1 + 1}} expression got evaluated and replaced with “2″. So, what happened here is that the page was downloaded and then Angular scanned the page for ng-app and processed any expressions that it found (in this case just the {{1 + 1}} expression) and replaced the content with the evaluated expression. If you would like to prove to yourself that the location of ng-app matters, try moving ng-app onto a div that does not include the {{1 + 1}} expression and you will see that the expression does not get evaluated (but any expressions inside the ng-app div do).


 
<body ng-app>
    <form>
         <input type="number" required />
         <input type="submit" />
         Hello {{1 + 1}} the World!
   </form>
</body>

and the output is







So this is how the AngularJs works. It's pretty simple