How to store fingerprint template to sql server - sql

I am having trouble in storing fpt templates in SQL Server.
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
//imports
using DHELTASSys.AuditTrail;
using DHELTASSys.Modules;
namespace Enrollment
{
delegate void Function(); // a simple delegate for marshalling calls from event handlers to the GUI thread
public partial class CreateAccount : Form
{
HRModuleBL obj = new HRModuleBL();
DHELTASSysAuditTrail audit = new DHELTASSysAuditTrail();
public CreateAccount(int emp_id)
{
InitializeComponent();
audit.Emp_id = emp_id;
}
protected void EmptyFields()
{
}
private void CloseButton_Click(object sender, EventArgs e)
{
Close();
}
private void OnTemplate(DPFP.Template template)
{
this.Invoke(new Function(delegate()
{
Template = template;
VerifyButton.Enabled = SaveButton.Enabled = (Template != null);
if (Template != null)
MessageBox.Show("The fingerprint template is ready for verification and saving", "Fingerprint Enrollment");
else
MessageBox.Show("The fingerprint template is not valid. Repeat fingerprint enrollment.", "Fingerprint Enrollment");
}));
}
private DPFP.Template Template;
private void EnrollButton_Click(object sender, EventArgs e)
{
EnrollmentForm Enroller = new EnrollmentForm();
Enroller.OnTemplate += this.OnTemplate;
Enroller.ShowDialog();
}
private void SaveButton_Click(object sender, EventArgs e)
{
obj.Last_name = txtLastname.Text;
obj.First_name = txtFirstName.Text;
obj.Middle_name = txtMiddleName.Text;
obj.Position_name = cmbPosition.Text;
obj.Company_name = cmbCompany.Text;
obj.Password = txtTempPassword.Text;
obj.Department_name = cmbDepartment.Text;
if (obj.Last_name == string.Empty) //Validation for empty texts
{
MessageBox.Show("Last name can't be empty!");
} else if (obj.First_name == string.Empty)
{
MessageBox.Show("First name can't be empty!");
}
else if (obj.Middle_name == string.Empty)
{
MessageBox.Show("Middle name can't be empty!");
}
else if (obj.Position_name == string.Empty)
{
MessageBox.Show("Position name can't be empty!");
}
else if (obj.Department_name == string.Empty)
{
MessageBox.Show("Deparment can't be empty!");
}
else if (obj.Company_name == string.Empty)
{
MessageBox.Show("Company name can't be empty!");
}
else if (obj.Password == string.Empty)
{
MessageBox.Show("Password can't be empty!");
}
else if (txtConfirmTempPassword.Text == string.Empty)
{
MessageBox.Show("Please verify your input password!");
}
else
{
if (txtTempPassword.Text != txtConfirmTempPassword.Text)
{
MessageBox.Show("Password does not match", "Password Mismatch",
MessageBoxButtons.OK);
}
else
{
MemoryStream fingerprintData = new MemoryStream();
Template.Serialize(fingerprintData);
fingerprintData.Position = 0;
BinaryReader br = new BinaryReader(fingerprintData);
byte[] bytes = br.ReadBytes((Int32)fingerprintData.Length);
obj.Biometric_code = bytes;
obj.AddAccountSetTempPassword();
audit.AddAuditTrail("Created account for " + obj.First_name + " " + obj.Last_name + ".");
MessageBox.Show("Account Created for " + txtLastname.Text + "," + txtFirstName.Text);
txtConfirmTempPassword.Text = "";
txtFirstName.Text = "";
txtLastname.Text = "";
txtMiddleName.Text = "";
txtTempPassword.Text = "";
cmbCompany.Text = "";
cmbDepartment.Text = "";
cmbPosition.Text = "";
}
}
}
private void VerifyButton_Click(object sender, EventArgs e)
{
VerificationForm Verifier = new VerificationForm();
Verifier.Verify(Template);
}
}
}
Wherein I have initiated the object obj for the class used to insert data to SQL Server.
Using the AddAccountSetTempPassword() method, I store the data into the database.
Problem is, when I look into the database, the image field for all fingerprint data is written as this 0x53797374656D2E427974655B5D.
UPDATE #1
Here is the class that I used to insert data into the database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Imports
using System.Data;
using DHELTASSys.DataAccess;
using DHELTASSys.AuditTrail;
namespace DHELTASSys.Modules
{
class HRModuleBL
{
DHELTASSysAuditTrail audit = new DHELTASSysAuditTrail();
private int emp_id;
public int Emp_id
{
get { return emp_id; }
set { emp_id = value; }
}
private string password;
public string Password
{
get { return password; }
set { password = value; }
}
private string last_name;
public string Last_name
{
get { return last_name; }
set { last_name = value; }
}
private string first_name;
public string First_name
{
get { return first_name; }
set { first_name = value; }
}
private string middle_name;
public string Middle_name
{
get { return middle_name; }
set { middle_name = value; }
}
private string position_name;
public string Position_name
{
get { return position_name; }
set { position_name = value; }
}
private string company_name;
public string Company_name
{
get { return company_name; }
set { company_name = value; }
}
private string email;
public string Email
{
get { return email; }
set { email = value; }
}
private string gender;
public string Gender
{
get { return gender; }
set { gender = value; }
}
private string address;
public string Address
{
get { return address; }
set { address = value; }
}
private string primary_Number;
public string Primary_Number
{
get { return primary_Number; }
set { primary_Number = value; }
}
private string alternative_Number;
public string Alternative_Number
{
get { return alternative_Number; }
set { alternative_Number = value; }
}
private string city;
public string City
{
get { return city; }
set { city = value; }
}
private DateTime birthdate;
public DateTime Birthdate
{
get { return birthdate; }
set { birthdate = value; }
}
private int sss_Number;
public int Sss_Number
{
get { return sss_Number; }
set { sss_Number = value; }
}
private int philHealth_number;
public int Philhealth_number
{
get { return philHealth_number; }
set { philHealth_number = value; }
}
private byte[] biometric_code;
public byte[] Biometric_code
{
get { return biometric_code; }
set { biometric_code = value; }
}
private string employee_status;
public string Employee_status
{
get { return employee_status; }
set { employee_status = value; }
}
private int company_id;
public int Company_id
{
get { return company_id; }
set { company_id = value; }
}
private string department_name;
public string Department_name
{
get { return department_name; }
set { department_name = value; }
}
//Methods
//Create account and set temporary password for employee
public void AddAccountSetTempPassword()
{
if (Position_name == "Supervisor") //If employee is supervisor
{
string cmd = "EXECUTE AddAccountSetTempPassword '" + Password + "',"
+ "'" + Last_name + "',"
+ "'" + First_name + "',"
+ "'" + Middle_name + "',"
+ "'" + Position_name + "',"
+ "'" + Company_name + "',"
+ "'" + Department_name + "',"
+ "'" + Biometric_code + "'";
DHELTASSysDataAccess.Modify(cmd);
string cmdTwo = "Execute AddSupervisor";
DHELTASSysDataAccess.Modify(cmdTwo);
}
else //If employee isn't a supervisor
{
string cmd = "EXECUTE AddAccountSetTempPassword '" + Password + "',"
+ "'" + Last_name + "',"
+ "'" + First_name + "',"
+ "'" + Middle_name + "',"
+ "'" + Position_name + "',"
+ "'" + Company_name + "',"
+ "'" + Department_name + "',"
+ "'" + Biometric_code + "'";
DHELTASSysDataAccess.Modify(cmd);
}
}
//Employee will enter permanent password for account
public void AddPermanentPasswordForAccount()
{
string cmd = "EXECUTE AddPermanentPasswordForAccount"
+ "'" + Password + "',"
+ "'" + Emp_id + "',";
DHELTASSysDataAccess.Modify(cmd);
//DHELTASSysAuditTrail.AddAuditTrail( "Changed password.");
}
//Employee adds his/her account details
public void AddAccountDetails()
{
string cmd = "EXECUTE AddAccountDetails"
+ "'" + Email + "',"
+ "'" + Gender + "',"
+ "'" + Address + "',"
+ "'" + Primary_Number + "',"
+ "'" + Alternative_Number + "',"
+ "'" + City + "',"
+ "'" + Birthdate + "',"
+ "'" + Sss_Number + "',"
+ "'" + Philhealth_number + "',"
+ "'" + Emp_id + "'";
DHELTASSysDataAccess.Modify(cmd);
//DHELTASSysAuditTrail.AddAuditTrail("Account details updated.");
}
//Displays all employees' information
public DataTable ViewEmployeeInformation()
{
string cmd = "EXECUTE ViewEmployeeInformation"
+ "'" + Company_id + "'";
DataTable dtEmployees = DHELTASSysDataAccess.Select(cmd);
return dtEmployees;
}
//Verifies account login in the forms application
public DataTable AccountEnrollmentLogin()
{
string cmd = "EXECUTE AccountEnrollmentLogin"
+ "'" + Emp_id + "',"
+ "'" + Password + "'";
DataTable dt = DHELTASSysDataAccess.Select(cmd);
return dt;
}
//Check if HR Manager
public DataTable CheckIfHRManager()
{
string cmd = "EXECUTE CheckIfHRManager"
+ "'" + Emp_id + "'";
DataTable dt = DHELTASSysDataAccess.Select(cmd);
return dt;
}
}
}
And the table looks like this:
table : employee
emp_id->int->PK
password->nvarchar(MAX)
last_name->varchar(50)
first_name->varchar(50)
middle_name->varchar(50)
position_id->int->FK
department_id->int->FK
company_id->int->FK
email_address->varchar(50)
gender->varchar(10)
address->varchar(100)
primary_contact_number->varchar(20)
alternative_contact_number->varchar(20)
city->varchar(50)
birthdate->date
sssNumber->int
philhealth_number->int
employee_status->bit
biometrics_image->image
I wish to convert the template into bytes to save it into the database.
Thanks in advance.

