Search This Blog

Friday, December 28, 2012

Key events not fired Windows Forms

C# > Form > KeyPreview 

KeyPreview gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.






Example

Key events not fired Windows Forms

Solution:

Set KeyPreview property to True


Thursday, December 27, 2012

double (C#)

C# > Types > Double






Double type stores 64-bit floating-point values.

range: ±5.0 × 10−324 to ±1.7 × 10308
precision: 15-16 digits

By default, a real numeric literal on the right side of the assignment operator is treated as double, but if you want an integer number to be treated as double, use the suffix d or D.

double x = 10D;


Integral types and floating-point types can be mixed in an expression:

  • If one type is double the expression evaluates to double
  • If no double type in the expression it evaluates to float
Example: the sum is double type


int x = 1;
float y = 2.5f;
double w = 1.2E+1;
MessageBox.Show ("The sum is: " + (x + y +  w).ToString());
 


 
 


Common Language Specification (CLS)

Common Language Specification is a set of base rules to which any language targeting the CLI should conform in order to interoperate with other CLS-compliant languages.

Common Language Specification (CLS) is a set of basic language features needed by many applications.

To fully interact with other objects regardless of the language they were implemented in, objects must expose to callers only those features that are common to all the languages they must interoperate with.

UInt32 Structure

UInt32 Structure represents a 32-bit unsigned integer.

The UInt32 type is not CLS-compliant.
The CLS-compliant alternative type is Int64.

HttpContext.Session ASP.NET

ASP.NET > HttpContext > Session

Gets the HttpSessionState object for the current HTTP request.

ASP.NET pages contain a default reference to the System.Web namespace you can reference the members of HttpContext on an .aspx page without the fully qualified class reference to HttpContext. For example, you can use just Session("USER").

Note: If you want to use the members of HttpResponse from an ASP.NET code-behind module, you must include a reference to the System.Web and also fully qualify the reference.

For example, in a code-behind page you must specify the full name:
 
HttpContext.Current.Session("USER").







Friday, December 21, 2012

Class with events VB NET

VB.NET > Class > WithEvents

WithEvents specifies that one or more declared member variables refer to an instance of a class that can raise events.

Example: class with events

 Public Class Export
        Public Event TimesUp()
        Public Sub New()
            Dim worker As New BackgroundWorker()
            AddHandler worker.DoWork, AddressOf DoWork
            AddHandler worker.RunWorkerCompleted, AddressOf bg_RunWorkerCompleted
            worker.RunWorkerAsync()
        End Sub
        Private Sub DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
            ' export stuff
            Thread.Sleep(5000)
        End Sub
        Private Sub bg_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
            MsgBox("Background worker completed", vbInformation, "Background worker")
            RaiseEvent TimesUp() 'Triggers an event declared at module level within a class, form, or document.
        End Sub
    End Class

    Dim WithEvents _Export As New Export
    Private Sub handleTimesUp() Handles _Export.TimesUp
        MsgBox("TimesUp Event Raised and Handled")
    End Sub

 





BackgroundWorker VB.NET

VB.NET > BackgroundWorker

Executes an operation on a separate thread.

DoWork event occurs when RunWorkerAsync is called.
RunWorkerCompleted event occurs when the background operation has completed, has been canceled, or has raised an exception.

Example:

Imports System.ComponentModel
Imports System.Threading
Module Module1

  Public Sub backWork()
    Dim worker As New BackgroundWorker()
    AddHandler worker.DoWork, AddressOf DoWork
    AddHandler worker.RunWorkerCompleted, AddressOf bg_RunWorkerCompleted
    worker.RunWorkerAsync()
  End Sub

  Private Sub DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
    ' some work
    Thread.Sleep(5000)
  End Sub

  Private Sub bg_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
    MsgBox("Background worker completed", vbInformation, "Background worker")
  End Sub

End Module





Thursday, December 20, 2012

ArrayList Class C#

C# > Collections > ArrayList

Implements the IList interface using an array whose size is dynamically increased as required.

Example

using System;
using System.Collections;
public class SampleArrayList  {

public static void Main()
{
   ArrayList m_l = new ArrayList();
   m_l.Add("a");
   m_l.Add("b");
   m_l.Add("c");
   m_l.Add(1);
   Console.WriteLine(" Count: {0}", m_l.Count);
   Console.WriteLine(" Capacity: {0}", m_l.Capacity);
   Console.Write( " Elements:" );
   PrintElements(m_l);
  }
  public static void PrintElements(IEnumerable m_l)
 {
    System.Collections.IEnumerator _enum = m_l.GetEnumerator();
    while (_enum.MoveNext())
           Console.Write("\t {0}", _enum.Current);
    Console.ReadLine ();
 }
}






Array C#

C# > Types > Array

An array is a data structure that contains a number of variables called the elements of the array.
C# arrays are zero indexed.
All of the array elements must be of the same type.
Array elements can be of any type, including an array type.

Single-Dimensional Arrays

int[] m_i = new int[3];
string[] m_s = new string[5];
int[] m_i = new int[] { 1, 2, 3 }; // Array Initialization

Multidimensional Arrays

int[,] m_i = new int[3,2]; // two-dimensional array of 3 rows and two columns:
int[,,] m_i_1 = new int [5,1,2]; //  array of three dimensions, 5, 1, 2
int[,] myArray = new  int[,] {{1,2}, {3,4}, {5,6} }; // Array Initialization

Jagged Arrays

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes.

int[][] m_j = new int[2][];

m_j[0] = new int[2];
m_j[1] = new int[3];


Loop all rows DataTable C#

C# > Data > DataTable > Loop all rows

foreach (DataRow row in DataTable1.Rows)
{
     m_v = row["ColName"].ToString();
}




HTTP (Hypertext Transfer Protocol)

HTTP (Hypertext Transfer Protocol) is the set of rules for transferring files (text, graphic images, sound, video, and other multimedia files) on the World Wide Web.
When a user opens their Web browser, the user is indirectly making use of HTTP.
HTTP is an application protocol that runs on top of the TCP/IP protocols.






Tuesday, December 18, 2012

Find locked tables SQL Server

SQL Server > Dynamic Management Views and Functions > sys.dm_tran_locks

Returns information about currently active lock manager resources in SQL Server. Each row represents a currently active request to the lock manager for a lock that has been granted or is waiting to be granted.

Example:

Find locked tables SQL Server

select
   object_name(P.object_id) as TableName,
   resource_type,
   resource_description
from
   sys.dm_tran_locks L
   join sys.partitions P on L.resource_associated_entity_id = p.hobt_id





Static Constructors C#

C# > Class > static constructor

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

  • A static constructor cannot be called directly.

  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
     public class Log
    {
         // Static constructor:
         static Log()
        {
            System.Console.WriteLine("The static constructor invoked.");
         }
         public static void Write(string text)
        {
           System.Console.WriteLine("The Write method invoked.");
        }
   }
   class Program
   {
       static void Main(string[] args)
      {
          Log.Write("text"); // constructor invoked
          Log.Write("text"); // constructor not invoked.
      }
  }
}





