Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, December 29, 2015

SignalR Implementation in XAML Page

XAML Page:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.AspNet.SignalR.Client;

namespace SignalRDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        HubConnection _connection;
        IHubProxy _hub;

        // Keep track of when fake "drag and drop" mode is enabled.
        private bool isDragging = false;

        // Store the location where the user clicked the control.
        private double clickOffsetX, clickOffsetY;

        private void window_Loaded(object sender, RoutedEventArgs e)
        {
            Start();
        }

        void label_MouseDown(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            var position = e.GetPosition(window);

            var label = sender as Label;
            var l = (double)label.GetValue(Canvas.LeftProperty);
            var t = (double)label.GetValue(Canvas.TopProperty);

            clickOffsetX = l - position.X;
            clickOffsetY = t - position.Y;
        }

        void label_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging == true)
            {
                // The control coordinates are converted into form coordinates
                // by adding the label position offset.
                // The offset where the user clicked in the control is also
                // accounted for. Otherwise, it looks like the top-left corner
                // of the label is attached to the mouse.

                var label = sender as Label;
                var position = e.GetPosition(window);

                var x = position.X + clickOffsetX;
                var y = position.Y + clickOffsetY;

                SetShapePosition(label, x, y);

                _hub.Invoke("MoveShape", int.Parse(label.Name.Replace("shape", "")), x, y);
            }
        }

        void label_MouseUp(object sender, MouseButtonEventArgs e)
        {
            isDragging = false;
        }

        private void Start()
        {
            _connection = new HubConnection("http://localhost/SignalRChat/myhubs/hubs");

            _hub = _connection.CreateHubProxy("SignalRHub");

            _connection.Start().Wait();

            _hub.On<int>("usersConnected", (count) =>
            {
                this.Dispatcher.Invoke(() =>
                    UpdateUserCount(count)
                );
            });

            _hub.On<List<Common.Shape>>("shapeList", (list) =>
            {
                this.Dispatcher.Invoke(() =>
                {
                    canvas.Children.Clear();

                    list.ForEach(q =>
                    {
                        var label = new Label();

                        label.Name = string.Format("shape{0}", q.Id);
                        label.Content = q.Name;
                        label.Height = 100;
                        label.Width = 100;
                        label.Padding = new Thickness(10, 10, 0, 0);
                        label.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(q.Color));
                        SetShapePosition(label, q.X, q.Y);
                        label.FontSize = 20;

                        label.MouseDown += label_MouseDown;
                        label.MouseMove += label_MouseMove;
                        label.MouseUp += label_MouseUp;

                        canvas.Children.Add(label);
                    });
                });
            });

            _hub.On<Common.Shape>("shapeMoved", (shape) =>
            {
                this.Dispatcher.Invoke(() =>
                    UpdatePosition(shape)
                );
            });

            _hub.Invoke("GetShapeList");
        }

        private void SetShapePosition(Label label, double x, double y)
        {
            if (label != null)
            {
                label.SetValue(Canvas.LeftProperty, x);
                label.SetValue(Canvas.TopProperty, y);
            }
        }

        private void UpdateUserCount(int count)
        {
            lblCount.Content = count;
        }

        private void UpdatePosition(Common.Shape shape)
        {
            var label = UIHelper.FindChild<Label>(Application.Current.MainWindow, string.Format("shape{0}", shape.Id));
            SetShapePosition(label, shape.X, shape.Y);
        }
    }

    public class UIHelper
    {
        /// <summary>
        /// Finds a Child of a given item in the visual tree. 
        /// </summary>
        /// <param name="parent">A direct parent of the queried item.</param>
        /// <typeparam name="T">The type of the queried item.</typeparam>
        /// <param name="childName">x:Name or Name of child. </param>
        /// <returns>The first parent item that matches the submitted type parameter. 
        /// If not matching item can be found, 
        /// a null parent is being returned.</returns>
        public static T FindChild<T>(DependencyObject parent, string childName)
           where T : DependencyObject
        {
            // Confirm parent and childName are valid. 
            if (parent == null) return null;

            T foundChild = null;

            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                // If the child is not of the request child type child
                T childType = child as T;
                if (childType == null)
                {
                    // recursively drill down the tree
                    foundChild = FindChild<T>(child, childName);

                    // If the child is found, break so we do not overwrite the found child. 
                    if (foundChild != null) break;
                }
                else if (!string.IsNullOrEmpty(childName))
                {
                    var frameworkElement = child as FrameworkElement;
                    // If the child's name is set for search
                    if (frameworkElement != null && frameworkElement.Name == childName)
                    {
                        // if the child's name is of the request name
                        foundChild = (T)child;
                        break;
                    }
                }
                else
                {
                    // child element found.
                    foundChild = (T)child;
                    break;
                }
            }

            return foundChild;
        }
    }

}

