Escape apostrophe in javascript and dynamic built scripts

The apostrophe in javascript is its string delimiter. To render the apostrophe on the response without errors it must be escaped using backslash \.

alert('John\'s name') will produce message box with text: John's name.

Using asp.net usually the scripts are built dynamically on server side before rendering the page. Remember that the backslash is also escape character in C# and you have to put two backslashes to build the javascript correctly:

Response.Write("alert('John\\'s name');");

FTP over SSL with IIS is not supported.

This is a common problem when you need more secure connection. Microsoft explains the features of their FTP server here:
http://support.microsoft.com/kb/283679

It is good to know that current FTP Service in IIS doesn't support Secure Sockets Layers (SSL). Of course that means your connection details and credentials to such service can be caught by Network listeners between you and the server. Therefore if you need secured connection you have to consider usage of Webdav over SSL or another FTP server which supports SSL.

A suggestion for free and easy to set up server is FileZilla FTP Server for Windows.

Edit shortcuts in Places bar in Save dialog / Open dialog in Windows

It's absolutely boring to navigate to your most often used folder in windows save or open dialogs. Th purpose of Places bar is to help you to do this faster. The Places bar locations can be edited via Group Policy editor in Windows XP Pro and Vista. Use the following way:

1. Open gpedit.msc (Start->Run)
2. Navigate to User Configuration -> Administrative Templates -> Windows Components -> Windows Explorer -> Common Open File Dialog
3. Open "Items displayed in Places bar" and write down the locations you want with their paths. Symbolic names are also allowed like Desktop.

SQL: How to check for existing contraint

Just an example how to get it form the database information schema:

IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA='dbo' AND CONSTRAINT_NAME='IX_Constraint' AND TABLE_NAME='TableName')
BEGIN
ALTER TABLE [dbo].[TableName] WITH CHECK ADD CONSTRAINT ..... /* constraints */
END

How to set column width in a CheckBoxList in an ASP.NET page

Maybe this is common problem since CheckBoxList control doesn't have set of parameters for obtaining column width and row height. But we always can use CSS for styling this control getting in mind he is rendered as html table or floated div tag.


<asp:checkboxlist runat="server" id="chkBoxList1" cssclass="chkBoxList" repeatcolumns="4" repeatlayout="Table">
</asp:checkboxlist>


Here we explicitly define the layout to be rendered as table (which is by default) and also need to define the css class "chkBoxList" in current page or web site theme.


<style>
.chkBoxList tr
{
height:24px;
}

.chkBoxList td
{
width:120px; /* or percent value: 25% */
}
</style>

Of course any other css styles can be attached here.

Only ASP.NET :)

SQL Stored Procedures - getting return value

Starting directly with example:

CREATE PROCEDURE ProcessValue
(
@value int,
@returnValue int OUTPUT
)
AS
BEGIN
/* do calculation and processing and assign the result value to output parameter */
SET @returnValue = value + 5*value

END

The following calling of the procedure shows how to get output parameter.
declare @result int
EXEC ProcessValue 15, @result OUTPUT


Of course this example is pretty simple - only for showing how to use. For such usage the SQL scalar-valued functions are better way.

Way for localizing MessageBox in Windows Forms

Very good article in code project, where you can see how the buttons of MessageBox can use custom text labels. The natural language of .NET platform will be overridden and only your labels will be shown.

http://www.codeproject.com/KB/miscctrl/Localizing_MessageBox.aspx

Actually if you use MessageBoxOptions in the parameters of MessageBox.Show(..) only the original labels are shown. But I don't think this is big problem.

How to map an extension for server side scripting - html to php

Sometimes we need including some functionality or server includes into static web files - html. But changing the extension can lose current search engine index and rank. That is why leaving the fiels with the same name is the better way. Easy html files can be mapped to be parsed as php file.

IIS 7.0:
1. Open IIS Management Console
2. Open Web-site node
3. Open Handler Mapping
4. Add the extension as request path (*.html)
5. Set the handler application/library: something like C:\Program Files\PHP\php5isapi.dll
6. Name it and click OK

