Showing posts with label Developer. Show all posts
Showing posts with label Developer. Show all posts

May 5, 2017

Inserting & Retrieving Images from SQL Server Database without using Stored Procedures

Inserting & Retrieving Images from SQL Server Database without using Stored Procedures


Objective:

To insert into & retrieve images from SQL server database without using stored procedures and also to perform insert, search, update and delete operations & navigation of records.

Introduction:

As we want to insert images into the database, first we have to create a table in the database, we can use the data type 'image' or 'binary' for storing the image.

Query for creating table in our application:

create table student(sno int primary key,sname varchar(50),course varchar(50),fee money,photo image) 

Design:



Design the form as above with 
1 PictureBox control, 
1 OpenFileDialog control, 
4 Labels, 
4 TextBoxes
11 Buttons.

PictureBox1 Properties:

BorderStyle=Fixed3D; SizeMode=StrechImage

Introduction to code:

In order to communicate with SQL sever database, include the namespace

'using System.Data.SqlClient'.

In this application, we will search a record by taking input from the InputBox. For this we have to add reference to Microsoft.VisualBasic.

Adding a Reference to 'Microsoft.VisualBasic':

Goto Project Menu ->Add Reference -> select 'Microsoft.VisualBasic' from .NET tab.

In order to use this reference we have to include the namespace:

'using Microsoft.VisualBasic' in the code.

Converting image into binary data: 

We can't store an image directly into the database. For this we have two solutions:

To store the location of the image in the database

Converting the image into binary data and insert that binary data into database and convert that back to image while retrieving the records.

If we store the location of an image in the database, and suppose if that image is deleted or moved from that location, we will face problems while retrieving the records. So it is better to convert image into binary data and insert that binary data into database and convert that back to image while retrieving records.

We can convert an image into binary data using
FileStream
MemoryStream

1. FileStream uses file location to convert an image into binary data which we may/may not provide while updating a record.

Example:

      FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open,                       FileAccess.Read);
      byte[] photo_aray = new byte[fs.Length];
      fs.Read(photo_aray, 0, photo_aray.Length);

2. So it is better to use MemoryStream which uses image in the PictureBox to convert an image into binary data.

Example:
             MemoryStream ms = new MemoryStream();
             pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
             byte[] photo_aray = new byte[ms.Length];
             ms.Position = 0;
             ms.Read(photo_aray, 0, photo_aray.Length);
In order to use FileStream or MemoryStream we have to include the namespace:
'using System.IO'.

OpenFileDialog Control:

We use OpenFileDialog control in order to browse for the images (photos) to insert into the record.

Loading the constraint details into the dataTable:

In this app. we use Find() method to search a record, which requires details of primarykey column, which can be provided using the statement:

adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

Pointing to current record in dataTable:

After searching a record, we have to get the index of that record so that we can navigate the next and previous records.

Example:

rno= ds.Tables[0].Rows.IndexOf(drow);
-------------

Code:

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.VisualBasic;

