Monday, January 24, 2011

Kill process id in windows - force windows service to stop from stopping status


Kill process id in windows - force windows service to stop from stopping status

You can retrieve the PID for the process of the service through the command

sc queryex <servicename>

it returns some information like this

NOME_SERVIZIO: <servicename>
TIPO : 10 WIN32_OWN_PROCESS
STATO : 3 STOP_PENDING
(STOPPABLE, NOT_PAUSABLE, ACCEPTS_SHUTDOWN)
CODICE_USCITA_WIN32 : 0 (0x0)
CODICE_USCITA_SERVIZIO : 0 (0x0)
PUNTO_ARRESTO : 0x0
INDICAZIONE_ATTESA : 0x0
PID : 1824
FLAG :

Then you can stop the service by the command

taskkill /F /PID 1824 (the specific PID)


Monday, December 27, 2010

How to create a mounted drive

How to create a mounted drive

To mount a volume:

  1. Click Start, click Run, and then type compmgmt.msc in the Open box.
  2. In the left pane, click Disk Management.
  3. Right-click the partition or volume that you want to mount, and then click Change Drive Letter and Paths.
  4. Click Add.
  5. Click Mount in the following empty NTFS folder (if it is not already selected), and then use one of the following steps:
    • Type the path to an empty folder on an NTFS volume, and then click OK.
    • Click Browse, locate the empty NTFS folder, click OK, and then click OK.
    • If you have not yet created an empty folder, click Browse, click New Folder to create an empty folder on an NTFS volume, type a name for the new folder, click OK, and then click OK.
  6. Quit the Disk Management snap-in.

How to remove a mounted drive

To remove a mounted volume:

  1. Click Start, click Run, and then type compmgmt.msc in the Open box.
  2. In the left pane, click Disk Management.
  3. Right-click the partition or volume that you want to unmount, and then click Change Drive Letter and Paths.
  4. Click the mounted drive path that you want to remove, and then click Remove.
  5. Click Yes when you are prompted to remove the drive path.
  6. Quit the Disk Management snap-in.

 

Monday, October 25, 2010

Sorting and Searching Using C# Lists

It is a fairly common programming scenario to find ourselves with a list of identical objects. In the past, without adequate support from programming languages, we found ourselves writing a lot of searching and sorting code, and that may have put you off using lists in favour of arrays. All that has changed with C# 2.0 - its implementation of a list makes handling such lists remarkably easy. For example, given the following class Person:

   public class Person
        {
            public int age;
            public string name;
 
            public Person(int age, string name)
            {
                this.age = age;
                this.name = name;
            }
        }

We can create a list of Person objects and add six people like so:

List<Person> people = new List<Person>();
 
people.Add(new Person(50, "Fred"));
people.Add(new Person(30, "John"));
people.Add(new Person(26, "Andrew"));
people.Add(new Person(24, "Xavier"));
people.Add(new Person(5, "Mark"));
people.Add(new Person(6, "Cameron"));
 

C# 2.0's list mechanism provides us with a number of useful methods. Personally, I find ForEach, FindAll and Sort to be very useful. ForEach allows us access to each item in the list. FindAll allows us to search for objects in the list that match a specific condition. Sort allows us to sort the objects in the list. The following code demonstrates how we might use each of these methods:

Console.WriteLine("Unsorted list");
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });
 
List<Person> young = people.FindAll(delegate(Person p) { return p.age < 25; });
Console.WriteLine("Age is less than 25");
young.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });
 
Console.WriteLine("Sorted list, by name");
people.Sort(delegate(Person p1, Person  p2) { return p1.name.CompareTo(p2.name); });
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });
            
people.Sort(delegate(Person p1, Person  p2) { return p1.age.CompareTo(p2.age); });
Console.WriteLine("Sorted list, by age");
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

And here is the output that we should expect:

Unsorted list
50 Fred
30 John
26 Andrew
24 Xavier
5 Mark
6 Cameron
 
Age is less than 25
24 Xavier
5 Mark
6 Cameron
 
Sorted list, by name
26 Andrew
6 Cameron
50 Fred
30 John
5 Mark
24 Xavier
 
Sorted list, by age
5 Mark
6 Cameron
24 Xavier
26 Andrew
30 John
50 Fred

Lists are powerful and result in fewer, and more elegant, lines of code. Hopefully this short example has demonstrated their ease and you will find yourself using them in your day-to-day development activities.

 

Wednesday, October 20, 2010

View all constraint of table in SQL Server.

Query is to view all constraints of the table in SQL Server.

 

 