Apache:
Just add the following row in the .htaccess file:
AddType application/x-httpd-php .html

SQL Server 2005 - Out Of Memory exceptions connected to its RAM usage

After the allocated RAM for SQL Server exceeds the System memory unexpected behavior of the server is present.

Here is a quick guide for configuring Sql server.

http://www.mattec.com/service/appnotes/820-0019.pdf

And remember: Never allocate less then 1 GB of RAM to SQL Server :)

VB.NET: General Exception Handling in Windows Forms

VB.NET

My.Application.UnhandledException Event is the way for handling all unhandled exceptions in an windows forms application. The application raises this event when it encounters unhandled exception.
For using the event editing ApplicationEvents.vb file is needed. By default ApplicationEvents.vb is hidden. For openning (unhiding) it use Project Properties -> Application tab -> View Appication Events.
Then the handler can be added/edited as in the example below:

Private Sub MyApplication_UnhandledException( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs _
) Handles Me.UnhandledException

Try
//write log, which is nessted in Application Data folder
My.Application.Log.WriteException( _
e.Exception, _
TraceEventType.Critical, _
"Unhandled Exception!")

//check up if the Event folder exists.
//if not - create new one
If Not EventLog.SourceExists("My software") Then
EventLog.CreateEventSource("My software", "My Software")
End If

//write event log, can be seen by Event Viewer
EventLog.WriteEntry("My software", _
e.Exception.ToString(), _
EventLogEntryType.Error)
Catch ex As Exception

End Try

// code for notifying the user with user friendly message
...................

//set the default application action (closing) not to be performed.
e.ExitApplication = False
End Sub
And from now on all unhandled exception in the application will be stored as exception information and stack trace in the application log file or in the Windows Event log and the user will receive friendly message.


C#

Of course most of my posts give examples with VB and C# when they are different. Now I will give up this pleasure to R. Newman with his great post "Top-level Exception Handling in Windows Forms Applications"

How to check the type of an object or control using VB.NET or C#

The VB.NET check up is:

If (TypeOf sender Is TextBox)Then
Dim txt As TextBox= DirectCast(sender, TextBox)
End If



And the C# code:

if (sender Is TextBox){
TextBox txt=(TextBox)sender;
}

Error reporting in PHP run on IIS

The PHP error reporting is controlled either by the php.ini file as a global setting or programatically, or using .htaccess.

The error reporting in php.ini is defined in "Error handling and logging" section.
  • error_reporting = E_ALL & ~E_NOTICE - shows all errors except E_NOTICE errors. E_NOTICE are possible errors which can occur even during normal program workflow - something like Microsoft's warnings.
  • display_errors = On
  • display_startup_errors = On
Programmatically the same settings are applied for current site like this:
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL & ~E_NOTICE);

In .htaccess the flags must be changed in the following way:
php_flag display_errors 1
php_flag display_startup_errors 1


Php error_reproting help -> http://php.net/error_reporting

URL Encoding - reserved and unsafe characters

RFC 1738: Uniform Resource Locators (URL) specification is described in the following page. Also simple convertor is included.

http://www.blooberry.com/indexdot/html/topics/urlencoding.htm


Server.URLEncode(url)
applies these rules to the url. During getting an url parameter from the query string the value will be automatically decoded.

Javascript trace log

Simple and useful tool can be found here:

http://v2.easy-designs.net/code/jsTrace/


Using it you can get rid of the alert messages while debug applications.

How to excute string with javascript

Simply use eval().

eval('peformAction()') will execute

Adding a relationship between DataTables

A DataTable can be related to another DataTable in the same DataSet using DataRelation object. Using DataRelation the navigation between DataTable (foreign key connection) becomes very easy.

An example for using Child Relation is located here:
http://msdn.microsoft.com/en-us/library/system.data.datatable.childrelations.aspx

Here is an example for using Parent Relation:

We have two DataTables: DataTableOrder (OrderId is foreign key to DataTableOrderDetails) and DataTableOrderDetails (Id is primary key)

//create dataset
DataSet dataSet = new DataSet();

