Time can make us forget some memories but there are some memories make the life sweeter.
Tuesday, August 25, 2009
Saturday, August 22, 2009
Enable SQL Broker
The proper syntax for the alter database statement is:
ALTER DATABASE OperationsManager SET ENABLE_BROKER WITH ROLLBACK AFTER 5
The options after the "WITH" also include NO_WAIT & ROLLBACK IMMEDIATE
Providing for the New Data Base
ALTER DATABASE DatbaseName SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE OperationsManager SET ENABLE_BROKER WITH ROLLBACK AFTER 5
The options after the "WITH" also include NO_WAIT & ROLLBACK IMMEDIATE
Providing for the New Data Base
ALTER DATABASE DatbaseName SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
Tuesday, August 11, 2009
Deleting script data from Data Base
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp_Delete_SpamCode]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @tablename nvarchar(20)
declare @schema_name nvarchar(20)
declare @column_name nvarchar(20)
declare @strQ nvarchar(1000)
declare testcursor cursor for
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
open testcursor
FETCH NEXT FROM testcursor INTO @tablename,@schema_name,@column_name
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
set @strQ= 'update '+@tablename+' set '+@column_name+'=SUBSTRING('+@column_name+',0,CHARINDEX(''<'','+@column_name+'))
WHERE CHARINDEX(''<'','+@column_name+')>0 AND CHARINDEX(''>'','+@column_name+')>0'
print @strQ
EXECUTE(@strQ)
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH;
FETCH NEXT FROM testcursor INTO @tablename,@schema_name,@column_name
END
CLOSE testcursor
DEALLOCATE testcursor
END
--exec [sp_Delete_SpamCode]
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp_Delete_SpamCode]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @tablename nvarchar(20)
declare @schema_name nvarchar(20)
declare @column_name nvarchar(20)
declare @strQ nvarchar(1000)
declare testcursor cursor for
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
open testcursor
FETCH NEXT FROM testcursor INTO @tablename,@schema_name,@column_name
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
set @strQ= 'update '+@tablename+' set '+@column_name+'=SUBSTRING('+@column_name+',0,CHARINDEX(''<'','+@column_name+'))
WHERE CHARINDEX(''<'','+@column_name+')>0 AND CHARINDEX(''>'','+@column_name+')>0'
print @strQ
EXECUTE(@strQ)
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH;
FETCH NEXT FROM testcursor INTO @tablename,@schema_name,@column_name
END
CLOSE testcursor
DEALLOCATE testcursor
END
--exec [sp_Delete_SpamCode]
Tuesday, March 31, 2009
Setting up SQL Session State Server
There are several reasons why you might want to setup the SQL session server. The first one is, on a shared server the ASP.NET worker process often recycles. This can cause you to lose session variables and frequently even if the session has not expired. The other reason you might want to install a session server is because sessions consumer memory. By using a session server, you free memory for your application.
Unfortunately, the default scripts that Microsoft gives you require your ability to install a SQL job. Something most hosting companies, including mywinhosting, will not allow. However, with the other hosting companies all to tell you is how to modify the default script so that will work in a shared hosting environment.
The first thing will need to do is generate the default script. You can do this by running an executable in C:\Windows\Microsoft.NET\Framework\v2.0.50727 called aspnet_regsql.exe passing in the parameters:
-d [databaseName]
-sstype c
-sqlexportonly [filename]
-ssadd
for syntax check http://msdn.microsoft.com/en-us/library/ms229862(VS.80).aspx
For example, if your database is userName_DotNetNuke, you might run aspnet_regsql like this from the command line:
Aspnet_regsql -d userName_DotNetNuke -sstype c -sqlexportonly c:\sqlstate.sql -ssadd
Which will place the sql script to create the sql session tables and stored procs in your database named userName_DotNetNuke in the root of the C drive in a file named "sqlstate.sql"
Next, load up either SQL Enterprise Manager, if you have it, or SQL Server Management Studio Express. You can get SQL Server Management Studio Express from Microsoft as a free download at: http://www.microsoft.com/downloads/details.aspx?familyid=C243A5AE-4BD1-4E3D-94B8-5A0F62BF7796&displaylang=en and use your sql connection information to connect to your database at MyWinHosting.com using TCP/IP. Next, load up the sqlstate.sql file. The remainder of the instructions will assume you are using SQL Server Management Studio Express.
The first thing we need to modify in the script is the fact that it is trying to create the database. Since you can't do that, and presumably your database is already created, you need to delete these lines from the sql script, located roughly at line 34 (at least it is in the one I generated)
USE master
GO
/* Create and populate the session state database */
IF DB_ID(N'username_dotnetnuke') IS NULL BEGIN
DECLARE @cmd nvarchar(500)
SET @cmd = N'CREATE DATABASE [username_dotnetnuke]'
EXEC(@cmd)
END
You'll also need to delete the lines immediately following this that remove the job if it exist. It doesn't exist and you couldn't remove it if it did. And since the tables have never been created before, you might as well delete the lines that delete the existing tables if they exist. To make this easy. Do a search for the next "Use" statement where it uses your database name and delete everything from there on up. The remaining lines that should be deleted will look something like this:
DECLARE @jobname nvarchar(200)
SET @jobname = N'username_dotnetnuke' '_Job_DeleteExpiredSessions'
-- Delete the [local] job
-- We expected to get an error if the job doesn't exist.
PRINT 'If the job does not exist, an error from msdb.dbo.sp_delete_job is expected.'
EXECUTE msdb.dbo.sp_delete_job @job_name = @jobname
GO
DECLARE @sstype nvarchar(128)
SET @sstype = N'sstype_custom'
IF UPPER(@sstype) = 'SSTYPE_TEMP' AND OBJECT_ID(N'dbo.ASPState_Startup', 'P') IS NOT NULL BEGIN
DROP PROCEDURE dbo.ASPState_Startup
END
USE [username_dotnetnuke]
GO
IF OBJECT_ID(N'dbo.ASPStateTempSessions','U') IS NOT NULL BEGIN
DROP TABLE dbo.ASPStateTempSessions
END
IF OBJECT_ID(N'dbo.ASPStateTempApplications','U') IS NOT NULL BEGIN
DROP TABLE dbo.ASPStateTempApplications
END
The next thing you'll want to do is to delete the script that creates the job to delete expired sessions. You can find this at the bottom of the script. The code you want to remove, looks something like this:
BEGIN TRANSACTION
DECLARE @JobID BINARY(16)
DECLARE @ReturnCode int
DECLARE @nameT nchar(200)
SELECT @ReturnCode = 0
-- Add the job
SET @nameT = N'username_dotnetnuke' '_Job_DeleteExpiredSessions'
EXECUTE @ReturnCode = msdb.dbo.sp_add_job
@job_id = @JobID OUTPUT,
@job_name = @nameT,
@owner_login_name = NULL,
@description = N'Deletes expired sessions from the session state database.',
@category_name = N'[Uncategorized (Local)]',
@enabled = 1,
@notify_level_email = 0,
@notify_level_page = 0,
@notify_level_netsend = 0,
@notify_level_eventlog = 0,
@delete_level= 0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
-- Add the job steps
SET @nameT = N'username_dotnetnuke' '_JobStep_DeleteExpiredSessions'
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobstep
@job_id = @JobID,
@step_id = 1,
@step_name = @nameT,
@command = N'EXECUTE DeleteExpiredSessions',
@database_name = N'username_dotnetnuke',
@server = N'',
@subsystem = N'TSQL',
@cmdexec_success_code = 0,
@flags = 0,
@retry_attempts = 0,
@retry_interval = 1,
@output_file_name = N'',
@on_success_step_id = 0,
@on_success_action = 1,
@on_fail_step_id = 0,
@on_fail_action = 2
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXECUTE @ReturnCode = msdb.dbo.sp_update_job @job_id = @JobID, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
-- Add the job schedules
SET @nameT = N'username_dotnetnuke' '_JobSchedule_DeleteExpiredSessions'
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobschedule
@job_id = @JobID,
@name = @nameT,
@enabled = 1,
@freq_type = 4,
@active_start_date = 20001016,
@active_start_time = 0,
@freq_interval = 1,
@freq_subday_type = 4,
@freq_subday_interval = 1,
@freq_relative_interval = 0,
@freq_recurrence_factor = 0,
@active_end_date = 99991231,
@active_end_time = 235959
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
-- Add the Target Servers
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @JobID, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:
GO
The last thing you'll need to do is to provide a way to delete the expired session variables. The job we deleted normally does that, but since we don't have that job anymore, we obviously need another way. So do a search for the stored procedure name TempGetAppID and insert the following line as the first executable line:
EXECUTE DeleteExpiredSessions
The resulting script should look like:
DECLARE @cmd nchar(4000)
SET @cmd = N'
CREATE PROCEDURE dbo.TempGetAppID
@appName tAppName,
@appId int OUTPUT
AS
Exec [dbo].[DeleteExpiredSessions]
SET @appName = LOWER(@appName)
SET @appId = NULL
SELECT @appId = AppId
FROM [username_dotnetnuke].dbo.ASPStateTempApplications
WHERE AppName = @appName
IF @appId IS NULL BEGIN
BEGIN TRAN
SELECT @appId = AppId
FROM [username_dotnetnuke].dbo.ASPStateTempApplications WITH (TABLOCKX)
WHERE AppName = @appName
IF @appId IS NULL
BEGIN
EXEC GetHashCode @appName, @appId OUTPUT
INSERT [username_dotnetnuke].dbo.ASPStateTempApplications
VALUES
(@appId, @appName)
IF @@ERROR = 2627
BEGIN
DECLARE @dupApp tAppName
SELECT @dupApp = RTRIM(AppName)
FROM [username_dotnetnuke].dbo.ASPStateTempApplications
WHERE AppId = @appId
RAISERROR(''SQL session state fatal error: hash-code collision between applications ''''%s'''' and ''''%s''''. Please rename the 1st application to resolve the problem.'',
18, 1, @appName, @dupApp)
END
END
COMMIT
END
RETURN 0'
EXEC(@cmd)
GO
This should delete expired sessions every time session data is requested. This modification should work for most installations. If you happen to get a lot of traffic, you might want to modify the DeleteExpiredSessions procedure so that it is a bit more efficient. There are several modifications available on the web and googling for DeleteExpiredSession along with the word "asp.net" should turn up several suggestions.
Next, you'll want to change or add the session state elements in your web.config file. It should look something like the following:
mode="SQLServer"
allowCustomSqlDatabase="true"
sqlConnectionString="Server=yourServer; Database=yourDatabase; uid=userName_xyz; pwd=Abc123;"
cookieless="false"
timeout="20"
/>
Be sure to include the allowCustomSqlDatabase attribute or it will not work.
Unfortunately, the default scripts that Microsoft gives you require your ability to install a SQL job. Something most hosting companies, including mywinhosting, will not allow. However, with the other hosting companies all to tell you is how to modify the default script so that will work in a shared hosting environment.
The first thing will need to do is generate the default script. You can do this by running an executable in C:\Windows\Microsoft.NET\Framework\v2.0.50727 called aspnet_regsql.exe passing in the parameters:
-d [databaseName]
-sstype c
-sqlexportonly [filename]
-ssadd
for syntax check http://msdn.microsoft.com/en-us/library/ms229862(VS.80).aspx
For example, if your database is userName_DotNetNuke, you might run aspnet_regsql like this from the command line:
Aspnet_regsql -d userName_DotNetNuke -sstype c -sqlexportonly c:\sqlstate.sql -ssadd
Which will place the sql script to create the sql session tables and stored procs in your database named userName_DotNetNuke in the root of the C drive in a file named "sqlstate.sql"
Next, load up either SQL Enterprise Manager, if you have it, or SQL Server Management Studio Express. You can get SQL Server Management Studio Express from Microsoft as a free download at: http://www.microsoft.com/downloads/details.aspx?familyid=C243A5AE-4BD1-4E3D-94B8-5A0F62BF7796&displaylang=en and use your sql connection information to connect to your database at MyWinHosting.com using TCP/IP. Next, load up the sqlstate.sql file. The remainder of the instructions will assume you are using SQL Server Management Studio Express.
The first thing we need to modify in the script is the fact that it is trying to create the database. Since you can't do that, and presumably your database is already created, you need to delete these lines from the sql script, located roughly at line 34 (at least it is in the one I generated)
USE master
GO
/* Create and populate the session state database */
IF DB_ID(N'username_dotnetnuke') IS NULL BEGIN
DECLARE @cmd nvarchar(500)
SET @cmd = N'CREATE DATABASE [username_dotnetnuke]'
EXEC(@cmd)
END
You'll also need to delete the lines immediately following this that remove the job if it exist. It doesn't exist and you couldn't remove it if it did. And since the tables have never been created before, you might as well delete the lines that delete the existing tables if they exist. To make this easy. Do a search for the next "Use" statement where it uses your database name and delete everything from there on up. The remaining lines that should be deleted will look something like this:
DECLARE @jobname nvarchar(200)
SET @jobname = N'username_dotnetnuke' '_Job_DeleteExpiredSessions'
-- Delete the [local] job
-- We expected to get an error if the job doesn't exist.
PRINT 'If the job does not exist, an error from msdb.dbo.sp_delete_job is expected.'
EXECUTE msdb.dbo.sp_delete_job @job_name = @jobname
GO
DECLARE @sstype nvarchar(128)
SET @sstype = N'sstype_custom'
IF UPPER(@sstype) = 'SSTYPE_TEMP' AND OBJECT_ID(N'dbo.ASPState_Startup', 'P') IS NOT NULL BEGIN
DROP PROCEDURE dbo.ASPState_Startup
END
USE [username_dotnetnuke]
GO
IF OBJECT_ID(N'dbo.ASPStateTempSessions','U') IS NOT NULL BEGIN
DROP TABLE dbo.ASPStateTempSessions
END
IF OBJECT_ID(N'dbo.ASPStateTempApplications','U') IS NOT NULL BEGIN
DROP TABLE dbo.ASPStateTempApplications
END
The next thing you'll want to do is to delete the script that creates the job to delete expired sessions. You can find this at the bottom of the script. The code you want to remove, looks something like this:
BEGIN TRANSACTION
DECLARE @JobID BINARY(16)
DECLARE @ReturnCode int
DECLARE @nameT nchar(200)
SELECT @ReturnCode = 0
-- Add the job
SET @nameT = N'username_dotnetnuke' '_Job_DeleteExpiredSessions'
EXECUTE @ReturnCode = msdb.dbo.sp_add_job
@job_id = @JobID OUTPUT,
@job_name = @nameT,
@owner_login_name = NULL,
@description = N'Deletes expired sessions from the session state database.',
@category_name = N'[Uncategorized (Local)]',
@enabled = 1,
@notify_level_email = 0,
@notify_level_page = 0,
@notify_level_netsend = 0,
@notify_level_eventlog = 0,
@delete_level= 0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
-- Add the job steps
SET @nameT = N'username_dotnetnuke' '_JobStep_DeleteExpiredSessions'
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobstep
@job_id = @JobID,
@step_id = 1,
@step_name = @nameT,
@command = N'EXECUTE DeleteExpiredSessions',
@database_name = N'username_dotnetnuke',
@server = N'',
@subsystem = N'TSQL',
@cmdexec_success_code = 0,
@flags = 0,
@retry_attempts = 0,
@retry_interval = 1,
@output_file_name = N'',
@on_success_step_id = 0,
@on_success_action = 1,
@on_fail_step_id = 0,
@on_fail_action = 2
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXECUTE @ReturnCode = msdb.dbo.sp_update_job @job_id = @JobID, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
-- Add the job schedules
SET @nameT = N'username_dotnetnuke' '_JobSchedule_DeleteExpiredSessions'
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobschedule
@job_id = @JobID,
@name = @nameT,
@enabled = 1,
@freq_type = 4,
@active_start_date = 20001016,
@active_start_time = 0,
@freq_interval = 1,
@freq_subday_type = 4,
@freq_subday_interval = 1,
@freq_relative_interval = 0,
@freq_recurrence_factor = 0,
@active_end_date = 99991231,
@active_end_time = 235959
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
-- Add the Target Servers
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @JobID, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:
GO
The last thing you'll need to do is to provide a way to delete the expired session variables. The job we deleted normally does that, but since we don't have that job anymore, we obviously need another way. So do a search for the stored procedure name TempGetAppID and insert the following line as the first executable line:
EXECUTE DeleteExpiredSessions
The resulting script should look like:
DECLARE @cmd nchar(4000)
SET @cmd = N'
CREATE PROCEDURE dbo.TempGetAppID
@appName tAppName,
@appId int OUTPUT
AS
Exec [dbo].[DeleteExpiredSessions]
SET @appName = LOWER(@appName)
SET @appId = NULL
SELECT @appId = AppId
FROM [username_dotnetnuke].dbo.ASPStateTempApplications
WHERE AppName = @appName
IF @appId IS NULL BEGIN
BEGIN TRAN
SELECT @appId = AppId
FROM [username_dotnetnuke].dbo.ASPStateTempApplications WITH (TABLOCKX)
WHERE AppName = @appName
IF @appId IS NULL
BEGIN
EXEC GetHashCode @appName, @appId OUTPUT
INSERT [username_dotnetnuke].dbo.ASPStateTempApplications
VALUES
(@appId, @appName)
IF @@ERROR = 2627
BEGIN
DECLARE @dupApp tAppName
SELECT @dupApp = RTRIM(AppName)
FROM [username_dotnetnuke].dbo.ASPStateTempApplications
WHERE AppId = @appId
RAISERROR(''SQL session state fatal error: hash-code collision between applications ''''%s'''' and ''''%s''''. Please rename the 1st application to resolve the problem.'',
18, 1, @appName, @dupApp)
END
END
COMMIT
END
RETURN 0'
EXEC(@cmd)
GO
This should delete expired sessions every time session data is requested. This modification should work for most installations. If you happen to get a lot of traffic, you might want to modify the DeleteExpiredSessions procedure so that it is a bit more efficient. There are several modifications available on the web and googling for DeleteExpiredSession along with the word "asp.net" should turn up several suggestions.
Next, you'll want to change or add the session state elements in your web.config file. It should look something like the following:
mode="SQLServer"
allowCustomSqlDatabase="true"
sqlConnectionString="Server=yourServer; Database=yourDatabase; uid=userName_xyz; pwd=Abc123;"
cookieless="false"
timeout="20"
/>
Be sure to include the allowCustomSqlDatabase attribute or it will not work.
Friday, January 9, 2009
creating a setup for windows application + c#.net
Please refer below links
http://www.eggheadcafe.com/community/aspnet/2/10039670/making-exe.aspx
http://www.dotnetspider.com/resources/1415-How-make-setup-for-Net-based-application-C-VB-Net.aspx
http://www.codeguru.com/csharp/.net/net_general/visualstudionetadd-ins/article.php/c7219
http://www.codeproject.com/KB/install/easysetup.aspx?fid=263053&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2498021
http://www.eggheadcafe.com/community/aspnet/2/10039670/making-exe.aspx
http://www.dotnetspider.com/resources/1415-How-make-setup-for-Net-based-application-C-VB-Net.aspx
http://www.codeguru.com/csharp/.net/net_general/visualstudionetadd-ins/article.php/c7219
http://www.codeproject.com/KB/install/easysetup.aspx?fid=263053&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2498021
Saturday, January 3, 2009
Embedding Flash in Windows Forms
Friday, December 26, 2008
Creating a Alpha numeric string in VB.NET
=====Generating a Alpha numeric Random number====
If System.String.Compare(txtPassword.Value, "", True) = 0 Then
Dim iNumChars As Integer
iNumChars = 5
txtPassword.Value = u_logic.RandomString(iNumChars)
End If
'=====Ends Here===================================
Public Function RandomString(ByVal iLength As Integer) As String
Dim iZero, iNine, iA, iZ, iCount, iRandNum As Integer
Dim sRandomString As String
' we'll need random characters, so a Random object
' should probably be created...
Dim rRandom As New Random(System.DateTime.Now.Millisecond)
' convert characters into their integer equivalents (their ASCII values)
iZero = Asc("0")
iNine = Asc("9")
iA = Asc("A")
iZ = Asc("Z")
' initialize our return string for use in the following loop
sRandomString = String.Empty
' now we loop as many times as is necessary to build the string
' length we want
While (iCount < iLength)
' we fetch a random number between our high and low values
iRandNum = rRandom.Next(iZero, iZ)
' here's the cool part: we inspect the value of the random number,
' and if it matches one of the legal values that we've decided upon,
' we convert the number to a character and add it to our string
If (((iRandNum >= iZero) And (iRandNum <= iNine) _
Or (iRandNum >= iA) And (iRandNum <= iZ))) Then
sRandomString = sRandomString + Chr(iRandNum)
iCount = iCount + 1
End If
End While
' finally, our random character string should be built, so we return it
RandomString = sRandomString
End Function
If System.String.Compare(txtPassword.Value, "", True) = 0 Then
Dim iNumChars As Integer
iNumChars = 5
txtPassword.Value = u_logic.RandomString(iNumChars)
End If
'=====Ends Here===================================
Public Function RandomString(ByVal iLength As Integer) As String
Dim iZero, iNine, iA, iZ, iCount, iRandNum As Integer
Dim sRandomString As String
' we'll need random characters, so a Random object
' should probably be created...
Dim rRandom As New Random(System.DateTime.Now.Millisecond)
' convert characters into their integer equivalents (their ASCII values)
iZero = Asc("0")
iNine = Asc("9")
iA = Asc("A")
iZ = Asc("Z")
' initialize our return string for use in the following loop
sRandomString = String.Empty
' now we loop as many times as is necessary to build the string
' length we want
While (iCount < iLength)
' we fetch a random number between our high and low values
iRandNum = rRandom.Next(iZero, iZ)
' here's the cool part: we inspect the value of the random number,
' and if it matches one of the legal values that we've decided upon,
' we convert the number to a character and add it to our string
If (((iRandNum >= iZero) And (iRandNum <= iNine) _
Or (iRandNum >= iA) And (iRandNum <= iZ))) Then
sRandomString = sRandomString + Chr(iRandNum)
iCount = iCount + 1
End If
End While
' finally, our random character string should be built, so we return it
RandomString = sRandomString
End Function
Image creation in php
session_start();
header("Content-type: image/png");
$pattern = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for($i=0;$i<7;$i++)
{
$rndnum.= $pattern{rand(0,33)};
}
//Registering Sessions Starts Here
$_SESSION['SecureCode']=$rndnum;
session_register('SecureCode');
//Ends Here
$im = @imagecreate(140, 30)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 47, 79, 79);
$text_color = imagecolorallocate($im, 255, 255, 255);
$font = imageloadfont('assets/images/chowfun.gdf');
imagestring($im, $font, 15, 3, "$rndnum", $text_color);
imagepng($im);
?>
header("Content-type: image/png");
$pattern = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for($i=0;$i<7;$i++)
{
$rndnum.= $pattern{rand(0,33)};
}
//Registering Sessions Starts Here
$_SESSION['SecureCode']=$rndnum;
session_register('SecureCode');
//Ends Here
$im = @imagecreate(140, 30)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 47, 79, 79);
$text_color = imagecolorallocate($im, 255, 255, 255);
$font = imageloadfont('assets/images/chowfun.gdf');
imagestring($im, $font, 15, 3, "$rndnum", $text_color);
imagepng($im);
?>
How to Bookmark your page
function funAddBookMark()
{
if (window.sidebar) // firefox
{
window.sidebar.addPanel(document.title, window.location.href, "");
}
else if(window.ie)// ie
{
window.external.AddFavorite(window.location.href, document.title);
}
else
{
var msg = "Don't forget to bookmark us!\n";
msg += "Press (CTRL+D) to bookmark.";
alert(msg);
}
}
please refer
http://stackoverflow.com/questions/374487/add-to-favorites-with-javascript-in-opera
{
if (window.sidebar) // firefox
{
window.sidebar.addPanel(document.title, window.location.href, "");
}
else if(window.ie)// ie
{
window.external.AddFavorite(window.location.href, document.title);
}
else
{
var msg = "Don't forget to bookmark us!\n";
msg += "Press (CTRL+D) to bookmark.";
alert(msg);
}
}
please refer
http://stackoverflow.com/questions/374487/add-to-favorites-with-javascript-in-opera
Friday, September 26, 2008
Difference between Response.Redirect and Server.Transfer
Server.Transfer can not be used to go to a page of a different website whereas Response.Redirect can do.
Response.Redirect can be used for both .html and .aspx pages but Server.Transfer works only for aspx pages
Explanation :
If i have two different pages Default1.aspx and Default2.aspx
and In the button click event of the Default1.aspx i wrote a code
Response.Redirect("Default2.aspx");
Now when i click the button ,the page will posted to the server and the code will be executed there.
Then what happens??
Response.Redirect sends message to browser saying that the browser should request some other page so basically it means that:
1. Browser is on page default1.aspx on which there is a Response.Redirect("") command which means that the server sends response (message) to browser that browser should request some other page default2.aspx
2. Browser sends request to server in order to get this page default2.aspx
3. Server sends page default2.aspx to browser
Server.Transfer doesn't tell the browser to request page default2.aspx. It just sends page default2.aspx, so e.g., browser address bar still shows the original page's URL.
Roundtrip is the combination of a request being sent to the server and response being sent back to browser.
Request is the message that the browser sends to the server and Response is the message the server sends back to the browser.
Server.Transfer also transfer the .Form data to the next page
Response.Redirect there are two round trips and in case of server.transfer there are only one roundtrip.
Response.Redirect can be used for both .html and .aspx pages but Server.Transfer works only for aspx pages
Explanation :
If i have two different pages Default1.aspx and Default2.aspx
and In the button click event of the Default1.aspx i wrote a code
Response.Redirect("Default2.aspx");
Now when i click the button ,the page will posted to the server and the code will be executed there.
Then what happens??
Response.Redirect sends message to browser saying that the browser should request some other page so basically it means that:
1. Browser is on page default1.aspx on which there is a Response.Redirect("") command which means that the server sends response (message) to browser that browser should request some other page default2.aspx
2. Browser sends request to server in order to get this page default2.aspx
3. Server sends page default2.aspx to browser
Server.Transfer doesn't tell the browser to request page default2.aspx. It just sends page default2.aspx, so e.g., browser address bar still shows the original page's URL.
Roundtrip is the combination of a request being sent to the server and response being sent back to browser.
Request is the message that the browser sends to the server and Response is the message the server sends back to the browser.
Server.Transfer also transfer the .Form data to the next page
Response.Redirect there are two round trips and in case of server.transfer there are only one roundtrip.
Ways to solve session expired problem
1)
setting time limit in the web.config file
< mode="InProc" timeout="20" cookieless="false" stateconnectionstring="tcpip=127.0.0.1:42424" sqlconnectionstring="data source=127.0.0.1;Trusted_Connection=yes" >
..Here the timeout "20" is mins
2)
One possible explaination is that you are using .Net Server 2003 and your IIS Application Pool is configured to recycle the worker process after 10 minutes.
When the asp worker process is recycled, the session state is dropped and the user is forced to log in again.
3)
Well, we solve the problem, we was hosting our web application at web garden architicture server machines (multi server machines), at that time our session mode was InProcess so, no unexpected logged out was happen in our local machines but when we host it to server unexpected logged out appears. So, wab garden server machines seems to distribute our worker processes so Session mode shall be in StateServer mode.
As i read, and for the reason that Worker process is distributed, you cannot use InProcess mode.
therefore, you should set session mode to stateserver, and make sure that your Session object is Serialized and any other objects that it used shall not be serialized.
another thing make sure that you don't miss your connections (leaking of connections) by disposing each connection opened, since any exception appeared within uses of connection will not close it, it will still opened so try to dispose connections always, even if you close it..
4)
Under ASP.NET , the timeout error message reads as follows:
Exception Details: System.Web.HttpException: Request timed out.
In .NET, there is an additional setting for this. The default script timeout is set to 90 seconds by the httpRuntime section of the machine.config file. You can change this setting to affect all applications on your site, or you can override the settings in your application-specific web.config as follows:
< system.web >
< httpRuntime executiontimeout="900" >
< /system.web >
The .NET config files are usually stored in the folder C:\Windows\Microsoft.NET\Framework\[version]\Config where [version] is the version of the .NET Framework such as v1.1.4322. You may need to restart IIS for such changes to take effect.
5)
You have to set the session timeout in default website also.
Do the following. go to IIS Manager, right click on the virtual directory and choose properties.
Now go to virtual directory tab, click Configuration button. now a dialog box will appear.
choose AppOptions tab. Set the session timeout that u need. This will solve the problem.
If you are agin getting the same problem then set the same thing for Default WebSite also.
6)
1.) I first noticed session ending during the redirect operation. Next most important was code executing after the redirect. I found when I use redirect, any coding following the redirect statement will execute and may cause errors.
2.) Any page or application errors may cause a session end. I set up an email message in the page catch statement and application level to track down bad coding on my part.
3.) Configuration of HttpRuntime help too, I found certain threading issues. This is my current webconfig statement:
< httpruntime executiontimeout="250" minfreethreads="12" minlocalrequestfreethreads="12" >
4.) If in production turn off debug, your application will running harder if turn on.
< compilation debug="false" defaultlanguage="vb" >
7)
use server.transfer () instead of response.redirect()...
8)
Try using sessionstate mode=stateserver, because the worker process my recycle any session in InProc will be deleted from memory along with the recycle.
The stateserver do not recycle with the worker processing and will allow for longer session times.
9)
It is IIS setting that reset ideal process after few mins if not used to refresh memory for IIS service.
We could allow your domain name the maximum time before service restart and that will help to resolve your issue
10)
If changing the timeout session in IIS do not work, you have 2 other solutions.
The first one is to remove the check of the session timeout in IIS, then the timeout will be read from the webconfig.
The second solution is to add the following code in the web.config file under
< system.web >
< sessionstate mode="InProc" timeout="240" cookieless="false" >
11)
I also faced the same problem of session timeout not working properly even changing the web config property.
Later when i debuged the code i found out that in FormsAuthenticationTicket I was setting the cookie expiration time out as something else than my session value on the web.config.This value I changed in my login form to solve the problem
<<<<< datetime.now.addminutes(60) >>>>> this setting i changed as per the web.config setting.
FormsAuthenticationTicket authTicket =
new FormsAuthenticationTicket(1, // version
txtUserName.Text,
DateTime.Now,
DateTime.Now.AddMinutes(60),
false,@"\");
setting time limit in the web.config file
< mode="InProc" timeout="20" cookieless="false" stateconnectionstring="tcpip=127.0.0.1:42424" sqlconnectionstring="data source=127.0.0.1;Trusted_Connection=yes" >
..Here the timeout "20" is mins
2)
One possible explaination is that you are using .Net Server 2003 and your IIS Application Pool is configured to recycle the worker process after 10 minutes.
When the asp worker process is recycled, the session state is dropped and the user is forced to log in again.
3)
Well, we solve the problem, we was hosting our web application at web garden architicture server machines (multi server machines), at that time our session mode was InProcess so, no unexpected logged out was happen in our local machines but when we host it to server unexpected logged out appears. So, wab garden server machines seems to distribute our worker processes so Session mode shall be in StateServer mode.
As i read, and for the reason that Worker process is distributed, you cannot use InProcess mode.
therefore, you should set session mode to stateserver, and make sure that your Session object is Serialized and any other objects that it used shall not be serialized.
another thing make sure that you don't miss your connections (leaking of connections) by disposing each connection opened, since any exception appeared within uses of connection will not close it, it will still opened so try to dispose connections always, even if you close it..
4)
Under ASP.NET , the timeout error message reads as follows:
Exception Details: System.Web.HttpException: Request timed out.
In .NET, there is an additional setting for this. The default script timeout is set to 90 seconds by the httpRuntime section of the machine.config file. You can change this setting to affect all applications on your site, or you can override the settings in your application-specific web.config as follows:
< system.web >
< httpRuntime executiontimeout="900" >
< /system.web >
The .NET config files are usually stored in the folder C:\Windows\Microsoft.NET\Framework\[version]\Config where [version] is the version of the .NET Framework such as v1.1.4322. You may need to restart IIS for such changes to take effect.
5)
You have to set the session timeout in default website also.
Do the following. go to IIS Manager, right click on the virtual directory and choose properties.
Now go to virtual directory tab, click Configuration button. now a dialog box will appear.
choose AppOptions tab. Set the session timeout that u need. This will solve the problem.
If you are agin getting the same problem then set the same thing for Default WebSite also.
6)
1.) I first noticed session ending during the redirect operation. Next most important was code executing after the redirect. I found when I use redirect, any coding following the redirect statement will execute and may cause errors.
2.) Any page or application errors may cause a session end. I set up an email message in the page catch statement and application level to track down bad coding on my part.
3.) Configuration of HttpRuntime help too, I found certain threading issues. This is my current webconfig statement:
< httpruntime executiontimeout="250" minfreethreads="12" minlocalrequestfreethreads="12" >
4.) If in production turn off debug, your application will running harder if turn on.
< compilation debug="false" defaultlanguage="vb" >
7)
use server.transfer () instead of response.redirect()...
8)
Try using sessionstate mode=stateserver, because the worker process my recycle any session in InProc will be deleted from memory along with the recycle.
The stateserver do not recycle with the worker processing and will allow for longer session times.
9)
It is IIS setting that reset ideal process after few mins if not used to refresh memory for IIS service.
We could allow your domain name the maximum time before service restart and that will help to resolve your issue
10)
If changing the timeout session in IIS do not work, you have 2 other solutions.
The first one is to remove the check of the session timeout in IIS, then the timeout will be read from the webconfig.
The second solution is to add the following code in the web.config file under
< system.web >
< sessionstate mode="InProc" timeout="240" cookieless="false" >
11)
I also faced the same problem of session timeout not working properly even changing the web config property.
Later when i debuged the code i found out that in FormsAuthenticationTicket I was setting the cookie expiration time out as something else than my session value on the web.config.This value I changed in my login form to solve the problem
<<<<< datetime.now.addminutes(60) >>>>> this setting i changed as per the web.config setting.
FormsAuthenticationTicket authTicket =
new FormsAuthenticationTicket(1, // version
txtUserName.Text,
DateTime.Now,
DateTime.Now.AddMinutes(60),
false,@"\");
Thursday, August 28, 2008
Creating Icon in the desktop in windows applications using c#.net
/// This will create a Application Reference file on the users desktop Starts
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
if (ad.IsFirstRun)
{
Assembly code = Assembly.GetExecutingAssembly();
string company = string.Empty;
string description = string.Empty;
if (Attribute.IsDefined(code, typeof(AssemblyCompanyAttribute)))
{
AssemblyCompanyAttribute ascompany = (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(code,
typeof(AssemblyCompanyAttribute));
company = ascompany.Company;
}
if (Attribute.IsDefined(code, typeof(AssemblyDescriptionAttribute)))
{
AssemblyDescriptionAttribute asdescription = (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(code,
typeof(AssemblyDescriptionAttribute));
description = asdescription.Description;
}
if (company != string.Empty && description != string.Empty)
{
string desktopPath = string.Empty;
desktopPath = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"\\", description, ".appref-ms");
string shortcutName = string.Empty;
shortcutName = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Programs),
"\\", company, "\\", description, ".appref-ms");
System.IO.File.Copy(shortcutName, desktopPath, true);
}
}
}
/// This will create a Application Reference file on the users desktop Ends
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
if (ad.IsFirstRun)
{
Assembly code = Assembly.GetExecutingAssembly();
string company = string.Empty;
string description = string.Empty;
if (Attribute.IsDefined(code, typeof(AssemblyCompanyAttribute)))
{
AssemblyCompanyAttribute ascompany = (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(code,
typeof(AssemblyCompanyAttribute));
company = ascompany.Company;
}
if (Attribute.IsDefined(code, typeof(AssemblyDescriptionAttribute)))
{
AssemblyDescriptionAttribute asdescription = (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(code,
typeof(AssemblyDescriptionAttribute));
description = asdescription.Description;
}
if (company != string.Empty && description != string.Empty)
{
string desktopPath = string.Empty;
desktopPath = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"\\", description, ".appref-ms");
string shortcutName = string.Empty;
shortcutName = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Programs),
"\\", company, "\\", description, ".appref-ms");
System.IO.File.Copy(shortcutName, desktopPath, true);
}
}
}
/// This will create a Application Reference file on the users desktop Ends
Friday, June 6, 2008
FTP Upload in PHP
$source_file=$_FILES['Filedata']['tmp_name'];
$destination_file ="/httpdocs/Uploads/".$_FILES['Filedata']['name'];
$ftp_server="SERVER NAME" ;
$ftp_user_name="USERNAME";
$ftp_user_pass="PASSWORD";
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// check connection
if ((!$conn_id) (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name";
}
// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);
// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}
// close the FTP stream
ftp_close($conn_id);
$destination_file ="/httpdocs/Uploads/".$_FILES['Filedata']['name'];
$ftp_server="SERVER NAME" ;
$ftp_user_name="USERNAME";
$ftp_user_pass="PASSWORD";
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// check connection
if ((!$conn_id) (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name";
}
// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);
// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}
// close the FTP stream
ftp_close($conn_id);
Thursday, June 5, 2008
FTP Upload in VB.NET
This is for Source File(ftpupload.aspx.vb)
Imports System
Imports System.Text
Imports System.Net
Imports system.Data
Imports System.IO
Imports System.Uri
Partial Class ftpupload
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub upload_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles upload.ServerClick
Dim fi As FileInfo
fi = New FileInfo(fileupload.Value)
''''''''''''''''''''''FTP UPLOAD STARTS HERE''''''''''''''''''''''''''''''''
'''''''''''''''''' Get the object used to communicate with the server'''''''''''''''''''''''.
Dim request As FtpWebRequest = DirectCast(WebRequest.Create("ftp://URL/www/FOLDERNAME/" & fi.Name), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.UploadFile
''''''''''''''''''This example assumes the FTP site uses anonymous logon'''''''''''''''''''''''''''''.
request.Credentials = New NetworkCredential("USERNAME", "PASSWORD")
'''''''''''''''''''Getting the filename ''''''''''''''''''''''''''''''''''''''''''''''
Dim selectedFile As HttpPostedFile = fileupload.PostedFile
''''''''''''''''''''Getting the file conetnt length'''''''''''''''''''''''''
Dim fileLength As Integer = selectedFile.ContentLength
Dim binarydata(fileLength) As Byte
'''''''''''''''''''''Reading data from the file''''''''''''''''''''''
selectedFile.InputStream.Read(binarydata, 0, fileLength)
Dim requestStream As Stream = request.GetRequestStream()
''''''''''''''''''''''''Writing data to the file''''''''''''''''''''''''
requestStream.Write(binarydata, 0, fileLength)
requestStream.Close()
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription)
response.Close()
''''''''''''''''''''''FTP UPLOAD ENDS HERE''''''''''''''''''''''''''''''''
End Sub
End Class
This for Design File(ftpupload.aspx)
Page Tag format ...
Page Language="VB" AutoEventWireup="false" CodeFile="ftpupload.aspx.vb" Inherits="ftpupload" Async="true" Strict="false"
Write Here HTML/BODY ..... tags Stars Here
One file type control with name "fileupload"
Ex:
One upload button with name "upload"
Ex:
Write Here HTML/BODY ..... tags Ends Here
Imports System
Imports System.Text
Imports System.Net
Imports system.Data
Imports System.IO
Imports System.Uri
Partial Class ftpupload
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub upload_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles upload.ServerClick
Dim fi As FileInfo
fi = New FileInfo(fileupload.Value)
''''''''''''''''''''''FTP UPLOAD STARTS HERE''''''''''''''''''''''''''''''''
'''''''''''''''''' Get the object used to communicate with the server'''''''''''''''''''''''.
Dim request As FtpWebRequest = DirectCast(WebRequest.Create("ftp://URL/www/FOLDERNAME/" & fi.Name), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.UploadFile
''''''''''''''''''This example assumes the FTP site uses anonymous logon'''''''''''''''''''''''''''''.
request.Credentials = New NetworkCredential("USERNAME", "PASSWORD")
'''''''''''''''''''Getting the filename ''''''''''''''''''''''''''''''''''''''''''''''
Dim selectedFile As HttpPostedFile = fileupload.PostedFile
''''''''''''''''''''Getting the file conetnt length'''''''''''''''''''''''''
Dim fileLength As Integer = selectedFile.ContentLength
Dim binarydata(fileLength) As Byte
'''''''''''''''''''''Reading data from the file''''''''''''''''''''''
selectedFile.InputStream.Read(binarydata, 0, fileLength)
Dim requestStream As Stream = request.GetRequestStream()
''''''''''''''''''''''''Writing data to the file''''''''''''''''''''''''
requestStream.Write(binarydata, 0, fileLength)
requestStream.Close()
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription)
response.Close()
''''''''''''''''''''''FTP UPLOAD ENDS HERE''''''''''''''''''''''''''''''''
End Sub
End Class
This for Design File(ftpupload.aspx)
Page Tag format ...
Page Language="VB" AutoEventWireup="false" CodeFile="ftpupload.aspx.vb" Inherits="ftpupload" Async="true" Strict="false"
Write Here HTML/BODY ..... tags Stars Here
One file type control with name "fileupload"
Ex:
One upload button with name "upload"
Ex:
Write Here HTML/BODY ..... tags Ends Here
Saturday, May 24, 2008
Thursday, April 10, 2008
My College Anniversery
Hi guys and gals,
How are u people doing? Hope u r doing fine.
Think u people r busy in work. So to refresh your mood.
Think u people r busy in work. So to refresh your mood.
I am sending some thing very interesting.Do have a look.
This video is regarding our college anniversery which contains an important clipping towards the end of the video ...
Hope u will enjoy the video
Thursday, October 11, 2007
Me with Goutham
Subscribe to:
Posts (Atom)