SignalR Hub Page :

using Microsoft.AspNet.SignalR;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common;

namespace SignalRChat
{
    public class SignalRHub : Hub
    {
        public SignalRHub()
        {

        }

        #region Moveable Shape
        public async Task GetShapeList() // this method will be called from the client, when the user drag/move the shape
        {
            await Clients.Caller.shapeList(ShapeHandler.Instance.ShapeList); // this method will send the coord x, y to the other users but the user draging the shape
        }

        public async Task MoveShape(int id, double x, double y) // this method will be called from the client, when the user drag/move the shape
        {
            var shape = ShapeHandler.Instance.GetShape(id, x, y);

            if (shape.X != x || shape.Y != y) await Clients.Caller.shapeMoved(shape);

            await Clients.Others.shapeMoved(shape); // this method will send the coord x, y to the other users but the user draging the shape
        }

        public override Task OnConnected() //override OnConnect, OnReconnected and OnDisconnected to know if a user is connected or disconnected
        {
            ShapeHandler.Instance.ConnectedIds.Add(Context.ConnectionId); //add a connection id to the list
            Clients.All.usersConnected(ShapeHandler.Instance.ConnectedIds.Count()); //this will send to ALL the clients the number of users connected
            return base.OnConnected();
        }

        public override Task OnReconnected()
        {
            ShapeHandler.Instance.ConnectedIds.Add(Context.ConnectionId);
            Clients.All.usersConnected(ShapeHandler.Instance.ConnectedIds.Count());
            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            ShapeHandler.Instance.ConnectedIds.Remove(Context.ConnectionId);
            Clients.All.usersConnected(ShapeHandler.Instance.ConnectedIds.Count());
            return base.OnDisconnected(stopCalled);
        }
        #endregion
    }
}

SignalR Implementation in HTML Page

Html Page :

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <label id="serverDate"></label>
    <button id="initTimer">Start Timer</button>

    <!--Script references. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.0.0.js"></script>

    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalR/hubs"></script>
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var hub = $.connection.demoHub;

            hub.client.serverDateTimeInfo = function (time) {
                $("#serverDate").text(time);
            };

            $.connection.hub.start().done(function () {
                alert('Server connected');

                hub.server.getServerDatetime();

                $("#initTimer").click(function () {
                    hub.server.initTimer();
                });
            });
        });
    </script>
</body>
</html>

SignalR Hub Page :

using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using System.Web;

namespace SignalRChat
{
    public class DemoHub :Hub
    {
        public void GetServerDatetime()
        {
            SendNotification();
        }

        private void SendNotification()
        {
            try
            {
                Clients.Caller.serverDateTimeInfo(DateTime.Now.ToString());
            }
            catch { }
        }

        public void InitTimer()
        {
            Timer timer = new Timer(1000);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.AutoReset = true;
            timer.Enabled = true;
        }

        public void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            SendNotification();
        }
        
    }
}

Thursday, July 8, 2010

Excel Permission Configration for ASP.NET Application

