Sunday, February 25, 2018

Beacon triangulation

Becon triangulation was done as a part of my BSc final year research project. It was used to get indoor navigation within a shoppingmall application. You can read full reseacrh paper here in IEEE library. I will explain how did we do it in a simple explanation as below. If you have any questions related to beacon triangulation please comment below. I will try to answer as soon as possible.

Beacon is a Bluetooth transmitting device and Beacon triangulation method was used to find indoor navigation. For this beacons should be located according to triangular manner. We wrote an algorithm to identify whether a particular user is inside the beacon area or outside for the nearest beacon triangle. Check this article to get idea of how it is coded. Heron’s formula was used to get the area of a triangle. Then the RSSI(Received Signale Strength Indicator) values were retrieved to the mobile screen from the three beacons of the triangle. According to RSSI values that were retrieved the exact square ID of the user was identified by getting coordinates from the 2D map of the shopping mall. Once the position of the user/shopper was found, identifying the angle and the direction of the phone was initiated. Using phone’s inbuilt sensors the vertical and horizontal angle were captured. Since shop details should be tagged to the camera panel, the user is notified to keep the camera panel vertical. If the user changes it from vertical angle to any other angle notifications will be popped up automatically. Direction of the phone is captured using geographical positioning system and the compass of the phone. To connect with beacons, Bluetooth should be enabled in the user’s phone.
This is the graphical view of beacon triangulation.


Monday, August 18, 2014

Beacon triangulation with android

To identify the location of a user according to beacon triangulation i used following methods in my android
project.Hope this will be helpful you to do your projects with beacons.







Saturday, September 28, 2013

Backups and Restore MySQL data

the main purpose of having backup function is whenever our database crashes,prevent from system failure..by keeping backups we can restore them at necessary time.here is the backup function which returns Boolean value.it checks for current date and time for purpose of naming the backup folder.then we can easily find which is the latest backup according to date and time.

         Here i have given path to mysqldump in  MySQL server which installed in my local disk C.if it is changing machine to machine we can configure it using app.config file.I have given that code segment also.you can implement this method to create backups and you should call this method in necessary events by passing MySQL credentials like username ,password, host name, database name.

      public static bool Backup(string user, string password, string host, string database, string path)
        {
            try
            {
                DateTime backupTime = DateTime.Now;
                int year = backupTime.Year;
                int month = backupTime.Month;
                int day = backupTime.Day;
                int hour = backupTime.Hour;
                int minute = backupTime.Minute;
                int second = backupTime.Second;
                int ms = backupTime.Millisecond;

                String tmestr;
                tmestr = path + "-" + year + "-" + month + "-" +                  day + "-" + hour + "-" + minute + ".sql";

                StreamWriter file = new StreamWriter(tmestr);

                ProcessStartInfo proc = new ProcessStartInfo();

                proc.FileName = @"C:\Program Files\MySQL\MySQL                   Server 5.1\bin\mysqldump";

                string cmd = string.Format(@"-u{0} -p{1} -h{2}                   {3} ", user, password, host, database, tmestr                     /*"backup.sql"*/);

                proc.Arguments = cmd;
                proc.RedirectStandardInput = false;
                proc.RedirectStandardOutput = true;
                proc.UseShellExecute = false;
                proc.CreateNoWindow = true;

                Process p = Process.Start(proc);
                string res;

                res = p.StandardOutput.ReadToEnd();
                    file.WriteLine(res);
                    p.WaitForExit();
                    file.Close();
                    return true;
             
            }
            catch (IOException ex)
            {
                return false;
            }
        }


How to configure path using app.config is like below.inside app.config we should give all the credentials needed to make backup.and then we can access it inside our .cs class.

<connectionStrings>
      <add name="cecb_host" connectionString="localhost"  
        providerName="MySql.Data.MySqlClient" />
  <add name="cecb_password" connectionString="123"/>
  <add name="cecb_user" connectionString="root"/>
  <add name="cecb_database" connectionString="cecb"/>
  <add name="cecb_path" connectionString="C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysqldump"/>
