Friday 28 November 2014

Find Invalid chars from a given string using JavaScript

 

// Test Data
var testString1 = "Te<s'ting";
var testString2 = "Test";

// set of Invalid characters.These should be avoided from test  strings
var RegExp = /[\'\<\>\"\%\;\(\)\&\+\#\*\--]/i;

// 1st Test String

// If the test string contains invalid characters then
if (RegExp.test(testString1)) {
    // Found a match with Invalid chars
    alert(testString1 + ' contains invalid chars');
}
else {
    // Not matching with Invalid chars
    alert('No invalid chars in ' + testString1);
}

// 2nd Test String

if (RegExp.test(testString2)) {
    // Found a match with Invalid chars
    alert(testString2 + ' contains invalid chars');
}
else {
   // Not matching with Invalid chars
    alert('No invalid chars in '+ testString2);
}

Tuesday 29 July 2014

How to find .NET version?

Type any one of the below commands to give you the latest version in the first line

1. CSC(works in Visual Studio Command prompt)


2. GACUTIL /l ? (works in Visual Studio Command prompt )


3. dir /b /ad /o-n %systemroot%\Microsoft.NET\Framework\v?.*


Last command will list out all the versions of .NET installed, latest first.

Tuesday 3 June 2014

Updating XML attribute in SQL Server XML column


--Remove the temp table if exisits
IF OBJECT_ID('tempdb..#XMLTemp') IS NOT NULL DROP TABLE #XMLTemp
GO

--Create the temp table
CREATE TABLE #XMLTemp (Id int, Name varchar(32), XML_Data xml)

--Insert values
INSERT INTO #XMLTemp VALUES
(1,        'AAA',        '<MyRoot><Data attr1="1" attr2="11">One</Data></MyRoot>'),
(2,        'BBB',        '<MyRoot><Data attr1="2" attr2="22">Two</Data></MyRoot>'),
(3,        'CCC',        '<MyRoot><Data attr1="3" attr2="33">Threee</Data></MyRoot>'),
(4,        'DDD',        '<MyRoot><Data attr1="4" attr2="44">Four</Data></MyRoot>')

--select the values
SELECT * FROM #XMLTemp

--Select all attribute values in a node where attr2 has value 32
SELECT Name
      ,C.value('@attr1', 'int') as Attribute1
      ,C.value('@attr2', 'int') as Attribute2
      ,C.value('.', 'varchar(10)') as NodeValue
FROM #XMLTemp CROSS APPLY
     #XMLTemp.XML_Data.nodes('MyRoot/Data') as X(C)
where C.value('@attr2', 'int') = 33

--Update attr2 value to 66666666666 if its value is 33
UPDATE #XMLTemp
SET XML_Data.modify('replace value of (/MyRoot/Data[@attr2="33"]/@attr2)[1] with "66666666666" ')


--select the values.Check to see if updated the row or not
SELECT * FROM #XMLTemp

Tuesday 20 May 2014

Calulating working days without cosidering Holidays

 

/***Drop temp table if exisits***/
IF OBJECT_ID('tempdb..#CalculteWorkingDays') IS NOT NULL
    DROP TABLE #CalculteWorkingDays
GO

/***Temp table for data***/
CREATE TABLE #CalculteWorkingDays
    (
        [CreatedDate]        DATE,
        [ClosedDate]         DATE,
        [ATA(days)]          INT
    )


/***Insert data to temp table***/
INSERT INTO #CalculteWorkingDays
(        [CreatedDate],    [ClosedDate]    )
SELECT    '12/01/2003',    '12/31/2003'    UNION ALL
SELECT    '12/01/2004',    '12/31/2004'    UNION ALL
SELECT    '12/01/2005',    '12/31/2005'    UNION ALL
SELECT    '12/01/2006',    '12/31/2006'    UNION ALL
SELECT    '12/01/2007',    '12/31/2007'    UNION ALL
SELECT    '12/01/2008',    '12/31/2008'    UNION ALL
SELECT    '12/01/2009',    '12/31/2009'    UNION ALL
SELECT    '12/01/2010',    '12/31/2010'    UNION ALL
SELECT    '12/01/2011',    '12/31/2011'    UNION ALL
SELECT    '12/01/2012',    '12/31/2012'    UNION ALL
SELECT    '12/01/2013',    '12/31/2013'    UNION ALL
SELECT    '12/01/2014',    '12/31/2014'               

/***Now calculte the Working days***/

--DATEDIFF Returns the number of dd(day),wk(week) boundaries that are
--crossed between two specified dates.
--By Default Sunday is considered as 1st day of week and Saturday
--as Last day of week.

-- Calculate the working days and update it to [ATA(days)] column

-- Caluculate the days between dates . DATEDIFF + 1 Includes Both Dates
-- Exclude the no of Weeks crossed between dates * 2 (for Sat and Sun)
-- If start date falls on Sunday then exclude this from Working days caluculation
-- If end date falls on Saturday then exclude this from Working days caluculation
-- Exclude BankHolidays(Doesn't include here.We need to calcul;ate them eother by mainitng sepetare table for holidays)
                                                           
                   
UPDATE #CalculteWorkingDays
                   
SET [ATA(days)] =(DATEDIFF(dd, [CreatedDate], [ClosedDate]) + 1)                    
                -(DATEDIFF(wk, [CreatedDate], [ClosedDate]) * 2)
                -(CASE WHEN DATENAME(dw, [CreatedDate]) = 'Sunday' THEN 1 ELSE 0 END)
                -(CASE WHEN DATENAME(dw, [ClosedDate]) = 'Saturday' THEN 1 ELSE 0 END)
                   
                   
SELECT * FROM #CalculteWorkingDays

Wednesday 2 April 2014

Submit button allowed to click only once with an ASP.NET Button Server Control

Introduction

It is often a required functionality that a button is only allowed to be clicked once during data submission in a web application. Clicking the button more than once might cause irrecoverable damage.

One of the solution i found useful in our case is:

  • Properly set up the properties of the button server control to enable client side click event and to change its submission behavior

Set Up Button Server Control Properties

Two of the properties of an ASP.NET button server control are of our interest:

  • UseSubmitBehavior: False
  • OnClientClick: this.disabled = true;

When UseSubmitBehavior is set to False, the button server control is rendered to a client browser as an HTML “button” (HTML <input> tag with type=“button”) instead of an HTML “submit button” (HTML <input> tag withtype=”submit”) which is the default behavior. As a result, client side JavaScript is able to intercept the submission process when the button is clicked.

The OnClientClick property specifies a client side JavaScript function. When the button is clicked, this function is executed first before submitting data to server. A decision can be made at client side for whether or not the submission should continue based on the result of client side validation.

If you disable a button in onclientclick, other events will not fire because the object they are tied to is disabled. So we need to set UseSubmitBehavior  to false so that javascript will take care of submitting the button.

HTML code of an ASP.NET button server control with the UseSubmitBehavior and OnClientclick properties at design time is shown below:

<asp:Button ID="btnSubmit" runat="server" CssClass="btn-active"   
Text="Submit Data" onclientclick="this.disabled = true;"   UseSubmitBehavior="False"
onclick="btnSubmit_Click" />

After being rendered to a client browser, the HTML code will look like that shown below. Note that the type is “button” but not “submit”. The event handler WebForm_DoPostBackWithOptions(...) deals with server side click while the onclick="this.disabled = true;" is for client side click.

<input type="button" name="btnSubmit" value="Submit Data" onclick="this.disabled = true;
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;btnSubmit&quot;,
&quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, true))" id="btnSubmit"
class="btn-active" style="width:120px;" />