Refer this link

http://blog.crowe.co.nz/archive/2006/03/02/589.aspx

Create XLS File in ASP.NET application

Class CreateXLS :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
using System.IO;
using System.Drawing;
using System.Reflection;

public class CreateXLS
{
#region Excel Variables
private Microsoft.Office.Interop.Excel.Application oXL;
private Microsoft.Office.Interop.Excel._Workbook oWB;
private Microsoft.Office.Interop.Excel._Worksheet oSheet;

private long iExcelRow = 2;
private long iExcelCol = 2;
private long iStartRow = 0;

private string sFromCellNo = "";
private string sToCellNo = "";

private enum enumXLSFields
{
EmployeeName,
Address,
AccountNo,
Earnings,
Deduction,
NetSalary
}

private float LogoLeft = 50;
private float LogoTop = 15;
private float LogoWidth = 52;
private float LogoHeight = 52;
#endregion

#region Properties
public string XLSPath { get; set; }
public string XLSFileName { get; set; }
public string XLSSheetName { get; set; }

public List<EmployeeInfo> EmployeeList { get; set; }

/// <summary>
/// Logo Properties
/// </summary>
public string LogoFile { get; set; }
#endregion

/// <summary>
/// Cunstructor
/// </summary>
public CreateXLS()
{
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = false;
oXL.UserControl = false;

this.EmployeeList = new List<EmployeeInfo>();
}

#region Public Methods
public void GenerateXLSFile()
{
try
{
#region GenrateXLSFile
GC.Collect();
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
//oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
oSheet.Name = this.XLSSheetName;

/*----------------Main Coding----------------*/
InsertLogoFileToSheet();

SetXLSTitle((int)enumXLSFields.EmployeeName, (int)enumXLSFields.NetSalary, "Employee Report", 10, true);

DisplayEmployeeInfo();

SheetAutoFit();
/*-------------------------------------------*/

#region XLS File Save into Server Path

#region Check XLS File if Exists
string sFileName = this.XLSPath + this.XLSFileName + ".XLS";
if (File.Exists(sFileName))
{
File.Delete(sFileName);
}
#endregion

//Create BillingXLS Directory
if (!System.IO.Directory.Exists(XLSPath))
{
System.IO.Directory.CreateDirectory(XLSPath);
}

string strXLSFile = string.Format("{0}\\{1}.xls", this.XLSPath, this.XLSFileName);
if (File.Exists(strXLSFile))
{
File.Delete(strXLSFile);
}
oWB.SaveAs(string.Format("{0}\\{1}", this.XLSPath, this.XLSFileName), XlFileFormat.xlWorkbookNormal, null, null, false, false, XlSaveAsAccessMode.xlExclusive, false, false, null, null, null);
oWB.Close(null, null, null);
#endregion

#endregion
}
catch
{
System.GC.Collect();
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);

oSheet = null;
oWB = null;
}
}

private void DisplayEmployeeInfo()
{
#region Header
iExcelRow++;

oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.EmployeeName] = "Employee Name";
oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.Address] = "Address";
oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.AccountNo] = "Account No";
oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.Earnings] = "Earnings";
oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.Deduction] = "Deduction";
oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.NetSalary] = "Net Salary";

SetRangeBackColor(iExcelRow, iExcelRow, (int)enumXLSFields.EmployeeName, (int)enumXLSFields.NetSalary);
iExcelRow++;
#endregion

#region Detail
iStartRow = iExcelRow;
foreach (EmployeeInfo Employee in EmployeeList)
{
oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.EmployeeName] = Employee.EmployeeName;
oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.Address] = Employee.Address;
oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.AccountNo] = Employee.AccountNo;
oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.Earnings] = Employee.Earnings;
oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.Deduction] = Employee.Deduction;
oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.NetSalary] = Employee.NetSalary;
iExcelRow++;
}
#endregion

#region Total

