Anil Sharma

just for code

How to Delete a Windows Service in Windows 7 or Vista or XP

The first thing you’ll need to identify the name of the service, so open up Services through the start menu or control panel, and then find the service in the list that you want to delete.

ou’ll need to open up a command prompt, and if you are using Windows 7 or Vista you’ll need to right-click the command prompt and choose Run as Administrator. We’ll use the sc command to actually do the work.

The syntax used to delete a service is this:

sc delete ServiceName

Delete a windows service

Here Iit.VPGiveUpService is name of service.

January 22, 2015 Posted by | IT | , , , , , , | Leave a comment

Visual Studio Shortcuts

  • CTRL + “.”: This is actually a shortcut for a shortcut. it is the same as CTRL + SHIFT + F10 which opens the smart tag window and allows you to add Using statements.
  • ALT + CTRL + “e”: This one will open the Exceptions window, which allows you to tell Visual Studio to halt at specific exceptions.
  • CTRL + “k” + “f” and CRTL + “k” + “d”: these two will format the code in the window to be nicely indented. using “d” will format all the document while using “f” will format only selected text. The formatting is for all types of documents, HTML, Xaml, XML, C#…
  • SHIFT + Del:This one will cut the entire row from the document and past it to the clipboard. No need to select the row, just put the marker there and click SHIFT + Del and it is gone.
  • CTRL + “k” + “c” and CTRL + “k” + “u”:These two are for commenting selected text (the “c” options) and uncommenting selected text (the “u” option).
  • ALT + ENTER: this little shortcut will open up the Properties window
  • CTRL + “k” + “s”:This one opens up the code snippets dialogue within the code.
  • F12: I think you all know this but still F12 is the shortcut for the “Go to definition” command which will take you to the definition of the object your marker is currently on.
  • F9: Another one i think you all know, clicking on F9 will add a breakpoint to the code line your marker is currently at. Clicking F9 again will remove this breakpoint from that line.
  • CTRL + ALT + “q”: This one will open the Quick watch window while
  • CTRL –
    and
    CTRL SHIFT –It moves the editing cursor to the last/next position
    this is great if you decide to edit something somewhere else and you want to go back to that last method you were editing. CTRL – will save you so much time!
  • Alt + Enter is also a general Windows shortcut for accessing properties of files, drives, shortcuts, etc. It is a nice keystroke to keep in mind.
  • Shift + Alt + Enter (FullScreen mode) is a must know! It helps you to get rid of all the properties, toolbar and other [obstrusive] windows that don’t let you see the code. Hit it a second time and the windows are back.
  • CTRL+M+M : Expanding / Collapsing code blocks, e.g. regions/methods.
    CTRL + ALT + P (attach to process) is very useful when you’re debugging web sites, windows services, etc.
  • CTRL + R + R (rename) is great for refactoring, particularly if you have Reshaper installed
  • Ctrl+Shift+B — Build solution
    Ctrl+J — Intellisense, list members
    Ctrl+Shift+Space — Intellisense, list parameter infoThe list members shortcut is handy. Before I started using this a lot, I would sometimes type ‘this.’ to get a list of members. The parameter info is helpful for seeing information about parameters you already typed in.
  • Lot of items can be accessed from the ‘Context Menu Key’ (assuming your keyboards have that key…the one that looks like a little menu)…CTX+Q – Quick Watch
    CTX+D – Definition
    CTX – same as CTRL+. aboveI generally can get almost anything done with CTX+key or CTX then a quick combo of down and right arrows.

Source : Internet

December 17, 2014 Posted by | Developement, visual studio | , , , , , , , , , , , , | Leave a comment

Find Dependencies on a specific table column in SQL SERVER

SQL Server provides a built-in stored procedure, sp_depends, that returns object dependencies.  Recently, I discovered a need for determining dependencies on a table column, not just the table itself.  For example, a table may be referenced by many stored procedures and views, but a specific column in that table may only be referenced in a few of those objects.  The following code will determine which views and stored procedures reference a specific column in a table, and whether the object is a view (V) or stored procedure (P).

SELECT OBJECT_NAME(sd.id) Dependent_Object,
(SELECT xtype FROM sysobjects so WHERE so.id = sd.id) Object_Type
FROM sysobjects so INNER JOIN syscolumns sc
ON so.id = sc.id
INNER JOIN sysdepends sd
ON so.id = sd.depid and sc.colid = sd.depnumber
WHERE so.id = OBJECT_ID(‘tableName’)
AND sc.name = ‘ColumnName’
 

 

