Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

Transaction usage

$
0
0

Hi,

I would like to implement a daily job in order to read from a database table if there are results, it will insert into two different tables and finally updates the record which is being read from the original table. Is the transaction usage is correct? Can you give me feedback, please?

using log4net;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DailyPINReconJob
{
    class Program
    {
       
        private static readonly log4net.ILog log1 = LogManager.GetLogger("FileAppenderError");
        private static readonly log4net.ILog log2 = LogManager.GetLogger("FileAppenderLog");

        static void Main(string[] args)
        {

			SqlTransaction trans; 
			
            try
            {
                DateTime runday = DateTime.Today;
                if (args.Length > 0)
                {
                    Console.WriteLine(args[0].ToString());
                    runday = DateTime.Parse(args[0].ToString());
                }
                using (var conn = new SqlConnection())
                {
                    conn.ConnectionString ="Server=(localdb)\\MSSQLLocalDB; Initial Catalog=Test; Integrated Security=True; MultipleActiveResultSets=True; Trusted_Connection=yes;";
                    conn.Open();
					//Transaction
					trans = connection.BeginTransaction(); 
                    var command = new SqlCommand("SELECT cf.productCode, cf.productDescription, cf.quantity, cf.unitPrice, cf.totalPrice, cf.currency, cf.totalPayablePrice, c.serial, c.pin, c.expiryDate, cf.referenceId, Id FROM [GameConfirmResponses] cf INNER JOIN [Coupons] c ON cf.Id = c.confirmResponseID WHERE cf.purchaseStatusDate>=@Today AND cf.purchaseStatusDate<DATEADD(day,1,@Today) and cf.status in (0,2) and cf.service != 'OUR'", conn, trans);
                    command.Parameters.Add(new SqlParameter("Today", runday));

                  

                    using (var reader = command.ExecuteReader())
                    {
                        Console.WriteLine("FirstColumn\tSecond Column\t\tThird Column\t\tForth Column\t");

                     
                        

                        while (reader.Read())
                        {
                            Console.WriteLine($"{reader[0]} \t | {reader[1]} \t | {reader[2]} \t | {reader[3]} \t | {reader[4]} \t | {reader[5]} \t | {reader[6]} \t | {reader[7]} \t | {reader[8]} \t | {reader[9]}");

                            Console.WriteLine("INSERT INTO command");

                            var insertCommand = new SqlCommand("INSERT INTO [GameBanks] (productCode, productDescription, quantity, unitPrice, totalPrice, currency, estimateUnitPrice, used, version, status, referenceId, validatedToken) VALUES (@productCode, @productDescription, @quantity, @unitPrice, @totalPrice, @currency, @estimateUnitPrice, @used, @version, @status, @referenceId, @validatedToken) SELECT SCOPE_IDENTITY(); ", conn, trans);

                            var insertDetailCommand = new SqlCommand("INSERT INTO [GameBankPins]  (serial, pin, expiryDate, GameBankID) VALUES ( @serial, @pin, @expiryDate, @GameBankID) ", conn, trans);
							var updateCommand = new SqlCommand("UPDATE [GameConfirmResponses]  SET used = 1 Where Id = @Id ", conn, trans);

                            
                            int used = 0;

                            insertCommand.Parameters.Add(new SqlParameter("productCode", reader.GetString(0)));
                            insertCommand.Parameters.Add(new SqlParameter("productDescription", reader.GetString(1)));
                            insertCommand.Parameters.Add(new SqlParameter("quantity", 1));
                            insertCommand.Parameters.Add(new SqlParameter("unitPrice", reader.GetDouble(3)));
                            insertCommand.Parameters.Add(new SqlParameter("totalPrice", reader.GetDouble(4) / reader.GetInt32(2)));
                            insertCommand.Parameters.Add(new SqlParameter("currency", reader.GetString(5)));
                            insertCommand.Parameters.Add(new SqlParameter("estimateUnitPrice", Math.Round((reader.GetDouble(6) / reader.GetInt32(2)), 2, MidpointRounding.ToEven)));
                            insertCommand.Parameters.Add(new SqlParameter("used", used));
                            insertCommand.Parameters.Add(new SqlParameter("version", "V1"));
                            insertCommand.Parameters.Add(new SqlParameter("status",used));
                            insertCommand.Parameters.Add(new SqlParameter("referenceId", new Guid("00000000-0000-0000-0000-000000000000")));
                            insertCommand.Parameters.Add(new SqlParameter("validatedToken", reader.GetGuid(10)+" Imported from Service Database"));


                            var insertedID = insertCommand.ExecuteScalar();


                            
                            insertDetailCommand.Parameters.Add(new SqlParameter("serial", reader.GetString(7)));
                            insertDetailCommand.Parameters.Add(new SqlParameter("pin", reader.GetString(8)));
                            insertDetailCommand.Parameters.Add(new SqlParameter("expiryDate", DateTime.Parse(reader[9].ToString())));
                            insertDetailCommand.Parameters.Add(new SqlParameter("GameBankID", insertedID));
							updateCommand.Parameters.Add(new SqlParameter("Id", reader.GetInt32(12)));


                            insertDetailCommand.ExecuteNonQuery();
							
							//COMMIT
							trans.Commit();
							
                            log2.Info(
                                $"{reader[0]};{reader[1]};{reader[2]};{reader[3]};{reader[4]};{reader[5]};{reader[6]};{reader[7]};{reader[8]};{reader[9]};{reader[10]}");
                            Console.WriteLine("Done! Press enter to move to the next step");

                        }
                    }
                    Console.WriteLine("Data displayed! Now press enter to move to the next section!");

                }
            }
            catch (Exception ex)
            {
				//ROLLBACK
				trans.Rollback();
				
                log1.Error("Error Message: " + ex.Message.ToString(), ex);
            }
        }
    }
}


Viewing all articles
Browse latest Browse all 1698

Trending Articles