Learn Ethical Hacking, SQL Injection and XSS Script.

Protect your website from SQL Injection, XSS Script and avoid vulnerability.

Learn SharePoint 2010,MOSS and Convert ASP.Net application to SharePoint

Learn Dotnet,SQL,NO-SQL ,C#,VB.NET,Java Script,Dotnet Open source project.

Check the free hosting in LINUX and Windows Server

Showing posts with label sql. Show all posts
Showing posts with label sql. Show all posts

SQL Server 2008 R2: Connect to Different Domain and Server Name



Right Click on Windows Firewall with Advance Security and point to Properties > Domain Tab > and Allow inBound connection.


3rd step---
Run Command Prompt:
cd\ <enter>
runas /user:DOMAIN1\admin /netonly "C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe" <enter>
Enter the password for DOMAIN1\admin then <enter>


wait until SQL Management Studio 2008 R2 open by itself.

4th step---
Once you get the Connect to Server Window. Fill in the Server Name as shown below:
Server type: Database Engine
Server name: 192.168.0.11\InstanceName
Authentication: Windows Authentication
Then click connect button.



Hope it works. Mine is working very well, now i can connect to my Hyper-V SQL Server. :) Good luck!

Using SMO to drop a SQL Database


SQL Server Management Objects(SMO) is the API you can use to manipulate the sql server,like create databse and delete database.
To get more details you can check the msdn documentation.
There are 2 ways you can drop a database
1. You could create a Database object and call Drop method:

Dim database As Database = New Database(Your database name)
 database.Drop()

2.However if you have existing connections to the database ,attempting to drop it using the above method will fail.Recall that when you try to drop the database from management studio ,you can tick the check box to close all the connections before drop the database.It is not so obvious , but you can do the exact same thing using SMO:

Dim server As Server= New Server(ServerConn)
                server.KillAllProcesses(Your database name)
                server.KillDatabase(Your database name)


Script Generator - Allows you to create classes for all your sql tables.


Introduction
Ever had to do a project, and had to create and recreate your classes for your database tables?  Well I have been there.  As frustrating as it is, I decided to create my own web based tool which will generate the c# classes.  I could either type the table name, select it from a drop down list, or generate for all tables of a database.  Since the connection string is in the web config file, I can easily change it to point to which ever project I am working on.

System Minimum Requirements
Visual Studio 2003
Framework 1.1
SQL/ORACLE/DB Connection String (Insert into Web Config)

Why Should I Use This?
The real reason why I have even releases this is because it can save developers a lot time.  I know in the real world, the database structures that are made are never the final structures.  Lots of normalization occurs as well as adding or removing fields.  Sometimes the data types change.  I had a project were a date field had te become a nvarchar field to accomadate for multilanguage dates.  Any how, I hope it will be helpful to others.

Modifications I Hope To Make
I am going to create a method to handle the connections.  I personally don't like to use datareaders, but if you do, make sure you close your connections.  If I release some new versions I will definately update it here.

Screen Shots
1.  Default Page:
          Here you will see all your tables in the drop down list.  There are 3 tasks that can be perfomed here.
          A.  Type in the table/view name, to generate a class for it.
          B.  Select the table/view name, to generate a class for it.
          C.  Select the checkbox, to go generate all the classes for your database for all tables.



2.  Example of typing in the table name:
       Just type in the table name, and click [Generate].  Wallah!  Your class is instantly created.



3.  Example of selecting the checkbox to generate all tables.



4.  Result of clicking generate from clicking from drop down list, or checkbox.  (Note: Messages for be more if checkbox is selected based on number of tables)



5.  Where to see your new class:
       Make sure you refresh your project.  The default directory is within the project.



6.  Sample screenshot of class created.



Now to the good part...

THE CODE