</connectionStrings>

accessing app.config connectionstrings through .cs class

string connectionString_host = ConfigurationManager.ConnectionStrings["cecb_host"].ConnectionString;
   
This is the restore method of database backups.here i have given the option of selecting backup file from local disk and open it.when it is opened it automatically execute through the MySQL server like manually script running.so it is very important and easy method to restoring backups.here what we do inside the implementation is run the script through MySQL server which is installed in local disk.that's why we are giving the path for MySQL.exe. here also we can configure path through app.config file for purpose of changing the path.

        public static void restore(string user, string password, string host, string database, string path)
        {
         try{
            StreamReader file = new StreamReader(path);
            ProcessStartInfo proc = new ProcessStartInfo();
            string cmdArgs = string.Format(@"-u{0} -p{1} -h{2} {3}", user, password, host, database);
            proc.FileName = "C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysql.exe";
            proc.RedirectStandardInput = true;
            proc.RedirectStandardOutput = false;
            proc.Arguments = cmdArgs;
            proc.UseShellExecute = false;
            proc.CreateNoWindow = true;
            Process p = Process.Start(proc);
            string res = file.ReadToEnd();
            file.Close();
            p.StandardInput.WriteLine(res);
            p.Close();
            }
            catch(Exception e)
           {
               MessageBox.Show("Restoring process failed !", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
          }
        }

       }










Mailing through c#

what we normally have to send a mail is create account and send mails through that account.but here i explains how to create interface to send mails using smtp server along with the attachments.it is clearly checking for network connection and empty streams of the fields in interface.therefore we can easily find which is the error by looking at message box.

this is the main implementation method which we can use.here i have passed 5 parameters as receiver mail address,message body,subject, attachment 1 and attachment 2.This is the purpose of i want only 2 attachments.If you want more than 2 attachments you can pass another parameter.
here in locations which i mentioned as "your mail address" and "your password", you should enter your mail account details.since this is using smtp server.it should be gmail account.
if the credentials have been successfully submitted message will sent successfully.



 public void mail(string receiver,string msg,string subject,string attachment1,string attachment2)
        {
            try
            {

                System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage(<your mail address>, receiver, subject, msg + " < CECB Experiments Results Updates >");

                MyMailMessage.IsBodyHtml = false;

                System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential(<give your  mail address>,<give your mail password>);

                System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);

                string file = attachment1;
                string file2 = attachment2;
                Attachment attach = new Attachment(file);
                Attachment attach2 = new Attachment(file2);

                // Add the file attachment to this e-mail message.


                MyMailMessage.Attachments.Add(attach);
                MyMailMessage.Attachments.Add(attach2);

                mailClient.EnableSsl = true;
                mailClient.UseDefaultCredentials = false;
                mailClient.Credentials = mailAuthentication;
                mailClient.Send(MyMailMessage);
                MessageBox.Show("Mail sent success!");

            }


            catch (Exception ee)
            {
                MessageBox.Show("Receiver's Mail , Attachment can't be Empty..Please Check", "Invalid or Empty", MessageBoxButtons.OK, MessageBoxIcon.Error);
           
            }



Then in necessary places we can call the method by passing parameters.









Excel sheets read and write using c#

When we have to work with excel sheets frequently using c# language, rather than implementing methods inside the main project we can create API with implementing those methods.then we can reuse it at later stages.here i have explained how to create API and how to access it.



Here we can add references by right clicking on references which is on solution explorer.then add needed references which displays below in top of the .cs class.
and then i have clearly implemented functions separately how to load excel sheets, read excel sheets and write to excel sheets.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
using QiHe.CodeLib;
using ExcelLibrary.CompoundDocumentFormat;
using ExcelLibrary.BinaryFileFormat;
using ExcelLibrary.SpreadSheet;
using Excel = Microsoft.Office.Interop.Excel;

