Blog

HomeBlog
software-testSoftware Test Engineer impact on Successful Businesses

Software Test Engineer impact on Successful Businesses

Now days we are fully aware of the cost associated with the lack of quality of software to companies who buy a software product as well as also to the companies who generates the same software part. The job of improving quality on a restricted cost base is a hard one.

A client will never like a costly and hectic problem with software that doesn’t work, isn’t completed on time, does not encounter specifications, effects customers adversely, has bugs or is too difficult to use! The importance of testing as well as related activities began at the start of a project.

The STE plays a part in the SDLC as testing is not just finding bugs but it is the systematic valuation of an application’s fitness for the purpose it has been designed for.

Properly perform STE is not just so much verification of functionality of your product, though verification that your software expansion process produces high quality at each and every step. Testing implies throughout the lifecycle for maximum project benefit

• Requirement here test cases works on gathering requirements so no ambiguity left regarding requirements.

• Design test component addresses the desire to define the number of tests to be performed, the conducts that testing will follow and the test conditions that need to be work out.

• Implementation at this phase testing done to check the functionality basically.

• Verification it makes sure that the product is designed to deliver all functionality to the customer.

• Maintenance to ensure the quality of the product after handing it over to the customer.

The responsibility of STE, afterward, is not merely to make sure your product works. It is to make sure that the business you are building around your product works the method you planned, by make sure that your product’s satisfies the target audience well.

While there are a number of STE processes and tools that one can use, there is no silver bullet for ensuring that all STE requirements are completely managed. However as with development, there is a very rich pool of practices, skills and training to draw on. The basic problem I faced while testing projects was dealing with the time management and this was due to missing requirement. Test plans are related to the requirements that lead to effective testing. Often, the requirements are missing, incomplete, incorrect, ambiguous, or uneven. Low level requirements are mostly derived from high level sources. Likely verification methods may be vague and the tracing between requirements and tests may be missing.

Facts Corner

• In 2012, a leap year bug cause a leading multinational corporation’s cloud computing service outage, this affected Governments and also consumers. The same leap year date bug also affected an Australian payment system resulting in 150,000 customers being prohibited from utilizing private health care cards for two days.

• In 2011, two commuter trains hit following a landslip north of Wellington, while luckily no one was hurt. The investigation originate that a computer glitch meant KiwiRail did not warn on heavy rain condition, this could have minimized the damage.

• In 2010, a bug in the software system at Gisborne Hospital affected in one patient’s data being showed as however it were another patient.

Continue Reading
zfHow to Create an Image Slider Using Foundation Orbit and Reveal Modal

How to Create an Image Slider Using Foundation Orbit and Reveal Modal

Are you having trouble finding an image slider for your images? Why not try making one for yourself quickly using Foundation Orbit and Reveal Modal. The process is straight forward and quite simple. Although, there are many ways to do this, but here’s the one that I’ve used:

As my project was based on Ruby on Rails, here’s how my models were related:

User ← Album ← Photo

Album model holds all your albums, while Photo model holds all your images. You may wanna save different versions of your image, as I’ve saved ‘profile, medium and giant’ version of my images.

Before we get started, I will assume, you are familiar and have configured Foundation in your Rails app. If not, go through the following links:

Configuring foundation in rails: https://github.com/zurb/foundation-rails

Foundation Reveal Modal http://foundation.zurb.com/docs/components/reveal.html

Foundation Orbit http://foundation.zurb.com/docs/components/orbit.html

Ok, now lets get started!
Step 1: First of all, list all of your images in your view:

[snippet id=”58″]

Step 2: You may want to associate link_to with your images, So upon clicking, you could show up your images in a Reveal Modal. Also remember to define your Modal:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#/albums/show.html.erb
 @photos.each do |photo|
 =link_to user_album_photo_path(current_user, @album, photo), remote: true do
<div class="thumbnail">
= image_tag photo.photo.profile
<div class="caption">
<h3 class="title text-center">=truncate(photo.title, length: 50) </h3>
</div>
<div class="thumbnail-filler"></div>
</div>
 end
 end
<div id="photo_modal" class="reveal-modal small" data-reveal="">
</div>

Set remote: true, so we could make ajax call to the server
Step 3: In the corresponding controller, define your action as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#PhotosController
def show
@user = current_user
@album = @user.albums.find(params[:album_id])
<a name="__DdeLink__0_1861686962" id="__DdeLink__0_1861686962"></a> @photo = @album.photos.find(params[:id])
respond_to do |format|
format.html
format.js
end
end

And define the corresponding js and html file as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<a name="__DdeLink__2_1861686962" id="__DdeLink__2_1861686962"></a> #/photos/show.js
$('#photo_modal').html('=j render 'photos/orbit_photos', album: @album, photos: @album.photos')
$('#photo_modal').foundation('reveal','open');
#/photos/show.html.erb
<div id="photos">
= image_tag @photo.photo.giant
</div>

Step 4: Define your partial file ‘orbit_photos’, which contains code for Foundation Orbit for your images:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#/photos/_orbit_photos.html.erb
<div id="photo_container">
<ul class="orbit-photos" data-orbit="" data-options="pause_on_hover: false; timer_speed: 4000; animation_speed:1500; slide_number: false; next_on_click: true;">
 photos.each do |photo|
<li>
<div class="text-center">
<h2 class="page-header">= link_to(photo.title, user_album_photo_path(current_user, album, photo)) </h2>
= link_to(image_tag(photo.photo.medium), user_album_photo_path(current_user, album, photo))
</div>
</li>
 end
</ul></div>

You can customize your orbit differently, by passing different attributes in data-options, you should reference Foundation Orbit documentation for more details.

Step 5: Now, you are almost done, but you may get different issues with your slider, now lets deal with them. Your images could be of different sizes, so, set options variable height equal to true for Orbit:

1
2
3
4
5
6
7
#/photos/show.js
$(".orbit-photos").foundation(orbit: {
variable_height: true,
});

Also, as images are dynamically loaded to Reveal modal, you may want to adjust its size, after orbit-photos have been loaded into it:

1
2
3
4
5
$("#photo_modal").on "opened", ->
$(window).trigger "resize"
return

 

That’s all folks, the image slider is all set!

Continue Reading
Migrate-Data-From-PostGres-to-MySQLHow to Migrate Data From PostGres to MySQL on a Remote Server for a Ruby on Rails Application

How to Migrate Data From PostGres to MySQL on a Remote Server for a Ruby on Rails Application

When it comes to migrating data from postgres to mysql, a developer might face some compatibility issues for which finding the right solution becomes a hectic task. I went through a lot of hassle when migrating data of an application from postgres local server to a remote mysql cloud based server. This small step by step process will guide you through the practical solution of how to migrate data when such a situation arises.

