Sunday, January 25, 2009

Upload T-SQL and execute at your hosting provider using an ASP.NET page

With this approach, you can use the Database Publishing Wizard to generate a T-SQL file from your local database. Then, you can upload the script to your hosting provider, and use the sample ASP.NET page provided to execute the code below.

This approach is useful in the following circumstances:

* Your hosting provider has not deployed the Database Publishing Services, enabling simple publishing of your SQL Server database
* Your hosting provider does not have a T-SQL script execution window or the T-SQL script generated by the Database Publishing Wizard is too large to paste into the T-SQL script execution window

Here is the code, just copy it then paste to your RunSQL.aspx


<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%
// **************************************************************************
// Update these variables here
// **************************************************************************
// Url of the T-SQL file you want to run

string fileUrl = @"http://<>/<>.sql";

// Connection string to the server you want to execute against
string connectionString = @"<>";

// Timeout of batches (in seconds)
int timeout = 600;
%>





Executing T-SQL






<%
SqlConnection conn = null;
try
{
this.Response.Write(String.Format("Opening url {0}
", fileUrl));

// read file
WebRequest request = WebRequest.Create(fileUrl);
using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
{
this.Response.Write("Connecting to SQL Server database...
");

// Create new connection to database
conn = new SqlConnection(connectionString);

conn.Open();

while (!sr.EndOfStream)
{
StringBuilder sb = new StringBuilder();
SqlCommand cmd = conn.CreateCommand();

while (!sr.EndOfStream)
{
string s = sr.ReadLine();
if (s != null && s.ToUpper().Trim().Equals("GO"))
{
break;
}

sb.AppendLine(s);
}

// Execute T-SQL against the target database
cmd.CommandText = sb.ToString();
cmd.CommandTimeout = timeout;

cmd.ExecuteNonQuery();
}

}
this.Response.Write("T-SQL file executed successfully");
}
catch (Exception ex)
{
this.Response.Write(String.Format("An error occured: {0}", ex.ToString()));
}
finally
{
// Close out the connection
//
if (conn != null)
{
try
{
conn.Close();
conn.Dispose();
}
catch (Exception e)
{
this.Response.Write(String.Format(@"Could not close the connection. Error was {0}", e.ToString()));
}
}
}
%>



Below are the instructions to use this approach:

1. Run the Database Publishing Wizard to generate a T-SQL script file for your local database
2. Using FTP (or another approach if applicable), upload this T-SQL file to your hosting account
3. Download the sample ASP.NET page by clicking on this link: RunSQL.aspx
4. Edit the ASPX page and change the values of the variables fileUrl and connectionString as follows:
1. fileUrl should be the url of the T-SQL file you uploaded. For example if your domain name is www.mydomain.Com, then the url would be http://www.mydomain.com/File.Sql
2. connectionString should be the connection string of your hosted SQL Server database
5. Upload the ASPX page to your hosting account
6. Point your web browser to the ASPX page you uploaded. When this page has completed loading, your database should now be populated in the remote SQL Server database
7. Important: Delete the T-SQL file and ASPX page in your hosting account. This will prevent others from reading your data or tampering with your database.

Sunday, December 28, 2008

Stored Procedure using the most CPU

The following query gives you a high-level view of which currently cached batches or procedures are using the most CPU. The query aggregates the CPU consumed by all statements with the same plan__handle (meaning that they are part of the same batch or procedure). If a given plan_handle has more than one statement, you may have to drill in further to find the specific query that is the largest contributor to the overall CPU usage.
select top 50
sum(qs.total_worker_time) as total_cpu_time,
sum(qs.execution_count) as total_execution_count,
count(*) as number_of_statements,
qs.plan_handle
from
sys.dm_exec_query_stats qs
group by qs.plan_handle
order by sum(qs.total_worker_time) desc

Saturday, December 13, 2008

Creating Antibot Image With c#

Antibots images are needed for avoiding Trojans to make fake registration with out human interaction.In the method given below generate random strings and generate the bitmap of that.This method Should be added as web handler(ashx) in the asp.net project.


public void ProcessRequest(HttpContext context)
{
if(context.Session["antibotimage"] == null)
{
context.Session["antibotimage"] = generateRandomString(4).ToUpper();
}

GenerateImage(context.Session["antibotimage"].ToString(), 100, 20, "Arial").Save(context.Response.OutputStream, ImageFormat.Jpeg);
}


private Bitmap GenerateImage(string text, int width, int height, string fontFamily)
{
Random random = new Random();

// Create a new 32-bit bitmap image.
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);

// Create a graphics object for drawing.
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, width, height);

// Fill in the background.
HatchBrush hatchBrush = new HatchBrush(HatchStyle.Wave, Color.LightGray, Color.White);
g.FillRectangle(hatchBrush, rect);

// Set up the text font.
SizeF size;
float fontSize = rect.Height + 1;
Font font;
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;

// Adjust the font size until the text fits within the image.
do
{
fontSize--;
font = new Font(fontFamily, fontSize, FontStyle.Bold);
size = g.MeasureString(text, font, new SizeF(width, height), format);
} while (size.Width > rect.Width);

// Create a path using the text and warp it randomly.
GraphicsPath path = new GraphicsPath();
path.AddString(text, font.FontFamily, (int)font.Style, font.Size, rect, format);
float v = 4F;
PointF[] points =
{
new PointF(random.Next(rect.Width) / v, random.Next(rect.Height) / v),
new PointF(rect.Width - random.Next(rect.Width) / v, random.Next(rect.Height) / v),
new PointF(random.Next(rect.Width) / v, rect.Height - random.Next(rect.Height) / v),
new PointF(rect.Width - random.Next(rect.Width) / v, rect.Height - random.Next(rect.Height) / v)
};
Matrix matrix = new Matrix();
matrix.Translate(0F, 0F);
path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

// Draw the text.
hatchBrush = new HatchBrush(HatchStyle.DashedUpwardDiagonal, Color.DarkGray, Color.Black);
g.FillPath(hatchBrush, path);

// Add some random noise.
int m = Math.Max(rect.Width, rect.Height);
for (int i = 0; i < (int)(rect.Width * rect.Height / 30F); i++)
{
int x = random.Next(rect.Width);
int y = random.Next(rect.Height);
int w = random.Next(m / 50);
int h = random.Next(m / 50);
g.FillEllipse(hatchBrush, x, y, w, h);
}

// Clean up.
font.Dispose();
hatchBrush.Dispose();
g.Dispose();

return bitmap;
}


private string generateRandomString(int size)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}