Friday, December 14, 2012

protected C#

C# > Access Modifiers > Protected

The protected access modifier is between the private and public and is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.

Example:

namespace WFA
{
   public  class A
    {
        protected int x = 1;
        private int y;
    }
    public class B : A
    {
        B()
        {
            x = 2; // can access x, but cannot access y
            A a = new A();
            a.x = 1; // Error: Cannot access protected member 'WFA.A.x' via a qualifier of type 'WFA.A'; the qualifier must be of type 'WFA.B' (or derived from it)
        }
    }



Partial Class c#

C# > Class > Partial

Partial split the definition of a class over  more source files.
Each source file contains a section of the class definition, and all parts are combined when the application is compiled.

Use partial class when:
  • working on large projects allows multiple programmers to work on it simultaneously.
  • working with automatically generated source, code can be added to the class without having to recreate the source file.
Example

public partial class Car
{
      public int Year()
     {
      }
}

public partial class Car
{
      public void Go()
     {
      }
}






Application Request Routing IIS

IIS Application Request Routing (ARR) 2.5 enables Web server administrators, hosting providers, and Content Delivery Networks (CDNs) to increase Web application scalability and reliability through rule-based routing, client and host name affinity, load balancing of HTTP server requests, and distributed disk caching. With ARR, administrators can optimize resource utilization for application servers to reduce management costs for Web server farms and shared hosting environments.

Microsoft Application Request Routing (ARR) for IIS 7 and above is a proxy-based routing module that forwards HTTP requests to content servers based on HTTP headers, server variables, and load balance algorithms. ARR can be used to:
  • Increase application availability and scalability.
  • Better utilize content server resources.
  • Facilitate application deployment including pilot management and A/B testing.
  • Lower management costs and create opportunities for shared hosters.
Install Application Request Routing

The Application Request Routing installer package contains the following components:
  • Microsoft URL Rewrite Module for IIS.
  • Microsoft Web Farm Management Version 1 for IIS.
  • Microsoft Application Request Routing Version 1 for IIS.
  • Microsoft External Cache Version 1 for IIS.
Download:

Microsoft Application Request Routing Version 2.5 for IIS 7 (x64)

Microsoft Application Request Routing Version 2.5 for IIS 7 (x86)





kill SQL Server

SQL Server > Transact-SQL > Kill

Terminates a user process that is based on the session ID.  

