After some anguish trying to connect to a SQLServer database with Ruby, I finally discovered TinyTDS and it's fantastic.
However, it requires a username and password to talk to the database. In C# tests in the past, we've used SSPI to supply this, so that any tester can pick up a script and run it and it'll use their Windows Authentication details.
I can't find a way to do this with TDS (beginning to suspect it's not possible with the current version) and hoping someone might prove me wrong, or have another suggestion?
Cheers.
Found the solution.
My install of tiny-tds was version 0.51.
The latest version has SSPI, and so to get that:
gem install tiny_tds --version ">= 0.6.0.rc1"
This comes with no need to specify a username/password and use SSPI by default.
So as an example:
require 'tiny_tds'
sql = "SELECT name from sys.databases"
client = TinyTds::Client.new(:dataserver => "myserver", :database => "mydatabase")
result = client.execute(sql)
results = result.each(:symbolize_keys => true, :as => :array, :cache_rows => true, :empty_sets => true) do |rowset| end
#THIS IS TO OUTPUT IT TO THE CONSOLE
for i in (0..result.fields.length)
printf("%14s", result.fields[i])
end
for j in (0...result.affected_rows)
puts ""
for i in (0...result.fields.length)
printf("%14s",results[j].at(i))
end
end
Will print out a list of the database names, using SSPI to access the database.
Related
I've searched several related posts for the issue I'm having but wasn't able to find an answer. I'm a student in a coding program where most people use Mac, but I'm on Windows ( 7, Pro, 64 ) - because of that I'm a bit locked in to the tools/software I'll post here.
I'm trying to open a connection through Ruby with the pg gem, and I'm using Sinatra and PostgreSQL. I've established the server, database, and configuration path variables for PostgreSQL, and I've successfully installed pg gem (didn't have an issue there as in some of the other posts) with the line:
gem install pg -- --with-pg-config=C:\Program Files\PostgreSQL\9.5\bin
So the problem is that when I boot up Sinatra and go to the localhost,
I get a NoMethodError, Undefined Method for nil:NilClass on a method that otherwise works for Mac users.
The method is:
configure :development do
set :db_config, { dbname: "news_aggregator_development" }
end
configure :test do
set :db_config, { dbname: "news_aggregator_test" }
end
def db_connection
begin
connection = PG.connect(Sinatra::Application.db_config)
yield(connection)
ensure
connection.close
end
end
get '/articles' do
#results = db_connection do |conn|
conn.exec("SELECT * FROM articles")
end
erb :index
end
connection returns nil, and so the close method returns with an undefined method error. I don't think there is a syntax error as I've checked with others regarding this, and I'm thinking it might be related to a connection error with pg.
First time post so please go easy on me =) Apologies if I've left out any needed information - let me know what more context could be helpful and I will try to provide it! Thank you!
Two points:
Wrap your Sinatra helpers in a helpers {} block. This will allow you to use settings.db_config instead of Sinatra::Application.db_config:
helpers do
def db_connection
connection = PG.connect(settings.db_config)
yield connection
ensure
connection.close
end
end
In your PG.connect call, you should pass the host, user, password, and any other options necessary for the pg gem to find, connect, and authenticate to your instance. The dbname alone is not enough—at least not on Windows.
configure :development do
set :db_config, {
host: "localhost",
port: 5432,
user: "foo",
password: "bar",
dbname: "news_aggregator_development"
}
end
Good luck!
I use free heroku instance to run my Dashing project. In result, it looses the value passed previously, when my instance sleeps. I was recommended to use Redis to keep history. I tryed to follow the instruction given here. In result I got the following config.ru (as part of my dashing project):
require 'dashing'
require 'redis-objects'
require 'yaml'
configure do
set :auth_token, 'my-token'
set :default_dashboard, 'def' # https://github.com/Shopify/dashing/wiki/How-To:-Change-the-default-dashboard
helpers do
def protected!
# Put any authentication code you want in here.
# This method is run before accessing any resource.
end
end
end
def redis?
ENV.has_key? 'REDISTOGO_URL'
end
if redis?
redis_uri = URI.parse(ENV['REDISTOGO_URL'])
Redis.current = Redis.new(:host => redis_uri.host,
:port => redis_uri.port,
:password => redis_uri.password)
set :history, Redis::HashKey.new('dashing-history')
elsif File.exists?(settings.history_file)
set history: YAML.load_file(settings.history_file)
else
set history: {}
end
map Sinatra::Application.assets_prefix do
run Sinatra::Application.sprockets
end
run Sinatra::Application
and the following Gemfile:
source 'https://rubygems.org'
gem 'dashing'
gem 'redis-objects'
## Remove this if you don't need a twitter widget.
gem 'twitter', '>= 5.9.0'
But it didn't help. What I did incorrectly?
I also tried to use this tutorial. But it was giving me an error at line redis_uri = URI.parse(ENV["REDISTOGO_URL"]) (something like wrong url is given).
The problem was that the app requires the add-on Redis To Go
If Redis To Go is configured, REDISTOGO_URL is added to environment variables, it will work
For more information on how to setup Redis To Go, read the heroku article
Adding Redis to an application provides benefits, you may be using RedisToGo to power simple Resque or Sidekiq jobs, or using the raw power of Redis 2.6 Lua Scripting to do some crazy fast operations. Redis can be used a database, but it’s often used as a complementary datastore. With over 140 commands, the possibilities are endless.
I downloaded the postgres.app for my Mac OSX machine. I have a rails app that has connected and used the postgres DB that came with the postgres app.
Now I am writing a pure Ruby test script (Not Rails, pure Ruby, not even Active Record) to try to connect to the postgres database instance. These are the steps I followed to set this up
1) ran this command on the terminal:
gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/MacOS/bin/pg_config
2) Added this code to the test script:
#!/usr/bin/env ruby
#encoding: utf-8
require "pg"
#conn = PG.connect(
:dbname => 'oData',
:user => 'am',
:password => '')
#conn.exec("CREATE TABLE programs (id serial NOT NULL, name character varying(255);");
I got this from this link
When I ran this script I get the following error:
/Users/am/.rvm/gems/ruby-2.0.0-p247/gems/pg-0.16.0/lib/pg.rb:38:in `initialize': could
not connect to server: No such file or directory (PG::ConnectionBad)
Is the server running locally and accepting
connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?
My Debug efforts:
My postgres.app is up and running.
I looked at the pg gem [documentation][2] and my syntax seemed OK.
The location of my postgres DB is entered in my bash script like so
PATH="/Applications/Postgres.app/Contents/MacOS/bin:$PATH"
Not sure what to do next. Any help would be appreciated, Thanks.
are you sure postgres is listening on a socket? are you sure the username and password is right?
I would be inclined to try something like
require 'pg'
puts PG::Connection.ping(:dbname => 'oData',:user => 'am',:password => '')
puts "trying with tcp"
puts PG::Connection.ping(:dbname => 'oData',:user => 'am',:password => '', :port => 5432)
I used active record gem to make the connection work and it was fine
Settings to connect works for me.
But that code should look like
#conn.exec("CREATE TABLE programs (id serial NOT NULL, name
character(255))")
I am experiencing issues with Ruby 2.0p0 and XMLRPC::Client. When I run the code below in 2 different versions of ruby, I get a correct response on 1.9.3 but an error with 2.0.0. Anyone with the same issues? Is the solution just not to use the newest version of ruby or is there a workaround?
require "xmlrpc/client"
server = XMLRPC::Client.new2('http://api.flickr.com/services/xmlrpc/')
begin
res = server.call('flickr.test.echo')
puts res
rescue XMLRPC::FaultException => e
puts e.faultCode
puts e.faultString
end
Using ruby-1.9.3-p392 [ x86_64 ]
I get the correct response from flickr, since I didn't supply an API key:
100
Invalid API Key (Key has invalid format)
Using ruby-2.0.0-p0 [ x86_64 ]
I get an error from ruby saying "Wrong size. Was 365, should be 207 (RuntimeError)"
/home/luisramalho/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/xmlrpc/client.rb:506:in `do_rpc': Wrong size. Was 365, should be 207 (RuntimeError)
from /home/luisramalho/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/xmlrpc/client.rb:281:in `call2'
from /home/luisramalho/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/xmlrpc/client.rb:262:in `call'
from xmlrpc.rb:5:in `<main>'
I had a similar problem accessing a different xml rpc api (upcdatabase.com's) (seriously, who still uses xml rpc apis?) with ruby2.
My solution was to use a different xmlrpc library than ruby's default. LibXML-XMLRPC. It uses c extentions and is supposed to be faster than the standard library one, but it was last updated in 2008, so who knows how true that statement is today.
This is what my code ended up being that worked.
require 'xml/libxml/xmlrpc'
require 'net/http'
net = Net::HTTP.new("www.upcdatabase.com", 80)
server = XML::XMLRPC::Client.new(net, "/xmlrpc")
result = server.call('lookup', 'rpc_key' => "YOLOSWAG", 'upc' => "071160055506")
Hope this helps.
I proposed a patch for this. Lets see what the team thinks about it.
https://github.com/ruby/ruby/pull/308
I have to send weekly emails to all the user about the latest things happening. I am using ActionMailer to accomplish other mailing task however I have no clue how to automate the weekly emails.
Update
I found whenever gem which could be used to schedule cron jobs. I guess this could be used to send weekly emails which I intend to. Still looking how to make it work with ActionMailer will update once I find the solution
Update 2
This is what I have done so far using whenever gem:-
in schedule.rb
every 1.minute do
runner "User.weekly_update", :environment => 'development'
end
in users_mailer.rb
def weekly_mail(email)
mail(:to => email, :subject => "Weekly email from footyaddicts")
end
in users.rb
def self.weekly_update
#user = User.all
#user.each do |u|
UsersMailer.weekly_mail(u.email).deliver
end
end
If i try to run User.weekly_update from the console I am able to get the mails. I am testing in development mode and using rvm. I checked my crontab file and it has got the right stuff.
However I am not getting any mails automatically from the app. Any clue what might be wrong?
Thanks,
OK so it turns out to be a path issue with whenever gem, and the problem was created when I installed another version of ruby.
In my machine the new ruby version is installed in /usr/local/bin/ruby. In my rails app I had to go to the file script/rails and replace #!/usr/bin/env ruby with #!/usr/local/bin/ruby.
I found this out by visiting cron.log file which showed this error message :- /usr/bin/env: ruby: No such file or directory
I made a cron.log file to log the cron error this is what I did in my schedule.rb code written in the question :-
every 2.minutes do
runner "User.weekly_update", :environment => 'development', :output => 'log/cron.log'
end
I am getting periodic mails now.
It seems like you haven't configured ActionMailer settings.
First check out the logs from console, whether the mailing process is working(paste your logs).
If yes then do following steps.
add this in your gemfile.
gem 'tlsmail'
run
bundle install
write these configuration setting in your config/environments/development.rb file
require 'tlsmail'
Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => "587",
:domain => "gmail.com",
:enable_starttls_auto => true,
:authentication => :login,
:user_name => "<address>#gmail.com",
:password => "<password>"
}
config.action_mailer.raise_delivery_errors = true
add your working password/email against user_name and password.
Don't forget to restart server.