Friday, January 17, 2014

New Thread implementation in C#.net 4.0

This is a huge jump for thread implementation, now it is become very easy to use thread without any headache. Just write your code snippet inside Thread lambda no need to create a function and point that function to thread.

Example:

public void MailSend(string from, string to, string bcc, string cc, string subject, string body)
{      
    new Thread(() => 
    {
            MailMessage mMailmsg = new MailMessage(); 
            mMailmsg.From ="jjj@gmail.com";
            char[] tosplitter = { ';' };
            string[] tos = to.Split(tosplitter);
            foreach (string d in tos)
            {
                mMailmsg.To.Add(new MailAddress(d));
            }
            try
            {
                if ((bcc != null) && (bcc != string.Empty))
                {
                    char[] bccsplitter = { ';' };
                    string[] bccs = bcc.Split(bccsplitter);
                    foreach (string d in bccs)
                    {
                        mMailmsg.Bcc.Add(new MailAddress(d));
                    }
                }
            }
            catch (Exception exp)
            {
                string str = exp.Message.ToString();
                throw exp;
            }
            try
            {
                if ((cc != null) && (cc != string.Empty))
                {

                    //Spliting to cc
                    char[] ccsplitter = { ';' };
                    string[] ccs = cc.Split(ccsplitter);
                    foreach (string ds in ccs)
                    {
                        mMailmsg.CC.Add(new MailAddress(ds));
                    }
                }
            }
            catch (Exception exp)
            {
                string str = exp.Message.ToString();
                throw exp;
            }
            mMailmsg.Subject = subject;

            mMailmsg.Body = body;

            mMailmsg.IsBodyHtml = true;

            mMailmsg.Priority = MailPriority.Normal; 


        SmtpClient mSmtpClient = new SmtpClient();
        mSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; 
 
        mSmtpClient.Send(mMailmsg); 

    }).Start();
}

Thursday, January 16, 2014

C# Convert Object (or List of Object) to XML

I have a scenario where i need to have xml data from list of objects to send data in a generalized format through http.
This is a generic function by which we can convert a single object as well as a list of objects into xml, object can have list of child objects also.

Main Function :
public string ConvertObjectToXML<T>(T obj)
        {
            System.Xml.Serialization.XmlSerializer xsSubmit = new      System.Xml.Serialization.XmlSerializer(typeof(T));
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            System.IO.StringWriter sww = new System.IO.StringWriter();
            System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sww);
            xsSubmit.Serialize(writer, obj);
            var xml = sww.ToString(); // Your xml context.Response.Write(xml);
            return xml;
        }


Implementation Example :

Test Objects:
 public class Order
    {
        public string orderno { get; set; }
        public List<OrderDetails> lst { get; set; }
    }

    public class OrderDetails
    {
        public string itemname { get; set; }
        public string itemqty { get; set; }
    }

Execution to get result :
public string About()
        {
            OrderDetails orderDetail1 = new OrderDetails { itemname="s", itemqty="1" };
            OrderDetails orderDetail2 = new OrderDetails { itemname = "s2", itemqty = "2" };
            OrderDetails orderDetail3 = new OrderDetails { itemname = "s3", itemqty = "3" };

            List<OrderDetails> lstOrderDetails1 = new List<OrderDetails>();
            lstOrderDetails1.Add(orderDetail1);
            lstOrderDetails1.Add(orderDetail2);
            lstOrderDetails1.Add(orderDetail3);

            Order order1 = new Order();
            order1.orderno = "001";
            order1.lst = lstOrderDetails1;


            OrderDetails orderDetail4 = new OrderDetails { itemname = "s4", itemqty = "4" };
            OrderDetails orderDetail5 = new OrderDetails { itemname = "s5", itemqty = "5" };
            OrderDetails orderDetail6 = new OrderDetails { itemname = "s6", itemqty = "6" };

            List<OrderDetails> lstOrderDetails2 = new List<OrderDetails>();
            lstOrderDetails2.Add(orderDetail4);
            lstOrderDetails2.Add(orderDetail5);
            lstOrderDetails2.Add(orderDetail6);

            Order order2 = new Order();
            order2.orderno = "002";
            order2.lst = lstOrderDetails2;

            List<Order> lstorder = new List<Order>();
            lstorder.Add(order1);
            lstorder.Add(order2);

            string resultXml = ConvertObjectToXML<List<Order>>(lstorder);
            return resultXml;
        }

Wednesday, January 15, 2014