February 25, 2014 Posted by | sqlserver | , , , , , | Leave a comment

User Account Control – Run Application with Admin privileges in Vista/Windows 7

UAC – User Account Control :

Some time we need run application under admin privileges then we need to update UAC with application manifest setting.

By default, Windows Vista® and Windows Server 2008 will run every application as a standard user even if you log on as a member of the administrator’s group. Conversely, when users attempt to launch an application that has been marked as requiring administrator permissions, the system will explicitly ask them to confirm their intention to do so. Only applications running with administrator privileges can modify system and global settings and behavior. This feature of Windows Vista and Windows Server 2008 is the User Account Control (UAC).

To resolve this we need to update .manifest file of application. In manifest file it has node requestedExecutionLevel .

It has attribute “level”. For this there are three options

1-asInvoker – Runs application as logged user account.

2-requireAdministrator – Runs application as Admin privileges.

3-highestAvailable – Runs application as highest privileges under logged user account.

<!–?xml version=”1.0″ encoding=”utf-8″?>
<asmv1:assembly manifestVersion=”1.0″ xmlns=”urn:schemas-microsoft-com:asm.v1″
xmlns:asmv1=”urn:schemas-microsoft-com:asm.v1″ xmlns:asmv2=”urn:schemas-microsoft-com:asm.v2″
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”&gt;
<assemblyIdentity version=”1.0.0.0″ name=”MyApplication.app”/>
<trustInfo xmlns=”urn:schemas-microsoft-com:asm.v2″>
<security>
<requestedPrivileges xmlns=”urn:schemas-microsoft-com:asm.v3″>
<!– UAC Manifest Options–>
If you want to change the Windows User Account Control level replace the
requestedExecutionLevel node with one of the following.

<requestedExecutionLevel  level=”asInvoker” uiAccess=”false” />
<requestedExecutionLevel level=”requireAdministrator” uiAccess=”false” />
<requestedExecutionLevel level=”highestAvailable” uiAccess=”false” />

If you want to utilize File and Registry Virtualization for backward
compatibility then delete the requestedExecutionLevel node.
–>
 <requestedExecutionLevel level=”asInvoker” uiAccess=”false” />
      </requestedPrivileges>
</security>
</trustInfo>
<!–asmv1:assembly>

 

If your application always requires administrator privileges, then you can change this value to “requireAdministrator”. Now, whenever your application starts it will always trigger UAC and ask the user to allow administrator access for your program.

Note that it’s worth seriously considering whether you actually need to do this, and why – especially given the intrusive experience of UAC. For instance, you shouldn’t need to write settings to Program Files, as Windows provides the user profile area and registry for just that purpose. In general UAC should hopefully force us all to think a bit more carefully about where we’re storing data, and what permissions the application *really* needs.

August 15, 2011 Posted by | Developement | , , , , , , | 1 Comment

Tips for improving performance of WPF applications.

Windows Presentation Foundation provides a very confortable way to develop rich user experiences. A drop shadow for example can added by inserting two simple lines of XML. But this simplicity can also mislead us to overuse them. This leads to performance issues. The following tips may help you to avoid or fix them.

1-Dispatch expensive calls either within the UI thread with a lower DispatcherPriority by calling Dispatcher.BeginInvoke() or to a background thread by using a BackgroundWorker to keep the UI responsive.
2-Fix binding errors because they consume a lot of time, trying to resolve the path error, including searching for attached properties. You can find them by looking for System.Windows.Data Error in the Visual Studio output log.
3-Reduce the number of visuals by removing unneeded elements, combining layout panels and simplifying templates. This keeps the memory footprint small and improves the rendering performance.
4-Prevent Software Rendering. The use of transparent windows by setting AllowsTransparency to true or using old BitmapEffects can cause WPF to render the UI in software on Windows XP, which is much slower.
5-Load resources when needed. Even thow it’s the most comfortable way to merge all resources on application level it can also cost performance by loading all resources at startup. A better approach is to load only often used resources and load the other on view level.
6-Virtualize lists and views by using a VirtualizingStackPanel as ItemsPanel for lists. This only creates the visible elements at load time. All other elements are lazy created when they get visible. Be aware that grouping or CanContextScrol=”True” prevents virtualization!
7-Enable Container Recycling. Virtualization brings a lot of performance improvements, but the containers will be disposed and re created, this is the default. But you can gain more performance by recycle containers by setting VirtualizingStackPanel.VirtualizationMode=”Recycling”
8-Freeze Freezables by calling Freeze() in code or PresentationOptions:Freeze=”true” in XAML. This reduces memory consumption and improves performance, because the system don’t need to monitor for changes.
9-Disable Assembly localization if you don’t need it. By using the [NeutralResourcesLanguageAttribute]. This prevents an expensive lookup for satelite assemblies
10-Lower the framerate of animations by setting Storyboard.DesiredFrameRate to lower the CPU load. The default is 60 frames/second
Use StreamGeometries instead of PathGeometries if possible to draw complex 2D geometries, because they are much more efficient and consume less memory.

