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.

Thursday 9 August 2012

Useful SQL Server

Date Function :

1. Return day of the week

SELECT DATENAME(dw, GETDATE())

OR

SELECT DATENAME(weekday, GETDATE())

OR

SELECT DATEPART(dw,GETDATE()) --- RETURNS INTEGER LIKE 6 FOR FRIDAY.


i.e Sunday.Monday etc



http://msdn.microsoft.com/en-us/library/ms174395.aspx



Formatting Currency :



cast a money field in SQL Server 2005 to format it



SELECT ‘£' + convert(varchar,cast(Price as money),-1) as Price FROM Products



Price

£194,950.00

Tuesday 24 July 2012

Import CSV file into SQL Server

 

 

Importing data from csv file to SQL server db.

BULK INSERT TableName FROM 'csv file path' WITH(FIRSTROW = 2, MAXERRORS = 0, FIELDTERMINATOR = ',' )

(Inserts csv file data to specified table Name )

 

FIRSTROW = 2                – Start import from this row

MAXERRORS = 0              – max number of syntax errors allowed

FIELDTERMINATOR = ','     –Char that separates Fields

There are some other parameters available like KEEPIDENTITY , KEEPNULLS , LASTROW , ROWTERMINATOR  etc.

http://msdn.microsoft.com/en-us/library/ms188365(v=sql.90).aspx

 

Just remember that the BULK INSERT command requires an extremely high level of permissions [ADMINISTER BULK OPERATIONS, a server-level permission], which you will be unable to grant in any application you build. You won’t notice this if you use sa, but sa is disabled on SQL2008 ;)

However, if you are doing an import from .NET code then the System.Data.SqlClient.SqlBulkCopy class is great, and needs far fewer permissions. If only they would give us the equivalent of SqlBulkCopy for exports too …

Sample Data:

D:\FileStore\names.csv

Title,Forename,Surname
Mr,John,Smith
Mrs,Jane,Smith
Miss,Elizabeth,Smith
Mr,James,Smith
Mr,Mathew,Smith
Mrs,Catherine,Smith
Miss,Mary,Smith
Mr,David,Smith

 

My Query :

CREATE TABLE [#FakeNames] (   
      Title VARCHAR(20),     
      Forename VARCHAR(50),
      Surname VARCHAR(50)
    )
BULK INSERT #FakeNames FROM 'D:\FileStore\names.csv' WITH(FIRSTROW = 2, MAXERRORS = 0, FIELDTERMINATOR = ',' )

Cookies in JavaScript

http://www.thesitewizard.com/javascripts/cookies.shtml

How to Use Cookies in JavaScript

Cookies are bits of data that a browser stores in your visitor's computer. They are useful in that they allow you to store things like your visitor's preferences when they visit your site or other types of data specific to a particular user.

What Kinds of Data Can Be Stored in a Cookie?

A cookie is basically a string of text characters not longer than 4 KB. Cookies are set in name=value pairs, separated by semi-colons. For example, a cookie might be a string like the following:

"MyCookieName=myvalue; max-age==" + 60*60*24*30 + "; path=/; domain=example.com"

" MyCookieName " is the name of the cookie I want to use and set and contains the real data that I wish to set.

· max-age

Cookies have, by default, a lifespan of the current browser session. As soon as your visitor closes his browser, your cookie disappears. To make it last longer, you will need to set the max-age variable to contain the number of seconds you want the cookie to last.

For example, if you want your cookie to last 30 days, set it to 2,592,000. Actually instead of pre-calculating this and putting it into your script, you can have the JavaScript interpreter calculate it for you at run time.

· path

By default cookies are valid only for web pages in the directory of the current web page that stored them, as well as its descendants. That is, if a cookie is set by http://example.com/abc/webpage.html, it will be valid for http://example.com/abc/yet-another-page.html as well as http://example.com/abc/Sub-Folder/index.html, but not for http://example.com/index.html.

If you want the cookie to be valid in some other directory, say, http://example.com/special/, you will need to set the path variable to contain the value "/special". If you want the cookie to be valid everywhere on your site, set it to the root of your web directory, that is, "/".

· domain

Another special variable name that you may want to take note of is the domain variable. Cookies set in sub-domains like www.example.com will only be valid for that subdomain. If you want it to be valid for all sub-domains of example.com, you will need to set the domain to point to "example.com". The cookie will then be valid for "www.example.com", "blog.example.com", and whatever other subdomains that you may have.

Note that for security reasons, if your domain is example.com, browsers will not accept a cookie for a different domain, like google.com.

· secure

There's another variable that has special meaning: secure. This variable should not be assigned any value. Including it means that the cookie will only be sent if your visitor is visiting your website over a secure connection.