protected void Button1_Click(object sender, EventArgs e)
{ 
        if (txtTableName.Text.Length > 0)
        {
            //Creates a file of type cs to generate a class with methods.
            string TableName = txtTableName.Text.Trim().Replace(" """);
            string TopBody = "using System; \nusing System.Data; \nusing System.Configuration; \nusing System.Web; \nusing System.Web.Security; \nusing System.Web.UI; \nusing System.Web.UI.WebControls;\nusing System.Web.UI.HtmlControls;\nusing ALLFunc;";
 
            string NameSpaceStart = "\nnamespace DB \n{";
            string MainClassStart = "\n\tpublic class " + TableName + "\n\t{ "; 
            string FunctionBODY = GenerateInsertStatements(TableName) + " \n\t\t\treturn \"\"; \n\t\t} ";
            FunctionBODY += GenerateStringInsertStatements(TableName) + " \n\t\t\treturn \"\"; \n\t\t} ";
            FunctionBODY += GenerateUpdateStatements(TableName) + " \n\t\t\treturn \"\"; \n\t\t} ";
            FunctionBODY += GenerateStringUpdateStatements(TableName) + " \n\t\t\treturn \"\"; \n\t\t} ";
            FunctionBODY += GenerateSelectStatementsSqlDataReader(TableName) + " \n\t\t}";
            FunctionBODY += GenerateSelectStatementsDataSet(TableName) + " \n\t\t}";
            FunctionBODY += GenerateDeleteStatements(TableName) + " \n\t\t}";
            FunctionBODY += GenerateUpdateStatementsWithParamatersOnly(TableName) + " \n\t\t}";
            string MainClassEnd = "\n\t}";
            string NameSpaceEnd = "\n}"; 
            string Path = Server.MapPath("..") + "\\Class\\ClassInfo\\" + TableName + ".cs";
            System.IO.StreamWriter SW;
            SW = System.IO.File.CreateText(Path);
            SW.WriteLine(TopBody + NameSpaceStart + MainClassStart + FunctionBODY + MainClassEnd + NameSpaceEnd);
            SW.Close(); 
            Msg.Text = "Class created for " + TableName + " at path: " + Path;
       }
}

This is not it though.  I have a bunch of other methods which you can see in the middle which creates the body of the *.cs files.  If you want it in visual basic (vb) make sure you change the extensions.  Here are a list of the other methods I call:

GenerateInsertStatements(TableName)
GenerateStringInsertStatements(TableName)
GenerateUpdateStatements(TableName)
GenerateStringUpdateStatements(TableName)
GenerateSelectStatementsSqlDataReader(TableName)
GenerateSelectStatementsDataSet(TableName)
GenerateDeleteStatements(TableName)
GenerateUpdateStatementsWithParamatersOnly(TableName)

They are pretty straight forward in the method name.  The method names identity the scripts it is going to generates.

Sql Script Generator in C#.-Insert

SQL Script Generator
Generator SQL Script Generator Generates the SQL Scripts to run on sql query analyzer these queries of only insert and update.