11-Fix binding errors:-
These errors generaly get intoduced in the application when we use MVVM design patttern and common controls.WPF window render time improved after fixing all binding errors

July 26, 2011 Posted by | asp.net | , , , , , , | Leave a comment

Online job

Work at home

Job at home

Whether you are looking for a gainful work at home or whether you desire getting income live; yes, in the end, you found it!

Receive financial independence

No pc skills needed. You can be completely new to control our application – you don’t need ANY knowledge. This is really easy.

You may stay at home and work at your free time. Even if you don’t have pc you may do this work in Internet cafe or on Internet mobile phone.

How it works?

We design a online-store for you with ready to operate e-commerce products. Your job is extremely easy; you have to post information about your web-shop to the Internet directories.
We will provide you with extremely simple step-by-step instruction how to do this. The typical instruction asks you to open a internet web site and fill in a form with information about your web-store and software.

You will be paid from US $20.00 to US 180.00 for each sale which is comes via your web-store.

There is no limitation for your revenue. No matter where you live your pay outs are 100% guaranteed.

Register Now…

Apply now to get economic independence. All you need is the simple: register now and getpersonal web business!

July 5, 2011 Posted by | asp.net | Leave a comment

TextBox Validation in WPF

To validate textinput type in wpf  is good by introduce dependency property.

Now we have many types of validation

1-Numeric

2-AlphaNumeric

3-Decimal

To support all types of validation we have Enum type

public enum TextValidationType
{
/// <summary>
/// Default Value
/// </summary>
Default = 0,

/// <summary>
/// For Numeric value validation
/// </summary>
Numeric = 1,

/// <summary>
///  For Deciaml value validation
/// </summary>
Decimal = 2,

/// <summary>
///  For Alphanumeric value validation
/// </summary>
Alphanumeric = 3,

/// <summary>
///  For Letter validation
/// </summary>
Letter = 4,

/// <summary>
///  For LetterUppercase value validation
/// </summary>
LetterUppercase = 5,

/// <summary>
///  For LetterLowercase value validation
/// </summary>
LetterLowercase = 6,

/// <summary>
///  For Numeric with dash value validation
/// </summary>
NumericSSN = 7,

/// <summary>
///  For Numenric with dash value validation
/// </summary>
NumericVital = 8,

/// <summary>
///  For AlphaNumericVital with dash value validation
/// </summary>
AlphaNumericVital = 9,

/// <summary>
///  For NegativeDecimal with dash value validation
/// </summary>
NegativeDecimal = 10,

/// <summary>
/// For Numeric Value with Percentage validation
/// </summary>
NumericPercent = 11,

/// <summary>
/// For Numeric Value with Zip validation
/// </summary>
NumericZip=12

}

And Class Is

————————————