#region Print Total
oSheet.Cells[iExcelRow, iExcelCol + (int)enumXLSFields.EmployeeName] = "Total";

SetRangeTotal(iExcelRow, (int)enumXLSFields.Earnings, iStartRow, iExcelRow - 1, (int)enumXLSFields.Earnings);
SetRangeTotal(iExcelRow, (int)enumXLSFields.Deduction, iStartRow, iExcelRow - 1, (int)enumXLSFields.Deduction);
SetRangeTotal(iExcelRow, (int)enumXLSFields.NetSalary, iStartRow, iExcelRow - 1, (int)enumXLSFields.NetSalary);
#endregion

#region Range Format
SetRangeNumberFormat(iStartRow, iExcelRow, (int)enumXLSFields.Earnings, (int)enumXLSFields.NetSalary);
SetRangeBackColor(iExcelRow, iExcelRow, (int)enumXLSFields.EmployeeName, (int)enumXLSFields.NetSalary);
SetRangeBorder(iStartRow, iExcelRow, (int)enumXLSFields.EmployeeName, (int)enumXLSFields.NetSalary);
#endregion

#endregion
}
#endregion

#region Private Methods
private void InsertLogoFileToSheet()
{
if (File.Exists(this.LogoFile))
{
oSheet.Shapes.AddPicture(this.LogoFile, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, LogoLeft, LogoTop, LogoWidth, LogoHeight);
}
SetXLSTitle((int)enumXLSFields.Address, (int)enumXLSFields.NetSalary, "ABC Inc.", 12, true);

iExcelRow = 6;
}

private void SheetAutoFit()
{
Range oRng = oSheet.get_Range("A1", "Z1");
oRng.EntireColumn.AutoFit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oRng);
}

private void SetXLSTitle(int StartColumn, int EndColumn, string ColumnHeading, int FontSize, bool MergeColumn)
{
sFromCellNo = ((char)(iExcelCol + StartColumn + 64)) + iExcelRow.ToString();
sToCellNo = ((char)(iExcelCol + EndColumn + 64)) + iExcelRow.ToString();

oSheet.Cells[iExcelRow, iExcelCol + StartColumn] = ColumnHeading;

Range oRng = oSheet.get_Range(sFromCellNo, sToCellNo);
oRng.Font.Name = "Arial";
oRng.Font.Size = FontSize;
oRng.Font.Bold = true;
if (MergeColumn)
{
oRng.Merge(1);
oRng.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
oRng.Font.Color = Color.White.ToArgb();
oRng.Interior.Color = Color.FromArgb(128, 128, 128).ToArgb();
oRng.Interior.Pattern = Microsoft.Office.Interop.Excel.XlPattern.xlPatternSolid;
oRng.Borders.Value = 1;
oRng.Borders.Color = Color.Black.ToArgb();
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(oRng);
}

private void SetRangeTotal(long DisplayRow, long DisplayColumn, long StartRow, long EndRow, long RangeColumn)
{
sFromCellNo = ((char)(iExcelCol + RangeColumn + 64)) + StartRow.ToString();
sToCellNo = ((char)(iExcelCol + RangeColumn + 64)) + EndRow.ToString();

oSheet.Cells[DisplayRow, iExcelCol + DisplayColumn] = "=SUM(" + sFromCellNo + ":" + sToCellNo + ")";
}

private void SetRangeNumberFormat(long StartRow, long EndRow, long StartColumn, long EndColumn)
{
sFromCellNo = ((char)(iExcelCol + StartColumn + 64)) + StartRow.ToString();
sToCellNo = ((char)(iExcelCol + EndColumn + 64)) + EndRow.ToString();

Range oRng = oSheet.get_Range(sFromCellNo, sToCellNo);
oRng.NumberFormat = "###,###,##0.00";
System.Runtime.InteropServices.Marshal.ReleaseComObject(oRng);
}

private void SetRangeBorder(long StartRow, long EndRow, long StartColumn, long EndColumn)
{
sFromCellNo = ((char)(iExcelCol + StartColumn + 64)) + StartRow.ToString();
sToCellNo = ((char)(iExcelCol + EndColumn + 64)) + EndRow.ToString();

Range oRng = oSheet.get_Range(sFromCellNo, sToCellNo);
oRng.Borders.Value = 1;
oRng.Borders.Color = Color.Black.ToArgb();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oRng);
}

