Thursday, November 6, 2008

Resize image

private System.Drawing.Image ResizeToMaxSize(System.Drawing.Image image, int maxWidth, int maxHeight, float xDpi, float yDpi)
{

if (image == null)
{
return image;
}
int width = image.Width;
int height = image.Height;

double widthFactor = (Convert.ToDouble(width) / Convert.ToDouble(maxWidth));
double heightFactor = (Convert.ToDouble(height) / Convert.ToDouble(maxHeight));

if (widthFactor < 1 && heightFactor < 1)
{
// Skip resize
return image;
}
else
{
int newWidth;
int newHeight;
if (widthFactor > heightFactor)
{
newWidth = Convert.ToInt32(Convert.ToDouble(width) / widthFactor);
newHeight = Convert.ToInt32(Convert.ToDouble(height) / widthFactor);
}
else
{
newWidth = Convert.ToInt32(Convert.ToDouble(width) / heightFactor);
newHeight = Convert.ToInt32(Convert.ToDouble(height) / heightFactor);
}

Bitmap bitmap = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);
bitmap.SetResolution(xDpi, yDpi);

Graphics graphics = Graphics.FromImage(bitmap);
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
image.Dispose();
return bitmap;
}
}

Friday, September 26, 2008

Upgrade varbinary(max) to varbinary(max) FILESTREAM

Code Snippet

-- Initial schema:

