Wednesday, August 13, 2008
Descending sortedList by value
class DescendingComparer : IComparer
{
public int Compare(object x, object y)
{
try
{
return System.Convert.ToInt32(x).CompareTo(System.Convert.ToInt32(y)) * -1;
}
catch (Exception ex)
{
return x.ToString().CompareTo(y.ToString());
}
}
}
class KeySortedList : SortedList
{
public SortedList ReversedList = new SortedList(new DescendingComparer());
public new void Add(object key, object value)
{
ReversedList.Add(value, key);
base.Add(key, value);
}
}
Thursday, August 07, 2008
Undefined function 'CONVERT' in expression issue in Office 12
eg,
Undefined function 'CONVERT' in expression "Crystal Reports"
CDATE({ERYTHROCYTE_SEDIMENTATION_RATE_HEADER.COLLECT_DATE}) >= cdate (2008, 07, 05)
to fix the problem, good luck
Monday, August 04, 2008
snapshot C# using PaintEventArgs
// Inside snapshot control ...
Rectangle rect = this.ClientRectangle;
//create an empty image with the same size of the control
Bitmap bmp = new Bitmap(rect.Width, rect.Height);
Graphics g = Graphics.FromImage(bmp);
PaintEventArgs p= new PaintEventArgs(g, rect);
// paint the background,
this.InvokePaintBackground(this, p);
// this will invoke the control paint method
this.InvokePaint(this, p);
Thursday, July 24, 2008
Sends the mail message asynchronously
{
ThreadStart threadStart = delegate { SendMailMessage(); };
Thread thread = new Thread(threadStart);
thread.Start();
}
Wednesday, July 23, 2008
?? operator in C#
string thisIsANull = null;
string thisIsANullCheck = thisIsANull ?? "";
thisIsANullCheck is set to ""
Friday, February 15, 2008
descending sorting in SortedList
internal class DescendingComparer : IComparer
{
public int Compare(object x, object y)
{
try
{
return System.Convert.ToInt32(x).CompareTo(System.Convert.ToInt32(y)) * -1;
}
catch (Exception ex)
{
return x.ToString().CompareTo(y.ToString());
}
}
}
SortedList membersList = new SortedList(new DescendingComparer());
membersList.Add()
Monday, January 21, 2008
Tuesday, November 20, 2007
easy way to make money !!
Friday, October 26, 2007
Tuesday, October 23, 2007
How to write settings to App.config(Configuration in C# .NET 2.0)
config.AppSettings.Settings["IP"].Value = "3";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
yeap this is the microsoft example. doesn't work at all. !!! dont get caught this never works. I was trying hours and hours,
use this class .
public enum ConfigFileType
{
WebConfig,
AppConfig
}
public class AppConfig : System.Configuration.AppSettingsReader
{
public string docName = String.Empty;
private XmlNode node = null;
private int _configType;
public int ConfigType
{
get
{
return _configType;
}
set
{
_configType = value;
}
}
public bool SetValue(string key, string value)
{
XmlDocument cfgDoc = new XmlDocument();
loadConfigDoc(cfgDoc);
// retrieve the appSettings node
node = cfgDoc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new System.InvalidOperationException("appSettings section not found");
}
try
{
// XPath select setting "add" element that contains this key
XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (addElem != null)
{
addElem.SetAttribute("value", value);
}
// not found, so we need to add the element, key and value
else
{
XmlElement entry = cfgDoc.CreateElement("add");
entry.SetAttribute("key", key);
entry.SetAttribute("value", value);
node.AppendChild(entry);
}
//save it
saveConfigDoc(cfgDoc, docName);
return true;
}
catch
{
return false;
}
}
private void saveConfigDoc(XmlDocument cfgDoc, string cfgDocPath)
{
try
{
XmlTextWriter writer = new XmlTextWriter(cfgDocPath, null);
writer.Formatting = Formatting.Indented;
cfgDoc.WriteTo(writer);
writer.Flush();
writer.Close();
return;
}
catch
{
throw;
}
}
public bool removeElement(string elementKey)
{
try
{
XmlDocument cfgDoc = new XmlDocument();
loadConfigDoc(cfgDoc);
// retrieve the appSettings node
node = cfgDoc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new System.InvalidOperationException("appSettings section not found");
}
// XPath select setting "add" element that contains this key to remove
node.RemoveChild(node.SelectSingleNode("//add[@key='" + elementKey + "']"));
saveConfigDoc(cfgDoc, docName);
return true;
}
catch
{
return false;
}
}
private XmlDocument loadConfigDoc(XmlDocument cfgDoc)
{
// load the config file
if (Convert.ToInt32(ConfigType) == Convert.ToInt32(ConfigFileType.AppConfig))
{
docName = ((Assembly.GetEntryAssembly()).GetName()).Name;
docName += ".exe.config";
}
else
{
// docName = System.Web.HttpContext.Current.Server.MapPath("web.config");
}
cfgDoc.Load(docName);
return cfgDoc;
}
}
==========================
Eg
AppConfig a = new AppConfig();
a.ConfigType = 1;
a.SetValue("IP", "123132123123");
============================
Monday, October 22, 2007
weekend
Thursday, October 18, 2007
ClickOnce on Vista
inside the manifest.... after that lots of issues started
1. The requested operation requires elevation
2. Execution level requested by the application is not supported.
are two common error in this field.
When i googled it, it says due to some security issues, it's not allowed to have admin previlage user context inside.
only solution for this problem is to re-run the exe file using shell command. :)
hope you guys will not waste time on this.. !
Tuesday, October 16, 2007
Vista Crack
Turn Off or Disable User Account Control (UAC) in Windows Vista
then you have to apply this crack :)
Unicode bug in RichTextBox
replace:
_doc.Append(_text.Replace("\n", @"\par "));
with this:
string Text = _text.Replace("\n", @"\par ");
char[] chars = Text.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
if ((int)chars[i] > 256)
{
_doc.AppendFormat(@"\u" + ((int)chars[i]).ToString() + "?");
}
else
{
_doc.Append(chars[i].ToString());
}
}
Thursday, October 04, 2007
top most control in .NET
Tuesday, October 02, 2007
System.InvalidOperationException:
System.InvalidOperationException: The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone).
at System.Threading.SynchronizationContextSwitcher.Undo()
at System.Threading.ExecutionContextSwitcher.Undo()
at System.Threading.ExecutionContext.runFinallyCode(Object userData, Boolean exceptionThrown)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteBackoutCodeHelper(Object backoutCode, Object userData, Boolean exceptionThrown)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
Thursday, September 27, 2007
Flash/Blinking Window in C#
static extern Int32 FlashWindowEx(ref FLASHWINFO pwfi);
[StructLayout(LayoutKind.Sequential)]
public struct FLASHWINFO
{
public UInt32 cbSize;
public IntPtr hwnd;
public UInt32 dwFlags;
public UInt32 uCount;
public UInt32 dwTimeout;
}
//Stop flashing. The system restores the window to its original state.
public const UInt32 FLASHW_STOP = 0;
//Flash the window caption.
public const UInt32 FLASHW_CAPTION = 1;
//Flash the taskbar button.
public const UInt32 FLASHW_TRAY = 2;
//Flash both the window caption and taskbar button.
//This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
public const UInt32 FLASHW_ALL = 3;
//Flash continuously, until the FLASHW_STOP flag is set.
public const UInt32 FLASHW_TIMER = 4;
//Flash continuously until the window comes to the foreground.
public const UInt32 FLASHW_TIMERNOFG = 12;
///
/// Flashes a window until the window comes to the foreground
/// Receives the form that will flash
///
/// The handle to the window to flash
///
public static bool FlashWindowEx(Form frm)
{
IntPtr hWnd = frm.Handle;
FLASHWINFO fInfo = new FLASHWINFO();
fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
fInfo.hwnd = hWnd;
fInfo.dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG;
fInfo.uCount = UInt32.MaxValue;
fInfo.dwTimeout = 0;
return (FlashWindowEx(ref fInfo) == 0);
}
Tuesday, September 11, 2007
"The search key was not found in any record." in dBase ?
TEPS TO RESOLVE ISSUE:
========================
1. To Resolve that issue, In the Registry Editor, browse to the following
Registry key:
\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Eng ines\Xbase
2. On the Right Pane, Click on Deleted.
3. Right-Click on the Deleted and click on Modify.
4. Change the entry from
0000 01
to
0000 00
4. Click OK.
5. Close the Registry and then open Access and the file imports fine.
special thanks to Amy Vargo.
Monday, September 03, 2007
convert an object in to byte array or byte array to object
public byte[] objectToByte(Object obj )
{
MemoryStream fs = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, obj);
return fs.ToArray() ;
}
catch (SerializationException e )
{
return null;
}
finally
{
fs.Close();
}
}
public object ByteArrayToObject(Byte[] Buffer )
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream(Buffer);
try
{
return formatter.Deserialize(stream);
}
catch
{
return null;
}
}
Monday, August 20, 2007
how to check bcp.exe wheather faild or sucessful ?
bcp.exe will return 1 if it fails, otherwise 0
Friday, August 10, 2007
C# Language Specification
http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc
How to create a stagging table ?
sp_CreateAndExecTableScript 'InterfaceTree', '_stagging', 0 , 1
CREATE PROCEDURE spCOMMS_CreateStaggingTable
(@TableName varchar(255) = '',
@TableNameExt varchar(255) = '',
@DisplayScript bit = 0,
@Exec bit = 0,
@NoPK bit = 0,
@PKOnly bit = 0,
@NoIndexes bit = 0,
@NoTable bit = 0
)AS
SET NOCOUNT ON
--Begin invalid entries for parameters section
--Test for empty entry
IF @TableName = ''
BEGIN
PRINT '@TableName is a required parameter.'
RETURN 1
END
--Test for source table
IF NOT EXISTS (select * from sysobjects where id = object_id(N'[dbo].[' + @TableName + ']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
PRINT 'Table ' + @TableName + ' not found.'
RETURN 2
END
--End invalid entries for parameters section
DECLARE @Query varchar (8000),
@DFQuery varchar(8000)
SET @Query = ''
SET @DFQuery = ''
--Begin building datetime value to be used to ensure primary key and index names are unique
DECLARE @DateTime varchar(20)
DECLARE @rawDateTime varchar(20)
SET @rawdatetime = CURRENT_TIMESTAMP
SET @DateTime = SUBSTRING(@rawDateTime, 5, 2) + LEFT(@rawDateTime, 3) + SUBSTRING(@rawDateTime, 8, 4)
IF SUBSTRING(@rawDateTime, 13, 1) = ' '
SET @DateTime = @DateTime + SUBSTRING(@rawDateTime, 14, 1)
ELSE
SET @DateTime = @DateTime + SUBSTRING(@rawDateTime, 13, 2)
SET @DateTime = LTRIM(@DateTime) + '_' + SUBSTRING(@rawDateTime, 16, 4)
--End building datetime value
--Begin creating temp tables
--temp table #TableScript is used to gather data needed to generate script that will create the table
IF @NoTable = 0 AND @PKOnly = 0
CREATE TABLE #TableScript (
ColumnName varchar (30),
DataType varchar(40),
Length varchar(4),
[Precision] varchar(4),
Scale varchar(4),
IsNullable varchar(1),
TableName varchar(30),
ConstraintName varchar(255),
DefaultValue varchar (255),
GroupName varchar(35),
collation sysname NULL,
IdentityColumn bit NULL
)
--temp table #IndexScript is used to gather data needed to generate script that will create indexes for table
CREATE TABLE #IndexScript (
IndexName varchar (255),
IndId int,
ColumnName varchar (255),
IndKey int,
UniqueIndex int
)
--End creating temp tables
--Begin filling temp table #TableScript
IF @NoTable = 0 AND @PKOnly = 0
BEGIN
INSERT INTO #TableScript (ColumnName, DataType, Length, [Precision], Scale, IsNullable, TableName,
ConstraintName, DefaultValue, GroupName, collation, IdentityColumn)
SELECT LEFT(c.name,30) AS ColumnName,
LEFT(t.name,30) AS DataType,
CASE t.length
WHEN 8000 THEN c.prec --This criteria used because Enterprise Manager delivers the length in parenthesis for these datatypes when using its scripting capabilities.
ELSE NULL
END AS Length,
CASE t.name
WHEN 'numeric' THEN c.prec
WHEN 'decimal' THEN c.prec
ELSE NULL
END AS [Precision],
CASE t.name
WHEN 'numeric' THEN c.scale
WHEN 'decimal' THEN c.scale
ELSE NULL
END AS Scale,
c.isnullable,
LEFT(o.name,30) AS TableName,
d.name AS ConstraintName,
cm.text AS DefaultValue,
g1a.groupname,
c.collation,
CASE
WHEN c.autoval IS NULL THEN 0
ELSE 1
END AS IdentityColumn
FROM syscolumns c
INNER JOIN sysobjects o ON c.id = o.id
LEFT JOIN systypes t ON t.xusertype = c.xusertype --the first three joins get column names, data types, and column nullability.
LEFT JOIN sysobjects d ON c.cdefault = d.id --this left join gets column default constraint names.
LEFT JOIN syscomments cm ON cm.id = d.id --this left join gets default values for default constraints.
LEFT JOIN sysindexes g1 ON g1.id = o.id --the left join for sysfilegroups and sysindexes with aliases g1 and g1a
LEFT JOIN sysfilegroups g1a ON g1.groupid = g1a.groupid --are for determining which file group the table is in.
WHERE o.name = @TableName
AND g1.id = o.id AND g1.indid in (0, 1) --these two conditions are to isolate the file group of the table.
END
--End filling temp table #TableScript
--Begin building create table and default value constraints scripts.
IF @NoTable = 0 AND @PKOnly = 0
BEGIN
SET @Query = 'if exists (select * from sysobjects where id = object_id(N' + '''[dbo].['
+ @TableName + @TableNameExt + ']''' + ') and OBJECTPROPERTY(id, N' + '''IsUserTable''' + ') = 1)'
+ CHAR(10) + 'drop table [dbo].[' + @TableName + @TableNameExt + ']'
+ CHAR(10) + 'GO'
+ CHAR(10) + CHAR(10) + 'CREATE TABLE [dbo].[' + @TableName + @TableNameExt + '] ('
DECLARE @DataType varchar(40),
@Length varchar(4),
@Precision varchar(4),
@Scale varchar(4),
@Isnullable varchar(1),
@DefaultValue varchar(255),
@GroupName varchar(35),
@ColumnName varchar(255),
@ConstraintName varchar(255),
@collation sysname,
@TEXTIMAGE_ON bit,
@IdentityColumn bit
SET @TEXTIMAGE_ON = 0
DECLARE ColumnName Cursor For
SELECT ColumnName
FROM #TableScript
OPEN ColumnName
FETCH NEXT FROM ColumnName INTO @ColumnName
WHILE (@@fetch_status = 0)
BEGIN
SELECT @DataType = DataType,
@Length = Length,
@Precision = [Precision],
@Scale = Scale,
@Isnullable = isnullable,
@DefaultValue = DefaultValue,
@ConstraintName = ConstraintName,
@collation = collation,
@IdentityColumn = IdentityColumn
FROM #TableScript
WHERE ColumnName = @ColumnName
IF @DefaultValue IS NOT NULL
BEGIN
IF @DFQuery = ''
SET @DFQuery = @DFQuery
+ CHAR(10) + CHAR(10) + 'ALTER TABLE [dbo].[' + @TableName + @TableNameExt + '] WITH NOCHECK ADD'
SET @DFQuery = @DFQuery
+ CHAR(10) + CHAR(9) + 'CONSTRAINT [DF_' + @TableName + @TableNameExt + '_'
+ @ColumnName + '_' + @DateTime + '] DEFAULT ' + @DefaultValue
+ ' FOR [' + @ColumnName + '],'
END
IF @DataType = 'text' OR @DataType = 'ntext'
SET @TEXTIMAGE_ON = 1
SET @Query = @Query
+ CHAR(10) + CHAR(9) + '[' + @ColumnName + '] [' + @DataType + ']'
IF @IdentityColumn = 1
SET @Query = @Query
+ ' IDENTITY (' + LTRIM(STR(IDENT_SEED(@TableName))) + ', ' + LTRIM(STR(IDENT_INCR(@TableName))) + ')'
IF @DataType = 'varchar' OR @DataType = 'nvarchar' OR @DataType = 'char' OR @DataType = 'nchar'
OR @DataType = 'varbinary' OR @DataType = 'binary'
SET @Query = @Query
+ ' (' + @Length + ')'
IF @DataType = 'numeric' OR @DataType = 'decimal'
SET @Query = @Query
+ ' (' + @Precision + ', ' + @Scale + ')'
IF @collation IS NOT NULL AND @DataType <> 'sysname' AND @DataType <> 'ProperName'
SET @Query = @Query
+ ' COLLATE ' + @collation
IF @Isnullable = '1'
SET @Query = @Query + ' NULL'
ELSE
SET @Query = @Query + ' NOT NULL'
FETCH NEXT FROM ColumnName INTO @ColumnName
IF @@fetch_status = 0
SET @Query = @Query + ', '
END
CLOSE ColumnName
DEALLOCATE ColumnName
SET @Query = @Query
+ CHAR(10) + ')'
--Assign file group name
SELECT DISTINCT @GroupName = GroupName
FROM #TableScript
IF @GroupName IS NOT NULL
SET @Query = @Query
+ ' ON [' + @GroupName + ']'
IF @TEXTIMAGE_ON = 1
SET @Query = @Query
+ ' TEXTIMAGE_ON [' + @GroupName + ']'
IF RIGHT(@DFQuery,1) = ','
SET @DFQuery = LEFT(@DFQuery, LEN(@DFQuery) - 1)
SET @Query = @Query
+ CHAR(10) + 'GO'
END
--End building create table and default value constraints scripts.
--Begin filling temp table #IndexScript.
INSERT INTO #IndexScript (IndexName, IndId, ColumnName, IndKey, UniqueIndex)
SELECT i.name,
i.indid,
c.name,
k.keyno,
(i.status & 2) --Learned this will identify a unique index from sp_helpindex
FROM sysindexes i
INNER JOIN sysobjects o ON i.id = o.id
INNER JOIN sysindexkeys k ON i.id = k.id AND i.indid = k.indid
INNER JOIN syscolumns c ON c.id = k.id AND k.colid = c.colid
WHERE o.name = @TableName
AND i.indid > 0 and i.indid < 255 --eliminates non indexes
AND LEFT(i.name,7) <> '_WA_Sys' --eliminates statistic indexes
--End filling temp table #IndexScript.
DECLARE @PK varchar(2),
@IndID int,
@IndexName varchar(255),
@IndKey int
SET @PK = ''
SET @IndKey = 1
SELECT DISTINCT @IndexName = IndexName,
@IndID = indid
FROM #IndexScript
WHERE LEFT (IndexName, 2) = 'PK'
--Begin creating primary key script.
IF @PKOnly = 1 OR (@NoTable = 1 AND @NoPK = 0)
BEGIN
SET @Query = '--Add Primary Key' + CHAR(10)
SET @PK = 'PK'
END
IF @NoPK = 0
BEGIN
IF @IndexName IS NOT NULL
BEGIN
SET @Query = @Query
+ CHAR(10) + CHAR(10) + 'ALTER TABLE [dbo].[' + @TableName + @TableNameExt + '] WITH NOCHECK ADD'
+ CHAR(10) + 'CONSTRAINT [PK_' + @TableName + @TableNameExt + @PK + '_' + @DateTime + '] PRIMARY KEY '
IF @IndID = 1
SET @Query = @Query
+ 'CLUSTERED'
ELSE
SET @Query = @Query
+ 'NONCLUSTERED'
SET @Query = @Query
+ CHAR(10) + '('
DECLARE @OldColumnName varchar(255)
SET @OldColumnName = 'none_yet'
WHILE @IndKey <= 16
BEGIN
SELECT @ColumnName = ColumnName
FROM #IndexScript
WHERE IndexName = @IndexName AND IndID = @IndID AND IndKey = @IndKey
IF @ColumnName IS NOT NULL AND @ColumnName <> @OldColumnName
BEGIN
SET @Query = @Query
+ CHAR(10) + '[' + @ColumnName + '],'
END
SET @OldColumnName = @ColumnName
SET @IndKey = @IndKey + 1
END
IF RIGHT(@Query,1) = ','
SET @Query = LEFT(@Query, LEN(@Query) - 1)
SET @Query = @Query
+ CHAR(10) + ')'
--Add file group name
IF @GroupName is not null
SET @Query = @Query
+ ' ON [' + @GroupName + ']'
SET @Query = @Query
+ CHAR(10) + 'GO'
END
END
--End creating primary key script.
--Add default value constraint script to main script.
IF @NoTable = 0 AND @PKOnly = 0
SET @Query = @Query
+ @DFQuery
+ CHAR(10) + 'GO'
--Begin building index script.
IF @NoIndexes = 0 AND @PKOnly = 0
BEGIN
IF @NoPK = 0
SET @Query = @Query
+ CHAR(10)
IF @NoTable = 1
SET @Query = @Query
+ '--Add Indexes' + CHAR(10)
ELSE
SET @Query = @Query
+ CHAR(10)
DECLARE @IndexNameOrig varchar(255),
@UniqueIndex int
DECLARE IndexName Cursor For
SELECT DISTINCT IndexName,
indid,
UniqueIndex
FROM #IndexScript
WHERE LEFT (IndexName, 2) <> 'PK' AND LEFT(IndexName, 4) <> 'hind'
OPEN IndexName
FETCH NEXT FROM IndexName INTO @IndexName, @IndID, @UniqueIndex
WHILE @@fetch_status = 0
BEGIN
SET @IndexNameOrig = @IndexName
IF RIGHT(@IndexName,2) = 'PM' OR RIGHT(@IndexName,2) = 'AM'
SET @IndexName = LEFT(@IndexName, LEN(@IndexName) - 5)
IF LEFT(RIGHT(@IndexName,10),1) = '_'
SET @IndexName = LEFT(@IndexName, LEN(@IndexName) - 10)
ELSE
IF LEFT(RIGHT(@IndexName,11),1) = '_'
SET @IndexName = LEFT(@IndexName, LEN(@IndexName) - 11)
ELSE
IF LEFT(RIGHT(@IndexName,12),1) = '_'
SET @IndexName = LEFT(@IndexName, LEN(@IndexName) - 12)
SET @Query = @Query
+ CHAR(10) + 'CREATE '
IF @IndID = 1
SET @Query = @Query
+ 'CLUSTERED '
IF @UniqueIndex <> 0
SET @Query = @Query
+ 'UNIQUE '
SET @Query = @Query
+ 'INDEX [' + @IndexName + '_' + @DateTime + '] ON [dbo].[' + @TableName + @TableNameExt + ']('
SET @IndKey = 1
SET @OldColumnName = 'none_yet'
WHILE @IndKey <= 16
BEGIN
SELECT @ColumnName = ColumnName
FROM #IndexScript
WHERE IndexName = @IndexNameOrig AND IndID = @IndID AND IndKey = @IndKey
IF @ColumnName IS NOT NULL AND @ColumnName <> @OldColumnName
BEGIN
SET @Query = @Query
+ '[' + @ColumnName + '],'
END
SET @OldColumnName = @ColumnName
SET @IndKey = @IndKey + 1
END
IF RIGHT(@Query,1) = ','
SET @Query = LEFT(@Query, LEN(@Query) - 1)
SET @Query = @Query + ')'
--Add file group name
IF @GroupName is not null
SET @Query = @Query
+ ' ON [' + @GroupName + ']'
SET @Query = @Query
+ CHAR(10) + 'GO' + CHAR(10)
FETCH NEXT FROM IndexName INTO @IndexName, @IndID, @UniqueIndex
END
CLOSE IndexName
DEALLOCATE IndexName
END
--End building index script.
DROP TABLE #IndexScript
IF @NoTable = 0 AND @PKOnly = 0
DROP TABLE #TableScript
IF @DisplayScript = 1
PRINT @Query
IF @Exec = 1
BEGIN
--This code needed to remark out all GO commands before executing the code in the variable @Query
SET @Query = REPLACE(@Query,CHAR(10) + 'GO', CHAR(10) + '--GO')
Exec (@Query)
END
RETURN 0
GO
Monday, July 30, 2007
nice google search tip
1. Go to Google
2. Click images
3. Type "flowers" or any other word.
4. You will get a page which is having full of images
5. Then delete the URL from the address bar and paste the below script
javascript:R= 0; x1=.1; y1=.05; x2=.25; y2=.24; x3= 1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI= document.images ; DIL=DI.length; function A(){for(i=0; i
betting tips
Each of these factors has sub-factors, which further contribute to the rating assigned to each horse.
Horse
-Raw ability
-Distance form
-Ground form
-Maturity / Exposure
Jockey
-Weight
-Success individually
-Success with today's trainer
-Success at this course
Trainer
-percentage of winners in the last 6 months
-percentage of winners in the last 4weeks
-Success at this course
By quantifying these factors each with a different weighting dependant on importance - i.e. a 3rd in a Class C event is more valuable in terms of weighting than 3rd in a seller
The final stage for this product to identify the two selections that stand out, not necessarily those with the highest ratings, but those with the greatest percentage above the next best horse in their races.
Friday, July 27, 2007
BCS finally finished
Monday, July 23, 2007
extracting parameter from a url using C#
where i am looking for key in the url.Query
Regex fileRegex = new Regex(@"^\?key=(?<1>[^&]*)$", RegexOptions.Singleline | RegexOptions.IgnoreCase);
Match fileMatch = fileRegex.Match(Uri.UnescapeDataString(url.Query));
if (fileMatch.Success)
return fileMatch.Groups[1].Value;
Thursday, July 19, 2007
CurrentDeployment.UpdateLocation cached
if you are getting a null issue in CurrentDeployment.ActivationUri that means you have not set the application publish->options allow parameters option
how to change the listview selected color ?
=====================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace listviewsample
{
public partial class Form1 : Form
{
public static int WM_NOTIFY = 0x004E;
public static int NM_FIRST = 0- 0;
public static int NM_CUSTOMDRAW = NM_FIRST-12;
public static int CDRF_DODEFAULT = 0x00000000;
public static int CDRF_NEWFONT = 0x00000002;
public static int CDRF_SKIPDEFAULT = 0x00000004;
public static int CDRF_NOTIFYPOSTPAINT = 0x00000010;
public static int CDRF_NOTIFYITEMDRAW = 0x00000020;
public static int CDRF_NOTIFYSUBITEMDRAW = 0x00000020;
public static int CDRF_NOTIFYPOSTERASE = 0x00000040;
public static int CDIS_SELECTED = 0x0001;
public static int CDIS_FOCUS = 0x0010;
public static int CDDS_PREPAINT = 0x00000001;
public static int CDDS_POSTPAINT = 0x00000002;
public static int CDDS_PREERASE = 0x00000003;
public static int CDDS_POSTERASE = 0x00000004;
public static int CDDS_ITEM = 0x00010000;
public static int CDDS_ITEMPREPAINT = CDDS_ITEM | CDDS_PREPAINT;
public static int CDDS_ITEMPOSTPAINT = CDDS_ITEM | CDDS_POSTPAINT;
public static int CDDS_ITEMPREERASE = CDDS_ITEM | CDDS_PREERASE;
public static int CDDS_ITEMPOSTERASE = CDDS_ITEM | CDDS_POSTERASE;
public static int CDDS_SUBITEM = 0x00020000;
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayout(LayoutKind.Sequential)]
public struct NMHDR
{
public int hwndFrom;
public int idFrom;
public int code;
}
[StructLayout(LayoutKind.Sequential)]
public struct NMCUSTOMDRAWINFO
{
public NMHDR hdr;
public IntPtr dwDrawStage;
public IntPtr hdc;
public RECT rc;
public IntPtr dwItemSpec;
public uint uItemState;
public IntPtr lItemlParam;
}
[StructLayout(LayoutKind.Sequential)]
public struct NMLVCUSTOMDRAW
{
public NMCUSTOMDRAWINFO nmcd;
public int clrText;
public int clrTextBk;
public int iSubItem;
}
protected override void WndProc(ref Message m)
{
if (m.Msg==WM_NOTIFY && m.WParam.Equals(listView1.Handle))
{
NMHDR nmhdr = (NMHDR)m.GetLParam(typeof(NMHDR));
if (nmhdr.code==NM_CUSTOMDRAW)
{
NMLVCUSTOMDRAW xCustomDraw =
(NMLVCUSTOMDRAW)m.GetLParam(typeof(NMLVCUSTOMDRAW) );
if
(listView1.SelectedIndices.IndexOf(xCustomDraw.nmcd.dwItemSpec.ToInt32())>-1
)
{
if ((xCustomDraw.nmcd.uItemState & CDIS_SELECTED)!=0)
{
xCustomDraw.nmcd.uItemState -= (uint)CDIS_SELECTED;
Marshal.StructureToPtr(xCustomDraw, m.LParam,
false);
}
if
(xCustomDraw.nmcd.dwDrawStage.ToInt32()==CDDS_PREPAINT)
{
m.Result = new IntPtr(CDRF_NOTIFYITEMDRAW);
return;
}
else if
(xCustomDraw.nmcd.dwDrawStage.ToInt32()==CDDS_ITEMPREPAINT)
{
xCustomDraw.clrText = ColorTranslator.ToWin32(Color.Blue);
xCustomDraw.clrTextBk = ((xCustomDraw.nmcd.uItemState & CDIS_FOCUS)!=0) ?
xCustomDraw.clrTextBk = ColorTranslator.ToWin32(Color.Yellow) :
xCustomDraw.clrTextBk = ColorTranslator.ToWin32(Color.Orange);
m.Result = new IntPtr(CDRF_NEWFONT);
Marshal.StructureToPtr(xCustomDraw, m.LParam,
false);
return;
}
}
}
}
base.WndProc(ref m);
}
public Form1()
{
InitializeComponent();
}
}
}
Tuesday, July 17, 2007
joke of the day !
- Gender Test ( funny )
- Important Test!
- Are you male or female??????
- To know the answer, look down...
-
-
-
-
-
-
-
-
-
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
- .
-
-
- NOT HERE... MY FRIEND
- I SAID LOOK DOWN....
- NOT SCROLL DOWN...
- @@@@@@@@@@@@ @@@@@@@@@ @@@@@@@@@ @
Monday, July 16, 2007
ActivationData is null??
if you get AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData = null then use ApplicationDeployment.CurrentDeployment.UpdateLocation.AbsoluteUri
parameter passing for oneclick installtion url
1. go to project properties -> Publish
2. click on options and check "allow parameters to be pass to the url"
3. use this code snippet extract the parameter value,
4. eg http://www.hostname.com/sample.application?parameter=test
private static string parseParameters()
{
if (ApplicationDeployment.IsNetworkDeployed)
{
string[] activationData = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData;
if (activationData != null)
{
Uri url = new Uri(activationData[0]);
Regex fileRegex = new Regex(@"^\?parameter=(?<1>[^&]*)$",
RegexOptions.Singleline);
Match fileMatch = fileRegex.Match(Uri.UnescapeDataString(url.Query));
if (fileMatch.Success)
return fileMatch.Groups[1].Value;
}
}
else
{
return null;
}
}
Friday, June 29, 2007
Mihin Air Flyies to Thailand!
http://www.mihinlanka.com/
Monday, June 25, 2007
Windows ListView with subitem images
i have pasted the code here, so u might save some time.
using System;
using System.Runtime.InteropServices;
public class ListViewEx : System.Windows.Forms.ListView
{
private const int LVIF_IMAGE = 0x2;
private const int LVS_EX_SUBITEMIMAGES = 0x2;
private const int LVM_FIRST = 0x1000;
private const int LVM_GETITEMA = LVM_FIRST + 5;
private const int LVM_GETITEMW = LVM_FIRST + 75;
private static readonly int LVM_GETITEM = (Marshal.SystemDefaultCharSize
== 1) ? LVM_GETITEMA : LVM_GETITEMW;
private const int LVM_SETITEMA = LVM_FIRST + 6;
private const int LVM_SETITEMW = LVM_FIRST + 76;
private static readonly int LVM_SETITEM = (Marshal.SystemDefaultCharSize
== 1) ? LVM_SETITEMA : LVM_SETITEMW;
private const int LVM_SETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 54;
[DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hwnd, int msg, IntPtr
wParam, ref LVITEM lParam);
[DllImport("User32.dll", CharSet=CharSet.Auto)]
private static extern int SendMessage(IntPtr hwnd, int msg, IntPtr
wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
private struct LVITEM
{
public int mask;
public int iItem;
public int subItem;
public int state;
public int stateMask ;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszText;
public int cchTextMax;
public int iImage;
public IntPtr lParam;
public int iIndent;
}
private bool ListView_SetItem(IntPtr hwnd, ref LVITEM lvi)
{
int result = SendMessage(hwnd, LVM_SETITEM, IntPtr.Zero, ref lvi);
return (result == 0) ? false : true;
}
private bool ListView_GetItem(IntPtr hwnd, ref LVITEM lvi)
{
int result = SendMessage(hwnd, LVM_GETITEM, IntPtr.Zero, ref lvi);
return (result == 0) ? false : true;
}
private void ListView_SetExtendedListViewStyleEx(IntPtr hwnd, int mask,
int style)
{
SendMessage(hwnd, LVM_SETEXTENDEDLISTVIEWSTYLE, new IntPtr(mask),
new IntPtr(style));
}
private void ListView_SetSubItemImageIndex(IntPtr hwnd, int index, int
subItemIndex, int imageIndex)
{
LVITEM lvi = new LVITEM();
lvi.iItem = index;
lvi.subItem = subItemIndex;
lvi.iImage = imageIndex;
lvi.mask = LVIF_IMAGE;
ListView_SetItem(hwnd, ref lvi);
}
private int ListView_GetSubItemImageIndex(IntPtr hwnd, int index, int
subItemIndex)
{
LVITEM lvi = new LVITEM();
lvi.iItem = index;
lvi.subItem = subItemIndex;
lvi.mask = LVIF_IMAGE;
if (ListView_GetItem(hwnd, ref lvi))
return lvi.iImage;
else
return -1;
}
protected override void OnCreateControl()
{
base.OnCreateControl();
ListView_SetExtendedListViewStyleEx(this.Handle,
LVS_EX_SUBITEMIMAGES, LVS_EX_SUBITEMIMAGES);
}
public void SetSubItemImageIndex(int index, int subItemIndex, int
imageIndex)
{
ListView_SetSubItemImageIndex(this.Handle, index, subItemIndex,
imageIndex);
}
public int GetSubItemImageIndex(int index, int subItemIndex)
{
return ListView_GetSubItemImageIndex(this.Handle, index,
subItemIndex);
}
}
Where is WMSDefine namespace in SP2 ?
I was working on a windows media service plug-in for my bro. When i installed it in Windows |Server 2003 standard version PC it didn't work because custom plug-in doesn't support in Windows 2003 stranded version either :) dammm
So I moved everything i had in to a 64 bit Windows Sever 2003 SP2 PC. nothing worked. i looked over and over thu a stupid error code in Google and didn't help it either.
So i compiled everything on top of Windows Freamwork 2.0, now WMSDefine enum is missing in the latest windowsmediaservice.dll ahh frustrating.. so i reflector to copy the WMSDefined class from 1.1 to my project and it worked.
simply this is why i dont like MS,
Friday, June 01, 2007
Auto Size Columns in the DataGrid ?
Public Sub AutoSizeGrid(ByVal Grid As DataGrid)
Try
Dim t As Type = grdInfo.GetType
Dim m As MethodInfo = t.GetMethod("ColAutoResize", _
BindingFlags.NonPublic Or BindingFlags.Instance)
Dim start As Integer
start = grdInfo.FirstVisibleColumn
Dim i As Integer = 0
While i < grdInfo.VisibleColumnCount OrElse i = 0
m.Invoke(Grid, New Object() {i + start})
i = i + 1
End While
Catch ex As Exception
m_parentForm.imcMessege.LogErrorMessage(Me, ex)
End Try
End Sub
need a combobox in DataGrid ?
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
// Derive class from DataGridTextBoxColumn
public class DataGridComboBoxColumn : DataGridTextBoxColumn
{
// Hosted ComboBox control
private ComboBox comboBox;
private CurrencyManager cm;
private int iCurrentRow;
// Constructor - create combobox, register selection change event handler,
// register lose focus event handler
public DataGridComboBoxColumn()
{
this.cm = null;
// Create ComboBox and force DropDownList style
this.comboBox = new ComboBox();
this.comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
// Add event handler for notification of when ComboBox loses focus
this.comboBox.Leave += new EventHandler(comboBox_Leave);
}
// Property to provide access to ComboBox
public ComboBox ComboBox
{
get { return comboBox; }
}
// On edit, add scroll event handler, and display combo box
protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
{
Debug.WriteLine(String.Format("Edit {0}", rowNum));
base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);
if (!readOnly && cellIsVisible)
{
// Save current row in the datagrid and currency manager associated with
// the data source for the datagrid
this.iCurrentRow = rowNum;
this.cm = source;
// Add event handler for datagrid scroll notification
this.DataGridTableStyle.DataGrid.Scroll += new EventHandler(DataGrid_Scroll);
// Site the combo box control within the bounds of the current cell
this.comboBox.Parent = this.TextBox.Parent;
Rectangle rect = this.DataGridTableStyle.DataGrid.GetCurrentCellBounds();
this.comboBox.Location = rect.Location;
this.comboBox.Size = new Size(this.TextBox.Size.Width, this.comboBox.Size.Height);
// Set combo box selection to given text
this.comboBox.SelectedIndex = this.comboBox.FindStringExact(this.TextBox.Text);
// Make the ComboBox visible and place on top text box control
this.comboBox.Show();
this.comboBox.BringToFront();
this.comboBox.Focus();
}
}
// Given a row, get the value member associated with a row. Use the value
// member to find the associated display member by iterating over bound datasource
protected override object GetColumnValueAtRow(System.Windows.Forms.CurrencyManager source, int rowNum)
{
if(this.comboBox.DataSource == null) return null;
Debug.WriteLine(String.Format("GetColumnValueAtRow {0}", rowNum));
// Given a row number in the datagrid, get the display member
object obj = base.GetColumnValueAtRow(source, rowNum);
// Iterate through the datasource bound to the ColumnComboBox
// Don't confuse this datasource with the datasource of the associated datagrid
CurrencyManager cm = (CurrencyManager) (this.DataGridTableStyle.DataGrid.BindingContext[this.comboBox.DataSource]);
// Assumes the associated DataGrid is bound to a DataView, or DataTable that
// implements a default DataView
DataView dataview = ((DataView)cm.List);
int i;
for (i = 0; i < dataview.Count; i++)
{
if (obj.Equals(dataview[i][this.comboBox.ValueMember]))
break;
}
if (i < dataview.Count)
return dataview[i][this.comboBox.DisplayMember];
return DBNull.Value;
}
// Given a row and a display member, iterating over bound datasource to find
// the associated value member. Set this value member.
protected override void SetColumnValueAtRow(System.Windows.Forms.CurrencyManager source, int rowNum, object value)
{
Debug.WriteLine(String.Format("SetColumnValueAtRow {0} {1}", rowNum, value));
object s = value;
// Iterate through the datasource bound to the ColumnComboBox
// Don't confuse this datasource with the datasource of the associated datagrid
CurrencyManager cm = (CurrencyManager)
(this.DataGridTableStyle.DataGrid.BindingContext[this.comboBox.DataSource]);
// Assumes the associated DataGrid is bound to a DataView, or DataTable that
// implements a default DataView
DataView dataview = ((DataView)cm.List);
int i;
for (i = 0; i < dataview.Count; i++)
{
if (s.Equals(dataview[i][this.comboBox.DisplayMember]))
break;
}
// If set item was found return corresponding value, otherwise return DbNull.Value
if(i < dataview.Count)
s = dataview[i][this.comboBox.ValueMember];
else
s = DBNull.Value;
base.SetColumnValueAtRow(source, rowNum, s);
}
// On datagrid scroll, hide the combobox
private void DataGrid_Scroll(object sender, EventArgs e)
{
Debug.WriteLine("Scroll");
this.comboBox.Hide();
}
// On combo box losing focus, set the column value, hide the combo box,
// and unregister scroll event handler
private void comboBox_Leave(object sender, EventArgs e)
{
try
{
if(this.comboBox.DisplayMember == "")
{
this.comboBox.Hide();
return;
}
if(this.comboBox.SelectedItem == null)
{
this.comboBox.Hide();
return;
}
DataRowView rowView = (DataRowView) this.comboBox.SelectedItem;
string s = (string) rowView.Row[this.comboBox.DisplayMember];
Debug.WriteLine(String.Format("Leave: {0} {1}", this.comboBox.Text, s));
SetColumnValueAtRow(this.cm, this.iCurrentRow, s);
Invalidate();
this.comboBox.Hide();
this.DataGridTableStyle.DataGrid.Scroll -= new EventHandler(DataGrid_Scroll);
}
finally
{
this.comboBox.Hide();
}
}
}
Friday, March 23, 2007
Company of Heros
When I was in thailand I bought a game named "Company of Heros" which happed to be the last year best startagic game. Now I am addicted to it. I intalled it in my bros computer and it worked with out any problems and i managed to complete 4 levels of the game spending ,night and cutting class. When i installed it in my laptop it starts giving problems, I can;t see soilders so i installed patches drivers nothing seems to be working.
just waitting till some mirecal happens for me to play the game on my laptop..
i also asked pitta to check my kendare. Hope it will same some thing good about the game :) even tho i am not beliving in god and stuff this is the time i tend to think about
Thursday, March 08, 2007
SQL Server Transaction Log Reader
http://www.lumigent.com/downloads/
Monday, March 05, 2007
Error 75 File Path Access Error On Windows 2003
so i kept a not so you dont have to go thur what we did
Tuesday, February 27, 2007
last couple od days
Iwent to thailand first week of Jan with a very old friend of mine and we has a awsome time. I managed to try some of the pills also .. no doubts about that ;) now
Monday, February 12, 2007
script to create indexes on Foreign Key
http://sqlblog.com/blogs/paul_nielsen/archive/2007/02/08/codegen-to-create-indexes-for-fks.aspx
Monday, January 29, 2007
how to read a CSV file
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Odbc;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dtRecords = GetDataTable("SELECT FirstName, LastName FROM members2.csv ");
foreach(DataRow dr in dtRecords.Rows) {
MessageBox.Show(dr["FirstName"].ToString() + " " + dr["LastName"].ToString() );
}
}
private static string GetConnection() {
return @"Driver={Microsoft Text Driver (*.txt; *.csv)};HDR=YES;Extensions=asc,csv,tab,txt;Dbq=C:\Temp";
}
public static DataTable GetDataTable(string sql) {
DataTable rt = new DataTable();
DataSet ds = new DataSet();
OdbcDataAdapter da = new OdbcDataAdapter();
OdbcConnection con = new OdbcConnection(GetConnection());
OdbcCommand cmd = new OdbcCommand(sql, con);
da.SelectCommand = cmd;
da.Fill(ds);
try {
rt = ds.Tables[0];
}
catch {
rt = null;
}
return rt;
}
public static void DoCommand(string sql) {
OdbcConnection con = new OdbcConnection(GetConnection());
OdbcCommand cmd = new OdbcCommand();
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
try {
cmd.ExecuteNonQuery();
}
catch (Exception e){
//HandleError(e,sql);
}
finally {
con.Close();
}
}
}
}
Thursday, January 25, 2007
Windows 2003 SP 1 Crack !!
First of all you have to download this and save your original key.
Magical Jelly Bean Keyfinder v1.51
http://www.magicaljellybean.com
Then You have to go here and get your Windows 2003 Activation Wizard to change the KEY
http://www.petri.co.il/change_the_serial_in_windows_xp.htm
and change the Key to this Key,
GXMMC-DFWVM-KPVBC-X3XGB-FXTBB
then u r ready to install Windows 2003 SP 1 On your Server...
Monday, January 22, 2007
Open a text file using .NET and read
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Odbc;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dtRecords = GetDataTable("SELECT FirstName, LastName FROM members2.csv ");
foreach(DataRow dr in dtRecords.Rows) {
MessageBox.Show(dr["FirstName"].ToString() + " " + dr["LastName"].ToString() );
}
}
private static string GetConnection() {
return @"Driver={Microsoft Text Driver (*.txt; *.csv)};HDR=YES;Extensions=asc,csv,tab,txt;Dbq=C:\Temp";
}
public static DataTable GetDataTable(string sql) {
DataTable rt = new DataTable();
DataSet ds = new DataSet();
OdbcDataAdapter da = new OdbcDataAdapter();
OdbcConnection con = new OdbcConnection(GetConnection());
OdbcCommand cmd = new OdbcCommand(sql, con);
da.SelectCommand = cmd;
da.Fill(ds);
try {
rt = ds.Tables[0];
}
catch {
rt = null;
}
return rt;
}
public static void DoCommand(string sql) {
OdbcConnection con = new OdbcConnection(GetConnection());
OdbcCommand cmd = new OdbcCommand();
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
try {
cmd.ExecuteNonQuery();
}
catch (Exception e){
//HandleError(e,sql);
}
finally {
con.Close();
}
}
}
}
Friday, January 19, 2007
The Process of Database Refactoring
http://www.simple-talk.com/sql/database-administration/refactoring-databases-the-process/
http://www.red-gate.com/products/SQL_Refactor/index.htm
console applicationt to detect USB
Imports System.Management
Module Module1
Private WithEvents m_MediaConnectWatcher As Management.ManagementEventWatcher
Sub Main()
Dim query As New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE TargetInstance ISA ""Win32_DiskDrive""")
Dim watcher As New ManagementEventWatcher(query)
AddHandler watcher.EventArrived, AddressOf HandleEvent
' Start listening for events
watcher.Start()
Console.Read()
' Stop listening for events
watcher.Stop()
Return
End Sub
Private Sub HandleEvent(ByVal sender As Object, ByVal e As System.Management.EventArrivedEventArgs) Handles m_MediaConnectWatcher.EventArrived
Dim mbo, obj As ManagementBaseObject
' the first thing we have to do is figure out if this is a creation or deletion event
mbo = CType(e.NewEvent, ManagementBaseObject)
' next we need a copy of the instance that was either created or deleted
obj = CType(mbo("TargetInstance"), ManagementBaseObject)
Select Case mbo.ClassPath.ClassName
Case "__InstanceCreationEvent"
If obj("InterfaceType") = "USB" Then
MsgBox(obj("Caption") & " (Drive letter " & GetDriveLetterFromDisk(obj("Name")) & ") has been plugged in")
End If
Case "__InstanceDeletionEvent"
If obj("InterfaceType") = "USB" Then
MsgBox(obj("Caption") & " has been unplugged")
End If
End Select
End Sub
Private Function GetDriveLetterFromDisk(ByVal Name As String) As String
Dim oq_part, oq_disk As ObjectQuery
Dim mos_part, mos_disk As ManagementObjectSearcher
Dim obj_part, obj_disk As ManagementObject
Dim ans As String
' WMI queries use the "\" as an escape charcter
Name = Replace(Name, "\", "\\")
' First we map the Win32_DiskDrive instance with the association called
' Win32_DiskDriveToDiskPartition. Then we map the Win23_DiskPartion
' instance with the assocation called Win32_LogicalDiskToPartition
oq_part = New ObjectQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=""" & Name & """} WHERE AssocClass = Win32_DiskDriveToDiskPartition")
mos_part = New ManagementObjectSearcher(oq_part)
For Each obj_part In mos_part.Get()
oq_disk = New ObjectQuery("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""" & obj_part("DeviceID") & """} WHERE AssocClass = Win32_LogicalDiskToPartition")
mos_disk = New ManagementObjectSearcher(oq_disk)
For Each obj_disk In mos_disk.Get()
ans &= obj_disk("Name") & ","
Next
Next
Return ans.Trim(","c)
End Function
End Module
Monday, January 08, 2007
Removing Unused or Problem Indexes
all you need is : sys.dm_db_index_usage_stats
http://www.sqlservercentral.com/columnists/aingold/2770.asp
Tuesday, January 02, 2007
x mas (x-men)
sta'day. In the morning we had a superb session on SQL Server By Dishesh Priyankara. I managed to learn da some
of da doubts I had on SQL Server.
after the session I went to enter-Sys to meet pitta and da rest of the guys, and played pool... Played against Cheena... damm..
I won 1 game after playing more than 100s...
party stared in the evnning around 7 and went back home around 4 a.m.
with in that time..
learn about a new pill (two days stright up... drop me an email if you want one :)
two guys almost had a fight
one guy vomited in the cab we went.
had to washe the cab (588588), (almost i vomited)
one guy broke one water tap,
went back in a 3- weeler
Friday, December 22, 2006
Monday, December 11, 2006
how to recover deleted or lost ldf file in SQL Server 2000 database ?
2. EXEC sp_detach_db 'dbname' -- this will detach the database from the server
3. Restart SQL Server
The database may still be seen in enterprise manager, but just ignore it.
4. Create a new database with the same name or a different name. You will have to use a different physical file name, which is fine.
5. Stop SQL Server.
6. Rename the new data file that was created to something else (ex: add.bak to the end)
7. Rename the old data file that you want to restore to the name of the newly created file (the same name as the file you changed in the step above)
8. Start SQL Server
Now the db will still be suspect but you now have a log file.
9. Switch to emergency mode on the database. You do this by doing the following:
1. Right click on the database root node in Enterprise manager and bring up the properties.
2. Under the Server Settings tab, check of "Allow modifications to be made directly to the system catalogs".
3. click ok
4. Now go to the master database and open the sysdatabases table.
5. Find the suspected database in here and modify the status column, setting it to: 32768. This will put it into emergency mode.
6. stop then start sql server
10. Now here's the tricky part and I'm not sure how this will work on a single install, i was lucky enough to have SQL Server 2000 installed. But anyways, open up the Import and Export Data (DTS) program from the start menu. And you want to copy data from the old database to a brand new one. Just copy tables and views.
Wednesday, December 06, 2006
tempdb index planning
http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/tempdb_capacity_planning_index.mspx
Wednesday, November 29, 2006
teleporting ...
there was an intersting program on CNN about the Next Genration Human Transpotation ?? they were taking about various things such as teleporting?.. one woemn was there said it is impossible. That is the same thing we though when ppl said ppl are going to fly,,? isn;t it..
So i though about teleporting.. how to do it? Well if we can compress our selfs and defined in 1's and 0's the we should be able to transport via a cable isn't it ? that is the only way i can think of, or may be i was out of my mind due to sickness
Wednesday, November 22, 2006
Gmail Maps Viewing (GMaps)
only think that you have to do is to pass the correct argements.. But still I cound;t find how to use the birdview.. if you know let me know..
Destination Address
+++++++++++++++
Its address is, roughly, 2233 S. Columbus Blvd.
http://maps.google.com/?q=2233+s+columbus+blvd+philadelphia&z=1
Location wise
+++++++++
I can be more accurate with latitude and longitude. 39.918 N, 75.135W. So this link is even better:
http://maps.google.com/?sll=39.918,-75.136
Parameters are there besides "q" (the regular Google query parameter), "z" (zoomlevel) and "sll" (latitude and longitude)
From : To
+++++++
"q" param denotes "from" in front of the first, and "to" in front of the second, and it will give you the directions between the two addresses.
Example: http://maps.google.com/maps?q=from+2233+s+columbus+blvd+philadelphia+to+1600+pennsylvania+ave,+washington,+dc&z=8
Thursday, November 16, 2006
Two greate Index Build strategys !
http://blogs.msdn.com/sqlqueryprocessing/archive/2006/11/08/index-build-strategy-in-sql-server-introduction-i.aspx
Index Build strategy in SQL Server - Introduction (II)
http://blogs.msdn.com/sqlqueryprocessing/archive/2006/11/09/index-build-strategy-in-sql-server-introduction-ii.aspx
Thursday, November 09, 2006
DataGrid with Excel Copy and Paste
'--------------------------------------------------------------------------------------------------
' Waha gini awelana sului
'------------------------------------------------------------------------------------------
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Data
Imports System.IO
Public Delegate Sub DataGridSelectionChangingEventHandler(ByVal sender As Object, ByVal e As DataGridSelectionChangingEventArgs)
Public Class iOMSelectionDataGrid
Inherits DataGrid
'fired when a selection is about to change
Public Event SelectionChanging As DataGridSelectionChangingEventHandler
'(top,left,bottom,right) of selection
Private _selectedRange As GridRange
'used in drawing
Private _selectionRectangle As Rectangle
Private _clipRectangle As Rectangle
'used to record row-col of click
Private _mouseDownRow As Integer
Private _mouseDownCol As Integer
Private _mouseUpRow As Integer
Private _mouseUpCol As Integer
'used in autoscroll
Private lastMoveHorz As Boolean
Friend WithEvents ContextPasteMenu As System.Windows.Forms.ContextMenu
Friend WithEvents MenuItemPaste As System.Windows.Forms.MenuItem
Friend WithEvents MenuItemClear As System.Windows.Forms.MenuItem
Public Sub New()
_selectedRange = New GridRange
_clipRectangle = Rectangle.Empty
'used to redraw selection during a scroll
AddHandler Me.Scroll, AddressOf HandleScroll
'used to get a clipping rectange for the initial display
AddHandler Me.Paint, AddressOf FirstPaint
Me.ContextPasteMenu = New System.Windows.Forms.ContextMenu
Me.MenuItemPaste = New System.Windows.Forms.MenuItem
Me.MenuItemClear = New System.Windows.Forms.MenuItem
'
'ContextPasteMenu
'
Me.ContextPasteMenu.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItemClear, Me.MenuItemPaste})
'
'MenuItemPaste
'
Me.MenuItemPaste.Index = 0
Me.MenuItemPaste.Text = "&Paste"
'
'MenuItemClear
'
Me.MenuItemClear.Index = 1
Me.MenuItemClear.Text = "&Clear"
'
'set up double buffering to minimize flashing during draws
Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True)
Me.SetStyle(ControlStyles.UserPaint, True)
Me.SetStyle(ControlStyles.DoubleBuffer, True)
End Sub 'New
#Region "Paint & Scroll Event Handlers"
Private Sub FirstPaint(ByVal sender As Object, ByVal e As PaintEventArgs)
'used to mark the size of original clientsize
RemoveHandler Me.Paint, AddressOf FirstPaint
If Not Me.DesignMode Then
_clipRectangle = Me.GetCellBounds(0, 0)
_clipRectangle.Height = Me.Height - _clipRectangle.Y - SystemInformation.HorizontalScrollBarHeight
_clipRectangle.Width = Me.Width - _clipRectangle.X - SystemInformation.VerticalScrollBarWidth
End If
End Sub 'FirstPaint
'helper method that gets the left column from knowing the initial cliprectangle
Public Function LeftColumn() As Integer
Dim hti As DataGrid.HitTestInfo = Me.HitTest(New Point(_clipRectangle.X, _clipRectangle.Y))
Return hti.Column
End Function 'LeftColumn
Private Sub HandleScroll(ByVal sender As Object, ByVal e As EventArgs)
DrawRange(True)
End Sub 'HandleScroll
#End Region
#Region "Selected Range property"
Public Property SelectedRange() As GridRange
Get
Return _selectedRange
End Get
Set(ByVal Value As GridRange)
'If Not (SelectionChanging Is Nothing) Then
Dim e As New DataGridSelectionChangingEventArgs(_selectedRange, Value)
RaiseEvent SelectionChanging(Me, e)
If e.Canceled Then
Return
End If
'End If
_selectedRange = Value
End Set
End Property
#End Region
#Region "mouse events that handle making selections"
Protected Overrides Sub OnMouseDown(ByVal e As System.Windows.Forms.MouseEventArgs)
'remember the initial click
If e.Button = MouseButtons.Left Then
Dim hti As DataGrid.HitTestInfo = Me.HitTest(New Point(e.X, e.Y))
_mouseDownRow = hti.Row
_mouseDownCol = hti.Column
_mouseUpRow = _mouseDownRow
_mouseUpCol = _mouseDownCol
'clear any existing selection
SelectedRange.Clear()
DrawRange(False)
ElseIf e.Button = MouseButtons.Right Then
'// Dispaly the menu on right click
ContextPasteMenu.Show(Me, New Point(e.X, e.Y))
End If
End Sub 'OnMouseDown
Protected Overrides Sub OnMouseMove(ByVal e As System.Windows.Forms.MouseEventArgs)
MyBase.OnMouseMove(e)
If e.Button = MouseButtons.Left Then
Dim hti As DataGrid.HitTestInfo = Me.HitTest(New Point(e.X, e.Y))
Select Case hti.Type
'move to a visible cell with no scrolling
Case HitTestType.Cell
If hti.Column <> Me._mouseUpCol OrElse hti.Row <> Me._mouseUpRow Then
lastMoveHorz = Me._mouseUpCol <> hti.Column
DrawRange(False)
Me._mouseUpCol = hti.Column
Me._mouseUpRow = hti.Row
SelectedRange = New GridRange(Me._mouseUpRow, Me._mouseUpCol, Me._mouseDownRow, Me._mouseDownCol)
DrawRange(True)
End If
Case HitTestType.ColumnHeader
If Me._mouseDownRow = -1 Then
Exit Select
End If
If Me.VertScrollBar.Value > 0 Then
Me.VertScrollBar.Value = Me.VertScrollBar.Value - 1
Me.CurrentRowIndex = Me.VertScrollBar.Value
Me._mouseUpCol = hti.Column
Me._mouseUpRow = Me._mouseUpRow - 1
SelectedRange = New GridRange(Me._mouseUpRow, Me._mouseUpCol, Me._mouseDownRow, Me._mouseDownCol)
DrawRange(True)
End If 'this.Invalidate();
Case HitTestType.RowHeader
If (True) Then
If Me._mouseDownCol = -1 Then
Exit Select
End If
Dim r As Rectangle = Me.GetCellBounds(0, Me._mouseUpCol)
If Me.HorizScrollBar.Value >= r.Width Then
Me.HorizScrollBar.Value -= r.Width
Me._mouseUpCol = Me._mouseUpCol - 1
Me.CurrentCell = New DataGridCell(Me.CurrentRowIndex, Me._mouseUpCol)
Me._mouseUpRow = hti.Row
SelectedRange = New GridRange(Me._mouseUpRow, Me._mouseUpCol, Me._mouseDownRow, Me._mouseDownCol)
DrawRange(True)
End If 'this.Invalidate();
End If
Case HitTestType.None
'Console.WriteLine("HitTestType.None");
If lastMoveHorz Then
Console.WriteLine("lastMoveHorz")
If Me._mouseUpCol < rectangle =" Me.GetCellBounds(0," _mouseupcol =" Me._mouseUpCol" currentcell =" New"> -1 Then
Me._mouseUpRow = hti.Row
End If
SelectedRange = New GridRange(Me._mouseUpRow, Me._mouseUpCol, Me._mouseDownRow, Me._mouseDownCol)
DrawRange(True)
End If
End If 'this.Invalidate();
Else
If Me._mouseUpRow < _mouseuprow =" Me._mouseUpRow"> 0 Then
Me._mouseUpCol = hti.Column
End If
Me.CurrentCell = New DataGridCell(Me._mouseUpRow, Me._mouseUpCol)
SelectedRange = New GridRange(Me._mouseUpRow, Me._mouseUpCol, Me._mouseDownRow, Me._mouseDownCol)
DrawRange(True)
End If 'this.Invalidate();
End If
End Select
End If
End Sub 'OnMouseMove
Protected Overrides Sub OnMouseUp(ByVal e As System.Windows.Forms.MouseEventArgs)
'if normal click clear things & click
If Me._mouseUpCol = Me._mouseDownCol AndAlso Me._mouseUpRow = Me._mouseDownRow Then
DrawRange(False)
_selectionRectangle = Rectangle.Empty
MyBase.OnMouseDown(e)
MyBase.OnMouseUp(e)
End If
End Sub 'OnMouseUp
#End Region
#Region "Drawing Code"
Private Sub DrawRange(ByVal showRange As Boolean)
'if removing selection just redraw
If Not showRange Then
_selectionRectangle = Rectangle.Empty
Me.Invalidate()
Return
End If
If SelectedRange.Left < _selectionrectangle =" Rectangle.Empty" rectangle =" Me.GetCellBounds(SelectedRange.Top," rectangle =" Me.GetCellBounds(SelectedRange.Bottom," x =" rect.Left" w =" rect1.Left" x =" rect1.Left" w =" rect.Left" y =" rect.Top" h =" rect1.Top" y =" rect1.Top" h =" rect.Top" _selectionrectangle =" New" height =" Me.Height" width =" Me.Width" datatable =" getExcelCopiedCells()" datatable =" CType(MyBase.DataSource," integer =" SelectedRange.Top" integer =" SelectedRange.Bottom" integer =" (SelectedRange.Bottom" integer =" SelectedRange.Left" integer =" SelectedRange.Right" integer =" (SelectedRange.Right" integer =" SelectedTop" integer =" SelectedLeft" selectedvalue =" Me(currentRowPos," selectedvalue = "NI" selectedvalue = "NP" selectedvalue = "NC" selectedvalue = "NF" selectedvalue = "ND" selectedvalue = "NT" selectedvalue = "NS" idataobject =" Clipboard.GetDataObject()" char =" {"> 0)
'Array to hold the split data for each row
Dim arrSplitData As Array
'Multipurpose Loop Counter
Dim iLoopCounter As Integer = 0
'Read a line of data from the StreamReader object
sFormattedData = srReadExcel.ReadLine()
'Split the string contents into an array
arrSplitData = sFormattedData.Split(charDelimiterArray)
If tblExcel2WinData.Columns.Count <= 0 Then
For iLoopCounter = 0 To arrSplitData.GetUpperBound(0)
tblExcel2WinData.Columns.Add()
Next
iLoopCounter = 0
End If
'Row to hold a single row of the Excel Data
Dim rowNew As DataRow
rowNew = tblExcel2WinData.NewRow()
For iLoopCounter = 0 To arrSplitData.GetUpperBound(0)
rowNew(iLoopCounter) = arrSplitData.GetValue(iLoopCounter)
Next
iLoopCounter = 0
'Add the row back to the DataTable
tblExcel2WinData.Rows.Add(rowNew)
rowNew = Nothing
End While
'Close the StreamReader object
srReadExcel.Close()
'Bind the data to the DataGrid
Return tblExcel2WinData
Else
MsgBox("Clipboard data does not seem to be copied from Excel!", MsgBoxStyle.Information)
Return Nothing
End If
Else
MsgBox("Clipboard is empty!", MsgBoxStyle.Information)
Return Nothing
End If
Catch exp As Exception
MsgBox(exp.Message, MsgBoxStyle.Information)
Return Nothing
End Try
End Function
Private Sub MenuItemClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MenuItemClear.Click
Dim SelectedTop As Integer = SelectedRange.Top
Dim SelectedBottom As Integer = SelectedRange.Bottom
Dim SelectedTopToBottom As Integer = (SelectedRange.Bottom - SelectedRange.Top) + 1
Dim SelectedLeft As Integer = SelectedRange.Left
Dim SelectedRight As Integer = SelectedRange.Right
Dim SelectedLeftToRight As Integer = (SelectedRange.Right - SelectedRange.Left) + 1
Dim selectedValue As String
'// Row Navigation
For currentRowPos As Integer = SelectedTop To SelectedBottom
'//Column Navigation
For CurrentColPos As Integer = SelectedLeft To SelectedRight
Try
selectedValue = Me(currentRowPos, CurrentColPos)
If selectedValue = "NI" OrElse selectedValue = "NP" OrElse selectedValue = "NC" OrElse selectedValue = "NF" OrElse selectedValue = "ND" OrElse selectedValue = "NT" OrElse selectedValue = "NS" Then
'// Color cells do nothing
Else
Me(currentRowPos, CurrentColPos) = ""
End If
Catch ex As Exception
End Try
Next CurrentColPos
Next currentRowPos
End Sub
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
Dim cellCurrent As DataGridCell
Dim curentCellValue As String
Const WM_KEYDOWN As Integer = &H100
Const WM_SYSKEYDOWN As Integer = &H104
If msg.Msg = WM_KEYDOWN Or msg.Msg = WM_SYSKEYDOWN Then
Select Case keyData
Case Keys.Control Or Keys.V
Call MenuItemPaste_Click(Nothing, Nothing)
End Select
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
End Class 'SelectionDataGrid '
#Region "GridRange class implementation"
'----^--- Pre-processor directives not translated
Public Class GridRange
Private _top As Integer
Private _left As Integer
Private _bottom As Integer
Private _right As Integer
Public Sub New()
_top = -1
_left = -1
_bottom = -1
_right = -1
End Sub 'New
Public Sub New(ByVal t As Integer, ByVal l As Integer, ByVal b As Integer, ByVal r As Integer)
_top = Math.Min(t, b)
_left = Math.Min(l, r)
_bottom = Math.Max(t, b)
_right = Math.Max(l, r)
End Sub 'New
Public Property Top() As Integer
Get
Return _top
End Get
Set(ByVal Value As Integer)
_top = Value
End Set
End Property
Public Property Bottom() As Integer
Get
Return _bottom
End Get
Set(ByVal Value As Integer)
_bottom = Value
End Set
End Property
Public Property Left() As Integer
Get
Return _left
End Get
Set(ByVal Value As Integer)
_left = Value
End Set
End Property
Public Property Right() As Integer
Get
Return _right
End Get
Set(ByVal Value As Integer)
_right = Value
End Set
End Property
Public Sub Clear()
Me.Bottom = -1
Me.Top = -1
Me.Left = -1
Me.Right = -1
End Sub 'Clear
Public Overrides Function ToString() As String
Return "TopLeft:" + Me.Top.ToString() + "," + Me.Left.ToString() + " BottomRight:" + Me.Bottom.ToString() + "," + Me.Right.ToString()
End Function 'ToString
End Class 'GridRange
#End Region
#Region "SelectionChangingEvent class implementation"
Public Class DataGridSelectionChangingEventArgs
Inherits EventArgs
Private _oldRange As GridRange
Private _newRange As GridRange
Private _canceled As Boolean
Public Sub New(ByVal oldValue As GridRange, ByVal newValue As GridRange)
_oldRange = New GridRange(oldValue.Top, oldValue.Left, oldValue.Bottom, oldValue.Right)
_newRange = New GridRange(newValue.Top, newValue.Left, newValue.Bottom, newValue.Right)
_canceled = False
End Sub 'New
Public Property Canceled() As Boolean
Get
Return _canceled
End Get
Set(ByVal Value As Boolean)
_canceled = Value
End Set
End Property
Public Property OldRange() As GridRange
Get
Return _oldRange
End Get
Set(ByVal Value As GridRange)
_oldRange.Bottom = Value.Bottom
_oldRange.Top = Value.Top
_oldRange.Left = Value.Left
_oldRange.Right = Value.Right
End Set
End Property
Public Property NewRange() As GridRange
Get
Return _newRange
End Get
Set(ByVal Value As GridRange)
_newRange.Bottom = Value.Bottom
_newRange.Top = Value.Top
_newRange.Left = Value.Left
_newRange.Right = Value.Right
End Set
End Property
End Class 'DataGridSelectionChangingEventArgs
#End Region
Tuesday, October 31, 2006
Fine Tuning your Database Design in SQL 2005
check it out @
http://www.simple-talk.com/sql/sql-server-2005/fine-tuning-your-database-design-in-sql-2005/
Friday, October 27, 2006
PIVOT dynamic column list
is it a bug ??
I found to achive it by doing hours of trying ....
DECLARE @colList VARCHAR(1024)
SELECT @colList = COALESCE(@colList + ',', '') + Subject FROM
(
SELECT DISTINCT '[' + Subject + ']' AS Subject
FROM StudentMarks
) AS StudentMarksColList
--get the column in the array format [maths], [science] ect ..
SELECT @colList
EXEC('SELECT * FROM StudentMarks
PIVOT
(
SUM(Marks)
FOR Subject
IN ('+ @colList +')
)AS p')
Wednesday, October 25, 2006
SQL Articals
http://www.code-magazine.com/Article.aspx?quickid=060063
http://www.code-magazine.com/Article.aspx?quickid=060093
Wednesday, October 18, 2006
BCS Exam
Wednesday, October 11, 2006
What's The Resolution?
http://www.code-magazine.com/Article.aspx?quickid=060083
Monday, October 09, 2006
Inserting way to insert data to the tabase
1. Reduce round trips
2. cocurrency handing
3. More control over the logic
4. it is clear.. !!!!
create proc dbo.Item_Add_toOrderList
(
@orderNumber char(20)
@itemNumber char(20)
@processedBy varchar(64) = null
)
as
declare @errorNumber
-- Test processedBy
if (@processedBy is null) set @processedBy = system_user
-- Transaction
begin tran
-- Test orderNumber (makre sure an appropriate order exists)
if not exists(select OrderID from dbo.Order where (OrderNumber =
@orderNumber))
begin
rollback tran
raiserror ('Item Add failed: orderNumber %s unknown.', 16, 1,
@orderNumber)
return -1
/*
This is the first point at which the transaction will be rolled back if one
of the parameters is erroneous.
*/
end
-- Initialize errorNumber
set @errorNumber = 0
insert dbo.Item
(
orderNumber
,itemNumber
,processedBy
,processedOn
)
select @orderNumber as orderNumber
,@itemNumber as itemNumber
,@processedBy as processedBy
,getdate() as processedOn
-- store current error code
set @errorNumber = @@error
if (@errorNumber != 0)
begin
rollback tran
raiserror ('Item Add failed: an error has occured.', 16, 1)
return @errorNumber
/* Here the transaction is rolled-back if an error occured at insert. */
end
else
begin
commit tran
return 0
/* If no error present transaction is committed. */
end
go
Sunday, October 08, 2006
Life
We all have a child hood that we can't forget or that we are trying to forget. Then we try to find a job that we can really enjoy, suddenly we get sick of it and you wish to go back to old that .. fun days!!! . And so on you get married and have kids and you watch how they grow up?.
finally when you look bouth you see that parents, brothers, relatives all are passed away.. And now it is your turn.. suddenly we are feeling the frear to die..
And one fine day you die.. That is what we all do ? have you ever though of doing some thing apart from that ?? those are the very basic things that common to all of us, We have to brake that chain... but how???
think who do whant to be in life that you will engoy.. otherwise one day we will feel that we have forgoten to enjoy our lifes so enjoy!
besides, if you figure out a way please let me know coz still i am thinking ....!
Thursday, October 05, 2006
Improve Performance with SQL 2005 Covering Index Enhancements
Improve Performance with SQL 2005 Covering Index Enhancements
http://www.mssqltips.com/tip.asp?tip1078
http://msdn2.microsoft.com/en-us/library/ms190806.aspx
Wednesday, October 04, 2006
Passing parameters to SPs
I have head lot of people are asking how to pass paramerts to a stored proc ?? this is how i like to do
<args>
<customerid>12</customerid>
</args>