Search This Blog

2016/12/04

Installing SQL SERVER on Fedora 23

Here are my notes on installation of MSSQL SERVER on Fedora.

First become root
    # su -

Microsoft sql server on fedora requires two new YUM repository one for actual sql server and other for command line tool to query it.

Add Microsoft Software repository to your Fedoara Machine as follows

   #curl https://packages.microsoft.com/config/rhel/7/mssql-server.repo > /etc/yum.repos.d/mssql-server.repo

   #curl https://packages.microsoft.com/config/rhel/7/prod.repo > /etc/yum.repos.d/msprod.repo

this will basically create two files in /etc/yum.repos.d/ folder namely “mssql-server.repo” & “msprod.repo”

Installing SQL Server :
   to install sql server issue following command

         #yum install -y mssql-server

this will install package yet we need to configure it by issuing following command

       #/opt/mssql/bin/sqlservr-setup

this will ask for System Administrator (SA) account password which requires two be 8 character,also ask if you want to start sql server at time of startup.

You can check if server is running by issuing following command

    #systemctl status mssql-server

output of this command in my case is

mssql-server.service - Microsoft(R) SQL Server(R) Database Engine
Loaded: loaded (/usr/lib/systemd/system/mssql-server.service; disabled; vendor preset: disabled)
Active: active (running) since Sun 2016-12-04 20:04:11 IST; 27min ago
Main PID: 6431 (sqlservr)
Tasks: 144
Memory: 547.2M
CPU: 45.053s
CGroup: /system.slice/mssql-server.service
├─6431 /opt/mssql/bin/sqlservr
└─6493 /opt/mssql/bin/sqlservr

Dec 04 20:04:19 SangramOnFedora23 sqlservr[6431]: [145B blob data]
Dec 04 20:04:20 SangramOnFedora23 sqlservr[6431]: [66B blob data]
Dec 04 20:04:20 SangramOnFedora23 sqlservr[6431]: [75B blob data]
Dec 04 20:04:20 SangramOnFedora23 sqlservr[6431]: [96B blob data]
Dec 04 20:04:20 SangramOnFedora23 sqlservr[6431]: [100B blob data]
Dec 04 20:04:20 SangramOnFedora23 sqlservr[6431]: [71B blob data]
Dec 04 20:04:20 SangramOnFedora23 sqlservr[6431]: [124B blob data]
Dec 04 20:09:22 SangramOnFedora23 sqlservr[6431]: [71B blob data]
Dec 04 20:11:04 SangramOnFedora23 sqlservr[6431]: [156B blob data]
Dec 04 20:11:04 SangramOnFedora23 sqlservr[6431]: [193B blob data]

Microsoft SQL server runs on port 1433 we need to open it for commutation with server from outside of localhost.

If you firewall is running & blocking 1433 port then add exception to it

        # firewall-cmd --zone=public --add-port=1433/tcp --permanent
       # firewall-cmd --reload

If we have sql server up & running we can install tool to connect to it

    #yum install mssql-tools

This package needs “msodbcsqlpackage and it has dependency on “unixODBC” package.
In my case version of “ unixODBC” is higher than what “msodbcsql” can handle probably in with GAMBAS so I was getting error in installation of “mssql-tools

after quick googling I got a solution what we need is remove existing unixodbc package as follows

#yum remove unixODBC

then we need to add new repo & import corresponding keys

#yum-config-manager --add-repo https://apt-mo.trafficmanager.net/yumrepos/mssql-rhel7-release/
#yum-config-manager --enable mssql-rhel7-release
#wget "http://aka.ms/msodbcrhelpublickey/dpgswdist.v1.asc"
#rpm --import dpgswdist.v1.asc

and then install “msodbcsql

#yum install msodbcsql

after successful installation try to install “mssql-tools

#yum install mssql-tools

On success we will check how to connect to server from command line.
Run below command,do not forgot to replace SA account password with your sql server’s SA password.

#sqlcmd -S localhost -U SA -P 'SA_Account_PASSWORD'

we will run simple command to check if we are through.First type some sql command say 

select name from sys.databases;

hit enter and then type “go”  do not end it with semicolon and hit again to see result of sql query.

Output should be similar to below:

name                                                                                                                            
--------------------------------------------------------------------------------------------------------------------------------
master                                                                                                                          
tempdb                                                                                                                          
model                                                                                                                           
msdb 

to come out of sql-cmd command prompt need to use "quit" command.

We can use universal sql GUI tools like squirrel sql , dbeaver to connect to our newly installed 
sql server. Though  I got some success with squirrel sql but it was messed between Oracle JAVA & OPEN JAVA 
when I tried it on Ubuntu 16.We will explore this soon.
 
Attach MDF & LDF to create new Database (LINUX):
 
Login to SQL Server as
 