CREATE TABLE [dbo].[Pictureimage](

[PictureId] [uniqueidentifier] NOT NULL,

[Image] [varbinary](max) NOT NULL,

[OriginalImage] [varbinary](max) NOT NULL,

[Version] [timestamp] NOT NULL,

CONSTRAINT [PK_Pictureimage] PRIMARY KEY CLUSTERED

(

[PictureId] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]

-- Attach 90 db…

-- Set Comp level

EXEC sp_dbcmptlevel Amigo, 100;

GO

-- Create FILESTREAM filegroup

ALTER database Amigo

ADD FILEGROUP fsfg_Amigo

CONTAINS FILESTREAM

GO

--Add a file for storing database photos to FILEGROUP

ALTER database Amigo

ADD FILE

(

NAME= 'fs_Amigo',

FILENAME = 'C:\fs_Amigo'

)

TO FILEGROUP fsfg_Amigo

GO

-- Migration to FILESTREAM

ALTER TABLE dbo.PictureImage

SET ( FILESTREAM_ON = fsfg_Amigo )

GO

ALTER TABLE dbo.PictureImage

ALTER COLUMN PictureId ADD ROWGUIDCOL

GO

ALTER TABLE dbo.PictureImage

ADD OriginalImageFS varbinary(MAX) FILESTREAM NULL;

GO

UPDATE dbo.PictureImage SET OriginalImageFS = [OriginalImage];

GO

ALTER TABLE dbo.PictureImage

DROP COLUMN OriginalImage;

GO

EXEC sp_rename 'AmigoProd.dbo.PictureImage.OriginalImageFS', 'OriginalImage', 'COLUMN';

GO

Monday, September 15, 2008

Recive PostSubmitter

if (Request.HttpMethod == "POST")
{
Stream dataStream = Request.InputStream;
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
string[] splittempQuery = responseFromServer.Split(("&").ToCharArray());
for (int i = 0; i < splittempQuery.Length; i++)
{
string[] qryValues = splittempQuery[i].Split(("=").ToCharArray());
if (qryValues[0].ToLower() == "op")
{
string aa = qryValues[1].ToString();
}
else if (qryValues[0].ToLower() == "rel_code")
{
string aa = qryValues[1].ToString();
}
else if (qryValues[0].ToLower() == "FREE_TEXT")
{
string aa = qryValues[1].ToString();
}
else if (qryValues[0].ToLower() == "SEARCH")
{
string aa = qryValues[1].ToString();
}
}
reader.Close();
dataStream.Close();
}

call postsubmitter

PostSubmitter post = new PostSubmitter();
post.Url = url;
post.PostItems.Add("op", "100");
post.PostItems.Add("rel_code", "1102");
post.PostItems.Add("FREE_TEXT", "c# jobs");
post.PostItems.Add("SEARCH", "");
post.Type = PostSubmitter.PostTypeEnum.Post;
string result = post.Post();

Http Post Post Submiter

public class PostSubmitter
{
///
/// determines what type of post to perform.
///
public enum PostTypeEnum
{
///
/// Does a get against the source.
///
Get,
///
/// Does a post against the source.
///
Post
}

private string m_url = string.Empty;
private NameValueCollection m_values = new NameValueCollection();
private PostTypeEnum m_type = PostTypeEnum.Get;
///
/// Default constructor.
///
public PostSubmitter()
{
}

///
/// Constructor that accepts a url as a parameter
///
///The url where the post will be submitted to.
public PostSubmitter(string url)
: this()
{
m_url = url;
}

///
/// Constructor allowing the setting of the url and items to post.
///
public PostSubmitter(string url, NameValueCollection values)
: this(url)
{
m_values = values;
}

///
/// Gets or sets the url to submit the post to.
///
public string Url
{
get
{
return m_url;
}
set
{
m_url = value;
}
}
///
/// Gets or sets the name value collection of items to post.
///
public NameValueCollection PostItems
{
get
{
return m_values;
}
set
{
m_values = value;
}
}
///
/// Gets or sets the type of action to perform against the url.
///
public PostTypeEnum Type
{
get
{
return m_type;
}
set
{
m_type = value;
}
}
///
/// Posts the supplied data to specified url.
///
string Post()
{
StringBuilder parameters = new StringBuilder();
for (int i = 0; i < result =" PostData(m_url,">
string Post(string url)
{
m_url = url;
return this.Post();
}
string Post(string url, NameValueCollection values)
{
m_values = values;
return this.Post(url);
}
string PostData(string url, string postData)
{
HttpWebRequest request = null;
if (m_type == PostTypeEnum.Post)
{
Uri uri = new Uri(url);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}
}
else
{
Uri uri = new Uri(url + "?" + postData);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
}
string result = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
return result;
}
void EncodeAndAddItem(ref StringBuilder baseRequest, string key, string dataItem)
{
if (baseRequest == null)
{
baseRequest = new StringBuilder();
}
if (baseRequest.Length != 0)
{
baseRequest.Append("&");
}
baseRequest.Append(key);
baseRequest.Append("=");
baseRequest.Append(System.Web.HttpUtility.UrlEncode(dataItem));
}
}

Friday, September 5, 2008

SMO Backup DB

// Delete the Preview directory
if ( Directory.Exists(previewAssetUnc + @"\" + studioCode) )
{
Directory.Delete(previewAssetUnc + @"\" + studioCode, true);
}

// Delete the Master Asset Backup directory
if ( Directory.Exists(backupUnc + @"\Masters\" + studioCode) )
{
Directory.Delete(backupUnc + @"\Masters\" + studioCode, true);
}

// Delete the Import directory
if ( Directory.Exists(importUnc + @"\" + studioCode) )
{
Directory.Delete(importUnc + @"\" + studioCode, true);
}

SMO Delete DB

// Kill the Studio DB
server.KillDatabase(dbName);

// Delete the Master Asset directory
if ( Directory.Exists(masterAssetUnc + @"\" + studioCode) )
{
Directory.Delete(masterAssetUnc + @"\" + studioCode, true);
}


// Delete the Preview directory
if ( Directory.Exists(previewAssetUnc + @"\" + studioCode) )
{
Directory.Delete(previewAssetUnc + @"\" + studioCode, true);
}

// Delete the Master Asset Backup directory
if ( Directory.Exists(backupUnc + @"\Masters\" + studioCode) )
{
Directory.Delete(backupUnc + @"\Masters\" + studioCode, true);
}

// Delete the Import directory
if ( Directory.Exists(importUnc + @"\" + studioCode) )
{
Directory.Delete(importUnc + @"\" + studioCode, true);
}

SMO Clean DB

string dbServerMachineName = dataSource;

Server server = new Server(dbServerMachineName);
Database db = server.Databases["sampleDBName"];

StringCollection tables = new StringCollection();
// Clean log data
tables.Add("SampleTable");


// Drops FK's
int dropCount = 0;
StringCollection script = new StringCollection();
for ( int i = 0; i < tables.Count; i++ )
{
try
{
if ( i == 43 )
{
string x = null;
}
Table table = db.Tables[tables[i], "Sample"];
for ( int j = 0; j < table.ForeignKeys.Count; j++ )
{
string[] fkScript = new string[table.ForeignKeys[j].Script().Count];
table.ForeignKeys[j].Script().CopyTo(fkScript, 0);
script.AddRange(fkScript);
table.ForeignKeys[j].MarkForDrop(true);
dropCount++;
}
table.Alter();
}
catch ( Exception ex )
{
throw ex;
}
}

// Truncate data
SqlServerController sqlServerController = new SqlServerController(dbServerMachineName);
for ( int i = 0; i < tables.Count; i++ )
{
sqlServerController.CleanTable(dbPrefix + studioCode + dbSuffix, tables[i], "Sample");
}

// Recreate FK's
for ( int i = 0; i < script.Count; i++ )
{
script[i] = script[i].Replace("REFERENCES", "REFERENCES[Sample].");
}
db.ExecuteNonQuery(script);

// Delete asset delivery files
if ( options.DeleteAssetFiles )
{
DirectoryInfo masterAssetDir = new DirectoryInfo(masterAssetUnc + @"\" + studioCode);
masterAssetDir.Delete(true);
masterAssetDir.Create();
}

// Rebuild Indexes
for ( int i = 0; i < tables.Count; i++ )
{
db.Tables[i].RebuildIndexes(0);
}

// Shring DB
db.Shrink(0, ShrinkMethod.Default);

SMO Detach Attach DataBase Sample

SqlConnection sqlConn = new SqlConnection(refDBConnectionString);
Server server = new Server(sqlConn.DataSource);
Database refDB = server.Databases[sqlConn.Database];
string refDBFilename = refDB.FileGroups[0].Files[0].FileName;
string refDBLogFilename = refDB.LogFiles[0].FileName;
string templateDBUnc = systemUnc + @"\SampleTemplate.mdf";
string templateDBLogUnc = systemUnc + @"\SampleTemplate.ldf";

// Detach Reference DB
server.DetachDatabase(sqlConn.Database, true);

// Copy and attach temp DB
FileInfo refDBUncFile = new FileInfo(refDBUnc);
string tempDBUnc = refDBUncFile.Directory.FullName + @"\SampleTempDev.mdf";
string tempDBLogUnc = refDBUncFile.Directory.FullName + @"\SampleTempDev.ldf";
File.Copy(refDBUnc, tempDBUnc, true);
File.Copy(refDBLogUnc, tempDBLogUnc, true);

// Re-attach the Reference DB
StringCollection refDBFiles = new StringCollection();
refDBFiles.Add(refDBFilename);
refDBFiles.Add(refDBLogFilename);
server.AttachDatabase(sqlConn.Database, refDBFiles);

URL to refer

website developer tool:-
http://www.ironspeed.com/products/Landing.aspx?c=AspAlliance

busroot:-
http://www.madras2chennai.co.in/busroutes.asp?flag=1&source=CHROMPET&destination=FORE%20SHORE%20ESTATE

missed cals:-
http://mobilecodes.blogspot.com/2007/07/tata-indicom2-tata-indicom1.html

fanbox.com rrrajesh84in@gmail.com(normaPswd)

online status
http://www.onlinestatus.org/node/6

yahooOnline link
http://forum.mosets.com/archive/index.php/t-624.html

Chat bots:-
http://vijaymodi.wordpress.com/2007/06/20/aim-yahoo-msn-icq-chat-bots/

project:-
http://cutesoft.net/downloads/folders/operator_client/default.aspx

copysite
www.copyscape.com

free sms
http://www.atrochatro.com/send_free_sms_india.html

VisualStudio Short cut keys
http://www.codinghorror.com/blog/files/Visual%20Studio%20.NET%202005%20Keyboard%20Shortcuts.htm

microsoft surface new technology
http://www.popularmechanics.com/technology/industry/4217348.html
http://www.microsoft.com/surface/

myspace
venkat_pdi@hotmail.com
cutting@12

send SMS
http://www.sendsmsnow.com/send.php?newid=2906449

javaScript numbers in Words RS:
http://javascript.internet.com/miscellaneous/number-pronunciator.html

popupwindow
http://www.quirksmode.org/js/popup.html

popwindow without frame
http://www.codelifter.com/main/javascript/amazingframelesspopup1.html

jscript:
http://docs.sun.com/source/816-6408-10/window.htm#1202731

popup
http://www.codeproject.com/aspnet/asppopup.asp

popup help Window.open msdn
http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/methods/open_0.asp

javaScript numbers in Words RS:
http://www.jsindir.com/goster/679

popup window Movable
http://www.codeproject.com/useritems/ASPNet_User_Control_Pops.asp

three tired architecture
http://www.asp.net/learn/dataaccess/default.aspx?tabid=63

file upload
http://www.stardeveloper.com/articles/display.html?article=2002022201&page=1

msdnupload download
http://msdn2.microsoft.com/en-us/library/aa446517.aspx

fileipload
http://www.codeproject.com/aspnet/fileupload.asp#form
http://www.codeproject.com/aspnet/FileUploadManager.asp
http://www.codeproject.com/Ajax/AJAXUpload.asp

fileupload with check extension
http://msdn2.microsoft.com/en-us/library/aa479405.aspx#uploadasp2_topic2


convert to swf
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=374250&SiteID=1

http://www.geovid.com/Video_to_Flash_Converter/
http://www.softplatz.com/software/video-to-flash/

http://www.vicman.net/lib/vb/netcconvert

resize picture
http://forums.asp.net/3/1403764/ShowThread.aspx



xml basic
http://www.c-sharpcorner.com/UploadFile/mahesh/ReadWriteXMLTutMellli2111282005041517AM/ReadWriteXMLTutMellli21.aspx

xml in grid
http://stardeveloper.com/articles/display.html?article=2002022801&page=1


cookie sample:-
http://www.codeproject.com/Purgatory/cookies_in_c_.asp

session sample:-
http://www.zdnetasia.com/builder/architect/db/0,39044553,39197925,00.htm

captcha:-

http://www.codeproject.com/aspnet/CaptchaLIKE.asp

create folder
http://www.aspcode.net/articles/l_en-US/t_default/.NET/Ensure-a-directory-exists-(otherwise-create-folders)-in-C__article_361.aspx

panel control
http://www.google.co.in/search?hl=en&client=firefox-a&channel=s&rls=org.mozilla%3Aen-US%3Aofficial&q=Adrotater+control+asp.net+c%23&btnG=Search&meta=

adrotator:-
http://www.codeproject.com/aspnet/AdRotator_VT.asp
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/standard/adrotator.aspx

rating control
http://www.codeproject.com/useritems/AjaxRating.asp

_____________________________________________________________________
validation
http://www.dotnetspider.com/kb/Article2862.aspx

super:
http://psacake.com/web/jb.asp

dateFromat
works Fine:
http://www.smartwebby.com/DHTML/date_validation.asp#explanation

probs:
http://www.mattkruse.com/javascript/date/source.html
____________________________________________________________________________

jscript age calculation
http://snippets.dzone.com/rss/tag/age

c# days calculation
http://tommycarlier.blogspot.com/2006/02/years-months-and-days-between-2-dates.html


Ajax SetFocus problem
http://forums.asp.net/p/1050223/1482124.aspx#1482124

Asp.Net Help FormView
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/data/formview.aspx

xml Serialization
http://72.14.235.104/search?q=cache:hhqIVr9aSfsJ:www.topxml.com/xmlserializer/serializer.PDF+XmlArrayAttribute+should+be+bind+dynamically+in+C%23&hl=en&ct=clnk&cd=3&gl=in

document reader
http://static.scribd.com/docs/7nefuc8admthv.swf

how to change the first character of textbox to uppercase while typing?
http://www.dotnetspider.com/qa/Question25040.aspx

thread
http://msdn2.microsoft.com/en-us/library/ms173179(VS.80).aspx


----------------------------------------------------------------------------------------------------------------------------

Find script src path
----------------------------------------------------------------------------------------------------------------------------

http://feather.elektrum.org/book/src.html

Ex...

var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];

alert(myScript.src);

----------------------------------------------------------------------------------------------------------------------------

URL's to refer

voice recoder Asp.net c#
http://www.dotnetspider.com/code/C-470-How-record-voice-from-microphone.aspx
http://www.vimas.com/wav.php

vb to C# converter
http://www.carlosag.net/Tools/CodeTranslator/default.aspx

free sms
http://www.atrochatro.com/send_free_sms_india.html

joke mobile tracking
:-
http://www.sat-gps-locate.com/


world map:-
http://www.tonec.com/products/acim/samples/s12.html?text1=India

lost mobile tracker samsung:- http://www.lossproofmobiles.com/index.asp
Entertainment:-
free Cursor:-http://cursormania.smileycentral.com/download/index.jhtml?partner=ZCxdm490&spu=true&ref=http%3A//as.casalemedia.com/s%3Fs%3D56757%26u%3Dhttp%253A//www.functionx.com/vcsharp/index.htm%26f%3D2%26id%3D8044481776.326072
My logo:- http://in.mobile.yahoo.com/new/name/
my logo editor:- http://in.mobile.yahoo.com/new/ol/


c# beginers :- ( http://www.csharphelp.com/archives2/archive402.html )
http://msdn.microsoft.com/vstudio/express/visualcsharp/learning/default.aspx#beginners



turorial http://msdn2.microsoft.com/en-us/vcsharp/aa336809.aspx )


http://samples.gotdotnet.com/quickstart/aspplus/

http://abstractvb.com/code.asp?A=1006

http://www.w3schools.com/webservices/default.asp

" http://samples.gotdotnet.com/quickstart/aspplus/doc/writingservices.aspx "

http://www.developerfusion.co.uk/show/3114/3/

http://www.developerfusion.co.uk/show/3114/5/

" http://www.codeproject.com/webservices/aspwebsvr.asp "

http://www.exforsys.com/content/view/1380/266/




Database:-
http://www.sitepoint.com/article/net-web-services-5-steps

task1-creating P/Invoke

http://msdn2.microsoft.com/en-us/library/aa446550.aspx
coding C:\Program Files\.NET Compact Framework Samples\PInvoke Library\Code\CS )


extra
http://msdn2.microsoft.com/en-us/library/aa446494.aspx

Delegate:-
" http://www.programmersheaven.com/articles/faisal/delegates.htm "


task2-GUID generator:-
( http://www.microsoft.com/downloads/details.aspx?FamilyID=aebc434c-14bc-409f-8537-43c711a0bf1e&DisplayLang=en )
coding-( C:\Program Files\.NET Compact Framework Samples\.NET Compact Framework-based Guid Generator Sample\ )


reading XML:-
http://abstractvb.com/code.asp?A=976

writing XML:-
http://abstractvb.com/code.asp?A=977

xml
http://www.c-sharpcorner.com/UploadFile/mahesh/ReadWriteXMLTutMellli2111282005041517AM/ReadWriteXMLTutMellli21.aspx

ajax get start:-
http://ajax.asp.net/docs/tutorials/CreateSimpleAJAXApplication.aspx

task3-foto vision
http://msdn2.microsoft.com/en-us/library/aa446509.aspx
fotovison for web exe;-( http://pdi-wks-c03/FotoVisionVB/album.aspx?album=Land )

cant convert pocketpc fotovisionvb.net-
http://www.elegancetech.com/CSVB_ConvertedLOC.aspx

iframe:
http://msdn.microsoft.com/library/default.asp?url=/workshop/author/om/measuring.asp?frame=true

cursor position:-
http://msdn2.microsoft.com/en-us/library/system.windows.forms.cursor.position(VS.80).aspx


xml to c# class file converter

http://www.canerten.com/xml-c-class-generator-for-c-using-xsd-for-deserialization/


javascript image dragger

http://www.walterzorn.com/dragdrop/dragdrop_e.htm

X,Y positon in C#

this.listBox1.Location = new System.Drawing.Point(8, 16);
http://www.daniweb.com/code/snippet182.html


resize array length

http://www.dotnetspider.com/namespace/ShowClass.aspx?ClassId=7

Zip and UnZip a file
http://aspalliance.com/1269_Zip_and_UnZip_files_in_C_using_J_libraries.2

Dynamic Master Page
//private void Page_PreInit(object sender, EventArgs e)
//{
// this.MasterPageFile = "~/Site.master";
//}

hit server side on TextBox KeyPress
searchTextBox.Attributes.Add("OnKeyPress", this.GetPostBackEventReference(searchTextBox, "CallSpecialCSharpMethod"));

if (this.IsPostBack)
{
string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ?
string.Empty : this.Request["__EVENTARGUMENT"];

if (eventArgument.Trim() == "CallSpecialCSharpMethod")
{
SearchText();
}
}

keypress event after stop typing
http://www.selfcontained.us/category/javascript/

codegoogle
http://code.google.com/apis/maps/documentation/overlays.html#Tile_Layer_Overlays
http://www.codeproject.com/KB/scripting/Use_of_Google_Map.aspx
http://en.googlemaps.subgurim.net/ejemplos/ejemplo_250_Tipo-de-mapa.aspx



WCF
______
http://wcf.netfx3.com/content/TheFutureofASPNETWebServicesintheContextoftheWindowsCommunicationFoundation.aspx
http://dotnetslackers.com/WSE/re-42694_How_To_Hosting_a_WCF_Service_in_IIS.aspx


asp.net3.5 ajax:
http://www.componentart.com/webui/demos/demos_control-specific/calendar/features/date_rangePicker/WebForm1.aspx


LINQ : -

http://krisvandermotten.wordpress.com/2006/11/30/creating-a-data-access-layer-with-linq-to-sql-part-2/

http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

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

SMO(Sql Server Management Object) User Creation

Server _server = new Server(new ServerConnection(new SqlConnection("Data Source=xxxx;Initial Catalog=Demo3Dev;Persist Security Info=True;User ID=sa;Password=xxxx")));

Microsoft.SqlServer.Management.Smo.Login newlogin = new Microsoft.SqlServer.Management.Smo.Login(_server, "Demo3Dev"); //Specified the server (.) and the LoginName (MyUserAccount)
newlogin.DefaultDatabase = "Demo3Dev"; //Choose the default Database for the user.
newlogin.LoginType = LoginType.SqlLogin; //Choose the SQLServer Login
newlogin.Create("xxxx"); // User was created here

User _user = new User(_server.Databases["Demo3Dev"], "Demo3Dev");
_user.Login = "Demo3Dev";
_user.Create();

Random Word Generation

string schars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
string name = string.Empty;
Random rand = new Random(DateTime.Now.Millisecond);
while (name.Length < 6)
name += schars[rand.Next(0, schars.Length)];

load in DataGrid general connection string C#

if(!Page.isPostBack())
{
string connectionstring =ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString;
SqlConnection myconnection = new mysqlconnection();
Dataset ds = new Dataset();
SqlAdapter as = new SqlAdapter("Select * from emp",MyConnection);
ds.fill(as);
Datagrid.Datasource= ds;
Datagrid.Databind();
}
if(!Ispostback)
{
String Connectionstring =(string)ConfigurationSection.AppSettings["ConnectionString"];
SqlConnection myconnection = new mysQlConnection();
sqlCommand cmd = new sqlcommand("select * from emp",Myconnection);
SqlDatareader dr = null;
dr = cmd.executereader();
datagrid.Datasource= dr;
datagrid.databind();



}

Send SPName and Parameters

public DataTable GeneralWithConnection(string argStrQuery, string[] arguments, string[] argumentNames)
{
DataTable detailDataTable = new DataTable();
using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
{
if (arguments.Length == argumentNames.Length)
{
SqlConnection myConnection = GetConnection();
myConnection.Open();
SqlCommand objComm = new SqlCommand(argStrQuery, myConnection);
objComm.CommandType = CommandType.StoredProcedure;
for (int i = 0; i < arguments.Length; i++)
{
objComm.Parameters.Add(new SqlParameter(argumentNames[i], arguments[i]));
}
SqlDataAdapter da = new SqlDataAdapter(objComm);
DataSet ds = new DataSet();
da.Fill(ds);

objComm.Dispose();
myConnection.Close();
if (ds.Tables.Count > 0)
{
detailDataTable = ds.Tables[0];
}
}
scope.Complete();
}
return detailDataTable;
}

Resize Image C#

public void ResizeFromStream(string sourFilePath, int MaxSideSize, string destFilePath)
{
System.Drawing.Image imgInput = System.Drawing.Image.FromFile(sourFilePath);
int intNewWidth;
int intNewHeight;

//Determine image format
ImageFormat fmtImageFormat = imgInput.RawFormat;

//get image original width and height
int intOldWidth = imgInput.Width;
int intOldHeight = imgInput.Height;

//determine if landscape or portrait
int intMaxSide;

if (intOldWidth >= intOldHeight)
{
intMaxSide = intOldWidth;
}
else
{
intMaxSide = intOldHeight;
}
if (intMaxSide > MaxSideSize)
{
//set new width and height
double dblCoef = MaxSideSize / (double)intMaxSide;
intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
}
else
{
intNewWidth = intOldWidth;
intNewHeight = intOldHeight;
}
//create new bitmap
Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);

bmpResized.Save(destFilePath, ImageFormat.Jpeg);
}

Monday, July 7, 2008

InsertSpaceInString JS

function InsertSpaceInString(textWithoutSpace,size,controlName)
{
var controlToBind = document.getElementById(controlName);
var textWithSpace = "";
var temp = textWithoutSpace.split(" ");
//alert(textWithoutSpace);
for (var i = 0; i < spliter = "" remaining = ""> size)
{
var loopCount = temp[i].length / size;
remaining = temp[i];
for (var j = 1; j <= loopCount; j++) { var a = remaining.substring(0, size); remaining = remaining.substring((size)); spliter = spliter + a + " "; } temp[i] = spliter + remaining; } textWithSpace = " " + textWithSpace + temp[i] + " "; } if (textWithSpace.length > 0)
{
var temperorary = textWithSpace.trim();
textWithSpace = temperorary;
}
controlToBind.innerHTML = textWithSpace;
}

ValidTime JS

function isValidTime(timeStr, timeValue)
{
var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AMamPMpm))?$/;
var matchArray = timeStr.match(timePat);
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];
if (matchArray == null)
{
alert("Time is not in a valid format.");
timeValue.select();
timeValue.focus();
return false;
}
if (second=="")
{
second = null;
}
if (ampm=="")
{
ampm = null
}
if (hour <> 23)
{
alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
timeValue.select();
timeValue.focus();
return false;
}
if (hour <= 12 && ampm == null)
{
if (confirm("Please indicate which time format you are using. OK = Standard Time, CANCEL = Military Time"))
{
alert("You must specify AM or PM.");
timeValue.select();
timeValue.focus();
return false;
}
}
if (hour > 12 && ampm != null)
{
alert("You can't specify AM or PM for military time.");
timeValue.select();
timeValue.focus();
return false;
}
if (minute<0> 59)
{
alert ("Minute must be between 0 and 59.");
timeValue.select();
timeValue.focus();
return false;
}
if (second != null && (second <> 59))
{
alert ("Second must be between 0 and 59.");
timeValue.select();
timeValue.focus();
return false;
}
return true;
}

Time Validation JS

//Time Validation
/* This function validate time in the format of HH:MM:SS AP/PM. The argument timeValue is the id of the textbox.
The argument required defines whether this field is either optionsl or not. It allows time in two formats.
One is Railway time format(does not contain AM or PM) and another is normal. */
function validateTime(timeValue, required)
{
var timeStr = timeValue.value;
var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AMamPMpm))?$/;
if(required == true)
{
if(timeStr == '' timeStr == "" timeStr == null)
{
alert("Enter the time");
timeValue.select();
timeValue.focus();
return false;
}
else
{
if(timeStr.match(timePat))
{
var s = isValidTime(timeStr, timeValue)
return s;
}
else
{
alert("Enter the time in the correct format");
timeValue.select();
timeValue.focus();
return false;
}
}
}
else
{
if(timeStr == '' timeStr == "" timeStr == null)
{
return true;
}
else
{
if(timeStr.match(timePat))
{
var s = isValidTime(timeStr, timeValue)
return s;
}
else
{
alert("Enter the time in the correct format");
timeValue.select();
timeValue.focus();
return false;
}
}
}
}

Allows Symbols JS

//This Allows Symbols only
/*The argument strText is the id of the textbox. This allows only symbols without text or numbers.*/
function symbolOnly(strText)
{
var str = strText.value;
//var format = /[^a-zA-Z0-9]+$/;
var format = /^[^0-9a-zA-Z]+$/;
if(str == "" str == null str == '')
{
alert("Enter any symbols");
strText.focus();
strText.select();
return false;
}
else
{
if(str.match(format))
{
return true;
}
else
{
alert("Enter Only Symbols");
strText.select();
strText.focus();
return false;
}
}
}

Only texts are allowed (a to z or A-Z). JS

/* Only texts are allowed (a to z or A-Z). The argument strValue is the id of the textbox.The argument required
defines the field is either optional or not. It takes the value of either true or false. The argument errorSpanID
is the id of the errorSpan
*/
function textOnly(controlID, required, errorSpanID)
{
var strValue = document.getElementById(controlID);
var errorSpan = document.getElementById(errorSpanID);
errorSpan.innerHTML = "";
var str = strValue.value;
var format = /^[A-Za-z]+$/;
if(required == true)
{
if(str == '' str == null str == "")
{
errorSpan.innerHTML = "Enter the Text";
strValue.focus();
strValue.select();
return false;
}
else
{
if (str.match(format))
{
return true;
}
else
{
errorSpan.innerHTML = "Invalid Text";
strValue.focus();
strValue.select();
return false;
}
}
}
else if(required == false)
{
if(str== '' str == null str == "")
{
return true;
}
else
{
if(str.match(format))
{
return true;
}
else
{
errorSpan.innerHTML = "Invalid Text";
strValue.focus();
strValue.select();
return false;
}
}
}
}

checkInternationalPhone,stripCharsInBag,isInteger JS

function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
var c = s.charAt(i);
if (((c < "0") (c > "9"))) return false;
}
return true;
}
function stripCharsInBag(s, bag)
{ var i;
var returnString = "";
for (i = 0; i < s.length; i++)
{
var c = s.charAt(i);
if (bag.indexOf(c) == -1)
returnString += c;
}
return returnString;
}
function checkInternationalPhone(strPhone)
{
var phoneNumberDelimiters = "()- ";
var validWorldPhoneChars = phoneNumberDelimiters + "+";
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= 10);
}

Phone number validation js

// Phone number validation
/*It validates the phone number in international level. The argument PhoenNumber is the id of textbox. PhoneNumber
must contain a minimum of 10 digits. checkRequired defines that it is either optional or must. */
function ValidatePhoneNumber(PhoneNumber, checkRequired)
{
var Phone = PhoneNumber.value;
if(checkRequired == true)
{
if (Phone == null Phone == "" Phone == '')
{
alert("Please Enter your Phone Number")
PhoneNumber.select();
PhoneNumber.focus();
return false;
}
}
else
{
if(Phone == null Phone == '' Phone == "")
{
return true;
}
}
if (checkInternationalPhone(Phone) == false)
{
alert("Please Enter a Valid Phone Number");
PhoneNumber.select();
PhoneNumber.focus();
return false;
}
return true;
}

Date Validation JS

//Date Validation
/*It validate the date in MM/DD/YYYY format. the argument DateValue is the id of the textbox. required defines that
this field is to be filled not not. it takes two value. one is true (Must filled). false means optional.*/
function validateDate(DateValue, required)
{
var date = DateValue.value;
var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]1[02])(\/-\.)31)\1(?:(?:0?[1,3-9]1[0-2])(\/-\.)(?:2930)\2))(?:(?:1[6-9][2-9]\d)?\d{2})(?:0?2(\/-\.)29\3(?:(?:(?:1[6-9][2-9]\d)?(?:0[48][2468][048][13579][26])(?:(?:16[2468][048][3579][26])00))))(?:(?:0?[1-9])(?:1[0-2]))(\/-\.)(?:0?[1-9]1\d2[0-8])\4(?:(?:1[6-9][2-9]\d)?\d{2}))($\ (?=\d)))?(((0?[1-9]1[012])(:[0-5]\d){0,2}(\ [AP]M))([01]\d2[0-3])(:[0-5]\d){1,2})?$/;
if(required == true)
{
if(date == '' date == null date == "")
{
alert("Enter the Date");
DateValue.select();
DateValue.focus();
return false;
}
else
{
if (date.match(RegExPattern))
{
return true;
}
else
{
alert("Enter a valid date as mm/dd/yyyy");
DateValue.select();
DateValue.focus();
return false;
}
}
}
else
{
if(date == '' date == null date == "")
{
return true;
}
else
{
if (date.match(RegExPattern))
{
return true;
}
else
{
alert("Enter a valid date as mm/dd/yyyy");
DateValue.select();
DateValue.focus();
return false;
}
}
}
}

Check the Confirm Passwordfunction JS

//Check the Confirm Passwordfunction
ValidateConfirmPassword(text1,text2,spanID){ document.getElementById(spanID).innerHTML= ''; textElement1=document.getElementById(text1); textElement2=document.getElementById(text2); var txt1 = textElement1.value; var txt2 = textElement2.value; if ( txt1 != txt2) { document.getElementById(spanID).innerHTML= 'Verify your password again'; return false; } else { return true; }}

check the length of Text or Numbers JS

//check the length of Text or Numbers
function ValidateLength(txtText,minSize,maxSize,required,spanID,controlName)
{
txtElement=document.getElementById(txtText);
var txt = txtElement.value;
document.getElementById(spanID).innerHTML='';
if ( required == true)
{
if(txt == '' txt == null txt == "")
{
document.getElementById(spanID).innerHTML=controlName+" is required";
return false;
}
else
{
if ( minSize > 0)
{
if(txt.length < minSize)
{
document.getElementById(spanID).innerHTML= 'Minimum is ' + minSize+ ' characters';
return false;
}
else
{
if (maxSize > 0)
{
if(txt.length > maxSize)
{
document.getElementById(spanID).innerHTML= 'Maximum is ' + maxSize+ ' characters';
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
}
else
{
if (maxSize > 0)
{
if(txt.length > maxSize)
{
document.getElementById(spanID).innerHTML= 'Maximum is ' + maxSize+ ' characters';
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
}
}
else
{
if ( minSize > 0)
{
if(txt.length < minSize)
{
document.getElementById(spanID).innerHTML= 'Minimum is ' + minSize+ ' characters';
return false;
}
else
{
if (maxSize > 0)
{
if(txt.length > maxSize)
{
document.getElementById(spanID).innerHTML= 'Maximum is ' + maxSize+ ' characters';
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
}
else
{
if (maxSize > 0)
{
if(txt.length > maxSize)
{
document.getElementById(spanID).innerHTML= 'Maximum is ' + maxSize+ ' characters';
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
}
}

Validate Text JS

//Validate Text
/*Only Alpha Numeric characters are allowed. The argument txtText is the id of textbox. checkRequired means the field is necessary or not
(necessary maens true otherwise false). The argument checkLength means to check the length of the
text against the size. We must send the size if we send checkLength as true otherwise not necessary*/
function ValidateText(txtText, checkRequired, checkLength, size,spanID,controlName)
{
txtElement=document.getElementById(txtText);
var txt = txtElement.value;
var format = /^[A-Za-z0-9\s]+$/;
document.getElementById(spanID).innerHTML='';
if(checkRequired == true)
{
if(txt == "" txt == '' txt == null)
{
document.getElementById(spanID).innerHTML=controlName+' is required';
return false;
}
else
{
if(txt.match(format))
{
if(checkLength == true)
{
if(txt.length > size)
{
document.getElementById(spanID).innerHTML='Maximum is '+ size +' characters.';
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
else
{
document.getElementById(spanID).innerHTML='Invalid Characters';
return false;
}
}
}
else
{
if(txt == "" txt == '' txt == null)
{
return true;
}
else
{
if(txt.match(format))
{
if(checkLength == true)
{
if(txt.length > size)
{
document.getElementById(spanID).innerHTML= 'Maximum is '+ size +' characters.';
return false;
}
}
else
{
return true;
}
}
else
{
document.getElementById(spanID).innerHTML= 'Invalid Characters';
return false;
}
}
}
}

Validate Number JS

//Validate Number
/*Only Numbers are allowed. The argument number is the id of textbox. checkRequired means the field is necessary or not
(necessary maens true otherwise false). The argument checkLength means to check the length of the
number against the size. We must send the size if we send checkLength as true otherwise not necessary*/
function ValidateNumber(textElement, checkRequired, checkLength, size,spanID,controlName)
{
document.getElementById(spanID).innerHTML='';
textElement=document.getElementById(textElement);
var num = textElement.value;
var format = /^[0-9]+$/;
if(checkRequired == true)
{
if(num == "" num == '' num == null)
{
document.getElementById(spanID).innerHTML= controlName+' is required';
return false;
}
else
{
if(num.match(format))
{
if(checkLength == true)
{
if(num.length > size)
{
document.getElementById(spanID).innerHTML= 'Maximum is '+ size +' digits';
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
else
{
document.getElementById(spanID).innerHTML= 'Invalid Number';
return false;
}
}
}
else
{
if(num == "" num == '' num == null)
{
return true;
}
else
{
if(num.match(format))
{
if(checkLength == true)
{
if(num.length > size)
{
document.getElementById(spanID).innerHTML= 'Maximum is '+ size + ' digits';
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
else
{
document.getElementById(spanID).innerHTML= 'Invalid Number';
return false;
}
}
}
}

Mandatory fields validation JS

//Mandatory fields
function ValidateRequired(txtItem,spanID)
{
document.getElementById(spanID).innerHTML='';
txtItem=document.getElementById(txtItem);
var txt = txtItem.value;
if(txt == '' txt == null txt == "")
{
document.getElementById(spanID).innerHTML= "Value required";
return false;
}
else
{
return true;
}
}

Common validation for Email in JS

//E-Mail validation
/* mail is the id of text box. The argument required means the field is necessary or not. If we send the value
of true to required, It means this is a mendatory field otherwise this field is optional */
function ValidateEmail(mail,required,spanID)
{
document.getElementById(spanID).innerHTML='';
mail=document.getElementById(mail);
var email = mail.value;
var emailFormat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}(comnetorgeduintmilgovarpabizaeronamecoopinfopromuseum))$/;
if(required == true)
{
if(email == '' email == null email == "")
{
document.getElementById(spanID).innerHTML="Email is required";
return false;
}
else
{
if (!email.match(emailFormat))
{
document.getElementById(spanID).innerHTML="Invalid email address";
return false;
}
else
{
return true;
}
}
}
else
{
if(email == '' email == null email == "")
{
return true;
}
else
{
if (!email.match(emailFormat))
{
document.getElementById(spanID).innerHTML="Invalid Mail ID";
return false;
}
else
{
return true;
}
}
}
}

inside ajax :- Textbox on Key up hit Servercode

js:-

function SetKeyUp(e)
{
document.onkeyup = AssignKeyPress.interceptKeypress;
}


AssignKeyPress = {
interval : 200,
lastKeypress : null,
interceptKeypress : function(e) {
var key;
if (window.event) {
key = window.event.keyCode;
} else if (e) {
key = e.which;
}
var text = String.fromCharCode(key);
var format = /^([A-Za-z0-9\s])+$/;
//alert(AssignKeyPress.interval);
if(text.match(format))
{
AssignKeyPress.lastKeypress = new Date().getTime();
var that = AssignKeyPress;
setTimeout(function() {
var currentTime = new Date().getTime();
if(currentTime - that.lastKeypress > that.interval) {
that.sendRequest();
}
}, that.interval + 100);
}
else if(key == 8 key == 46)
{
AssignKeyPress.lastKeypress = new Date().getTime();
var that = AssignKeyPress;
setTimeout(function() {
var currentTime = new Date().getTime();
if(currentTime - that.lastKeypress > that.interval) {
that.sendRequest();
}
}, that.interval + 100);
}
},
sendRequest : function() {
__doPostBack('ctl00$SiteContentPlaceHolder$searchTextBox','SearchTextBoxKeyPress');
}

C#:-


if (this.IsPostBack)
{
string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];
if (eventArgument.Trim() == "SearchTextBoxKeyPress")
{
_setFocus = true;
SearchTextBoxKeyPress(selectTabHiddenField.Value);
}
else
{
_setFocus = false;
}
}

if (httpBrowserCapabilities.Browser == "Firefox")
{
searchTextBox.Attributes.Add("OnKeyUp", "SetKeyUp(this);");
}
else
{
searchTextBox.Attributes.Add("OnKeyUp", "AssignKeyPress.interceptKeypress(this);");
}

set focus issue in ajax

C#:-
(this.Master.FindControl("ScriptManager1") as System.Web.UI.ScriptManager).SetFocus(searchTextBox);

set cursor in end of the word in textbox firefox issue

js:-

function SetEnd(textBox)
{
if (textBox.createTextRange)
{
var fieldRange = textBox.createTextRange();
fieldRange.moveStart('character', textBox.value.length);
fieldRange.collapse();
fieldRange.select();
}
}
C#:-

HttpBrowserCapabilities httpBrowserCapabilities = new HttpBrowserCapabilities();

httpBrowserCapabilities = Request.Browser;

if (httpBrowserCapabilities.Browser != "Firefox")
{
searchTextBox.Attributes.Add("OnFocus", "SetEnd(this)");
}

email validation in javascript

function ValidateEmail(mail,spanID)
{
var email = mail;
var emailFormat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}(comnetorgeduintmilgovarpabizaeronamecoopinfopromuseum))$/;
if (!email.match(emailFormat))
{
document.getElementById(spanID).innerHTML = "Invalid Mail ID -"+mail;
}
}

hit the serverside event from javascript

JS:-
__doPostBack('ctl00$SiteContentPlaceHolder$searchTextBox','SearchTextBoxKeyPress');

C#:-
inside pageload

if (this.IsPostBack)
{
string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];
if (eventArgument.Trim() == "SearchTextBoxKeyPress")
{
_setFocus = true;
SearchTextBoxKeyPress(selectTabHiddenField.Value);
}
else
{
_setFocus = false;
}
}