SELECT * FROM (

Select SysObjects.[Name] As [Contraint Name] ,Tab.[Name] as [Table Name],Col.[Name] As [Column Name]

 From SysObjects Inner Join (Select [Name],[ID] From SysObjects Where XType = 'U') As Tab

On Tab.[ID] = Sysobjects.[Parent_Obj]

Inner Join sysconstraints On sysconstraints.Constid = Sysobjects.[ID]

Inner Join SysColumns Col On Col.[ColID] = sysconstraints.[ColID] And Col.[ID] = Tab.[ID]

 ) A WHERE A.[TABLE NAME]='TABLENAME'

 

 

 

Thanks,

Siddu

 

P Please consider the environment before printing this e-mail

 

 

Defining SQL Server constraints with TSQL

 

Types of constraints

I focus on four types of constraints: primary key, foreign key, unique, and check. Here's a brief overview of each.

Primary key
This constraint is used to guarantee that a column or set of columns on a table contain unique values for every record in the given table. This lets you ensure data integrity by always being able to uniquely identify the record in the table.

Get SQL tips in your inbox

TechRepublic's SQL Server newsletter, delivered each Tuesday, contains hands-on tips that will help you become more adept with this powerful relational database management system.

Automatically sign up today!

A table can have only one primary key constraint defined on it, and the rows in the primary key columns cannot contain null values. A primary key constraint can be defined when a table is created, or it can be added later.

This script creates a primary key constraint on a single field when the table is created:

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;

GO