sqlcmd -S localhost -U SA -P 'yourPassword' 
 
CREATE DATABASE cart ON (NAME = 'cart', FILENAME = '/home/sangram/workspace/dotnet/cart/cart.mdf' , 
SIZE = 2048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) LOG ON (NAME = 'cart_log', 
FILENAME = '/home/sangram/workspace/dotnet/cart/cart_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
FOR ATTACH; 

GO:

You can see your cart database is attached.

References:
https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-setup-red-hat

2016/09/11

Running Ubuntu headless in Fedora 23 on Docker


First we will add docker repository for Fedora 23 for that inside directory

/etc/yum.repos.d/ 

add "docker.repo" file in which add following content.I use nano a simple command line text editor for it through root privileges.most of tutorial assumes root previlages on bash shell.

docker.repo” file should look like

[dockerrepo]
name=Docker Repository
baseurl=https://yum.dockerproject.org/repo/main/fedora/23
enabled=1
gpgcheck=1
gpgkey=https://yum.dockerproject.org/gpg


now we will update repository as follows

dnf update

lets install docker on our fedora machine

dnf install docker-engine

let’s enable docker service as follows

systemctl enable docker.service

need to start docker service as follows

systemctl start docker

we can check status of docker service is running or not using below command

systemctl status docker

Now we will install ubuntu image

docker pull ubuntu

once we pulled ubuntu image we can run it

docker run -it ubuntu
  
docker run -it ubuntu:latest /bin/bash

every time we run a image it creates new container we can see list of container using following command

docker ps -a

by the way to see list of pulled images we can use following command

docker images

once we have command prompt of container we can install some package that are useful in our quest

apt-get install nano

this will install nano command line text editor while below command will install subset of networking related tools that are suitable for docker container image

apt-get install -y inetutils-ping

we can check ip address of ubuntu server from fedora command prompt as follows

docker inspect e350390fd549

output of above command will be json string in which find a key "IPAddress" which will give us ip address of Ubuntu server running in docker,here ‘e350390fd549is container id that we can get by issuing docker ps -a or simply by looking at command prompt of ubuntu machine.

Adding new users

adduser sangram

adduser sagar

add user sangram to sudo group

usermod -aG sudo sangram

Install ssh server as follows

apt-get install openssh-server

modify setting of ssh demeon as follows.

Open config file

nano /etc/ssh/sshd_config

modify it to allow root login,X11 Forwarding,enable password authentication ,change port from default value to suitable value.check if DSA & RSA & Public key authentication is enabled or disabled check where it will look for password.There may be text similar to below

DSAAuthentication yes
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile %h/.ssh/authorized_keys

change flags suitably.

create public ,private keys using either rsa & dsa

ssh-keygen -t rsa

it will create two files under .ssh dir in you home directory of current user (root),in same location create a file

authorized_keys 
 
and add content of public key to it.Now copy the private key to you Fedora machine convert it to suitable format using puttygen command

puttygen id_dsa  -O private-openssh -o my-openssh-key

restart ssh serverusing below command replace restart by start if not running.

 /etc/init.d/ssh restart

now from fedora machine try to run putty and provide private key in ssh auth change IP address to Ubuntu server ip address also check port is same as one in which ssh server is running.

From command prompt you can check it as follows

ssh -p 2221 root@175.17.0.2

where 2221 is ssh port & 175.17.0.2 is ip address of you ubuntu server.

Lets install virtual framebuffer & lightweight window manager (jwm) & vnc server as follows

apt-get install xvfb

apt-get install x11vnc

jwm is very small window manager for X server.we are using xdm instead of gdm or kdm,xdm is default for X server.
apt-get install jwm

apt-get install xterm

apt-get --reinstall install xfonts-base

to assign password to vnc login issue following command

x11vnc -storepasswd

it will ask for password & confirmation do not change location where password will be stored default location will be /etc/x11vnc.pass

we need to define display settings as follows

Xvfb -screen 0 800x600x16 -ac &

now we will launch window manger JWM as follows

DISPLAY=:0 jwm &

to view our Window manager lets start vnc server as follows

x11vnc -rfbauth /etc/x11vnc.pass -display :0

now from fedora machine launch VNC viewer say tiger VNC viewer in that put ip address of our Ubuntu server it will ask for vnc password provide one you will see JWM running.

you can save changes made in running container to same image or new image so that you can latter work further on this as follows

docker commit e350390fd549 nameofconatainer

wish you best of luck.In case i miss some step in between(as this is done over weekends) please correct me.

2016/08/31

Linq - Group by into an array

LINQ has lot of capability that we seldom use.For example sometime we need to group a column into a string array or collection of some sort like say list based on another column.

Here I will demonstrate same into an array.

For purpose of demonstration I will create a class in some existing project

  public class KeyValue
    {
        public string KeyCol { get; set; }
        public string ValueCol { get; set; }
    }
 
Now I will create simple array of type 'KeyValue' just created.

  var wordList = new Model.DTO.KeyValue[] {
                new Model.DTO.KeyValue {KeyCol="key1", ValueCol="value1" },
                new Model.DTO.KeyValue {KeyCol="key2", ValueCol="value1" },
                new Model.DTO.KeyValue {KeyCol="key3", ValueCol="value2" },
                new Model.DTO.KeyValue {KeyCol="key4", ValueCol="value2" },
                new Model.DTO.KeyValue {KeyCol="key5", ValueCol="value3" },
                new Model.DTO.KeyValue {KeyCol="key6", ValueCol="value4" }
            };

Lets build a linq query on this collection(Array).Query groups 'KeyCol' property based on 'ValueCol' into group 'g' i.e. means g is collection of 'KeyCol'

            var query =from m in wordList
                     group m.KeyCol by m.ValueCol into g
                     select new { Name = g.Key, KeyCols = g.ToList().ToArray<string>() };

You can check resultset my looping  'query' 

    foreach (var rec in query)
    {
        var name = rec.Name;
        var strArray = rec.KeyCols;
    }

e.g in loop above when 'name' becomes 'value1' ,'strArray' will have value string[]{'key1','key2'} and so on.

we can further generalize this query to create object array in group by.

2016/08/17

Table valued function parameter in postgres SQL

   In Postgres -SQL server whenever we create a new table it automatically creates a composite Type that corresponds with structure of table. we can use this type to create a variable ,it can hold a single row of corresponding table.
In situation where we need to pass whole result-set as parameter to Postgres function there seems to be no native support in postgres unlike Microsoft SQL server so converting a existing MSSQL Procedure to Postgres function become quite a headache.
we can create an equivalent representation of result set in XML or JSON and pass it to function; inside function we can deserialize this into result-set for purpose of further operation on result-set that way we can compensate absence of Table Valued Parameters in Postgres SQL .
 Along with JSON & XML we can also create an array of objects from result-set to function as parameter.
Here I will demonstrate this approach with inbuilt Array functionality of Postgres.

Lets create a Table as follows
CREATE TABLE public."Projects"
(
   id integer NOT NULL,
  "createdAt" timestamp with time zone,
  "updatedAt" timestamp with time zone,
  name character varying(255) NOT NULL,
  "UserId" integer
);

For purpose of demonstration add few records into “Projects” table with two different user ids say 1 & 2.

Now let’s create a one more table that will used for passing result-set to our function, function is trivial one it just give count of rows user wise

CREATE table projectlist
(
                list int[],
                user_id int
);

Now we will use ROW construct to serialize our result-set and save that as a single row in projectlist table as follows

insert into projectlist(user_id,list)
select  1 "UserId",ARRAY(select id from "Projects" where "UserId" =1) ;

insert into projectlist(user_id,list)
select  2 "UserId",ARRAY(select id from "Projects" where "UserId" =2) ;

The Array function will convert values passed to it as an array e.g if it got 3 records as input  14,15,16 then resultant value will {14,15,16}. unnest is another Postgres function that do exactly reverse of it that we will use for de-serialization.
Below is my function that will read the record set

CREATE OR REPLACE FUNCTION public.demo_func(
    IN  list1 projectlist,
    IN  list2 projectlist)
  RETURNS TABLE(user_id int, count bigint) AS
$BODY$
BEGIN
               
        RETURN QUERY
                WITH  list1_cte AS (
                              
                ),
                list2_cte  AS (
                              
                )
                select  list1_cte.user_id,count(*) as count from list1_cte group by list1_cte.user_id
                union
                select  list2_cte.user_id,count(*) as count from list2_cte group by list2_cte.user_id;

END
$BODY$
LANGUAGE plpgsql ;

Now we need to join all dots and call our function by passing serialized result set.We create two table type variables list1 & list2 and give them serialized data that we had already inserted into our table created for same purpose.
   After that we will call our function that will return some records that I am looping using cursor.

DO
$$
DECLARE list1 projectlist;
DECLARE list2 projectlist;
DECLARE cursor_op_record RECORD;
DECLARE cursor_var refcursor;
BEGIN
                select p.* into list1  from projectlist p where user_id=1;
                select q.* into list2  from  projectlist q where user_id=2;
   OPEN cursor_var FOR
   select user_id,count from public.demo_func(list1,list2);

   RAISE INFO 'user_id, count';
   LOOP
                FETCH cursor_var INTO cursor_op_record;
                EXIT WHEN NOT FOUND;

        RAISE INFO '%,%', cursor_op_record.user_id, cursor_op_record.count;
   END LOOP;
END$$;

Here  our table projectlist has list column which is just an int[] but we can also replace it with array of composite type object and pass a single tuple.