Quantcast
Channel: Visual C# forum
Viewing all 31927 articles
Browse latest View live

What am i doing wrong in this console application using methods

$
0
0

So I am super new to programming and I was trying to write a program from my book.

Here is the assignment:

Write a program that allows this school club ability to determine a few things about their candy bar sales. They can enter things like how many boxes they have, the cost per box, the cost per candy bar etc. Then the program using methods will return some calculations for them such as their gross profit, deduct % due to their student government and give the net profit.

ErrorCS0116A namespace cannot directly contain members such as fields or methodsAssignment3Israel

code:

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Assignment3Israel

{

    classGranolaBarSalesProject

    {

       //Constant variable sga 10% cut per candy bar sold//

       constdecimal sgaDues = .010m;

 

       staticvoid Main(string[] args)

        {

           //Capture total number of candy bars//

           decimal totalAmountCases = GetCases();

           //Capture cost per case of candy bars//

           decimal perCaseCost = GetCaseCost();

           //Capture total cost of goods (cogs)

           decimal cogs = CalctotalAmountCases(perCaseCost);

           //Capture total number of candy bars per case

            int candyBarsPerCase = GetCandyBarsPerCase();

           //Get cost per candy bar

           decimal pricePerCandyBar = GetPricePerCandyBar();

           //Get the total amount of candy bars

           decimal totalAmountCandyBars = CalctotalAmountCases(candyBarsPerCase);

           //Get the amount of candy bars sold

           decimal totalCandyBarsSold = GetTotalCandyBarsSold();

           //Calculate the total amount of bars sold

           decimal totalCandyBarSales = CalctotalCandyBarsSold(pricePerCandyBar);

           //Calculate the Gross Profits

           decimal grossProfit = CalctotalACandyBarSales(cogs);

           //Capture the total amount due to the student government

           decimal totalDuesOwed = CalcgrossProfit(sgaDues);

           decimal netProfit = CalcgrossProfit(totalDuesOwed);

           Console.ReadKey();

        }

 

       publicstaticstring GetCases()

        {

           Console.Write("How many cases of candy bars:");

           returnConsole.ReadLine();

        }

 

       publicstaticstring GetCaseCost()

        {

           Console.Write("How much per case of candy bars:");

           returnConsole.ReadLine();

        }

 

       publicstaticstring GetCandyBarsPerCase()

        {

           Console.Write("how many candy bars per case:");

           returnConsole.ReadLine();

        }

 

       publicstaticstring GetPricePerCandyBar()

        {

           Console.Write("how much per candy bar: ");

           returnConsole.ReadLine();

        }

 

       publicstaticstring GetTotalCandyBarsSold()

        {

           Console.Write("how many candy bars did you sell:");

           returnConsole.ReadLine();

        }

 

       

 

    }

    publicstaticdecimal CalctotalAmountCandyBars(decimal candyBarsPerCase)

    {

       return totalAmountCases * candyBarsPerCase;

       //returns the total number of candy bars

    }

    //Calculating the total nuber of candy bars and returning that calculation

    publicstaticvoid ShowTotalAmountCandyBars(string totlalAmountCandyBarsIn)

    {

       Console.WriteLine("Here are the total number of candy bars {0}: ", totlalAmountCandyBarsIn);

    }

 

 

    publicstaticdecimal CalctotalCandyBarSales(decimal pricePerCandyBar)

    {

       return totalCandyBarsSold * pricePerCandyBar;

       //returns the candy bar sales before the 10% cut to Student gov

    }

    //Calculating candy bar sales and displaying amount

    publicstaticvoid ShowtotalCandyBarsales(string totalCandyBarSalesIn)

    {

       Console.WriteLine("Here is the Candy Bar sales before dues to SG {0:C}: ", totalCandyBarSalesIn);

    }

 

 

    publicstaticdecimal CalcgrossProfit(decimal cogs)

    {

       return totalCandyBarSales - cogs;

       //returns the gross profit

    }

    //Calculating the gross profit and returning that calculation

    publicstaticvoid ShowgrossProfit(string grossProfitIn)

    {

       Console.WriteLine("Here is the Gross Profits of sales {0:C}: ", grossProfitIn);

    }

 

    publicstaticdecimal CalctotalDuesOwed(decimal sgaDues)

    {

       return grossProfit * sgaDues;

       //returns the total amount due to SG

    }

    //Calculating the total amount of dues to SG and display

    publicstaticvoid ShowtotalDuesOwed(string totalDuesOwedIn)

    {

       Console.WriteLine("Here is the total due to the Student Government {0:C}: ", totlalDuesOwedIn);

    }

 

    publicstaticdecimal CalcnetProfit(decimal totalDuesOwed)

    {

       return grossProfit - totalDuesOwed;

       //returns the net profit of candy bar sales

    }

    //Calculating the net profit and displaying it

    publicstaticvoid ShownetProfit(string netProfitIn)

    {

       Console.WriteLine("Here is the Net Profit of your sales {0:C} ", netProfitIn);

 

    }

 

}


Using assignment operator to change field in an instance

$
0
0

I am creating a "group" class that represents an integer (number of assigned group).  Is it possible to change a single field using an assignment operator?  For example, lets say I have some class:

public class SomeClass
{
	int n;
	bool bold;
	Color whatever;
}