namespace CECB_API
{

    public class xml_refer
    {
    

        public void LoadExcelSheets(CompoundDocument file, TabControl tab)
        {


            byte[] bookdata = file.GetStreamData("Workbook");
            if (bookdata == null) return;
            Workbook book = WorkbookDecoder.Decode(new                      MemoryStream(bookdata));

            tab.TabPages.Clear();

            foreach (Worksheet sheet in book.Worksheets)
            {
                TabPage sheetPage = new TabPage(sheet.Name);
                DataGridView dgvCells = new DataGridView();
                dgvCells.Dock = DockStyle.Fill;
                dgvCells.RowCount = sheet.Cells.LastRowIndex + 1;
                dgvCells.ColumnCount = sheet.Cells.LastColIndex +                  1;

                // tranverse cells
                foreach (Pair<Pair<int, int>, Cell> cell in sheet.Cells)
                {
                    dgvCells[cell.Left.Right, cell.Left.Left].Value = cell.Right.Value;
                    if (cell.Right.Style.BackColor != Color.White)
                    {
                        dgvCells[cell.Left.Right, cell.Left.Left].Style.BackColor = cell.Right.Style.BackColor;
                    }
                }

                // tranvers rows by Index
                for (int rowIndex = sheet.Cells.FirstRowIndex; rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
                {
                    Row row = sheet.Cells.GetRow(rowIndex);
                    for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
                    {
                        Cell cell = row.GetCell(colIndex);
                    }
                }
                // tranvers rows directly
                foreach (KeyValuePair<int, Row> row in sheet.Cells.Rows)
                {
                    foreach (KeyValuePair<int, Cell> cell in row.Value)
                    {
                    }
                }


                foreach (KeyValuePair<Pair<int, int>, Picture> cell in sheet.Pictures)
                {
                    int rowIndex = cell.Key.Left;
                    int colIndex = cell.Key.Right;
                    if (dgvCells.RowCount < rowIndex + 1)
                    {
                        dgvCells.RowCount = rowIndex + 1;
                    }
                    if (dgvCells.ColumnCount < colIndex + 1)
                    {
                        dgvCells.ColumnCount = colIndex + 1;
                    }
                    dgvCells[colIndex, rowIndex].Value = String.Format("<Image,{0}>", cell.Value.Image.FileExtension);
                }

                sheetPage.Controls.Add(dgvCells);
                tab.TabPages.Add(sheetPage);
            }
        }


      /// <summary>
      /// mypath parameter should give full path from the location of a file
      /// var datatype has used for future need.it is implicit type
      /// 1.open excel sheet using given path
      /// </summary>
      /// <param name="myPath"></param>
      /// <param name="stage"></param>
      /// <returns></returns>

        
        public string[] readarray(string myPath, string stage)
        {
            FileInfo fi = new FileInfo(myPath);

            var excelApp = new Microsoft.Office.Interop.Excel.Application();
            var workbook = excelApp.Workbooks.Open(myPath);
            Excel.Worksheet worksheet = workbook.Sheets.get_Item(1);

            int count = worksheet.UsedRange.Rows.Count;

          
            string col = "";
            if (stage == "1")
            {
                col = "A";
            }
            else if (stage == "2")
            {
                col = "B";
            }

            else if (stage == "3")
            {
                col = "C";
            }
            else if (stage == "4")
            {
                col = "D";
            }
            else if (stage == "5")
            {
                col = "E";
            }
            else if (stage == "6")
            {
                col = "F";
            }

           
            else
            {
                MessageBox.Show("Give valid stage..");
            }

            string[] statge1 = new string[count];
            string toDisplay = "";


            for (int x = 1; x < count; x++)
            {

                statge1[x] = Convert.ToString((worksheet.Cells[x.ToString(), col]).Value2);
                toDisplay = string.Join(",", statge1);

            }

          
            return statge1;
        }
        

        public void openandwrite(string row, string col, string value)

        {
            Excel.Application excelApp = new Excel.Application();
            Excel.Workbook workbook = (Excel.Workbook)excelApp.Workbooks.Add(Missing.Value);
            Excel.Worksheet worksheet;

            worksheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);

            ((Excel.Range)worksheet.Cells[row, col]).Value2 = value;

            excelApp.Visible = true;
        }