· expires

The expires variable is obsolete although still supported by today's browsers. Use the max-age variable instead, since it is easier to use. Be careful not to use "expires" as a variable name to store your data as well.

· No spaces, commas, semi-colons

Your cookie values cannot have any embedded whitespaces, commas or semi-colons. If you have any, they must be converted to its "encoded" equivalent. The easiest way to do this is to use the encodeURIComponent() function to encode it, and the decodeURIComponent() function to decode it when you read the cookie.

Expanding on my earlier example, if you want to set a "theme" variable to "blue theme", you can do it this way:

"Cookiename=" + encodeURIComponent("value") + "; max-age=" + 60*60*24*30 + "; path=/; domain=example.com"

· Cookie Limits

Although different browsers may implement different limits for cookies, the bare minimum that they are supposed to support is as follows:

    • Cookie length: 4 KB. The total length of your string, including all the variables with special meaning, should not be more than 4,096 characters.
    • Maximum number of cookies per web server: 20.
    • Total number of cookies supported by the browser: 300. This includes cookies stored by other websites.

How to Set a Cookie

Setting a cookie is extremely simple. Just assign the string you want for the cookie to the document.cookie property. For example, if I want to set the cookie given in my example above, I can simply include the following JavaScript code.

document.cookie =

"cookiename=" + encodeURIComponent("value") +

"; max-age=" + 60*60*24*30 +

"; path=/; domain=example.com" ;

How to Read a Cookie

Setting a cookie is great and all that, but a cookie is only useful if one can actually read what one has set previously.

To read a cookie, just read the string currently held in document.cookie. Since the string includes all the usual overhead for a cookie, like "max-age", "path" and "domain", you will need to parse the string to obtain the value you want. There are many ways to do this, such as splitting the string into separate tokens, using one of the substring search functions, or using regular expressions.

The following function allow you to easily get the cookie value you want by simply specifying the variable name.

function get_cookie ( cookie_name )

{

var cookie_string = document.cookie ;

if (cookie_string.length != 0) {

var cookie_value = cookie_string.match (

'(^|;)[\s]*' +

cookie_name +

'=([^;]*)' );

return decodeURIComponent ( cookie_value[2] ) ;

}

return '' ;

}

If get_cookie() cannot find the cookie, it will return an empty string. This may happen even if you have set a cookie, since the visitor may have deleted it, or alternatively, disabled cookie support in his/her browser.

How to Delete a Cookie

There are times when you may want to delete a cookie, such as when a visitor logs out of your site. To do this, set the max-age variable to 0 (zero) for the same cookie in the same path and domain.

 

 

Issues :

Setting cookie using JavaScript is working fine in Chrome and Firefox but IE deleting the cookies on exit even if expiry date is set to 100 years from now.

After researching a bit I came to know that it is not creating cookie with the expiry date as I send but just creating session cookies(without any expiry date and will be deleted once we close the browser).

I thought time format which i am using to set expiry date might not be acceptable to IE.

So I changed it to differed format(GMT format).

Also when I am trying to read cookies using normal array and split Firefox is not recognising my cookie for some reason.I have to use the substring method to get my cookie.

Check my code :

        function ReadCookie(cookieName) {
            var allcookies = document.cookie;
            // Get all the cookies pairs in an array
            cookiearray = allcookies.split(';');
            // Now take key value pair out of this array
            for (var i = 0; i < cookiearray.length; i++) {
                var value = '';
                var name = '';
                name = cookiearray[i].split('=')[0];
                value = cookiearray[i].split('=')[1];
                var searchFor = cookieName + "=";
                //alert("Key is : " + name + " and Value is : " + value);
                var start = document.cookie.indexOf(searchFor) + searchFor.length; //Bad coding style but i didn't find any other way at that time. Annoyed
                var end = document.cookie.indexOf(";", start);
                if (end == -1) {
                    end = document.cookie.length;
                }
                value = document.cookie.substring(start, end);
                //alert(cookieName == name);
                if (value == "true") {
                    //if (cookieName == name) { //Not working in Firefox Sad smile
                    return value;
                } else {
                }
            }
            return null;
        }
      

        $(document).ready(function () {

            if (ReadCookie("bReadCookiesInfo") != null) {
            } else {
                $('#divCookieInfo').fadeIn('slow', function () {
                });
                var expireDate = new Date()
                expireDate.setTime(new Date().getTime() + 60 * 60 * 24 * 365 * 100) //1000 because time is in milliseconds , 100 -NO OF YEARS

                setCookie("bReadCookiesInfo", true, expireDate, '');
            }

            });

        function setCookie(name, value, expirydate, domain) {
            document.cookie = name + "=" + value + ";expires=" + expirydate.toGMTString() + ";path=/;";
        }