Related

Entity framework in order

Sourcefile and file name are the source path . Archive folder and the archive filename is the destination folder . The value of the input file should be moved to the destination file.Getting error while copying file from source to destination. Showing "File has been already created". Please let me know how to find the directory of a source file without hardcode. How can I write the valid details in another file in the XML Format.
using System; using System.Collections.Generic;using System.IO;
using System.Linq;using System.Security; using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using EmployeeValidation;
using static EmployeeValidation.FundsValidatorException;
namespace FundsValidator
{
public class empValidator
{
public bool ProcessData(string sourceFolder, string fileName, string archiveFolder, string archiveFileName, SqlConnection connection)
{
List<Order> Orders = ReadAllDataFromInputFile(sourceFolder,fileName);
//Step 2
//SetValidationFlag
List<Order> ValidOrder = SetValidationFlag(Orders);
//Step 3
//InsertOrderData
bool insertBit = InsertOrderData(ValidOrder, connection);
//Step 4
//GetProductsCommission
DataTable dtprodcomm = GetProductsCommission(connection);
//Step 5
//archive file
bool archive = CopyToArchive( sourceFileName, sourceFilePath, archiveFileName, archiveFilePath)
return true;
}
public List<Order> ReadAllDataFromInputFile(string sourceFolder, string fileName)
{
List<Order> inputlist = null;
{
try
{
inputlist = new List<Order>();
var inputlines = File.ReadAllLines(sourceFolder + fileName);
foreach (var item in inputlines)
{
string[] datas = item.Split(',');
Order orderdetails = new Order()
{
OrderId = datas[0],
SalesPersonId = datas[1],
OrderDate = Convert.ToDateTime(datas[2]).ToShortDateString(),
ModelNbr = datas[3],
Quantity = datas[4],
CustomerId = datas[5],
DeliveryDate = datas[6]
};
inputlist.Add(orderdetails);
}
}
catch(OrderProcessorException)
{
throw new OrderProcessorException();
}
}
return inputlist;
}
public List<Order> SetValidationFlag(List<Order> Orders)
{
List<Order> validList = null;
validList = new List<Order>();
int num = 0;
DateTime dtOrderdate;
DateTime dtdeliverydate;
if (Orders != null && Orders.Count >0)
{
foreach(var item in Orders)
{
if(int.TryParse(item.OrderId, out num) &&
item.SalesPersonId.StartsWith("SP") && item.SalesPersonId.Substring(2).Length == 3 && int.TryParse(item.SalesPersonId.Substring(2), out num) &&
DateTime.TryParse(item.OrderDate, out dtOrderdate) &&
item.ModelNbr.StartsWith("ML") && item.ModelNbr.Substring(2).Length == 3 && int.TryParse(item.ModelNbr.Substring(2), out num) &&
int.TryParse(item.Quantity, out num) && DateTime.TryParse(item.DeliveryDate, out dtdeliverydate) && (Convert.ToDateTime(item.DeliveryDate) - Convert.ToDateTime(item.OrderDate)).TotalDays > 7)
{
item.ValidFlag = "V";
}
else
{
item.ValidFlag = "E";
}
validList.Add(item);
}
}
return validList;
}
public bool InsertOrderData(List<Order> Orders, SqlConnection connectionString)
{
bool bret = true;
{
if(Orders !=null && Orders.Count >0)
{
foreach(var item in Orders)
{
using (SqlCommand command = connectionString.CreateCommand())
{
command.CommandText = "Insert into SBA.Orders(OrderId,SalesPersonId,OrderDate,ModelNbr,Quantity,CustomerId,Deliverydate,ValidFlag) Values('" + item.OrderId + "','" + item.SalesPersonId + "','" + item.OrderDate + "','" + item.ModelNbr + "','" + item.Quantity + "','" + item.CustomerId + "','" + item.DeliveryDate + "','" + item.ValidFlag + "')";
command.Connection = connectionString;
connectionString.Open();
int count = command.ExecuteNonQuery();
connectionString.Close();
if (count > 0)
{
bret = true;
}
else
bret = false;
}
}
}
else
{
bret = false;
}
}
return bret;
}
public DataTable GetProductsCommission(SqlConnection connectionString)
{
DataTable dtProductsCommission = null;
using (SqlCommand command = connectionString.CreateCommand())
{
command.CommandText = "Select ModelNbr,Commission_Percentage,Base_Price from SBA.Product_Commission";
command.Connection = connectionString;
connectionString.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
dtProductsCommission = ds.Tables[0];
}
return dtProductsCommission;
}
public bool InsertCommissionData(List<Order> Orders, DataTable dtProductsCommission, SqlConnection connectionString)
{
bool bret = true;
if (Orders != null && Orders.Count > 0 && dtProductsCommission.Rows.Count > 0)
{
foreach (var item in Orders)
{
if (item.ValidFlag == "V")
{
foreach (DataRow dr in dtProductsCommission.Rows)
{
float commamt = Convert.ToInt32(dr["Commission_Percentage"]) * Convert.ToInt32(dr["Base_Price"]) * Convert.ToInt32(item.Quantity);
using (SqlCommand cmd = connectionString.CreateCommand())
{
cmd.CommandText = "Insert into SBA.Order_Commission(OrderId,CommissionAmt) Values('" + item.OrderId + "','" + commamt + "')";
connectionString.Open();
cmd.ExecuteNonQuery();
connectionString.Close();
bret = true;
}
}
}
}
}
else
{
bret = false;
}
return bret;
}
public bool CopyToArchive(string sourceFileName, string sourceFilePath, string archiveFileName, string archiveFilePath)
{
bool bret = true;
if(!File.Exists(archiveFilePath + archiveFileName))
{
File.Copy(sourceFilePath + sourceFileName, archiveFilePath + archiveFileName);
}
else
{
File.Delete(archiveFilePath + archiveFileName);
File.Copy(sourceFilePath + sourceFileName, archiveFilePath + archiveFileName);
}
return bret;
}
}
}
I have fixed this problem.Please refer this program for more details
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.Xml.Serialization;
using System.Text.RegularExpressions;
using System.Xml;
namespace EmployeeValidation
{
public class FundsValidator
{
public void ProcessData(string FilePath, string FileName, SqlConnection connection, string errorFilename, string errorFilepath)
{
List<Funds> Alllstfunds = new List<Funds>();
List<Funds> Validlstfunds = new List<Funds>();
Alllstfunds= ReadValuesfromInputfile(FilePath, FileName);
Validlstfunds = GetValidFunds(Alllstfunds, errorFilename, errorFilepath);
SaveValidListToDB(Validlstfunds,connection);
List<Funds> Removeddup= GerPerFundDetails(Validlstfunds);
CalculateNavandSaveToDatabase(Removeddup,connection);
}
public List<Funds> ReadValuesfromInputfile(string FilePath, string FileName)
{
List<Funds> AllListfunds = new List<Funds>();
string s1= null;
StreamReader sw = File.OpenText(FilePath + FileName);
while ((s1 = sw.ReadLine()) != null)
{
Funds fund = new Funds();
string[] s = s1.Split(',');
fund.FundsID = s[0].ToString();
fund.SubfundID = s[1].ToString();
fund.Asset = s[2].ToString();
fund.La = s[3].ToString();
fund.o = s[4].ToString();
AllListfunds.Add(fund);
}
return AllListfunds;
}
public List<Funds> GetValidFunds(List<Funds> Alllstfunds, string errorFilename,string errorFilepath)
{
try
{
List<Funds> validlist = new List<Funds>();
List<Funds> Invalid = new List<Funds>();
foreach (Funds x in Alllstfunds)
{
bool valid = true;
valid = valid && (!string.IsNullOrEmpty(x.FundsID) && x.FundsID.StartsWith("F")) && x.FundsID.Length == 4 && x.FundsID.Substring(1).Length == 3 && x.FundsID.Substring(1).All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(x.SubfundID)) && x.SubfundID.StartsWith("SF") && x.SubfundID.Length == 5 && x.SubfundID.Substring(2).Length == 3 && x.SubfundID.Substring(2).All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(x.Asset)) && x.Asset.All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(x.La)) && x.La.All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(x.o)) && x.o.All(char.IsDigit);
if (valid)
{
validlist.Add(x);
}
else
{
Invalid.Add(x);
}
}
SaveInValidinErrorTxt(Invalid, errorFilename, errorFilepath);
return validlist;
}
catch (Exception ex)
{
throw new FundsValidatorException(ex.Message);
}
}
public void SaveInValidinErrorTxt(List<Funds> Invalid,string errorFilename,string errorFilepath)
{
if (Invalid.Count > 0 && Invalid != null)
{
if (!File.Exists(errorFilepath + errorFilename))
{
var i=File.Create(errorFilepath + errorFilename);
i.Close();
}
StreamWriter sw = File.AppendText(errorFilepath+errorFilename);
foreach (Funds f in Invalid)
{
sw.WriteLine(f.FundsID+","+f.SubfundID+","+f.Asset+","+f.La+","+f.o);
}
sw.Flush();
sw.Close();
}
}
public void SaveValidListToDB(List<Funds> Validlstfunds, SqlConnection connection)
{
try
{
foreach (Funds f in Validlstfunds)
{
connection.Open();
SqlCommand cmd = new SqlCommand(("Insert into SBA.Fund_Details (FundId,SubFundId,Assets,Liabilities,OutstandingShares) Values ( '" + f.FundsID + "','" + f.SubfundID + "','" + f.Asset + "','" + f.La + "','" + f.o + "')"), connection);
int i = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
connection.Close();
}
}
catch (Exception ex)
{
throw new FundsValidatorException(ex.Message);
}
}
public List<Funds> GerPerFundDetails(List<Funds> Validlists)
{
List<string> s = new List<string>();
List<Funds> RemoveDup = new List<Funds>();
String[] r = (from a in Validlists
select a.FundsID).Distinct().ToArray();
foreach (String x in r)
{
int assetnum = 0;
int lanum = 0;
int onum=0;
foreach (Funds q in Validlists)
{
if (x.ToString() == q.FundsID)
{
assetnum = assetnum + int.Parse(q.Asset);
lanum=lanum+int.Parse(q.La);
onum=onum+int.Parse(q.o);
}
}
Funds f= new Funds();
f.FundsID=x.ToString();
f.Asset=assetnum.ToString();
f.La=lanum.ToString();
f.o= onum.ToString();
RemoveDup.Add(f);
}
return RemoveDup;
}
public void CalculateNavandSaveToDatabase(List<Funds> Removeddup,SqlConnection connection)
{
List<Funds> NAVClaculated = new List<Funds>();
foreach(Funds item in Removeddup)
{
item.NAV= (float)(Math.Round(((float.Parse(item.Asset) - float.Parse(item.La))/(float.Parse(item.o))),2));
NAVClaculated.Add(item);
}
foreach (Funds f in NAVClaculated)
{
connection.Open();
SqlCommand cmd = new SqlCommand(("Insert into SBA.Nav_Report (FundId,Assets,Liabilities,OutstandingShares,Nav) Values ( '" + f.FundsID + "','" + f.Asset + "','" + f.La + "','" + f.o +"','"+f.NAV+ "')"), connection);
int i = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
connection.Close();
}
}
}
}
namespace Tarriffs
{
public class Tariff
{
public string UserId { get; set; }
public string UserName { get; set; }
public string Category { get; set; }
public string LastMeterReading { get; set; }
public string CurrentMeterReading { get; set; }
public string ReadingDate { get; set; }
public string NoofUnits { get; set; }
public string CalculatedAmount { get; set; }
}
class Program
{
static void Main(string[] args)
{
string inputfile = #"D:\Tarriffs\Input file\Tarriff_0919.txt";
List<Tariff> read = new List<Tariff>();
StreamReader sr = File.OpenText(inputfile);
string s= null;
while((s= sr.ReadLine())!=null)
{
string[] item = s.Split(',');
Tariff tar = new Tariff();
tar.UserId= item[0];
tar.UserName= item[1];
tar.Category= item[2];
tar.LastMeterReading= item[3];
tar.CurrentMeterReading= item[4];
tar.ReadingDate= item[5];
bool valid = validandlogger(tar.UserId, tar.UserName, tar.Category, tar.LastMeterReading, tar.CurrentMeterReading, tar.ReadingDate);
if (valid)
{
double[] tarriffcalculation = tarriffcalc(tar.LastMeterReading, tar.CurrentMeterReading);
Tariff final = new Tariff();
final.UserId = item[0];
final.UserName = item[1];
final.NoofUnits = tarriffcalculation[0].ToString();
final.CalculatedAmount = tarriffcalculation[1].ToString();
SqlConnection conn= new SqlConnection(#"Data Source=NA03OSDVP00746\SQLEXPRESS;Initial Catalog=DBTarriffValidation;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("Insert into dbo.custom values ('" + final.UserId + "','" + final.UserName + "','" + final.NoofUnits + "','" + final.CalculatedAmount + "')", conn);
int i = cmd.ExecuteNonQuery();
conn.Close();
}
}
}
public static bool validandlogger(string UserId, string UserName, string Category, string LastMeterReading, string CurrentMeterReading, string ReadingDate)
{
bool valid = true;
DateTime dt;
Regex name = new Regex("^[a-zA-Z0-9]{6}$");
valid = valid && (!string.IsNullOrEmpty(UserId)) && UserId.All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(UserName)) && name.IsMatch(UserName);
string[] vcategory = { "COM", "DOM", "OTD" };
valid = valid && vcategory.Contains(Category);
valid = valid && LastMeterReading.All(char.IsDigit);
valid = valid && CurrentMeterReading.All(char.IsDigit);
valid = valid && DateTime.TryParseExact(ReadingDate, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
if (!valid)
{
string errortextfile = #"D:\Tarriffs\Error_log\";
string errorfile = "Error_"+DateTime.Now.ToString("MMyyyy")+".txt";
if (!File.Exists(errortextfile + errorfile))
{
var i = File.Create(errortextfile + errorfile);
i.Close();
}
StreamWriter sw = File.AppendText(errortextfile + errorfile);
sw.WriteLine(UserId + "," + UserName + "," + Category + "," + LastMeterReading + "," + CurrentMeterReading + "," + ReadingDate);
sw.Flush();
sw.Close();
}
else
{
return true;
}
return false;
}
public static double[] tarriffcalc(string LastMeterReading, string CurrentMeterReading)
{
int LMeterReading = 0;
int CMeterReading = 0;
LMeterReading = int.Parse(LastMeterReading);
CMeterReading = int.Parse(CurrentMeterReading);
int units = CMeterReading - LMeterReading;
double totalamount = 0;
if (units <= 100)
{
var baserate = 20;
totalamount = (units * 1) + baserate;
}
else if (units <= 200)
{
var baserate = 20;
totalamount = (units * 1.5) + baserate;
}
else if (units <= 500)
{
var baserate = 40;
totalamount = 250 +((units-200)*3)+baserate;
}
else if (units > 500)
{
var baserate = 40;
totalamount = 1700 + ((units - 500) * 5.75) + baserate;
}
return new double[] {units,totalamount};
}
}
}

migrating CQ 5.6.1(jdk 1.7) to AEM 6.4(jdk 1.8), Unable to deserialze byte array while reading session from Cassandra using Serializer<SimpleSession>

i am migrating java bundles from CQ 5.6.1 to AEM 6.4, bundle is working in jdk 1.7,
code is using apache shiro to serealize and deserialize session, here is the code to save and read session stored in Cassandra
it works good with AEM 5.6.1 and 6.1 (works in jdk 1.7) when i migrate it to AEM 6.4 (working in jdk 1.8) code is
giving exception in "method doReadSession" when it is trying to deserialize session in bite array
it throw an exception
In method doReadSession where it return "serializer.deserialize(bytes)"
exception thrown is
Caused by: org.apache.shiro.io.SerializationException: Unable to deserialze argument byte array.
at org.apache.shiro.io.DefaultSerializer.deserialize(DefaultSerializer.java:82)
at com.xyz.web.platform.common.security.shiro.cassandra.CassandraSessionDAO.doReadSession(CassandraSessionDAO.java:252)
at org.apache.shiro.session.mgt.eis.AbstractSessionDAO.readSession(AbstractSessionDAO.java:168)
at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSessionFromDataSource(DefaultSessionManager.java:236)
import com.xyz.web.platform.common.security.shiro.session.idgenerator.UUIDSessionIdGenerator;
import com.xyz.web.platform.common.tracelogging.TMTraceLogger;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Collections;
import org.apache.shiro.ShiroException;
import org.apache.shiro.io.DefaultSerializer;
import org.apache.shiro.io.Serializer;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.apache.shiro.util.Destroyable;
import org.apache.shiro.util.Initializable;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
public class CassandraSessionDAO extends AbstractSessionDAO implements Initializable, Destroyable {
private static final TMTraceLogger CASSANDRA_LOGGER = TMTraceLogger
.getLogger("cassandraLogger" + "." + CassandraSessionDAO.class.getName());
private String DEFAULT_CONSISTENCY_LEVEL = ConsistencyLevel.LOCAL_QUORUM.toString();
private static final String DEFAULT_CACHING = "ROWS_ONLY";
private static final String DEFAULT_DATA_CENTER = "DC1";
private String keyspaceName;
private String tableName;
private Cluster cluster;
private Serializer<SimpleSession> serializer;
private String readConsistencyLevel;
private String writeConsistencyLevel;
private String defaultTTL;
private String gc_grace_seconds;
private String caching = DEFAULT_CACHING;
private String dataCenter = DEFAULT_DATA_CENTER;
private PreparedStatement deletePreparedStatement;
private PreparedStatement savePreparedStatement;
private PreparedStatement readPreparedStatement;
private com.datastax.driver.core.Session cassandraSession;
public CassandraSessionDAO() {
setSessionIdGenerator(new UUIDSessionIdGenerator());
this.serializer = new DefaultSerializer<SimpleSession>();
}
private SimpleSession assertSimpleSession(Session session) {
if (!(session instanceof SimpleSession)) {
throw new IllegalArgumentException(CassandraSessionDAO.class.getName() + " implementations only support "
+ SimpleSession.class.getName() + " instances.");
}
return (SimpleSession) session;
}
public Cluster getCluster() {
return cluster;
}
public void setCluster(Cluster cluster) {
this.cluster = cluster;
}
public String getKeyspaceName() {
return keyspaceName;
}
public void setKeyspaceName(String keyspaceName) {
this.keyspaceName = keyspaceName;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getReadConsistencyLevel() {
return readConsistencyLevel;
}
public void setReadConsistencyLevel(String readConsistencyLevel) {
this.readConsistencyLevel = readConsistencyLevel;
}
public String getWriteConsistencyLevel() {
return writeConsistencyLevel;
}
public void setWriteConsistencyLevel(String writeConsistencyLevel) {
this.writeConsistencyLevel = writeConsistencyLevel;
}
public String getDefaultTTL() {
return defaultTTL;
}
public void setDefaultTTL(String defaultTTL) {
this.defaultTTL = defaultTTL;
}
public String getGc_grace_seconds() {
return gc_grace_seconds;
}
public void setGc_grace_seconds(String gc_grace_seconds) {
this.gc_grace_seconds = gc_grace_seconds;
}
public String getCaching() {
return caching;
}
public void setCaching(String caching) {
this.caching = caching;
}
public String getDataCenter() {
return dataCenter;
}
public void setDataCenter(String dataCenter) {
this.dataCenter = dataCenter;
}
public void init() throws ShiroException {
com.datastax.driver.core.Session systemSession = cluster.connect();
boolean create = false;
try {
if (!isKeyspacePresent(systemSession)) {
create = true;
createKeyspace(systemSession);
if (!isKeyspacePresent(systemSession)) {
throw new IllegalStateException("Unable to create keyspace " + keyspaceName);
}
}
} finally {
systemSession.shutdown();
}
cassandraSession = cluster.connect(keyspaceName);
if (create) {
createTable();
}
prepareReadStatement();
prepareSaveStatement();
prepareDeleteStatement();
}
public void destroy() throws Exception {
if (cassandraSession != null) {
cassandraSession.shutdown();
cluster.shutdown();
}
}
protected boolean isKeyspacePresent(com.datastax.driver.core.Session systemSession) {
PreparedStatement ps = systemSession.prepare("select * from system.schema_keyspaces");
BoundStatement bs = new BoundStatement(ps);
ResultSet results = systemSession.execute(bs);
// ResultSet results = systemSession.execute("select * from
// system.schema_keyspaces");
for (Row row : results) {
if (row.getString("keyspace_name").equalsIgnoreCase(keyspaceName)) {
return true;
}
}
return false;
}
protected void createKeyspace(com.datastax.driver.core.Session systemSession) {
String query = "create keyspace " + this.keyspaceName
+ " with replication = {'class' : 'NetworkTopologyStrategy', '" + dataCenter + "': 2};";
systemSession.execute(query);
}
protected void createTable() {
long defaultTTLLong = Long.parseLong(defaultTTL);
long gc_grace_secondsLong = Long.parseLong(gc_grace_seconds);
String query = "CREATE TABLE " + tableName + " ( " + " id varchar PRIMARY KEY, " + " start_ts timestamp, "
+ " stop_ts timestamp, " + " last_access_ts timestamp, " + " timeout bigint, "
+ " expired boolean, " + " host varchar, " + " serialized_value blob " + ") " + "WITH "
+ " gc_grace_seconds = " + gc_grace_secondsLong + " AND default_time_to_live = " + defaultTTLLong
+ " AND caching = '" + caching + "' AND " + " compaction = {'class':'LeveledCompactionStrategy'};";
cassandraSession.execute(query);
}
#Override
protected Serializable doCreate(Session session) {
SimpleSession ss = assertSimpleSession(session);
Serializable timeUuid = generateSessionId(session);
assignSessionId(ss, timeUuid);
save(ss);
return timeUuid;
}
#Override
protected Session doReadSession(Serializable sessionId) {
long startTime = System.currentTimeMillis();
if (CASSANDRA_LOGGER.isDebugEnabled()) {
CASSANDRA_LOGGER.logDebug("In the doReadSession()..");
CASSANDRA_LOGGER.logDebug("The start time is " + startTime + " ms");
}
// put a not-null & not-empty check
if (sessionId != null && !sessionId.equals("")) {
String id = sessionId.toString();
PreparedStatement ps = prepareReadStatement();
/*
* String query = "SELECT * from " + tableName + " where id = ?";
* PreparedStatement ps = cassandraSession.prepare(query);
*/
BoundStatement bs = new BoundStatement(ps);
bs.bind(id);
if (readConsistencyLevel == null) {
readConsistencyLevel = DEFAULT_CONSISTENCY_LEVEL;
}
bs.setConsistencyLevel(ConsistencyLevel.valueOf(readConsistencyLevel));
ResultSet results = cassandraSession.execute(bs);
for (Row row : results) {
String rowId = row.getString("id");
if (id.equals(rowId)) {
ByteBuffer buffer = row.getBytes("serialized_value");
if (buffer != null) {
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
return serializer.deserialize(bytes);
}
}
}
}
long endTime = System.currentTimeMillis();
long timeTaken = endTime - startTime;
if (CASSANDRA_LOGGER.isDebugEnabled()) {
CASSANDRA_LOGGER.logDebug("The total time taken is " + timeTaken + " ms");
}
return null;
}
private PreparedStatement prepareReadStatement() {
if (this.readPreparedStatement == null) {
String query = "SELECT * from " + tableName + " where id = ?";
this.readPreparedStatement = cassandraSession.prepare(query);
}
return this.readPreparedStatement;
}
// In CQL, insert and update are effectively the same, so we can use a single
// query for both:
protected void save(SimpleSession ss) {
// long timeoutInSeconds = ss.getTimeout() / 1000;
/*
* String query = "UPDATE " + tableName + " SET " + "start_ts = ?, " +
* "stop_ts = ?, " + "last_access_ts = ?, " + "timeout = ?, " + "expired = ?, "
* + "host = ?, " + "serialized_value = ? " + "WHERE " + "id = ?";
* PreparedStatement ps = cassandraSession.prepare(query);
*/
long startTime = System.currentTimeMillis();
if (CASSANDRA_LOGGER.isDebugEnabled()) {
CASSANDRA_LOGGER.logDebug("In the save()..");
CASSANDRA_LOGGER.logDebug("The start time is " + startTime + " ms");
}
PreparedStatement ps = prepareSaveStatement();
BoundStatement bs = new BoundStatement(ps);
byte[] serialized = serializer.serialize(ss);
ByteBuffer bytes = ByteBuffer.wrap(serialized);
bs.bind(ss.getStartTimestamp(), ss.getStopTimestamp() != null ? ss.getStartTimestamp() : null,
ss.getLastAccessTime(), ss.getTimeout(), ss.isExpired(), ss.getHost(), bytes, ss.getId().toString());
if (writeConsistencyLevel == null) {
writeConsistencyLevel = DEFAULT_CONSISTENCY_LEVEL;
}
bs.setConsistencyLevel(ConsistencyLevel.valueOf(writeConsistencyLevel));
cassandraSession.execute(bs);
long endTime = System.currentTimeMillis();
long timeTaken = endTime - startTime;
if (CASSANDRA_LOGGER.isDebugEnabled()) {
CASSANDRA_LOGGER.logDebug("The total time taken is " + timeTaken + " ms");
}
}
private PreparedStatement prepareSaveStatement() {
if (this.savePreparedStatement == null) {
String query = "UPDATE " + tableName + " SET " + "start_ts = ?, " + "stop_ts = ?, " + "last_access_ts = ?, "
+ "timeout = ?, " + "expired = ?, " + "host = ?, " + "serialized_value = ? " + "WHERE " + "id = ?";
this.savePreparedStatement = cassandraSession.prepare(query);
}
return this.savePreparedStatement;
}
public void update(Session session) throws UnknownSessionException {
SimpleSession ss = assertSimpleSession(session);
save(ss);
}
public void delete(Session session) {
/*
* String query = "DELETE from " + tableName + " where id = ?";
* PreparedStatement ps = cassandraSession.prepare(query);
*/
long startTime = System.currentTimeMillis();
if (CASSANDRA_LOGGER.isDebugEnabled()) {
CASSANDRA_LOGGER.logDebug("In the delete()..");
CASSANDRA_LOGGER.logDebug("The start time is " + startTime + " ms");
}
PreparedStatement ps = prepareDeleteStatement();
BoundStatement bs = new BoundStatement(ps);
bs.bind(session.getId().toString());
cassandraSession.execute(bs);
long endTime = System.currentTimeMillis();
long timeTaken = endTime - startTime;
if (CASSANDRA_LOGGER.isDebugEnabled()) {
CASSANDRA_LOGGER.logDebug("The total time taken is " + timeTaken + " ms");
}
}
private PreparedStatement prepareDeleteStatement() {
if (this.deletePreparedStatement == null) {
String query = "DELETE from " + tableName + " where id = ?";
this.deletePreparedStatement = cassandraSession.prepare(query);
}
return this.deletePreparedStatement;
}
public Collection<Session> getActiveSessions() {
return Collections.emptyList();
}
}
Need to add your class or pacakge in the configuration in whitelist section
https://helpx.adobe.com/experience-manager/6-4/sites/administering/using/mitigating-serialization-issues.html

How to get list of email address based on a specified group (CN) from memberOf Attribute in Active Directory in java

I had written a program to fetch all attributes from active directory based on username. now i want to get list of email address based on the group name CN= App_abc_Admin inside memerOf attribute.
Main .java
public void ldapQueryService()throws Exception{
try {
System.out.println("Querying Active Directory Using Java");
System.out.println("------------------------------------");
String domain = "abc.com";
String url = "ldap.abc.com:389";
String username = "username";
String password = "password";
String choice = "samaccountname";
String searchTerm = "xyz";
//Creating instance of ActiveDirectory
ActiveDirectory activeDirectory = new ActiveDirectory(username, password, domain, url);
//Searching
NamingEnumeration<SearchResult> result = activeDirectory.searchUser(searchTerm, choice, null);
while (result.hasMore()) {
SearchResult rs = (SearchResult) result.next();
Attributes attrs = rs.getAttributes();
String temp = attrs.get("samaccountname").toString();
System.out.println("Username : " + temp.substring(temp.indexOf(":") + 1));
String memberOf = attrs.get("memberOf").toString();
String stringToSearch = "CN=App_abc_Admin";
boolean test = memberOf.toLowerCase().contains(stringToSearch.toLowerCase());
if(test){
String mail = attrs.get("mail").toString();
System.out.println("Email ID : " + mail.substring(mail.indexOf(":") + 1));
}
}
activeDirectory.closeLdapConnection();
}catch(Exception e){
}
}
ActiveDirectory.java
public class ActiveDirectory {
//required private variables
private Properties properties;
private DirContext dirContext;
private SearchControls searchCtls;
private String[] returnAttributes = { "*"};
private String domainBase;
private String baseFilter = "(&((&(objectCategory=Person)(objectClass=User)))";
public ActiveDirectory(String username, String password, String domainController,String url) {
properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.put(Context.PROVIDER_URL, "LDAP://" + url);
properties.put(Context.SECURITY_PRINCIPAL, username + "#" + domainController);
properties.put(Context.SECURITY_CREDENTIALS, password);
//initializing active directory LDAP connection
try {
dirContext = new InitialDirContext(properties);
} catch (NamingException e) {
//LOG.severe(e.getMessage());
//e.printStackTrace();
}
//default domain base for search
domainBase = getDomainBase(domainController);
//initializing search controls
searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchCtls.setReturningAttributes(returnAttributes);
}
public NamingEnumeration<SearchResult> searchUser(String searchValue, String searchBy, String searchBase) throws NamingException {
String filter = getFilter(searchValue, searchBy);
String base = (null == searchBase) ? domainBase : getDomainBase(searchBase);
return this.dirContext.search(base, filter, this.searchCtls);
}
public void closeLdapConnection(){
try {
if(dirContext != null)
dirContext.close();
}
catch (NamingException e) {
//e.printStackTrace();
}
}
private String getFilter(String searchValue, String searchBy) {
String filter = this.baseFilter;
if(searchBy.equals("email")) {
filter += "(mail=" + searchValue + "))";
} else if(searchBy.equals("username")) {
filter += "(samaccountname=" + searchValue + "))";
}else if(searchBy.equals("title")) {
filter += "(title=" + searchValue + "))";
}else if(searchBy.equals("department")) {
filter += "(department=" + searchValue + "))";
}else if(searchBy.equals("givenname")) {
filter += "(givenname=" + searchValue + "))";
}
else if(searchBy.equals("samaccountname")) {
filter += "(samaccountname=" + searchValue + "))";
}
return filter;
}
private static String getDomainBase(String base) {
char[] namePair = base.toUpperCase().toCharArray();
String dn = "DC=";
for (int i = 0; i < namePair.length; i++) {
if (namePair[i] == '.') {
dn += ",DC=" + namePair[++i];
} else {
dn += namePair[i];
}
}
return dn;
}
}
In the above example i'm passing the search by and search term. But how to get list of users based on the CN in the memberOf attribute?
I tried to update the filter as below but no output
private String baseFilter = "(&(objectClass=Person)(memberOf=cn=App_abc_Admin,ou=Application Groups,dc=abc,dc=com))";
updated the filter as below.It works now
private String baseFilter = "(&((&(objectCategory=Person)(objectClass=User)(mail=*abc.com)(memberOf=CN=App_abc_Admin,OU=Application Groups,OU=Security Groups,OU=Users_OU,DC=abc,DC=com))))";

Visual Basic / SQL Server: identity_insert is set to off error

I just recently started toying with all of this programming stuff, so I'm not quite sure on how to fix a minor problem I seem to have with the communication between the server and the client.
when I start up the server, players are able to connect and log out when they are done playing without any problems, but the server throws an error and doesn't save the item in the table items.
It's almost as if the server/client can't communicate properly with the dbo.items table :/
Any help would be appreciated! Thank you.
And sorry for the bad English
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Goose
{
/**
* Item, holds the actual item data
*
* Each item in game is separate
* Holds the original template and modified/added stats
*
*/
public class Item : IItem
{
public int ItemID { get; set; }
public int TemplateID { get; set; }
public ItemTemplate Template { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int GraphicEquipped { get; set; }
public int GraphicTile { get; set; }
public int GraphicR { get; set; }
public int GraphicG { get; set; }
public int GraphicB { get; set; }
public int GraphicA { get; set; }
int weapondamage = 0;
public int WeaponDamage
{
get
{
return this.weapondamage + (int)Math.Ceiling(this.Template.WeaponDamage * this.StatMultiplier);
}
set
{
this.weapondamage = value;
}
}
/**
* Body pose/state 1 for normal, 3 for staff, 4 for sword
*/
public int BodyState { get; set; }
public AttributeSet BaseStats { get; set; }
public AttributeSet TotalStats { get; set; }
public decimal StatMultiplier { get; set; }
/**
* Dirty, has data changed since loading
*
*/
public bool Dirty { get; set; }
/**
* Delete, item is no longer in game so delete it
*/
public bool Delete { get; set; }
public long Value { get; set; }
bool bound = false;
public bool IsBound
{
get { return this.bound; }
set { this.bound = value; }
}
/**
* These properties are read only and just pass along from the templates properties
*
*/
public int WeaponDelay { get { return this.Template.WeaponDelay; } }
public int StackSize { get { return this.Template.StackSize; } }
public bool IsLore { get { return this.Template.IsLore; } }
public bool IsBindOnPickup { get { return this.Template.IsBindOnPickup; } }
public bool IsBindOnEquip { get { return this.Template.IsBindOnEquip; } }
public bool IsEvent { get { return this.Template.IsEvent; } }
public ItemTemplate.ItemSlots Slot { get { return this.Template.Slot; } }
public ItemTemplate.ItemTypes Type { get { return this.Template.Type; } }
public ItemTemplate.UseTypes UseType { get { return this.Template.UseType; } }
public int MinLevel { get { return this.Template.MinLevel; } }
public int MaxLevel { get { return this.Template.MaxLevel; } }
public long MinExperience { get { return this.Template.MinExperience; } }
public long MaxExperience { get { return this.Template.MaxExperience; } }
/**
* This is a bitmask
* Therefore only limited to about 64 classes, which should be enough.
* If the bit is set then that class id CAN'T use the item.
*
*/
public long ClassRestrictions { get { return this.Template.ClassRestrictions; } }
public SpellEffect SpellEffect { get { return this.Template.SpellEffect; } }
public decimal SpellEffectChance { get { return this.Template.SpellEffectChance; } }
public int LearnSpellID { get { return this.Template.LearnSpellID; } }
public bool Unsaved { get; set; }
public Item()
{
this.Unsaved = true;
this.ItemID = 0;
this.TotalStats = new AttributeSet();
this.BaseStats = new AttributeSet();
this.StatMultiplier = 1;
this.Dirty = true;
this.Delete = false;
}
/**
* LoadFromTemplate, loads item from a template
*
* This is when we want an item the same as the template.
*
*/
public void LoadFromTemplate(ItemTemplate template)
{
this.Template = template;
this.TemplateID = this.Template.ID;
this.TotalStats += this.Template.BaseStats;
this.Name = this.Template.Name;
this.Description = this.Template.Description;
this.GraphicEquipped = this.Template.GraphicEquipped;
this.GraphicTile = this.Template.GraphicTile;
this.GraphicR = this.Template.GraphicR;
this.GraphicG = this.Template.GraphicG;
this.GraphicB = this.Template.GraphicB;
this.GraphicA = this.Template.GraphicA;
this.Value = this.Template.Value;
this.BodyState = this.Template.BodyState;
}
/**
* LoadTemplate, adds template to item
*
* This is when we want to just add the templates stats to our item
* ie when loading the items database, eg for surname/titled items
*
* Note: Doesn't load the value from the template as we want to keep the value as 0
* if the item is custom for example
*
*/
public void LoadTemplate(ItemTemplate template)
{
this.TotalStats += template.BaseStats;
this.TotalStats *= this.StatMultiplier;
this.TotalStats += this.BaseStats;
}
/**
* AddItem, adds item to database
*
*/
public void AddItem(GameWorld world)
{
SqlParameter nameParam = new SqlParameter("#itemName", SqlDbType.VarChar, 64);
nameParam.Value = this.Name;
SqlParameter descriptionParam = new SqlParameter("#itemDescription", SqlDbType.VarChar, 64);
descriptionParam.Value = this.Description;
string query = "INSERT INTO items (item_id, item_template_id, item_name, item_description, " +
"player_hp, player_mp, player_sp, stat_ac, stat_str, stat_sta, stat_dex, stat_int, " +
"res_fire, res_water, res_spirit, res_air, res_earth, weapon_damage, item_value, " +
"graphic_tile, graphic_equip, graphic_r, graphic_g, graphic_b, graphic_a, stat_multiplier, " +
"bound, body_state) VALUES (" +
this.ItemID + "," +
this.TemplateID + ", " +
"#itemName, " +
"#itemDescription, " +
this.BaseStats.HP + ", " +
this.BaseStats.MP + ", " +
this.BaseStats.SP + ", " +
this.BaseStats.AC + ", " +
this.BaseStats.Strength + ", " +
this.BaseStats.Stamina + ", " +
this.BaseStats.Dexterity + ", " +
this.BaseStats.Intelligence + ", " +
this.BaseStats.FireResist + ", " +
this.BaseStats.WaterResist + ", " +
this.BaseStats.SpiritResist + ", " +
this.BaseStats.AirResist + ", " +
this.BaseStats.EarthResist + ", " +
this.weapondamage + ", " +
this.Value + ", " +
this.GraphicTile + ", " +
this.GraphicEquipped + ", " +
this.GraphicR + ", " +
this.GraphicG + ", " +
this.GraphicB + ", " +
this.GraphicA + ", " +
this.StatMultiplier + ", " +
(this.bound ? "'1'" : "'0'") + ", " +
this.BodyState + ")";
this.Dirty = false;
this.Unsaved = false;
SqlCommand command = new SqlCommand(query, world.SqlConnection);
command.Parameters.Add(nameParam);
command.Parameters.Add(descriptionParam);
command.BeginExecuteNonQuery(new AsyncCallback(GameWorld.DefaultEndExecuteNonQueryAsyncCallback), command);
}
/**
* SaveItem, updates item info in database
*
*/
public void SaveItem(GameWorld world)
{
SqlParameter nameParam = new SqlParameter("#itemName", SqlDbType.VarChar, 64);
nameParam.Value = this.Name;
SqlParameter descriptionParam = new SqlParameter("#itemDescription", SqlDbType.VarChar, 64);
descriptionParam.Value = this.Description;
string query = "UPDATE items SET " +
"item_template_id=" + this.TemplateID + ", " +
"item_name=" + "#itemName, " +
"item_description=" + "#itemDescription, " +
"player_hp=" + this.BaseStats.HP + ", " +
"player_mp=" + this.BaseStats.MP + ", " +
"player_sp=" + this.BaseStats.SP + ", " +
"stat_ac=" + this.BaseStats.AC + ", " +
"stat_str=" + this.BaseStats.Strength + ", " +
"stat_sta=" + this.BaseStats.Stamina + ", " +
"stat_dex=" + this.BaseStats.Dexterity + ", " +
"stat_int=" + this.BaseStats.Intelligence + ", " +
"res_fire=" + this.BaseStats.FireResist + ", " +
"res_water=" + this.BaseStats.WaterResist + ", " +
"res_spirit=" + this.BaseStats.SpiritResist + ", " +
"res_air=" + this.BaseStats.AirResist + ", " +
"res_earth=" + this.BaseStats.EarthResist + ", " +
"weapon_damage=" + this.weapondamage + ", " +
"item_value=" + this.Value + ", " +
"graphic_tile=" + this.GraphicTile + ", " +
"graphic_equip=" + this.GraphicEquipped + ", " +
"graphic_r=" + this.GraphicR + ", " +
"graphic_g=" + this.GraphicG + ", " +
"graphic_b=" + this.GraphicB + ", " +
"graphic_a=" + this.GraphicA + ", " +
"stat_multiplier=" + this.StatMultiplier + ", " +
"bound=" + (this.bound ? "'1'" : "'0'") + ", " +
"body_state=" + this.BodyState +
" WHERE item_id=" + this.ItemID;
SqlCommand command = new SqlCommand(query, world.SqlConnection);
command.Parameters.Add(nameParam);
command.Parameters.Add(descriptionParam);
command.BeginExecuteNonQuery(new AsyncCallback(GameWorld.DefaultEndExecuteNonQueryAsyncCallback), command);
this.Dirty = false;
}
/**
* DeleteItem, deletes item from database
*
*/
public void DeleteItem(GameWorld world)
{
SqlCommand command = new SqlCommand(
"DELETE FROM items WHERE item_id=" + this.ItemID,
world.SqlConnection);
command.BeginExecuteNonQuery(new AsyncCallback(GameWorld.DefaultEndExecuteNonQueryAsyncCallback), command);
}
}
}
public void AddItem(GameWorld world)
{
SqlParameter nameParam = new SqlParameter("#itemName", SqlDbType.VarChar, 64);
nameParam.Value = this.Name;
SqlParameter descriptionParam = new SqlParameter("#itemDescription", SqlDbType.VarChar, 64);
descriptionParam.Value = this.Description;
string query = "INSERT INTO items (item_template_id, item_name, item_description, " +
"player_hp, player_mp, player_sp, stat_ac, stat_str, stat_sta, stat_dex, stat_int, " +
"res_fire, res_water, res_spirit, res_air, res_earth, weapon_damage, item_value, " +
"graphic_tile, graphic_equip, graphic_r, graphic_g, graphic_b, graphic_a, stat_multiplier, " +
"bound, body_state) VALUES (" +
this.TemplateID + ", " +
"#itemName, " +
"#itemDescription, " +
this.BaseStats.HP + ", " +
this.BaseStats.MP + ", " +
this.BaseStats.SP + ", " +
this.BaseStats.AC + ", " +
this.BaseStats.Strength + ", " +
this.BaseStats.Stamina + ", " +
this.BaseStats.Dexterity + ", " +
this.BaseStats.Intelligence + ", " +
this.BaseStats.FireResist + ", " +
this.BaseStats.WaterResist + ", " +
this.BaseStats.SpiritResist + ", " +
this.BaseStats.AirResist + ", " +
this.BaseStats.EarthResist + ", " +
this.weapondamage + ", " +
this.Value + ", " +
this.GraphicTile + ", " +
this.GraphicEquipped + ", " +
this.GraphicR + ", " +
this.GraphicG + ", " +
this.GraphicB + ", " +
this.GraphicA + ", " +
this.StatMultiplier + ", " +
(this.bound ? "'1'" : "'0'") + ", " +
this.BodyState + ")";
this.Dirty = false;
this.Unsaved = false;
SqlCommand command = new SqlCommand(query, world.SqlConnection);
command.Parameters.Add(nameParam);
command.Parameters.Add(descriptionParam);
command.BeginExecuteNonQuery(new AsyncCallback(GameWorld.DefaultEndExecuteNonQueryAsyncCallback), command);
}
dont insert column item_id because it is identity and it will be inserted automatically

Coded UI c# - how to click a table htmlcell

I have tried numerous things to access a cell in a table. I have actually found the row that I need based on an innertext search, but then when I change the columnindex to the column for the found row, I cannot get mouse.click(cell); to do anything. Please see my code below. It has been modified many times! I have also used record to capture information about the cell.
The Method:
` public string SelectExistingCustomer(UITestControl parent, TestContext TestContext, string sLastName)
{
Controls control = new Controls(this.parent);
EditControl econtrol = new EditControl(this.parent);
HtmlTable tCustomerSearch = new HtmlTable(this.parent);
//HtmlTable tCustomerSearch1 = tCustomerSearch;
HtmlCell cell = new HtmlCell(tCustomerSearch);
//HtmlCell cell = GetCell;
string sFullName = "";
string sRowIndex = "";
if (sLastName != "")
{
try
{
// CodedUI scrolls items into view before it can click them
bool notfound = true;
int NumberOfpages = 0;
while (notfound)
{
tCustomerSearch.SearchProperties.Add(HtmlTable.PropertyNames.TagName, "TABLE");
Trace.WriteLine("####tCustomerSearch??? : " + tCustomerSearch + " : TABLE.");
tCustomerSearch.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
int rowcount = tCustomerSearch.RowCount;
Trace.WriteLine("Row###: " + rowcount + ".");
HtmlRow lastRow = (HtmlRow)tCustomerSearch.Rows[rowcount - 1];
//lastRow.EnsureClickable();
NumberOfpages++;
cell.SearchProperties.Add(HtmlCell.PropertyNames.InnerText, sLastName, PropertyExpressionOperator.Contains);
cell.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
if (cell.TryFind())
{
notfound = false;
sFullName = cell.GetProperty(HtmlCell.PropertyNames.InnerText).ToString();
sRowIndex = cell.GetProperty(HtmlCell.PropertyNames.RowIndex).ToString();
Trace.WriteLine(string.Format("found name at page {0}", NumberOfpages));
Trace.WriteLine(string.Format("Table row nr: {0}", cell.RowIndex));
Trace.WriteLine("cell####: " + cell + ".");
}
else Trace.WriteLine("NOT FOUND: CELL###:" + cell + ". And sFullName: " + sFullName + ".");
}
Trace.WriteLine("CELL###:" + cell + ". And sFullName: " + sFullName + ". And sRowIndex: " + sRowIndex + ".");
cell.SearchProperties.Add(HtmlCell.PropertyNames.RowIndex, sRowIndex);
cell.SearchProperties.Add(HtmlCell.PropertyNames.ColumnIndex, "0");
cell.SearchProperties[HtmlCell.PropertyNames.InnerText] = "Get";
cell.SetFocus();
//HtmlInputButton stry = new HtmlInputButton(cell);
Mouse.Click(cell);
//Mouse.Click(stry);
Assert.IsTrue(!notfound);
}
catch (Exception ex)
{
Trace.WriteLine("Failed to Search and find. Exception: " + ex + ".");
return "Failed";
}
}
//else - For the Future
return sFullName;
}
Table and cell - I modified this from the recording, not really sure what this does but I did something similar when I was having difficulty selecting from a combox:
public class tCustomerSearch : HtmlTable
{
public tCustomerSearch(UITestControl searchLimitContainer) :
base(searchLimitContainer)
{
#region Search Criteria
this.FilterProperties[HtmlTable.PropertyNames.ControlDefinition] = "class=\"table table-striped\"";
this.FilterProperties[HtmlTable.PropertyNames.Class] = "table table-striped";
this.FilterProperties[HtmlTable.PropertyNames.TagInstance] = "1";
#endregion
}
#region Properties
public HtmlCell GetCell
{
get
{
if ((this.mGetCell == null))
{
this.mGetCell = new HtmlCell(this);
#region Search Criteria
this.mGetCell.SearchProperties[HtmlCell.PropertyNames.InnerText] = "Get";
//this.GetCell.SearchProperties[HtmlCell.PropertyNames.MaxDepth] = "3";
Trace.WriteLine("###sLastName: " + sLastName + ". And mGetCell: " + mGetCell + ".");
#endregion
}
return this.mGetCell;
}
}
#endregion
// public string ctrlPropertyValue { get; private set; }
public string sLastName { get; }
#region Fields
private HtmlCell mGetCell;
#endregion
}
`
So, I found my own answer - even though this is not the best - it works!
` Keyboard.SendKeys("{TAB}");
Keyboard.SendKeys("{ENTER}");
'
I use this in place of mouse.click(cell);
The TAB highlights the button in the cell, and Enter triggers the event.