namespace inserting_imgs
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        SqlConnection con;
        SqlCommand cmd;
        SqlDataAdapter adapter;
        DataSet ds; int rno = 0;
        MemoryStream ms;
        byte[] photo_aray;

        private void Form1_Load(object sender, EventArgs e)
        {
            con = new SqlConnection("user id=sa;password=123;database=prash");
            loaddata();
            showdata();
        }
        void loaddata()
        {
            adapter = new SqlDataAdapter("select sno,sname,course,fee,photo from student", con);
            adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
            ds = new DataSet(); adapter.Fill(ds, "student");
        }
        void showdata()
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                textBox1.Text = ds.Tables[0].Rows[rno][0].ToString();
                textBox2.Text = ds.Tables[0].Rows[rno][1].ToString();
                textBox3.Text = ds.Tables[0].Rows[rno][2].ToString();
                textBox4.Text = ds.Tables[0].Rows[rno][3].ToString();
                pictureBox1.Image = null;
                if (ds.Tables[0].Rows[rno][4] != System.DBNull.Value)
                {
                    photo_aray = (byte[])ds.Tables[0].Rows[rno][4];
                    MemoryStream ms = new MemoryStream(photo_aray);
                    pictureBox1.Image = Image.FromStream(ms);
                }
            }
            else
                MessageBox.Show("No Records");
        }
        private void browse_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*";
            DialogResult res = openFileDialog1.ShowDialog();
            if (res == DialogResult.OK)
            {
                pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
            } 
        }
        private void newbtn_Click(object sender, EventArgs e)
        {
            cmd = new SqlCommand("select max(sno)+10 from student", con);
            con.Open();
            textBox1.Text = cmd.ExecuteScalar().ToString();
            con.Close();
            textBox2.Text = textBox3.Text = textBox4.Text = "";
            pictureBox1.Image = null;
        }
        private void insert_Click(object sender, EventArgs e)
        {
            cmd = new SqlCommand("insert into student(sno,sname,course,fee,photo) values(" + textBox1.Text + ",'" +
textBox2.TabIndex + "','" + textBox3.Text + "'," + textBox4.Text + ",@photo)", con);
            conv_photo();
            con.Open();
            int n = cmd.ExecuteNonQuery();
            con.Close();
            if (n > 0)
            {
                MessageBox.Show("record inserted");
                loaddata();
            }
            else
                MessageBox.Show("insertion failed");
        }
        void conv_photo()
        {
            //converting photo to binary data
            if (pictureBox1.Image != null)
            {
                //using FileStream:(will not work while updating, if image is not changed)
                //FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                //byte[] photo_aray = new byte[fs.Length];
                //fs.Read(photo_aray, 0, photo_aray.Length);  

                //using MemoryStream:
                ms = new MemoryStream();
                pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
                byte[] photo_aray = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(photo_aray, 0, photo_aray.Length);
                cmd.Parameters.AddWithValue("@photo", photo_aray);
            }
        }

        private void search_Click(object sender, EventArgs e)
        {
            try
            {
                int n = Convert.ToInt32(Interaction.InputBox("Enter sno:", "Search", "20", 100, 100));
                DataRow drow;
                drow = ds.Tables[0].Rows.Find(n);
                if (drow != null)
                {
                    rno = ds.Tables[0].Rows.IndexOf(drow);
                    textBox1.Text = drow[0].ToString();
                    textBox2.Text = drow[1].ToString();
                    textBox3.Text = drow[2].ToString();
                    textBox4.Text = drow[3].ToString();
                    pictureBox1.Image = null;
                    if (drow[4] != System.DBNull.Value)
                    {
                        photo_aray = (byte[])drow[4];
                        MemoryStream ms = new MemoryStream(photo_aray);
                        pictureBox1.Image = Image.FromStream(ms);
                    }
                }
                else
                    MessageBox.Show("Record Not Found");
            }
            catch
            {
                MessageBox.Show("Invalid Input");
            }
        }
        private void update_Click(object sender, EventArgs e)
        {
            cmd = new SqlCommand("update student set sname='" + textBox2.Text + "', course='" + textBox3.Text + "', fee='" + textBox4.Text + "', photo=@photo where sno=" + textBox1.Text, con);
            conv_photo();
            con.Open();
            int n = cmd.ExecuteNonQuery();
            con.Close();
            if (n > 0)
            {
                MessageBox.Show("Record Updated");
                loaddata();
            }
            else
                MessageBox.Show("Updation Failed");
        }

        private void delete_Click(object sender, EventArgs e)
        {
            cmd = new SqlCommand("delete from student where sno=" + textBox1.Text, con);
            con.Open();
            int n = cmd.ExecuteNonQuery();
            con.Close();
            if (n > 0)
            {
                MessageBox.Show("Record Deleted");
                loaddata();
                rno = 0;
                showdata();
            }
            else
                MessageBox.Show("Deletion Failed");
        }
        private void first_Click(object sender, EventArgs e)
        {
            rno = 0; showdata();
            MessageBox.Show("First record"); 
        }

        private void previous_Click(object sender, EventArgs e)
        {

            if (rno > 0)
            {
                rno--; showdata();
            }
            else
                MessageBox.Show("First record");
        }
        private void next_Click(object sender, EventArgs e)
        {
            if (rno < ds.Tables[0].Rows.Count - 1)
            {
                rno++; showdata();
            }
            else
                MessageBox.Show("Last record");
        }
        private void last_Click(object sender, EventArgs e)
        {
            rno = ds.Tables[0].Rows.Count - 1;
            showdata(); MessageBox.Show("Last record");
        }
        private void exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
     }
}

April 21, 2017

Bootstrap Tricks And Tips

Bootstrap is full of incredible features but can seem too complex for many of us. You simply cannot remember all the functions or cannot take one week off to study its documentation. Many times even experienced users get surprised when they discover some of its hidden gems.

I have carefully chosen some of the best tips and tricks that I have used in my Bootstrap coding career so far and I would like to share them with you.

For a better reading experience, I divided them into 4 groups.

