Micro blog about Answer to the Ultimate Question of Life, the Universe, and Everything.
  • Home
    • List all categories
    • Sitemap
  • Downloads
    • WebSphere
    • Hitachi902
    • Hospital
    • Kryptonite
    • OCR
    • APK
  • About me
    • Gallery
      • Italy2022
      • Côte d'Azur 2024
    • Curriculum vitae
      • Resume
      • Lebenslauf
    • Social networks
      • Facebook
      • Twitter
      • LinkedIn
      • Xing
      • GitHub
      • Google Maps
      • Sports tracker
    • Adventures planning
  1. You are here:  
  2. Home
  3. C#

Execute sql scripts from console

Details
Written by: Stanko Milosev
Category: Code snippets
Published: 24 November 2012
Last Updated: 17 May 2016
Hits: 6065
using System;
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[] filePaths = Directory.GetFiles(@"c:\myListOfScripts\", "*.sql");
            Array.Sort(filePaths);

            string connectionString = "server=myServer\\myInstance;database=myDatabase;uid=sa;pwd=mySaPwd";

            SqlConnection cn = new SqlConnection(connectionString);

            Console.WriteLine("Last how many scripts you want to execute?");
            var lastNoScript = Convert.ToInt16(Console.ReadLine());

            FileStream ostrm;
            StreamWriter writer;
            TextWriter oldOut = Console.Out;
            try
            {
                ostrm = new FileStream("./log.txt", FileMode.OpenOrCreate, FileAccess.Write);
                writer = new StreamWriter(ostrm);
            }
            catch (Exception e)
            {
                Console.WriteLine("Cannot open log.txt for writing");
                Console.WriteLine(e.Message);
                return;
            }

            Console.SetOut(writer);
            cn.Open();
            for (int i = filePaths.Length - lastNoScript; i < filePaths.Length; i++)
            {
                Console.WriteLine("Executing script: ");
                Console.WriteLine(filePaths[i]);
                Console.WriteLine();

                FileInfo file = new FileInfo(@filePaths[i]);
                string script = file.OpenText().ReadToEnd();

                ServerConnection svrConnection = new ServerConnection(cn);
                Server server = new Server(svrConnection);
                try
                {
                    server.ConnectionContext.ExecuteNonQuery(script);
                }
                catch (Exception e)
                {
                    Console.WriteLine(script + " : Message: " + e.Message + " Inner exception: " + e.InnerException.Message);
                }
            }
            Console.SetOut(oldOut);
            writer.Close();
            ostrm.Close();
            Console.WriteLine("Press any key...");
            Console.ReadKey(true);
        }
    }
}


For:

using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

you will need to add reference to files:

C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.ConnectionInfo.dll

and

C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Management.Sdk.Sfc.dll

C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Smo.dll

Your app.config file must to look like:

<?xml version="1.0"?>
<configuration>
<!--<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>-->
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <requiredRuntime version='v4.0.20506' safemode='true'/>
    <supportedRuntime version='v4.0'/>
  </startup>
</configuration>

To add app.config file do next:

1. On the Project menu, click Add New Item.
2. The Add New Item dialog box appears.

Select the Application Configuration File template and then click Add.

A file named app.config is added to your project.

OCR with MODI

Details
Written by: Stanko Milosev
Category: Code snippets
Published: 27 November 2010
Last Updated: 18 December 2011
Hits: 6366

OCR - optical character recognition, with MODI - microsoft office document imaging.

Microsoft has developed tool for OCR, which we can use it as a COM object.

First you need to install MODI on your computer, then, you can use it like this:

Document md = new Document();
String ocrText = String.Empty;

md.Create(openFileDialog1.FileName);
const bool ocrOrientImage = false;
const bool ocrStraightenImage = false;
md.OCR(MiLANGUAGES.miLANG_ENGLISH, ocrOrientImage, ocrStraightenImage);

var image = (MODI.Image)md.Images[0];
var layout = image.Layout;

foreach (Word word in layout.Words)
{
 if (ocrText.Length > 0)
 {
   ocrText += " ";
 }

  ocrText += word.Text;
}
textBox1.Text = ocrText;

Only problem is if you want to really release the object md, then you ave to use SaveAs method something like:

 

string path = Path.GetDirectoryName(openFileDialog1.FileName);

md.SaveAs(path + "\\deleteMe.tif", MODI.MiFILE_FORMAT.miFILE_FORMAT_DEFAULTVALUE, 
MODI.MiCOMP_LEVEL.miCOMP_LEVEL_MEDIUM);

Taken from here, and from this source code.

My source you can download from here, and exe file can be found here.

Beginner's All-Purpose Symbolic Instruction Code

Details
Written by: Stanko Milosev
Category: Code snippets
Published: 23 November 2010
Last Updated: 18 December 2011
Hits: 5019

Open new form in "modal" style:

  Form2 frmTest = new Form2();
  frmTest.ShowDialog();

To get path from file name:

using System.IO;
...
string path = Path.GetDirectoryName(openFileDialog1.FileName);

NUnit - Get Started

Details
Written by: Stanko Milosev
Category: NUnit
Published: 29 May 2016
Last Updated: 08 November 2018
Hits: 4270

In my case I decided to go to NUnit download page page and download NUnit directly (NUnit.3.2.1.msi).

Start new console application. In the solution add new class library. Then, in that class library add reference to NUnit, in my case file is:

C:\Program Files (x86)\NUnit.org\framework\3.2.1.0\net-4.5\nunit.framework.dll

Also add reference in class library to console application (application which we are going to test)

We will also need NUnit Test Adapter, in order to see our tests in test explorer.

Go to Tools -> Extensions and Updates

Go to online and search for NUnit3 Test Adapter - in my case I needed NUnit3 because of VS 2015

Install it. Restart VS. Code in console application which I am going to test looks like:

namespace NUnit
{
  public class Program
  {
    static void Main(string[] args)
    {
    }

    public string ATest()
    {
      return "Hello World";
    }
  }
}

Class library looks like:

using NUnit.Framework;
using NUnit;

namespace NUnitTest
{
  [TestFixture]
  public class HelloWorldTest
  {
    Program source;

    [SetUp]
    public void Init()
    {
      source = new Program();
    }

    [Test]
    public void ShouldShowHelloWorld()
    {
      Assert.AreEqual("Hello World", source.ATest());
    }
  }
}

Now rebuild solution. Open Test Explorer (Test -> Window -> Test Explorer)

And run all tests:

  1. Parameterized Tests
  2. Number of years of oldest child in a list of parents
  3. Simple example
  4. Writing Custom Control in .NET 6

Subcategories

WPF

Beginning

Code snippets

NUnit

LINQ

Windows Forms

Page 35 of 38

  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38