CREATE TABLE [dbo].[SalesHistory](
      [SaleID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
      [Product] [char](150) NULL,
      [SaleDate] [datetime] NULL,
      [SalePrice] [money] NULL
)

GO

The followings script creates the primary key constraint when the table is created. This method allows you to define a name for the constraint and to create the constraint on multiple columns if necessary.

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;

GO
CREATE TABLE [dbo].[SalesHistory](
      [SaleID] [int] IDENTITY(1,1) NOT NULL,
      [Product] [char](150) NULL,
      [SaleDate] [datetime] NULL,
      [SalePrice] [money] NULL,
      CONSTRAINT pk_SaleID PRIMARY KEY (SaleID)

)

GO

This script creates the primary key constraint on the table after it is created:

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;

GO



CREATE TABLE [dbo].[SalesHistory](
      [SaleID] [int] IDENTITY(1,1) NOT NULL,
      [Product] [char](150) NULL,
      [SaleDate] [datetime] NULL,
      [SalePrice] [money] NULL

)

GO

ALTER TABLE SalesHistory

ADD CONSTRAINT  pk_SaleID PRIMARY KEY (SaleID)

GO

Foreign key
This constraint limits the values of columns in one table based upon the values of columns in another table. This link between the two tables requires the use of a "lookup table," which contains the accepted list of values; this list must contain a unique or primary key constraint. After the constraint is established between the two tables, any data modifications to the fields defined in the constraint on the foreign key table will cause a validation to ensure that the data being updated or inserted is contained in the lookup table.

The script in Listing A creates a ProductTypes table, which will serve as the lookup table and the SalesHistory table, which will reference the ProductID in the ProductTypes table. If I had excluded the constraint definition in the table declaration, I could go back later and add it. You can do this with the script in Listing B.

The previous script contains the WITH NOCHECK clause. I use it so that any existing values in the table are not considered when the constraint is added. Any records in the table that violate the newly added constraint will be ignored so that the constraint is created. The constraint will only be applicable to new records entered into the SalesHistory table.

Unique
This constraint guarantees that the values in a column or set of columns are unique. Unique and primary key constraints are somewhat similar because each provide a guarantee for uniqueness for a column or set of columns. A primary key constraint automatically has a unique constraint defined on it.

There are two differences between the constraints: (1) You may have only one primary key constraint per table, yet you may have many unique constraints per table; (2) A primary key constraint will not allow null values but a unique constraint will (although it will only allow one null value per field).

This script creates a unique constraint on the SaleID column when the table is created:

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;

GO
CREATE TABLE [dbo].[SalesHistory](
      [SaleID] [int] NOT NULL UNIQUE,
      [Product] [char](150) NULL,
      [SaleDate] [datetime] NULL,
      [SalePrice] [money] NULL

)

GO

The following script creates a unique constraint on the table at creation, and it allows for constraint naming and for defining the unique constraint on multiple columns if necessary.

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;

GO

CREATE TABLE [dbo].[SalesHistory](
      [SaleID] [int]  NOT NULL,
      [Product] [char](150) NULL,
      [SaleDate] [datetime] NULL,
      [SalePrice] [money] NULL,
      CONSTRAINT uc_SaleID UNIQUE (SaleID)

)

GO

This script creates the unique constraint on the SalesHistory table by altering the table after it has been created:

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;

GO

CREATE TABLE [dbo].[SalesHistory](
      [SaleID] [int] NOT NULL,
      [Product] [char](150) NULL,
      [SaleDate] [datetime] NULL,
      [SalePrice] [money] NULL

)

GO

ALTER TABLE SalesHistory

ADD CONSTRAINT  uc_SaleID UNIQUE(SaleID)

GO

Check
This constraint limits the value range, or domain, in a column. Check constraints check the acceptable values against a logical expression defined in the constraint. These constraints are similar to foreign key constraints in that they both govern the acceptable values for a column or set of columns in a given row in a table. You can create a check constraint at the column or table level. A check constraint on a single column allows only certain values for those columns, while a table check constraint can limit values in certain columns based on values in other fields in the row.

The following script creates a check constraint on the SalePrice column in the SalesHistory table, limiting entries where the SalePrice must be greater than 4. Any attempt to enter a record with the SalePrice present and less than 4 will result in an error.

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;

GO

CREATE TABLE [dbo].[SalesHistory](
      [SaleID] [int]  NOT NULL,
      [Product] [char](150) NULL,
      [SaleDate] [datetime] NULL,
      [SalePrice] [money] NULL CHECK (SalePrice > 4)

)

GO

The script in Listing C creates a check constraint on the SalesHistory table, limiting the SalePrice to be greater than 10 and the Product field to have the value Computer. This isn't a very practical constraint, but it does illustrate how you can set constraints on multiple columns for a table. Listing D is effectively the same as the script in Listing C, but it defines the constraint after the table is created.

 

Tuesday, September 28, 2010

How to import Excel XML spreadsheets without interop

How to import Excel XML spreadsheets without interop
Simple way how to import XML Excel spreadsheets into DataTable

Did you need to import Excel spreadsheet ever? If you did you know there're sometimes problems with interop assemblies deploying to desktops and so. Office 2003 offers to store spreadsheets in XML. So store your spreadsheet as XML and try to import. Just include ExcelReader.cs in your project and use SPOTX namespace. Then you'll be able to add imported DataTable as datasource to your grid like in included exampe.




using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Data;

namespace SPOTX
{

    /// <summary>
    /// Static methods for reading XML schema
    /// </summary>
    class ExcelReader
    {

        /// <summary>
        /// Main static method which imports XML spreadsheet into DataTable
        /// </summary>
        /// <param name="ExcelXmlFile">Imported file</param>
        /// <returns>dataTable result</returns>
        public static DataTable ReadExcelXML(string ExcelXmlFile)
        {
            DataTable dt = new DataTable();
            XmlDocument xc = new XmlDocument();
            xc.Load(ExcelXmlFile);
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xc.NameTable);
            nsmgr.AddNamespace("o", "urn:schemas-microsoft-com:office:office");
            nsmgr.AddNamespace("x", "urn:schemas-microsoft-com:office:excel");
            nsmgr.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");

            XmlElement xe = (XmlElement)xc.DocumentElement.SelectSingleNode("//ss:Worksheet/ss:Table", nsmgr);
            if (xe == null)
                return null;
            XmlNodeList xl = xe.SelectNodes("ss:Row", nsmgr);
            int Row = -1, Col = 0;
            Dictionary<int, string> cols = new Dictionary<int, string>();
            foreach (XmlElement xi in xl)
            {
                XmlNodeList xcells = xi.SelectNodes("ss:Cell", nsmgr);
                Col = 0;
                foreach (XmlElement xcell in xcells)
                {
                    if (Row == -1)
                    {
                        dt.Columns.Add(xcell.InnerText);
                        cols[Col++] = xcell.InnerText;
                    }
                    else
                    {
                        if (xcell.Attributes["ss:Index"] != null)
                        {
                            int idx = int.Parse(xcell.Attributes["ss:Index"].InnerText);
                            Col = idx - 1;
                        }

                        SetCol(dt, Row, (string)cols[Col++], xcell.InnerText, typeof(string));
                    }
                }
                Row++;
            }
            return dt;
        }

        /// <summary>
        /// Adds row to datatable, manages System.DBNull and so
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="AcceptChanges"></param>
        /// <returns></returns>
        public static int AddRow(DataTable dt, bool AcceptChanges)
        {
            object[] Values = new object[dt.Columns.Count];
            for (int Column = 0; Column < dt.Columns.Count; Column++)
            {
                if (!dt.Columns[Column].AllowDBNull)
                {
                    if (dt.Columns[Column].DefaultValue != null &&
                        dt.Columns[Column].DefaultValue != System.DBNull.Value)
                    {
                        Values[Column] = dt.Columns[Column].DefaultValue;
                    }
                }
            }
            dt.Rows.Add(Values);
            if (AcceptChanges)
            {
                dt.AcceptChanges();
            }
            return dt.Rows.Count - 1;
        }

        /// <summary>
        /// Sets data into datatable in safe manner of row index
        /// </summary>
        /// <param name="dt">DataTable to set</param>
        /// <param name="Row">Ordinal row index</param>
        /// <param name="ColumnName">name of column to set</param>
        /// <param name="Value">non/typed value to set</param>
        /// <param name="TypeOfValue">Becase Value can be null we must know datatype to manage default values</param>
        /// <returns></returns>
        public static DataColumn SetCol(DataTable dt, int Row, string ColumnName,
                                        object Value, System.Type TypeOfValue)
        {
            if (dt == null || ColumnName == null || ColumnName == "")
                return null;

            if (Value == null)
                Value = System.DBNull.Value;

            int nIndex = -1;
            DataColumn dcol = null;
            bool Added = false;
            if (dt.Columns.Contains(ColumnName))
            {
                dcol = dt.Columns[ColumnName];
            }
            else
            {
                dcol = dt.Columns.Add(ColumnName, TypeOfValue);

            }
            if (dcol.ReadOnly)
                dcol.ReadOnly = false;

            nIndex = dcol.Ordinal;
            //new empty row appended
            if (dt.Rows.Count == Row && Row >= 0)
            {
                AddRow(dt, false);
                Added = true;
            }
            //one row
            if (Row >= 0)
            {
                dt.Rows[Row][nIndex] = Value;
            }
            else if (Row == -1)
            { //all rows
                try
                {
                    for (Row = 0; Row < dt.Rows.Count; Row++)
                    {
                        if (dt.Rows[Row].RowState == DataRowState.Deleted)
                        {
                            continue;
                        }
                        dt.Rows[Row][nIndex] = Value;
                    }
                }
                catch (Exception)
                {
                }
            }

            return dcol;
        }

    }
}