Assuming you have mysql installed on the remote machine and access to cmd interface on local server.

1. Access your localmachine/local server with postgres database using from terminal using the following command:

run ssh -X username@localserver.ip.addresss -p

2. Navigate to the rails application folder:

cd var/data/myapplication

3. There are two options to export your data:

a) Using Postgres dump command from terminal:

pg_dump -h localhost -p 5432 -U postgres -F p -b -a -f "/path/to/file/for/dumping/examplefile.sql" databasename

where

-h= –hostname e.g. localhost

-p= –port (usually 5432 for postgres)

-U= –Username is the database username (default postgres)

-F p= –format=format Selects the format of the output. format can be one of the following

p plain : Output a plain-text SQL script file (the default).

c custom : Output a custom-format archive suitable for input into pg_restore.

d directory : Output a directory-format archive suitable for input into pg_restore

-b=–blobs Include large objects in the dump. This is the default behavior except when –schema, –table, or –schema-only is specified, so the -b switch is

only useful to add large objects to selective dumps.

-a=–data-only Dump only the data, not the schema (data definitions). Table data, large objects, and sequence values are dumped.

-f=–filename is the file name with path where to dump the data. (Create the examplefile.sql before hand at the path)

For more information on pg_dump extensions visit: http://www.postgresql.org/docs/9.3/static/app-pgdump.html

b) Using the GUI of Posgtres my admin:

– Open terminal and run:

 pgmyadmin3

– When the GUI is open, Connect to the database server using the login credentials for your account

– When connection is made, press the + sign on the hierarchical menu and go to the public directory

– Right click, from options choose Backup from bottom

– A new window appears, Enter the name of file, and options from different tabs including plain format, blobs and excluding privileges, owner name etc

– Make sure to check data only options in the second tab to extract only data from the tables, and column inserts in column inserts options

– Select all /required tables for which data needs to be exported

– When you have chosen the desired options, press Ok button and the data will be generated in the external file

4. Now that postgres dump file has been created there is a need to convert the data to mysql compatible format:

– Download pg2sql.tar.gz2 from http://www.lightbox.ca/pg2mysql.php (you may copy paste the code from the data file to the online version of the converter but for large data files, copy pasting is not a desirable option so its better to use the local copy of software)

– unzip the files to some directory using command | tar xjvf pg2mysql-1.9.tar.bz2 (in my case the directory was /tmp, and the file was also dumped to /tmp folder)

– Go to the pg2mysql folder using command | cd /tmp/pg2mysql-1.9

– To convert the examplefile.sql to mysql compatible format run command in the pg2mysql directory:

php pg2mysql_cli.php /tmp/myexamplefile.sql /tmp/myexamplefile_mysql.sql innodb

Command format is = php pg2mysql_cli.ph /[path-file-to-convert] /[output-file-path-with-name] [engine]

In case you get an error (in my case I did) running the pg2mysql_cli.php, do the following:

-emacs pg2mysql.inc.php [you may use any other editor like vi]

-Press Ctrl+S, and search for &$ , change it to $ only as in newer versions of php, & will be a deprecated option with the code

-Press Ctrl+X+S to save changes and then Ctrl+X+C to exit emacs

-re run the php command in the last step and wait till your file is converted

-You may view the converted file using command | less /filepath/filename.extension

5. Now that the file is converted on your local server, copy the file from there to the cloud project directory using SCP or RSYNC Command from local server:

scp /tmp/rmyexamplefile_mysql.sql cloudhostname@ip.addrress.of.cloud.instance:/tmp

6. Now log in to the cloud server using the login credentials using terminal (In our example we used Google Cloud).

7. Copy file from temporary folder to the upload folder of PHPMyAdmin (Default directory to upload PHPMyAdmin import files):

cp /tmp/myexamplefile_mysql.sql /var/lib/phpMyAdmin/upload/

8. Considering you have mysql2 gem installed in your cloud application, and config/database.yml file of rails app filled with correct database user credentials, to create your database tables automatically, Go to your application directory and run database migrations based on your environment. In case of plugins in application, make sure to run plugin migrations separately as well:

rake db:migrate RAILS_ENV=production

9. Migrations may have some dummy data present in the tables so its a good practice to truncate any default data to upload the converted mysql2 data:

 mysql -uUSERNAME -pPASSWORD -Nse 'show tables' DATABASENAME | while read table; do mysql DATABASENAME -uUSERNAME -pPASSWORD -e "SET FOREIGN_KEY_CHECKS=0;truncate table $table;SET FOREIGN_KEY_CHECKS=1;"; done

10. Now that tables are truncated, you may import the myexamplefile_mysql.sql data file which is mysql2 compatible. File may be chosen from upload directory using PHPMyAdmin UI view but if the files are large >8 MB, it may create problems in uploading them directory. Its recommended to use command line interface:

mysql -uUSERNAME -pPASSWORD DATABASENAME

This takes in username, password and database name to upload the file, takes in the path to file and uploads the data to the tables no matter how large the file is.

11. Now that the file is uploaded, restart mysql service on the cloud instance and you are ready to use the database with the application:

sudo /etc/init.d/mysqld restart

This effort will surely help you save a lot of time and hassle of migrating database from postgres to mysql. This blog will also give you basics of how to work with terminal to upload large import files to mysql/phpMyAdmin, manually truncate databases, and copying files between servers and systems.

Make sure to transfer files between servers you have the right permissions (e.g. ssh keys added to permissible list of keys). Feel free to give your comments or imporvements in the steps if you feel are important.

Continue Reading
reality-huntHow to Use Reality Hunt

How to Use Reality Hunt

App Overview

Ever wanted to have an application that can teach your kids valuable information while having fun and playing games? Reality hunt is the app you have been looking for. Reality hunt is an augmented reality based application to teach kids about different animals, scientists, and fruits.

You pick a category from among animals, scientists, and fruits to begin playing. A particular scientist, animal, or plant is assigned each time to find out using the camera; once it’s found you get valuable information about the object and answer some basic question about that information to continue to the next element.

 

Image set download link: Download and print this target that contains all images needed for the application: Print the downloadable image

Image can also be downloaded from /wp-content/uploads/2015/04/all-in-one2.jpg

How to Use

This step-by-step guide will tell you in detail about the steps to follow to use this application. The first thing you do is the selection of a game among scientists, animals, or fruits to begin.

Each of the three games corresponds to a particular category, and once the game is selected then you will be given the names of the objects of that category to find out.

 