//add existing tables to the DataSet
dataSet.Tables.Add(DataTableOrder );
dataSet.Tables.Add(DataTableOrderDetails);

// create relation between both tables
dataSet.Relations.Add(
dataSet.Tables[1].Columns["Id"],
dataSet.Tables[0].Columns["OrderId"]);

foreach (DataRow row in DataTableOrder .Rows)
{
//get parent rows using relation - all order details for current order
//use GetParentRows for relations 1 to many
DataRow dr=row.GetParentRow(dtm.ParentRelations[0]);
//check if there is a parent row
if(dr!=null){
Response.Write(row["OrderName"].ToString() +"->"+ dr["OrderDetails"].ToString() +"
")
}
}

Good working free CAPTCHA control for asp.net


CAPTCHA stands for "Completely Automated Public Turing test to tell Computers and Humans Apart" and means software peace which makes user input challenges which are easy for solving by humans and difficult for machines. The purpose is to avoid spam or hackers attacks which can harm your data or make unpredictable responses.

This post will show you one very good CAPTCHA control, which is tested by me and works fine, even with ajax. It is easy for use and will save you time to develop such control.

Thanks for Mondor software.
http://www.mondor.org/captcha.aspx

Why don't you have .NET 3.5 as a selectable framework in IIS

The reason is that the .NET Framework 3.5 delivers not whole new runtime machine, but only library extension of .NET 2.0. In other words there are no new CLR or new language compilers. But there are new available libraries and new versions of C# (3.0) and VB (9)

.NET Framework 2.0 includes the CLR, Winforms, Asp.NET and web services.

.NET Framework 3.0 includes in addition libries for WCF (Windows Communication Foundation), WPF (Windows Presentation Foundation) and Windows Workflow (WF).

.NET Framework 3.0 includes in addition libraries for AJAX, LINQ and REST

Finally you will see there is no problem with your IIS. You've just received some new additional and really good features for easier programming.

Gmail consider the mail as SPAM. How to avoid that?

Obviously Gmail uses Sender-ID and DKIM to verify every email. That is why you need to modify DNS records for your domain using txt record. Here is a tutorial how to do that openspf.org.
You can build your txt records using the wizard and add them. You need something like:
record for domain.com in txt: v=spf1 a mx ~all
record for the mail server mail.domain.com in txt: v=spf1 a -all

Very good way to see how your html table will look like

http://www.somacon.com/p141.php

Interactive tool for creating good looking html table using css. Make the table you want and copy and paste the generated css classes.

How to obtain current SQL Server version using sql query

SELECT SERVERPROPERTY('productversion') As Version, SERVERPROPERTY ('edition') As Edition, SERVERPROPERTY ('productlevel') As Updates

The first columns shows current version as number, the second one is the edition (standard, express etc.) and the third one shows which version level the server belongs to (SP1, SP2 etc.)

Trick to start web application with another SQL Server database

The following exception is thrown when you try to use one application with the another database. The problem is caused by asp.net membership provider which cannot recognize its schema.

The 'System.Web.Security.SqlMembershipProvider' requires a database schema compatible with schema version '1'. However, the current database schema is not compatible with this version. You may need to either install a compatible schema with aspnet_reqsql.exe (available in the framework installation directory), or upgrade the provider to a newer version.

First of all be sure the aspnet membership provider is registered on that database using aspnet_regsql.exe.

Then the solution is: taking the web application offline and then online using Web Site Administration Tool. That makes some changes in web.config in the pages tag and globalization if needed. Then you can go!

SQL pagination: get fixed number of rows page by page

See the following examples:

SELECT * FROM
(SELECT ROW_NUMBER() OVER (ORDER BY Id) AS [SortNum], * FROM MyTable) As Tmp
WHERE SortNum Between 11 AND 20

or

WITH Tmp As
SELECT ROW_NUMBER() OVER (ORDER BY Id) AS [SortNum], * FROM MyTable)
SELECT * FROM Tmp
WHERE SortNum Between @StartRow AND @StartRow+@NumberOfRows-1


or