        public void openexistingexcel(string myPath)
        {
           // this must be full path.
            FileInfo fi = new FileInfo(myPath);
            if (!fi.Exists)
            {
                MessageBox.Show("file doesn't exists!");
            }
            else
            {
                var excelApp = new Microsoft.Office.Interop.Excel.Application();
                var workbook = excelApp.Workbooks.Open(myPath);


                Excel.Worksheet worksheet;

                worksheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
                excelApp.Visible = true;
            }
        }

        public void WriteToExcel(string row, string col, string val,string myPath)

        {
            // this must be full path.

            FileInfo fi = new FileInfo(myPath);
            if (!fi.Exists)
            {
                MessageBox.Show("file doesn't exists!");
            }
            else
            {
                var excelApp = new Microsoft.Office.Interop.Excel.Application();
                var workbook = excelApp.Workbooks.Open(myPath);


                Excel.Worksheet worksheet;

                worksheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
               

                    ((Excel.Range)worksheet.Cells[row, col]).Value2 = val;

                    excelApp.Visible = true;
           

                workbook.Save();
               workbook.Close();



            }
        }


    }
    
}

After developing API we can run it and add it as dll to our main project.then we have to do is create object from API and calling the methods.following is another example for method calling.

 CECB_API.xml_refer a = new CECB_API.xml_refer();


Since it is time consuming function i created thread here.

 public void Function()
        {
            val = cmbCertificateNo.SelectedValue.ToString();

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += TimeConsumingFunction;
            //// var frame = new DispatcherFrame();
            worker.RunWorkerCompleted += (sender, args) =>
            {
                //    // frame.Continue = false;
            };
            worker.RunWorkerAsync();
            //// Dispatcher.PushFrame(frame);
        }