After you have selected the game (in the below scenario: animals), then you will be given a name of the animal to find out. You will have to move your camera and take it to the picture of that particular animal from the downloaded and printed image set given below to detect it.

 

Once you have found a particular target in the camera, a new screen appears with the name, picture, and other basic and interesting information about the particular target as shown in the below picture.

After you have read the information, tap on the screen to see a random question about the presented information. You can re-read the information if the answer is not known, although re-reading contributes to losing score. Once the question is answered then you will be provided with the next target to found out.

After all the targets are found, you will be shown your score with the number of detected objects and number of answered questions along with the time to find the targets and the time to read the info and answer the questions.

 

Score Details

  • 20 points are awarded on succesfully detecting a target.
  • 20 points are given if the question is answered in the first attempt.
  • Each wrong attempt or re-reading of the information contributes in deducting 1 mark from your score.

 

Image set download link: Download and print this target that contains all images needed for the application: Print the downloadable image

Image can also be downloaded from /wp-content/uploads/2015/04/all-in-one2-1.pdf

 

Demo

Continue Reading
app-blog-imgKick that Photojack!

Kick that Photojack!

Ever had those beautiful pictures with your loved ones taken, only to have some photojack appear? Then Abracadabra Snap! is the app for you. Abracadabra Snap! is a simple to use photo editing iOS application to move or completely remove objects within the picture. The app provides an easy to use interface to remove unwanted objects from the image, move different objects around, and remove photobombs or unwanted appearances in the image.

 

App Overview

The first thing you do is selection of a picture for editing. You can select the photo from image gallery or take a snap on the fly. You can also load one of your previously edited photos from within the application.

Abracadabra Snap!

To change the orientation of the selected picture, you can rotate the photo in any direction you want. Once the photo and its rotation is finalized then Abracadabra Snap! assists in the process by the help of automatic object detection and it provides a photo with all the objects marked in red.

You can simply tap on any detected object that you intend to move and it will get selected.

Abracadabra Snap! photobomb remover

The customization tool in the application gives you complete freedom to manually select and adjust an object of choice if the automatic detection does not work perfect or if you want to create a manual selection with multiple objects at once.

Each selection point can be moved with a simple drag and drop to make an object of choice.

Abracadabra Snap! iOS

After manually creating the final selected object, you simply have to drag the object to move it. When you start to drag the object, a trash icon appears either on the left or the bottom of the screen.

If you choose this options and drop the selected object in the trash, it gets removed from the original position and is thrown out of the image and the background is modeled in the location to reduce the effect of any movement of object from that location. It gives the impression that the object never existed in that place.

Abracadabra Snap! app

If the user places it somewhere else in the image, the object is removed from its initial position and placed at the final position, which can help you do fun stuff with your application by moving different objects around and rearranging the whole setting of objects or people in the photo.

Abracadabra Snap! Android

The background modelling algorithms model the background in place of the moved object to reduce the effect of object movement.

Another feature of ‘copy object’ is provided in the application that can be used for two different purposes.

  1. If you think the background adjustment at the place of moved object is not perfect then you can further improve the background modelling at the place from where the object is moved. It can be improved by manually selecting a small background texture area and placing it everywhere where the background needs to be improved.
  2. If it is intended to make multiple copies of the objects in the image

The object is selected in the copy object option in the same way as in the move object option but a duplicate copy of the object is created at the dropped place instead of removing the object from the original place.

The below image depicts this functionality by creating multiple copies of the same object at two different locations:

abracadabra snap ios app

App Features

  • Pick an image from gallery or take a picture from camera
  • Rotate the object to adjust to the required orientation for further processing
  • The application automatically selects and marks all objects in the image
  • Manual objects can be selected and marked manually by the customization tool
  • Objects are moved or completely removed from the image by a simple drag and drop
  • The modified images are automatically saved in the workshops so that the user can keep modifying the images on next launch of application
  • Save the modified image in the photo gallery and share it on facebook and twitter
Continue Reading
Introduction-to-Basics-of-RSpec-in-Ruby-On-RailsA Brief Introduction to Basics of RSpec in Ruby On Rails

A Brief Introduction to Basics of RSpec in Ruby On Rails

RSpec is a library that focuses on testing the behavior of your everyday projects for Ruby programming language. Developers are usually reluctant to use it because probably testing practice is the most difficult mindset a developer has to learn.

But once Rspec testing habit is developed and Test Driven Development is in , it becomes really useful in diagnosing problems in large scale applications once they are modified for some changes in future.

In the long term, a developer will not have to check each web page every time a new feature is added, but he will only check if the specific test passed and so handling of large applications becomes a convenient task.

Born under the banner of Behavior-Driven Development, Rspec is a productive and enjoyable automated testing experience with features like:

-a rich command line program (the rspec command)

-textual descriptions of examples and groups (rspec-core)

-flexible and customizable reporting

-extensible expectation language (rspec-expectations)

-built-in mocking/stubbing framework (rspec-mocks)

The post is a brief step by step process to setup RSpec with your project and use it. The tests for rspec will be written in capybara language, which is similar to natural language and is widely used for testing purposes. Capybara helps you test web applications by simulating how a real user would interact with your app.