I want to be able to change the value of n using the assignment operator (because the class' primary purpose is to represent a group that has customized formatting in a report).  The other data is simply for formatting purposes. I want to be able to assign it like this:

SomeClass instance = SomeClass(/*formatting data used in constructor */);
instance = 5;

Is there a way to overload the assignment operator so that it doesn't create a new instance, it simply replaces the default value of n within the instance?   


Error: CHKDSK cannot continue in read-only mode

$
0
0

Hi All,

I'm getting "Error: CHKDSK cannot continue in read-only mode" message when I run the chkdsk.exe programmatically. But the same will work properly If I run through command prompt.

Code snippet for reference:

            ProcessStartInfo startInfo = new ProcessStartInfo("C:\\Windows\\System32\\chkdsk.exe", "C:");
            startInfo.UseShellExecute = false; 
            startInfo.RedirectStandardOutput = true;
            startInfo.CreateNoWindow = true; 
            Process pTemp = Process.Start(startInfo); 
            string test = pTemp.StandardOutput.ReadToEnd();  
            pTemp.WaitForExit();

Thanks in advance

Nataraj


Limited number of application launched in Session 0 (UI-less) by the Same Logon User

$
0
0

I have a windows service that runs in session 0 (UI-Less). it will be used to launch additional applications in the session 0 using Start() method with the instance of Process, the instance of process will be disposed after successfully launch the application. But it failed to launch additional applications when it has around 110 - 111 running applications in session 0. 

I have tried to use Task Scheduler to launch the application in Session 0 and it happens the same. When i tried to launch the application that are not in session 0, it does not have this kind of limitation.

Is it that a single user able to launch only a limited number of applications in Session 0? Is there a way to increase this limit on the same user?

Use sample XML file to generate c# code with values from XML file too

$
0
0

I have an xsd and generated classes from it. I also have a sample XML file with values. Is there a way I can automatically generate/write a c# method that could instantiate classes and assign the values to recreate the XML with the values again?  Any ideas would be greatly appreciated! 

passing strings between functions

$
0
0

Hello i have the following code that takes a date from a text file and format it.

The file Contains several lines 

1......Date.....

2......

3........

END

4......Date

5.....

END

I want to take the Date from line 1 convert it and then write a file that has the name .. date

next time take the date from line 4 and write a file that has the name of the date in line 4

The problem now that the date is always the same, it is not changed. I am wondering how every time it selects a date it does the operation of converting and then write the file. Thanks in Advance

How can i update the date each time and put it in string name?

 static void DoOperation (string y) {
            string[] month = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

            y = y.Replace(" ", "-").Replace(":", ".");

            //  Console.WriteLine(SomeGlobalVariables.yy);


            for (int m = 0; m <= month.Length - 1; m++)
            {

                if (y.Contains(month[m]))
                {
                    int monthInDigit_int = DateTime.ParseExact(month[m], "MMM", CultureInfo.CurrentCulture).Month;
                    string monthInDigit = monthInDigit_int.ToString();
                    y = y.Replace(month[m], monthInDigit.PadLeft(2, '0'));
                }

            }


            y = y.Remove(10, 1).Insert(10, ".");
            y = SwapCharacters(y, 0, 3);
            y = SwapCharacters(y, 1, 4);



        }

static void ReadDATA(out string[,] Result)
        {
 Match zi = Regex.Match("", "");
           List<string> dates = File
                   .ReadAllLines(fileName)
                   .Where(v => { zi = Regex.Match(v, @"(?<=\|)\d{2}\s+\w{3}\s+\d{4}\s+\d{2}:\d{2}:\d{2}(?=\|)"); return zi.Success; })
                   .Select(v => zi.Value)
                   .ToList()
                   ;
           dates.ForEach(DoOperation); // Converting date
var name = string.Format(@"C:\Users\Desktop\{0}" + "." + "rslt" + "." + y, fields2[1]);
// make a name out of the second field.

 File.WriteAllLines(name, templines.Skip(currentLine).Take(terminatorLine - currentLine).Select( line => string.Join(",", line.Split( ',' ).Select( ( text, index ) => (index == 1) ? fields2[1] : text ))) ); // copy the lines.

Hijacking ftp pipeline

$
0
0

Hi, 

I have a requirement to have my own ftp handlers to fetch content from a custom web server.

I did a similar thing for webdav requests and I made use of Ihttpmodule interface to extend the functionality.

Is there a similar thing for ftp? I checked out the FTP service extensibility features but I didn't really find what I was looking for.

Any help appreciated.

Thanks

XmlDocument KML Placemark Polygon Coodinates

$
0
0

I have a simple kml file where I select a specify node and replace the coordinates in the placemark xPath, However I need to add the polygon to the kml placemark path. So there will be two identical polygons in the same polygon file. Review kml data below. I am trying to figure out how to add the second polygon in the file.

I have both polygon coodinates in memory ready to add to the polygon section, but I havent thought of robust way to add the second polygon to placemark xpath.  This is what I am doing currently with a template file.

 KmlObjectString = geoFileStringBuilder.ToString();

                                var xmlNode = kmlDoc.SelectSingleNode("kml/Document/Placemark/MultiGeometry/Polygon/outerBoundaryIs/LinearRing/coordinates");
                                if (xmlNode != null)
                                {
                                    xmlNode.InnerText = KmlObjectString.ToString();
                                    string[] nameArray = browseFile.SafeFileName.Split('.');
                                    kmlDoc.Save(@"C:\temp\KML\" + nameArray[0]+ ".kml");
                                }

START WITH:

 <Placemark>
      <name>Volume</name>
      <styleUrl>#default0</styleUrl>
      <MultiGeometry>
        <Polygon>
          <!-- top -->
          <tessellate>1</tessellate>
          <altitudeMode>absolute</altitudeMode>
          <outerBoundaryIs>
            <LinearRing>
              <coordinates>-118.805245304129,34.2582332081979,1490
-118.796790853877,34.2497094883196,1490
-118.778939913084,34.2512370401627,1490
-118.778024543953,34.2582326065422,1490
-118.77893786207,34.2652282224139,1490
-118.796792544255,34.2667579688469,1490
-118.805245304129,34.2582332081979,1490
</coordinates>
            </LinearRing>
          </outerBoundaryIs>
        </Polygon>
      </MultiGeometry>
    </Placemark>
  </Document>

EXPECTED OUTPUT BELOW

 <Placemark>
      <name>Volume</name>
      <styleUrl>#default0</styleUrl>
      <MultiGeometry>
        <Polygon>
          <!-- top -->
          <tessellate>1</tessellate>
          <altitudeMode>absolute</altitudeMode>
          <outerBoundaryIs>
            <LinearRing>
              <coordinates>-118.805245304129,34.2582332081979,1490
-118.796790853877,34.2497094883196,1490
-118.778939913084,34.2512370401627,1490
-118.778024543953,34.2582326065422,1490
-118.77893786207,34.2652282224139,1490
-118.796792544255,34.2667579688469,1490
-118.805245304129,34.2582332081979,1490
</coordinates>
            </LinearRing>
          </outerBoundaryIs>
        </Polygon>
                <Polygon>
          <!-- bottom-->
          <tessellate>1</tessellate>
          <altitudeMode>absolute</altitudeMode>
          <outerBoundaryIs>
            <LinearRing>
              <coordinates>-118.805245304129,34.2582332081979,1300
-118.796790853877,34.2497094883196,1300
-118.778939913084,34.2512370401627,1300
-118.778024543953,34.2582326065422,1300
-118.77893786207,34.2652282224139,1300
-118.796792544255,34.2667579688469,1300
-118.805245304129,34.2582332081979,1300
</coordinates>
            </LinearRing>
          </outerBoundaryIs>
        </Polygon>
      </MultiGeometry>
    </Placemark>
  </Document>


pianoboyCoder


Problem to get difference of two dates

$
0
0
Hi,
I get 0 to Age0 by these
                    DateTime zeroTime = new DateTime(1, 1, 1);
                    TimeSpan span = DateTime.Now - DateTime.ParseExact(tb_birth.Text.Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                    Age0 = (zeroTime + span).Year - 1;


while tb_birth.Text is 05/06/1963. Why?

Many Thanks & Best Regards, Hua Min

c# send text to a external program via api.

$
0
0

ok i been looking up how to send text via my program to a external program text box but i cant seem to get it to work at all :( this is the code i have got so far. 

class Api_calls
    {
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("User32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);


        public void sendmgs()
        {
            try
            {
                const int WM_SETTEXT = 0x002056E;

                Process uxt = Process.GetProcessesByName("UltraUXThemePatcher_3.0.4")[0];

                IntPtr uxt_edit = FindWindowEx(uxt.MainWindowHandle, IntPtr.Zero, "Edit", null);

                SendMessage(uxt_edit, WM_SETTEXT, 0, "elfenliedtopfan5!");

                MessageBox.Show(uxt_edit.ToString());
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }


    }

the issue i have is it dont do anything and the message box shows 0. when i push it this is the winspy++ image. 

yet i still cant get it to change the text in the textbox that says not patched 

take note i am only practicing on this program i know it had textbox in the installer so i used this installer just have no idea how to do it at all :( and its driving me crazy any idears ? '

thanks in advance elfenliedtopfan5


How check these records and set a local variable after evaluating all of them

$
0
0

The code below should set the verificationsComplete bool to true only if the status of every record is "Green".  The approach below will ignore previous records, set verificationsComplete  and exit the loop based the last record evaluated.

What is a good way to check all of the records passed in to_verificationRepo,GetByOnsiteIdAndYear and only set verificationsComplete to true when all statuses are "Green"?

  public bool AllVerificationsComplete(int onsiteId, int year)
        {
            bool verificationsComplete = false;

            var verifications = _verificationRepo.GetByOnsiteIdAndYear(onsiteId, year);

            foreach(var verification in verifications)
            {
                if(verification.Status != "Green")
                {
                    verificationsComplete = false;
                    if (verificationsComplete == false)
                    {
                        break;
                    }
                }
                else
                {
                   // Set this a different way to account for all records
                    verificationsComplete = true;                         }
            }
            return verificationsComplete;
        }


connection string issue

$
0
0

Hi dear,

I'm using this connection string. Can u reveal whats going wrong in this? 

<add name="LUCKINDIA" connectionString="Data Source=192.111.150.130:1433\luckindia_db;;  Initial Catalog=luckindia_db; User Id=LUCKINDIA; Password=aVyf698_"
	providerName="System.Data.SqlClient" />

Error is throwing that.

[   A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid) ]

MY environments are:

Plesk panel (hosting domain)

visual studio 2013

asp.net  with c#.

sql server 2014

Thanks in advance.

SOLID and Design Pattern

$
0
0
From your exeprience when you have worked with lots of project, how far have you used SOLID and design pattern?

I have worked C# project from school and sparetime using concept N-tier and MVC but I have not really used design pattern or entirety SOLID in workplace. (http://www.codeproject.com/Articles/703634/SOLID-architecture-principles-using-simple-Csharp).

My Question is:

Is there a context when it is relevant to use SOLID and design pattern in relation to line of business, product development, 3D coding etc.

Thanks!

A question about C# using

$
0
0

Hello,
I copy the necessary files to its path.(mscoree.dll , System.dll and more)
But it run need to setup .NET Framework.
That's important!
How can I do for?
I only want to Programming in C#!

(My application is only 10KB, the full Framework setup is over 40 or 60 MB, and the setup finish will more, It's terrible!)

Thanks!

How come my data is not updated into the gridview by using this code.....

$
0
0

Hi, need help about this one.

I have just starting learn c# by youtube.
I have followed all his command, difference is just the number of the text box and cells number.
Yet, when i am testing, i want to upload my input into grid view, it do nothing!!!

Thank you 

      private void label10_Click(object sender, EventArgs e)
        {
            bool Found = false;
            if (dataGridView1.Rows.Count > 0)
            {
                foreach(DataGridViewRow row in dataGridView1.Rows)
                {
                    if (Convert.ToString(row.Cells[1].Value) == textBox6.Text &&
                    Convert.ToString(row.Cells[2].Value) == textBox7.Text &&
                    Convert.ToString(row.Cells[3].Value) == textBox8.Text &&
                    Convert.ToString(row.Cells[5].Value) == textBox9.Text &&
                    Convert.ToString(row.Cells[7].Value) == textBox10.Text) ;
                    Found = true;
                 }           
            }       
            if(!Found)
            {
                dataGridView1.Rows.Add(textBox7.Text, textBox8.Text, textBox6.Text, textBox9.Text, textBox10.Text, 1);
            }
                else
                {
                dataGridView1.Rows.Add(textBox7.Text, textBox8.Text, textBox6.Text, textBox9.Text, textBox10.Text, 1);
            }


        }



how to install Adesso av-200 video capture express

$
0
0

Hi,

how to install Adesso av-200 video capture express

Open Form2 to specific record based on selected row of DataGridView on Form1

$
0
0

Hi guys!  I have a form called StudentsList with a DataGridView on it.  I would like to do the following:  When I doubleclick on a row, the formStudentsListDetails will open to the specific record selected from theDataGridView on StudentsList.

On the form StudentsList I created a class calledVariables that has a public static int variable calledRecordID:

CODE ON FORM1:

        private void tbl_alunosDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {          
            Form Alunos = new Alunos();
            Alunos.MdiParent = this.MdiParent;
            Alunos.Show();
            Variables.RecordID = tbl_alunosBindingSource.Position;
        }

    }

    class Variables
    {
        public static int RecordID;
    }

CODE ON FORM2:

        private void Alunos_Load(object sender, EventArgs e)
        {
            tbl_alunosBindingSource.Position = Variables.RecordID;          
        }

Can anyone please tell me what I am doing wrong?  I greatly appreciate your time and help.  Thank you! :)


jcrcarmo

Make Dynamic Scripting for Insert, Delete, Update SQLite query in C#

$
0
0

Hello Sir/Madam,

I have created one windows application for Batch Report using C# in which i am logging the data into Sqlite Database table (BatchDetails) .The issue is i want to use same script in multiple project, that's why i want to make that script dynamic, even if i will add the same script in new project , but i don't want to change in the script.

Now the problem i have faced is, if column name in the table will change, then i have to change in the script to accordingly.

SC_BatchReport Script Module

//--------------------------------------------------------------
// Press F1 to get help about using script.
// To access an object that is not located in the current class, start the call with Globals.
// When using events and timers be cautious not to generate memoryleaks,
// please see the help for more information.
//---------------------------------------------------------------

namespace Neo.ApplicationFramework.Generated
{
	using System.Windows.Forms;
	using System;
	using System.Drawing;
	using Neo.ApplicationFramework.Tools;
	using Neo.ApplicationFramework.Common.Graphics.Logic;
	using Neo.ApplicationFramework.Controls;
	using Neo.ApplicationFramework.Interfaces;

	using System.IO;					// for ApplicationPath
	using System.Reflection;    		// for ApplicationPath
	using System.Collections.Generic;	// for List<T>
	using System.Data;					// for DataTables, DataSets...
	using System.Data.SQLite;			// for SQLite Database IO
	using System.Globalization;			// for CultureInfo
	using System.Text;					// for Stringbuilder
	using System.IO.Ports; 				// for COM...

	using Neo.ApplicationFramework.Common.Printer.Document;
	using Neo.ApplicationFramework.Tools.Printer;
	using Neo.ApplicationFramework.Interfaces.Printer;
	using Neo.ApplicationFramework.Tools.OpcClient;
	using Core.Api.Service;				//IsecurityServiceCF
	public partial class SC_BatchReport
	{
		ISecurityServiceCF securityServiceMessage = ServiceContainerCF.GetService<ISecurityServiceCF>();
		public DataTable dtLogData = new DataTable ("DataLogger1");
		public DataTable dtAlarmData = new DataTable ("AlarmServer");
		public DataTable dtAuditData = new DataTable ("AuditLog");
		public DateTime CurrentDate;
		public DateTime BatchStartTime;
		public DateTime BatchStopTime;
		public String UniqueID;
		public string excecutingPath;
		public DataTable dtBatchDetails = new DataTable ("BatchDetails");
		public DataTable dtBatchHeader = new DataTable ("BatchDetails");
		string sProjectReportPath;
		SerialPort m_port = new SerialPort();

		public void ReadFromDataLogger(string fstart, string fstop)
		{
			dtLogData.Clear();
			dtAlarmData.Clear();
			// Create a new SQL connection object.
			using (var sqlConnection = new SQLiteConnection())
			{
				// Specify the ConnectionString, with the full path to the database.
				excecutingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);

				sqlConnection.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "Database.db"));

				try
				{
					// Tries to open the connection.
					sqlConnection.Open();

					// Define a query that selects the 10 top data elements
					string query = "SELECT time(Time) as Time,BlenderSpeed FROM DataLogger1 Where Time >= '"+fstart+"' and Time <= '"+fstop+"'";
					SQLiteDataAdapter sqlda = new SQLiteDataAdapter(query,sqlConnection);
					sqlda.Fill(dtLogData);

					string query1 = "SELECT Text,ActiveTime,InActiveTime FROM AlarmServer Where ActiveTime >= '"+fstart+"' and ActiveTime <= '"+fstop+"'";
					SQLiteDataAdapter sqlda1 = new SQLiteDataAdapter(query1,sqlConnection);
					sqlda1.Fill(dtAlarmData);
					sqlConnection.Close();
				}
				catch (SQLiteException exception)
				{
					MessageBox.Show(exception.ToString());
				}
			}
		}

		public void ReadFromAuditTrail(string fstart, string fstop)
		{
			var data = new StringBuilder();
			dtAuditData.Clear();
			// Create a new SQL connection object.
			using (var sqlConnectionAudit = new SQLiteConnection())
			{
				// Specify the ConnectionString, with the full path to the database.
				string excecutingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
				sqlConnectionAudit.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "AuditTrail.db"));

				try
				{
					// Tries to open the connection.
					sqlConnectionAudit.Open();

					// Define a query that selects the 10 top data elements
					string query = "SELECT TimeStamp,Message,ValueBefore As VBefore,ValueAfter As VAfter,UserName As User FROM AuditLog Where TimeStamp >= '"+fstart+"' and TimeStamp <= '"+fstop+"'";
					//MessageBox.Show(query);
					SQLiteDataAdapter sqlda1 = new SQLiteDataAdapter(query,sqlConnectionAudit);
					sqlda1.Fill(dtAuditData);
					sqlConnectionAudit.Close();
				}
				catch (SQLiteException exception)
				{
					MessageBox.Show(exception.ToString());
				}
			}
		}

		public void BatchStart()
		{
			Globals.Tags.BatchStarted.Value=true;
			var data = new StringBuilder();
			BatchStartTime=DateTime.Now;
			Globals.Tags.UniqueID.Value = DateTime.Now.ToString("yyyyMMddHHmmss");

			// Create a new SQL connection object.
			using (var sqlConnection = new SQLiteConnection())
			{
				// Specify the ConnectionString, with the full path to the database.
				string excecutingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);

				sqlConnection.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "Database.db"));

				try
				{
					// Tries to open the connection.
					sqlConnection.Open();

					// Define a query that selects the 10 top data elements
					Globals.Tags.BatchStartTime.Value=BatchStartTime;
					string query = "INSERT INTO BatchDetails (BatchStartTime, BatchStopTime, ProductName, OperatorName, ProductCode, BatchCode, RecipeNo, BatchSize,PrintInterval, UniqueID, TotalNoMixings, Mixing1_Bit,Mixing1,Mixing2_Bit, Mixing2,Mixing3_Bit, Mixing3,Mixing4_Bit, Mixing4,Mixing5_Bit, Mixing5) VALUES ('"+ BatchStartTime +"', '"+Globals.Tags.SystemTagDateTime.Value.ToString() +"', '"+Globals.Tags.PRODUCT_NAME.Value.ToString()+"','"+Globals.Tags.OPERATOR_NAME.Value.ToString() +"','"+Globals.Tags.PRODUCT_CODE.Value.ToString() +"','"+Globals.Tags.BATCH_NO.Value.ToString() +"','"+Globals.Tags.RECIPE_NO.Value.ToString() +"','"+Globals.Tags.BATCH_SIZE.Value.ToString() +"','"+Globals.Tags.PRINT_INTERVAL.Value.ToString() +"','"+Globals.Tags.UniqueID.Value.ToString() +"', '"+Globals.Tags.TOTAL_NO_MIXINGS.Value.ToString() +"','"+Globals.Tags.m240.Value.ToString() +"', '"+Globals.Tags.MIXING_1.Value.ToString() +"','"+Globals.Tags.m241.Value.ToString() +"', '"+Globals.Tags.MIXING_2.Value.ToString() +"','"+Globals.Tags.m242.Value.ToString() +"', '"+Globals.Tags.MIXING_3.Value.ToString() +"','"+Globals.Tags.m243.Value.ToString() +"', '"+Globals.Tags.MIXING_4.Value.ToString() +"','"+Globals.Tags.m244.Value.ToString() +"', '"+Globals.Tags.MIXING_5.Value.ToString() +"'); ";
					//MessageBox.Show(query);
					SQLiteDataAdapter sqlda = new SQLiteDataAdapter(query,sqlConnection);
					sqlda.Fill(dtLogData);

					sqlConnection.Close();
				}
				catch (SQLiteException exception)
				{
					MessageBox.Show(exception.ToString());

				}
			}

		}

		public void BatchStop()
		{
			Globals.Tags.BatchStarted.Value=false;
			var data = new StringBuilder();
			if(	Globals.Tags.UniqueID.Value != null)
			{
				// Create a new SQL connection object.
				using (var sqlConnection = new SQLiteConnection())
				{
					BatchStopTime=DateTime.Now;
					Globals.Tags.Date.Value=BatchStopTime.ToString("dd/MM/yyyy");
					Globals.Tags.Time.Value=BatchStopTime.ToString("HH:mm:ss");
					Globals.Tags.BatchStopTime.Value=BatchStopTime;

					// Specify the ConnectionString, with the full path to the database.
					string excecutingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);

					sqlConnection.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "Database.db"));

					try
					{
						// Tries to open the connection.
						sqlConnection.Open();

						// Define a query that selects the 10 top data elements
						Globals.Tags.BatchStopTime.Value = BatchStopTime.ToString();
						string query = "UPDATE BatchDetails SET BatchStopTime = '"+BatchStopTime.ToString()+"' WHERE UniqueID = '"+ Globals.Tags.UniqueID.Value +"'";
						//MessageBox.Show(query);
						SQLiteDataAdapter sqlda = new SQLiteDataAdapter(query,sqlConnection);

						sqlda.Fill(dtLogData);

						sqlConnection.Close();
						Globals.Tags.UniqueID.Value="";

					}
					catch (SQLiteException exception)
					{
						MessageBox.Show(exception.ToString());
					}
				}

			}
			else
			{
				securityServiceMessage.ShowMessageBoxWithTimeout("Machine was not started", "WARNING");
			}
		}

		public string[] GetStoredReports()
		{
			string BatchName=string.Empty;
			List<string> sReports = new List<string>();

			using (var sqlConnection = new SQLiteConnection())
			{
				string excecutingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);

				sqlConnection.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "Database.db"));
				try
				{
					dtBatchDetails.Clear();
					sqlConnection.Open();
					string query = "SELECT * FROM BatchDetails LIMIT 10";
					SQLiteDataAdapter sqlda = new SQLiteDataAdapter(query,sqlConnection);
					sqlda.Fill(dtBatchDetails);
					sqlConnection.Close();
					sReports.Clear();
					foreach (DataRow DR in dtBatchDetails.Rows){
						{
						foreach(DataColumn dc in dtBatchDetails.Columns)
						{
							if ((dc.ColumnName == "BatchStartTime") || (dc.ColumnName == "BatchStopTime") || (dc.ColumnName == "BatchCode")) // skip column "Id"
							{
								if (dc.ColumnName == "BatchCode")
								{
									BatchName+=DR[dc].ToString();
								}
								else{BatchName+=DR[dc].ToString()+"_";}
							}
						}
						sReports.Add(BatchName);
						BatchName="";
					}
						}

				}
				catch (SQLiteException exception)
				{
					MessageBox.Show(exception.ToString());
				}
				return sReports.ToArray();
			}

		}
		public void DataBase()
		{
			foreach (DataRow DR in dtLogData.Rows)
			{
				foreach(DataColumn dc in dtLogData.Columns)
				{
					MessageBox.Show(DR[dc].ToString());
				}
			}

		}
		public void BatchHeader(string IDvalue)
		{
			if(IDvalue!=null)
			{
				using (var sqlConnection = new SQLiteConnection())
				{
					string excecutingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);

					sqlConnection.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "Database.db"));
					try
					{
						dtBatchHeader.Clear();
						sqlConnection.Open();
						string query = "SELECT BatchStartTime,BatchStopTime,ProductName,OperatorName,ProductCode,BatchCode,RecipeNo,BatchSize,PrintInterval,TotalNoMixings,Mixing1_Bit,Mixing1,Mixing2_Bit,Mixing2,Mixing3_Bit,Mixing3,Mixing4_Bit,Mixing4,Mixing5_Bit,Mixing5 FROM BatchDetails WHERE UniqueID='"+IDvalue+"'";

						SQLiteDataAdapter sqlda = new SQLiteDataAdapter(query,sqlConnection);
						sqlda.Fill(dtBatchHeader);
					}
					catch (SQLiteException exception)
					{
						//MessageBox.Show(exception.ToString());
					}
				}
			}
		}
		public void Delete(string deleteBatchID, string deleteBatchStartTime, string deleteBatchStopTime)
		{
			try
			{
				if(deleteBatchID!=null)
				{
					using (var sqlConnection = new SQLiteConnection())
					{

						string excecutingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);

						sqlConnection.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "Database.db"));
						dtBatchDetails.Clear();
						sqlConnection.Open();
						string query = "DELETE FROM BatchDetails WHERE UniqueID='"+deleteBatchID+"'";
						SQLiteDataAdapter sqlda = new SQLiteDataAdapter(query,sqlConnection);
						sqlda.Fill(dtBatchDetails);
						sqlConnection.Close();
						//MessageBox.Show("header Deleted successfully");
						excecutingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
						sqlConnection.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "AuditTrail.db"));
						sqlConnection.Open();
						query = "DELETE FROM AuditLog Where TimeStamp >= '"+deleteBatchStartTime+"' and TimeStamp <= '"+deleteBatchStopTime+"'";
						SQLiteDataAdapter sqlda1 = new SQLiteDataAdapter(query,sqlConnection);
						sqlda1.Fill(dtAuditData);
						sqlConnection.Close();
						//MessageBox.Show("Audit Deleted successfully");
						excecutingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
						sqlConnection.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "Database.db"));
						sqlConnection.Open();
						query = "DELETE FROM DataLogger1 Where Time >= '"+deleteBatchStartTime+"' and Time <= '"+deleteBatchStopTime+"'";
						SQLiteDataAdapter sqlda2 = new SQLiteDataAdapter(query,sqlConnection);
						sqlda2.Fill(dtLogData);
						//MessageBox.Show("Log value Deleted successfully");
						query = "DELETE FROM AlarmServer Where ActiveTime >= '"+deleteBatchStartTime+"' and ActiveTime <= '"+deleteBatchStopTime+"'";
						SQLiteDataAdapter sqlda3 = new SQLiteDataAdapter(query,sqlConnection);
						sqlda3.Fill(dtAlarmData);
						sqlConnection.Close();
						securityServiceMessage.ShowMessageBoxWithTimeout("Batch Related Data Deleted successfully", "Batch Status");
						//MessageBox.Show("Batch Related Data Deleted successfully");
					}
				}
			}
			catch (SQLiteException exception)
			{
				MessageBox.Show(exception.ToString());
			}
		}

		public void PrintReport()
		{

			Globals.Tags.Date.Value=DateTime.Now.ToString("dd/MM/yyyy");
			Globals.Tags.Time.Value=DateTime.Now.ToString("HH:mm:ss");
			try
			{
				StringBuilder sReport = new StringBuilder();
				int count=0;
				int[] MaxLength={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
				int RowValueLength=0;
				int LastRowValueLength=0;
				int columnNumber=0;
				if (dtBatchHeader.Rows.Count > 0)
				{
					columnNumber=columnNumber+1;
					foreach(DataColumn dc in dtBatchHeader.Columns)
					{
						foreach (DataRow DR in dtBatchHeader.Rows)
						{
							RowValueLength=DR[dc].ToString().Length;
							if(LastRowValueLength < RowValueLength)
							{
								LastRowValueLength=RowValueLength;
							}
						}
						MaxLength[columnNumber]=LastRowValueLength;

						LastRowValueLength=0;
						RowValueLength=0;
					}
				}

				if (dtBatchHeader.Rows.Count > 0)
				{
					sReport.Append("                                ***   Batch Report   ***                        ").AppendLine();
					sReport.Append("Date :"+Globals.Tags.Date.Value.ToString()+"                                                  Time :"+Globals.Tags.Time.Value.ToString()+"").AppendLine();
					sReport.Append("--------------------------------------------------------------------------------").AppendLine();
					sReport.Append("                                Dr. REDDY'S LABORATORIES LTD.                   ").AppendLine();
					sReport.Append("                                          FTO- 3,                               ").AppendLine();
					sReport.Append("OCTAGONAL BLENDER                                               EQP ID. :PRE 224").AppendLine();
					//sReport.Append("------------------------------------------------------------------------------").AppendLine();
					sReport.Append("________________________________________________________________________________").AppendLine();
					sReport.Append("--------------------------------------------------------------------------------").AppendLine();
					sReport.Append("          SET PARAMETER ").AppendLine();
					sReport.AppendLine();

					string cs_mixing1_bit = string.Empty;
					string cs_mixing2_bit = string.Empty;
					string cs_mixing3_bit = string.Empty;
					string cs_mixing4_bit = string.Empty;
					string cs_mixing5_bit = string.Empty;
					foreach (DataRow DR in dtBatchHeader.Rows)
					{
						foreach(DataColumn dc in dtBatchHeader.Columns)
						{
							count=count+1;

							var field1 = DR[dc];

							if(dc.ColumnName =="BatchStartTime")
							{
								sReport.Append("BATCH START TIME   : "+field1.ToString()).AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="BatchStopTime")
							{
								sReport.Append("BATCH STOP TIME    : "+field1.ToString()).AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="ProductName")
							{
								sReport.Append("PRODUCT NAME       : "+field1.ToString()).AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="OperatorName")
							{
								sReport.Append("OPERATOR NAME      : "+field1.ToString()).AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="ProductCode")
							{
								sReport.Append("PRODUCT CODE       : "+field1.ToString()).AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="BatchCode")
							{
								sReport.Append("BATCH CODE         : "+field1.ToString()).AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="RecipeNo")
							{
								sReport.Append("RECIPE NO.         : "+field1.ToString()).AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="BatchSize")
							{
								sReport.Append("BATCH SIZE         : "+field1.ToString()).AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="PrintInterval")
							{
								sReport.Append("PRINT INTERVAL     : "+field1.ToString()).AppendLine();
								sReport.Append("--------------------------------------------------------------------------------").AppendLine();
								sReport.Append("SET PARAMETERS : ").AppendLine();
							}
							else if(dc.ColumnName=="TotalNoMixings")
							{
								sReport.Append("TOTAL NO OF MIXINGS: "+field1.ToString()).AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="Mixing1_Bit")
							{
								string bitresult = "OFF";
								if(field1.ToString() == "False"){bitresult = "OFF";}else{bitresult = "ON";}
								cs_mixing1_bit = "MIXINGS 1: "+ bitresult;
							}
							else if(dc.ColumnName=="Mixing1")
							{
								sReport.Append(cs_mixing1_bit + "     " + field1.ToString()+ " MIN ").AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="Mixing2_Bit")
							{
								string bitresult = "OFF";
								if(field1.ToString() == "False"){bitresult = "OFF";}else{bitresult = "ON";}
								cs_mixing2_bit = "MIXINGS 2: "+ bitresult;
							}
							else if(dc.ColumnName=="Mixing2")
							{
								sReport.Append(cs_mixing2_bit + "     " + field1.ToString()+ " MIN ").AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="Mixing3_Bit")
							{
								string bitresult = "OFF";
								if(field1.ToString() == "False"){bitresult = "OFF";}else{bitresult = "ON";}
								cs_mixing3_bit = "MIXINGS 3: "+ bitresult;
							}
							else if(dc.ColumnName=="Mixing3")
							{
								sReport.Append(cs_mixing3_bit + "     " + field1.ToString()+ " MIN ").AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="Mixing4_Bit")
							{
								string bitresult = "OFF";
								if(field1.ToString() == "False"){bitresult = "OFF";}else{bitresult = "ON";}
								cs_mixing4_bit = "MIXINGS 4: "+ bitresult;
							}
							else if(dc.ColumnName=="Mixing4")
							{
								sReport.Append(cs_mixing4_bit + "     " + field1.ToString()+ " MIN ").AppendLine();
								sReport.AppendLine();
							}
							else if(dc.ColumnName=="Mixing5_Bit")
							{
								string bitresult = "OFF";
								if(field1.ToString() == "False"){bitresult = "OFF";}else{bitresult = "ON";}
								cs_mixing5_bit = "MIXINGS 5: "+ bitresult;
							}
							else if(dc.ColumnName=="Mixing5")
							{
								sReport.Append(cs_mixing5_bit + "     " + field1.ToString()+ " MIN ").AppendLine();
								sReport.Append("--------------------------------------------------------------------------------").AppendLine();
							}
						}
						count=0;
					}
				}

				sReport.AppendLine();
				//sReport.AppendLine();
				//sReport.AppendLine();
				//sReport.Append("CHECKED BY                                                Verified By:").AppendLine();
				//sReport.AppendLine();
				//sReport.Append("Operator   :").AppendLine();
				//sReport.AppendLine();
				//sReport.Append("Pharmacist :").AppendLine();
				//sReport.AppendLine();
				//sReport.Append("--------------------------------------------------------------------------------------------------------------------------------------").AppendLine();
				//MessageBox.Show(sReport.ToString());

				OpenPort("COM5", 9600,Parity.None,StopBits.One,8);
				m_port.Write(sReport.ToString());
				m_port.Close();
				sReport.Remove(0,sReport.Length);
				PrintBatchLogData();
				PrintAlarmReport();
				PrintAuditReport();
				sReport.AppendLine();
				//sReport.AppendLine();
				//sReport.AppendLine();
				sReport.Remove(0,sReport.Length);
				sReport.AppendLine();
				sReport.AppendLine();
				sReport.Append("--------------------------------------------------------------------------------").AppendLine();
				sReport.Append("CHECKED BY                                                Verified By:").AppendLine();
				sReport.AppendLine();
				sReport.Append("Operator   :").AppendLine();
				sReport.AppendLine();
				sReport.AppendLine();
				sReport.AppendLine();
				//sReport.Append("--------------------------------------------------------------------------------------------------------------------------------------").AppendLine();

				OpenPort("COM5", 9600,Parity.None,StopBits.One,8);
				m_port.Write(sReport.ToString());
				m_port.Close();

				//MessageBox.Show(sReport.ToString());
				//PrintMessage(sReport.ToString());

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}


		/// <summary>
		/// open COM port
		/// </summary>
		public void OpenPort(string portName, int baudrate, Parity parity, StopBits stopbit, int databits)
		{

			try
			{

				m_port.PortName = portName;
				m_port.BaudRate = baudrate;
				m_port.Parity = parity;
				m_port.DataBits = databits;
				m_port.StopBits = stopbit;
				m_port.ReadTimeout = 1000;
				//m_port.ReadBufferSize =50000;
				/*m_Timer = new Timer();
				m_Timer.Interval = 10000;
				m_Timer.Enabled = true;*/
				if(!m_port.IsOpen)
				{
					m_port.Open();
				}
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
		public void PrintMessage(string text)
		{
			IPrinterServiceCF printerService= new PrinterToolCF();

			if (printerService != null)
			{
				Paragraph paragraph = new Paragraph(text);
				FlowDocument flowDocument = new FlowDocument();
				flowDocument.Blocks.Add(paragraph);

				try
				{
					printerService.SendToPrinterAsync(flowDocument);
					MessageBox.Show("Print Data Send to Port Successfully");
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.ToString());
				}
			}
			else
			{
				MessageBox.Show("No printer device configured!");
			}
		}
		public void CreateReport(string fBatchName ,string fBatchStartTime, string fBatchStopTime)
		{
			MessageBox.Show("1");
			int iFirstDataRow = 54;
			string sReportPeriod = fBatchStartTime + " - " + fBatchStopTime;
			MessageBox.Show("2");
			string 	sConfigPath = ApplicationPath + @"\Project Files\Config\";
			MessageBox.Show("3");
			sProjectReportPath = ApplicationPath + @"\Project Files\";
			//Make sure that the path and template file name is correct
			MessageBox.Show("4");
			FlexCel.XlsAdapter.XlsFile xls = new FlexCel.XlsAdapter.XlsFile(sConfigPath + "Template.xls");
			MessageBox.Show("5");
			// defining a DateTime Cell Format - aligned left
			FlexCel.Core.TFlxFormat f1 = xls.GetDefaultFormat;
			f1.Format="DD.MM.YYYY hh:mm:ss";
			f1.HAlignment = FlexCel.Core.THFlxAlignment.left;
			int iFormatDateTime = xls.AddFormat(f1); // first index = 1
			// defining a Arial 12 bold underlined Format - aligned left
			FlexCel.Core.TFlxFormat f2 = xls.GetDefaultFormat;
			f2.HAlignment = FlexCel.Core.THFlxAlignment.left;
			FlexCel.Core.TFlxFont ft = new FlexCel.Core.TFlxFont();// generates Arial size 10
			ft.Size20 = 240; // 240/20 = 12 pixel
			ft.Style = FlexCel.Core.TFlxFontStyles.Bold;
			ft.Underline = FlexCel.Core.TFlxUnderline.Single;
			f2.Font = ft;
			string fBatchNameSufix=fBatchStartTime.Replace(":","");
			fBatchNameSufix=fBatchNameSufix.Replace(" ","");
			fBatchNameSufix=fBatchNameSufix.Replace("-","");
			string sReportName = fBatchName + "_" + fBatchNameSufix;

			int iFormatArial12BoldUnderlined = xls.AddFormat(f2);

			xls.SetCellValue(4, 2, sReportName);
			xls.SetCellValue(4, 4, sReportPeriod);

			xls.SetCellValue(50, 2, dtAlarmData.Rows.Count);
			xls.SetCellValue(51, 2, dtAuditData.Rows.Count);
			xls.SetCellValue(52, 2, dtLogData.Rows.Count);
			//xls.SetCellValue(53, 2, dtLoadedRecipes.Rows.Count);

			MessageBox.Show("6");
			int iRow = iFirstDataRow;
			int iCol = 1;
			if (dtAlarmData.Rows.Count > 0)
			{
				xls.SetCellValue(iRow, 1, "Alarms:");
				xls.SetCellFormat(iRow, 1, iFormatArial12BoldUnderlined);
				iRow++;

				// Loop through the Alarm table header
				foreach (DataColumn dc in dtAlarmData.Columns)
				{
					if (dc.ColumnName != "Id") // skip column "Id"
					{
						xls.SetCellValue(iRow, iCol, dc.ColumnName);
						iCol ++;
					}
				}
				iRow++;
				// Loop through the Alarm table rows
				foreach (DataRow DR in dtAlarmData.Rows)
				{
					iCol = 1;
					foreach(DataColumn dc in dtAlarmData.Columns)
					{
						if (dc.ColumnName != "Id") // skip column "Id"
						{
							if (dc.ColumnName.Contains("Time"))
							{
								xls.SetCellFormat(iRow, iCol, iFormatDateTime);
							}
							var field1 = DR[dc];
							xls.SetCellValue(iRow, iCol, field1);
							iCol ++;
						}
					}
					iRow ++;
				}
				iRow++; // "add" an empty line
			}


			if (dtAuditData.Rows.Count > 0)
			{
				xls.SetCellValue(iRow, 1, "Events:");
				xls.SetCellFormat(iRow, 1, iFormatArial12BoldUnderlined);
				iRow++;

				iCol = 1;
				// Loop through the Events table header
				foreach (DataColumn dc in dtAuditData.Columns)
				{
					if (dc.ColumnName != "Id") // skip column "Id"
					{
						xls.SetCellValue(iRow, iCol, dc.ColumnName);
						iCol ++;
					}
				}
				iRow++;
				// Loop through the Events table rows
				foreach (DataRow DR in dtAuditData.Rows)
				{
					iCol = 1;
					foreach(DataColumn dc in dtAuditData.Columns)
					{
						if (dc.ColumnName != "Id") // skip column "Id"
						{
							if (dc.ColumnName.Contains("Time"))
							{
								xls.SetCellFormat(iRow, iCol, iFormatDateTime);
							}
							var field1 = DR[dc];
							xls.SetCellValue(iRow, iCol, field1);
							if (dc.ColumnName == "Message")
							{
								string sMessage = DR[dc].ToString();
								if (sMessage.StartsWith("Load Recipe"))
								{
									string[] sMessageArray = sMessage.Split(' ');
									MessageBox.Show(sMessageArray[2]);
								}
							}
							iCol ++;
						}
					}
					iRow ++;
				}
				iRow++; // "add" an empty line
			}


			if (dtLogData.Rows.Count > 0)
			{
				xls.SetCellValue(iRow, 1, "Logged Data:");
				xls.SetCellFormat(iRow, 1, iFormatArial12BoldUnderlined);
				iRow++;

				iCol = 1;
				// Loop through the LogData table header
				foreach (DataColumn dc in dtLogData.Columns)
				{
					if (dc.ColumnName != "Id") // skip column "Id"
					{
						xls.SetCellValue(iRow, iCol, dc.ColumnName);
						iCol ++;
					}
				}
				iRow++;
				// Loop through the LogData table rows
				foreach (DataRow DR in dtLogData.Rows)
				{
					iCol = 1;
					foreach(DataColumn dc in dtLogData.Columns)
					{
						if (dc.ColumnName != "Id") // skip column "Id"
						{
							if (dc.ColumnName.Contains("Time"))
							{
								xls.SetCellFormat(iRow, iCol, iFormatDateTime);
							}
							var field1 = DR[dc];
							xls.SetCellValue(iRow, iCol, field1);
							iCol ++;
						}
					}
					iRow ++;
				}
				iRow++; // "add" an empty line
			}


		/*	if (dtLoadedRecipes.Rows.Count > 0)
			{
				xls.SetCellValue(iRow, 1, "Loaded Recipes:");
				xls.SetCellFormat(iRow, 1, iFormatArial12BoldUnderlined);
				iRow++;

				iCol = 1;
				// Loop through the LoadedRecipes table header
				foreach (DataColumn dc in dtLoadedRecipes.Columns)
				{
					xls.SetCellValue(iRow, iCol, dc.ColumnName);
					iCol ++;
				}
				iRow++;
				// Loop through the LoadedRecipes table rows
				foreach (DataRow DR in dtLoadedRecipes.Rows)
				{
					iCol = 1;
					foreach(DataColumn dc in dtLoadedRecipes.Columns)
					{
						if (dc.ColumnName.Contains("Time"))
						{
							xls.SetCellFormat(iRow, iCol, iFormatDateTime);
						}
						var field1 = DR[dc];
						xls.SetCellValue(iRow, iCol, field1);
						iCol ++;
					}
					iRow ++;
				}
			}
			*/
			MessageBox.Show(sReportName);
			if (! File.Exists(sProjectReportPath + sReportName + ".xls"))
			{
				xls.Save(sProjectReportPath + sReportName + ".xls");
				//copyfile(sReportName);
			}
			else
			{
				//copyfile(sReportName);
			}
			//copyfile(sReportName);
			MessageBox.Show(sReportName);
		}
		private string ApplicationPath
		{
			get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName); }
		}
		public void copyfile()
		{
			try
			{
				bool UsbPresent = Directory.Exists("\\Hard Disk");
				bool NetworkPasent = Directory.Exists("\\MAESTROTEK");
				//MessageBox.Show(UsbPresent.ToString());
				bool SDCardPresent = Directory.Exists("\\Storage Card");
				if (UsbPresent==true)
				{
					DateTime time1;
					time1=DateTime.Now;
					string sFilename=time1.ToString("yyyyMMdd_HHmmss");
					//sFilename=sFilename.Replace(" ","");
					//sFilename=sFilename.Replace("/","");

					string sProjectReportPathcopy="\\Hard Disk\\";
					//string sProjectReportPathcopy="\\SERVICE-MAESTRO\\share\\";
					//sProjectReportPathcopy=@"\\192.168.1.110\Shared\";
					sProjectReportPath = ApplicationPath + @"\";
					string sConfigPath = ApplicationPath + @"\Project Files\Config\";

					File.Copy(sProjectReportPath + "Database" + ".db",sProjectReportPathcopy + sFilename + "DataBase" + ".db");//"AuditTrail.db"
					File.Copy(sProjectReportPath + "AuditTrail" + ".db",sProjectReportPathcopy + sFilename + "AuditTrail" + ".db");//"AuditTrail.db"
					//File.Copy(sConfigPath + "HeaderData" + ".db",sProjectReportPathcopy + sFilename + "HeaderData" + ".db");
					MessageBox.Show("DataBase Backup Succesfuly");
					using (var sqlConnection = new SQLiteConnection())
					{
						//Delete Headers Details:
						//string excecutingPath = ApplicationPath + @"\Project Files\Config\";
						string excecutingPath = ApplicationPath + @"\";
						sqlConnection.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "Database.db"));
						dtBatchDetails.Clear();
						sqlConnection.Open();
						string query = "DELETE FROM BatchDetails";
						SQLiteDataAdapter sqlda = new SQLiteDataAdapter(query,sqlConnection);
						sqlda.Fill(dtBatchDetails);
						sqlConnection.Close();
						MessageBox.Show("Header Deleted Succesfuly");
						//Delete Alarm and Data
						excecutingPath = ApplicationPath + @"\";
						sqlConnection.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "Database.db"));
						dtBatchDetails.Clear();
						sqlConnection.Open();
						query = "DELETE FROM DataLogger1";
						SQLiteDataAdapter sqlda1 = new SQLiteDataAdapter(query,sqlConnection);
						sqlda1.Fill(dtLogData);
						//Alarm Clear
						query = "DELETE FROM AlarmServer";
						SQLiteDataAdapter sqlda2 = new SQLiteDataAdapter(query,sqlConnection);
						sqlda2.Fill(dtAlarmData);
						sqlConnection.Close();
						MessageBox.Show("Alarm Deleted Succesfuly");
						// Audit Trail Clear.............
						excecutingPath = ApplicationPath + @"\";
						sqlConnection.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "AuditTrail.db"));
						dtBatchDetails.Clear();
						sqlConnection.Open();
						query = "DELETE FROM AuditLog";
						SQLiteDataAdapter sqlda3 = new SQLiteDataAdapter(query,sqlConnection);
						sqlda3.Fill(dtAuditData);
					}
				}
				else
				{
					MessageBox.Show("Pendrive Not Found.............");
				}
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}

		public void BatchTrend(string sFilename)
		{
			if (dtLogData.Rows.Count > 0)
			{
				// Loop through the LogData table rows
				foreach (DataRow DR in dtLogData.Rows)
				{
					foreach(DataColumn dc in dtLogData.Columns)
					{
						if (dc.ColumnName != "Id") // skip column "Id"
						{
							var field1 = DR[dc];
						}
					}

				}

			}
		}
		public void filesName()
		{
			//sProjectReportPath = ApplicationPath + @"\\Hard Disk\";
			//string sConfigPath = ApplicationPath + @"\Project Files\Config\";
			string path = "\\Hard Disk";
			try
			{
				// Only get files that begin with the letter "c."
				string[] dirs = Directory.GetFiles(path , ".db");

				foreach (string dir in dirs)
				{
					MessageBox.Show(dir.ToString());
				}
			}
			catch (Exception e)
			{
				MessageBox.Show(Convert.ToString(e));
				//Console.WriteLine("The process failed: {0}", e.ToString());
			}

		}
		public void stringtest( string stringValue, int stringLength)
		{
			if ((stringValue.Length>stringLength)&&(stringValue!=null))
			{
				stringValue=stringValue.Substring(0,stringLength);
			}
			else if((stringValue.Length<=stringLength)&&(stringValue!=null))
			{
				stringValue=stringValue.PadLeft(stringLength,' ');
			}
			//string st2=stringValue.
			MessageBox.Show(stringValue);
			MessageBox.Show(stringValue);
		}
		public void MyStringFormate()
		{
			//stringtest(Globals.Tags.BatchName.Value,Globals.Tags.ProductName.Value.Int);
			/*if (Globals.Tags.BatchName.Value!=null){
				string t1=string.Format("{0:0.00}",Globals.Tags.BatchName.Value.Decimal);
				MessageBox.Show(t1);
				string t2=string.Format("{0:0.00}",100.01);
				MessageBox.Show(t2);
				string t3=string.Format("{0:0.00}",100);
				MessageBox.Show(t3);
			}*/
			//MessageBox.Show(Globals.Tags.BatchName.Value.ToString().PadLeft(10,'-'));
		}
		private GlobalDataItem GetGlobalDataItem(string propertyName)
		{
			PropertyInfo tagProperty = typeof (Neo.ApplicationFramework.Generated.Tags).GetProperty(propertyName);
			if(tagProperty == null)
				return null;
			else
				return tagProperty.GetValue(Globals.Tags, null) as GlobalDataItem;
		}
		public void ReadAlarmTimeBased(string fstart, string fstop)
		{
			dtAlarmData.Clear();
			// Create a new SQL connection object.
			using (var sqlConnection = new SQLiteConnection())
			{
				// Specify the ConnectionString, with the full path to the database.
				excecutingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
				//excecutingPath = ApplicationPath + @"\Project Files\Config\";
				sqlConnection.ConnectionString = string.Format("data source={0}", Path.Combine(excecutingPath, "Database.db"));
				// Using a try/catch in case something goes wrong.
				// Should the full path to the database be wrong, it will throw an exception.
				// This prevents the termination of the program.
				try
				{
					// Tries to open the connection.
					sqlConnection.Open();

					string query1 = "SELECT Text,ActiveTime,InActiveTime FROM AlarmServer Where ActiveTime >= '"+fstart+"' and ActiveTime <= '"+fstop+"'";
					SQLiteDataAdapter sqlda1 = new SQLiteDataAdapter(query1,sqlConnection);
					sqlda1.Fill(dtAlarmData);
					sqlConnection.Close();
				}
				catch (SQLiteException exception)
				{
					MessageBox.Show(exception.ToString());
				}
			}
		}
		public void AlarmPrint()
		{
			Globals.Tags.Date.Value=DateTime.Now.ToString("dd/MM/yyyy");
			Globals.Tags.Time.Value=DateTime.Now.ToString("HH:mm:ss");
			try
			{
				StringBuilder sReport = new StringBuilder();
				string printdata="";
				int count=0;
				int[] MaxLength={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
				int RowValueLength=0;
				int LastRowValueLength=0;
				int columnNumber=0;
				if (dtAlarmData.Rows.Count > 0)
				{
					columnNumber=columnNumber+1;
					foreach(DataColumn dc in dtAlarmData.Columns)
					{
						foreach (DataRow DR in dtAlarmData.Rows)
						{
							RowValueLength=DR[dc].ToString().Length;
							if(LastRowValueLength < RowValueLength)
							{
								LastRowValueLength=RowValueLength;
							}
						}
						MaxLength[columnNumber]=LastRowValueLength;
						LastRowValueLength=0;
						RowValueLength=0;
					}
				}
				if (dtAlarmData.Rows.Count > 0)
				{
					sReport.Append("                                Emcure Pharmaceuticals Ltd.                                             ").AppendLine();
					sReport.Append("Date :"+Globals.Tags.Date.Value.ToString()+"                                          Time :"+Globals.Tags.Time.Value.ToString()+"").AppendLine();
					//sReport.Append("Equipment ID       : "+Globals.Tags.PRODUCT_CODE.Value.ToString()+"  ").AppendLine();
					sReport.AppendLine();
					sReport.AppendLine();
					sReport.Append("         Alarm Text                       Active Time            InActive Time").AppendLine();

					foreach (DataRow DR in dtAlarmData.Rows)
					{
						foreach(DataColumn dc in dtAlarmData.Columns)
						{

							count=count+1;
							var field1 = DR[dc];

							if(dc.ColumnName =="Text")
							{
								printdata=field1.ToString();
								sReport.Append("   "+printdata.PadRight(30,' '));

							}
							else if(dc.ColumnName=="ActiveTime")
							{
								sReport.Append("   "+field1.ToString());

							}
							else if(dc.ColumnName=="InActiveTime")
							{
								sReport.Append("   "+field1.ToString());

							}

						}
						sReport.AppendLine();
						count=0;
					}

				}
				sReport.AppendLine();
				//sReport.AppendLine();
				//sReport.AppendLine();
				sReport.Append("CHECKED BY                                                Verified By:").AppendLine();
				sReport.AppendLine();
				sReport.Append("Operator   :").AppendLine();
				sReport.AppendLine();
				sReport.Append("Pharmacist :").AppendLine();
				sReport.AppendLine();
				sReport.AppendLine();
				sReport.AppendLine();
				//sReport.Append("--------------------------------------------------------------------------------------------------------------------------------------").AppendLine();

				OpenPort("COM5", 9600,Parity.None,StopBits.One,8);
				m_port.Write(sReport.ToString());
				m_port.Close();

			}
			catch(Exception ex)
			{
			}
		}
		public void PrintAuditReport()
		{
			try
			{
				StringBuilder sReport = new StringBuilder();
				int count=0;
				string[] maxlength = new String[dtAuditData.Columns.Count];
				for (int j =0; j < dtAuditData.Columns.Count; j++)
				{
					int refmaxlength = dtAuditData.Columns[j].ColumnName.ToString().Length;
					for (int i =0; i < dtAuditData.Rows.Count; i++)
					{
						if (refmaxlength < dtAuditData.Rows[i][j].ToString().Length){maxlength[j] = dtAuditData.Rows[i][j].ToString().Length.ToString();refmaxlength = dtAuditData.Rows[i][j].ToString().Length;}
						else{	maxlength[j] = refmaxlength.ToString();}
					}
					//	MessageBox.Show(j.ToString()+"" + maxlength[j].ToString());
				}
				if (dtAuditData.Rows.Count > 0)
				{
					sReport.AppendLine();
					sReport.Append("Audit Trail:").AppendLine();
					sReport.Append("--------------------------------------------------------------------------------").AppendLine();
					// Loop through the Alarm table header
					foreach (DataColumn dc in dtAuditData.Columns)
					{
						count=count+1;
						if(count==1)//|| count==2 || count==3
						{
							string columnnametoprint = dc.ColumnName;
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[0]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}
						if(count==2)//|| count==2 || count==3
						{
							string columnnametoprint = dc.ColumnName;
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[1]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}
						else if(count==3)
						{
							string columnnametoprint = dc.ColumnName;
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[2]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}
						else if(count==4)
						{
							string columnnametoprint = dc.ColumnName;
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[3]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}
						else if(count==5)
						{
							string columnnametoprint = dc.ColumnName;
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[4]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}
					}
					sReport.AppendLine();
					sReport.Append("--------------------------------------------------------------------------------").AppendLine();
					count=0;
					foreach (DataRow DR in dtAuditData.Rows)
					{
						foreach(DataColumn dc in dtAuditData.Columns)
						{
							count=count+1;
							var field1 = DR[dc];
							if(count==1)//|| count==2 || count==3
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[0]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}
							else if( count==2 )
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[1]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}
							else if( count==3 )
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[2]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}
							else if(count==4)
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[3]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}
							else if( count==5 )
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[4]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}
							/*else if( count==6 )
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[5]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}*/
						}
						count=0;
						OpenPort("COM5", 9600,Parity.None,StopBits.One,8);
						m_port.Write(sReport.ToString());
						m_port.Close();
						sReport.Remove(0,sReport.Length);
						sReport.AppendLine();

					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}
		public void PrintAlarmReport()
		{
			try
			{
				StringBuilder sReport = new StringBuilder();
				int count=0;
				string[] maxlength = new String[dtAlarmData.Columns.Count];
				for (int j =0; j < dtAlarmData.Columns.Count; j++)
				{
					int refmaxlength = dtAlarmData.Columns[j].ColumnName.ToString().Length;
					for (int i =0; i < dtAlarmData.Rows.Count; i++)
					{
						if (refmaxlength < dtAlarmData.Rows[i][j].ToString().Length){maxlength[j] = dtAlarmData.Rows[i][j].ToString().Length.ToString();refmaxlength = dtAlarmData.Rows[i][j].ToString().Length;}
						else{	maxlength[j] = refmaxlength.ToString();}
					}
					//	MessageBox.Show(j.ToString()+"" + maxlength[j].ToString());
				}
				if (dtAlarmData.Rows.Count > 0)
				{
					sReport.Append("Alarms:").AppendLine();
					sReport.Append("--------------------------------------------------------------------------------").AppendLine();
					// Loop through the Alarm table header
					foreach (DataColumn dc in dtAlarmData.Columns)
					{
						count=count+1;
						if(count==2)//|| count==2 || count==3
						{
							string columnnametoprint = "Event Time";
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[1]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}
						if(count==1)//|| count==2 || count==3
						{
							string columnnametoprint = "Text";
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[0]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}
						else if(count==3)
						{
							string columnnametoprint = dc.ColumnName;
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[2]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}
					}
					sReport.AppendLine();
					sReport.Append("--------------------------------------------------------------------------------").AppendLine();
					count=0;
					foreach (DataRow DR in dtAlarmData.Rows)
					{
						foreach(DataColumn dc in dtAlarmData.Columns)
						{
							count=count+1;
							var field1 = DR[dc];
							if(count==1)
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[0]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}
							else if( count==2 )
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[1]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}
							else if( count==3 )
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[2]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}
						}
						count=0;
						OpenPort("COM5", 9600,Parity.None,StopBits.One,8);
						m_port.Write(sReport.ToString());
						m_port.Close();
						sReport.Remove(0,sReport.Length);
						sReport.AppendLine();

					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}
		public void PrintBatchLogData()
		{
			try
			{
				StringBuilder sReport = new StringBuilder();
				int count=0;
				string[] maxlength = new String[dtLogData.Columns.Count];
				for (int j =0; j < dtLogData.Columns.Count; j++)
				{
					int refmaxlength = dtLogData.Columns[j].ColumnName.ToString().Length;
					for (int i =0; i < dtLogData.Rows.Count; i++)
					{
						if (refmaxlength < dtLogData.Rows[i][j].ToString().Length){maxlength[j] = dtLogData.Rows[i][j].ToString().Length.ToString();refmaxlength = dtLogData.Rows[i][j].ToString().Length;}
						else{	maxlength[j] = refmaxlength.ToString();}
					}
					//	MessageBox.Show(j.ToString()+"" + maxlength[j].ToString());
				}
				if (dtLogData.Rows.Count > 0)
				{
					sReport.AppendLine();
					sReport.Append("Log Data:").AppendLine();
					sReport.Append("--------------------------------------------------------------------------------").AppendLine();
					// Loop through the Alarm table header
					foreach (DataColumn dc in dtLogData.Columns)
					{
						count=count+1;
						/*if(count==1)//|| count==2 || count==3
						{
							string columnnametoprint =dc.ColumnName;
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[0]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}*/
						if(count==1)//|| count==2 || count==3
						{
							string columnnametoprint =dc.ColumnName;
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[0]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}
						else if(count==2)
						{
							string columnnametoprint = "Blender Speed (RPM)";
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[1]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}
						/*else if(count==4)
						{
							string columnnametoprint = dc.ColumnName;
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[3]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}
						else if(count==5)
						{
							string columnnametoprint = dc.ColumnName;
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[4]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}
						else if(count==6)
						{
							string columnnametoprint = dc.ColumnName;
							columnnametoprint = columnnametoprint.PadRight(Convert.ToInt32(maxlength[5]),' ');
							sReport.Append(columnnametoprint + " | ").ToString();
						}*/
					}
					sReport.AppendLine();
					sReport.Append("--------------------------------------------------------------------------------").AppendLine();
					count=0;
					foreach (DataRow DR in dtLogData.Rows)
					{
						foreach(DataColumn dc in dtLogData.Columns)
						{
							count=count+1;
							var field1 = DR[dc];
							if(count==1)//|| count==2 || count==3
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[0]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}
							else if( count==2 )
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[1]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}
							/*else if( count==3 )
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[2]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}
							else if(count==4)
							{
								string columnvaluetoprint = field1.ToString();
								columnvaluetoprint = columnvaluetoprint.PadRight(Convert.ToInt32(maxlength[3]),' ');
								sReport.Append(columnvaluetoprint + " | ").ToString();
							}*/
						}
						count=0;
						sReport.AppendLine();
						OpenPort("COM5", 9600,Parity.None,StopBits.One,8);
						m_port.Write(sReport.ToString());
						m_port.Close();
						sReport.Remove(0,sReport.Length);
						sReport.AppendLine();

					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}
	}
}




