Menol

A stored procedure that can auto-genarate SQL queries using exec method

06-10-2011

Have you ever wanted to write a flexible and dynamic stored procedure that would allow you to send the table name as a parameter?

Have you ever wanted to write a flexible and dynamic stored procedure that would allow you to send only the condition but also the column name you want to include in the where clause?

Well I did. I wanted to create a stored procedure that would take Table name, Criteria column name  and the Target criteria value as parameters and create the SQL query dynamically.

Usually, we have to write our SQL code in the stored procedure body where we cannot treat our sql statement as a string.

The way to achieve this, however, is by using the Exec method provided in SQL.

Exec (execute) allows you to execute a command or a character string that contains Transact-SQL command(s).

Without wasting more time, following is the code I used to achieve my goal:

CREATE PROCEDURE GetRowCountByStringColumn

@TableName nvarchar(50),
@CriteriaColumnName nvarchar(50),
@CriteriaValue nvarchar(150)
AS
BEGIN

EXEC('SELECT  Count(*) FROM ' + @TableName
+ ' WHERE ' + @CriteriaColumnName + ' = ''' + @CriteriaValue + '''')

END
GO

As you can see the procedure takes three arguments:

TableName
CriteriaColumnName – the name of the column that should be checked in the where clause
CriteriaValue – the value the Criteria Column Name should be checked against

The exec command creates the SQL command (at run time) and executes it.

This helped me to create many dynamic stored procedures for my current project and saved me from having to create stored procedures for each table.

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek


The Structure-Conduct-Performance Model

2010-04-01

In 1930s, a group of economists developed an approach to understand relationship among a firm’s environment, behaviour and performance. This theoretical framework, since then, is known as the Structure-Conduct-Performance (S-C-P) Model.

Structure-Conduct-Performance model

 

 

 

 

 

 

 

 

 

 

 

Structure, in this model refers to the structure of the industry in which the firm is operating. According to their findings, following factors could be used by a firm to measure the industry structure it’s operating in.

  • Number of Competing Firms
  • Homogeneity of Products
  • Cost of Entry and Exit

Conduct refers to the set of strategies that the firm implement to gain competitive advantage over its rivals.

Performance in the s-c-p model has two meanings:

  1. Performance of the individual firm
  2. Performance of the economy as a whole

The Link Among Structure, Conduct and Performance

Attributes of the industry structure define the range of options and constraints a firm has to face. In highly competitive industries, firms have a very limited motion space as they are only let with a very few options too many constraints when compared to options. In such setting, both firm’s conduct and long term performance are determined by the industry structure making (in general) firms only able to gain competitive (not competitive advantage).

On the other hand, in less competitive industries, firms have the liberty of large ranges of conduct options and fewer constraints, enabling capable firms to gain competitive advantages. However, even at this type of setting, the industry structure can impact on firms critically such as deciding how long a firm can maintain its competitive advantage.

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek


A Simple JavaScript To Get English Language Definition From A Dictionary

2009-05-19

English is not my first language so I use online dictionaries frequently as a part of my daily routine to clarify and learn unfamiliar words as I read through articles in the Internet.

I have been using www.ditionary.com for a long time and I had the plan to make this work easy by creating a small application to retrieve the definition with support of a web service. This morning suddenly a new idea hit me to use JavaScript to get the word in the first place and load the appropriate URL.

How Does This Work?

When a user enters a word in the www.dictionary.com interface it redirects the user to the following dynamic URL.

http://dictionary.reference.com/browse/Target-Word

Target-Word is The word we are seeking the definition for

What this JavaScript does is it retrieves the desired word from the user via a prompt, generate the appropriate URL according to the above format and open the new URL in a new window or tab so the time taken (under normal circumstance) to, load the web site, type-in the word, wait till the site redirects you, is saved. Now time is only taken for a single server request/response.

How To Set This Up?

It’s simple, just add a new favorite (for IE) or bookmark (for FireFox) in your browser and paste following code as the URL (for IE) or Location (for FireFox):

javascript:(function(){var%20word=prompt(%22Enter Word:%22);if(word!=null){window.open(%22http://dictionary.reference.com/browse/%22+word);}})();

Add bookmark dialog box in firefox

Add bookmark dialog box in firefox

 

 

 

 

 

 

 

Now, when you open the favorite/bookmark, it will ask you for the word you want to look for and open the definition in a new window/tab.

 

Sample use of the script

Sample use of the script

 

 

 

 

It’s easier to use if you add the bookmark/favorite as a button into your bookmark/links toolbar

Bookmark button

Bookmark button


This small script helps me a lot daily so I hope this would help you too!

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek



D LINQ : How to Map Columns Which Auto Generate Values At the Database

2009-05-11


I have being working on a software application made on .Net and recently my client asked me to use D LINQ instead of SQL.

D LINQ has great benefits loaded! As I started working with DLINQ I started to know that preventing SQL injection is not a headache anymore and misspelled SQL queries will not trouble agian at run time because DLINQ generates all necessary SQL inside the framework!

I chose to use annotations inside the class instead of using separate xml file. Following is a part of the first class I ported to D LINQ.

</p>
_
Public Class Process
_
Public ProcessID As Integer
_
Public BusinessProcessID As String
_
Public ProcessText As String
...
...

ProcessID column is the primary key of my database table tbl_Process.

Important Point: I use database to auto-generate values for the primary key column (integer value incremented by one).

So when I run the application, It gave me this unexpected error:

Cannot insert explicit value for identity column in table ‘tbl_Process’ when IDENTITY_INSERT is set to OFF.

Basically, the IDENTITY_INSERT when using the database to auto generate value for a field but when I ran a SQL insert statement at the database end it worked fine!

After some tough time I found out the solution for this problem!

When we use an auto-generate field in a data table we have to specifically mention it in the matching field in the appropriate class.

The code to state this is:

Syntax:

IsDbGenerated:=True

This has to be added to the annotation added for the specific column like:

</p>
_
Public ProcessID As Integer

Now D LINQ can understand that the field value is auto-generated by the database!

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek


Six Advices to Succeed in Online Paid Surveys

2009-03-14

I have been working with many survey sites in the Internet and I have learnt a lot of lessons. I learnt some of these when I was researching about online survey sites and most of these lessons are learnt by experience. So I thought to share my knowledge with the rest of the world hoping it would help someone out there.

So in this article, I will give a set of advices that I have learnt in the hard way…

Rule 1 – Don’t Select Survey Sites From Lists Rated By Other People

Many people in the Internet are involved in affiliate marketing. Many surveying sites pay bloggers when they refer a new person to their site. So don’t believe in those lists such as “Top 10 Most Paid Survey Sites”, “Top 5 Survey Companies”, etc. because the TOP site of those lists is the site that pays the blogger most! So my advice is not to believe in those ranked lists.

Rule 2 – Ask the site this question: ” What Do I Get For Responding To Surveys? “

The answer depends on the site you are going to work with. Some sites pay money and some sites pay by other means such as coupon codes and sweepstakes entries while some sites are charity sites where you get non-paid public service surveys.

Rule 3 – Work Only For Cash

As I mentioned there are many sites which pays you in indirect methods such as coupon codes. My advice is never work on surveys unless they pay you by money because there is no way to measure the value of your work. They will give you a coupon code or sweepstakes entry at the end of your days work and you still have to go around the corner to get your own earnings. Since most of the times these are given as discounts, you have to spend more money and buy something to apply those discounts. In simple words, you only feel you earn but you never get your earnings into your hands.

The worst problem is some coupon codes may not be useful for you at the moment and some discounts may not be available in your region. You have to take this very seriously if you are not living in the same country or region as the origin of the site where it is operational.

Rule 4 – Check Available Payment Methods

Your computer may simply get surveys through the site without any problems or delays but it doesn’t mean your payment gets to your bank account in the same speed. Go and check the payment options supported by the site. Some sites support various payment methods while some sites only have one or two methods.

For most payment methods there are limitations across countries. This isn’t a problem if you are located in the same country where the site is operational but if you are living in a different region or a country you have to be more concerned about this matter.
For an example, you may be able to create a Paypal account from your country but you may not be able to accept payments to that account because Paypal doesn’t support that service in your country. In such situations if your site does not have suitable options you may lose your money.

Rule 5 – Don’t Go After Fortunes

There’s no such thing as easy money! Remember this as you go on finding for survey sites because you will face sites that say they would pay bulks of money for each survey. My advice according to what I have learnt so far is don’t go for those sites because the more money they promise, the more chances for that site to be a scam. Unfortunately, many people around the world get into these scams everyday. The best thing is to find a site that pays a reasonable and especially practical price for your work.

Rule 6 – Work Hard! There’s No Boss To Push You Forward!

If you are working in a company then you have a boss looking at you to make sure you meet company expectations and to kick you off if you lose performance. In this case, you are your own boss. The good news is there’s no one to kick you off and you own everything you earn. The bad news is you have to take care of everything. Especially you have to keep your motivation up. It’s not easy to do something of your own without postponing. You must dedicate yourself to the work at least till you reach a solid level of ground to stand on.

In this new office you don’t have office times. You have your freedom and at the same time you have all responsibilities on your shoulders. In simple words, It’s your baby go ahead and grow it!

Don’t look for fortunes, Work hard and make your own fortune!

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek


The Blood Brain Barrier

2009-01-08


I wouldn’t be wrong if I say the Brain is the most vital organ in the human body. As we all know brain handles most of critical operations inside our body such as keeping and managing memories, organizing our activities, keep other organs perform, and so much more.

The Brain, as most of us already know, works by sending electric signals through complex meshes of neurons so the brain has to maintain a good environment around to keep the accuracy of this electrical signal flow.

The environment inside the brain is the brain fluid so the ingredients or components of the brain fluids are very critical to the functionalities of brain.

Any organ of the body gets the supplies it needs through blood and so does the brain. Ingredients of human blood vary depending on the situation, food, problems of other organs, etc. so it is obvious that the blood is not the same all the time.

Not like other organs, the brain has to think a lot before extracting anything from blood because if the chemical levels of brain fluid vary it directly affects the signals passed through neurons. If the brain fluid is not maintained in an optimum level, the environment will become too noisy for neurons and sending signals would become like talking in the middle of a party.

So there is this Blood-Brain Barrier (which is also referred to as BBB) which extracts the necessary ingredients such as Oxygen and Glucose and make sure nothing else is taken in.

Blood-Brain Barrier Diagram

blood-brain-barrier

Photo courtesy: Malcolm Segal


Where is Blood-Brain Barrier Located?

BBB is located at the brain blood capillaries. These capillaries are unusual in several aspects from capillaries in other organs. Those aspects are briefly described below:

  • The end-points of cells which make up the walls of these capillaries are sealed together at their edges by tight junctions which are a key component in the barrier. These junctions make sure that water soluble substances in the blood don’t pass between the edges of cells.
  • These capillaries are enclosed by flattened cells which altogether called the ‘end-feet’ which also work as a (partial and active) barrier.
  • The only way for water soluble substances in the blood is through the walls of capillaries. These walls plays the other role in the barrier because their cell membranes are made up of a lipid/protein belayed only allowing flat-soluble molecules including those of oxygen and carbon dioxide, anesthetics and alcohol to pass through the walls of capillaries.
  • In the capillary wall there are three classes of ‘efflux pumps’ which pumps various lipid-soluble molecules back in to the blood out of the brain.

However, the brain needs water soluble compounds such as Glucose for energy production and amino acids for protein synthesis so there are these Carriers in the walls of capillaries which allow those compounds to go through the wall and move waste products and unwanted molecules in the opposite direction.

The blood-brain barrier plays another key role in keeping the volume of the brain at a constant level. Since the brain is contained inside a rigid skull it is important to keep the fluid from free movement thus keeping volume of the brain static.

Problems Related to BBB

Even though BBB is made in the sole purpose of protecting the brain, it has become a barrier to medicine to access the brain. Since many medicines are water soluble, they are barricaded at the BBB. This process has made it very hard to treat brain tumors and infections such as AIDS virus.

In fact, AIDS virus uses BBB as a shield by hiding behind the BBB from body defense mechanisms.

Due to such reasons medicine has to be made as fat-soluble but then a new problem arises because then the medicine will be absorbed by most cells of the body which may be toxic.

The alternatives are making drug molecules that can ride on natural transporter proteins or use drugs that can open the Blood-Brain-Barrier.

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek


What is a Permalink

2009-01-07

If you maintain or work around blogs then the word “Permalink” should be familiar to you.

In early stages of the Internet all web addresses or URLs were static or permanent but as the web became more complex where large volumes of content is added daily, it became hard to handle in the usual way.

The involvement of database driven systems was necessary to manage large volumes of web content.

The URLs used with these systems were not human readable and each URL is only brings a main or central page and loads the requested page from their.

Ex/ Non-Permanent (Old) link for the Wikipedia page for Albert Einstein

http://en.wikipedia.org/w/index.php?title=Albert_Einstein

As you can see, these dynamic URLs do not provide a permanent link to the relevant page. The part “Albert_Einstein” is only a parameter sent to the internal CGI of Wikipedia.

A Permalink is a permanent link for each item in the web site or domain. With this concept each page of a domain gets a unique permanent URL.

Ex/ Permalink for the Wikipedia page for Albert Einstein

http://en.wikipedia.org/wiki/Albert_Einstein

Why Permalinks are Helpful for Bloggers…?

In blogs, post goes down the stack as new posts arrive. So when permalink is enabled, each of your post gets an individual URL so that anyone on the Internet can link to your post from their site or blog without depending on what happens at your blog.

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek

Recommended Books:


C# ASP.NET – GridView : How to Use Checkbox in Gridview to Select Multiple Rows

2009-01-06

I wanted to select multiple rows of the grid view using check boxes to select each row.

In this post I will discus how and what I did to achieve this goal…

I used a template column which holds a check box to select or de-select a row in the grid view.

Adding a Template Column:

There are several simple ways to add a template column/field to your grid view:

  1. Select your grid view and then click on the small task button (the small square button located to the top right corner of the grid view control) and select “Add New Column…” from the “GridView Tasks” box.
    1. Use “TemplateField” as the field type
    2. Provide a header text
    3. click ok
  2. Or… Select “Edit Columns…” from the “GridView Tasks” box and
    1. Select “TemplateField” from the “Available fields: ” section
    2. Click “Add” button
    3. Provide a header text in the “TemplateField properties: ” section
    4. click ok
  3. Or… Select “Columns” from the grid view properties and follow the steps described in the earlier method (2nd one)

Adding a Checkbox to the Template Column:

  1. Select “Edit Templates” from the “GridView Tasks” box. Then it will show you the inside of the template.
  2. Select “Item Template” from the “Display: ” drop down list.
  3. Drag and drop a check box in the item template area.
  4. Give an id as “chkid” for the check box – You can use a different name if you want but make sure you don’t confuse when I use this name in later parts of this article.
  5. Click “End Template Editing” from the “GridView Tasks” box.

If you have completed the above steps correctly, you should see the expected checkbox column added in to the grid view.

Design View
As you can see in the image above, in my example I use a Name column along with the check box column to make this clearer.

How to Databind the Template Field:

I use a datatable to populate the gridview so we have to databind our two columns.

The second column name is a “BoundField” so to databind it simply specify the name of the data table column you want to bind to this column in “DataField” property under “Data” property set in the fields dialog box you get when adding the second column (use one of the ways I described above to add a column).

Databinding the template field is a bit tricky, but not hard.

  1. Click “Edit Templates” from the “GridView Tasks” box so that you will see the check box.
  2. Click on the small button with a triangle in the upper right corner of the check box which is similar to the one we clicked on the grid view to get the “Checkbox Tasks” box and then click on the “Edit Databindings…” link inside that box.

You can use this dialog box to bind any property of the control to a data source column

In this example we will bind the “Checked” property of our check box to a Boolean column called “Selected” of the data source.

For that:

  • Select “Checked” from the Bindable Properties section and enter following in the Custom Binding section:
    • DataBinder.Eval(Container, “DataItem.Selected“)
  • Note: the word “Selected” (in red color) refers to the “Selected” field of the data source.

Populating the GridView:

As I described earlier I create a simple data table in the page load, populate it with some dummy data and then bind the grid view with it.

Note: I have used several methods to add data to a table to illustrate those to you.

The Code:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Selected", System.Type.GetType("System.Boolean")));
dt.Columns.Add(new DataColumn("Name", System.Type.GetType("System.String")));

DataRow dr = dt.NewRow();
dr.ItemArray = new object[] { false, "Cassian" };
dt.Rows.Add(dr);
dt.Rows.Add(new object[] { false, "Menol" });
dt.Rows.Add(new object[] { false, "Razeek" });

this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
}

There are several things that I’d like to bring to your notice:

  • I have checked for postback to make sure this data population is not occurred in general post backs. The reason is the framework refreshes when the grid view is re-bound.
  • So if we don’t do this check, whenever we click on a check box, a postback occurs, the grid gets refreshed, the check boxes get cleared, we cannot keep track of what check boxes are selected…!
  • As illustrate in my code, you can either first populate a datarow and then add it to the datatable
  • Or you can directly add the items using only one line of code.

Retrieving the Status of Checkboxes:

Now we have completed the interface and the user now can select several rows of the grid view using the appropriate check box.

The next step is to capture the rows that the user has selected.

In my example, I have used a button, once clicked; it will display the list of names of the selected people.

I will introduce the code first and then explain it to you.

protected void Button1_Click(object sender, EventArgs e)
{
ArrayList names = new ArrayList();
foreach (GridViewRow gvr in this.GridView1.Rows)
{
if (((CheckBox)gvr.FindControl("chkid")).Checked == true)
{
names.Add(gvr.Cells[1].Text);
}
}

this.Label1.Text = string.Empty;
foreach (object itm in names)
{
this.Label1.Text += " " + itm.ToString();
}
}

Note following:

  • The code iterates through each row of the grid view using a for each loop, takes the Name field from the selected rows and then adds those names into a arraylist
  • The GridViewRow refers to a single row in a grid view
  • Control Control.FindControl(string controlID) – GridViewRow class provides this method to find a specific control within a grid view row. This method becomes very handy in situations like this where we cannot directly access the control from the code because those are generated at run time
  • FindControl returns a control so you have to explicitly cast the returned control to the type of it

Screen Shot:

21

Conclusion:

We can use a template field with a checkbox to allow user to select multiple rows using checkboxes associated to each row. When the button is clicked, checkbox of each row is checked for its status and the row is selected if the user has chosen it.


Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek


How Fibonacci Sequence Relates to Nature

2009-01-05

Italian mathematician Leonardo Pisano had a problem worked on to find a mathematical pattern to answer the question: how many pairs of rabbits can be produced from a single pair of rabbits in one year?

He carried out his work on following assumptions:

  1. Rabbits are kept under optimal conditions
  2. Female rabbits always give birth to pairs
  3. Each pair consists of one male and one female

If we start with a pair of new born rabbits and monitor the population monthly…

Rabbits cannot reproduce until they are at least one month old. So in the first month there will only be one pair and at the end of the second month the pair is able to reproduce so the female rabbit will give birth to a new pair.

In month three the original pair gives birth to yet another pair while their first pair of baby rabbits grows to the adulthood.

In the beginning of month four there are two pairs of adult rabbits and one pair growing so both of these adult pairs give birth to two new pairs. So the total number of pairs in the end of the fourth month:

Adult pairs : 2
Growing pairs : 3
Total : 5

Like wise the pattern goes on as follows:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, … on to the infinity. Each number is the sum of the previous two.

Leonardo Pisano found this interesting pattern on 1202. How come the pattern is named Fibonacci Sequence?

Leonardo Pisano was also knows as Fibonacci, meaning “son of Bonacci” giving this name to his finding.

Are rabbits the only species having relevance to Fibonacci Sequence?

Many natural entities such as Fruits, Vegetables and Seed Heads show spiral patterns which follows Fibonacci Sequence.

Some examples:

If you look at the array of seeds in a center of a sunflower you should notice that those seeds are arranged in spiral patterns curving left and right. And the amazing thing is if you count the number of these spirals you will get a Fibonacci number. The most amazing thing is if you divide the spirals pointed to left and right and count those separately you will get two consecutive Fibonacci numbers!

If you look at a pineapple you can notice that its scales make a spiral pattern and if you look closer and count those scales in each spiral you will notice that those numbers reflect Fibonacci Sequence.

Same thing can be noticed in pinecones, cauliflower and many more natural things we live with.

This sequence has an amazing link with the nature and that’s may be why the ratio between two of these numbers is called The Golden Ratio.

The Golden Ratio:

Two numbers are considered as in The Golden Ratio if the ratio between the sum of two numbers and the larger one is equal to the ratio between the larger one and the smaller.

In mathematics the golden ratio is often denoted by the Greek letter ϕ (phi).

The value of the golden ratio: ϕ = 1.6180339887…

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek


My Goals for the New Year 2009!

2009-01-01

It’s a New Year…!

I want to be much more improved in both my personal and professional lives when I look back at the end of this New Year!

So I decided to make a list of goals I want to achieve in this year. And I will make sure that I achieve my goals as I go on living this New Year.

Goals for My Professional Life:

I have a set of goals which will improve the quality of my professional life and will increase the value of me in the profession. If I directly go to the list…

  1. Obtain MCTS Certification
  2. Obtain SCJP Certification
  3. Be More Competent on My Work at My Office
  4. Make My Clients Happy
  5. Find More Freelance Work
  6. Create Several Methods to Earn Some Money Online

Goals for My Personal Life:

  1. Keep My Family Happy
  2. Focus More on Health of My and My Girl Friend’s Parents
  3. Cut Extra Fat I Have Gained and Get the Body I Used to Have
  4. Learn to Play Guitar – ANYHOW!!!
  5. Go to Swim

My Financial Goals:

  1. Open a Fixed Deposit Before the End of June

Other Goals:

  1. Obtain Work Permit
  2. Give Clothes Regularly to Children of a Poor Family

These are the Goals I have in my mind at the moment and I will update the list as I go on…!

Yes, I know, I will have to work so hard if I want to have all of these achieved at the end of this year. I will definitely make this dream come true with the great help from my parents, my girl friend and all my friends around me and always the best helper, The God!

I wish the whole world, a Happy and Successful New Year!

Cassian Menol Razeek


  • Visitors Since Oct, 2008
  • Protected By Copyscape Duplicate Content Checker
    Do Not Copy Without Referencing To This Site
  • Copyright © 1996-2010 I Learnt Today.... All rights reserved.
    iDream theme by Templates Next | Powered by WordPress