  • if the specified session has a lot of work to undo, the KILL statement may take some time to complete
  • KILL can be used to terminate a normal connection, which internally terminates the transactions that are associated with the specified session ID. 
  • can also be used to terminate orphaned and in-doubt distributed transactions when Microsoft Distributed Transaction Coordinator (MS DTC) is in use.


Example

exec sp_who

Results:
spid ecid status         loginame hostname    blk dbname                    cmd request_id
53   0       suspended sa            pc01            0    db                             DELETE 0

kill 53

Results:
Command(s) completed successfully.




sp_who SQL Server

SQL Server > System Stored Procedures > sp_who

Returns information about current users, sessions, and processes.
 Syntax: sp_who [ loginame | sessionID | 'ACTIVE' ]  

Example
Find the spid and kill user process.

exec sp_who

Results:
spid ecid status         loginame hostname    blk dbname                    cmd request_id
53   0       suspended sa            pc01            0    db                             DELETE 0

kill 53


sp_who2 is undocumented and unsupported. sp_who2 adds some extra columns which sp_who does not include.

EXEC sp_who2




Thursday, December 13, 2012

If function Excel

Excel > Functions > IF

The IF function returns one value if a condition you specify evaluates to TRUE, and another value if that condition evaluates to FALSE.
       IF(logical_test, [value_if_true], [value_if_false])
 
Example:







Response.IsClientConnected asp.net

ASP.NET > Web > HttpResponse > IsClientConnected

The IsClientConnected property is a read-only property that indicates if the client has reset the connection to the server.

This property enables you greater control over circumstances where the client may have reset the connection to the server. For example, if a long period of time has elapsed between when a client request was made and when the server responded, it may be beneficial to make sure the client is still connected before continuing with something.

Example

If Not Response.IsClientConnected Then 
  Response.Redirect("login.aspx")
End if

Response.Redirect asp.net

Redirects a client to a new URL. Specifies the new URL and whether execution of the current page should terminate.

Parameters

url
The target location.
endResponse
Indicates whether execution of the current page should terminate.

bool continue;

// some code

if (continue)
{
    Response.Redirect("page.aspx", false);
}
else
{
    Response.End();
}

HttpCookie asp.net

ASP.NET > HttpCookie 

The HttpCookie class gets and sets properties of individual cookies.

HttpCookie loginCookie = Request.Cookies.Get("loginCookie");
if (loginCookie == null)
{
     loginCookie = new HttpCookie("loginCookie");
     loginCookie.Value = txtUsr.Text;
     loginCookie.Expires = DateTime.Now.AddDays(15);
     Response.Cookies.Add(loginCookie);
}





Sunday, December 9, 2012

OBJECT_ID SQL Server

SQL Server > Built-in FunctionsOBJECT_ID

OBJECT_ID returns the database object identification number of a schema-scoped object.

Example:

IF OBJECT_ID (N'dbo.tbl1', N'U') IS NOT NULL
  DROP TABLE dbo.tbl;
GO




SET XACT_ABORT SQL Server

SQL > Set Statements > XACT_ABORT

Specifies whether SQL Server automatically rolls back the current transaction when a Transact-SQL statement raises a run-time error.






Syntax:
SET XACT_ABORT { ON | OFF }

Example

IF OBJECT_ID(N'tbl1', N'U') IS NOT NULL
DROP TABLE tbl1;
GO
IF OBJECT_ID(N'tbl2', N'U') IS NOT NULL
DROP TABLE tbl2;
GO

CREATE TABLE tbl1
(fld1 INT NOT NULL PRIMARY KEY);
CREATE TABLE tbl2
(fld2 INT NOT NULL REFERENCES tbl1(fld1));
GO
INSERT INTO tbl1 VALUES (1);
INSERT INTO tbl1 VALUES (2);
INSERT INTO tbl1 VALUES (3);
INSERT INTO tbl1 VALUES (4);
GO
SET XACT_ABORT OFF;
GO
BEGIN TRANSACTION;
INSERT INTO tbl2 VALUES (1);
INSERT INTO tbl2 VALUES (2);
INSERT INTO tbl2 VALUES (5); -- Foreign key error. SELECT shows only values 1 and 2 inserted. -- Values 5 insert failed and was rolled back, but
-- XACT_ABORT was OFF and rest of transaction
-- succeeded.

COMMIT TRANSACTION;
GO
SET XACT_ABORT ON;
GO
BEGIN TRANSACTION;
INSERT INTO tbl2 VALUES (3);
INSERT INTO tbl2 VALUES (5); -- Foreign key error.
-- Values 5 insert error with XACT_ABORT ON caused
-- all of the second transaction to roll back.
INSERT INTO tbl2 VALUES (4);
COMMIT TRANSACTION;
GO

SELECT * FROM tbl2;
GO






Saturday, December 1, 2012

date datatype SQL Server

SQL Server > Data Types > Date

Default format: YYYY-MM-DD
Range: 0001-01-01 through 9999-12-31

Example

DECLARE @date1 date
CREATE TABLE Table1 ( datefield date )

-- difference between date and datetime

DECLARE @date date= '12-10-21';
DECLARE @datetime datetime= @date;

SELECT @date AS 'date', @datetime AS 'datetime';

--Result
--date              datetime
------------       -----------------------
--2021-12-10  2021-12-10 00:00:00.000

Other Examples