For reference attached herewith screenshot of application and code snippet.

Please do needful.

Thanks & Regards

MTrush

DataGridView Custom format for phone number

$
0
0

Hello everyone!  I am trying to do a phone number custom format for a column in a DataGridView, but nothing I try works!  Any ideas on how to fix this?  Here's my code:

        private void tbl_alunosDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            try
            {
                this.tbl_alunosDataGridView.Columns["TelFixo"].DefaultCellStyle.Format = "(##) ####-####";
                this.tbl_alunosDataGridView.Columns["TelCelular"].DefaultCellStyle.Format = "(##) #####-####";
            }
            catch (Exception)
            {
            }
        }


jcrcarmo

How can I throw this NullReferenceException

$
0
0

My code as follow,when the loop running, if return null value, it will stop, I tried throw it, or skip, but not success.

How can I code it

When null return, skip it, and keep the loop go on ?

Many thanks

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using HtmlAgilityPack;

using System.IO;

using System.Globalization;

namespace GetVol

{

   class Program

   {

       static void Main(string[] args)

       {

           int counter = 0;

           string line;

           TextWriter writer = File.CreateText($"C:\\stocks\\{DateTime.Now.ToString("yyyyMMdd")}.txt");

           writer.Close();

           string dayfile = ($"C:\\stocks\\{DateTime.Now.ToString("yyyyMMdd")}.txt");

           // Read the file and display it line by line.

           StreamReader file =

           new System.IO.StreamReader("c:\\stocks\\symbols.txt");

           while ((line = file.ReadLine()) != null)

               Console.WriteLine("please wait");

           {

               HtmlWeb webClient = new HtmlWeb();

               HtmlAgilityPack.HtmlDocument doc = webClient.Load($"https://uk.finance.yahoo.com/q/hp?s={line}");

               string name = doc.DocumentNode.SelectSingleNode(@"/html/body/div/div/div/div/div/div/div/div/h2").InnerText;

               string yprice = doc.DocumentNode.SelectSingleNode(@"//table[@class='yfnc_datamodoutline1']//table/tr[2]/td[@class='yfnc_tabledata1'][7]").InnerText;

               if (name != null && yprice != null)



                   {

                       File.AppendAllText(dayfile, name + Environment.NewLine);

                       Console.WriteLine(name);

                   }



               counter++;

           }

           Console.ReadKey();

       }

   }

}



Viewing all 31927 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>