adsense

Wednesday, December 6, 2017

.NET Support for TLS 1.2

It seems that support for TLS 1.2 dependent on the .net framework version.

  • NET 4.6 and above. Supported by default.
  • .NET 4.5. TLS 1.2 is supported. The following code will make TLS 1.2 to be used as the default protocol.                                                                  ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
  • .NET 4.0. TLS 1.2 is not supported, but following code can be used as a workaround:
    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
  • .NET 3.5 or below. TLS 1.2 is not supported.
Cheers,

Samitha

Thursday, November 16, 2017

Removing XML Nodes from a XML Document

Following code can be used to remove a XmlNode with all the children nodes

      XmlDocument doc = new XmlDocument();
        doc .Load(MapPath("~/FileName.xml"));
        XmlNodeList selectedNodes = doc .SelectNodes("//SubNode");
      
       foreach (XmlNode node in selectedNodes )
        {
            node.ParentNode.RemoveChild(node);
        }

Regards,
Samitha

Thursday, November 2, 2017

IIS error accessing WCF (HTTP Error 404.3)

When accessing a WCF service through browser, you  might have encountered following IIS error.

HTTP Error 404.3 - Not Found The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

This occurs due to a feature in IIS which is not turned on by default.


This issue can be solved through following steps.

  1. From Control Panel -> Programs and Features -? Turn Windows features on or off.
  2. Click.NET Framework 4.6 Advanced Services - WCF Services (actual framework version may change)
  3.  Select HTTP Activation
  4. Ok

 

Wednesday, October 4, 2017

jquery paste event

You can use the jQuery paste event on any textbox/editor as shown below. It is supported by all modern browsers.

Following example shows handling numeric values on key press and past.

 <script type="text/javascript">

 function pageLoad() {
  $("#controlID").on('paste, keydown', function e() {
        return isNumericKey(e);
  });
 }
 
function isNumericKey(e) {
    var charInp = window.event.keyCode;
        if (charInp > 31 && (charInp < 48 || charInp > 57)) {
            return false;
        }
        return true;
  }
 
</script> 
 
Cheers,
Samitha 

Wednesday, August 30, 2017

Refused to display in a frame because it set 'X-Frame-Options' to 'DENY'

You might Sometimes encounter the error above when you are using iframes w to load resources outside from the domain.

This Issue can be fixed in two ways

1) Add this to web.config

<httpProtocol>
    <customHeaders>
      <add name="X-Frame-Options" value="AllowAll" />
    </customHeaders>
  </httpProtocol>

2) Add this to Global.asax.cs

protected void Application_PreSendRequestHeaders()
{
 Response.Headers.Remove("X-Frame-Options");
 Response.AddHeader("X-Frame-Options", "AllowAll");
}
 
Please read this discussion in stackoverflow for a detailed discussion on the topic.

Regards,
Samitha


Wednesday, August 9, 2017

drop database user that owns a schema


First you will have to determine the schema's owned by a given user in order to  drop the user.

Execute the following query to determine the schemas owned by the user  named ‘user1’ .

SELECT name FROM sys.schemas
WHERE principal_id = USER_ID('user1');

When you run the query above, suppose you get db_datawriter as the schema owned by user (in this case user1)

Next step is to change the owner of the schema db_datawriter to some other user (e.g. dbo):

ALTER AUTHORIZATION ON SCHEMA::db_datawriter TO dbo;



You will have to remove all the schemas to drop a db user. When the user has no schemas owned you can drop it.


Friday, July 14, 2017

Retrieve the uploaded file extension from JavaScript

Following java script unction can be used to get the extension of a uploaded file.

function getFileExtension(fileName)
{
  var extension = /^.+\.([^.]+)$/.exec(fileName);
  return extension == null ? "" : extension [1];
}

Cheers
Samitha

Tuesday, June 27, 2017

Enable/Disable button when checkbox clicked

This can be easily achieved using jQuery as displayed below.

//bind this event in pageLoad or Dom Ready

$("#chkAgree").click(function(e) {
  $("#btnSave").attr("disabled", !this.checked);
});

Regards,
Samitha

Friday, June 2, 2017

asp.net textbox Enter key press focus to next control