Tuesday 17 July 2012

Random selection of Rows and update random record in a table

 

CREATE TABLE Table1
(
    Column1 INT IDENTITY(1,1) PRIMARY KEY,
    Column2 VARCHAR(20) NOT NULL,
    Column3 VARCHAR(50) NOT NULL,
    Column4 VARCHAR(50) NOT NULL
)

INSERT INTO Table1 VALUES('Mr','AAA','111')
INSERT INTO Table1 VALUES('Mrs','BBB','222')
INSERT INTO Table1 VALUES('Miss','CCC','333')
INSERT INTO Table1 VALUES('Mr','DDD','444')
INSERT INTO Table1 VALUES('Mrs','EEE','555')

CREATE TABLE Table2
(
    Col1 INT IDENTITY(1,1) PRIMARY KEY,
    Col2 VARCHAR(20) NOT NULL,
    Col3 VARCHAR(50) NOT NULL,
    Col4 VARCHAR(50) NOT NULL
)


INSERT INTO Table2 VALUES('','','')
INSERT INTO Table2 VALUES('','','')
INSERT INTO Table2 VALUES('','','')
INSERT INTO Table2 VALUES('','','')
   
DECLARE @Column1 INT   
DECLARE @Column2 VARCHAR(20)
DECLARE @Column3 VARCHAR(50)
DECLARE @Column4 VARCHAR(50)

SELECT TOP 1
    @Column1 = Column1 ,
    @Column2 = Column2 ,
    @Column3 = Column3 ,
    @Column4 = Column4
FROM
    Table1
ORDER BY NEWID()
    
UPDATE Table2
SET
    Col2 = @Column2 ,
    Col3 = @Column3 ,
    Col4 = @Column4       
FROM   
    Table2 T1
    INNER JOIN
        (
            SELECT TOP 1 Col1 FROM Table2 ORDER BY NEWID()
        ) T2 ON T2.Col1 = T1.Col1

Friday 18 May 2012

Using command line parameters with Remote Desktop Connection

 

Instead of starting Remote Desktop Connection from the Start menu, you can start it from the search box in this version of Windows, from the Run dialog box, or from a command line. With these methods, you can use additional command line parameters to control how Remote Desktop Connection looks or behaves.

To start Remote Desktop from the Run dialog box, follow these steps:

  1. Click the Start button Picture of the Start button, click All Programs, click Accessories, and then click Run.

  2. In the Open box, type mstsc.

  3. Type a space, followed by any additional parameters that you want to use.

The following table lists the parameters you can use.

Command line syntax for Remote Desktop Connection

Syntax

mstsc [<connection file>] [/v:<server[:port]>] [/admin] [/f[ullscreen]] [/w:<width>] [/h:<height>] [/public] | [/span] [/edit "connection file"] [/migrate] [/?]

Command line parameters for Remote Desktop Connection

Parameter
Description

/v:<server[:port]>

Specifies the remote computer you want to connect to.

/admin

Is used for administration of a terminal server. In this version of Remote Desktop Connection, if the Terminal Server role service is installed on the remote computer, running mstsc /admin will do the following (for the current connection only):

  • Disable Terminal Services client access licensing.

  • Disable time zone redirection.

  • Disable TS Session Broker redirection.

  • Disable TS EasyPrint.

/admin also does the following on connections toWindows Server 2008 with the Terminal Server role service installed:

  • Disables Plug and Play device redirection for this connection only.

  • Changes the remote session theme to Windows Classic View for this connection only.

To connect to a remote computer with the Terminal Server role service installed, follow these steps:

  1. Open the Command Prompt window by clicking the Startbutton Picture of the Start button, clicking All Programs, clicking Accessories, and then clicking Command Prompt.

  2. Type mstsc /v:server /admin.

/f

Starts Remote Desktop Connection in full-screen mode.

/w:<width>

Specifies the width of the Remote Desktop Connection window.

/h:<height>

Specifies the height of the Remote Desktop window.

/public

Runs Remote Desktop Connection in public mode.

/span

Matches the remote desktop width and height with the local virtual desktop, spanning across multiple monitors if necessary. To span across monitors, the monitors must all have the same height and be aligned side by side.

/edit "connection file"

Opens the specified .rdp connection file for editing.

/migrate

Migrates older connection files that were created with Client Connection Manager to new .rdp connection files.

/?

Lists these parameters.

http://windows.microsoft.com/en-us/windows-vista/Use-command-line-parameters-with-Remote-Desktop-Connection