This is the actual implementaion where i read my excel data using object created from API

        private void TimeConsumingFunction(object sender, DoWorkEventArgs doWorkEventArgs)
        {

            try
            {
                  MessageBox.Show(cmbCertificateNo.SelectedItem.ToString());
                string aw = val;
                string[] stage1 = a.readarray(Chosen_File, "2");


                string[] stage2 = a.readarray(Chosen_File, "3");
                string[] stage3 = a.readarray(Chosen_File, "4");
                string[] stage4 = a.readarray(Chosen_File, "5");
                string[] stage5 = a.readarray(Chosen_File, "6");
                string[] date = a.readarray(Chosen_File, "1");

                bool status = false;

                int length = 136;
                for (int x = 1; x < length; x++)
                {

                    string qry = "INSERT INTO `realdata` (`projectID`,`datentime`,  `sgage1`,  `sgage2`,  `sgage3`,  `sgage4`,  `force_`) VALUES ('"+aw+"','" + date[x].ToString() + "','" + stage1[x].ToString() + "','" + stage2[x].ToString() + "','" + stage3[x].ToString() + "','" + stage4[x].ToString() + "','" + stage5[x].ToString() + "')";
                    status=MVCAController.db_access.InsertData(qry);
                }
                if (status)
                {
                    killexcelprocess();
                    do
                    {
                        Thread.Sleep(10);
                    }
                    while (progressBar2.Value == 100);
                }

                else
                {
                    timer1.Stop();

                    killexcelprocess();
                    MessageBox.Show("Insert Fail !", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
               
                }
            }
            catch (Exception ex)
            {
                timer1.Stop();
                killexcelprocess();
                MessageBox.Show("First select a File path to store "+ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
}


When we work with excel it starts background running.so we should kill excel processes all times.this code will end all excel processes at necessary locations

  public void killexcelprocess()
        {
             foreach (Process clsProcess in Process.GetProcesses())
                if (clsProcess.ProcessName.Equals("EXCEL"))  //Process Excel?
                    clsProcess.Kill();

           
        }



This is how it displays when excel data have been opened.



Tuesday, September 24, 2013

Generating a Student ID with crystal reports and MySQL database

crystal reports are not much hard as you think.when we got into it,it is really no big deal.here i am going to explain how we can generate class ID using crystal reports.I learnt about crystal reports deeply because of my 3rd year SEP project in my campus(SLIIT).Now i have considerable knowledge of crystal reports as i did it many times with customizing.So if you want to know crystal reports,what you should do is create every possible ways by customizing reports.

1.First we should create a table or view according to data fields we need to generate the report.Following shows a view which i used to create a A/L class ID for my client.




2.Then we should add a data set to access actual database values through the crystal report.here in visual c# items we can find a field as data and there we have data set item.it is xsd file.just give a name.but it is good to give a name which explains the data set.

3.then we get a window like below.here i added my view to the window by drag and drop.first you need to expand "Server Explorer" from "View" menu in visual studio.then it will show all available connections with database server.i selected "SIMS_" as my database which i have my data for the report.there i selected view named "idstudentview" and drag it to window and dropped.


4.Then i created a new windows form and i should add crystal report viewer to it.you can find crystal report viewer from tool box under "Reporting" section.drag and drop it to the windows form.


5.After adding crystal report viewer this is what you can see.left side column we can use to add another tools if we need.right side column is where you are going to generate the report.


6.Here i added few combo boxes,radio buttons,labels and buttons according to my purpose.I want to create IDs for A/L students by selecting A/L year and the stream.and also i want to create single ID by giving student ID.so that i created those group boxes. 


7.Then we should add crystal report by clicking arrow which is shown in step 5 image right side.if not we can add manually using tool box.

8.After clicking "create a new crystal report" following window will appear.we should give a name here.


9.Then it will show a window like below.there we can select fields from field explorer.by right clicking in design view we can customize report in many ways.

here this image shows how can we change "stdimage" blob value field.Like this other fields also can change



10.also in field explorer by right clicking on "database fields" we can have following database expert window and also we can data sets at this point also.


11 This is what i designed in my crystal report design view.


12. We can change displaying methods also.here when we select format with multiple columns we can have columns with same kind of data fields .but different values


13.In generate report button click event we should write the code to connect database and the report together through data set.

This method will return MySQL data adapter object and we can use it to create report
         public static MySqlDataAdapter Getadapter(string qry)
        {
            try
            {
                comm.CommandText = qry;
                MySqlDataAdapter dr = new MySqlDataAdapter(comm);

                return dr;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                // comm.Cancel();
            }
                  
    } 

//Then we can add following code to button click event.i wrote the method for "Bulk IDs" generate part.

          string query = "select * from idstudentvw where stdalyear='"+cmbAlYear.Text+"' and                                          stdstream='"+CmbStramreport.Text+"' "; //query which returns data fields for report

           MySqlDataAdapter  adapter = access.GetAdapter(query);

            backgrounddata ds = new backgrounddata(); //this is data set
            dra.Fill(re.Tables[0]);
            backgroundreport cry = new backgroundreport(); //this is crystal report
            cry.SetDataSource(re);
            crystalReportViewer1.ReportSource = cry; //this is crystal report viewer
            crystalReportViewer1.Refresh();

Then this is what we get after generate report.this is individual report generating.

This is bulk id generating report.




So ,that's all we should do to create crystal report.we can have different kind of reports.i just upload another few reports which i created for my projects.

a) 1st page 


2)2nd page


3)3rd page