The default behavior when  pressing Enter key on textbox is to fire the form submit event.
 This default behavior can be overridden and force the input to be advanced to the next control as shown below.

<script type="text/javascript">
 
 function pageLoad(){
 //you can use the control id or class
    $("#<%=txtName.ClientID%>").keypress(function (event) {
                var Text = $(this).val();
                if (event.which == 13) {
                    event.preventDefault();
                    $("#<%=txtPwd.ClientID%>").focus();
                }
            });
 
     $("#<%=txtPwd.ClientID%>").keypress(function (event) {
                var Text = $(this).val();
                if (event.which == 13) {
                    event.preventDefault();
                    $("#<%=butnLogin.ClientID%>").focus();
                }
            });
 } 
 
</script> 
 
 


Thursday, May 25, 2017

Multiple ID and class seletor



CSS
#divTitle.Format {  }

#divTitle.Format { }

Above CSS rules looks identical but they serves different purposes. As a summary above rules can be described as follows.

First CSS rule will Select all elements with the class named Format that are descendants of the element with an ID of divTitle.

 Second CSS rule will Select the element which has an ID of divTitle and also a class name of Format.

So if you want to select a specific HTML element with a given id and class the second CSS rule will come handy.

More detailed discussion of the above topic can be found here.
 
Cheers
Samitha

Thursday, May 4, 2017

Expand and Collapse a html Table Rows on Click

HTML Table rows can be easily expanded/collapsed using jQuery as displayed in  code snippet below.

e.g.
HTML

<table class="Menu">
            <tr class="row" >
               <td>Menu 1</td>
            </tr>
            <tr class="row" >
                <td>
                    Sub Menu 1
                    Sub Menu 2
                </td>              
            </tr>
            <tr class="row" >
                <td>Menu 2</td>
            </tr>
        </table>

JavaScript

<script type="text/javascript">
           $(function(){
              //collapse all rows on load
              $(".row").hide();
              
              ToggleCollapse();
           });

  function   ToggleCollapse(){
    var isCollapsed = true;

    $(".Menu").click(function () {
                    if (isCollapsed) {
                        $(".row").show();
                        isCollapsed = false;
                    }
                    else
                    {
                        $(".row").hide();
                       isCollapsed = true;
                    }
                  });
 }
</script>


I have used CSS classes to identify the table rows and  the HTML Table.

Cheers,
Samitha

Friday, April 28, 2017

Visual Studio Performance enhancements

If you get the feeling that Visual Studio takes long time for debugging process, ensure that you have made this changes to enhance the performance.

1.Disable XAML Designer (from Options -> XAML Designer -> General -> Enable XAML Designer)

2. Disable Diagnostic Tools while debugging (from Options -> Debugging -> General -> Enable Diagnostic Tools while debugging)