private void SetRangeBackColor(long StartRow, long EndRow, int StartColumn, int EndColumn)
{
sFromCellNo = ((char)(iExcelCol + StartColumn + 64)) + StartRow.ToString();
sToCellNo = ((char)(iExcelCol + EndColumn + 64)) + EndRow.ToString();

Range oRng = oSheet.get_Range(sFromCellNo, sToCellNo);
oRng.Font.Name = "Arial";
oRng.Font.Bold = true;
oRng.Font.Color = Color.Black.ToArgb();
oRng.Interior.Color = System.Drawing.Color.FromArgb(192, 192, 192).ToArgb();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oRng);
}

private void SetRangeBold(long StartRow, long EndRow, long StartColumn, long EndColumn)
{
sFromCellNo = ((char)(iExcelCol + StartColumn + 64)) + StartRow.ToString();
sToCellNo = ((char)(iExcelCol + EndColumn + 64)) + EndRow.ToString();

Range oRng = oSheet.get_Range(sFromCellNo, sToCellNo);
oRng.Font.Name = "Arial";
oRng.Font.Bold = true;
oRng.Font.Color = Color.Black.ToArgb();
oRng.Interior.Color = System.Drawing.Color.FromArgb(192, 192, 192).ToArgb();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oRng);
}
#endregion
}

public class EmployeeInfo
{
public string EmployeeName { get; set; }
public string Address { get; set; }
public string AccountNo { get; set; }
public float Earnings { get; set; }
public float Deduction { get; set; }
public float NetSalary { get; set; }
}

ProcessXLS.ASPX :

public partial class ProcessXLS : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GenrateXLS();
}

private void GenrateXLS()
{
CreateXLS objXLS = new CreateXLS();

objXLS.EmployeeList.Add(new EmployeeInfo() { EmployeeName = "Eugene Malarky", Address = "Grove Street, Smithtown", AccountNo = "A001", Earnings = 1500, Deduction = 450, NetSalary = 1050 });
objXLS.EmployeeList.Add(new EmployeeInfo() { EmployeeName = "Sam Adams", Address = "Main Street, Suite 1000, Ashville", AccountNo = "A002", Earnings = 1250, Deduction = 320, NetSalary = 930 });
objXLS.EmployeeList.Add(new EmployeeInfo() { EmployeeName = "Loren Sandler", Address = "Main Street, Hometown", AccountNo = "A003", Earnings = 1800, Deduction = 550, NetSalary = 1250 });

objXLS.XLSPath = Server.MapPath("XLSFiles");
objXLS.XLSFileName = "EmployeeSalary";
objXLS.XLSSheetName = "EmployeeList";

objXLS.LogoFile = Server.MapPath("XLSFiles/JDLogo.jpeg");

objXLS.GenerateXLSFile();
}
}

Sample XLS File

Monday, July 5, 2010

Delegate using in ASPX Page and user control

In ASPX Page :

public partial class Activity_ContactActivity : Page
{
protected void Page_Load(object sender, EventArgs e)
{
MonthActivity1.LoadWeekTabInformation += new UserControls_Activity_MonthActivity.LoadTabInformation(MonthActivity1_LoadWeekTabInformation);
}

void MonthActivity1_LoadWeekTabInformation()
{
this.ActivityDate = MonthActivity1.ActivityDate;
this.CurrentActivityTab = enumContactActivityTab.Week;
LoadActivityInformation();
}
}


In User Control Page :