It is agnostic about the driver running your tests and comes with Rack::Test and Selenium support built in. WebKit is supported through an external gem. (http://rubydoc.info/gems/capybara/2.2.1/frames)

1. Include gem ‘rspec-rails’, gem “capybara”, “~> 2.1.0”, gem “shoulda”, “~> 3.3.2”, gem ‘factory_girl_rails’

In your command line install the rspec gems:

2. gem install rspec

3. gem install rspec-rails

4. gem install capybara

Generate the rspec testing module files using this command

5. script/rails generate rspec:install

Run bundle installer

6. bundle install

Run required migrations

7. rake db:migrate RAILS_ENV=development

8. Include require ‘rspec/rails’, require ‘capybara/rspec’ in you spec_helper file

9. Add config.include Capybara::DSL in the same file to make Capybara available in all test cases deriving from ActionDispatch::IntegrationTest:

Generators

Once the environment is set. Its time to generate the testing files. There are different test types including, model , view, controller,and integeration tests. Other types of tests are request, mailer and helper tests.

They are written as per requirements to cover every aspect of the application. This article will cover commands and examples related to the most commonly used type of Rspec Tests.

-rails generate rspec:model model_name

-rails generate rspec:controller contoller_name

-rails generate rspec:view folder_name view_name

-rails generate integration_test feature_name

Execution Commands

To run specific tests from command line following commands should be used:

Models: bundle exec rspec spec/models/search_phrase_spec.rb

Controllers: bundle exec rspec spec/controllers/users_controller_spec.rb

Views: bundle exec rspec spec/views/search_phrases/index.html.erb_spec.rb

Integration: bundle exec rspec spec/features/search_phrases_spec.rb

The Naming convention for the Rspec Testing files:

Models: modelname_spec.rb

Controllers: controllername_controller_spec.rb

Views: viewname.html.extensionname_spec.rb

Integeration: featurename_spec.rb

Example of Tests

Stub method to simulate dummy user creation and devise sign_in authentication before tests

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
before :all do
@user = User.find_by_name('testuser')
@user ||= begin
user = User.new(email: "test@gmail.com",
password: "$2a$10$T",
uid: "10000697585", name: "testuser",
authority_token: "AUExuiUkFoBAEsYd")
user.save!
user
end
end
 
before :each do
User.stub(:current_user).and_return(@user)
sign_in @user
end

OR USE FactoryGirl to create the user for model test

1
2
3
4
5
6
7
8
9
10
11
FactoryGirl.define do
factory :user do |user|
 
user.email "testformodel@gmail.com"
user.password "$2a$10$T"
user.uid "10000697585"
user.name "testuserformodel"
user.authority_token "AUExuiUkFoBAEsYd"
end
 
end

You can use either of the above mentioned codes as per need.

Models

Here is an example code for the associated models:

class SearchPhrase

2. # bowling.rb

1
2
3
4
5
6
7
8
class Bowling
def hit(pins)
end
 
def score
0
end
end

Following are the related Rspec tests:

Test

First of all:

1. # search_phrase_spec.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
require 'spec_helper'
class ValidatingWidget
2. # bowling_spec.rb
<pre class="brush: ruby">require 'bowling'
describe Bowling, "#score" do
it "returns 0 for all gutter game" do
bowling = Bowling.new
20.times { bowling.hit(0) }
bowling.score.should eq(0)
end
end
</pre><p>
These tests will pass when executed</p>
<h3>Controller</h3>
<p>In this example a controller method creates search phrases for a specific user using keywords and saves them in database<br>
#search_phrase_controller.rb</p>
<pre class="brush: ruby">def create
@search_phrase = current_user.search_phrases.new(params[:search_phrase].permit(:keyword))
if @search_phrase.save
redirect_to search_phrases_path, notice: 'Search Phrase was successfully created.' }
end
end
</pre><p>
Following are the related Rspec tests:</p>
<h3>Test</h3>
<p>#search_phrase_controller_spec.rb</p>
<pre class="brush: ruby">require 'spec_helper'
describe SearchPhrasesController do
include Devise::TestHelpers
describe "POST #create" do
it "should pass params to search phrases" do
post :create ,search_phrase: {keyword: 'testkeywordnew'}
assigns[:search_phrase].keyword.should == 'testkeywordnew'
end
it " should redirect to 'index' with a notice on successful save" do
post :create ,search_phrase: {keyword: 'testkeywordnew'}
response.should redirect_to(search_phrases_path)
end
end
</pre>
<h3>View</h3>
<p>This example is shows the index page of the search phrase example app for which the tests are written<br><br>
#index.html.erb</p>
<pre class="brush: ruby"><div> </div>
<h2> </h2>
<div> <button>Add Keyword</button></div>
<br><div>
 
 'new' %>
</div>
 
<div>
 
<table><thead><tr><td>Keywords</td>
<td>Options</td>
</tr></thead><tbody><tr id="table-row-<%=keyword.id%>"><td>
<div></div>
<div>
 'edit', :locals => {:search_phrase => keyword} %>
</div>
</td>
<td>
<button id="button-edit-<%=keyword.id%>" class="btn btn-info"><i class="icon-pencil icon-white"></i></button>
 
</td>
</tr></tbody></table></div>
</pre>
<h3>Test</h3>
<p>Following are the related Rspec tests:</p>
<p>#index.html.erb_spec.erb</p>
<pre class="brush: ruby">require 'spec_helper'
 
describe "search_phrases/index.html.erb" do
include Devise::TestHelpers
 
<put user="" sign="" in="" stub="" here="" if="" devise="" authentication="" required="">
 
#Mock model is creating a virtual model to write view tests
let(:search_phrase) do
mock_model('SearchPhrase',
:id => 1,
:keyword => 'testkeyword2',
:user_id => @user.id,
:created_at => Time.utc(2000))
end
 
before do
assign :search_phrases, []
end
 
#displays and renders the pages
it "renders the template 'index.html.erb_spec'" do
 
puts "*--Search Phrases #{@search_phrases.to_yaml}"
render
expect(view).to render_template( "search_phrases/index","search_phrases/_new")
end
 
#displays script
it "displays the script tag '<script>
<!--//--><![CDATA[// ><!--
<!--//--><![CDATA[// ><!--
'" do
render
expect(rendered).to match /<script>/
end
 
it "displays the user image in index" do
render
expect(rendered).to include(@user.image)
end
 
it "displays the user name in index" do
render
expect(rendered).to include(@user.name)
end
 
it "displays the button Text 'Add Keyword'" do
render
expect(rendered).to match /Add Keyword/
end
 
it "displays the button 'Add Keyword'" do
render
puts "*Rendered View #{rendered}"
rendered.should have_button('Add Keyword')
end
 
it "displays the heading'Keyword'" do
render
rendered.should have_content('Keyword')
end
 
it "displays the button 'Add Keyword'" do
render
rendered.should have_button('Add')
end
 
end
 
//--><!]]]]><![CDATA[>
//--><!]]>
</script></put></pre><h3>Integration</h3>
<p>Integration tests deal with the integration functions of a complete set of application function. For the scope of this post, we are taking example of a page, where user opens a web page, the application checks if user is signed in or not, if user is signed in, the user has authority to perform search function using a keyword phrase, and edit or update the search phrases.</p>
<h3>Test</h3>
<p>The tests show how these functions are tested:</p>
<pre class="brush: ruby">describe "SearchPhrases" do
 
#@user stub code for authentication or phrase creation>
 
#===========TESTS START=========================================================
# '/' refers to home of application
 
def logged_in?
page.has_selector? "username", text: "Sign Out"
end
 
describe "Go to Application Start" do
 
it "should not have user logged in before" do
visit '/'
logged_in?.should == false
end
 
it "should have the content 'Welcome to Demo Application'" do
visit '/'
expect(page).to have_content('Welcome to Demo Application')
end
end
 
describe "check images and icons" do
 
it "should have the Demo logo" do
visit '/'
puts "*Demo Logo xpath-> #{:xpath.to_s}"
page.should have_css("img[src*='arkhitech']")
end
end
 
describe "After User Logs In", js: true do
 
before :each do
 