WITH Tmp As
SELECT ROW_NUMBER() OVER (ORDER BY Id) AS [SortNum], * FROM MyTable)
SELECT * FROM Tmp
WHERE SortNum Between (@page-1)*10+1 AND (@page)*10


The first one gives the second page of 10 records.
The second example shows the usage of WITH keyword and getting rows passed as parameter of stored procedure.
The third one shows you how to use 1 passed parameter as number of the desired page.

How to set your master page by the nested page

The PreInit Page event n the nested page can be used for setting some Master page parameters.

protected void Page_PreInit(object sender, EventArgs e)
{
(this.Master as MasterType).Property = value;
}

Then the Master page will be loaded and rendered using these settings.
Master is the reference to the Master page. MasterType is the type of master page used.
Property is the public variable which must be set before loading page.

Using Page_PreInit the Master page can be set dynamically.

Sql Date Manipulation

DATEPART (datepart, date) returns the desired part of the date specified by datepart parameter: year,
quarter, month, dayofyear, day, week, weekday, hour, minute, second, millisecond.

Example: DATEPART(month, GETDATE()) returns current month number

DAY(date), MONTH(date), YEAR(date) return respectively the number of the day, month or year of the passed date.

To add or subtract date parts from a given date use this function:
DATEADD (datepart , number, date)
where datepart is one of the following parameter (datepart): year,
quarter, month, dayofyear, day, week, weekday, hour, minute, second, millisecond.

Example: DATEADD(day, -7, GETDATE()) return the date week ago.

DATEDIFF (datepart, startdate, enddate) gives you the difference between two dates in desired date part (see DATEPART date parts above). Startdate should be date before end date. Otherwise a negative number will be returned.

Example: DATEADD(day, DATEADD(day, -7, GETDATE()), GETDATE()) return 7 days.

Ajax Error Message:The state information is invalid for this page and might be corrupted

The message is shown when a page with partial postback regions (update panels) is refreshed by F5 or browser's refresh button and then a new partial postback request is performed. In this case the information stored in the page has been changed and causes not to be possible to perform partial postback. For pages like these the page parameter EnableEventValidation must be set to false:

<%@ Page EnableEventValidation="false" ....

Another case is described here: http://support.microsoft.com/kb/323744

How to execute string (custom built sql query ) in a stored procedure

sp_executesql executes string in a stored procedure. It is used in more complex queries which we need to build concatenating strings. The string is run as a batch. The following example gets the TOP records from a table matching predefined conditions.

CREATE PROCEDURE [GetTOPRecords]
@count varchar(6),
@conditions nvarchar(300)
AS
BEGIN

DECLARE @SQL nvarchar(1000)

SET
@SQL='SELECT
TOP '+ @count + ' * FROM RecordsTable
WHERE ' + @conditions

EXEC sp_executesql @SQL

END


The @count and @conditions are passed as parameters. The execution string is built run-time and executed. If you don't need any conditions here just pass the string ' 1=1 ' as @conditions.

How to build unsafe C# code with Visual Studio

Unsafe code may only appear if compiling with /unsafe

This appears as an error when you try to compile assembly which contains unsafe code in release mode.
You must change the compiler options using project's Properties page -> Build -> and check Allow Unsafe Code. Consider if you want to use unsafe code :)))

Javascript: How to check if the variable is a number?

There are some ways for doing this but I think the following is the most easiest and convenient for use:

if (! isNaN(variable)) {
//code here
}


isNaN comes from is Not A Number and can be used for understanding if the variable is a number.

How to maintain the view state of dynamically added control in an asp.net page

First of all you must read these articles:

The viewstate of a dynamically added control can be saved for maintaining the state of the control after postback.
This can be achieved by adding the controls before the Load Viewstate stage (see the page stages in the articles above). Therefore the viewstate information ( control value) from the request will be applied to already added controls as they are defined already in the page.
The right place of adding dynamic controls is Page_Init. Use Page_Init also for defining dynamically master pages and themes.

Understanding AutoEventWireup attribute in Asp.net page. Event handlers.