public static class TextBoxValidation
{
static int intCaretIndex = 0;
static int inttextboxlength=0;

#region Focus Change

/// <summary>
/// Gets the focus change.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <returns></returns>
public static bool GetFocusChange(DependencyObject obj)
{
return (bool)obj.GetValue(FocusChangeProperty);
}

/// <summary>
/// Sets the focus change.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <param name=”value”>if set to <c>true</c> [value].</param>
public static void SetFocusChange(DependencyObject obj, bool value)
{
obj.SetValue(FocusChangeProperty, value);
}

// Using a DependencyProperty as the backing store for MaxValue.  This enables animation, styling, binding, etc…
/// <summary>
/// MAx Value Dependency Property
/// </summary>
public static readonly DependencyProperty FocusChangeProperty =
DependencyProperty.RegisterAttached(“FocusChange”, typeof(bool), typeof(TextBoxValidation), new UIPropertyMetadata(null));

#endregion

#region MAXVALUE
/// <summary>
/// Gets the max value.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <returns></returns>
public static decimal GetMaxValue(DependencyObject obj)
{
return (decimal)obj.GetValue(MaxValueProperty);
}

/// <summary>
/// Sets the max value.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <param name=”value”>The value.</param>
public static void SetMaxValue(DependencyObject obj, decimal value)
{
obj.SetValue(MaxValueProperty, value);
}

// Using a DependencyProperty as the backing store for MaxValue.  This enables animation, styling, binding, etc…
/// <summary>
/// MAx Value Dependency Property
/// </summary>
public static readonly DependencyProperty MaxValueProperty =
DependencyProperty.RegisterAttached(“MaxValue”, typeof(decimal), typeof(TextBoxValidation), new UIPropertyMetadata(null));
#endregion

#region MinValue
/// <summary>
/// Gets the Min value.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <returns></returns>
public static decimal GetMinValue(DependencyObject obj)
{
return (decimal)obj.GetValue(MinValueProperty);
}

/// <summary>
/// Sets the Min value.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <param name=”value”>The value.</param>
public static void SetMinValue(DependencyObject obj, decimal value)
{
obj.SetValue(MinValueProperty, value);
}

// Using a DependencyProperty as the backing store for MaxValue.  This enables animation, styling, binding, etc…
/// <summary>
/// MAx Value Dependency Property
/// </summary>
public static readonly DependencyProperty MinValueProperty =
DependencyProperty.RegisterAttached(“MinValue”, typeof(decimal), typeof(TextBoxValidation), new UIPropertyMetadata(null));

#endregion

/// <summary>
/// Gets the type of the text box validation.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <returns></returns>
public static TextValidationType GetTextBoxValidationType(DependencyObject obj)
{
return (TextValidationType)obj.GetValue(TextBoxValidationTypeProperty);
}

/// <summary>
/// Sets the type of the text box validation.
/// </summary>
/// <param name=”obj”>The obj.</param>
/// <param name=”value”>The value.</param>
public static void SetTextBoxValidationType(DependencyObject obj, TextValidationType value)
{
obj.SetValue(TextBoxValidationTypeProperty, value);
}

// Using a DependencyProperty as the backing store for TextBoxValidationType.  This enables animation, styling, binding, etc…
public static readonly DependencyProperty TextBoxValidationTypeProperty =
DependencyProperty.RegisterAttached(“TextBoxValidationType”, typeof(TextValidationType), typeof(TextBoxValidation), new UIPropertyMetadata(TextValidationType.Default, OnValueChanged));

/// <summary>
/// Handles changes to the IsDecimalOnly property.
/// </summary>
/// <param name=”d”><see cref=”DependencyObject”/> that fired the event</param>
/// <param name=”e”>A <see cref=”DependencyPropertyChangedEventArgs”/> that contains the event data.</param>
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextValidationType isNumeric = (TextValidationType)e.NewValue;
if (d.DependencyObjectType.Name == “TextBox”)
{
TextBox textBox = (TextBox)d;

if (isNumeric != TextValidationType.Default)
{
textBox.PreviewTextInput += BlockNonDigitCharacters;
textBox.TextChanged += TextBox_TextChanged;
textBox.PreviewKeyDown += ReviewKeyDown;
}
else
{
textBox.PreviewTextInput -= BlockNonDigitCharacters;
textBox.PreviewKeyDown -= ReviewKeyDown;
textBox.TextChanged -= TextBox_TextChanged;
}
}
}

/// <summary>
/// Handles the TextChanged event of the textBox control.
/// </summary>
/// <param name=”sender”>The source of the event.</param>
/// <param name=”e”>The <see cref=”System.Windows.Controls.TextChangedEventArgs”/> instance containing the event data.</param>
public static void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
DependencyObject depSender = sender as DependencyObject;

