Tuesday, February 25, 2014

get column name from column description in mssql

 select
        st.name [Table],
        sc.name [Column],
        sep.value [Description]
    from sys.tables st
    inner join sys.columns sc on st.object_id = sc.object_id
    left join sys.extended_properties sep on st.object_id = sep.major_id
                                         and sc.column_id = sep.minor_id
                                         and sep.name = 'MS_Description'
                                where st.name = 'actBill'
                                AND sep.value = 'aaa'  ---description of the column

Thursday, February 6, 2014

Shorten length of string if it is too large and set ... at the end of sentence or word

I am getting a very large text without any space so it is overflowing parent container, so to manage that situation it will be better if we can calculate the width and trim last part and set ... at the end of the line to show continuation. To do this I have implemented following thing, here if content width is larger than parent width then it will show ... at the end of line and if not then show text as it is. While resizing the window at that time also it will work.

BEST WAY JUST USE CSS

.shortenText {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

}

<span class="shortenText">test string where ...will come at the end of line if line is very long</span>

Using JQUERY
Here I have user attribute to locate the text container.
Hover the content with ... will show the content in tooltip.

EXAMPLE:

<style type="text/css">
    [autowidth='auto']
    {
        display: none;
    }
</style>

<div style="width:20%">
    <div >
        <div autowidth="auto">abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz</div>      
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
              resizeText();
    });

    $(window).resize(function () {
        resizeText();
    });

 function resizeText() {
        $("[autowidth='auto']").parent().find('.dot').remove()
        $("[autowidth='auto']").parent().find('.resized').remove()

        $("[autowidth='auto']").each(function () {

            var width = $(this).parent().width();
            var childDivWidth = $(this).width();

            var dotwidth = 10;
            var mainContainerCalculatedWidth = width - (dotwidth + 1);
            
            var maindiv = $("<div class='resized'>").text($(this).text()).css('width', mainContainerCalculatedWidth + 'px').css('float', 'left').css('overflow', 'hidden');
            $(this).parent().append(maindiv);

            if (childDivWidth > width) {
                var extra = $("<div class='dot'>").text('...').css('width', dotwidth + 'px').css('float', 'left').attr('title', $(this).text());
                $(this).parent().append(extra);
            }
        });
    }
</script>

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);
}
}
}