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/

Friday 19 April 2013

Control with id XXX could not be located or a different control is assigned to the same ID after postback

 

I came across this error while developing a page with so many user controls in it.

Some of them are loaded dynamically in the code behind like image buttons in a ListView.

While filtering the ListView, sometimes I would get the error and sometimes not.

Problem

Server Error in '/YYY Application.


An error has occurred because a control with id ‘XXX' could not be located or a different control is assigned to the same ID after postback. If the ID is not assigned, explicitly set the ID property of controls that raise postback events to avoid this error.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.Web.HttpException: An error has occurred because a control with id 'ctl00$contentMain$lstGoalList$ctrl4$ctl00' could not be located or a different control is assigned to the same ID after postback. If the ID is not assigned, explicitly set the ID property of controls that raise postback events to avoid this error.
Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[HttpException (0x80004005): An error has occurred because a control with id 'XXX' could not be located or a different control is assigned to the same ID after postback. If the ID is not assigned, explicitly set the ID property of controls that raise postback events to avoid this error.]

System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +988

System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3294

Solution

I forgot to assign id’s to the dynamically generated Image controls.It used to work fine even with no id’s. Error was very rare and sometimes unable to reproduce it.

I added unique IDs to each Image control when I created them and it solved the problem.

Friday 25 January 2013

Enabling Distributed Transaction Manager

 

.NET exception :

Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool.

You can resolve this by following the steps below

Control Panel – Administrative Tools – Component Services – My Computer properties – MSDTC tab – Security Configuration tab – Network DTC Access (checked) / Allow Remote Clients (checked) / Allow Inbound (checked) / Allow Outbound (checked) / Enable TIP Transactions (checked)

 

or

 

Control Panel – Administrative Tools – Component Services – My Computer – Local DTC Properties– Security Configuration tab – Network DTC Access (checked) / Allow Remote Clients (checked) / Allow Inbound (checked) / Allow Outbound (checked) / Enable TIP Transactions (checked)

image

image

imageimage

Friday 9 November 2012

The Controls collection cannot be modified because the control contains code blocks ((i.e. <%..%>)).

I am trying to add css file reference to the head section of the master page from code behind as follows.

// CSS

HtmlLink link = new HtmlLink();

link.Href = "../Styles/MyCSS.css";

link.Attributes.Add("rel", "stylesheet");

link.Attributes.Add("type", "text/css");

// Need this because we're in a master page

Control headControl = Page.Master.FindControl("head");

if (headControl != null)

{

headControl.Controls.Add(link); // Add css to header

}

But I got the below error at run time.

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

There are 2 solutions :

1. This link contains the actual solution :

http://www.dotnetboss.com/2010/09/27/the-controls-collection-cannot-be-modified-because-the-control-contains-code-blocks-i-e/

But I don’t know how to add data binding expressions from code behind.

2. Add this css file to the html body.

This worked for me.

Code now changed to:

// CSS

HtmlLink link = new HtmlLink();

link.Href = "../Styles/MyCSS.css";

link.Attributes.Add("rel", "stylesheet");

link.Attributes.Add("type", "text/css");

Page.Master.Controls.Add(link);

// Need this because we're in a master page

//Control headControl = Page.Master.FindControl("head");

//if(headControl != null)

//{

// headControl.Controls.Add(link); // Add css to header

//}

Friday 7 September 2012

Calling LoadLibraryEx on ISAPI filter “c:\windows\Microsoft.NET\Framework\v4.0.30319\aspnet_filter.dll” failed

I installed .Net 1.1 recently(I have .net 2,3.5 and 4 on my system previously) on my machine.

All of a sudden I am unable to access my applications from IIS. VS build in webservier is working fine. But IIS its giving the following error.

Calling LoadLibraryEx on ISAPI filter "C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_filter.dll" failed

image

In searching about this problem a lot of solutions pointed at using aspnet_regiis –r from the Framework64 directory, but that did not fix my problem.

Then I found this article which fixed my problem.

http://www.west-wind.com/weblog/posts/2011/Apr/04/Error-on-64-Bit-Install-of-IIS-LoadLibraryEx-failed-on-aspnetfilterdll

Even changing app pool to use 32 bit is not worked for me.

2nd option which requires changing isapi settings worked.

Enabling 32 bit code is a quick fix solution to this problem, but not an ideal one.

In this IIS trying to load a 32 bit DLL in a 64 bit install, especially even if the application pool is configured to not allow 32 bit code at all.

Go to Default Web Site (or any other root Web Site) and go to the ISAPI filter list:

image

Here is the list

image

Notice that there are 3 entries for ASP.NET 4.0 in this list. Only two of them however are specifically scoped to the specifically to 32 bit or 64 bit. As you can see the 64 bit filter correctly points at the Framework64 folder to load the dll, while both the 32 bit and the ‘generic’ entry point at the plain Framework 32 bit folder.

 

Go the Web Site root and use the Configuration Editor option in the Management Group.

image

image

Drill into System.webServer/isapiFilters

image

image

and then click on the Collection’s … button on the right. You should now see a display like this:

image

These entries correspond to these raw ApplicationHost.config entries(above diusplayed entries):

<filter name="ASP.Net_4.0" path="C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_filter.dll" enableCache="true" preCondition="runtimeVersionv4.0" />
<filter name="ASP.Net_4.0_64bit" path="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_filter.dll" enableCache="true" preCondition="runtimeVersionv4.0,bitness64" />
<filter name="ASP.Net_4.0_32bit" path="C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_filter.dll" enableCache="true" preCondition="runtimeVersionv4.0,bitness32" />

 

The key attribute we’re concerned with here is the preCondition and the bitness subvalue. Notice that the ‘generic’ version – which comes first in the filter list – has no bitness assigned to it, so it defaults to 32 bit and the 32 bit dll path. And this is where our problem comes from.

The simple solution to fix the startup problem is to remove the generic entry from this list here or in the filters list shown earlier and leave only the bitness specific versions active.

The preCondition attribute acts as a filter and as you can see here it filters the list by runtime version and bitness value. This is something to keep an eye out in general – if a bitness values are missing it’s easy to run into conflicts like this with any settings that are global and especially those that load modules and handlers and other executable code. On 64 bit systems it’s a good idea to explicitly set the bitness of all entries or remove the non-specific versions and add bit specific entries.

I just made enabled to false for the erred configuration.

This solves the problem.

aspnet_regiis –r from the Framework64 directory, did not fix this extra entry in the filters list – it adds the required 32 bit and 64 bit entries, but it doesn’t remove the errand un-bitness set entry.