unless logged_in?
visit '/'
OmniAuth.config.mock_auth[:provider] = {
provider: 'provider',
uid: @user.uid,
credentials: {
token: @user.provider_token
}
}
click_link "Sign in"
end
end
 
it "should be logged in" do
logged_in?.should == true
end
 
it "should show the name of user" do
page.should have_content "#{@user.name}"
end
 
it "should show the display picture of user" do
page.should have_css("img[src*='#{@user.image}']")
end
 
#------------------------------- Now Add Key Word Button Pressed----------------
 
it "click button 'Add Keyword' and display Keyword heading" do
find('#toggleKeywordAdd').click
expect(page).to have_content('Keyword')
 
end
 
it "click button 'Add Keyword' and display edit and remove buttons" do
find('#toggleKeywordAdd').click
fill_in('search_phrase[keyword]', :with => 'KEYWORD_3')
click_button("Add")
expect(page).to have_content('KEYWORD_3')
page.should have_css("button[class*='btn btn-info']")
page.should have_css("a[class*='btn btn-danger remove_fields']")
end
 
it "click button 'Add Keyword', adds keyword and click update button to update" do
find(:css,"button[id*='button-edit-#{@search_phrase.id}']" ).click
page.should have_css("input[class*='btn btn-medium btn-primary']")
page.should have_css("input[id*='search_phrase_keyword']")
fill_in('search_phrase[keyword]', :with => 'KEYWORD_EDIT')
click_button("Update")
expect(page).to have_content('KEYWORD_EDIT')
end
 
it "log out user on Sign Out" do
click_link("Sign Out")
current_path.should eq root_path
logged_in?.should == false
end
end
end
</pre><p>
These are some comprehensive examples which I practiced as a beginner. Again practicing brings perfection, so keep practicing with RSpec and get in control of your huge big applications. For your ease, here is quick summary of capybara language commands to write your tests. [courtesy: github/zhengjia]</p>
<p><em>=Navigating=</em><br><em> visit('/projects')</em><br><em> visit(post_comments_path(post))</em></p>
<p><em>=Clicking links and buttons=</em><br><em> click_link('id-of-link')</em><br><em> click_link('Link Text')</em><br><em> click_button('Save')</em><br><em> click('Link Text') # Click either a link or a button</em><br><em> click('Button Value')</em></p>
<p><em>=Interacting with forms=</em><br><em> fill_in('First Name', :with => 'John')</em><br><em> fill_in('Password', :with => 'Seekrit')</em><br><em> fill_in('Description', :with => 'Really Long Text…')</em><br><em> choose('A Radio Button')</em><br><em> check('A Checkbox')</em><br><em> uncheck('A Checkbox')</em><br><em> attach_file('Image', '/path/to/image.jpg')</em><br><em> select('Option', :from => 'Select Box')</em></p>
<p><em>=scoping=</em><br><em> within("//li[@id='employee']") do</em><br><em> fill_in 'Name', :with => 'Jimmy'</em><br><em> end</em><br><em> within(:css, "li#employee") do</em><br><em> fill_in 'Name', :with => 'Jimmy'</em><br><em> end</em><br><em> within_fieldset('Employee') do</em><br><em> fill_in 'Name', :with => 'Jimmy'</em><br><em> end</em><br><em> within_table('Employee') do</em><br><em> fill_in 'Name', :with => 'Jimmy'</em><br><em> end</em></p>
<p><em>=Querying=</em><br><em> page.has_xpath?('//table/tr')</em><br><em> page.has_css?('table tr.foo')</em><br><em> page.has_content?('foo')</em><br><em> page.should have_xpath('//table/tr')</em><br><em> page.should have_css('table tr.foo')</em><br><em> page.should have_content('foo')</em><br><em> page.should have_no_content('foo')</em><br><em> find_field('First Name').value</em><br><em> find_link('Hello').visible?</em><br><em> find_button('Send').click</em><br><em> find('//table/tr').click</em><br><em> locate("//*[@id='overlay'").find("//h1").click</em><br><em> all('a').each { |a| a[:href] }</em></p>
<p><em>=Scripting=</em><br><em> result = page.evaluate_script('4 + 4');</em></p>
<p><em>=Debugging=</em><br><em> save_and_open_page</em></p>
<p><em>=Asynchronous JavaScript=</em><br><em> click_link('foo')</em><br><em> click_link('bar')</em><br><em> page.should have_content('baz')</em><br><em> page.should_not have_xpath('//a')</em><br><em> page.should have_no_xpath('//a')</em></p>
<p><em>=XPath and CSS=</em><br><em> within(:css, 'ul li') { ... }</em><br><em> find(:css, 'ul li').text</em><br><em> locate(:css, 'input#name').value</em><br><em> Capybara.default_selector = :css</em><br><em> within('ul li') { ... }</em><br><em> find('ul li').text</em><br><em> locate('input#name').value</em></p>
<h3></h3>
<h3>Further Reading</h3>
<p>Furthur information and best practices can be reviewd on RDocs:</p>
Continue Reading
developer-tools_0Web Developer Tools: A Must Add-on for Web Development

Web Developer Tools: A Must Add-on for Web Development

Web Developer tool, is the add-on for your firefox, chrome, seamonkey browsers. It gives you extra tools to debug your website, HTML, layout, javascript and even images. It lets you control your browser’s cache and cookies etc. as well. Following is a quick overview of how this can be useful to you:

Disable

Cookies

CSS

Forms

Images

Information

Miscellaneous

Outline

Resize

Tools

View Source

Options

Installation

1. Choose your browser, compatible browsers are firefox, chrome and seamonkey. 2. Follow the link Web Developer Tools  3. Click the button “Download Now” and it will download and install for your browser. You need to restart your browser to make it work. Special thanks to developer of this tool.

Continue Reading
check-facebook-fan-page-like-in-phpHow to Check if a User is Following Your Facebook Page in PHP

How to Check if a User is Following Your Facebook Page in PHP

Social media optimization is really essential these days and awarding your site users some points or badges for liking your Facebook fan page is a nice trick to swiftly increase your Facebook fan base. In order to award a user some social bonus, we first need to check whether that user has actually liked the Facebook fan page or not. In order to check this we need the user to login into its Facebook account and allocate all the necessary permissions that our Facebook app will ask (OAuth 2.0).

In case you are NOT OK with user giving the permissions you can skip this tutorial as this tutorial specifically requires OAuth permissions from the users. And, if you are OK with OAuth permissions and your site happens to be a PHP based website, follow this step by step tutorial to easily detect whether a user has liked your fan page or not:

 

Step: 1

Create a new Facebook app here. Enter the URL of your site in Settings->Platform->Website->Site URL and note down the ‘App ID’ and ‘App Secret’ as we will be using these in step 5!

 

