Query with distinct keyword and subquery not working in Hive with udf - hive

Not working Query :
select lookup(city, state, tax,'addresslookup')
from (select distinct city, state, tax
from open_glory.addylookup) a
Working Query (without distinct):
select lookup(city, state, tax,'addresslookup')
from (select city, state, tax
from open_glory.addylookup) a
Any help would be appreciated.
UDF code:
Not working Query :
select lookup(city, state, tax,'addresslookup')
from (select distinct city, state, tax
from open_glory.addylookup) a
Working Query (without distinct):
select lookup(city, state, tax,'addresslookup')
from (select city, state, tax
from open_glory.addylookup) a
Any help would be appreciated.
UDF code:
public class Lookup extends GenericUDF {
private static String delimiter = "|";
private ConcurrentHashMap < String, HashMap < String, String >> fileMap = new ConcurrentHashMap < String, HashMap < String, String >> ();
protected String loggedInUser;
protected String loggedInApplication;
private transient GenericUDFUtils.StringHelper returnHelper;
private transient StringConverter[] stringConverter;
private static final Logger LOG = LoggerFactory.getLogger(Lookup.class.getName());
#Override
public ObjectInspector initialize(ObjectInspector[] arguments)
throws UDFArgumentException {
if (arguments.length < 2) {
throw new UDFArgumentLengthException(
"lookup takes 2 or more arguments");
}
stringConverter = new StringConverter[arguments.length];
for (int i = 0; i < arguments.length; i++) {
if (arguments[0].getCategory() != Category.PRIMITIVE) {
throw new UDFArgumentException(
"lookup only takes primitive types");
}
stringConverter[i] = new PrimitiveObjectInspectorConverter.StringConverter(
(PrimitiveObjectInspector) arguments[i]);
}
setLoggedInUser();
returnHelper = new GenericUDFUtils.StringHelper(
PrimitiveCategory.STRING);
LOG.info("initialize successful");
return PrimitiveObjectInspectorFactory.writableStringObjectInspector;
}
private void setLoggedInUser() {
if (loggedInUser == null) {
loggedInUser = SessionState.get().getUserName();
if (loggedInUser != null) {
int idx = loggedInUser.indexOf('.');
loggedInApplication = idx > -1 ? loggedInUser.substring(0, idx) : null;
}
}
}
private void initMap(String f) {
LOG.info("initMap involked");
if (loggedInApplication == null)
throw new NullPointerException(
"Unable to retrieve application name from user.");
String filePath = "/basepath/" + loggedInApplication.toLowerCase() + "/" + f +
".txt";
String line = null;
try {
LOG.info("filePath =" + filePath);
FileSystem fs = FileSystem.get(new Configuration());
FSDataInputStream in = fs.open(new Path(filePath));
BufferedReader br = new BufferedReader(new InputStreamReader( in ));
HashMap < String, String > map = new HashMap < String, String > ();
while ((line = br.readLine()) != null) {
// ignore comment lines
if (line.startsWith("#")) {
continue;
}
String[] strs = line.split("\t");
if (strs.length == 2) {
map.put(strs[0].toUpperCase().trim(), strs[1].trim());
} else if (strs.length > 2) {
map.put(getKey(strs), strs[strs.length - 1].trim());
}
}
fileMap.put(f, map);
br.close();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
public Text getValue(String s, String f) {
initMap(f);
HashMap < String, String > map = fileMap.get(f);
LOG.info("getValue() fileMap =" + fileMap);
String v = map.get(s);
return v == null ? null : new Text(v);
}
#Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
String val = buildVal(arguments);
String lookupFile = (String) stringConverter[arguments.length - 1].convert(arguments[arguments.length - 1].get());
Text returnVal = getValue(val.toUpperCase(), lookupFile.toLowerCase());
return returnVal == null ? null : returnHelper.setReturnValue(returnVal.toString());
}
#Override
public String getDisplayString(String[] arg0) {
return "lookup()";
}
private String buildVal(DeferredObject[] arguments) throws HiveException {
StringBuilder builder = new StringBuilder();
int cnt = arguments.length - 1;
for (int i = 0; i < cnt; i++) {
builder.append((String) stringConverter[i].convert(arguments[i].get()));
if (i < cnt - 1) {
builder.append(delimiter);
}
}
return builder.toString();
}
private String getKey(String[] strs) {
StringBuilder builder = new StringBuilder();
int cnt = strs.length - 1;
for (int i = 0; i < cnt; i++) {
builder.append(strs[i].toUpperCase().trim());
if (i < cnt - 1) {
builder.append(delimiter);
}
}
return builder.toString();
}
}

Related

Read Data attributes or Custom Attributes in SQL server from string

I want in SQL prepared dynamic query based on the shortcode.
For Eg.
DECLARE #ShortCode VARCHAR(MAX)
SET #ShortCode = '[User data="Name" data="MobileNumber"]';
User = table name
Name = User table field
MobileNumber = User table field
Query output be like
SELECT [Name],[MobileNumber] FROM [dbo].[User]
SET #ShortCode = '[Country data="Name" ID="1"]';
Country = table name
Name = Country table field
ID = User table field
Query output be like
SELECT [Name] FROM [dbo].[Country] WHERE [ID] = 1
How to extract all data attributes values and how to get User in the []
This functionality is done in C#
Here My c# code
// Model class
public class ShortCodeResult
{
public Guid? ID { get; set; }
public string TableName { get; set; }
public bool IsValidShortCode { get; set; }
public string Message { get; set; }
public Dictionary<string,object> KeyValue { get; set; }
public ShortCodeResult() {
KeyValue = new Dictionary<string, object>();
ID = Guid.NewGuid();
}
}
//Regex Filter
public class RegexFilter
{
private string oPattern = #"(\w+)=[\""]([a-zA-Z0-9_.:\""]+)";
public ShortCodeResult GetShortCodeValues(string Code)
{
var oShortCodeModel = new ShortCodeResult();
var oRegex = new Regex(oPattern, RegexOptions.IgnoreCase);
var oTableNameRegex = Regex.Match(Code, #"\b[A-Za-z]+\b", RegexOptions.Singleline).Value;
var lstMatchCollection = oRegex.Matches(Code).Cast<Match>().Where(x=>x.Value.StartsWith("data")).ToList();
if (lstMatchCollection != null && lstMatchCollection.Count > 0)
{
for (int i = 0; i < lstMatchCollection.Count; i++)
{
var oSelected = new Regex("[^=]+$").Match(Convert.ToString(lstMatchCollection[i]));
if (oSelected != null)
{
oShortCodeModel.KeyValue.Add(i.ToString(), oSelected.Value.Trim('"'));
}
}
}
oShortCodeModel.TableName = oTableNameRegex;
return oShortCodeModel;
}
}
//HtmlHelper Extension
public static MvcHtmlString RenderShortCode(this HtmlHelper htmlHelper, string IdOrExprssion)
{
#region Get short code data
var oShortCode = ShortCodeHelper.GetShortCode(IdOrExprssion);
#endregion
var oMvcHtmlString = new MvcHtmlString(IdOrExprssion);
var oRegexFilter = new RegexFilter();
var shortCodeModel = oRegexFilter.GetShortCodeValues(oShortCode.Expression);
var ostringBuilder = new StringBuilder();
if (!string.IsNullOrEmpty(shortCodeModel.TableName))
{
ostringBuilder.AppendLine("SELECT ");
ostringBuilder.AppendLine((shortCodeModel.KeyValue.Count > 0 ? string.Join(",", shortCodeModel.KeyValue.Select(x => x.Value)) : "*"));
ostringBuilder.AppendLine(" FROM ");
ostringBuilder.AppendLine(oShortCode.TableName);
ostringBuilder.AppendLine(" WITH(NOLOCK) ");
if (oShortCode.FilterCode.Count() > 0)
{
ostringBuilder.AppendLine("WHERE ");
foreach (var filterCode in oShortCode.FilterCode)
{
ostringBuilder.AppendLine(filterCode.FilterColumnName);
ostringBuilder.AppendLine(filterCode.Operator);
ostringBuilder.AppendLine(filterCode.FilterColumnValue);
}
}
}
var oDyanamicData = DBHelper.GetDataTable(ostringBuilder.ToString(), System.Data.CommandType.Text, new List<SqlParameter>());
if (oDyanamicData != null)
{
if (oShortCode.IsHtmlRender)
{
for (int i = 0; i < oDyanamicData.Rows.Count; i++)
{
for (int j = 0; j < oDyanamicData.Columns.Count; j++)
{
string key = Convert.ToString(oDyanamicData.Columns[j]);
string value = Convert.ToString(oDyanamicData.Rows[i].ItemArray[j]);
if (oShortCode.DisplayCode.Count > 0)
{
var displayCode = oShortCode.DisplayCode.FirstOrDefault(x => x.DisplayColumnName == key);
if (displayCode != null && !string.IsNullOrEmpty(displayCode?.ReplaceKey))
{
oShortCode.DefinedHtml = oShortCode.DefinedHtml.Replace(displayCode.ReplaceKey, value);
}
}
}
}
return new MvcHtmlString(oShortCode.DefinedHtml);
}
else
{
string key = string.Empty, value = string.Empty;
#region For Json
List<JObject> dataList = new List<JObject>();
for (int i = 0; i < oDyanamicData.Rows.Count; i++)
{
JObject eachRowObj = new JObject();
for (int j = 0; j < oDyanamicData.Columns.Count; j++)
{
key = Convert.ToString(oDyanamicData.Columns[j]);
value = Convert.ToString(oDyanamicData.Rows[i].ItemArray[j]);
eachRowObj.Add(key, value);
}
dataList.Add(eachRowObj);
}
return new MvcHtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(dataList));
#endregion
}
}
return oMvcHtmlString;
}
Can anyone help me solved above in SQL server or prepared query in store procedure

#DataProvider + #Factory + Hashmaps

Facing compilation error when using #Factory with #DataProvider.
Trying to map hashmap to my dataprovider, and want to run all my testcase with first testdata row then next, so trying to use #Factory
HashMap < String, String testdata = new HashMap < String, String();
#Test
private void test_01() {
System.out.println(testdata.get("-some-hashmap-key-"));
}
#DataProvider
public static Object[][] getDataSet() {
int i = 0;
Object[][] dataSet = new Object[2][1];
HashMap < String, String > rowValuesMap = new HashMap();
for (-some logic - ) {
for (-some logic - ) {
dataSet[i][0] = rowValuesMap;
}
i++;
}
return dataSet;
}
#Factory(dataProvider = "getDataSet")
public MyTestFile(HashMap < String, String testdata) {
this.testdata = sheetdata;
}
HashMap declaration is wrong in all place. Try this
HashMap < String, String > testdata = new HashMap < String, String > ();
#Test
private void test_01() {
System.out.println(testdata.get("-some-hashmap-key-"));
}
#DataProvider
public static Object[][] getDataSet() {
int i = 0;
Object[][] dataSet = new Object[2][1];
HashMap < String, String > rowValuesMap = new HashMap < String, String > ();
for (-some logic - ) {
for (-some logic - ) {
dataSet[i][0] = rowValuesMap;
}
i++;
}
return dataSet;
}
#Factory(dataProvider = "getDataSet")
public MyTestFile(HashMap < String, String > testdata) {
this.testdata = sheetdata;
}

Find the largest String in the list

I am required to find the largest string in the ArrayList, and the print it. My code is not currently working though.
public class Solution {
private static List<String> strings;
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
strings = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
String n = reader.readLine();
strings.add(n);
}
String largestString = strings.get(0);
for (int i = 0; i < strings.size(); i++) {
if (strings.get(i).length() > largestString.length()) {
largestString = strings.get(i);
System.out.println(largestString);
}
}
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String value = null;
int length = 0;
for (int i = 0; i < 5; i++) {
String n = reader.nextLine();
if (n != null && n.length() > length) {
length = n.length();
value = n;
}
}
System.out.println("Largest String : " + value + " of length : " + length);
}