Background
Sql Script Generator in C# From SQL ,MS Access, FoxPro ,MySql etc Table Generator SQL Script Generator Generates the SQL Scripts to run on sql query analizere these queries of only insert and update this class still not contain Delete query but u can change according to ur requirement
this contain methods only for sql still not for others u can change it this also contain a method from which u can find ID or Primary Key Name of a table method name is GetprimaryKey(string tableName)
NOTE
"sp_pkeys" is sql server default store procedure u just pass it only table Name it will return primary key column
Using the code
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using System.Collections;
//using Microsoft.SqlServer.Management.Smo;
//using Microsoft.SqlServer.Management.Nmo;
//using Microsoft.SqlServer.Management.Smo.Agent;
namespace FoxPro_2_SQL_Synchroniser
{
class SQLScriptGenerater
{
//This class generates the SQL Scripts of of a table from SQL Table
// these are globle variable
//DesTableName this is destination table name for which script will be //generated like qry= insert into //DesTableName(id,name)value('1','idrees')
// I have destination table name as "Tableee"
//source table name is TableName name as " Tab "; this of sql //Table
string primaryKey, updateqry, Insertqry,DesTableName="Tableee", TableName = "Tab";
string updateAdd = "";
public SQLScriptGenerater()
{
}
public void Run(string cnString)
{
string values, IDValues = "", insqry, upqry ;
int i = 0;
SqlDataReader myReader;
SqlConnection mySqlConnection = new SqlConnection();
SqlConnection mSqlConnection = new SqlConnection();
SqlCommand mySqlCommand = new SqlCommand();
SqlCommand msqlCommand = new SqlCommand();
string cnnString = " cnnString ";
mSqlConnection = new SqlConnection(cnnString);
mySqlConnection = new SqlConnection(cnnString);
mySqlCommand = new SqlCommand("select * from Tab", mySqlConnection);
TableName = "Tab";
primaryKey = GetprimaryKey(TableName);
insqry = "";
mySqlConnection.Open();
myReader = mySqlCommand.ExecuteReader();
if (myReader != null)
{
while (myReader.Read())
{
// i this variable count the total number of record
i = i + 1;
// once a query is written at next it a vriable should be empty to build query again
updateAdd = "";
insqry = "";
string celldata = "", coulmenName = "";
for (int j = 0; j <> 0)
{
// this condition is used for "," in insert and update qyery
{
coulmenName += "," + myReader.GetName(j).ToString();
celldata += ",'" + myReader[j].ToString() + "'";
}
}
else
{
coulmenName += myReader.GetName(j).ToString();
celldata += "'" + myReader[j].ToString() + "'";
}
if (primaryKey == myReader.GetName(j).ToString())
{
IDValues = myReader[j].ToString();
}
if (IDValues != null)
{
//Generates the update Query
upqry = UpdateQuery(coulmenName, celldata, primaryKey, IDValues);
updateAdd += upqry;
//Generates the Insert Query
insqry = InsertQuery(coulmenName, celldata, DesTableName);
}
}
WriteScripts(DesTableName, insqry, updateAdd, IDValues, primaryKey, i);
}
MessageBox.Show("Total number of record in database are=" + i);
}
}
#region this Methods retun ID columan of table which table we pass to
public string GetprimaryKey(string tableName ,string cnnString)
{
string names, ID = "";
SqlDataReader mReader;
SqlConnection mSqlConnection = new SqlConnection();
SqlCommand mSqlCommand = new SqlCommand();
string cnString = cnString
mSqlConnection = new SqlConnection(cnString);
mSqlConnection.Open();
// sp_pkeys is sql server default store procedure u just pass it only table Name it will return //primary key column
mSqlCommand = new SqlCommand("sp_pkeys", mSqlConnection);
mSqlCommand.CommandType = CommandType.StoredProcedure;
mSqlCommand.Parameters.Add("@table_name", SqlDbType.NVarChar).Value = tableName;
mReader = mSqlCommand.ExecuteReader();
while (mReader.Read())
{
// the primary key column reside at 4 index
ID = mReader[3].ToString();
}
return ID;
}
#endregion
#region this methods retun ID values to compaire for insert or Update
public void WriteScripts(string tableName, string insertqry, string updateqry, string IDvalues, string PrimaryKey, int i)
{
string script = "";
updateqry = "update " + DesTableName + " set " + updateqry + " Where " + PrimaryKey + " = '" + IDvalues + "'";
int index = updateqry.LastIndexOf(",");
string updatqry = updateqry.Remove(index, 1);
if (i == 1)
{
//if will be first time executed and all required variable are declared and next all times else //condition will be executed
script += "DECLARE @updateCount INT;"+Environment.NewLine;
script += "DECLARE @insertCount INT;"+ Environment.NewLine;
script += "DECLARE @count INT;"+Environment.NewLine;
script += "SET @updateCount = 0;"+Environment.NewLine;
script += "SET @insertCount = 0;"+Environment.NewLine;
script += "SELECT @count = COUNT(*) FROM [" + tableName + "] WHERE [" + PrimaryKey + "] = '" + IDvalues + "'" + Environment.NewLine;
script += "IF @count = 0" + Environment.NewLine;
script += "BEGIN ";
script += insertqry + "" + Environment.NewLine;
script += "SET @insertCount = @insertCount + 1 " + Environment.NewLine;
script += "END" + Environment.NewLine;
script += "ELSE" + Environment.NewLine;
script += "BEGIN " + Environment.NewLine;
script += updatqry + "" + Environment.NewLine;
script += "SET @updateCount = @updateCount + 1 " + Environment.NewLine;
script += "END" + Environment.NewLine;
StreamWriter sw = new StreamWriter(@"d:\script1.txt", true,Encoding.UTF8);
sw.Write(script);
sw.Close();
}
else
{
script += "SELECT @count = COUNT(*) FROM [" + tableName + "] WHERE [" + PrimaryKey + "] = '" + IDvalues + "'" + Environment.NewLine;
script += "IF @count = 0" + Environment.NewLine;
script += "BEGIN " + Environment.NewLine;
script += insertqry + "" + Environment.NewLine;
script += "SET @insertCount = @insertCount + 1 " + Environment.NewLine;
script += "END" + Environment.NewLine;
script += "ELSE" + Environment.NewLine;
script += "BEGIN " + Environment.NewLine;
script += updatqry + "" + Environment.NewLine;
script += "SET @updateCount = @updateCount + 1 " + Environment.NewLine;
script += "END" + Environment.NewLine;
StreamWriter sw = new StreamWriter(@"d:\script1.txt", true, Encoding.UTF8);
sw.Write(script);
sw.Close();
}
}
#endregion
#region this methods retun insert query and update query
public string InsertQuery(string coulmenName, string celldata,string TableName)
{
return Insertqry = "insert into " + TableName + "(" + coulmenName + ")values(" + celldata + ")";
}
public string UpdateQuery(string coulmenName, string celldata, string Name, string Value)
{
string IDName, IDValue, Ud = "", name = "", values = "";
IDName = Name;
IDValue = Value;
if (IDName != null)
{
int indexcolumn = coulmenName.LastIndexOf(",");
int indexValues = celldata.LastIndexOf(",");
if (indexcolumn > 0 && indexValues > 0)
{
coulmenName = coulmenName.Substring(indexcolumn);
celldata = celldata.Substring(indexValues);
name = coulmenName.Replace(",", "");
values = celldata.Replace(",", "");
if (name != IDName && values != IDValue)
{
Ud = name + "=" + values + ",";
}
}
else
{
name = coulmenName;
values = celldata;
if (name != IDName && values != IDValue)
{
Ud = name + "=" + values + ",";
}
}
}
return Ud;
}
#endregion
}
}
this also contain a method from which u can find ID or Primary Key Name of a table
method name is GetprimaryKey(string tableName)