OUTPUT clause in SQL Server to access temp tables at the time of INSERT, UPDATE, DELETE, MERGE like Trigger

Reference :
1. http://technet.microsoft.com/en-us/library/ms177564.aspx
2. http://blog.sqlauthority.com/2007/10/01/sql-server-2005-output-clause-example-and-explanation-with-insert-update-delete/

Concept : 
While executing INSERT UPDATE DELETE or MERGE statement you can access temp tables- Inserted and Deleted just like trigger. This can be executed from code to get just deleted items or inserted item, you can get the no of rows affected from there.
Inserted and Deleted tables are creating on the fly at the time of execution of statement in memory, after commit of execution those tables also get deleted.

Example [from: http://technet.microsoft.com/en-us/library/ms177564.aspx]:

USE tempdb;
GO

CREATE TABLE dbo.table1
(
    id INT,
    employee VARCHAR(32)
)
go

INSERT INTO dbo.table1 VALUES 
      (1, 'Fred')
     ,(2, 'Tom')
     ,(3, 'Sally')
     ,(4, 'Alice');
GO

DECLARE @MyTableVar TABLE
(
    id INT,
    employee VARCHAR(32)
);

PRINT 'table1, before delete' 
SELECT * FROM dbo.table1;

DELETE FROM dbo.table1
OUTPUT DELETED.* INTO @MyTableVar
WHERE id = 4 OR id = 2;

PRINT 'table1, after delete'
SELECT * FROM dbo.table1;

PRINT '@MyTableVar, after delete'
SELECT * FROM @MyTableVar;

DROP TABLE dbo.table1;

--Results
--table1, before delete
--id          employee
------------- ------------------------------
--1           Fred
--2           Tom
--3           Sally
--4           Alice
--
--table1, after delete
--id          employee
------------- ------------------------------
--1           Fred
--3           Sally
--@MyTableVar, after delete
--id          employee
------------- ------------------------------
--2           Tom
--4           Alice
 

Friday, January 10, 2014

Strongly typed view with 2 or multiple models + get model list in post action

Strongly typed view with 2 or multiple models


I faced one situation where a single page contains user info as well as a list of permissions for that user on that page itself, to do this I think it will be the best practice to strongly type the page with 2 models at a time. Then when saving we can get 2 values through models.

Along with this requirement as I have a list of permissions I used editor template.


GET action for this page:


public PartialViewResult UserProfileCreateEdit()
{
UserProfile_ViewModel upvm = new UserProfile_ViewModel();

List<Permission_Result> PermissionList = new List<Permission_Result>();
appUser user = new appUser();

//get user info
using (var context = new abcEntities())
{
int userID = Utility.GetInt(Session["UserId"]);
user = context.appUsers.First(i => i.appUsers_ID == userID);


//set the existing password- blank
user.appUsers_Password = "";

//permissions list by a sp
PermissionList = context.GetPermissionsByUser(userID).ToList();
}


var tuple = new Tuple<List<Permission_Result>, appUser>(PermissionList, user);
return PartialView("UserProfilePartial", tuple);
}



VIEW for this page, this is partial view in my application


@model Tuple<List<DAL.Permission_Result>, DAL.appUser>
@using (Ajax.BeginForm("UserProfileUpdate", "DashBoard", "", new AjaxOptions
{
UpdateTargetId = "ajaxtestP",
OnSuccess = "Success",
OnFailure = "Error"
}, new { id = "ajaxForm" }))
{
<div id="user-profile">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×</button>
<h3 id="myModalLabel">
User Profile</h3>
@Html.HiddenFor(model => model.Item2.appUsers_ID)
</div>
<div >
<div >
<div>
<label>
User Name</label>
@Html.TextBoxFor(model => model.Item2.appUsers_UserName, new { @disabled = "disabled" })
</div>
<div >
<label>
Email id</label>
@Html.TextBoxFor(model => model.Item2.miscTelecom.miscTelecom_Email, new { @disabled = "disabled" })
</div>
</div>
<div >
<div >
<label>
New Passowrd</label>
@Html.TextBoxFor(model => model.Item2.appUsers_Password, new { @type = "password" })
</div>
<div class="span6">
<label>
Confirm Password</label>
<input name="ConfirmPassword" type="password" id="ConfirmPassword" titlemsg="These passwords don't match. Try again?" class="input-block-level" />
</div>
</div>
<div >
<div>
<label>
Role Name</label>
@Html.TextBoxFor(model => model.Item2.admRole.admRole_Name, new { @disabled = "disabled" })
</div>
</div>
<div >
@Html.EditorFor(Item1 => Model, "_TemplateAutoAlertList")
</div>
</div>
<div >
<button class="btn" >
Cancel</button>
<button id="bntsave" class="btn">
Save</button>
</div>
</div>
}


EditorTemplates for this page

@model Tuple<List<DAL.Permission_Result>, DAL.appUser>
<fieldset>
<legend>Permissions</legend>
<table class="table">
<thead>
<tr class="table-heading">
<th>
PermissionType
</th>
<th>
PermissionName
</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Item1.Count; i++)
{
<tr>
<td>
<div >
@Html.DisplayFor(item => Model.Item1[i].PermissionName, new { })
@Html.HiddenFor(item => Model.Item1[i].PermissionID)
</div>
</td>
<td>
<div >
@Html.DisplayFor(item => Model.Item1[i].PermissionType, new { })
</div>
</td>
</tr>
}
</tbody>
</table>
</fieldset>