public partial class UserControls_Activity_MonthActivity : UserControl
{
public delegate void LoadTabInformation();
public event LoadTabInformation LoadWeekTabInformation;

private void DisplayWeekTabInformation()
{
LoadWeekTabInformation();
}
}

Execute Process in Threading Pool


using System.Threading;

public class ImportData()
{
public void Import()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(SendImportDataRequest), new ImportParameter()
{
PageURL = "ImportData.aspx",
CurrentUpload = enumUploadData.CustodianData,
XMLCustodianIds = sbCustodianId.ToString().Substring(1),
ImportDate = txtImportDate.Text.ToDateTimeValue(),
LoginContactId = this.LoginContactId,
LoginUserId = this.LoginUserId
});
}

public static void SendImportDataRequest(object Parameter)
{
ImportParameterDTO objParameter = (ImportParameterDTO)Parameter;
string urlEncodedUserInput = string.Format("StartImport={0}&CurrentUpload={1}&CustodianIds={2}&ImportDate={3}&LoginContactId={4}&LoginUserId={5}"
, (int)enumYesNo.Yes // 0
, objParameter.CurrentUpload // 1
, objParameter.XMLCustodianIds // 2
, objParameter.ImportDate.ToShortDateString() // 3
, objParameter.LoginContactId // 4
, objParameter.LoginUserId // 5
);

System.Net.WebRequest httpRequest = System.Net.WebRequest.Create(objParameter.PageURL);

httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
byte[] bytedata = System.Text.Encoding.UTF8.GetBytes(urlEncodedUserInput);
httpRequest.ContentLength = bytedata.Length;
System.IO.Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();

try
{
System.Net.WebResponse res = httpRequest.GetResponse();
}
catch (Exception ex)
{
}
}
}

public class ImportParameter()
{
public string PageURL { get; set; }
public enumUploadData CurrentUpload { get; set; }
public string XMLCustodianIds { get; set; }
public DateTime ImportDate { get; set; }
public long LoginContactId { get; set; }
public long LoginUserId { get; set; }
}

Friday, June 11, 2010

Using ConvertAll and Aggregate in LINQ


string strImportResult = this.ImportResult.ToList()
.ConvertAll<string>(Import => string.Format("<tr><td>
{0}</td><td>{1}</td><td>{2}</td><td>
{3}</td></tr>"

, Import.CustodianName
, Import.ImportFile
, Import.ImportStatus
, Import.Particular))
.Aggregate((ImportA, ImportB) => ImportA + ImportB);

Multipal Field Group By IN LINQ



var objOrderList = from OrderList in
(from OrderDetail in objOrderDetail
join Item in objItem on OrderDetail.ItemId equals Item.ItemId
join ItemGroup in objItemGroup on Item.GroupId equals ItemGroup.GroupId
select new
{
GroupName = ItemGroup.GroupName,
ItemName = Item.ItemName,
Rate = Item.Rate,
Qty = OrderDetail.Qty
}
)
group OrderList by new
{
OrderList.GroupName,
OrderList.ItemName
} into OrderList
select new
{
GroupName = OrderList.Key.GroupName,
ItemName = OrderList.Key.ItemName,
OrderTotal = OrderList.Sum(OL => OL.Qty * OL.Rate)
};

Left Outer Join and Group By In LINQ


List Table1 = new List();
List Table2 = new List();

var objList = from ListData in
(from a in Table1
join b in Table2 on a.Id equals b.Id into t2
from t2Data in t2.DefaultIfEmpty()
select new
{
Product = a.Product,
Title = t2Data.Title,
Amount = a.Amount
}
)
group ListData by new
{
ListData.Product,
ListData.Title
} into GroupData
select new
{
Product = GroupData.Key.Product,
Title = GroupData.Key.Title,
Amount = GroupData.Sum(OL => OL.Amount)
};

EditTemplates for FieldType in MVC

View->Shared->EditorTemplates->Decimal.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.TextBox("", String.Format("{0:F}", Model)) %>