With the above two properties properly set, the button can be disabled at client side during submission to prevent it from being clicked more than once. In addition, a warning message may also be displayed or the current page may be completely greyed out to indicate the progress of data processing at server side.

Tuesday 7 January 2014

$(document).ready() vs pageLoad()

 

$(document).ready() and pageLoad() are very different behind the scenes.

$(document).ready()

If a browser supports the DOMContentLoaded event (many non-IE browsers do), then $(document).ready() will fire on that event. However, IE can’t safely fire $(document).ready() until the document’s readyState reaches “complete”, which is typically later.

If none of those optimizations are available, window.onload will trigger the event.

pageLoad()

Instead of targeting browser-specific optimizations, the ASP.NET AJAX pageLoad() shortcut function is called as a result of a more uniform process.

That process is queued up the same way on all browsers, via a call to setTimeout with a timeout of 0 milliseconds. This trick leverages JavaScript’s single-threaded execution model to (theoretically) push the init event back until just after the DOM has finished loading.

Counter-intuitively, this isn’t the only point at which pageLoad() is called. It is also called after every partial postback. It basically functions as a combination ofApplication.Init and PageRequestManager.EndRequest.

Danger: UpdatePanels ahead

Since pageLoad() is called after every UpdatePanel refresh, the complications that arise can be initially difficult to grasp. For example, you’ll often see code like this:

<script type="text/javascript"> 
function pageLoad() {
// Initialization code here, meant to run once.
}
</script>   <asp:ScriptManager runat="server" />   <asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button runat="server" ID="Button1" />
<asp:Literal runat="server" ID="TextBox1" />
</ContentTemplate>
</asp:UpdatePanel>


That initialization code will execute on the initial load, and things will seem okay at first. However, pageLoad() will then continue to be called each time Button1 is triggered, resulting in the initialization code running more often than intended.



This problem is similar to the classic ASP.NET mistake of forgetting to test for IsPostBack during the server-side Page_Load event. Depending on the nature of your initialization code, you may not even notice that there’s a problem, but it’s bound to catch up with you eventually.



In the case of initialization code that should run once, $(document).ready() is the ideal solution. It will do exactly what you need and nothing more.



Sometimes, pageLoad() is exactly what you want


While $(document).ready() is ideal for one-time initialization routines, it leaves you hanging if you have code that needs to be re-run after every partial postback. The LiveQuery functionality added in jQuery v1.3+ helps with this, but only works for a limited set of functionality.



For example, what if we wanted to add a jQueryUI datepicker to the TextBox in the previous example? Adding it in $(document).ready() would work great, until a partial postback occurred. Then, the UpdatePanel’s new TextBox element would no longer have the datepicker wired up to it. This is exactly where pageLoad() shines:



<script type="text/javascript">
function pageLoad() {
$('#TextBox1').unbind();
$('#TextBox1').datepicker();
}
</script>   <asp:ScriptManager runat="server" />   <asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button runat="server" ID="Button1" />
<asp:TextBox runat="server" ID="TextBox1" />
</ContentTemplate>
</asp:UpdatePanel>


By attaching in pageLoad(), our TextBox will now have the datepicker attached to it on initial page load, and have it re-attached after every partial postback.



The call to unbind() is optional in this case, but a good precaution on more complex pages. Else, you run the risk of stacking multiple events on elements that were notrefreshed as part of the partial postback.



An ASP.NET AJAX alternative to $(document).ready()


The previous sections should make it easier to decide between jQuery and ASP.NET AJAX’s events, but they assume you’re using both frameworks. What if you’re only using ASP.NET AJAX and want functionality similar to $(document).ready()?



Luckily, ASP.NET AJAX does provide a corresponding event. The Application.Initevent fires only one time per page load, and is perfect for onetime initialization tasks. It’s not available through a shortcut function and requires slightly more caution, but serves its purpose:



<asp:ScriptManager runat="server" />   <script type="text/javascript"> 
Sys.Application.add_init(function() {
// Initialization code here, meant to run once.
});
</script>


Note that the call to Application.add_init is placed after the ScriptManager. This is necessary because the ScriptManager injects its reference to MicrosoftAjax.js in that location. Attempting to reference the Sys object before that point will result in a “sys is undefined” JavaScript error.



If you think that limitation is a bit messy, you are not alone. I’m not a big fan of littering my presentation code with any more inline JavaScript than is necessary. To avoid this clutter, you may alternatively include your Application.Init code in an external file, included via a ScriptReference (see the previous link for an example).



Summary (tl;dr)


$(document).ready()




  • Ideal for onetime initialization.


  • Optimization black magic; may run slightly earlier than pageLoad().


  • Does not re-attach functionality to elements affected by partial postbacks.



pageLoad()




  • Unsuitable for onetime initialization if used with UpdatePanels.


  • Slightly less optimized in some browsers, but consistent.


  • Perfect for re-attaching functionality to elements within UpdatePanels.



Application.Init




  • Useful for onetime initialization if only ASP.NET AJAX is available.


  • More work required to wire the event up.


  • Exposes you to the “sys is undefined” error if you aren’t careful.



 



Source : http://encosia.com/document-ready-and-pageload-are-not-the-same/