Wednesday, February 5, 2014

Replace String with ignore case

I have faced a situation where I need to replace some tag in mail body template with value but tags can be created in any case so while replacing I had to do ignore case. So I created a extension method for string as follows.

//main function
        static public string ReplaceIgnoreCase(this string source, string OldText, string NewText)
        {
            source = Regex.Replace(source, OldText, NewText, RegexOptions.IgnoreCase);
            return source;
        }

//implementation
emailbody = emailbody.ReplaceIgnoreCase("<email>", "abc@ggg.com");

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>