TextBox textBox = (sender as TextBox);
decimal value, maxValue, minvalue;
decimal.TryParse(textBox.Text, out value);
maxValue = GetMaxValue(depSender);
minvalue = GetMinValue(depSender);
int intMin = ((System.Windows.Controls.TextBox)(((System.Windows.RoutedEventArgs)(e)).Source)).CaretIndex – 1;
TextValidationType isNumeric = GetTextBoxValidationType((DependencyObject)sender);
if (isNumeric != TextValidationType.NumericPercent)
{
if (maxValue != 0 || minvalue != 0)
{
CalculateMaxLength(e, textBox, intMin, value, maxValue, minvalue);
return;
}
}
else
{
if (value < maxValue && value > minvalue && intMin < textBox.MaxLength)
{
e.Handled = true;
return;

}
if (intMin == textBox.MaxLength – 1)
{

textBox.Text = textBox.Text.Remove(textBox.Text.Length – 1);
textBox.Text = textBox.Text.Insert(intMin, “%”);
textBox.CaretIndex = textBox.Text.Length;
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;

}
if (intMin == 0 && textBox.Text.Contains(“%”))
{
textBox.Text = textBox.Text.Remove(textBox.Text.Length – 1);
textBox.CaretIndex = textBox.Text.Length;
e.Handled = true;
return;
}
}

}

/// <summary>
/// Calculates the length of the max.
/// </summary>
/// <param name=”e”>The <see cref=”System.Windows.Controls.TextChangedEventArgs”/> instance containing the event data.</param>
/// <param name=”textBox”>The text box.</param>
/// <param name=”intMin”>The int min.</param>
/// <param name=”value”>The value.</param>
/// <param name=”maxValue”>The max value.</param>
/// <param name=”minvalue”>The minvalue.</param>
private static void CalculateMaxLength(TextChangedEventArgs e, TextBox textBox, int intMin, decimal value, decimal maxValue, decimal minvalue)
{
if (string.IsNullOrEmpty(textBox.Text))
{
textBox.MaxLength = inttextboxlength;
return;
}
if (value <= maxValue && value >= minvalue)
{
e.Handled = true;
return;
}
else if (value > maxValue || value < minvalue)
{
EndofTextboxFocusChange(e, textBox);
return;
}

}

/// <summary>
/// Focuses the navigation direction for textbox.
/// </summary>
private static void FocusNavigationDirectionForTextbox()
{
FocusNavigationDirection focusDirection = FocusNavigationDirection.Next;

// MoveFocus takes a TraveralReqest as its argument.
TraversalRequest request = new TraversalRequest(focusDirection);

// Gets the element with keyboard focus.
UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;

// Change keyboard focus.
if (elementWithFocus != null)
{
elementWithFocus.MoveFocus(request);
}
}

/// <summary>
/// Endofs the textbox focus change.
/// </summary>
/// <param name=”e”>The <see cref=”System.Windows.Controls.TextChangedEventArgs”/> instance containing the event data.</param>
/// <param name=”textBox”>The text box.</param>
private static void EndofTextboxFocusChange(TextChangedEventArgs e, TextBox textBox)
{
textBox.Text = textBox.Text.Remove(textBox.Text.Length – 1);
textBox.CaretIndex = textBox.Text.Length;
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}

