Thursday, February 25, 2016

UPDATE part of a string in SQL Server using REPLACE

I've got a table with two columns, ID and Value. I want to change a part of some strings in the second column.
Example of Table:
ID            Value
---------------------------------
1             c:\temp\xyz\abc\111
2             c:\temp\xyz\abc\222
3             c:\temp\xyz\abc\333
4             c:\temp\xyz\abc\444
Now the xyz\ in the Value string is not needed. 
For UPDATE and REPLACE the same, use below SQL query :
UPDATE dbo.xxx
SET Value = REPLACE(Value, 'xyz\', '')
WHERE ID <=4
you can read more about REPLACE here .

Saturday, February 20, 2016

How to force ASP.NET Web API to always return JSON?


  • Edit your Global.asax.cs to Clear all formatters and add Json formatter back.
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
  • After adding above two lines in your code, your code will be look like below and it will always return JSON :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace BoomInteractive.TrainerCentral.Server {
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class WebApiApplication : System.Web.HttpApplication {
        protected void Application_Start() {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Force JSON responses on all requests
            GlobalConfiguration.Configuration.Formatters.Clear();
            GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
        }
    }
}

Thursday, February 18, 2016

Set default page for your website using Web.Config file in ASP.Net

  • This feature is applicable for .Net 3.5, 4.0, 4.5 or above frameworks.
  • Go to your web.config file and add below code.
Single Default Page

<system.webServer> 
<defaultDocument enabled="true">
 <files>
    <clear/>
    <add value="Home.aspx"/>
 </files>
</defaultDocument>
</system.webServer> 

Multiple Default Pages

  • Here if the Home.aspx page is missing the 2nd page i.e. Contact.aspx will become the Default page.
<system.webServer> 
<defaultDocument enabled="true">
 <files>
    <clear/>
    <add value="Home.aspx"/>
    <add value="Contact.aspx"/>
 </files>
</defaultDocument>
</system.webServer> 

Tuesday, February 2, 2016

Difference between $(window).load and $(document).ready

$(document).ready is a jQuery event. It fires as soon as the DOM is loaded and ready to be manipulated by script. This is the earliest point in the page load process where the script can safely access elements in the page's html DOM. This event is fired before all the images, css etc.. are fully loaded.


$(window).load event fires when the DOM and all the content on the page (images, css etc) is fully loaded. This event is fired after all the images, css etc.. are fully loaded that means after ready event.


The following example proves the above point. When you run the page with the following script, notice that the alert in ready function is displayed before the alert in load function.


<script type="text/javascript">
    $(window).load(function () {
        alert('Window loaded');
    });

    $(document).ready(function () {
        alert('DOM Loaded and ready');
    });
</script>

In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. So ready() is usually the best place to write your JavaScript code.

However, in your application there could be scenarios where you should be using $(window).load over $(document).ready. For example, let's say we want to display the actual image dimensions (Height and Width). To get the actual image dimensions, we will have to wait until the image is fully loaded, so the jQuery code to get the height and width should be in $(window).load event.

Monday, July 27, 2015

Slug generator or Make Friendly URL from a post title


  • Normally we want to generate Friendly URL or we can say Slug from our post title.
  • Just pass your string to below "GenerateSlug" function and it will return you Friendly URL.



        public string GenerateSlug(string phrase)
        {
            string str = RemoveAccent(phrase).ToLower();
            // invalid chars           
            str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
            // convert multiple spaces into one space   
            str = Regex.Replace(str, @"\s+", " ").Trim();
            // cut and trim 
            str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim();
            str = Regex.Replace(str, @"\s", "-"); // hyphens   
            return str;
        }

        public string RemoveAccent(string txt)
        {
            byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(txt);
            return System.Text.Encoding.ASCII.GetString(bytes);
        }


  • You can find more detail discussion and other solutions here.

Convert Image to byte or Base64 String



  • We have to just provide input stream as "FileUpload1.PostedFile.InputStream" to below function

Image Stream to Byte :-

public static byte[] StreamToByte(Stream input)
        {
            byte[] buffer = new byte[input.Length];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }


Image Stream to Base64String :-

public static string StreamToBase64(Stream input)
        {
            byte[] buffer = new byte[input.Length];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                string temp_inBase64 = Convert.ToBase64String(ms.ToArray());
                return temp_inBase64;
            }
        }
        

Monday, October 21, 2013

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'.

Error :-
Login failed for user 'IIS APPPOOL\ASP.NET v4.0'.

Solution:-

You can change the ApplicationPoolIdentity from IIS7 -> Application Pools -> Advanced Settings.




Under ApplicationPoolIdentity you will find local system. This will make your application run under NT AUTHORITY\SYSTEM, which is an existing login for the database by default.