Generating SQL Backup Script for Tables & Data from any .NET Application using SMO


What is SMO?

SMO, SQL Server Management Object, is a collection of objects that includes all you need to manage SQL Server from .NET applications. With SMO you can manage pretty much everything – from databases, tables, stored procedures, jobs – you name it.
Actually, SMO is “.NET Version” of COM object known as SQL-DMO (SQL Distributed Management Objects).
SMO Assemblies (dll’s) can usually be found at: C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\ (for SQL Server 2008).

What We’re Going To Do?

In this post I’ll show an easy way to write a method that generates SQL File that include backup of both the schema and the data of specific tables (CREATE statements for each table and INSERT statements for all the data). Same as if you right-click on DB name at SQL Server Management Studio and choose “Generate Scripts”

The Method

First, we’ll have to add references to the following assemblies:
  1. Microsoft.SqlServer.ConnectionInfo
  2. Microsoft.SqlServer.Management.Sdk.Sfc
  3. Microsoft.SqlServer.Smo
[All of them can be found in the directory I mentioned before, with the same name as in the list just with “.dll” in the end]
In the following example, we want to backup specific tables (we know the tables names) that are in a specific DB. This is how our method will look:
   1: public static void Backup(string FileName, string[] Tables)
   2: {
   3:     StringBuilder sb = new StringBuilder();
   4:     Server srv = new Server(new Microsoft.SqlServer.Management.Common.ServerConnection("<db name>", "<user name>", "<password>"));
   5:     Database dbs = srv.Databases["<db name>"];
   6:     ScriptingOptions options = new ScriptingOptions();
   7:     options.ScriptData = true;
   8:     options.ScriptDrops = false;
   9:     options.FileName = FileName;
  10:     options.EnforceScriptingOptions = true;
  11:     options.ScriptSchema = true;
  12:     options.IncludeHeaders = true;
  13:     options.AppendToFile = true;
  14:     options.Indexes = true;
  15:     options.WithDependencies = true;
  16:     foreach (var tbl in Tables)
  17:     {
  18:         dbs.Tables[tbl].EnumScript(options);
  19:     }
  20: }
