I need some help. I need to combine these two methods into one and I can't figure out how.
I tried with an IF statement (we checked if employeeMark is NullOrEmpty, we use the first logic and if it's not, the second logic) but it's just duplicated code in one method instead of two.
This is the first method :
private async Task<ProcessedContractsIdentifiers> GetContractsIdentifiersByContractsCodes(List<ImportableContractIdentifier> importableContractsIdentifiers)
{
var errors = new List<ContractImportValidationErrorDto>();
foreach (var contract in importableContractsIdentifiers.Where(contract => string.IsNullOrWhiteSpace(contract.ContractCode)))
{
errors.Add(new ContractImportValidationErrorDto
{
ValidatedCode = string.Empty,
Line = contract.RowNumber,
ErrorCode = ContractImportValidationErrorCode.ContractCodeIsRequired
});
}
var contractsCodes = importableContractsIdentifiers.ConvertAll(x => x.ContractCode);
contractsCodes = contractsCodes.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
var contractsSignatures = await GetContractsSignaturesByContractsCodes(contractsCodes);
var unresolvedContracts = contractsCodes.Except(contractsSignatures.Select(cs => cs.Code)).ToHashSet();
foreach (var c in unresolvedContracts)
{
errors.Add(new ContractImportValidationErrorDto
{
ValidatedCode = c,
ErrorCode = ContractImportValidationErrorCode.InvalidContractCode
});
}
return new ProcessedContractsIdentifiers
{
IdentificationMethod = ContractIdentificationMethod.ByContractCode,
IdentifiedContractsSignatures = contractsSignatures,
NonIdentifiableContracts = errors
};
}
And this is the second method :
private async Task<ProcessedContractsIdentifiers> GetContractsIdentifiersByEmployeesMarks(List<ImportableContractIdentifier> importableContractsIdentifiers)
{
const int withSingleContract = 1;
var errors = new List<ContractImportValidationErrorDto>();
foreach (var contract in importableContractsIdentifiers.Where(contract => string.IsNullOrWhiteSpace(contract.EmployeeMark)))
{
errors.Add(new ContractImportValidationErrorDto
{
ValidatedCode = string.Empty,
Line = contract.RowNumber,
ErrorCode = ContractImportValidationErrorCode.EmployeeMarkIsRequired
});
}
var employeesMarks = importableContractsIdentifiers.Select(x => x.EmployeeMark).Where(x => !string.IsNullOrWhiteSpace(x)).ToHashSet();
var contractsSignatures = await GetContractsSignaturesByEmployeeMark(employeesMarks);
var contractsGroupedByEmployeeMark = contractsSignatures.GroupBy(x => x.EmployeeMark);
foreach (var contracts in contractsGroupedByEmployeeMark.Where(x => x.ToList().Count != withSingleContract))
{
errors.Add(new ContractImportValidationErrorDto
{
ValidatedCode = contracts.Key,
ErrorCode = ContractImportValidationErrorCode.EmployeeMarkWithMultipleContracts
});
}
var unresolvedMarks = employeesMarks.Except(contractsSignatures.Select(cs => cs.EmployeeMark)).ToHashSet();
foreach (var eMark in unresolvedMarks)
{
errors.Add(new ContractImportValidationErrorDto
{
ValidatedCode = eMark,
ErrorCode = ContractImportValidationErrorCode.InvalidEmployeeMark
});
}
return new ProcessedContractsIdentifiers
{
IdentificationMethod = ContractIdentificationMethod.ByEmployeeMark,
IdentifiedContractsSignatures = contractsSignatures,
NonIdentifiableContracts = errors
};
}
Use Enum as parameter, so according to its value you can write code blocks.
public Enum IOMode
{
In=0,
Out=1
}
public void CalculateAttendance(List<Log> lstLog, IOMode eIOMode)
{
if(eIOMode==IOMode.In)
{}
else
{ }
}
call CalculateAttendance(lstLog, IOMode.In) etc
Related
I compare the speed of Sql with ElasticSearch. I have 1.5 million data. But sql query runs faster than elastic search. I don't understand the problem.
Why is the word like query coming faster in sql?
My code for Sql
public static List<Sales> GetAllRecords(string itemType)
{
List<Sales> salesReports = new List<Sales>();
string sqlQuery = String.Format(#"SELECT * FROM dbo.Sales where Region like '%{0}%'", itemType);
using (SqlConnection connection = new SqlConnection(CONNECTION_STRING))
{
var result = connection.Query<Sales>(sqlQuery);
foreach (var item in result)
{
Sales global = new Sales()
{
Region = item.Region,
Country = item.Country,
Item_Type=item.Item_Type,
Order_Date=item.Order_Date,
Order_ID = item.Order_ID,
Order_Priority=item.Order_Priority,
Sales_Channel=item.Sales_Channel,
Ship_Date = item.Ship_Date,
Total_Cost=item.Total_Cost,
Total_Profit=item.Total_Profit,
Total_Revenue=item.Total_Revenue,
Units_Sold=item.Units_Sold,
Unit_Cost=item.Unit_Cost,
Unit_Price = item.Unit_Price
};
salesReports.Add(global);
}
return result.ToList();
}
}
My code for ElasticSearch.
I search the data that I indexed before with elasticsearch here.
public static List<Sales> ConfigureES(string inputText)
{
List<Sales> salesReports = new List<Sales>();
// 1. Connection URL's elastic search
var listOfUrls = new Uri[]
{
// here we can set multple connectionn URL's...
new Uri("http://localhost:9200/")
};
StaticConnectionPool connPool = new StaticConnectionPool(listOfUrls);
ConnectionSettings connSett = new ConnectionSettings(connPool);
ElasticClient eClient = new ElasticClient(connSett);
// var see = eClient.DeleteIndex(INDEX_NAME);
// check the connection health
var checkClusterHealth = eClient.ClusterHealth();
if (checkClusterHealth.ApiCall.Success && checkClusterHealth.IsValid)
{
// 2. check the index exist or not
var checkResult = eClient.IndexExists(INDEX_NAME);
if (!checkResult.Exists)
{
// Raise error to Index not avaliable
}
// Search particular text field
var searchResponse = eClient.Search<Sales>(s =>
s.Index(INDEX_NAME).From(0).Size(5000).Scroll("10m")
.Query(q => q.Match(m => m.Field(f => f.Region).Query(inputText))));
//var results = eClient.Scroll<Salesreport>("10m", searchResponse.ScrollId);
while (searchResponse.Documents.Any())
{
var res = searchResponse.Documents;
var sds = res.Cast<Sales>();
salesReports.AddRange(sds);
searchResponse = eClient.Scroll<Sales>("10m", searchResponse.ScrollId);
}
}
else
{
// fail log the exception further use
var exception = checkClusterHealth.OriginalException.ToString();
var debugException = checkClusterHealth.DebugInformation.ToString();
}
return salesReports;
}
where I index data to elasticsearch.
public static string CONNECTION_STRING = string.Empty;
public static string INDEX_NAME = "elastic";
public static string INDEX_TYPE = "report4";
private static ElasticClient eClient;
static void Main(string[] args)
{
try
{
// read the config file ...
var configuration = new ConfigurationBuilder()
.SetBasePath(#"C:\Users\Celal\Desktop\ElasticSearch-master\ElasticSearch-master\ElasticSearchBGPJob\ElasticSearchBGPJob\ElasticSearchBGPJob")
.AddJsonFile("appsettings.json", false)
.Build();
CONNECTION_STRING = configuration.GetSection("DefaultConnection").Value;
if (string.IsNullOrEmpty(CONNECTION_STRING))
throw new ArgumentException("No connection string in appsettings.json");
// 1. Connection URL's elastic search
var listOfUrls =
// here we can set multple connectionn URL's...
new Uri("http://localhost:9200/");
ConnectionSettings connSett = new ConnectionSettings(listOfUrls);
eClient = new ElasticClient(connSett);
// var see = eClient.DeleteIndex(INDEX_NAME);
var createIndexDescriptor = new CreateIndexDescriptor(INDEX_NAME).Mappings(ms => ms.Map<Sales>(m => m.AutoMap()));
// check the connection health
var checkClusterHealth = eClient.ClusterHealth();
if (checkClusterHealth.ApiCall.Success && checkClusterHealth.IsValid)
{
// 2. check the index exist or not
var checkResult = eClient.IndexExists(INDEX_NAME);
if (!checkResult.Exists)
{
var createIndexResponse = eClient.CreateIndex(createIndexDescriptor);
if (createIndexResponse.ApiCall.Success && createIndexResponse.IsValid)
{
// index is created successfully....
}
else
{
// fail log the exception further use
var exception = createIndexResponse.OriginalException.ToString();
var debugException = createIndexResponse.DebugInformation.ToString();
}
}
// 3. get the last documet id of index
var lastRecordResponse = eClient.Search<Sales>(s => s
.Index(INDEX_NAME)
.Type(INDEX_TYPE)
.From(0)
.Size(1).Sort(sr => sr.Descending(f => f.Order_ID)));
if (lastRecordResponse.ApiCall.Success && lastRecordResponse.IsValid)
{
Console.WriteLine("Start " + DateTime.Now);
long salesRecordId = 0;
var listofrecords = new List<Sales>();
if (lastRecordResponse.Documents.Count >= 1)
{
var obj = lastRecordResponse.Documents;
foreach (var item in obj)
{
salesRecordId = item.Order_ID;
}
listofrecords = GetAllRecords(salesRecordId);
}
else
{
listofrecords = GetAllRecords(salesRecordId);
}
Console.WriteLine("END " + DateTime.Now);
// Insert the data into document format corresponding index...
if (listofrecords.Count > 0)
{
Console.WriteLine("===== START========= " + DateTime.Now);
BulkInsertData(listofrecords, eClient).Wait();
Console.WriteLine("===== END========= " + DateTime.Now);
}
}
else
{
// fail log the exception further use
var exception = lastRecordResponse.OriginalException.ToString();
var debugException = lastRecordResponse.DebugInformation.ToString();
}
}
else
{
// fail log the exception further use
var exception = checkClusterHealth.OriginalException.ToString();
var debugException = checkClusterHealth.DebugInformation.ToString();
}
Console.WriteLine("Hello World!");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
public static List<Sales> GetAllRecords(long LastSalesId)
{
List<Sales> salesReports = new List<Sales>();
string sqlQuery = String.Format(#"SELECT * FROM dbo.Sales where Order_ID > {0} ", LastSalesId);
using (SqlConnection connection = new SqlConnection(CONNECTION_STRING))
{
connection.Open();
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
command.CommandTimeout = 1000;
using (SqlDataReader dataReader = command.ExecuteReader())
{
if (dataReader.HasRows)
{
while (dataReader.Read())
{
Sales global = new Sales()
{
Order_ID=Convert.ToInt32(dataReader["Order_ID"]),
Region=Convert.ToString(dataReader["Region"]),
Country = Convert.ToString(dataReader["Country"]),
Total_Cost = (decimal)Convert.ToDouble(dataReader["Total_Cost"]),
Total_Revenue = Convert.ToString(dataReader["Total_Revenue"]),
Item_Type = Convert.ToString(dataReader["Item_Type"])
};
salesReports.Add(global);
}
}
}
}
connection.Close();
}
return salesReports;
}
static async Task BulkInsertData(List<Sales> ListofData, ElasticClient Eclient)
{
try
{
var splitTheLargeList = ChunkBy(ListofData);
var test = splitTheLargeList.LastOrDefault();
foreach (var item in splitTheLargeList)
{
var bulkResponse = await Eclient.BulkAsync(b => b
.Index(INDEX_NAME)
// .Type(INDEX_TYPE)
.IndexMany(item));
if (bulkResponse.ApiCall.Success && bulkResponse.IsValid)
{
// success fully inserted...
}
else
{
// fail log the exception further use
var exception = bulkResponse.OriginalException.ToString();
var debugException = bulkResponse.DebugInformation.ToString();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException.ToString());
}
}
public static List<List<T>> ChunkBy<T>(List<T> source, int chunkSize = 1000)
{
return source
.Select((x, i) => new { Index = i, Value = x })
.GroupBy(x => x.Index / chunkSize)
.Select(x => x.Select(v => v.Value).ToList())
.ToList();
}
public static IEnumerable<List<T>> SplitList<T>(List<T> ListofData, int listSize = 1000)
{
for (int i = 0; i < ListofData.Count; i += listSize)
{
yield return ListofData.GetRange(i, Math.Min(listSize, ListofData.Count - i));
}
}
In a list i have 4 rows and I am try to get all the rows of the list but it is giving only one row, how to get all the rows of the list.
I have tried below code
public async Task<ResponseUserModel> get()
{
List<ResponseUserModel> responseUsers = new List<ResponseUserModel>();
using (nae2sasqld0003Entities context = new nae2sasqld0003Entities())
{
var listt = context.Producers.Select(all => all).ToList();
foreach (var item in listt)
{
responseUsers.Add(new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
});
}
return responseUsers;
}
}
please let me know where i to fix the issue
Use list to return all:
List<ResponseUserModel> responseUsers = new List<ResponseUserModel>();
then
foreach (var item in listt)
{
responseUsers.Add(new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
});
}
return responseUsers;
Note: change return type of the method to IList<ResponseUserModel>
or in this way
using (var context = new nae2sasqld0003Entities())
{
return context.Producers.Select(item =>
new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
}).ToList();
}
I need to refactor the below code so that the deleted_at logic will be outside of the foreach (var app in data) loop. I tried to create the list guids and then add guids to it but its not working because model.resources is inside the loop and it is still deleting all the apps.
I need deleted_at logic outside because I'm trying to delete all apps which are in the database but are not in new data that I'm receiving from API.
If you have a better approach on my code I would love to see that, Thank you.
public async Task GetBuilds()
{
var data = new List<GetBuildTempClass>();
var guids = new List<GetBuildTempClass>();
using (var scope = _scopeFactory.CreateScope())
{
var _DBcontext = scope.ServiceProvider.GetRequiredService<PCFStatusContexts>();
foreach (var app in data)
{
var request = new HttpRequestMessage(HttpMethod.Get,
"apps/" + app.AppGuid + "/builds?per_page=200&order_by=updated_at");
var response = await _client_SB.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();
BuildsClass.BuildsRootObject model =
JsonConvert.DeserializeObject<BuildsClass.BuildsRootObject>(json);
foreach (var item in model.resources)
{
var x = _DBcontext.Builds.FirstOrDefault(o =>
o.Guid == Guid.Parse(item.guid));
if (x == null)
{
_DBcontext.Builds.Add(new Builds
{
Guid = Guid.Parse(item.guid),
State = item.state,
CreatedAt = item.created_at,
UpdatedAt = item.updated_at,
Error = item.error,
CreatedByGuid = Guid.Parse(item.created_by.guid),
CreatedByName = item.created_by.name,
CreatedByEmail = item.created_by.email,
AppGuid = app.AppGuid,
AppName = app.AppName,
Foundation = 2,
Timestamp = DateTime.Now
});
}
else if (x.UpdatedAt != item.updated_at)
{
x.State = item.state;
x.UpdatedAt = item.updated_at;
x.Timestamp = DateTime.Now;
}
var sqlresult = new GetBuildTempClass
{
AppGuid = Guid.Parse(item.guid)
};
guids.Add(sqlresult);
}
//var guids = model.resources.Select(r => Guid.Parse(r.guid));
var builds = _DBcontext.Builds.Where(o =>
guids.Contains(o.Guid) == false &&
o.Foundation == 2 && o.DeletedAt == null);
foreach (var build_item in builds)
{
build_item.DeletedAt = DateTime.Now;
}
}
await _DBcontext.SaveChangesAsync();
}
}
I got it working I added var guids = new List < Guid > (); list to store data,
added guids.Add(Guid.Parse(item.guid)); to populate the list and finally wrote var builds = _DBcontext.Builds.Where(o = >guids.Contains(o.Guid) == false && o.Foundation == 2 && o.DeletedAt == null); outside the loop.
If anyone has a better suggestion please add a new answer.
public async Task GetBuilds() {
var data = new List < GetBuildTempClass > ();
var guids = new List < Guid > ();
using(var scope = _scopeFactory.CreateScope()) {
var _DBcontext = scope.ServiceProvider.GetRequiredService < PCFStatusContexts > ();
foreach(var app in data) {
var request = new HttpRequestMessage(HttpMethod.Get, "apps/" + app.AppGuid + "/builds?per_page=200&order_by=updated_at");
var response = await _client_SB.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();
BuildsClass.BuildsRootObject model = JsonConvert.DeserializeObject < BuildsClass.BuildsRootObject > (json);
foreach(var item in model.resources) {
var x = _DBcontext.Builds.FirstOrDefault(o = >o.Guid == Guid.Parse(item.guid));
if (x == null) {
_DBcontext.Builds.Add(new Builds {
Guid = Guid.Parse(item.guid),
State = item.state,
CreatedAt = item.created_at,
UpdatedAt = item.updated_at,
Error = item.error,
CreatedByGuid = Guid.Parse(item.created_by.guid),
CreatedByName = item.created_by.name,
CreatedByEmail = item.created_by.email,
AppGuid = app.AppGuid,
AppName = app.AppName,
Foundation = 2,
Timestamp = DateTime.Now
});
}
else if (x.UpdatedAt != item.updated_at) {
x.State = item.state;
x.UpdatedAt = item.updated_at;
x.Timestamp = DateTime.Now;
}
guids.Add(Guid.Parse(item.guid));
}
}
var builds = _DBcontext.Builds.Where(o = >guids.Contains(o.Guid) == false && o.Foundation == 2 && o.DeletedAt == null);
foreach(var build_item in builds) {
build_item.DeletedAt = DateTime.Now;
}
await _DBcontext.SaveChangesAsync();
}
}
I have a form for employees called frmEmployees where I need to load couple of combo box with data like country, category, nationality, such others.
Now when user click on to open frmEmployees, window is stuck for bit and then open. I assume that this is because of data loading and initializing the combo box.
Now! what I want is, just after click on button to open frmEmployees run a progress bar till data loading complete and then open form.
public frmEmployee()
{
InitializeComponent();
con = new Connection();
LoadComboboxDS();
}
I have tried also
private void FrmEmployee_Load(object sender, EventArgs e)
{
LoadComboboxDS();
}
private void LoadComboboxDS()
{
//company
var _companies = con.Companies.Where(x => x.IsDeleted == false).ToList();
_companies.Insert(0,new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
cbCompany.DataSource = _companies;
cbCompany.DisplayMember = "Name";
cbCompany.ValueMember = "ID";
//gender
cbGender.DataSource = Enum.GetValues(typeof(Gender));
//merital status
cbMeritalStatus.DataSource = Enum.GetValues(typeof(MaritalStatus));
//citizenship
var _citizenships = con.Countries.Select(x => x.Citizenship).Distinct().ToList();
_citizenships.Insert(0, "--Select--");
cbCitizenship.DataSource = _citizenships;
cbCitizenship.DisplayMember = "Citizenship";
//nationality
var _nations = con.Countries.Select(x => x.Name).Distinct().ToList();
_nations.Insert(0, "--Select--");
cbNationality.DataSource = _nations;
cbNationality.DisplayMember = "Name";
//domicile
var _domiciles = con.Countries.Select(x => x.Name).Distinct().ToList();
_domiciles.Insert(0, "--Select--");
cbDomicile.DataSource = _domiciles;
cbDomicile.DisplayMember = "Name";
//cast category
var _casts = con.CastCategories.Select(x => new {x.ShortText, x.Description}).Distinct().ToList();
_casts.Insert(0, new { ShortText = "", Description = "--Select--" });
cbCategory.DataSource = _casts;
cbCategory.DisplayMember = "Description";
cbCategory.ValueMember = "ShortText";
//religion
cbReligion.DataSource = Enum.GetValues(typeof(Religion));
}
You can use Async extension methods of Entity Framework 6 to make your code asynchronous.
Separate your data access and presentation layer, at first:
public static class MyRepository // consider not static, just an example
{
public static async Task<List<Company>> GetCompanies()
{
using (var connection = new Connection()) // consider factory
{
return await con.Companies.Where(x => x.IsDeleted == false).ToListAsync();
}
}
public async Task<List<Citizenship>> GetCitizenships()
{
using (var connection = new Connection()) // factory?
{
return await con.Countries.Select(x => x.Citizenship).Distinct().ToList();
}
}
}
Then, you can run all these tasks at once and wait for them to complete:
// Wherever you are going to open frmEmployee
public async Task openFrmEmployee_OnClick(object sender, EventArgs e)
{
var getCompaniesTask = MyRepository.GetCompanies();
var getCitizenshipsTask = MyRepository.GetCitizenships();
await Task.WhenAll(getCompaniesTask, getCitizenshipsTask); // UI thread is not blocked
var form = new FrmEmployee(getCompaniesTask.Result, getCitizenshipsTask.Result); // form is created with data
}
Now, you only need to make your form accept complete data in constructor instead of making your form load this data which breaks abstraction:
public class FrmEmployees
{
public FrmEmployees(List<Company> companies, List<Citizenship> citizenships)
{
companies.Insert(0,new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
cbCompany.DataSource = companies;
cbCompany.DisplayMember = "Name";
cbCompany.ValueMember = "ID";
citizenships.Insert(0, "--Select--");
cbCitizenship.DataSource = _citizenships;
cbCitizenship.DisplayMember = "Citizenship";
// etc.
}
}
One important thing: you can get many tasks and many data passed to a form constructor. If all this data is going to be used often togetther, then you would probably want to encapsulate this "get all these things" logic into a single place to remove possible code duplication.
See what I have done... if anyone can review my code it would be appreciable.
public class EmployeeFormDataRepesenter
{
public List<Company> Companies { get; set; }
public List<Country> Countries { get; set; }
public List<CastCategory> CastCategories { get; set; }
}
public void LoadData(EmployeeFormDataRepesenter representer)
{
//gender
cbGender.DataSource = Enum.GetValues(typeof(Gender));
//merital status
cbMeritalStatus.DataSource = Enum.GetValues(typeof(MaritalStatus));
//religion
cbReligion.DataSource = Enum.GetValues(typeof(Religion));
//company
var _companies = representer.Companies;
_companies.Insert(0, new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
cbCompany.DataSource = _companies;
cbCompany.DisplayMember = "Name";
cbCompany.ValueMember = "ID";
//citizenship
var _citizenships = representer.Countries.Select(x => x.Citizenship).ToList();
_citizenships.Insert(0, "--Select--");
cbCitizenship.DataSource = _citizenships;
cbCitizenship.DisplayMember = "Citizenship";
//nationality
var _nations = representer.Countries.Select(x => x.Name).ToList();
_nations.Insert(0, "--Select--");
cbNationality.DataSource = _nations;
cbNationality.DisplayMember = "Name";
//domicile
var _domiciles = representer.Countries.Select(x => x.Name).ToList();
_domiciles.Insert(0, "--Select--");
cbDomicile.DataSource = _domiciles;
cbDomicile.DisplayMember = "Name";
//cast category
var _casts = representer.CastCategories.Select(x => new { x.ShortText, x.Description }).Distinct().ToList();
_casts.Insert(0, new { ShortText = "", Description = "--Select--" });
cbCategory.DataSource = _casts;
cbCategory.DisplayMember = "Description";
cbCategory.ValueMember = "ShortText";
}
private async void btnEmplyee_Click(object sender, EventArgs e)
{
con = new Connection();
Action showProgress = () => frmStatrup._progressBar.Visible = true;
Action hideProgress = () => frmStatrup._progressBar.Visible = false;
EmployeeFormDataRepesenter representer;
Task<List<Company>> _taskCompany = new Task<List<Company>>(() =>
{
BeginInvoke(showProgress);
var list = con.Companies.ToListAsync();
BeginInvoke(hideProgress);
if (list != null)
return list.Result;
return null;
});
Task<List<Country>> _taskCountry = new Task<List<Country>>(() =>
{
BeginInvoke(showProgress);
var list = con.Countries.ToListAsync();
BeginInvoke(hideProgress);
if (list != null)
return list.Result;
return null;
});
Task<List<CastCategory>> _taskCasts = new Task<List<CastCategory>>(() =>
{
BeginInvoke(showProgress);
var list = con.CastCategories.ToListAsync();
BeginInvoke(hideProgress);
if (list != null)
return list.Result;
return null;
});
_taskCompany.Start();
var _companies = await _taskCompany;
_taskCountry.Start();
var _countries = await _taskCountry;
_taskCasts.Start();
var _casts = await _taskCasts;
if (_companies.Count != 0)
{
representer = new EmployeeFormDataRepesenter();
representer.Companies = _companies;
representer.Countries = _countries;
representer.CastCategories = _casts;
}
else
{
representer = null;
}
if (representer != null)
{
frmEmployee _emp = new frmEmployee();
_emp.LoadData(representer);
Functions.OpenForm(_emp, this.ParentForm);
}
}
I'm experimenting with Couchbase + Xamarin.Forms trying to do a simple search, showing the results in a ListView but I've stuck. :(
Someone know how to add the rows/documents of a query in a list?
public List<Visitor> SearchRecord (string word)
{
var viewByName = db.GetView ("ByName");
viewByName.SetMap((doc, emit) => {
emit (new object[] {doc["first_name"], doc["last_name"]}, doc);
}, "2");
var visitorQuery = viewByName.CreateQuery();
visitorQuery.StartKey = new List<object> {word};
// visitorQuery.EndKey = new List<object> {word, new Dictionary<string, object>()};
visitorQuery.Limit = 100;
var visitors = visitorQuery.Run();
var visitorList = new List<Visitor> ();
foreach (var visitor in visitors) {
// visitorList.Add(visitor.Document); <-- Error.
System.Console.WriteLine(visitor.Key);
}
return visitorList;
}
I get the error messages:
Error CS1501: No overload for method Add' takes2' arguments
(CS1501) (Demo_Couchbase.Droid) Error CS1502: The best overloaded
method match for
System.Collections.Generic.List<Demo_Couchbase.Visitor>.Add(Demo_Couchbase.Visitor)'
has some invalid arguments (CS1502) (RegistroAgil_Couchbase.Droid)
Error CS1503: Argument#1' cannot convert Couchbase.Lite.Document'
expression to typeDemo_Couchbase.Visitor' (CS1503)
(Demo_Couchbase.Droid)
Thank you in advance for any help you can provide.
There is problem in your mapping part. You can directly cast documents on GetView.
You can try bellow code.
public List<Visitor> SearchRecord (string word)
{
var viewByName = db.GetView<Visitor>("ByName","ByName");
var visitorQuery = viewByName.CreateQuery();
visitorQuery.StartKey = new List<object> {word};
visitorQuery.Limit = 100;
var visitors = visitorQuery.Run();
var visitorList = new List<Visitor> ();
foreach (var visitor in visitors) {
visitorList.Add(visitor.Document);
System.Console.WriteLine(visitor.Key);
}
return visitorList;
}
I don't know if this is the most elegant solution though but my code works fine now.
Visitor ToRecord(Document d) {
var props = d.Properties;
return new Visitor {
Id = props["_id"].ToString(),
FirstName = (string)props["first_name"],
LastName = (string)props["last_name"],
Occupation = (string)props["occupation"],
Company = (string)props["company"],
Email = (string)props["email"],
Phone = (string)props["phone"],
Birthday = (string)props["birthday"],
LastVisit = (string)props["last_visit"],
LocalImagePath = (string)props["local_image_path"],
Type = (string)props["type"],
CreatedAt = (string)props["created_at"],
UpdatedAt = (string)props["updated_at"],
DeletedAt = (string)props["deleted_at"]
};
}
public List<Visitor> SearchRecord (string word)
{
var viewByName = db.GetView ("ByName");
viewByName.SetMap((doc, emit) => {
if ((doc.ContainsKey("type") && doc["type"].ToString() == "visitor") && (doc.ContainsKey("deleted_at") && doc["deleted_at"] == null))
emit (new [] {doc["first_name"], doc["last_name"]}, doc);
}, "2");
var visitorQuery = viewByName.CreateQuery();
visitorQuery.StartKey = word;
visitorQuery.Limit = 50;
var rows = visitorQuery.Run();
var visitorList = new List<Visitor> ();
for (int i = 0; i < rows.Count (); i++) {
var row = rows.GetRow (i);
var name = row.Document.GetProperty ("first_name").ToString ().ToLower () + " " + row.Document.GetProperty ("last_name").ToString ().ToLower ();
if (name.Contains (word))
visitorList.Add(ToRecord(row.Document));
}
return visitorList;
}