The AutoEventWireup attribute indicates if the page events are auto-wired up. If the attribute is set to true .Net framework searches automatically for methods which names are created in the way Page_xxxxx (Page_Load, Page_Init etc.) and connects them to the events. Otherwise the developer or the environment must do that using delegates:

this.Load += new System.EventHandler(this.Page_Load);

for all handled page events. Setting AutoEventWireup to false is the better way because of the performance -> the framework uses only the methods with code!

The attribute can be set on several places: in machine.config, web.config and for every page.

Note:
The note is not connected directly to the page events, but to events of postback controls like button, linkbutton etc.
In VB.NET the event handlers can be attached to the events using the keyword "Handles".

Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton1.Click

This method will handle the event Click and will work like adding the attribute
OnClick="LinkButton1_Click" to the LinkButton tag. But NEVER USE both of the ways at the same because this will invoke the method twice!!
Consider using keyword "Handles" OR OnEvent="", but never use them together.

How to covert System.Drawing.Color to a HTML/CSS color value

The System.Drawing.Color represenation of the color including the alpha color element:
alpha, red, green, blue.
The process is simple - convert the decimal color representation to a hexadecimal, then remove the alpha hexadecimal value from the string and concatenate to '#'.

Dim HTMLColor As String = Hex(color.ToArgb())
HTMLColor = "#" + HTMLColor.Substring(2)

where "color" is an instance of System.Drawing.Color

There is a difference between VB.NET and C# in getting the hexadecimal value as string. The C# fans can use the folloing code:

string HTMLColor = color.ToArgb().ToString("X8");
HTMLColor = "#" + HTMLColor.Substring(2);


The opposite process can be accomplished by ColorTranslator' services:
Dim color As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#e5e5e5")

Javascript string functions

Let's see how to use replace() function for replacing string with another one. The specialty here is the usage of regular expressions to replace the string if it occurs more than once in the source string.

replace('aa','a'); is gonna replace only the first occurrence of the 'aa'.
replace(/aa/g, 'a') will replace all occurrences of the 'aa' string.
replace(/A/i, 'b') will replace the occurrences of 'A' or 'a' with 'b' - case insensitive.

Very common problems are the special character replacement. These characters should be escaped using \.

replace(/\./g, '') will replace all occurrences . with an empty ('') string.

Unicode and hosted PHP

To make apache to work with unicode you must add into .htaccess the following:

php_value default_charset utf-8
AddDefaultCharset utf-8

.htaaccess geve you the ability to change PHP settings without changing php.ini

How to get the whole url on the page in PHP

Here is a usefull function for getting current url:

function GetCurrentURL() {
$url = '';

if ($_SERVER["HTTPS"] == "on")
{
$url .= "https://";
}
else
{
$url .= "http://";
}
if ($_SERVER["SERVER_PORT"] != "80") {
$url .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$url .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $url;
}

Get UrlRewritingNet to work with IIS 7.0

There is a well known problem using url rewriting functionality with UrlRewritingNet and IIS 7. The problem can be solved by setting the pipeline mode of the application pool to be in classic mode. Looking forward for the next version :).
Actually the url rewriting functionality can be achieved much easier with IIS 7.

AJAX: Timeout problem by asyncronous postback

The most common cause of this problem is the time of asyncronous response. It occur when the response takes more than 90 seconds. First of all be sure that there is no client script in the update panel. Use

ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "tmp", "<script type='text/javascript'></script>", False)

to register such scripts during loading page.

If the reason is long calculations on the srever you can change the asyncronous timeout in the ScriptManager tag.

<asp:ScriptManager ID="ScriptManager1" AsyncPostBackTimeOut="3600" runat="server" />

This makes the response to be valid an hour.

How to sum values in Excel only from visible cells

There is a good article in microsoft support site for this problem and the example works fine.

How to use a VBA Macro to Sum Only Visible Cells

see also how to create user defined functions (UDF)
in Excel

Creating User Defined Function in Excel (UDF)

You have to use VBA for making User Defined Function in Excel (UDF).
Click on Developers tab in the ribbon (Excel 2007) then click on Visual Basic or use Alt+F11.
Then insert a new module by Insert->Module and write your function there.
The functions will be inlcuded Insert Function dialog box in "User Defined" category.