Entity Framework in stock market

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();
//}
}
}

Rewriting from MonoTouch Application to MonoDroid

I'm going to rewrite the application from Monotouh to Monodroid application for android. Correct me if I'm wrong. The logic remains the same as in MonoTouch or change anything? If something changes, please tell me, what?
As far as I understand, only GIU changes. Thanks in advance!
So, this is my code where i call data from my server:
namespace Mobile{
public static class SiteHelper
{
public static string DbPath = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "Sql_1.4.sqlite");
public const string TempDbPath = "./Sql.sqlite";
public static UIView View { get; set; }
public static BaseController Controller { get; set; }
private static event NIHandler _noInternetHandler;
private static bool _noInternetShoved = false;
public static string SiteDomain = "http://mysite.com"; //files which connecting to the DB on server (.asx files)
private delegate void NIHandler ();
public static XDocument DoRequest (string Request)
{
if (_noInternetHandler != null) {
foreach (var del in _noInternetHandler.GetInvocationList()) {
_noInternetHandler -= del as NIHandler;
}
}
if (Controller != null)
_noInternetHandler += new NIHandler (Controller.PushThenNoInternet);
string CryptoString = "";
string Language = "ru";
using (MD5 md5Hash = MD5.Create()) {
string hashKey = Guid.NewGuid ().ToString ().Substring (0, 4);
CryptoString = Request + (Request.Contains ("?") ? "&" : "?") + "hash=" + GetMd5Hash (
md5Hash,
"myprogMobhash_" + hashKey
) + "&hashKey=" + hashKey + "&language=" + Language;
UIActivityIndicatorView _preloader = null;
if (Controller != null) {
Controller.InvokeOnMainThread (delegate() {
_preloader = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.Gray);
if (View != null && Request.IndexOf ("login.ashx") == -1
&& Request.IndexOf ("yandex") == -1
&& Request.IndexOf ("GetDialogMessages") == -1) {
lock (_preloader) {
if (_preloader != null && !_preloader.IsAnimating)
_preloader.HidesWhenStopped = true;
_preloader.Frame = new RectangleF (150, 170, 30, 30);
_preloader.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeScale ((float)1.3, (float)1.3);
_preloader.StartAnimating ();
View.Add (_preloader);
}
}
});
}
/*ctx.GetText(Resource.String.SiteAddress)*/
Stream Stream = null;
try {
HttpWebRequest request = new HttpWebRequest (new Uri (SiteDomain + "/FolderWithFiles/" + CryptoString));
request.Timeout = 8000;
Stream = request.GetResponse ().GetResponseStream ();
_noInternetShoved = false;
if (_noInternetHandler != null)
_noInternetHandler -= new NIHandler (Controller.PushThenNoInternet);
} catch (WebException) {
if (_noInternetHandler != null)
_noInternetHandler.Invoke ();
var resp = new XDocument (new XElement ("Response",
new XElement ("status", "error"),
new XElement ("error", "Отсутствует интернет"))
);
return resp;
}
StreamReader Sr = new StreamReader (Stream);
string Resp = Sr.ReadToEnd ();
XDocument Response = XDocument.Parse (Resp.Substring (0, Resp.IndexOf ("<html>") == -1 ? Resp.Length : Resp.IndexOf ("<!DOCTYPE html>")));
string Hash = Response.Descendants ().Where (x => x.Name == "hash")
.FirstOrDefault ().Value;
string HashKey = Response.Descendants ().Where (x => x.Name == "hashKey")
.FirstOrDefault ().Value;
Sr.Close ();
Stream.Close ();
if (Controller != null && _preloader != null) {
Controller.InvokeOnMainThread (delegate() {
lock (_preloader) {
_preloader.StopAnimating ();
_preloader.RemoveFromSuperview ();
}
});
}
if (VerifyMd5Hash (
md5Hash,
"mobileSitehash_" + HashKey,
Hash
))
return Response;
else
throw new Exception ();
}
}
public static XDocument DoWriteFileRequest (string Request, byte[] file)
{
string CryptoString = "";
string Language = "ru";
using (MD5 md5Hash = MD5.Create()) {
string hashKey = Guid.NewGuid ().ToString ().Substring (0, 4);
CryptoString = Request + (Request.Contains ("?") ? "&" : "?") + "hash=" + GetMd5Hash (
md5Hash,
"mobileMobhash_" + hashKey
) + "&hashKey=" + hashKey + "&language=" + Language;
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create (SiteDomain + "/misc/mobile/" + CryptoString);
Req.Method = "POST";
Stream requestStream = Req.GetRequestStream ();
requestStream.Write (file, 0, file.Length);
requestStream.Close ();
Stream Stream = Req.GetResponse ().GetResponseStream ();
StreamReader Sr = new StreamReader (Stream);
string Resp = Sr.ReadToEnd ();
XDocument Response = XDocument.Parse (Resp);
string Hash = Response.Descendants ().Where (x => x.Name == "hash")
.FirstOrDefault ().Value;
string HashKey = Response.Descendants ().Where (x => x.Name == "hashKey")
.FirstOrDefault ().Value;
Sr.Close ();
Stream.Close ();
if (VerifyMd5Hash (
md5Hash,
"mobileSitehash_" + HashKey,
Hash
))
return Response;
else
throw new Exception ();
}
}
public static string GetMd5Hash (MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash (Encoding.UTF8.GetBytes (input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder ();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++) {
sBuilder.Append (data [i].ToString ("x2"));
}
// Return the hexadecimal string.2
return sBuilder.ToString ();
}
//Geting the info for my app
public static List<PackageListModel> GetUserPackages (int UserID)
{
List<PackageListModel> Events = new List<PackageListModel> ();
string Req = "SomeFile.ashx?UserID=" + UserID;
XDocument XmlAnswer = DoRequest (Req);
if (XmlAnswer.Descendants ("status").First ().Value == "ok") {
foreach (var el in XmlAnswer.Descendants ("Response").First ().Descendants().Where(x=>x.Name == "Event")) {
PackageListModel Event = null;
Event = new PackageListModel ()
{
ID = int.Parse(el.Attribute("ID").Value),
Title = el.Element("Title").Value,
Date = el.Element("Date").Value,
Price = el.Element("Price").Value,
ImageUrl = el.Element("ImageUrl").Value,
Location = el.Element("Location").Value
};
Events.Add (Event);
}
}
return Events;
}
//Получить пользовательские поездки
public static List<TransporterListModel> GetUserTransporters (int UserID)
{
List<TransporterListModel> Events = new List<TransporterListModel> ();
string Req = "SomeFile.ashx?UserID=" + UserID;
XDocument XmlAnswer = DoRequest (Req);
if (XmlAnswer.Descendants ("status").First ().Value == "ok") {
foreach (var el in XmlAnswer.Descendants ("Response").First ().Descendants().Where(x=>x.Name == "Event")) {
TransporterListModel Event = null;
Event = new TransporterListModel ()
{
ID = int.Parse(el.Attribute("ID").Value),
Date = el.Element("Date").Value,
Price = el.Element("Price").Value,
TransportsStr = el.Element("Transports").Value,
Location = el.Element("Location").Value
};
Events.Add (Event);
}
}
return Events;
}
}
}
}
I think you should read this.
In brief - you can reuse application logic that not depends on platform-specific parts, so working with database/server can be shared between MonoTouch and Mono for Android.