Programmed by
Renju.R,
Software Engineer,
ISOFT, Chennai,India

Saturday, October 11, 2008

Parsing/Looping through Treeview using Interface

private static void parseNode(TreeNode tn)
{

IEnumerator ie = tn.ChildNodes.GetEnumerator();

string parentnode = "";

parentnode = tn.Text;

while (ie.MoveNext())
{
TreeNode ctn = (TreeNode) ie.Current;

if (ctn.ChildNodes.Count == 0)
{
sr.Write(ctn.Text);
}
else
{
sr.Write("<" + ctn.Text + ">");
}
if (ctn.ChildNodes.Count > 0)
{
parseNode(ctn);
}
}

sr.Write("");
sr.WriteLine("");

}

Saving the treeview to XML

public static void exportToXml(TreeView tv, string filename)
{
sr = new StreamWriter(filename, false, System.Text.Encoding.UTF8);
sr.WriteLine("");
if (tv.Nodes.Count > 0)
{
IEnumerator ie = tv.Nodes.GetEnumerator();
ie.Reset();
if (ie.MoveNext())
{
TreeNode tn = (TreeNode)ie.Current;
sr.WriteLine("<" + tn.Text + ">");
parseNode(tn);
}
}

sr.Close();
}

Monday, September 15, 2008

SCOPE_IDENTITY

Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

SCOPE_IDENTITY()

Returns numeric value.eg:- RETURN SCOPE_IDENTITY()

Wednesday, September 10, 2008

Parsing Emails using Regular Expressions

Using Regular Expressions

Using regular expression we can simply parse valid emails from the given contents.this is mainly used to extract actual email addressess from the to,from,cc and bcc fields.

Implementation(c#)

First import using System.Text.RegularExpressions;

the code is as below

private string ParseEmails(string text)
{
const string emailPattern = @"\w+@\w+\.\w+((\.\w+)*)?";

MatchCollection emails = Regex.Matches(text, emailPattern, RegexOptions.IgnoreCase);
StringBuilder emailString = new StringBuilder();
foreach (Match email in emails)
{
if (emailString.Length ==0)
{
emailString.Append(email.Value);
}
else
{
emailString.Append("," + email.Value);
}
}

return emailString.ToString();
}

Monday, September 8, 2008

Word Break for Gridview/DataGrid

Sometime we are facing problems with gridview in inserting word breaks to format the grid.ie if we are inserting a coloumn that is having more length so the grid layout is changed.

"wbr" Tag is used for that.That should be placed in angle bracket("<>").I'm representing it as wbr in the code given below as it is an html tag.

public static string WordBreak(String inString, int length)
{
StringBuilder stb = new StringBuilder();
String ret = "";
int pos;
if (length == 0)
length = 10;
while ((true))
{
if (inString.Length <= length)
{
ret += inString;
break;
}
pos = inString.IndexOf(" ");
if (pos != -1)
{
if (pos > length - 1)
{
pos = length;
ret += inString.Substring(0, pos + 1) + "wbr";
}
else
{
ret += inString.Substring(0, pos + 1);
}
inString = inString.Substring(pos + 1);
}
else
{
ret += inString.Substring(0, length) + "wbr";
inString = inString.Substring(length);
}
}
if (ret.Length > 50)
{
string temp = ret.Substring(0, 50);
stb.Append(temp);
stb.Append("....");
ret = stb.ToString();
}
return ret;
}


Regards
www.renjucool.com

Saturday, September 6, 2008

Don’t run production ASP.NET Applications with debug=”true” enabled

One of the things you want to avoid when deploying an ASP.NET application into production is to accidentally (or deliberately) leave the switch on within the application’s web.config file.
Doing so causes a number of non-optimal things to happen including:

1) The compilation of ASP.NET pages takes longer (since some batch optimizations are disabled)

