Friday, July 30, 2010

How to: List all Query string variables in C#

This is how you can do it in C#, Either of will work for getting Query string values

for (int i = 0; i < Request.QueryString.Count; i++)
{                 
    Response.Write(Request.QueryString.Keys[i].ToString()+ ":"+Request.QueryString.Keys[i].ToString()+"<br/>");
}
foreach (string key in Request.QueryString.Keys)
{
    Response.Write(key+ ":"+Request.QueryString[key]+"<br/>");
}
  

How to: List all Session variables?

This is how we can get list of all session variables using c#.

for (int i = 0; i < Session.Contents.Count; i++)
{
    Response.Write(Session.Keys[i] + " - " + Session[i] + "<br />");
}
foreach (string key in Session.Keys)
{
    Response.Write(key + " - " + Session[key] + "<br />");
}

Either of them can get you all session details.

Ionic Zip Utility : SaveProgress Event

Save() method in Ionic Zip, this method allows the application to explicitly specify the name of the zip file when saving. Use this when creating a new zip file, or when updating a zip archive.

The ZipFile instance is written to storage, typically a zip file in a filesystem, only when the caller calls Save. The Save operation writes the zip content to a temporary file, and then renames the temporary file to the desired name. If necessary, this method will delete a pre-existing file before the rename.

using (ZipFile zip = ZipFile.Read("Archive.zip"))
{
  zip.AddFile("test.jpg");
  zip.Save("UpdatedArchive.zip");
}

There is an Save Progress event handler which invoked when a Save() starts, before and after each entry has been written to the archive, when a Save() completes, and during other Save events.
Depending on the particular event, different properties on the SaveProgressEventArgs parameter are set.


The following  EventTypes describes under which this event handler is invoked  with the given EventType.
ZipProgressEventType.Saving_Started Fired when ZipFile.Save() begins.
ZipProgressEventType.Saving_BeforeSaveEntry Fired within ZipFile.Save(), just before writing data for each particular entry.
ZipProgressEventType.Saving_AfterSaveEntry Fired within ZipFile.Save(), just after having finished writing data for each particular entry.
ZipProgressEventType.Saving_Completed Fired when ZipFile.Save() has completed.
ZipProgressEventType.Saving_AfterSaveTempArchive Fired after the temporary file has been created. This happens only when saving to a disk file. This event will not be invoked when saving to a stream.
ZipProgressEventType.Saving_BeforeRenameTempArchive Fired just before renaming the temporary file to the permanent location. This happens only when saving to a disk file. This event will not be invoked when saving to a stream.
ZipProgressEventType.Saving_AfterRenameTempArchive Fired just after renaming the temporary file to the permanent location. This happens only when saving to a disk file. This event will not be invoked when saving to a stream.
ZipProgressEventType.Saving_AfterCompileSelfExtractor Fired after a self-extracting archive has finished compiling. This EventType is used only within SaveSelfExtractor().
ZipProgressEventType.Saving_BytesRead Set during the save of a particular entry, to update progress of the Save(). When this EventType is set, the BytesTransferred is the number of bytes that have been read from the source stream. The TotalBytesToTransfer is the number of bytes in the uncompressed file.


In example below to see how it can be used.

static bool justHadByteUpdate= false;
public static void SaveProgress(object sender, SaveProgressEventArgs e)
{
    if (e.EventType == ZipProgressEventType.Saving_Started)
        Console.WriteLine("Saving: {0}", e.ArchiveName);
    else if (e.EventType == ZipProgressEventType.Saving_Completed)
    {
        justHadByteUpdate= false;
        Console.WriteLine();
        Console.WriteLine("Done: {0}", e.ArchiveName);
    }
    else if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry)
    {
        if (justHadByteUpdate)
            Console.WriteLine();
        Console.WriteLine("  Writing: {0} ({1}/{2})",
                          e.CurrentEntry.FileName, e.EntriesSaved, e.EntriesTotal);
        justHadByteUpdate= false;
    }
    else if (e.EventType == ZipProgressEventType.Saving_EntryBytesRead)
    {
        if (justHadByteUpdate)
            Console.SetCursorPosition(0, Console.CursorTop);
         Console.Write("     {0}/{1} ({2:N0}%)", e.BytesTransferred, e.TotalBytesToTransfer,
                      e.BytesTransferred / (0.01 * e.TotalBytesToTransfer ));
        justHadByteUpdate= true;
    }
}
public static ZipUp(string targetZip, string directory)
{
  using (var zip = new ZipFile()) {
    zip.SaveProgress += SaveProgress;
    zip.AddDirectory(directory);
    zip.Save(targetZip);
  }
}