DisplayFor in MVC

Views->Shared->DisplayTemplates->EmailAddress.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<a href="mailto:<%= Html.Encode(Model) %>"><%= Html.Encode(Model) %></a>
<img src="/Content/images/sendemail.gif" />

EditorFor in MVC

Models->Supplier:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace FeaturesOfMVC2.Models
{
[MetadataType(typeof(Supplier_Validation))]
public partial class Supplier
{
class Supplier_Validation
{
[ScaffoldColumn(false)]
[DisplayName("Supplier Id :")]
public int SupplierId { get; set; }

[Required(ErrorMessage = "Name Required!")]
[DisplayName("Supplier Name :")]
public string SupplierName { get; set; }

[UIHint("StateDDL")]
[DisplayName("State :")]
public int StateId { get; set; }

[UIHint("CityDDL")]
[DisplayName("City :")]
public int CityId { get; set; }

[UIHint("EmailAddress")]
[DisplayName("Email Address :")]
public string EmailId { get; set; }
}
}
}


Views->Shared->EditorTemplates->StateDDL.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.DropDownList("", new SelectList(ViewData["States"] as IEnumerable, "Id", "Name", Model))%>


Views->Shared->EditorTemplates->CityDDL.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.DropDownList("", new SelectList(ViewData["Cities"] as IEnumerable, "Id", "Name", Model))%>


Views->Supplier->Edit.aspx

<%= Html.EditorFor(model => model.StateID) %>
<%= Html.EditorFor(model => model.CityID) %>

JSON Calling from MVC Page

HTML:

<%= Html.DropDownList("", new SelectList(ViewData["States"] as IEnumerable, "Id", "Name", Model))%>
<%= Html.DropDownList("", new SelectList(ViewData["Cities"] as IEnumerable, "Id", "Name", Model))%>


Javascript:

<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("select[id='StateId']").change(function() {
$.ajax({
type: "POST",
url: "/Supplier/StateCityInfo/",
data: { StateId: $(this).val() },
dataType: "json",
error: function(xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
alert(status);
},
success: function(data) {
$("#CityId").empty();
$.each(data, function(key, City) {
$("#CityId").append($("<option></option>").val(City.Id).html(City.Name));
});
}
});
})
})
</script>


Supplier Controller:

public class SupplierController : Controller
{
[AcceptVerbs("POST")]
public ActionResult StateCityInfo(int StateId)
{
return Json(this.AllCity(StateId));
}
}

JSON Calling from ASP.Net

HTML:

<body>
<form id="form1" runat="server">
No Of Doors :
<input id="txtNoOfDoor" type="text" /><br />
<input type="button" id="Button1" value="Get All Cars" />
<input type="button" id="Button2" value="Get Car By No Of Door" />
<div id="output">
</div>
</form>
</body>


Javascript:

<script type="text/javascript" language="javascript">
$(function() {
$('#Button1').click(getCars);
$('#Button2').click(getCarsByDoors);
});

function getCars() {
$.ajax({
type: "POST",
url: "CarService.asmx/GetAllCars",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var cars = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#output').empty();
for (var i = 0; i < cars.length; i++) {
$('#output').append('<p><strong>' + cars[i].Make + ' ' +
cars[i].Model + '</strong><br /> Year: ' +
cars[i].Year + '<br />Doors: ' +
cars[i].Doors + '<br />Colour: ' +
cars[i].Colour + '<br />Price: £' +
cars[i].Price + '</p>');
}
},

failure: function(msg) {

$('#output').text(msg);

}
});
}