If you would have suggestions for some more tricks, share them with me in comments.




Bootstrap Components

navbar, footer

How to open a navbar dropdown on hover

A standard behaviour of Bootstrap dropdowns is that they open on click. It has its pros and cons and I usually keep it as default. If you would like to open dropdowns on hover, it is not a complicated process to achieve it.

We will need to change two things and we will apply our changes only if the viewport's wider than 768px (i.e. navbar is not collapsed).

First, add this CSS rule to your stylesheet after loading the Bootstrap's CSS. It is quite straightforward - if the viewport's wider than 768px and you hover above a .dropdown link, a .dropdown-menu opens.

Second, if the parent link should point to an URL too, we will need  to add a bit of JS code to change the .dropdown links' onclick behaviour. 

How to change navbar height

When you want to change the navbar height, you will need to adjust more things than simply adding a new height value for .navbar. 

In the following code, I outline an approach how to change your navbar's height to 80px. 

How to create sticky footer

Create a sticky footer for your website following these steps:

1. Create a footer element and set its position to absolute with bottom offset 0. 2. Set a fixed height for it. (In my example, it will be 80px).
3. Add bottom padding to your element, set it to the same value as the footer's height.

Bootstrap Grid

How to make columns same height

This is a classical problem. You have content boxes with different content but you want them to have the same height. A solution to this problem will be a smart usage of flexbox on the Bootstrap rows.

This approach consists of these steps:

1. Create a .row-flex and apply it to your content boxes' parent row.
2. Columns in the .row-flex row will have same height now.
3. Usually do not mix Bootstrap with my components and I have all the           backgrounds, padding, etc. of the content boxes declared in its child element -    .content. To make everything work, all you need to do is just to set a height: 100% to the .content boxes.

How to add vertical spacing to columns

To add some vertical spacing to your columns easily, use the following simple CSS rule that gives bottom margin of 30px to every Bootstrap column. 

How to use your own classes instead of columns and rows

Many people simply do not like the Bootstrap way of writing the code with columns and rows such as:

To achieve it, you will need to use Bootstrap {LESS} .make-row() and .make-*-column() mixins.

How to change ordering of columns on mobile

A quite useful feature of the Bootstrap grid is an ability to order columns differently on mobile devices and differently on desktops. 

All you need to do is to use .col-(breakpoint)-push-(number) and .col-(breakpoint)-pull-(number) classes to push or pull the columns on the specified breakpoint out of its original place.

I know it sounds a bit complicated and usually, it takes me some time to visualise the outcome but let's have a look at it in an example. In the following code, the first column will appear as a first item on mobiles but as a second item on tablets and desktops.

In the following code, the first column will appear as a first item on mobiles but as a second item on tablets and desktops.

How to show or hide elements on mobile

If you need to quickly and easily hide an element only on xs devices, there is a .hidden-xs class that you can use. 

Similarly, you can use a .hidden-(breakpoint) class for the rest of the breakpoints too and combine them together, i.e. use classes .hidden-lg, .hidden-md, .hidden-sm.

On the other hand, if you want to show an element only on certain devices, you can use .visible-(breakpoint)-(display) classes. Note a slight difference there - you have to use a display property there too. Possible values for the (display) part of the class name are block, inline-block and inline. So, if you need to display an element as a block on large devices, just add a .visible-lg-block class to it.

How to disable responsiveness

There can be situations when you would prefer your page to behave as a non-responsive. These could be when preparing your web page for print or generating output for PDF.

Basic steps to disable responsiveness:

Omit a
Set a fix width for your .container. E.g., .container {width: 1000px !important;}

April 13, 2017

Set Static Port SQL Server 2012

How to assign a static port to a SQL Server named instance

While Books Online clearly mentions the steps to Configure a Server to Listen on a Specific TCP Port we still see people missing out on one small but important detail in these steps: they forget to delete the entry (0 or some random port) for dynamic port. This firstly results in confusion and occasionally can result in connectivity problems as well. Let me explain how using an example from one of our lab setups.

As a first step, let’s see what the ‘administrator’ (in this case, yours truly Smile) had done:


As you can see, they have added the static port for ‘IPAll’ with a value of 1450. That part is fine. The problem though is they forgot to remove the entries for the dynamic ports (0 or some random port). That means that when they restarted SQL, the dynamic port setting is still valid. In fact if we query sys.tcp_endpoints, you will still see the engine thinks it is listening on dynamic port:

SELECT        name, protocol_desc, type_desc, state_desc, is_admin_endpoint, port,        is_dynamic_port, ip_address 
FROM            sys.tcp_endpoints

The important observation is that the engine reports that it is still using a dynamic port. It does not report the static port number 1450 which we selected in Configuration Manager. Let’s double-check in the errorlog to see if indeed the static port is being picked up at all. And lo and behold:

Server is listening on [ ‘any’ 1450]. 
Server is listening on [ ‘any’ 1450]. 
Server is listening on [ ‘any’ 49626]. 
Server is listening on [ ‘any’ 49626].

In our case, sqlservr.exe has a PID of 1240. Using the command netstat –ano, we can see what it is listening on.

  Proto  Local Address       Foreign Address                State                  PID 
  TCP      0.0.0.0:1450                0.0.0.0:0                           LISTENING             1240 
  TCP      0.0.0.0:49626             0.0.0.0:0                           LISTENING             1240 
  TCP      127.0.0.1:49627          0.0.0.0:0                           LISTENING             1240 
  TCP      192.168.1.101:1450    192.168.1.200:49386      ESTABLISHED       1240 
  TCP      192.168.1.101:1450    192.168.1.200:49396      ESTABLISHED       1240 
  TCP      [::]:1450                      [::]:0                                   LISTENING             1240 
  TCP      [::]:49626                   [::]:0                                   LISTENING             1240 
  TCP      [::1]:49627                  [::]:0                                   LISTENING            1240

So it is not only listening on the static port, but also on the dynamic port 49626. The DAC is listening on TCP port 49627. The values with a local address of [::] are the IPv6 ‘All’ address.

So depending on what got cached earlier in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\SNI11.0\LastConnect on the client (you can find some detail about the LastConnect registry key and the caching mechanism in this KB article), the client might attempt to connect to the previous dynamic port (which is still valid based on our observation above.)

FYI, if we run NetMon, we can see that the SSRP response from the SQL Browser correctly gives back 1450 as the port for this named instance:


For clarity I’ve reproduced the response from SQL Browser (using the SSRP protocol) back to my client (SQLCMD.exe):

.^.ServerName;SOMESERVER;InstanceName;SOMEINSTANCE;IsClustered;No;Version;11.0.2100.60;tcp;1450;;

From the above it is clear that SQL Browser is correctly sending the static port assignment. But if you are like me, I feel uneasy till I fix the root cause, which is to delete the dynamic port assignment!

To summarize here is what we saw in this walkthrough:

The official steps (captured in Books Online) to assign a static port for a named instance involve also deleting the value (0 or some random port) for the dynamic port.
Failure to delete the dynamic port value in SQL Configuration Manager will cause SQL to listen on both the static as well as the dynamic ports.
This means that clients will succeed to connect to the erstwhile dynamic port if they had that cached in the LastConnect client side registry key.
For clients which do not have cached connection details, SQL Browser seems to pickup the static port and sends that back to the client.
So follow the steps in the BOL article to the T and delete the dynamic port value right after you type in the static port value, and in any case before you restart the instance.
FYI the steps to fix a static port for the Dedicated Admin Connection (DAC) are in the KB article How to configure SQL Server to listen on a specific port under the section ‘Configuring an instance of SQL Server to use a static port’.

Facebook API JSON File

This is an example of a Facebook JSON file which you might see when getting data from the Facebook API. It might also be used to contain profile information which can be easily shared across your system components using the simple JSON format.

Example :
{
   "data": [
      {
         "id": "X999_Y999",
         "from": {
            "name": "Tom Brady", "id": "X12"
         },
         "message": "Looking forward to 2010!",
         "actions": [
            {
               "name": "Comment",
               "link": "http://www.facebook.com/X999/posts/Y999"
            },
            {
               "name": "Like",
               "link": "http://www.facebook.com/X999/posts/Y999"
            }
         ],
         "type": "status",
         "created_time": "2010-08-02T21:27:44+0000",
         "updated_time": "2010-08-02T21:27:44+0000"
      },
      {
         "id": "X998_Y998",
         "from": {
            "name": "Peyton Manning", "id": "X18"
         },
         "message": "Where's my contract?",
         "actions": [
            {
               "name": "Comment",
               "link": "http://www.facebook.com/X998/posts/Y998"
            },
            {
               "name": "Like",
               "link": "http://www.facebook.com/X998/posts/Y998"
            }
         ],
         "type": "status",
         "created_time": "2010-08-02T21:27:44+0000",
         "updated_time": "2010-08-02T21:27:44+0000"
      }
   ]
}