2) Code can execute slower (since some additional debug paths are enabled)

3) Much more memory is used within the application at runtime

4) Scripts and images downloaded from the WebResources.axd handler are not cached

This last point is particularly important, since it means that all client-javascript libraries and static images that are deployed via WebResources.axd will be continually downloaded by clients on each page view request and not cached locally within the browser. This can slow down the user experience quite a bit for things like Atlas, controls like TreeView/Menu/Validators, and any other third-party control or custom code that deploys client resources. Note that the reason why these resources are not cached when debug is set to true is so that developers don’t have to continually flush their browser cache and restart it every-time they make a change to a resource handler (our assumption is that when you have debug=true set you are in active development on your site).

When is set, the WebResource.axd handler will automatically set a long cache policy on resources retrieved via it – so that the resource is only downloaded once to the client and cached there forever (it will also be cached on any intermediate proxy servers). If you have Atlas installed for your application, it will also automatically compress the content from the WebResources.axd handler for you when is set – reducing the size of any client-script javascript library or static resource for you (and not requiring you to write any custom code or configure anything within IIS to get it).

Model View Controller Pattern


Luckily, the ASP.NET team has been listening to developers like me and has started development of a new Web application framework that sits side-by-side with the Web Forms you know and love but has a distinctly different set of design goals:

* Embrace HTTP and HTML—don't hide it.
* Testability is built-in from the ground up.
* Extensible at almost every point.
* Total control over your output.

This new framework is based around the Model View Controller (MVC) pattern, thus the name, ASP.NET MVC. The MVC pattern was originally invented back in the '70s as part of Smalltalk. As I'll show in this article, it actually fits into the nature of the Web quite well. MVC divides your UI into three distinct objects: the controller, which receives and handles input; the model, which contains your domain logic; and the view, which generates your output. In the context of the Web, the input is an HTTP request, and the request flow looks like Figure
above

This is actually quite different from the process in Web Forms. In the Web Forms model, the input goes into the page (the View), and the view is responsible for both handling the input and generating the output. When it comes to MVC, on the other hand, the responsibilities are separated.

Building Web Apps without Web Forms

Click Here

Friday, September 5, 2008

Insert Values into an Identity Column

Identity columns are commonly used as primary keys in database tables. These columns automatically assign a value for each new row inserted.

use tempdb
GO
IF OBJECT_ID('IdentityTable') IS NOT NULL
DROP TABLE IdentityTable
GO
CREATE TABLE IdentityTable (
TheIdentity INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
TheValue NVARCHAR(20) NOT NULL )
GO

Simply trying to INSERT a value into the identity column generates an error:

INSERT IdentityTable(TheIdentity, TheValue)
VALUES (1, 'First Row')
GO

Msg 544, Level 16, State 1, Line 3
Cannot insert explicit value for identity column in table 'IdentityTable' when IDENTITY_INSERT is set to OFF.

The trick is to enable IDENTITY_INSERT for the table. That looks like this:

SET IDENTITY_INSERT IdentityTable ON

INSERT IdentityTable(TheIdentity, TheValue)
VALUES (3, 'First Row')

SET IDENTITY_INSERT IdentityTable OFF

Here are some key points about IDENTITY_INSERT

* It can only be enabled on one table at a time. If you try to enable it on a second table while it is still enabled on a first table SQL Server will generate an error.
* When it is enabled on a table you must specify a value for the identity column.
* The user issuing the statement must own the object, be a system administrator (sysadmin role), be the database owner (dbo) or be a member of the db_ddladmin role in order to run the command.

If you insert a value greater than the current identity seed SQL Server uses the value to reset the identity seed. For example:

SET IDENTITY_INSERT IdentityTable ON

INSERT IdentityTable(TheIdentity, TheValue)
VALUES (10, 'Row Ten')

SET IDENTITY_INSERT IdentityTable OFF

INSERT IdentityTable(TheValue)
VALUES ('Should be 11')

SELECT * FROM IdentityTable
GO

(1 row(s) affected)

(1 row(s) affected)
TheIdentity TheValue
----------- --------------------
10 Row Ten
11 Should be 11

(2 row(s) affected)