/// <summary>
/// Disallows non-digit character.
/// </summary>
/// <param name=”sender”>The source of the event.</param>
/// <param name=”e”>An <see cref=”TextCompositionEventArgs”/> that contains the event data.</param>
private static void BlockNonDigitCharacters(object sender, TextCompositionEventArgs e)
{
TextBox textBox = (sender as TextBox);
int objSender = textBox.CaretIndex;
TextValidationType isNumeric = GetTextBoxValidationType((DependencyObject)sender);
foreach (char ch in e.Text)
{
if ((string.IsNullOrEmpty(textBox.Text) && textBox.MaxLength == inttextboxlength) ||
inttextboxlength==0)
{
inttextboxlength = textBox.MaxLength;
}
if (isNumeric == TextValidationType.Numeric)
{
if (!Char.IsDigit(ch))
{
e.Handled = true;
}
if (objSender == textBox.MaxLength – 1)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}
}
else if (isNumeric == TextValidationType.Decimal)
{

if (!Char.IsDigit(ch) && ch != ‘.’)
{
e.Handled = true;
}
if (textBox.Text.Contains(“.”) && ch == ‘.’)
{
e.Handled = true;
}
if (ch == ‘.’ && !textBox.Text.Contains(“.”))
{
textBox.MaxLength = inttextboxlength;
textBox.MaxLength = textBox.MaxLength + 3;
}
if (objSender == textBox.MaxLength)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}
}
else if (isNumeric == TextValidationType.Alphanumeric)
{
if (!char.IsLetterOrDigit(ch) && ch != ‘.’)
{
e.Handled = true;
}
if (textBox.Text.Contains(“.”) && ch == ‘.’)
{
e.Handled = true;
}
if (objSender == textBox.MaxLength – 1)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}
}
else if (isNumeric == TextValidationType.Letter)
{
if (!char.IsLetter(ch))
{
e.Handled = true;
}
}
else if (isNumeric == TextValidationType.LetterLowercase)
{
if (!char.IsLetter(ch) || !char.IsLower(ch))
{
e.Handled = true;
}
}
else if (isNumeric == TextValidationType.LetterUppercase)
{
if (!char.IsLetter(ch) || !char.IsUpper(ch))
{
e.Handled = true;
}
}
else if (isNumeric == TextValidationType.NumericSSN)
{
if (objSender == 3 || objSender == 6)
{
if (!char.IsDigit(ch) && ch == ‘-‘)
{
e.Handled = false;
}
else
{
e.Handled = true;
}

}
else if (!char.IsDigit(ch))
{
e.Handled = true;
}

}
else if (isNumeric == TextValidationType.NumericVital)
{
if ((!Char.IsDigit(ch) && ch != ‘-‘) ||
(textBox.Text.Contains(“-“) && ch == ‘-‘) ||
(objSender != 0 && ch == ‘-‘))
{
e.Handled = true;
}
if (ch == ‘-‘)
{
textBox.MaxLength = textBox.MaxLength + 1;
}
if (objSender == textBox.MaxLength)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}
}
else if (isNumeric == TextValidationType.AlphaNumericVital)
{
if (!char.IsLetterOrDigit(ch) && ch == ‘-‘)
{
e.Handled = false;
}
if ((textBox.Text.Contains(“-“) && ch == ‘-‘) ||
(objSender != 0 && ch == ‘-‘))
{
e.Handled = true;
}
if (ch == ‘-‘)
{
textBox.MaxLength = textBox.MaxLength + 1;
}
if (objSender == textBox.MaxLength)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}
}
else if (isNumeric == TextValidationType.NegativeDecimal)
{

if (!Char.IsDigit(ch) && ch != ‘.’ && ch != ‘-‘)
{
e.Handled = true;
}
if ((textBox.Text.Contains(“.”) && ch == ‘.’) ||
(objSender != 0 && ch == ‘-‘))
{
e.Handled = true;
}
if (ch == ‘-‘)
{
textBox.MaxLength = textBox.MaxLength + 1;
}
if (ch == ‘.’ && !textBox.Text.Contains(“.”))
{
textBox.MaxLength = inttextboxlength;
textBox.MaxLength = textBox.MaxLength + 3;
}
if (objSender == textBox.MaxLength)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}

}
else if (isNumeric == TextValidationType.NumericPercent)
{
if (!Char.IsDigit(ch) && ch != ‘%’)
{
e.Handled = true;
}
if (textBox.Text.Contains(“%”) && ch == ‘%’)
{
e.Handled = true;
}
if (textBox.Text.Contains(“%”))
{
intCaretIndex = textBox.Text.IndexOf(‘%’);
if (intCaretIndex < objSender)
e.Handled = true;
}
if (objSender == textBox.MaxLength – 1)
{
FocusNavigationDirectionForTextbox();
e.Handled = true;
return;
}
}
else if (isNumeric == TextValidationType.NumericZip)
{
if (objSender == 2 || objSender == 5 || objSender == 8)
{
if (!char.IsDigit(ch) && ch == ‘-‘)
{
e.Handled = false;
}
else
{
e.Handled = true;
}

}
else if (!char.IsDigit(ch))
{
e.Handled = true;
}
}
}
}

/// <summary>
/// space key.
/// </summary>
/// <param name=”sender”>The source of the event.</param>
/// <param name=”e”>An <see cref=”KeyEventArgs”/> that contains the event data.</param>
private static void ReviewKeyDown(object sender, KeyEventArgs e)
{
TextValidationType isNumeric = GetTextBoxValidationType(sender as DependencyObject);
if (e.Key == Key.Space)
{
if (isNumeric == TextValidationType.Alphanumeric)
{
// Allow the space key, which  raises a PreviewTextInput event.
e.Handled = false;
}
else
{
// Disallow the space key, which doesn’t raise a PreviewTextInput event.
e.Handled = true;
}
}
}
}

———————————————–

USE IN xaml

MAKE REFERENCE IN XAML