To use the functions in another excel documents you must save them in your own add-in by saving the file as add-in file .xla or .xlam for Excel 2007. Then load the add-in by Start->Excel Options->Add-ins->Go.

How to enable VBA on Excel 2007 (Microsoft Office 2007)

The developer's functions of excel and VBA are disabled by default. They can be unlocked using Start->Excel Options window. Check "Show developers tab in the Ribbon" in Popular section. After clicking OK the developers tab is shown at the last place in the ribbon.
Another important thing is the saving xls documetns with recorded macros or inlcuded VBA scripts. You must save the file by Save As dialog box as an Excel Macro-Enabled Workbook with extension .xlsm .

Error rendering a custom control

Maybe this is a little MS Visual Studio bug. It is connected to the control registering in the page in case of using a control defined in App_Code folder, not in another assembly. The exception thrown while opening design view of the page is:

Error Rendering Control - [control] An unhandled exception has occurred. There was an error parsing the theme. The assembly attribute cannot be an empty string.

So the VS environment doesn't recognize the control defined in the App_Code. Therefore the control regitration must inlcude the assembly name - "App_Code"

<%@ Register TagPrefix="my" Namespace="MyControls" assembly="App_Code" %>

or

<add tagPrefix="my" namespace="MyControls" assembly="App_Code" />
in web.config - pages/controls section

SQL Server Express permissions

Fix for exceptions like these:
"CREATE DATABASE permission denied in database 'master'",
"EXECUTE permission denied on object "
"SELECT permission denied on object"

Asp.NET uses the NETWORK SERVICE account (for Windows Server 2003) and ASPNET user for Windows XP. If we use windows authetincation for using sql express we need to add these users as sql server logins:
SQL Server manager -> Security -> Logins -> add "NT AUTHORITY\NETWORK SERVICE" or ASPNET
Then click on the properties menu of the login and make the login dbcreator. This will fix the first of the exceptions above. Then with User Mapping setting we can add permissions explicitly to the desired database -> dbowner gives all needed permission.

How to get Profile instance out of asp.net page,

The way of getting Profile instance from a page context is Profile.GetProfile(). But how to do this when you need to get it from App_Code for instance. Here is the way:

MembershipUser mUser = Membership.GetUser(UserId);
ProfileCommon prof = (ProfileCommon)System.Web.Profile.ProfileBase.Create(mUser.UserName);

the object "prof" has all profile fields as in a page.

How to set page/script timeout on an asp.net page

The solution is pretty simple. Use Server.ScriptTimeout to set the timeout for the script in a page. The value is measured in seconds.

Server.ScriptTimeout = 3600

Use this in Page_Load event. The example makes the timeout to be an hour.

NOTE: using compilation debug="true" will ignore script timeout and it won't work. Make sure the debug value is false on the release version of web.config

FormsAuthentication.Authenticate vs Membership.ValidateUser

FormsAuthentication.Authenticate can be used with clear passwods to check user authentication:
if(FormsAuthentication.Authenticate(Username.Text, Password.Text))
{
FormsAuthentication.RedirectFromLoginPage(Username.Text, false);
}

This doesn't work if the password format is not clear. Asp.NET membership provider offers you Clear, MD5 or SHA1 represented passwords.
In case of using MD5 or SHA1 (specified in web.config, SHA1 is default for hashed passwords) the checking for user credentials should be done by Membership.ValidateUser which delivers the provider model for user authentication.

if( Membership.ValidateUser(curentUserName, pwd)){
FormsAuthentication.RedirectFromLoginPage(Username.Text, chkPersistent.Cheked);
}

The other things of authentication process can be left to the Asp.Net provider.

See also for web.config: authentication and authorization, machine key generation, password format, password salt ...

How to use SQL Express database for more than one application

Somethimes we need to use one database for more than one application, web, desktop or service.
The only thing to do is to get rid of the generation of a new user instance by the connection string in web.config. Assure that User Instance=False in the connection string and try again.