POST action for this page

[HttpPost]
public JsonResult UserProfileUpdate([Bind(Prefix = "Item1")] List<Permission_Result> lstpc, [Bind(Prefix = "Item2")] appUser user)
{
using (var context = new Entities())
{
try
{
-------logic---------

context.SaveChanges();

string msg = "";
msg = "Information Updated";


return Json(new { message = msg, IsSuccess = true }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { message = ex.InnerException, IsSuccess = false }, JsonRequestBehavior.AllowGet);
}
}
}


Thursday, January 9, 2014

SQL server PARSENAME function

ref: http://www.sqlteam.com/article/using-the-parsename-function-to-split-delimited-data

This function basically split a string by delimiter "." and can fetch any of section of the string by position number (count starting from write hand side ).
For real life implementation we can have delimiter like "," or "|" in that case just replace those by "." first then you can use this function easily.

Sample code:

Declare @ObjectName nVarChar(1000)
Set @ObjectName = 'HeadOfficeSQL1.Northwind.dbo.Authors'

SELECT
        PARSENAME(@ObjectName, 4) as Server,
        PARSENAME(@ObjectName, 3) as DB,
        PARSENAME(@ObjectName, 2) as Owner,
        PARSENAME(@ObjectName, 1) as Object,
        PARSENAME('sss.dd',1)

Result:

Server                        DB          Owner  Object    (No column name)
HeadOfficeSQL1    Northwind    dbo    Authors    dd

c# MVC on page edit (basic) for CMS sites

I was trying to create a CMS project there user will edit content and save if he is admin, and this save option and text box will appear on the page itself without going to admin section separately. This is a demo to do that you can consider this as first step.



my class [consider cms page's place holder id and content]:
namespace Implementation.Models
{
    public class PageContent
    {
        public string Content { get; set; }
        public int PlaceID { get; set; }
    }
}

my controller [ for index page]
namespace Implementation.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            PageContent pc1 = new PageContent { Content = "ssss", PlaceID = 1 };
            PageContent pc2 = new PageContent { Content = "qqqq", PlaceID = 2 };

            List<PageContent> lstpc = new List<PageContent>();
            lstpc.Add(pc1);
            lstpc.Add(pc2);

            ViewBag.isAdmin = true;

            return View(lstpc);
        }

        [HttpPost]
        public ActionResult Index(List<PageContent> lstpc)
        {
            ViewBag.isAdmin = true;

            return View(lstpc);
        }

        public ActionResult About()
        {
            return View();
        }
    }
}

my index view:
@model List<Implementation.Models.PageContent>
@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>

@using (Html.BeginForm())
{
    <div clss="parentContainer">
    @for (int i = 0; i < Model.Count; i++)
    {
    <div id="parentRow">
        @if (Convert.ToBoolean(ViewBag.isAdmin))
        {
            <div id='div_@(i)' style="display:none" class="editor">
                @Html.EditorFor(item => Model[i], "contentPage")
            </div>
        }

        <div class="dispay">
            @Html.DisplayFor(item => Model[i], "contentPage")
        </div>
        @if (Convert.ToBoolean(ViewBag.isAdmin))
        {
            <input type="button" id='btn_@(i)' value="Edit" onclick="OpenDiv(this)" />
        }
    </div>
        }
    </div>
   
    <input type="submit" value="save" />
}

<script type="text/javascript">
    function OpenDiv(obj) {

        $(obj).parent().parent().find('.editor').hide();       
        $(obj).parent().parent().find('.dispay').show();

        $(obj).parent().find('.editor').show();
        $(obj).parent().find('.dispay').hide();
    }