Step: 2

Download Facebook PHP SDK from here. Extract the files and place it in the same folder with the file in which you will paste the code given in the step 5 below!

 

Step: 3

Get your Facebook Fan Page ID using this tool.

 

Step: 4 (Optional)

Generate Facebook like box code for your page from here. You can display this like box if a user hasn’t already liked the page.

Step: 5

After 1, 2, 3 and 4 steps are complete, you can check if user has liked a page or not with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!--?php require('facebook.php');
    $config = array(
         'appId' =?--> 'your facebook app id',
         'secret' => 'your facebook app secret code',
        'allowSignedRequest' => false
    );
    $facebook = new Facebook($config);
    $user_id = $facebook->getUser();
    if (isset($user_id)) {
        try {          
            $likes = $facebook->api('/me/likes/your_facebook_page_id_here', 'GET');            
            if (!empty($likes['data'])) // if user has liked the page then $likes['data'] wont be empty otherwise it will be empty
            {
                echo 'Thank you for liking our fan page!';         
                // you can write some custom code here to award users some points or some badge        
            }
           else {
                echo 'You have not liked our fan page! Like it now:';
                ?>                  
                <iframe src="//www.facebook.com/plugins/likebox.php?href=https%3A%2F%2Fwww.facebook.com%2Farkhitech&width&height=290&colorscheme=light&show_faces=true&header=true&stream=false&show_border=true&appId=1392604484339363" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:290px;" allowtransparency="true"></iframe> //replace this with your own Facebook like box code
                <!--?php }
        } catch (FacebookApiException $e) {
            $login_url = $facebook-?-->getLoginUrl();
            echo '<a href="' . $login_url . '">Please click here to login into your Facebook account.</a>';
            error_log($e->getType());
            error_log($e->getMessage());
        }
    } else {
        $login_url = $facebook->getLoginUrl();
        echo '<a href="' . $login_url . '">Please lick here to login into your Facebook account</a>';
    }
    ?>

 

Output

The user will click on the “Please click here to login into your Facebook account.” text which will redirect it to our Facebook app’s (created in step 1) permissions page, once the user grants the permissions to the app, the code will fetch user’s data and will display the likebox if user hasn’t liked the fan page.

If the user has already liked the page then it will display the thank you message (and will run some custom code included in this section to award some points/badge to the user).

 

Prevent Cheating

In order to award points only once (so that users cant get points again and again by liking and unliking the page), you can attach a Boolean field (with a default value of 0) with all user accounts which you can turn to 1 once the bonus points have been awarded. An additional conditional check at line 14 in the code given above like “if (!empty($likes[‘data’] && $userfield != 1 ))” will do the trick.

You can also print a message like “You already got the bonus for liking the page!” for users that have already got the bonus points by adding another if statement like this “if (!empty($likes[‘data’] && $custom_user_field == 1 ))”.

 

Feel free to discuss any issues that you may face in the comments section below!

Continue Reading
significant-doc-signingSignicat Authentication and Document Signing in Ruby on Rails

Signicat Authentication and Document Signing in Ruby on Rails

Signicat is an e-id authentication service provider that operates in Europe and extends that functionality further by providing users the ability to electronically sign and store documents. They provide authentications for several others e-id’s as well, the complete list can be seen here.

They have plentiful resources and documents on how to integrate their service into your website however I found it really difficult to make the ends meet with the help of those documents, as most of them are good as individual problem solvers but don’t help much in the bigger picture.

I will give several references and links to their documentation here but the problems I faced in finding the links and connecting the dots will be ironed out in this document.

Furthermore their code is in C# and/or Java which is translated to ruby.

When everything fits together it works great and looks easy, but putting it together is the hard part. So buckle up.

 

Starting Off

We will be authenticating a user through Signicat. This exercise will also help in listing down what is needed and in knowing how to get a user for this testing and how these processes work.

 

Creating a Test User

We can create a fully working application but to know if its truly working we will need some test users for credentials authentication. For this document I will use Nem-id’s. The information stored in the response received from Signicat depends on which e-id is used for authentication.

The link mentioned below explains in detail how to get the users in working order:

https://support.signicat.com/display/SUP/NemID,+creating+test+users

However just skip the first step, and instead of filling the form in second step, use ‘Autofill’ button.

Once the user is good to go, we need to authenticate him through the service (this was the point of creating him in the first place to test our application with his credentials).

‘https://env.signicat.com/std/method/service?id=method:profile:language&target=target

Quick brief on what is what in this url. The blue part is all generic and the colored ‘RED’ part is explained in different paragraph for each ‘RED’ placeholders.

Env: is just telling signicat what environment you are currently running. Test is for development and test phase for production it is replaced with ‘id’

Service: name of your service, for testing ‘Shared’ is used once you get the service name for which you have paid for it should be replaced with the service name, as it is configured separately for each service and might need to be adjusted. Code that worked on shared doesn’t necessarily will work on production (trust me it happened and after emailing with Signicat the service was adjusted to our needs, PHEW!!!).

Method: it specifies which e-id provider credentials the user will provide, for the scope of this article I will use ‘NEMID’.

Profile: is the name of the graphical profile, you would like to use. If you don’t have a graphical profile, you can omit the value and the default profile will be used. I in my case used default, that doesn’t interfere in any way and is a good place holder for future in case one does use a profile.

Language: the language that the interface will be shown in. Its better to use a language one is comfortable with and once everything is finalized then change the language as required.

Target: It’s the URL on which the response from Sigincat would be received. This method would be an encoded URI.

More can be read on this here.

 

What to do With the Response Received

What received is SAML 1.1 response (if authentication is successful), and it will be received on the target url described above, so it will have a proper route defined. In my case I have a controller whose action receives the response. Now how that response is handled is a different story, because it does need to be translated into a readable format because SAML can’t be used directly.

I used Omniauth-SAML gem for this purpose, all was good and hay, the response was being translated but the problem occurred when the SAML was being validated. All the gems I came across were build for SAML 2, and Omniauth-SAML will throw an error in validating the translated response, so I had to hack the gem or should I say remove the ‘validate’ part (wink, wink).