xmlns:UC=”clr-namespace:Test.Presentation.UserControls” /// Location of TextValidation file

<TextBox Grid.Row=”4″ Grid.Column=”1″
UC:TextBoxValidation.TextBoxValidationType=”NumericZip”/>

March 23, 2011 Posted by | TextBox Validation, WPF | , , , , , , , , | Leave a comment

Gmail chat – how to type words in bold and italics

 how to type a word in bold. how to type in italics, and also strikethrough a word.

Bold: Surround the word with asterisks, e.g. *word* -> word
Italics: Surround the word with underscores, e.g. _word_ -> word
Strikethrough: Surround the word with hyphens, e.g. -word- -> word

August 29, 2009 Posted by | Developement, Normal | , | Leave a comment

ASP.NET – How to call a server-side method from client-side JavaScript

Introduction

This is a tutorial on how to call a server-side ASP.NET method from a client-side JavaScript method.

If you are wondering when that could become useful, imagine the following scenario:

A Web Application having an implemented authentication system.
Users log in with their username and password.
At any point the user is able to log out by clicking on the respective “Log Out” button.
On the server-side, the log out action would trigger a cleaning up process of user’s temp data.

However, the user instead of clicking on the “Log Out” button, may simply close the browser window. Now since HTTP is a stateless protocol, the server-side cannot directly detect the user’s action. Therefore the client-side (browser) would have to notify the server that the user is closing the window.

A solution to this problem would be to call a JavaScript function when the client-side “onUnload” event is triggered. The JavaScript function would then be able to call the appropriate server-side method to clean up the data.

The exact required AJAX mechanism to accomplish that kind of communication is described on the “Hello World” project below.

Please note that for the purpose of this tutorial all methods are kept as simple as possible, so that you can easily modify them for your application.

1. Creating a new ASP.NET project

AJAX is required, thus a new “AJAX enabled ASP.NET Web Application” has to be created on Visual Studio 2005 or “ASP.NET Web Application” on  2008.

aspnet_server_side_from_client_side_1

2. Modifying the server-side code

Every server-side method that is called from the client-side, must be declared as “static”, and also has to be decorated with the [System.Web.Services.WebMethod] tag.

