Related
public List<StockMarket> ReadAllRecords(string TxtFilePath, string TxtFileName)
{
List<StockMarket> Stock = new List<StockMarket>();
String[] a = File.ReadAllLines(TxtFilePath + TxtFileName);
foreach (var b in a)
{
String[] d = b.Split(',');
StockMarket S = new StockMarket();
S.ProductId = d[0];
S.ProductName = d[1];
S.StockId = d[2];
S.StockName = d[3];
S.StockPrice = d[4];
S.NumberofStocks = d[5];
S.Currency = d[6];
Stock.Add(S);
}
return Stock;
}
public List<StockMarket> GetValidRecords(List<StockMarket> Stock, string ErrorFilePath, string ErrorFileName)
{
List<StockMarket> Valid = new List<StockMarket>();
List<StockMarket> InValid = new List<StockMarket>();
foreach (var s in Stock)
{
bool ValidRecord = true;
if (String.IsNullOrEmpty(s.ProductId) || !s.ProductId.All(Char.IsDigit))
{
ValidRecord = false;
}
if (!s.ProductName.StartsWith("ABC") || s.ProductName.Length != 6)
{
ValidRecord = false;
}
if (String.IsNullOrEmpty(s.StockId) || !s.StockId.All(Char.IsDigit))
{
ValidRecord = false;
}
if (!s.StockName.StartsWith("SBC") || s.StockName.Length != 7)
{
ValidRecord = false;
}
if (string.IsNullOrEmpty(s.StockPrice))
{
ValidRecord = false;
}
if (string.IsNullOrEmpty(s.NumberofStocks) || !s.NumberofStocks.All(char.IsDigit))
{
ValidRecord = false;
}
if (!(s.Currency.Equals("INR") || s.Currency.Equals("USD") || s.Currency.Equals("EUR")))
{
ValidRecord = false;
}
if (ValidRecord)
{
Valid.Add(s);
}
else
{
InValid.Add(s);
}
}
LogErrorRecord(InValid, ErrorFilePath, ErrorFileName);
return Valid;
}
public List<StockMarket> CalculateTotalPrice(List<StockMarket> Stock)
{
foreach (var s in Stock)
{
if (s.Currency.Equals("INR"))
{
s.TotalPrice = (Convert.ToDouble(s.StockPrice) * Convert.ToDouble(s.NumberofStocks) * 1).ToString();
}
else if (s.Currency.Equals("USD"))
{
s.TotalPrice = (Convert.ToDouble(s.StockPrice) * Convert.ToDouble(s.NumberofStocks) * 0.5).ToString();
}
else if (s.Currency.Equals("EUR"))
{
s.TotalPrice = (Convert.ToDouble(s.StockPrice) * Convert.ToDouble(s.NumberofStocks) * 0.75).ToString();
}
}
return Stock;
}
public void LogErrorRecord(List<StockMarket> InvalidStock, string ErrorFilePath, string ErrorFileName)
{
List<String> InvalidItems = new List<string>();
foreach (var I in InvalidStock)
{
InvalidItems.Add(I.ProductId + " " + I.ProductName + " " + I.StockId + " " + I.StockName + " " + I.StockPrice + " " + I.NumberofStocks + " " + I.Currency);
}
File.AppendAllLines(ErrorFilePath + ErrorFileName, InvalidItems);
}
public void SavetoDB(List<StockMarket> Stock, SqlConnection connection)
{
String Query = "insert into StockMarket(ProductId,Productname,StockId,StockName,StockPrice,NumberofStocks,Currency,TotalPrice) Values(#ProductId,#ProductName,#StockId,#StockName,#StockPrice,#NumberofStocks,#Currency,#TotalPrice)";
connection.Open();
foreach (var a in Stock)
{
SqlCommand cmd = new SqlCommand(Query, connection);
cmd.Parameters.Add("#ProductId", a.ProductId);
cmd.Parameters.Add("#ProductName", a.ProductName);
cmd.Parameters.Add("#StockId", a.StockId);
cmd.Parameters.Add("#StockName", a.StockName);
cmd.Parameters.Add("#StockPrice", a.StockPrice);
cmd.Parameters.Add("#NumberofStocks", a.NumberofStocks);
cmd.Parameters.Add("#Currency", a.Currency);
cmd.Parameters.Add("#TotalPrice", a.TotalPrice);
int b = cmd.ExecuteNonQuery();
}
connection.Close();
}
public void SaveDistinctProductName(List<StockMarket> Stock, SqlConnection connection)
{
String Query = "if not exists( select * from Product where ProductId = #ProductId) begin insert into Product (ProductId,ProductName) Values(#ProductId,#ProductName)end";
connection.Open();
foreach (var a in Stock)
{
SqlCommand cmd = new SqlCommand(Query, connection);
cmd.Parameters.Add("#ProductId", a.ProductId);
cmd.Parameters.Add("#ProductName", a.ProductName);
int b = cmd.ExecuteNonQuery();
}
connection.Close();
}
public void SaveDistinctStockName(List<StockMarket> Stock, SqlConnection connection)
{
String Query = "if not exists( select * from Stock where StockId = #StockId) begin insert into Stock (StockId,StockName) Values(#StockId,#StockName)end";
connection.Open();
foreach (var a in Stock)
{
SqlCommand cmd = new SqlCommand(Query, connection);
cmd.Parameters.Add("#StockId", a.StockId);
cmd.Parameters.Add("#StockName", a.StockName);
int b = cmd.ExecuteNonQuery();
}
connection.Close();
}
Entity Framework allows you to create a model by writing code or using boxes and lines in the EF Designer. Both of these approaches can be used to target an existing database or create a new database. This short video explains the differences and how to find the one that is right for you.
Please let me know the overview of the code
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
namespace EmployeeValidation
{
public class Program
{
public static void Main()
{
/*
* Pass the file path, file names and connection string if any in this method alone.
* Do not hardcode in any other methods
*/
SqlConnection connection = new SqlConnection(#"Data Source=NA03OSDVP00746\SQLEXPRESS;Initial Catalog=DBEmployeeValidation;Integrated Security=True");
EmployeeValidator empValidator = new EmployeeValidator();
empValidator.ProcessData(#"D:\Employee_Validator\Input File\", "Emp_122014.xml", #"D:\Employee_Validator\Error File\", "Emp_122014.xml", connection);
}
}
}
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
using System.Xml.Linq;
using System.Linq;
using System.Text.RegularExpressions;
using System.Data.Linq;
using System.Globalization;
using System.Xml.Serialization;
using System.IO;
namespace EmployeeValidation
{
public class EmployeeValidator
{
/*
* Do not remove the attached TestProject. It is meant for auto evaluation of your source code.
* Do not attach any test classess to the attached test project.
* Do not attach any new test projects.
* You are not required to write any automated test cases. You are supposed to write only the code.
*/
public void ProcessData(string xmlFilePath, string xmlFileName,string errorFilePath, string errorFileName, SqlConnection connection)
{
//Do your logic here
//Step 1
//ReadAllEmployeesFromXmlFile
List<Employee> lstemp = new List<Employee>();
List<Employee> validemp = new List<Employee>();
lstemp = ReadAllEmployeesFromXmlFile(xmlFilePath,xmlFileName);
validemp = PickValidEmployees(lstemp);
SaveValidEmployeesToDB(validemp, connection);
ReadfromDBtoTxt(connection);
//Step 2
//PickValidEmployees
//Step 3
//SaveValidEmployeesToDataBase
}
public List<Employee> ReadAllEmployeesFromXmlFile(string xmlFilePath, string xmlFileName)
{
//Read the employee details from the xml file and return it in List collection
//Do not hardcode the filename and the file path here
//Do not return the date with time appended to it.
string employeefile = xmlFilePath + xmlFileName;
List<Employee> empdetail = new List<Employee>();
XElement getelementfile = XElement.Load(employeefile);
IEnumerable<XElement> items = getelementfile.Elements();
foreach (var item in items)
{
string _EmployeeId = item.Element("EmployeeId").Value;
string _EmployeeName = item.Element("EmployeeName").Value;
string _EmailId = item.Element("EmailId").Value;
string _DateOfJoining = item.Element("DateOfJoining").Value;
empdetail.Add(new Employee(){ EmployeeId= _EmployeeId,
EmployeeName= _EmployeeName,
EmailId=_EmailId,
DateOfJoining=_DateOfJoining
});
}
return empdetail;
}
public List<Employee> PickValidEmployees(List<Employee> employees)
{
//Pick the valid employees from the List collection
//Return the valid employees in a List
List<Employee> valid = new List<Employee>();
List<Employee> Invalid = new List<Employee>();
List<string> empnum = new List<string>();
bool isvalid = true;
foreach(Employee em in employees)
{
Regex rgxisnumeric = new Regex(#"^\d$");
Regex rgxisalphanumeric=new Regex( #"^\d*[a-zA-Z]{1,}\d*");
Regex rgxemail = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
Regex rgxDate= new Regex(#"^((0[1-9]|1[0-2])\/((0|1)[0-9]|2[0-9]|3[0-1])\/((19|20)\d\d))$");
if (!empnum.Contains(em.EmployeeId))
{
empnum.Add(em.EmployeeId);
isvalid = true;
}
else
{
isvalid = false;
}
int empname;
isvalid= isvalid && (!string.IsNullOrEmpty(em.EmployeeId)) && (rgxisnumeric.IsMatch(em.EmployeeId));
isvalid= isvalid && (int.TryParse(em.EmployeeName, out empname)== false);
isvalid= isvalid && (!string.IsNullOrEmpty(em.EmployeeName)) && (rgxisalphanumeric.IsMatch(em.EmployeeName));
isvalid= isvalid && (!string.IsNullOrEmpty(em.EmailId)) && (rgxemail.IsMatch(em.EmailId));
isvalid= isvalid && (!string.IsNullOrEmpty(em.DateOfJoining)) && (rgxDate.IsMatch(em.DateOfJoining));
if(isvalid)
{
DateTime dt;
isvalid= isvalid && DateTime.TryParseExact(em.DateOfJoining,"MM/dd/yyyy",new CultureInfo("en-US"),DateTimeStyles.None, out dt);
}
if(isvalid)
{
valid.Add(em);
}
else
{
Invalid.Add(em);
}
}
SaveInValidEmployeesTotxt(Invalid);
return valid;//Return only valid employees in List
}
public void SaveValidEmployeesToDB(List<Employee> employees, SqlConnection connection)
{
//Do not Prefix Database name in the SQL Query. Query should be "Insert into SBA.TableName"
//Should not be "Insert into DatabaseName.SBA.TableName"
//Do not hardcode the connection string here
SqlConnection conn = connection;
foreach(Employee emp in employees)
{
string command = "Insert into SBA.Employees (EmployeeId,EmployeeName,EmailId,DateOfJoining) values (#EmployeeId,#EmployeeName,#EmailId,#DateOfJoining)";
SqlCommand cmd = new SqlCommand(command, conn);
conn.Open();
cmd.Parameters.AddWithValue("#EmployeeId",emp.EmployeeId);
cmd.Parameters.AddWithValue("#EmployeeName",emp.EmployeeName);
cmd.Parameters.AddWithValue("#EmailId",emp.EmailId);
cmd.Parameters.AddWithValue("#DateOfJoining",DateTime.Parse(emp.DateOfJoining).ToString("MM/dd/yyyy"));
cmd.ExecuteNonQuery();
conn.Close();
}
}
public void SaveInValidEmployeesTotxt(List<Employee> Invalid)
{
string invalidpath = #"D:\Employee_Validator\Error File\Emp_122014.xml";
XmlSerializer serialise = new XmlSerializer(typeof(List<Employee>));
TextWriter writeinvalid = new StreamWriter(invalidpath);
serialise.Serialize(writeinvalid,Invalid);
}
public void ReadfromDBtoTxt(SqlConnection connection)
{
string newfilepath = #"D:\Employee_Validator\DBtoTXT\EmpoValid_" + DateTime.Now.ToString("MMyyyy") + ".txt";
List<Employee> dbtotextlist = new List<Employee>();
if (!File.Exists(newfilepath))
{
var g= File.Create(newfilepath);
g.Close();
}
SqlCommand cmd = new SqlCommand("Select * from SBA.Employees",connection);
connection.Open();
SqlDataReader readdata = cmd.ExecuteReader();
while (readdata.Read())
{
dbtotextlist.Add(new Employee
{
EmployeeId = readdata["EmployeeId"].ToString(),
EmployeeName = readdata["EmployeeName"].ToString(),
EmailId = readdata["EmailId"].ToString(),
DateOfJoining = readdata["DateOfJoining"].ToString()
});
}
sconnection.Close();
StreamWriter sw = File.AppendText(newfilepath);
foreach(Employee s in dbtotextlist)
{
sw.WriteLine(s.EmployeeId+","+s.EmployeeName+","+s.EmailId+","+ DateTime.Parse(s.DateOfJoining).ToString("MM/dd/yyyy"));
}
sw.Flush();
sw.Close();
}
}
}
static void Main(string[] args)
{
SqlConnection connectionObject = new SqlConnection(#"Data Source=NA03OSDVP00746\SQLEXPRESS;Initial Catalog= DBFXCalculation;Integrated Security=True");
Main fxcalculatorobj = new Main();
fxcalculatorobj.ProcessData(#"D:\frameworksample\Input File\", "TradeOrders_032013.txt",
#"D:\frameworksample\ErrorLog\", "InvalidRecords_032014.txt", connectionObject,
#"D:\frameworksample\Archive\", "TradeOrders_032013_Processed.txt");
/*
* Pass the file path, file names and connection string in this method alone.
* Do not hardcode in any other methods
*/
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Reflection;
namespace frameworksample
{
class Main
{
public void ProcessData(string sourceFolder, string fileName, string errorLogFilePath,
string errorLogFileName, SqlConnection connectionObject,
string archiveFilePath, string archiveFileName)
{
//Step 1:ReadAllDataFromInputFile
List<Trade> trades = ReadAllDataFromInputFile(sourceFolder, fileName);
//Step 2:PickValidTradeDetails;
List<Trade> validateTrade = PickValidTradeDetails(trades, errorLogFilePath, errorLogFileName);
//Step 3: SaveValidRecordsToDB
SaveValidRecordsToDB(validateTrade, connectionObject);
//Step 4:CalculateFXRate
List<FXRate> fxRates = CalculateFXRate(connectionObject);
//Step 5:SaveFXRate
//List<FXRate> fxRates = new List<FXRate>();
SaveFXRate(fxRates, connectionObject);
//Step 6:CopyToArchive
CopyToArchive(archiveFilePath, archiveFileName);
//Validate data
}
public List<Trade> ReadAllDataFromInputFile(string sourceFolder, string fileName)
{
List<Trade> trades = new List<Trade>();
//Do your logic to read file and storing it into list of trades ..here..
//Do not hardcode the filename and the file path here
using(StreamReader sr= File.OpenText(sourceFolder+fileName))
{
string s="";
while((s=sr.ReadLine())!=null)
{
if(s.Contains(','))
{
string[] splited= s.Split(',');
Trade tradeitem= new Trade();
tradeitem.TradeId= splited[0];
tradeitem.ISIN= splited[1];
tradeitem.TradeDate= splited[2];
tradeitem.MaturityDate= splited[3];
tradeitem.SchemeName= splited[4];
tradeitem.TradeType= splited[5];
tradeitem.Currency= splited[6];
tradeitem.Amount= splited[7];
trades.Add(tradeitem);
}
}
}
return trades;
}
public List<Trade> PickValidTradeDetails(List<Trade> trades, string errorLogFilePath, string errorLogFileName)
{
//email: \w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)* ,,,, \b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b
// Step 1 : filter the valid trades and invalid trades, save the invalid
List<Trade> validTrades = new List<Trade>(); //identify all the valid trades and assign.
//Do not hardcode the filename and the file path here
List<Trade> invalidTrade = new List<Trade>();
bool isValid = true;
foreach (Trade x in trades)
{
isValid=(!string.IsNullOrEmpty(x.TradeId));
Regex rgxtradeid = new Regex(#"\bTR\d{3}\b");
isValid = isValid && rgxtradeid.IsMatch(x.TradeId);
isValid=(isValid && (!string.IsNullOrEmpty(x.ISIN)));
Regex rgxisin = new Regex(#"\bISIN\d{3}\b");
isValid = (rgxisin.IsMatch(x.ISIN));
Regex rgxdate = new Regex("((0[1-9]|1[0-2])\\/((0|1)[0-9]|2[0-9]|3[0-1])\\/((19|20)\\d\\d))$");
DateTime dt;
isValid = (isValid && (!string.IsNullOrEmpty(x.TradeDate)) && (rgxdate.IsMatch(x.TradeDate)));
isValid = (isValid && (!string.IsNullOrEmpty(x.MaturityDate)) && (rgxdate.IsMatch(x.MaturityDate)));
if (isValid)
{
DateTime MD = DateTime.Parse(x.MaturityDate);
DateTime TD = DateTime.Parse(x.TradeDate);
int year = MD.Year - TD.Year;
isValid = isValid && (year > 5);
isValid = isValid && (!string.IsNullOrEmpty(x.TradeType));
isValid = isValid && (x.Currency.Equals("GBP") || x.Currency.Equals("EUR") || x.Currency.Equals("USD") || x.Currency.Equals("INR"));
isValid = isValid && (!string.IsNullOrEmpty(x.Amount));
int i;
bool isnumeric = int.TryParse(x.Amount, out i);
isValid = isValid && (isnumeric);
}
if(isValid)
{
Trade val= new Trade();
val.TradeId= x.TradeId;
val.ISIN= x.ISIN;
val.TradeDate= x.TradeDate;
val.MaturityDate= x.MaturityDate;
val.SchemeName= x.SchemeName;
val.TradeType= x.TradeType;
val.Currency= x.Currency;
val.Amount= x.Amount;
validTrades.Add(val);
}
else
{
Trade valerror= new Trade();
valerror.TradeId= x.TradeId;
valerror.ISIN= x.ISIN;
valerror.TradeDate= x.TradeDate;
valerror.MaturityDate= x.MaturityDate;
valerror.SchemeName= x.SchemeName;
valerror.TradeType= x.TradeType;
valerror.Currency= x.Currency;
valerror.Amount= x.Amount;
invalidTrade.Add(valerror);
}
}
SaveInvalidRecordsToLogFile(invalidTrade, errorLogFilePath, errorLogFileName);
// SaveInvalidRecordsToLogFile(List<Trades>); // pass all the invalid trades to log...
return validTrades;
}
public bool SaveInvalidRecordsToLogFile(List<Trade> invalidTrades, string errorLogFilePath, string errorLogFileName)
{
//Do your logic here
//Do not hardcode the filename and the file path here
if (invalidTrades != null && invalidTrades.Count > 0)
{
string errorLogfile = errorLogFilePath + errorLogFileName;
try
{
if (!File.Exists(errorLogfile))
{
var invalidfile = File.Create(errorLogfile);
invalidfile.Close();
}
using (StreamWriter swinvalid = File.AppendText(errorLogfile))
{
swinvalid.WriteLine("TradeId|ISIN|TradeDate|MaturityDate|Tradetype|Currency|Amount");
foreach (Trade ivt in invalidTrades)
{
swinvalid.WriteLine(ivt.TradeId + "," + ivt.ISIN + "," + ivt.TradeDate + "," + ivt.MaturityDate + "'" + ivt.TradeType + "," + ivt.Currency + "," + ivt.Amount);
}
}
}
catch (Exception ex)
{
throw new FXCalculatorException(ex.Message);
}
}
return true;
}
public bool SaveValidRecordsToDB(List<Trade> validTrades, SqlConnection sqlConnectionObject)
{
//Do your logic here to upload to DB table
//Do not hardcode the connection string here
//Do not create the redundant connection Object for SqlConnection, use the conncetionObject given in the method parameter.
//Do not Prefix Database name in the SQL Query. Query should be "Insert into SBA.TableName"
//Should not be "Insert into DatabaseName.SBA.TableName"
//var ConnectionString = sqlConnectionObject.ConnectionString;
if (validTrades.Count > 0 && validTrades != null)
{
SqlConnection conn = sqlConnectionObject;
conn.Open();
foreach (Trade valid in validTrades)
{
SqlCommand cmd = new SqlCommand(("Insert into SBA.Trade_Details (TradeID,ISIN,TradeDate,MaturityDate,SchemeName,TradeType,Currency,Amount) values (#TradeID,#ISIN,#TradeDate,#MaturityDate,#SchemeName,#TradeType,#Currency,#Amount)"),conn);
cmd.Parameters.Add("#TradeID",valid.TradeId);
cmd.Parameters.Add("#ISIN", valid.ISIN);
cmd.Parameters.Add("#TradeDate", valid.TradeDate);
cmd.Parameters.Add("#MaturityDate", valid.MaturityDate);
cmd.Parameters.Add("#SchemeName", valid.SchemeName);
cmd.Parameters.Add("#TradeType", valid.TradeType);
cmd.Parameters.Add("#Currency", valid.Currency);
cmd.Parameters.Add("#Amount", valid.Amount);
cmd.ExecuteNonQuery();
}
conn.Close();
}
return true;
}
public List<FXRate> CalculateFXRate(SqlConnection sqlConnectionObject)
{
// TODO :Read the Trade details for TradeType FX from database and calculate the rates.
// Calculate the rate for each trade and add in a list of FXRates.
//Do not Prefix Database name in the SQL Query. Query should be "Insert into SBA.TableName"
//Should not be "Insert into DatabaseName.SBA.TableName"
//List<FXRate> FxRates = null; // assign list of FXRates;
//Do not hardcode the connection string here
//Do not create the redundant connection Object for SqlConnection, use the conncetionObject given in the method parameter.
List<FXRate> FxRates = new List<FXRate>();
List<Trade> trades = new List<Trade>();
try
{
SqlConnection conne = sqlConnectionObject;
string queryString = "Select * from SBA.Trade_Details";
SqlCommand cmd = new SqlCommand(queryString, conne);
conne.Open();
SqlDataReader datareader = cmd.ExecuteReader();
while (datareader.Read())
{
Trade validfx = new Trade{TradeId = datareader["TradeId"].ToString(),ISIN = datareader["ISIN"].ToString(),TradeDate = datareader["TradeDate"].ToString(),
MaturityDate = datareader["MaturityDate"].ToString(),SchemeName = datareader["SchemeName"].ToString(),TradeType = datareader["TradeType"].ToString(),
Currency = datareader["Currency"].ToString(), Amount = datareader["Amount"].ToString()};
trades.Add(validfx);
}
conne.Close();
foreach (Trade trad_para_to_calc_fx in trades)
{
FXRate fx = new FXRate();
fx.TradeId = trad_para_to_calc_fx.TradeId;
fx.Currency = trad_para_to_calc_fx.Currency;
fx.Amount = trad_para_to_calc_fx.Amount;
float amount = float.Parse(fx.Amount, CultureInfo.InvariantCulture.NumberFormat);
if (trad_para_to_calc_fx.Currency == "USD")
{
fx.AppliedFXRate = float.Parse("0.5",CultureInfo.InvariantCulture.NumberFormat).ToString();
float app_fx_rate = float.Parse("0.5",CultureInfo.InvariantCulture.NumberFormat);
fx.CalculatedFXRate = ((app_fx_rate) * (amount)).ToString();
}
if (trad_para_to_calc_fx.Currency == "GBP")
{
fx.AppliedFXRate = float.Parse("0.6", CultureInfo.InvariantCulture.NumberFormat).ToString();
float app_fx_rate = float.Parse("0.7",CultureInfo.InvariantCulture.NumberFormat);
fx.CalculatedFXRate = ((app_fx_rate) * (amount)).ToString();
}
if (trad_para_to_calc_fx.Currency == "EUR")
{
fx.AppliedFXRate = float.Parse("0.7", CultureInfo.InvariantCulture.NumberFormat).ToString();
float app_fx_rate = float.Parse("0.7",CultureInfo.InvariantCulture.NumberFormat);
fx.CalculatedFXRate = ((app_fx_rate) * (amount)).ToString();
}
if (trad_para_to_calc_fx.Currency == "INR")
{
fx.AppliedFXRate = float.Parse("1", CultureInfo.InvariantCulture.NumberFormat).ToString();
float app_fx_rate = float.Parse("1",CultureInfo.InvariantCulture.NumberFormat);
fx.CalculatedFXRate = ((app_fx_rate) * (amount)).ToString();
}
FxRates.Add(fx);
}
}
catch (Exception ex)
{
throw new FXCalculatorException(ex.Message);
}
return FxRates;
}
public bool SaveFXRate(List<FXRate> fxRates, SqlConnection sqlConnectionObject)
{
//Do your logic here to upload to DB table
//Do not hardcode the connection string here
//Do not create the redundant connection Object for SqlConnection, use the conncetionObject given in the method parameter.
//Do not Prefix Database name in the SQL Query. Query should be "Insert into SBA.TableName"
//Should not be "Insert into DatabaseName.SBA.TableName"
try
{
if (fxRates.Count > 0 && fxRates != null)
{
SqlConnection conne = sqlConnectionObject;
conne.Open();
foreach(FXRate calculated in fxRates)
{
SqlCommand cmd = new SqlCommand("Insert into SBA.FX_Rate (TradeId,Currency,Amount,AppliedFXRate,CalculatedFXRate) values (#TradeId,#Currency,#Amount,#AppliedFXRate,#CalculatedFXRate)", conne);
cmd.Parameters.AddWithValue("#TradeId", calculated.TradeId);
cmd.Parameters.AddWithValue("#Currency",calculated.Currency);
cmd.Parameters.AddWithValue("#Amount",calculated.Amount);
cmd.Parameters.AddWithValue("#AppliedFXRate",calculated.AppliedFXRate);
cmd.Parameters.AddWithValue("#CalculatedFXRate", calculated.CalculatedFXRate);
cmd.ExecuteNonQuery();
}
conne.Close();
}
}
catch (Exception ex)
{
throw new FXCalculatorException(ex.Message);
}
return true;
}
public bool CopyToArchive(string sourcePathWithFileName, string targetPathWithFileName)
{
//Do your logic here
//Do not hardcode the filename and the file path here
try
{
string inputpath="";
string input="";
FileInfo[] files;
DirectoryInfo Di;
string targetFile = sourcePathWithFileName + targetPathWithFileName;
Di = new DirectoryInfo(#"D:\frameworksample\");
files = Di.GetFiles("*.txt", SearchOption.AllDirectories);
foreach (FileInfo di1 in files)
{
if (di1.Name == "TradeOrders_032013.txt")
{
inputpath = di1.DirectoryName.ToString();
input = inputpath+"\\" + di1.Name.ToString();
}
}
if (!Directory.Exists(sourcePathWithFileName))
{
Directory.CreateDirectory(sourcePathWithFileName);
var targetfilecreation = File.Create(targetFile);
targetfilecreation.Close();
}
else
{
File.Delete(targetFile);
Directory.Delete(sourcePathWithFileName, true);
Directory.CreateDirectory(sourcePathWithFileName);
var targetfilecreation =File.Create(targetFile);
targetfilecreation.Close();
}
System.IO.File.Copy(input, targetFile, true);
}
catch (Exception ex)
{
throw new FXCalculatorException(ex.Message);
}
//File.Copy(sourcePathWithFileName + "\\" + targetPathWithFileName, true);
return true;
}
private void ProcessData(Main main)
{
throw new NotImplementedException();
}
//internal void ProcessData(string p, string p_2, string p_3, string p_4, System.Data.SqlClient.SqlConnection connectionObject, string p_5, string p_6)
//{
// throw new NotImplementedException();
//}
}
}
This is where I show my form. Basically I'm editing data in a database. I get the exception at line DataGridViewRow object.
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e)
{
int selectedIndex = dataGridView1->CurrentCell->RowIndex;
if (selectedIndex >= 0)
{
MessageBox::Show("selection is" + selectedIndex);
edit->Show();
try
{
DataGridViewRow ^row = this->dataGridView1->Rows[selectedIndex];
edit->itemcodetextBox->Text = row->Cells[0]->Value->ToString();
edit->itemnametextbox->Text = row->Cells[1]->Value->ToString();
edit->stockamnttextBox->Text = row->Cells[2]->Value->ToString();
edit->pricetextBox->Text = row->Cells[3]->Value->ToString();
edit->categorytextBox->Text = row->Cells[4]->Value->ToString();
}
catch (Exception^ ex)
{
MessageBox::Show(" Error Updating Data ");
}
}
I have created an online examination system. It is working fine with only a single user at a time. However, a problem occurs when more than one user logs in.
There are 20 questions in each test. If only a single user is doing the test it works fine. The user can do all the 20 questions. Now another user logs in at the same time. That user is not getting all the 20 questions. Say User1 has completed 12 question. User2 will get only 8 question.
Suppose there there are User1,User2,User3 logged in at the same time. User1 did 8 questions, User2 did 6 questions and User3 also 8 questions. They would all arrive at the result Page without completing their 20 questions. That means if there are 20 users they will get only 1 question instead of 20. Can anyone help?
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["hasexaminationConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
cmd.Connection = con;
cmd.CommandText = "select * from tblregister where Name=#Name and EMail=#EMail";
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = TxtStName.Text;
cmd.Parameters.Add("#EMail", SqlDbType.VarChar).Value = TxtStudentID.Text;
//cmd.Parameters.Add("#Flag", SqlDbType.Int).Value = Convert.ToInt32(HiddenField1.Value);
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
FormsAuthentication.RedirectFromLoginPage(TxtStName.Text, false);
Session["Name"] = TxtStName.Text;
Session["EMail"] = TxtStudentID.Text;
Response.Redirect("TestHome.aspx");
}
else
{
Label1.Visible = true;
Label1.Text = "UserName or Password is Required/Incorrect.";
}
}
catch
{ }
}
next page:
protected void Page_Load(object sender, EventArgs e)
{
mob = HttpContext.Current.Session["Name"].ToString();
number = HttpContext.Current.Session["EMail"].ToString();
//Response.Cache.SetCacheability(HttpCacheability.NoCache);
if (Session["mob"] == null & Session["number"] == null)
//Response.Redirect("Home.aspx");
if (!IsPostBack)
{
DataSet TestList = getTestList("GetTestList");
DataList1.DataSource = TestList;
DataList1.DataBind();
}
}
public DataSet getTestList(string procedurename)
{
using (DataSet QuestionSet = new DataSet())
{
using (DataTable QTable = new DataTable())
{
QTable.Columns.Add("TESTNAME");
QTable.Columns.Add("TESTNUMBER");
DataTable dt;
cmd.Connection = con;
cmd.CommandText = "select * from testnumber";
using (Da = new SqlDataAdapter(cmd))
{
con.Open();
dt = new DataTable();
Da.Fill(dt);
if (dt.Rows.Count > 0)
{
DataRow dr;
for (int i = 0; i < dt.Rows.Count; i++)
{
dr = QTable.NewRow();
dr[0] = dt.Rows[i]["testname"].ToString();
dr[1] = dt.Rows[i]["testnumber"].ToString();
QTable.Rows.Add(dr);
}
}
}
QuestionSet.Tables.Add(QTable);
return QuestionSet;
}
}
}
protected void LinkButton_Click(object sender, CommandEventArgs e)
{
string name = e.CommandArgument.ToString();
Response.Redirect("TakeTest1.aspx?testno=" + e.CommandArgument.ToString());
}
next:
protected void Page_Load(object sender, EventArgs e)
{
//UserName = Session["UserName"].ToString();
//Password = Session["Password"].ToString();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["hasexaminationConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
cmd.Connection = con;
cmd.CommandText = "select username,password,flag from tblcollegeuser where username='" + UserName + "'and password='" + Password + "'";
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
HiddenField1.Value = dr["Flag"].ToString();
if (HiddenField1.Value.ToString() == "0")
{
//Response.Write("<script>alert('Your Session Timer has Expired! We are Sorry!')</script>");
Response.Redirect("Result.aspx");
}
}
if (HttpContext.Current.Session["Name"] == null && HttpContext.Current.Session["EMail"] == null)
{
Response.Write("<script>alert('Your Session Timer has Expired! We are Sorry!')</script>");
Response.Redirect("default.aspx");
}
if (!IsPostBack)
{
this.timerStartValue = long.Parse(ConfigurationManager.AppSettings["Delay"].ToString());
this.TimerInterval = 500;
tno = Request.QueryString["testno"].ToString();
//string query = "select * from questions where tnumber='" + tno + "'";
Questions = GetDataSet(tno);
totalQs = GetCount(tno);
LoadQuestion();
DataSet questions = new DataSet("Questions");
questions.Tables.Add();
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string strDisAbleBackButton;
strDisAbleBackButton = "";
ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "clientScript", strDisAbleBackButton);
}
public DataSet GetDataSet(string query)
{
using (DataSet QuestionSet = new DataSet())
{
using (DataTable QTable = new DataTable())
{
QTable.Columns.Add("ROW_NUMBER");
QTable.Columns.Add("QuestionNo");
QTable.Columns.Add("Tname");
QTable.Columns.Add("Tnumber");
QTable.Columns.Add("question");
QTable.Columns.Add("ans1");
QTable.Columns.Add("ans2");
QTable.Columns.Add("ans3");
QTable.Columns.Add("ans4");
DataTable dt;
using (cmd.Connection = con)
{
//cmd.CommandText = " SELECT * FROM test ORDER BY CHECKSUM(NEWID()) where tnumber='" + query + "'";
cmd.CommandText = " SELECT * FROM test WHERE tnumber='" + query + "' ORDER BY CHECKSUM(NEWID()) ";
//cmd.Parameters.AddWithValue("#cse", query);
Da = new SqlDataAdapter(cmd);
con.Open();
dt = new DataTable();
Da.Fill(dt);
if (dt.Rows.Count > 0)
{
DataRow dr;
for (int i = 0; i < dt.Rows.Count; i++)
{
dr = QTable.NewRow();
dr[0] = dt.Rows[i]["id"].ToString();
dr[1] = "Qno" + dt.Rows[i]["Qno"].ToString();
dr[2] = dt.Rows[i]["tname"].ToString();
dr[3] = dt.Rows[i]["tnumber"].ToString();
dr[4] = dt.Rows[i]["quation"].ToString();
dr[5] = dt.Rows[i]["ans1"].ToString();
dr[6] = dt.Rows[i]["ans2"].ToString();
dr[7] = dt.Rows[i]["ans3"].ToString();
dr[8] = dt.Rows[i]["ans4"].ToString();
QTable.Rows.Add(dr);
}
}
}
QuestionSet.Tables.Add(QTable);
return QuestionSet;
}
}
}
public Int32 GetCount(string tno)
{
return 10;
}
void Page_PreRender(object sender, EventArgs e)
{
StringBuilder bldr = new StringBuilder();
bldr.AppendFormat("var Timer = new myTimer({0},{1},'{2}','timerData');", this.timerStartValue, this.TimerInterval, this.lblTimerCount.ClientID);
bldr.Append("Timer.go()");
ClientScript.RegisterStartupScript(this.GetType(), "TimerScript", bldr.ToString(), true);
ClientScript.RegisterHiddenField("timerData", timerStartValue.ToString());
}
void Page_PreInit(object sender, EventArgs e)
{
string timerVal = Request.Form["timerData"];
if (timerVal != null || timerVal == "")
{
timerVal = timerVal.Replace(",", String.Empty);
timerStartValue = long.Parse(timerVal);
}
}
private Int32 TimerInterval
{
get
{
object o = ViewState["timerInterval"];
if (o != null) { return Int32.Parse(o.ToString()); }
return 50;
}
set { ViewState["timerInterval"] = value; }
}
void RedirectToResults()
{
Response.Redirect("Results.aspx");
}
protected void LoadQuestion()
{
if (Questions.Tables[0].Rows.Count > 0)
{
//Load Question;
DataRow DR = Questions.Tables[0].Rows[0];
//Question.Text = DR[0].ToString() + " of " + 20;
//Question.Text = (i + 1).ToString() + " of " + 20;
sno = DR[1].ToString();
TestName.Text = DR[2].ToString();
TestNo.Text = DR[3].ToString();
Questionlbl.Text = DR[4].ToString();
rbtnAns.Items.Clear();
rbtnAns.Items.Add(DR[5].ToString());
rbtnAns.Items.Add(DR[6].ToString());
rbtnAns.Items.Add(DR[7].ToString());
rbtnAns.Items.Add(DR[8].ToString());
Questions.Tables[0].Rows.Remove(DR);
if (Questionlbl.Text.Equals(totalQs.ToString()))
{
IsLastQs = true;
}
}
else
{
//End Of File;
//Response.Write("<script>alert('Thanks For Your Presence! You Can Leave Now.')</script>");
//Session.Abandon();
Session["raj"] = Questions;
RedirectToResults();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//Write your code here to save the question
//Displays the Next Question
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["hasexaminationConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("insert into testdisplay Values ('" + sno + "','" + Session["Name"] + "','" + Session["EMail"] + "','" + Questionlbl.Text + "','" + rbtnAns.SelectedItem.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
LoadQuestion();
}
catch (Exception ex)
{
Response.Write("<script>alert(''" + ex.Message + "'')</script>");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//When Skip Button is pressed it loads the next question
LoadQuestion();
}
and result page:
protected void Page_Load(object sender, EventArgs e)
{
l = Session["Name"].ToString();
m = Session["EMail"].ToString();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["hasexaminationConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("select tnumber,quation,ans1,ans2,ans3,ans4,ans from test left join testdisplay on (test.ans= testdisplay.answ and test.quation= testdisplay.quations) where UserName='" + Session["Name"] + "' and Password='" + Session["EMail"] + "'", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
con.Close();
{
int to = 20;
GridView1.DataSource = dt;
GridView1.DataBind();
int marks = GridView1.Rows.Count;
Label1.Text = Convert.ToInt32(GridView1.Rows.Count).ToString();
decimal total = Convert.ToDecimal((double)marks / (double)20) * 100;
lbltotal.Text = total.ToString();
}
}
public void bind()
{
// Write your code to get the summary of the result and display it
}
protected void Button1_Click(object sender, EventArgs e)
{
//Response.Redirect("Home.aspx");
string uniqueCode = string.Empty;
//SqlDataReader dr;
try
{
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["hasexaminationConnectionString"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT Name,EMail FROM tblregister Where EMail= '" + txtEmail.Text.Trim() + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
////}
if (Page.IsValid)
{
//GridView1.RenderControl(hw);
const string SERVER = "relay-hosting.secureserver.net";
MailMessage oMail = new MailMessage();
oMail.From = new MailAddress("contact#dssgroups.com");
oMail.To.Add(new MailAddress(txtEmail.Text.Trim()));
oMail.Subject = "Your Test Details";
oMail.IsBodyHtml = true; // enumeration
oMail.Priority = MailPriority.High; // enumeration
oMail.Body = "Hi, <br/><b>Please check your Test Details:</b><br/><br/>Your Marks Percentage: " + lbltotal.Text+" % "+"<br/>For any query contact "+" http://dssgroups.com";
SmtpClient sC = new SmtpClient(SERVER);
sC.EnableSsl = false;
ContentType contentType = new ContentType();
contentType.MediaType = MediaTypeNames.Application.Octet;
contentType.Name = "xml.xml";
sC.Send(oMail);
oMail = null; // free up resources
lblMessage.ForeColor = System.Drawing.Color.DarkKhaki;
lblMessage.Text = "EMail Sent";
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('EMail Sent');", true);
}
else
{
lblMessage.Text = "The Email you entered not exists.";
}
}
//}
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Session.Clear();
Session.Abandon();
Response.Redirect("default.aspx");
}
Not able to set image source Uri on find Object.
Stackpanel contain two children Textbox and image control.
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
var textBox = (TextBox)sender;
textBox.Style = Application.Current.Resources["TextBoxNormal"] as Style;
textBox.FontSize = 15;
textBox.Foreground = new SolidColorBrush(Colors.Gray);
var stackpanel = textBox.Parent as StackPanel;
if (stackpanel == null)return;
var img = stackpanel.Children.Where(a => a is Image).FirstOrDefault();
if (textBox.Text != "")
{
//I was trying set Uri as mention below, but there is Nothing like "Image.Source"
//image.Source = new BitmapImage(new Uri("/Images/Others/TickRight.png", UriKind.RelativeOrAbsolute));
}
So I Would suggest Trouble shooting here.
if (textBox.Text != "")
{
BitmapImage picture = new BitmapImage(new Uri("/Images/Others/TickRight.png", UriKind.RelativeOrAbsolute));
picture.ImageFailed += (o, e) => System.Threading.SynchronizationContext.Current.Send((oo) => System.Windows.Browser.HtmlPage.Window.Alert("Image failed: " + e.ErrorException), null);
picture.ImageOpened += (o, e) => System.Threading.SynchronizationContext.Current.Send((oo) => System.Windows.Browser.HtmlPage.Window.Alert("Image opened: " + e.OriginalSource), null);
image.Source = picture;
}
//BANG.. your error should be naked!
You need cast img as Image
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
var stackpanel = textBox.Parent as StackPanel;
if (stackpanel == null)return;
var img = stackpanel.Children.Where(a => a is Image).FirstOrDefault() as Image;
}
I have a gridview control that i am manually binding the data in. When i edit a row and update it the values of the text boxes that are sent are always the Old Values. I've found a few threads on this but have not had any luck extracting the new values.
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
Private Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
Dim gv As GridView = sender
For i As Integer = 0 To gv.Columns.Count Step 1
Dim cell As DataControlFieldCell = gv.Rows(e.RowIndex).Cells(i)
gv.Columns(0).ExtractValuesFromCell(e.NewValues, cell, DataControlRowState.Edit, True)
Next
For Each s As DictionaryEntry In e.NewValues
Debug.Print(s.Key & " | " & s.Value)
Next
ds.Tables("testTable").Rows(e.RowIndex).BeginEdit()
[ ... ]
ds.Tables("testTable").Rows(e.RowIndex).EndEdit()
GridView1.EditIndex = -1
BindData()
End Sub
I also want to point out that the ExtractValuesFromCell code is just my most recent attempt to get the New Data. Prior to that i was using something like this
Dim tb as TextBox = sender.Rows(e.RowIndex).Cells(1).Controls(0)
Label1.Text = tb.Text
Also here is how the data looks to start
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (ds.Tables.Count = 0) Then
ds.Tables.Add("testTable")
ds.Tables("testTable").Columns.Add("Driver Name")
ds.Tables("testTable").Columns.Add("Total")
ds.Tables("testTable").Columns.Add("# Of Calls")
ds.Tables("testTable").Columns("Total").ReadOnly = True
ds.Tables("testTable").Columns("# Of Calls").ReadOnly = True
Dim newRow As DataRow = ds.Tables("testTable").NewRow()
newRow("Driver Name") = ""
newRow("Total") = ""
newRow("# Of Calls") = ""
ds.Tables("testTable").Rows.Add(newRow)
End If
BindData()
End Sub
You should DataBind your GridView only if Not Page.IsPostback, otherwise the new values are overwritten.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowupdating.aspx
public static void filedownload(string Path)
{
string str = "";
FileInfo file = new FileInfo(Path);
// Checking if file exists
if (file.Exists)
{
// Clear the content of the response
HttpContext.Current.Response.ClearContent();
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
// Add the file size into the response header
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
HttpContext.Current.Response.ContentType = CommonStrings.returnextension(file.Extension.ToLower());
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
HttpContext.Current.Response.WriteFile(file.FullName);
// End the response
HttpContext.Current.Response.End();
}
else
{
// 9-vgrfu8i "File Not Found!";
}
// Response.Redirect(e.CommandArgument.ToString());
}
public static string GetBarCodeid(ListBox lbListBox)
{
string strCode = "";
if (lbListBox.Items.Count > 0)
{
for (int i = 0; i < lbListBox.Items.Count; i++)
{
if (lbListBox.Items[i].Selected == true)
{
if (strCode == "")
{
strCode = lbListBox.Items[i].Value.ToString();
}
else
{
strCode += "," + lbListBox.Items[i].Value.ToString();
}
}
}
}
return strCode;
}
public static string GetBarCodeName(ListBox lbListBox)
{
string strBarCodeName = "";
if (lbListBox.Items.Count > 0)
{
for (int i = 0; i < lbListBox.Items.Count; i++)
{
if (lbListBox.Items[i].Selected == true)
{
if (strBarCodeName == "")
{
strBarCodeName = lbListBox.Items[i].Text.ToString();
}
else
{
strBarCodeName += "," + lbListBox.Items[i].Text.ToString();
}
}
}
}
return strBarCodeName;
}
public static double GetBarCodeCount(ListBox lbListBox, double Count)
{
double intBarCodeCount = 0;
if (lbListBox.Items.Count > 0)
{
for (int i = 0; i < lbListBox.Items.Count; i++)
{
if (lbListBox.Items[i].Selected == true)
{
if (intBarCodeCount == 0)
{
intBarCodeCount = 1;
}
else
{
intBarCodeCount++;
}
}
}
}
return intBarCodeCount;
}
public static void SelectListBox(ListBox lbListBox, string strBarCodeId)
{
ExecuteProcedures ex = new ExecuteProcedures(1, MasterCommonStrings.ConnectionString);
ex.Parameters.Add("#vcrBarCodeid", SqlDbType.VarChar, 500, strBarCodeId);
DataTable dt = (DataTable)ex.LoadTableWithProcedure("Proc_Erp_Trn_Get_BarCode_Bata");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < lbListBox.Items.Count; j++)
{
if (dt.Rows[i]["data"].ToString() == lbListBox.Items[j].Value.ToString())
{
lbListBox.Items[j].Selected = true;
break;
}
}
}
}
}
public static string GetgridBarCode(DataTable dt, string strColumnName)
{
string strBarCodeCount = "";
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
if (Convert.ToInt32(dt.Rows[i]["intStatus"]) != 2)
{
if (dt.Rows[i][strColumnName].ToString() != "")
if (strBarCodeCount == "")
{
strBarCodeCount = dt.Rows[i][strColumnName].ToString();
}
else
{
strBarCodeCount += dt.Rows[i][strColumnName].ToString();
}
}
}
}
return strBarCodeCount;
}
public static DataTable CheckBarCodeExistsOrNot(ListBox lbListbox, string strColumeName, string strReplacegridBarCodeid, DataView dvDescription)
{
DataTable dtDescription = new DataTable();
dtDescription = (DataTable)dvDescription.Table;
string strgridBarCode = CommonFunctions.GetgridBarCode(dtDescription, strColumeName);
string strSelectBarCode = CommonFunctions.GetBarCodeid(lbListbox);
ExecuteProcedures ex = new ExecuteProcedures(3, MasterCommonStrings.ConnectionString);
ex.Parameters.Add("#vcrgridBarcodeid", SqlDbType.VarChar, 500, strgridBarCode);
ex.Parameters.Add("#vcrSelectBarcodeid", SqlDbType.VarChar, 500, strSelectBarCode);
ex.Parameters.Add("#vcrReplaceBarCodeid", SqlDbType.VarChar, 500, strReplacegridBarCodeid);
DataTable dt = (DataTable)ex.LoadTableWithProcedure("Proc_Erp_Trn_Check_BarCode_Exists_Or_Not");
return dt;
}
public static int BarcodeUpdateIntoBarCodeDrec(string strBarCode_Description_Drec_id, SqlTransaction sqlTran, SqlConnection Con)
{
ExecuteProcedures ex = new ExecuteProcedures(1, MasterCommonStrings.ConnectionString);
ex.Parameters.Add("#intBarCode_Description_Drec_id", SqlDbType.VarChar, 8000, strBarCode_Description_Drec_id);
int i = Convert.ToInt32(ex.InvokeProcedure("Proc_Erp_Trn_Update_erp_mst_BarCode_Drec", sqlTran, ValueDataType.Number, Con));
if (i != 0)
{
return i;
}
else
{
return 0;
}
}
public static string AddBarcodeToListBox(TextBox txtScanBarcode, ListBox lbScanBarCode, ListBox lbSystemBarCode)
{
string barcodePresent = "";
if (txtScanBarcode.Text != "")
{
foreach (ListItem li in lbSystemBarCode.Items)
{
if (li.Text != txtScanBarcode.Text)
{
barcodePresent = "Not In Our System";
}
else
{
if (li.Selected == true)
{
barcodePresent = "Barcode Already Scan";
txtScanBarcode.Text = "";
txtScanBarcode.Focus();
break;
}
else
{
lbScanBarCode.Items.Add(txtScanBarcode.Text);
li.Selected = true;
txtScanBarcode.Text = "";
txtScanBarcode.Focus();
barcodePresent = "Barcode Scan Successfully";
break;
}
}
}
if (barcodePresent == "Not In Our System")
{
txtScanBarcode.Text = "";
txtScanBarcode.Focus();
}
}
else
{
barcodePresent = "Please Scan Barcode";
}
return barcodePresent;
}
public static void RemoveBarCodeFromListBox(ListBox lbScanBarCode, ListBox lbSystemBarCode)
{
if (lbScanBarCode.Items.Count > 0)
{
for (int i = 0; i < lbScanBarCode.Items.Count; i++)
{
if (lbScanBarCode.Items[i].Selected)
{
foreach (ListItem li1 in lbSystemBarCode.Items)
{
if (lbScanBarCode.Items[i].Text == li1.Text)
{
li1.Selected = false;
break;
}
}
lbScanBarCode.Items.Remove(lbScanBarCode.Items[i]);
}
}
}
}
public static void AddBarcodeToGridListBox(ListBox lbBarCode, ListBox lbGridScanBarCodeDisplay)
{
if (lbBarCode.Items.Count > 0)
{
for (int i = 0; i < lbBarCode.Items.Count; i++)
{
if (lbBarCode.Items[i].Selected == true)
{
lbGridScanBarCodeDisplay.Items.Add(lbBarCode.Items[i].Text);
}
}
}
}
public static void Alert(string strMessage, System.Web.UI.Page PAGE)
{
HttpContext Current = HttpContext.Current;
string strScript = "<script type=text/javascript>alert('" + strMessage + "')</script>";
if (!PAGE.IsStartupScriptRegistered("Alert"))
{
PAGE.RegisterStartupScript("Alert", strScript);
}
}
public static int DeletedTotalDrec(DataView dv, string strTableName, string strColumnName, string Value, SqlTransaction SqlTra, SqlConnection Con)
{
DataTable dtDrec = new DataTable();
dtDrec = (DataTable)dv.Table;
int i = 0;
if (dtDrec.Rows.Count > 0)
{
ExecuteProcedures one = new ExecuteProcedures(3, MasterCommonStrings.ConnectionString);
one.Parameters.Add("#TableName", SqlDbType.VarChar, 8000, strTableName);
one.Parameters.Add("#ColumnName", SqlDbType.VarChar, 8000, strColumnName);
one.Parameters.Add("#ColumnValue", SqlDbType.VarChar, 8000, Value);
int b = Convert.ToInt32(one.InvokeProcedure("Proc_Erp_Trn_Deleted_Transction_Total_Drec", SqlTra, ValueDataType.Number, Con));
for (int j = 0; j < dtDrec.Rows.Count; j++)
{
ExecuteProcedures EX = new ExecuteProcedures(19, MasterCommonStrings.ConnectionString);
EX.Parameters.Add("#TableName", SqlDbType.VarChar, 8000, strTableName);
EX.Parameters.Add("#FirstColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[0].ColumnName.ToString());
EX.Parameters.Add("#SecondColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[1].ColumnName.ToString());
EX.Parameters.Add("#ThiredColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[2].ColumnName.ToString());
EX.Parameters.Add("#FourColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[3].ColumnName.ToString());
EX.Parameters.Add("#FiveColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[4].ColumnName.ToString());
EX.Parameters.Add("#SixtColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[5].ColumnName.ToString());
EX.Parameters.Add("#SevenColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[6].ColumnName.ToString());
EX.Parameters.Add("#EightColumnName ", SqlDbType.VarChar, 8000, dtDrec.Columns[7].ColumnName.ToString());
EX.Parameters.Add("#NineColumnName", SqlDbType.VarChar, 8000, strColumnName);
EX.Parameters.Add("#FirstColumnNameValue ", SqlDbType.VarChar, 8000, dtDrec.Rows[j][0].ToString());
EX.Parameters.Add("#SecondColumnNameValue", SqlDbType.VarChar, 8000, dtDrec.Rows[j][1].ToString());
EX.Parameters.Add("#ThiredColumnNameValue", SqlDbType.VarChar, 8000, dtDrec.Rows[j][2].ToString());
EX.Parameters.Add("#FourColumnNameValue ", SqlDbType.VarChar, 8000, dtDrec.Rows[j][3].ToString());
EX.Parameters.Add("#FiveColumnNameValue", SqlDbType.VarChar, 8000, dtDrec.Rows[j][4].ToString());
EX.Parameters.Add("#SixtColumnNameValue", SqlDbType.VarChar, 8000, dtDrec.Rows[j][5].ToString());
EX.Parameters.Add("#SevenColumnNameValue", SqlDbType.VarChar, 8000, dtDrec.Rows[j][6].ToString());
EX.Parameters.Add("#EightColumnNameValue", SqlDbType.VarChar, 8000, dtDrec.Rows[j][7].ToString());
EX.Parameters.Add("#NineColumnNameValue ", SqlDbType.VarChar, 8000, Value);
i = Convert.ToInt32(EX.InvokeProcedure("proc_erp_Trn_Insert_into_Total_Drec", SqlTra, ValueDataType.Number, Con));
}
}
return i;
}
public static bool CheckRows(Manage_Drec Description)
{
if (Description.InTable.Rows.Count > 0)
{
return true;
}else
{
return false;
}
}
#endregion
# region "Procedures"
public static void SetRadiobutton(string strStatus, RadioButton Rbyes, RadioButton rbNo)
{
if (strStatus == "Yes")
{
Rbyes.Checked = true;
}
else
{
Rbyes.Checked = false;
}
if (strStatus == "No")
{
rbNo.Checked = true;
}
else
{
rbNo.Checked = false;
}
}
public static void Set_CheckBox(bool Status, CheckBox ChkName)
{
if (Status == true)
{
ChkName.Checked = true;
}
else
{
ChkName.Checked = false;
}
}
public static void DoSomeFileWritingStuff(string message)
{
//Debug.WriteLine("Writing to file...");
try
{
using (StreamWriter writer = new StreamWriter(LOG_FILE, true))
{
if (message == "")
{
writer.WriteLine("Cache Callback: {0}", DateTime.Now);
}
else
{
writer.WriteLine(message);
}
writer.Close();
}
AspSendEmail smail = new AspSendEmail();
//smail.strHost = mail.intrawebsolns.com
smail.SendEmail("support#intrawebsolns.com", "amit4692#gmail.com", "Exception Error", message, "Error ERP");
}
catch (Exception x)
{
//Debug.WriteLine(x);
DoSomeFileWritingStuff(x.Message);
}
//Debug.WriteLine("File write successful");
}
public static void SetRights(string Rights, Panel pnl)
{
foreach (Control ctrl in pnl.Controls)
{
if (ctrl.GetType().Name == "Button")
{
if ((((Button)ctrl).ID == "btnAdd" && Rights.IndexOf("A") > -1) || (((Button)ctrl).ID == "btnEdit" && Rights.IndexOf("E") > -1)
|| (((Button)ctrl).ID == "btnDelete" && Rights.IndexOf("D") > -1))
{
ctrl.Visible = true;
}
if ((((Button)ctrl).ID == "btnAdd" && Rights.IndexOf("S") > -1) || (((Button)ctrl).ID == "btnEdit" && Rights.IndexOf("S") > -1)
|| (((Button)ctrl).ID == "btnDelete" && Rights.IndexOf("S") > -1))
{
ctrl.Visible = true;
}
}
}
}
#endregion
public static void Enable_Btn_For_Add(Button btnAdd, Button btnCancel, Button btnDelete, Button btnEdit, Button btnUpdate, Button btnexit, Button btnfind)
{
btnEdit.Enabled = false;
btnAdd.Enabled = false;
btnfind.Enabled = false;
btnUpdate.Enabled = true;
btnCancel.Enabled = true;
btnDelete.Enabled = false;
btnexit.Enabled = true;
}
public static bool Check_Entry_exists(string tableName, string columnName, string columnValue)
{
bool result=false;
try
{
ExecuteProcedures ex = new ExecuteProcedures(4, AccountCommonStrings.ConnectionString);
ex.Parameters.Add("#tableName", SqlDbType.VarChar, 100, tableName);
ex.Parameters.Add("#columnName", SqlDbType.VarChar, 100, columnName);
ex.Parameters.Add("#columnValue", SqlDbType.VarChar, 100, #columnValue);
ex.Parameters.Add("#isbitdeleted", SqlDbType.Int, 0);
string temp =Convert.ToString( ex.InvokeProcedure("proc_check_Delete_entry", ValueDataType.String));
if (temp == "false")
{
result = false;
}
else
{
result = true;
}
}
catch (Exception)
{
}
return result;
}
public static bool Check_Entry_exists(string tableName, string columnName, string columnValue,string isbitdeleted)
{
bool result = false;
try
{
ExecuteProcedures ex = new ExecuteProcedures(4, AccountCommonStrings.ConnectionString);
ex.Parameters.Add("#tableName", SqlDbType.VarChar, 100, tableName);
ex.Parameters.Add("#columnName", SqlDbType.VarChar, 100, columnName);
ex.Parameters.Add("#columnValue", SqlDbType.VarChar, 100, #columnValue);
ex.Parameters.Add("#isbitdeleted", SqlDbType.Int, isbitdeleted);
string temp = Convert.ToString(ex.InvokeProcedure("proc_check_Delete_entry", ValueDataType.String));
if (temp == "false")
{
result = false;
}
else
{
result = true;
}
}
catch (Exception)
{
}
return result;
}
}