My hack involved overriding the ‘callback_phase’ function in the GEM and commenting out the validate part, I am commenting it out here and not entirely removing it because it was later included with change in validation policy, I won’t go into that because it is out of scope of this article, and right now we should be focusing on running the application so we can concentrate on how the data will be used in our application I did was to store the information in the Database.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
require 'omniauth/strategies/saml'
module OmniAuth
module Strategies
class SAML
def callback_phase
unless request.params['SAMLResponse']
raise OmniAuth::Strategies::SAML::ValidationError.new("SAML response missing")
end
response = Onelogin::Saml::Response.new(request.params['SAMLResponse'], options)
response.settings = Onelogin::Saml::Settings.new(options)
node = REXML::XPath.first(response.document,
"/Response[@ResponseID='#{response.document.
signed_element_id}']/Assertion/AttributeStatement/Subject/NameIdentifier[@Format='#{
options[:name_identifier_format]}']")
@name_id = node.text#response.nem_id
@attributes = attributes_patch(response)
if @name_id.nil? || @name_id.empty?
raise OmniAuth::Strategies::SAML::ValidationError.new("SAML response missing 'name_id'")
end
# response.validate!
super
rescue OmniAuth::Strategies::SAML::ValidationError
fail!(:invalid_ticket, $!)
rescue Onelogin::Saml::ValidationError
fail!(:invalid_ticket, $!)
end
end
end
end

We just required the file that we will be overriding the functions in, and just commented out the response.validate! line.

Instead of hitting the url directly I used ‘Omniauth’ gem because it is well integrated with

‘OmniauthSAML’.

1
2
3
4
5
6
7
8
Rails.application.config.middleware.use OmniAuth::Builder do
provider :saml,
:issuer => issuer_name,
:idp_sso_target_url => target_url,
:idp_cert_fingerprint => idp_cert_fingerprint,
:name_identifier_format => name_identifier_format
end
require 'saml_patch'

This code goes in config/initializers/omniauth.rb. The code is explained below.

Issuer: takes the registered name of your service, it is an Omniauth required field as some of the authentication services require the issuer name to be present, in Signicat’s case they don’t have any such compulsion, so the value can be anything, just to surpass Omniauth field requirement validation.

Idp_sso_target_url: the Signicat’s structured url will be placed here.

Idp_cert_fingerprint: The SHA1 fingerprint of the certificate. This is provided from the identity provider when setting up the relationship.

Name_identifier_format: This will tell omniauth what kind of packaging method would be used. Again this is required by omniauth because Signicat sends the  package depending on methods specified in the url. So in NEM-ID’s case the value is “urn:kantega:ksi:3.0:nameid-format:fnr”.

And in the end we have required the patch we created to override ‘callback_phase’ method.

Now when we want to hit the target we will assign this code to any variable and it will hold the response from Signicat.

1
2
foo = request.env["omniauth.auth"].extra.raw_info
bar = foo.to_hash

The response will be be available in a hash in ‘bar’ variable and valid (for now) for use.

Now as the framework is more or less created we will move onto signing the document.

For signing we need to make SOAP calls to Signicat’s document service url.

The url to which the call’s are being made for this purpose is:

https://test.signicat.com/ws/documentservice-v2?wsdl

It is recommended that you visit their site or contact their support to know which service is being lately used, and adjust your SOAP call accordingly.

Now to make the SOAP call I used a nifty little gem called SAVON. The methods created is given below followed by explanation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def send_signature_request(user, task_id, completion_callback_url)
document_id = id
ref_sds_id = upload_file
client = Savon.client(wsdl: 'https://test.signicat.com/ws/documentservice-v2?wsdl', raise_errors: false)
response = client.call(:create_request,
message: {
service: 'shared',
password: 'password',
request: {
profile: 'default',
language: 'en',
task: [{
:@id => task_id,
:@bundle => false,
subject: {
:@id => user.id,
"national-id" => user.cpr,
},
:attributes! => {"document-action" => {type: "sign",
"order-index" => 1, "send-result-to-archive" => false, optional: false}},
"document-action" => {
:attributes! => {
document: {
id: document_id, "ref-sds-id" => ref_sds_id,
"send-to-archive" => false,
'xsi:type'=> 'tns:sds-document'
}
},
document: {
description: 'description of file goes here'
}
},
signature: {
method: ["nemid-sign"]
},
"on-task-complete" => completion_callback_url
}],
}
})
response.success? && response.body[:create_request_response]
end

So the way it is structured is that we created a function which takes a user (which is called subject in Signicat’s terminology), task_id, every task requires a unique id, by which its status can be requested and identified on our end. I am sending this to our function you can create it inside the function as well, its a choice of personal preference or requirement of the scenario.

Completion_callback_url, this is the url which will accept the response from Signicat on completion of task, similarly there are can be 2 more url’s one for postponing the task and other for on task cancel. However here we will just cater the completion of task for the sake of simplicity and more or less it will act in the same way to this.

This url is made by appending the controller’s action route defined to the base url of your application.

Since I had created this function inside my model which stored the files(pdf’s) for signing, so the id

is being assigned to document_id is readily available as model’s attribute. Since there are more than one way of providing the file to Signicat which can be read about here.

I went with sds-document which is session data storage provided by Signicat. And in my function called another model function created called upload_file

1
2
3
4
5
6
7
8
9
10
11
def upload_file
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
file = File.open("file_path/file.name", 'rb')
request = Net::HTTP::Post.new(url.path, {"Content-Type" => file.content_type,
"Content-Disposition" => "form-data; name=\"datafile\"; filename=\"file.name\"\r\n"} )
request.basic_auth('shared', 'password')
response = http.request(request, file.read)
response.body
end

In this call we are just uploading the datafile to the shared session data storage provided by Signicat. And it sends back the ref_sds_id.

Now that file is uploaded and we have everything in order lets break the code in chunks and explain each chunk. So savon client call won’t be explained as plentiful of documentation is available, and what I found boggling in in implementation was the actual message that we send to the wsdl call which we post to :create_request.

In ‘message’ before we can define any kind of activity, we need to provide our credentials.

