Monday, March 31, 2014

Enable Large file Upload

I was getting error:

Maximum request length exceeded.

while uploading an image of 5 mb, google helped me out to solve this problem. We need to write 2 sections in web.config to get rid of this.

<system.web>
    <httpRuntime maxRequestLength="1048576" /> <!--[value in kb]-->
</system.web>

FOR IIS & or above
<system.webServer>
  <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" /> <!--[value in byte]-->
      </requestFiltering>
    </security>
  </system.webServer>

Now it is allowing me to upload file upto 1 gb.

Web page redirection for mobile devices by checking viewport only

I am facing one scenario where main browser site need to be shown in large devices but for small devices show mobile site.
To do this device profile checking is not enough for me, so need to go with window width.

//under width of 768 mobile site will open.
 if (window.screen.width < 768) {
   window.location = '~/Mobile/Home.aspx'; //for example
 }

//New update : second solution

Now  I extended the functionality, if any desktop page opened in mobile site then that page will be redirected to the mobile version of that page.
NOTE: every desktop page should have their mobile version under "mobile"  folder.

if (window.screen.width < 768)

  var currentPath= location.pathname;
  if(currentPath=='/')
  {
    currentPath="/Home.aspx";
  }
  if((currentPath.indexOf('/mobile/') != -1)||(currentPath.indexOf('/Mobile/') != -1)){
    //console.log("found so no need to redirect");
  }
  else
  {
    //console.log("not found but screen size small so redirect to mobile")
    //console.log('Mobile/'+currentPath);
    window.location = location.protocol +'//'+ location.host+'/Mobile'+currentPath;//Home.aspx
  }
}

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