I have copied this information from Ionic help file for my future reference.

DotNetZip - Zip and Unzip in C#, VB, any .NET language

DotNetZip is an easy-to-use, FAST, FREE class library and toolset for manipulating zip files or folders. Zip and Unzip is easy: with DotNetZip, .NET applications written in VB, C# - any .NET language - can easily create, read, extract, or update zip files. For Mono or MS .NET.

You can find more information at codeplex. Download from here.

Thursday, July 29, 2010

How to: Javascript Loading Conditionally for IE

Loading Javascript conditionally for IE. When rendering fixes are needed for IE, you can enclose CSS, JavaScript, or HTML markup in conditional comment tags directed at one or more versions of IE with an "if" statement; IE will then execute the code specified within them, while all other browsers treat them as standard comment tags and ignore them. The "if" statement must reference IE in square brackets as shown below; in this example include script only for IE

<!--[if IE]>
    <script type="text/javascript">
        /*  Do Stuff */
    </script>
<![endif]-->
below example shows how to exclude a script block from IE:
<![if !IE]>
    <script type="text/javascript">
        /*  Do Stuff */
    </script>
<![endif]>
Conditional comments can also be targeted to a particular version of IE, or a subset of versions, like those released prior to IE7 or IE6
<!--[if lt IE 7]>
  <link rel="stylesheet" type="text/css" href="ie_fixes.css" />
<![endif]-->

Hope this helps!

Tuesday, July 27, 2010

How to: Remove empty lines in text using Visual Studio.

Visual Studio has ability to delete empty lines in replace operation using regular expressions.
1.Click Ctrl-H (quick replace)
2. Tick "Use Regular Expressions"
3. In Find specify ^$\n
4. In Replace box delete everything.
5 Click "Replace All".

All empty lines will be deleted.

Regular expression for empty line consist of 

Beginning of line ^
End of line $
Line break \n

Monday, July 26, 2010

Keystroke Function

WIN - Opens the Start Menu

WIN + E - Opens My Computer in Windows Explorer

WIN + Pause/Break - Opens the System Properties dialog box

WIN + U - Opens the Utility Manager

WIN + R - Opens the Run box

WIN + F - Opens the Search for Files and Folder window

WIN + M - Minimizes all Windows

WIN + L - Lock Computer

WIN + B - Selects the first item in the System.Use arrow keys to navigate.

Alt + Tab - Switch between open programs.

Alt + Enter - Opens the Properties page of a selected item

Shift + Delete - Permanently deletes and item
Ctrl + Shift + Esc - Opens the Windows Task Manager

PrntScn - Takes a screenshot of the entire screen, saves it on the clipboard

Alt + PrntScn - Takes a screenshot of the active  windows

F1 - Opens the Windows XP

F2 - Help = Rename selected item

F3 - Search

F5 - Refresh Internet Explorer page

Ctrl + A - Select All

Ctrl + C - Copy

Ctrl + X - Cut

Ctrl + V - Paste

Ctrl + P - Print

Ctrl + O - Open

Ctrl + Backspace - Deletes the entire word to the left

Ctrl + Delete - Deletes the entire word to the right

Ctrl + Right arrow - Moves the cursor to the beginning of the next word

Ctrl + Left arrow - Moves the cursor to the beginning of the previous word

Ctrl + Down arrow - Moves the cursor to the beginning of the next paragraph

Ctrl + Up arrow - Moves the cursor to the beginning of the previous paragraph

Click Shift 5 times - Turns StickyKeys on or off

Thursday, July 22, 2010

Understanding VARCHAR(MAX) in SQL Server 2005