1
2
3
message: {
service: 'shared',
password: 'password',

With these credentials if we are authenticated, then we move further to the request part which holds all of the settings and the task.

request: { profile: ‘default’, language: ‘en’,

Here we tell the service which profile to use(if created), in my case I just used their default profile, and the preferred language in which the prompts will be displayed to the user. Then comes the most important part which is the defining the task in which the actual signing will take place.

1
2
3
task: [{
:@id => task_id,
:@bundle => false,

As mentioned previously @id is given the value of task_id, it is provided for checking the status and keeping track of the request made.

@bundle => false, as I am using the latest wsdl service of Signicat this functionality is not fully implemented at the moment and its removal causes the call to fail and nothing can be found about it in their currently available document, so setting its value to false will work.

Now we tell Signicat who would be signing the document. This is done by creating a subject block in the task.

1
2
3
4
subject: {
:@id => user.id,
"national-id" => user.cpr,
},

@id values will be used to identify the subject with. As I am using NEM_ID I used user CPR, if the person who is signing the document doesn’t match this CPR Signicat will not accept his sign. Exactly what you need to send to define the subject depends upon the method used for signing. Since I authenticated my user with Nemid I am also signing my document with the same method.

1
2
3
4
5
6
7
8
9
10
:attributes! => {"document-action" => {type: "sign",
"order-index" => 1, "send-result-to-archive" => false, optional: false}},
"document-action" => {
:attributes! => {
document: {
id: document_id, "ref-sds-id" => ref_sds_id,
"send-to-archive" => false,
'xsi:type'=> 'tns:sds-document'
}
},

Now we define what is to be done in the task on the document by creating the above block called the document-action.

Attributes in  SOAP call in RAILS is defined in the form shown below, and you will see that the code above is adhering to the format.

1
2
3
4
:attributes! => {foo: {all attributes of foo}}
foo:{
fields of foo
}

So we tell in our code that the type of document-action is sign and that we do not want to send the resulting document to be send to archive and order-index tells when to execute the particular action in case there are more than one action is defined. Since we are just signing a single document we only have one task and hence the value 1.

After the attributes we create the document block on which the action defined in document-action attributes will be performed.

Here we again have the document attributes in which the document unique identifier is present. Since we want to use the SDS provided we tell the document type to be sds-document, and ref_sds_id which we sat in the beginning of the function after uploading the file. And again I didn’t want to store the original file in the archive so it is set to value.

In the document there is only one field that I have used and that is document description.

1
2
3
4
document: {
description: 'description of file goes here'
}
},

and the part of document-action is completed. Now we create a block to tell about the kind of signature we will be using.

signature: { method: [“nemid-sign”] },

This is it, in signature we mentioned the method we would be using and that is nemid-sign. For complete list check the complete list of signature methods.

Now before we close the TASK block we will provide the url’s for each status of task i.e completion, postpone and cancellation. In our case its just the task completion.

1
2
3
"on-task-complete" => completion_callback_url
}],
}

I am putting all the closing brackets for the sake of closing the message block.

response.success? && response.body[:create_request_response]

now we check if we get a successful response if yes then we return the response.body[:create_request_reponse]

We store this in a variable let’s call it sign_request_response.

So the result will look something like this

1
2
sign_request_response = data_file.send_signature_request(current_user, task_id,
completion_callback_url)

Datafile here is the object of the model we created all the functions for.

Now we check sign_request_response exists and create the actual url where user will be signing the document.

1
2
3
4
5
if sign_request_response
sign_request_response[:request_id]}&task_id=#{task_id}"
redirect_to doc_signing_url
end

Both the codes(model function and the creation of doc_signing_url) are put together in a function called sign_document

def sign_document data_file = DataFile.find(params[:data_file_id]) base_url = ‘Applications base url’ completion_callback_url = “#{base_url}#{route to controller#index }?request_id=${requestId}” task_id = “#{current_user.id}-#{data_file.id}” response = data_file.send_signature_request(current_user, task_id, completion_callback_url) if sign_request_response doc_signing_url = “https://test.signicat.com/std/docaction/contracto.dk?request_id=#{ sign_request_response[:request_id]}&task_id=#{task_id}” redirect_to doc_signing_url end end

In this code the current_user is an application method that returns the session user.

the document is signed and by default you will receive DSIGXML.

What is done with this is entirely upto the application requirement. However I have used Signicat’s packaging method which creates a Signed PDF document.

Continue Reading
why-you-should-learn-to-code-infographicWhy You Should Learn to Code [Infographic]

Why You Should Learn to Code [Infographic]

You may have heard about coding over the years, but what is it exactly and why is it all the rage in recent years? Well, simply put, coding is a phase within the process of computer programming. It allows us to tell a computer what to do. When I say computer, I do not just mean the laptop you have lying around, I mean every bit of sophisticated technology you use, from tablets to PCs, smartphones to PDAs. With our modern world being dominated by so many electronic devices, the least we can do is learn how to code in order to effectively make something for these devices. Here are four solid reasons why you should learn to code this year:

 

You Will be in Great Demand!

Since 90% of our world’s multi-million business transactions and telecommunications take place via sophisticated devices, people who can code are needed for a wide variety of reasons, ranging from security, to developing programs, to creating servers or even small but significant stuff like designing web layouts.

As per reports, the number of software development jobs is set to grow twice as fast as any other type of job within this decade. If you need any proof for that indication, fortune 500 companies such as Twitter, Facebook, Microsoft and Google are scrounging around and looking for the best coders on the planet to safely secure them for the upcoming years. Talk about high demand!

 

You Will Learn it Faster Than Anything Ever Before!

Learning how to code a particular language is actually faster and less time consuming (and also conveniently less of a headache) than trying to learn any spoken language. It doesn’t matter whether you choose JavaScript, HTML, C++, Python, Ruby, PHP or any of the other hundreds. Each and every one is guaranteed to be learnt quicker than an actual spoken language.

An example of this is the SF developer Bootcamp, which teaches one of the hardest coding languages around, Ruby in less than 10 months! Sure, for that kind of crash course, they are asking a whopping $12,000 + for it, but what most people don’t see is that 17 out of 21 people who complete the camp receive jobs with salaries that pay over $79,000!

For comparison, average Master’s Degree requiring jobs pay about $70,000 even after all of the years put into attaining that degree.

 

It’s More Than Women Friendly!

As per 2012 stats, there is about 1 female coder out of every 10 coders. While this may seem off putting to many women, it was not always like this! In fact, in the 1980s, 1 out of every 3 coder was a woman. What does this mean? Simply put, coding is women friendly. It is not labor intensive and women can more than ace it.

In fact, let it be known that most of the computer programming pioneers were none other than female coders. In 1842, Ada Lovelace designed the very first algorithm that was to be processed by a machine, effectively making her the world’s first computer programmer.

In 1946, a team of 6 women programmed the world’s first electronic computer. Even in 1952, Grace Hopper’s language compiler had earned her the nickname of the Mother of COBOL. How is that for a little girl power?

 

Just About Anyone Can Learn it!

From young kids to middle aged adults, just about everyone can learn how to code. Every year, more and more schools are integrating computer studies into their curriculum for children as young as 12. Aside from that, people can even learn it for free right at their home using online tutorials.

There will be a day when coding becomes a basic principle of education just like grammar and arithmetic. If billionaires like Michael Bloomberg are ready to start learning to get ahead of the curve, then what’s stopping you? Get out there and learn how to code today!

 

Here is a brief and beautiful infographic that sums up things for a better visual perspective:

why you should learn to code infographic

Infographic Courtesy: OnlineCollege.org

Continue Reading
  • 1
  • 2