3. Disable full solution analysis  (from  Options -> Text Editor -> C# -> Advanced -> Enable full solution analysis)

Regards
Samitha

Thursday, April 6, 2017

Visual Studio 2015 Installer Projects

If you try to open an Installer project created from Visual Studio 2010 from Visual Studio 2015 you will get a error.

This can be resolved by installing the extension for Visual Studio 2015 which can be downloaded here.

Friday, March 10, 2017

asp.net DropDownList get selected Text and Value

You can use JavaScript or jQuery to get the selected text/value of a fiven dropdownl list as shown below.

HTML
<asp:DropDownList ID="ddlPerson" runat="server"  onchange="GetSelected(this)">
                                                                           

JavaScript

<script type="text/javascript">

    function GetSelectedTextValue(ddl) {
        var selectedText = ddl.options[ddl.selectedIndex].innerHTML;
        var selectedValue = ddl.value;
        alert("Text: " + selectedText + " Value: " + selectedValue);
    }

</script>

jQuery

 <script type="text/javascript">

    $(function () {
        $("#ddlPerson").change(function () {
            var selectedText = $(this).find("option:selected").text();
            var selectedValue = $(this).val();
            alert("Text: " + selectedText + " Value: " + selectedValue);
        });
    });

</script>

Cheers
Samita

Thursday, February 23, 2017

Asp.net Preview Image before Upload

If you want to preview and image before its uploaded you have two options

1. Using a jQuery plugin
  There are plenty of jQuery plugins available that you can use to achieve this purpose. Here I will list some of the common plugins used.

2.Without using a jQuery plugin
  Here you can use simple jQuery as shown below.

HTML

<form id="form1" runat="server">
    <input type='file' id="imgUp" />
    <img id="preview" src="#" alt="your image" />
</form>

JavaScript

<script type="text/javascript">

 $("#imgUp").change(function(){

     var input= $(this).val();


    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#preview').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
});

 </script>

Cheers
Samitha




Friday, February 17, 2017

ASP.Net MVC generate Url of any file

If you want to get generate a URL for a given file (image)  in ASP.net MVC you can use following method

public static string ResolveServerUrl(string serverUrl, bool forceHttps)
{
    if (serverUrl.IndexOf("://") > -1)
        return serverUrl;

    string newUrl = serverUrl;
    Uri originalUri = System.Web.HttpContext.Current.Request.Url;
    newUrl = (forceHttps ? "https" : originalUri.Scheme) +
        "://" + originalUri.Authority + newUrl;
    return newUrl;
} 
 
 Then you can get the absolute URL by calling the method as displayed below.

ResolveServerUrl(VirtualPathUtility.ToAbsolute("~/images/YourImage.gif"),false))
 
 
Refer to this stackflow discussion for more information

 
Cheers,
Samitha
 
 

Friday, February 3, 2017

Printing web pages


When you are developing a Web page, you will have to consider Web page printing facility. There are some guidelines you need to follow to ensure that all the content within the page is printed in a usable way.

Following article discusses on the way you should design the page. In summary you should consider following when designing the style sheet.

1. Design a print style sheet (use media="print")
2. Remove unwanted items (use a no-print class). In addition you might need to eliminate hyperlinks being printed. That can be achieved as shown below.
 @media print
{
     a[href]:after {
    content: none !important;
   }
}

3. Format the page
4. Change the font and Links


Cheers,
Samitha

Friday, January 27, 2017

asp.net mvc disable submit when ENTER key is pressed

When you create a view with a submit button, the default behavior is submit will be triggered on KEY PRESS events.

If your view has a BeginForm, following code will stop submitting on KEY PRESS.

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { onkeydown = "return event.keyCode!=13" }))
{
    //code
}


Alternatively you can use jQuery to resolve the same issue as follows

<script>

 $(function () {
         $(document).on("keydown", "input", function(e) {
             if (e.which==13) e.preventDefault();
        });
  });

</script>


Friday, January 20, 2017

Rotate Image OnClick

An image can be easily rotated using JavaScript or jQuery. I ll share both ways in this post.

HTML

 <img src="Pic.jpg" id="image" onclick="rotate90(this)"> 
 
JavaScript

 <script>
    var angle=90;
 
    function rotate90(ele){
  
     if(angle>360)//reset angle
                angle=90;
 
     ele.style.webkitTransform="rotate("+angle+"deg)";//Mozilla
     ele.style.msTransform ="rotate("+delta+"deg)"; //IE
 
     /*optionally set other vendor specific transformation
       ele.style.MozTransform = rotate("+delta+"deg)";
       ele.style.OTransform = rotate("+delta+"deg)";
    */
 
        angle+=90;
    }
 </script>
 
jQuery
 
 Use jQuery Rotate plugin to do the actual rotation 

 <script>
    var angle=90;
 
    function rotate90(ele){
  
       if(angle>360)//reset angle
                angle=90;
 
       $(this).rotate(angle);
 
        angle+=90;
    }
 </script>
 
Cheers
Samitha

Wednesday, January 11, 2017

asp.net MVC Make DIV redirect

 Suppose you have a DIV element on a page, such that when clicked should behave like a normal Hyperlink. This can be easily achieved using jQuery.

HTML

<div class="logo" data-action ="@Url.Action("ActionName", "ControllerName")" style="cursor: pointer;" >                   
  DivText       
</div>
 
JavaScript

<script>
   $(function() {

     $('.logo').click(function () {
                var url = $(this).attr('data-action');

                if (url !== undefined)
                    window.location.href = url;
            });
});

</script>