In SQL Server 2000 and SQL Server 7, a row cannot exceed 8000 bytes in size. This means that a VARBINARY column can only store 8000 bytes (assuming it is the only column in a table), a VARCHAR column can store up to 8000 characters and an NVARCHAR column can store up to 4000 characters (2 bytes per unicode character). This limitation stems from the 8 KB internal page size SQL Server uses to save data to disk.

To store more data in a single column, you needed to use the TEXT, NTEXT, or IMAGE data types (BLOBs) which are stored in a collection of 8 KB data pages that are separate from the data pages that store the other data in the same table. These data pages are arranged in a B-tree structure. BLOBs are hard to work with and manipulate. They cannot be used as variables in a procedure or a function and they cannot be used inside string functions such as REPLACE, CHARINDEX or SUBSTRING. In most cases, you have to use READTEXT, WRITETEXT, and UPDATETEXT commands to manipulate BLOBs.
To solve this problem, Microsoft introduced the VARCHAR(MAX),  NVARCHAR(MAX), and VARBINARY(MAX) data types in SQL Server 2005. These data types can hold the same amount of data BLOBs can hold (2 GB) and they are stored in the same type of data pages used for other data types. When data in a MAX data type exceeds 8 KB, an over-flow page is used. SQL Server 2005 automatically assigns an over-flow indicator to the page and knows how to manipulate data rows the same way it manipulates other data types. You can declare variables of MAX data types inside a stored procedure or function and even pass them as variables. You can also use them inside string functions.

Microsoft recommend using MAX data types instead of BLOBs in SQL Server 2005. In fact, BLOBs are being deprecated in future releases of SQL Server.

Browser : Epic

Bangalore-based startup, Hidden Reflex, has developed a browser for the Indian audience called Epic, thanks to Mozilla’s popular open-source platform. Though made on lines of the Firefox browser, it has many firsts

It’s the only browser that has an in-built anti-virus scanner and other unique privacy features like the flash cookie deletion.

Epic also has a side-bar with shortcut icons for frequently used applications and websites – all of which are a part of the 1500+ apps that ‘Epic’ boasts of.

Epic provides a uniquely Indian browsing experience. Epic's India sidebar supports Indian content by providing users access to the latest national and regional news from popular publications, live television channels, videos, stock quotes, live cricket scores, top music albums, and local events

My favourite, however, is the ‘type in Indian languages’ widget that can be done using the English script, which the browser instantly converts into the regional language chosen.

Users can choose from 1500+ customised Indian themes and wallpapers ranging from freedom fighters to famous Bollywood and regional film stars. Writing in Indian languages is supported throughout Epic. Users can instantly write in Indian languages on any webpage or in Write, Epic's free built-in word processor. Twelve Indian languages are currently supported. Free antivirus scanning and healing is built into Epic

Download Epic from here.

Friday, July 16, 2010

Karbon Flv Downloader for Firefox

Here is the nice plug-in you can add-on for Mozilla.

You Download and install Karbon here. Once you install this plug-in you can see an icon in the Mozilla status bar.

karbon

You can see the number of downloadable files. Click on Karbon icon to see all the downloadable files

karbon2

You can Download FLVs and MP3s from almost any embedded web pages. Have Fun.

Thursday, July 15, 2010

Windows 7: SMTP Server

I am using Windows 7, as a developer some times i need to send emails from my applications. But using Windows 7  i can’t send emails as SMTP service used to ship with IIS 6.0 and earlier versions are missing from IIS 7.0 on Windows 7.  there is no default SMTP configured, I am very impressed with Windows 7 but  IIS 7.0 does not include Post Office Protocol or Simple Mail Transfer Protocol.

For this there many third party free SMTP Servers available over net.  But for me after trying various SMTP service solutions, the one that I found to be pretty simple to install and configure is hMailServer. Just like the old SMTP that ships with IIS 6.0, hMailServer allows one to restrict access to the local machine (127.0.0.1) only in order to prevent being vulnerable to spam. It installs a SQL database meant for storing inbound email for users to POP/IMAP mail out of. Its a security features of locking it down to the loopback address. But as developer its simple and easy to use