Our method get two parameters. The first one is the Full path to the file we want to export, and the second is an array with name of the tables we want to generate SQL backup script for.
In line 4 you can see that there is a new instance of “Server” object that represents the SQL Server itself.
In line 5 choose the DB that we want (Pay attention to add Exception handling if you going to use this code).
Then, from line 6 to 15 we set some properties in the ScriptingOptions object that includes our settings for the script generation. In this example, i backup both data and schema soScriptData and ScriptSchema are both true.

I also backup the Indexes. And, in this example, i set WithDependencies property as true which means that the generated script will include CREATE statements for tables that are somehow related to the tables we actually backup. For example, if table A has FK to table Band I’ll backup table A with this method, it’ll also generates the SQL Statements to backup table B.
You can find the full documentation of all the available settings here.
In lines 15-18 we iterate the array we get as a parameter to the method and for each table call Table.EnumScript method thet get ScriptiongOptions instance as parameter (which includes all the settings). This method also returns a collection of strings (IEnumerable<string>) that includes the generated SQL.

In this example i Ignore the returned value because i set the propertyScriptiongOptions.FileName to a path for a file where the SQL will be saved, so i don’t need the collection in the code (know that because i call EnumScript several times, for each table, it’s important to set ScriptingOptions.AppendToFile as true or we’ll override the file each time).

The Difference Between EnumScript and Script

If you’ll take a look in the documentation you’ll see that there is also method called Scriptthat we can use with Table object. So why don’t I use it?
The reason (which i couldn’t find in the official documentation) is that if we set in theScriptingOptions object we pass to the method ScriptiongOptions.ScriptData = true we must use EnumScript because Script will give us the following Exception:
“This method does not support scripting data”.

Summary

In order to work with SQL Server from .NET Applications we have SMO components.
We can generate SQL statements that can be used to backup table (create table and insert data) with Table.EnumScript method, and we can give the settings we want withScriptingOptions object.

Run a .sql script files in C#


If you have placed in situation to execute .sql script files from .NET code on SQL Server, you will see that SqlCommand class is not that useful. In other words, you can't execute batch commands that contains 'GO' (batch finalizer command). So you can think of several options, like split that script to several commands, and execute one by one. But you realize how complex is that task.
If you wanted to do that prior to SQL Server 2005, the only option is using osql utility. Since SQL Server 2005 there is another option which is much better and preferred. That option is using SMO library which comes with SQL Server and can be used for managing everything on SQL Server 2005. You can backup, restore databases, configure permissions, replication, etc.
I plan to post about how to backup and restore database using this SMO library in near future. Here will write only about how to read sql file and execute the content on SQL Server.
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string sqlConnectionString =
                "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
            FileInfo file = new FileInfo("C:\\myscript.sql");
            string script = file.OpenText().ReadToEnd();
            SqlConnection conn = new SqlConnection(sqlConnectionString);
            Server server = new Server(new ServerConnection(conn));
            server.ConnectionContext.ExecuteNonQuery(script);
        }
    }
}
This post is based from my answer on one MSDN forums' question located here.