function getCarsByDoors() {
var data = '{doors: ' + $('#txtNoOfDoor').val() + ', Name : "Jayesh" }';
$.ajax({
type: "POST",
url: "CarService.asmx/GetCarsByDoors",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var cars = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#output').empty();
for (var i = 0; i < cars.length; i++) {
$('#output').append('<p><strong>' + cars[i].Make + ' ' +
cars[i].Model + '</strong><br /> Year: ' +
cars[i].Year + '<br />Doors: ' +
cars[i].Doors + '<br />Colour: ' +
cars[i].Colour + '<br />Price: £' +
cars[i].Price + '</p>');
}
},

failure: function(msg) {

$('#output').text(msg);

}
});
}

</script>


CarService.asmx:

/// <summary>
/// Summary description for CarService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
[ScriptService]
public class CarService : System.Web.Services.WebService
{
List<Car> objCarList = new List<Car>{
new Car{Make="Audi",Model="A4",Year=1995,Doors=5,Colour="Red",Price=2995f},
new Car{Make="Ford",Model="Focus",Year=2002,Doors=5,Colour="Black",Price=3250f},
new Car{Make="BMW",Model="5 Series",Year=2006,Doors=4,Colour="Grey",Price=24950f},
new Car{Make="Renault",Model="Laguna",Year=2000,Doors=5,Colour="Red",Price=3995f},
new Car{Make="Toyota",Model="Previa",Year=1998,Doors=5,Colour="Green",Price=2695f},
new Car{Make="Mini",Model="Cooper",Year=2005,Doors=2,Colour="Grey",Price=9850f},
new Car{Make="Mazda",Model="MX 5",Year=2003,Doors=2,Colour="Silver",Price=6995f},
new Car{Make="Ford",Model="Fiesta",Year=2004,Doors=3,Colour="Red",Price=3759f},
new Car{Make="Honda",Model="Accord",Year=1997,Doors=4,Colour="Silver",Price=1995f}
};

[WebMethod]
public List<Car> GetAllCars()
{
return objCarList;
}

[WebMethod]
public List<Car> GetCarsByDoors(int doors, string Name)
{
var query = from c in objCarList
where c.Doors == doors
select c;

return query.ToList();
}

[WebMethod]
public string GetAllCarsInString()
{
JavaScriptSerializer objJS = new JavaScriptSerializer();
return objJS.Serialize(objCarList);
}
}


Car Class:

public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public int Doors { get; set; }
public string Colour { get; set; }
public float Price { get; set; }
}

Tuesday, February 2, 2010

Page Method

Code in aspx page :

[System.Web.Services.WebMethod]
public static string CheckUserAvailability(string sUserId, string sUserName)
{
return CommonFunctions.CheckUserAvailability(sUserId, sUserName);
}

HTML :
<a href="#" onclick="CheckAvailability()">Check User Availability</a>
<span id="lblCheck"></span>

Javascript :

function CheckAvailability() {
PageMethods.CheckUserAvailability(document.getElementById('<%= hdnCurrentUserId.ClientID %>').value, document.getElementById('<%= txtUserName.ClientID %>').value, OnSucceededUser, OnFailedUser);

return false;
}

function OnSucceededUser(result, userContext, methodName) {
document.getElementById('lblCheck').innerHTML = result;
return;
}

function OnFailedUser(error, userContext, methodName) {
return;
}

Sunday, January 31, 2010

LINQ Extended method for Update Data

Extended Method

public delegate void Func(TArg0 element);

///
/// Executes an Update statement block on all elements in an IEnumerable sequence.
///
/// The source element type.
/// The source sequence.
/// The update statement to execute for each element.
/// The numer of records affected.
public static int Update(this IEnumerable source, Func update)
{
if (source == null) throw new ArgumentNullException("source");
if (update == null) throw new ArgumentNullException("update");
if (typeof(TSource).IsValueType)
throw new NotSupportedException("value type elements are not supported by update.");

int count = 0;
foreach (TSource element in source)
{
update(element);
count++;
}
return count;
}

Example :

int intUpdate = lstItem
.Where(a => a.ItemGroupId.Equals(lngItemGroupId))
.Update(b =>
{
b.GroupName = strGroupName;
b.GroupLocation = strLocation;
}
);