Download and install hMailServer.

Some pointers on ensuring you restrict access to your local machine only.

Once you attempt to connect i ask for the password which is give at the time of installation.

8

This will open the admin console.  Go to Protocols section in Settings, and check only SMTP and save.

9

Now go to Advanced in Settings –>Settings –> Advanced. Select IP Ranges section

image

Select My Computer from IP Ranges and click Edit,

image

Uncheck all from Require SMTP authentication section. And keep the rest all default settings as it is.

That is it.  You have a mail server now on Windows 7.  This software has a lot of options including having multiple domains.  Remember to secure it the best you can so you don’t become a spam haven.  Happy SMTP Mailing Smile

Wednesday, July 14, 2010

SP_EXECUTESQL vs EXECUTE/EXEC

Common Properties

  • The Transact-SQL statements in the sp_executesql or EXECUTE string are not compiled into an execution plan until sp_executesql or the EXECUTE statement are executed. The strings are not parsed or checked for errors until they are executed. The names referenced in the strings are not resolved until they are executed.
  • The Transact-SQL statements in the executed string do not have access to any of the variables declared in the batch that contains the sp_executesql or EXECUTE statement. The batch containing the sp_executesql or EXECUTE statement does not have access to variables or local cursors defined in the executed string.
  • If the executed string has a USE statement that changes the database context, the change to the database context only lasts until sp_executesql or the EXECUTE statement completes.

Comparison SP_EXECUTESQL vs EXECUTE/EXEC

sp_executesql gives you the possibility to use parameterised statements, EXECUTE does not. Parameterised statements gives no risk to SQL injection and also gives advantage of cached query plan. The sp_executesql stored procedure supports parameters. So, using the sp_executesql stored procedure instead of the EXECUTE statement improve readability of your code when there are many parameters are used. When you use the sp_executesql stored procedure to executes a Transact-SQL statements that will be reused many times, the SQL Server query optimizer will reuse the execution plan it generates for the first execution when the change in parameter values to the statement is the only variation.

sp_executesql can be used instead of stored procedures to execute a Transact-SQL statement a number of times when the change in parameter values to the statement is the only variation. Because the Transact-SQL statement itself remains constant and only the parameter values change, the SQL Server query optimizer is likely to reuse the execution plan it generates for the first execution.

Use SP_EXECUTESQL rather than EXEC(), it has better performance and improved security.

sp_executesql [ @statement= ] statement
[ 
  { , [ @params = ] N'@parameter_name data_type [ OUT | OUTPUT ][ ,...n ]' } 
     { , [ @param1= ] 'value1' [ ,...n ] }
]

Thursday, July 08, 2010

How to: Drop a Database if it exists

Here is the T-SQL code for checking to create if the database exists. This code below drops the database and creates new.

-- Changed database context to 'master'
USE master
GO
-- Check Exists
IF EXISTS(SELECT name FROM sys.databases
WHERE name = 'Angel83')
DROP DATABASE Angel83
GO
-- Create Database
CREATE DATABASE Angel83
GO

Tuesday, July 06, 2010

SQL SERVER Tweaks

Here are some shortcuts to monitor and admin SQL Server

Determines Server available disk space:
xp_fixeddrives

Determine Log Size Log Space used and status of the available databases

DBCC SQLPERF(LOGSPACE);
GO


Database size and service broker information:

DBCC CHECKDB

Uses to get information of the database work tables to hold intermediate results and for sort operations

How to get Current time and user information:

SELECT
    CURRENT_TIMESTAMP AS TIME,
    USER AS Username,
    SYSTEM_USER AS System_Username,
    CURRENT_USER AS Current_Username,
    SESSION_USER AS Session_Username

Monitoring SQL-Server:

sp_who2

Useful stored procedures:

sp_helpdb -- Displays information about all databases on the server
sp_helpdb ‘databasename’ -- Displays information about a particular database
sp_help objectname -- Displays information about a table
sp_spaceused -- Displays information about the space used in the current database
sp_tables -- Lists the tables in a database
sp_helptext name -- Displays the code used in a particular stored procedure
sp_dboption -- Sets or returns information about database options

Hope this helps.