Ref link:



Friday, August 20, 2010

Error - Application popup: wzunzip.exe while using WinZip 14.5 command line in Window service.

Bug :Was not able extract any zip files( WinZip 14.5 ) through Window service application ( which was using WinZip 14.5  command line )

Description: An Information found in Event logger – System as
Application popup: wzunzip.exe - Application Error : The application failed to initialize properly (0xc0000142). Click on OK to terminate the application.

Resolved :
This can be resolved just setting up the property of your application window service as below .


By check – Allow service to interact with desktop , it is said to service allow popup windows but by default service will run in hidden / silent mode . So nothing to worry about the popup .

Using Winzip14.5 command line – wzunzip.exe
Code snippet, I used in my application testing .

 using System;  
 using System.Collections.Generic;  
 using System.Text;  
 using System.IO;  
 namespace UnZipTest  
 {  
   public class UnZip  
   {  
     public void Run (string path,string extractPath){  
       DirectoryInfo dirInfo = new DirectoryInfo(path);  
       System.Diagnostics.Process P = new System.Diagnostics.Process();  
       if(Directory.Exists(extractPath)==false){  
         Directory.CreateDirectory(extractPath);  
       }  
       string UnZipCmd = null;  
       foreach(FileInfo fl in dirInfo.GetFiles("*.zip")){  
         try  
         {  
           string password = "123";  
           string zipExtract = extractPath + "\\" + fl.Name + "_" + Guid.NewGuid().ToString().Substring(0, 4);  
           if (password.Trim().Length == 0)  
           {  
             UnZipCmd = string.Format("-o \"{0}\" \"{1}\"", fl.FullName, zipExtract);  
             P = System.Diagnostics.Process.Start(@"C:\Program Files\WinZip\wzunzip", UnZipCmd);  
           }  
           else{  
             UnZipCmd = string.Format("-s\"{0}\" -o \"{1}\" \"{2}\"",password, fl.FullName, zipExtract);  
             P = System.Diagnostics.Process.Start(@"C:\Program Files\WinZip\wzunzip", UnZipCmd);  
           }  
           P.WaitForExit();  
         }  
         catch (Exception ex){  
           throw ex;  
         }  
       }  
     }  
   }  
 }  

Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code