</script>

my display template [created under shared/DisplayTemplates folder -contentPage.cshtml]
@model Implementation.Models.PageContent
<div class="test">
    @Html.DisplayFor(model => model.Content)
    @Html.HiddenFor(model => model.PlaceID)
</div>

my editor template [created under shared/EditorTemplates folder -contentPage.cshtml]
@model Implementation.Models.PageContent
<div class="ksdks">
   @Html.TextBoxFor(model => model.Content)
   @Html.HiddenFor(model => model.PlaceID)
</div>

Wednesday, January 8, 2014

Bundles implementation for MVC 3 by Cassette

Benefits-

http://getcassette.net/benefits
as per site:

Improve your website’s Y-Slow score

A faster website means happier users and can even improve your business’s bottom line. Cassette combines and minifies your assets into bundles. This results in fewer HTTP requests, reducing page load time. 
Cassette bundles are served using the right HTTP caching headers and compressed to ensure optimal client download performance.
Bundle URLs include a hash of the contents, so a changed file results in a new URL. Your users will never have to clear their browser cache again.

Organize your application, your way

Cassette’s flexible configuration system lets you decide how to structure your assets. Use the simple, code-based API to define bundles by convention.
The bundle processing pipeline is fully customizable. It provides full control over how bundles are combined, minified and rendered.

Create cleaner code, faster

Use your favourite awesome languages - CoffeeScript, LESS and Sass. Cassette will compile these into JavaScript and CSS.

Automagic asset ordering

Don’t waste time maintaining that ever-growing file of scripts listed in the right order. Be explicit about each file's dependencies with handy reference comments, and let Cassette determine the correct order for you.
Alternatively, Cassette does offer a simple file format to explicitly order assets.

Simple “in-page” API

Reference the bundles your page view or partial requires using the simple Bundles helper class. Then tell Cassette where to render the HTML. It will generate all the script and link elements for you.
If you reference one bundle that requires another, Cassette knows to include both bundles in the generated HTML.

Easy Debugging & Production Performance

Debug your original JavaScript files - much easier than trying to debug a minified monster! Proper filenames and line numbers let you find and fix problems faster. In debug-mode Cassette puts each source asset into the page individually.
With a single configuration change for production deployment, Cassette will generate the optimized bundle includes instead. This requires absolutely no manual changes to your page source.

Manageable HTML Templates

Embedding HTML templates directly within a page is messy. Keeping each template in its own file makes projects much simpler to maintain. Let Cassette handle the embedding for you.
Cassette can pre-compile the HTML templates into JavaScript for even faster client-side load times.

by installing Cassette package through Nuget that bundle concept can be implemented, site like:
http://getcassette.net/
 
 

1.Open – tool- library package manager – package manager console

          2. execute following statements to install cassettee-


Install-Package Cassette.Less

Install-Package Cassette.Sass

Install-Package Cassette.CoffeeScript

create a class in your project can be named-                      3.CassetteConfiguration name space as the main project


in the class:


4.using Cassette;


using Cassette.Scripts;


using Cassette.Stylesheets;






public class CassetteConfiguration


{


public void Configure(BundleCollection bundles)


{


bundles.Add<StylesheetBundle>("Content", bundle => bundle.EmbedImages());


bundles.AddPerSubDirectory<ScriptBundle>("Scripts");


}


}






Previous case not runnign new implementation:

WORKING: http://www.arroyocode.com/asset-and-bundling-management-in-asp-net-mvc-3

Execute following stetment for mvc 3

1. Install-Package Cassette.Web

web.config in View folder you can find - <add namespace="Cassette.Views" /> which will register the namespace
Follow step 3 and 4  as previous.
In _Layout.cshtml
put that at top of the page to load required css and scripts :

@{
    Bundles.Reference("Content/Site.css");
    Bundles.Reference("Scripts/modernizr-2.5.3.js", "headerScripts");
    Bundles.Reference("Scripts/jquery-1.7.1.js", "footerScripts");
}
for asp.net forms:
<% Cassette.Views.Bundles.Reference("Content/Site.css"); %>

IN head to load css:
@Bundles.RenderStylesheets()
for asp.net forms:
<%: Cassette.Views.Bundles.RenderStylesheets() %> 


In required location:
@Bundles.RenderScripts("headerScripts")
or
 @Bundles.RenderScripts("footerScripts")

to render the content on the page