Now let’s create a simple function that returns a string value.

  •   
  • [System.Web.Services.WebMethod]   
  •  public static string Message()   
  • {   
  •     return “Hello from the server-side World!”;   
  • }  
  • [System.Web.Services.WebMethod]
    public static string Message()
    {
        return "Hello from the server-side World!";
    }

    3. Modifying the ScriptManager

    The “EnablePageMethods” attribute has to be added on the ScriptManager tag.

  • <asp:ScriptManager ID=“ScriptManager1” runat=“server” EnablePageMethods=“true” />  
  • <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />

    4. Adding a simple HTML button

    We are going to add a simple HTML button rather than a server-side ASP.NET button control. The “onClick” event is going to be associated with the JavaScript function “GetMessage”.

  • <input onclick=“GetMessage()” type=“submit” value=“Get Message” />  
  • <input onclick="GetMessage()" type="submit" value="Get Message" />

    5. Adding the JavaScript code

    Let’s add the “GetMessage” JavaScript function, which is going to call our server-side “Message” method.

  •   
  •  function GetMessage() {   
  •     PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure);   
  • }  
  • function GetMessage() {
        PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure);
    }

    The “OnGetMessageSuccess” is the name of the JavaScript function that will be called if the request is successful. Whereas the “OnGetMessageFailure” will be called if an exception is thrown.

    So let’s add these two functions:

  •   
  •  function OnGetMessageSuccess(result, userContext, methodName) {   
  •     alert(result);   
  • }   
  •   
  •  function OnGetMessageFailure(error, userContext, methodName) {   
  •     alert(error.get_message());   
  • }  
  • function OnGetMessageSuccess(result, userContext, methodName) {
        alert(result);
    }
    
    function OnGetMessageFailure(error, userContext, methodName) {
        alert(error.get_message());
    }

    Please note that you can give to the functions any name you wish, as long as they match the PageMethods call parameters.

    If there are no errors, the “OnGetMessageSuccess” will show a pop-up window with our server-side “Message” text. Else, the pop-up will have an exception message.

    6. Running the Web Application

    This is it, we are ready to run our Web Application. Everything seems to be working just fine on Internet Explorer (IE6 and IE7):

    aspnet_server_side_from_client_side_2

    However if we run it on Firefox (currently the latest version is 3.0.4) the pop-up will display the following message:

    The server method ‘Message’ failed.

    aspnet_server_side_from_client_side_3

    7. Fixing the Firefox issue

    We just need to modify the button’s onclick event a bit:

  • <input type=“submit” value=“Get Message” onclick=“GetMessage();return false;” />  
  • <input type="submit" value="Get Message" onclick="GetMessage();return false;" />

    And this would do the trick:

    aspnet_server_side_from_client_side_4

    8. Here is the complete source code for your reference

    Default.aspx

    (Had to replace double quotes (”) with single quote (’) in order to post it correctly.)

  •   
  •  <%@ Page Language=‘C#’ AutoEventWireup=‘true’ CodeBehind=‘Default.aspx.cs’ Inherits=‘AJAXEnabledWebApplication2._Default’ %>  
  •   
  • <!DOCTYPE html PUBLIC ‘-//W3C//DTD XHTML 1.0 Transitional//EN’ ‘http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&#8217;>  
  •   
  •  <html xmlns=http://www.w3.org/1999/xhtml&#8217; >  
  •  <head runat=‘server’>  
  •     <title>Page</title>  
  •     <script type=‘text/javascript’>  
  •         function GetMessage() {   
  •             PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure);   
  •         }   
  •         function OnGetMessageSuccess(result, userContext, methodName) {   
  •             alert(result);   
  •         }   
  •         function OnGetMessageFailure(error, userContext, methodName) {   
  •             alert(error.get_message());   
  •         }   
  •     </script>  
  •  </head>  
  • <body>  
  •     <form id=‘form1’ runat=‘server’>  
  •     <asp:ScriptManager ID=‘ScriptManager1’ runat=‘server’ EnablePageMethods=‘true’ />  
  • <div>  
  •             <input type=‘submit’ value=‘Get Message’ onclick=‘GetMessage();return false;’ /></div>  
  • </form>  
  • </body>  
  • </html>  
  • <%@ Page Language='C#' AutoEventWireup='true' CodeBehind='Default.aspx.cs' Inherits='AJAXEnabledWebApplication2._Default' %>
    
    <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
    
    <html xmlns='http://www.w3.org/1999/xhtml' >
    <head runat='server'>
        <title>Page</title>
        <script type='text/javascript'>
            function GetMessage() {
                PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure);
            }
            function OnGetMessageSuccess(result, userContext, methodName) {
                alert(result);
            }
            function OnGetMessageFailure(error, userContext, methodName) {
                alert(error.get_message());
            }
        </script>
    </head>
    <body>
        <form id='form1' runat='server'>
        <asp:ScriptManager ID='ScriptManager1' runat='server' EnablePageMethods='true' />
    <div>
                <input type='submit' value='Get Message' onclick='GetMessage();return false;' /></div>
    </form>
    </body>
    </html>

    Default.aspx.cs

  •   
  • using System;   
  • using System.Data;   
  • using System.Configuration;   
  • using System.Collections;   
  • using System.Web;   
  • using System.Web.Security;   
  • using System.Web.UI;   
  • using System.Web.UI.WebControls;   
  • using System.Web.UI.WebControls.WebParts;   
  • using System.Web.UI.HtmlControls;   
  •   
  • namespace AJAXEnabledWebApplication2   
  • {   
  •     public partial class _Default : System.Web.UI.Page   
  •     {   
  •         protected void Page_Load(object sender, EventArgs e)   
  •         {   
  •   
  •         }   
  •         [System.Web.Services.WebMethod]   
  •         public static string Message()   
  •         {   
  •             return “Hello from the server-side World!”;   
  •         }   
  •     }   
  • }  
  • August 29, 2009 Posted by | asp.net, Developement | , , , , , | 2 Comments

    GridView vs DataList vs Repeater vs Formview vs DetailsView – which one to choose

    Feature                                      Repeater DataList GridView

    Table layout                                  No            No            Yes

    Flow layout                                  Yes          Yes           No

    Column layout                           No           Yes           No

    Style properties                       No        Yes         Yes

    Templates                                  Yes     Yes           Columns/optional

    Select/ Edit/Delete                 No       Yes             Yes

    Sort                                               No        No               Yes

    Paging                                         No           No                   Yes

    August 7, 2009 Posted by | asp.net | , , , | Leave a comment