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);
}
}
Related
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 have a problem.
In my Android app I use a: Android.Support.V4.View.ViewPager to swap between a summary and a wallet. The summary page is filled with 3 TextViews and the Wallet is created with 1 GridView. Both the pages are getting filled with data from a HTTPS call from where the response will be parsed into a List. Now I want to refresh both the pages every second. So I tried this:
public void LoadOrderPage()
{
Android.Support.V4.View.ViewPager SummaryWalletSwitcher = FindViewById<Android.Support.V4.View.ViewPager>(Resource.Id.SummaryWalletSwitcher);
List<View> viewlist = new List<View>();
viewlist.Add(LayoutInflater.Inflate(Resource.Layout.AgentSummary, null, false));
viewlist.Add(LayoutInflater.Inflate(Resource.Layout.AgentWallet, null, false));
SummaryWalletAdapter ViewSwitchAdapter = new SummaryWalletAdapter(viewlist);
SummaryWalletSwitcher.Adapter = ViewSwitchAdapter;
Timer AgentInfo_Timer = new Timer();
AgentInfo_Timer.Interval = 1000;
AgentInfo_Timer.Elapsed += LoadAgentInfo;
AgentInfo_Timer.Enabled = true;
}
public void LoadAgentInfo(object sender, ElapsedEventArgs e)
{
TextView TextPortfolioValue = FindViewById<TextView>(Resource.Id.txtPortfolioValue);
TextView TextValueUSDT = FindViewById<TextView>(Resource.Id.txtValueUSDT);
TextView TextTotalValue = FindViewById<TextView>(Resource.Id.txtTotalValue);
GridView GridviewWallet = FindViewById<GridView>(Resource.Id.GridviewWallet);
if (FirstWalletRun == true)
{
List<wallet> EmptyWalletList = new List<wallet>();
WalletListAdapter = new WalletListAdapter(this, EmptyWalletList);
GridviewWallet.Adapter = WalletListAdapter;
FirstWalletRun = false;
}
PortfolioValue = 0;
ValueUSDT = 0;
TotalValue = 0;
string response = "";
AgentId = getSelectedAgentId();
if (AgentId == 0)
{
AgentId = 1;
}
try
{
WebClient client = new WebClient();
var reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("agentid", AgentId.ToString());
reqparm.Add("devicetoken", DeviceToken);
byte[] responsebytes = client.UploadValues("https://www.test.nl/getagentwallet.php", "POST", reqparm);
IgnoreBadCertificates();
response = Encoding.UTF8.GetString(responsebytes);
response = response.Replace("\n", "").Replace("\t", "");
}
catch (Exception ex)
{
string exFullName = (ex.GetType().FullName);
string ExceptionString = (ex.GetBaseException().ToString());
TextPortfolioValue.Text = "Unknown";
TextValueUSDT.Text = "Unknown";
TextTotalValue.Text = "Unknown";
}
if (response != "No updates")
{
//Parse json content
var jObject = JObject.Parse(response);
//Create Array from everything inside Node:"Coins"
var walletPropery = jObject["Wallet"] as JArray;
//Create List to save Coin Data
walletList = new List<wallet>();
//Find every value in Array: coinPropery
foreach (var property in walletPropery)
{
//Convert every value in Array to string
var propertyList = JsonConvert.DeserializeObject<List<wallet>>(property.ToString());
//Add all strings to List
walletList.AddRange(propertyList);
}
//Get all the values from Name, and convert it to an Array
string[][] NamesArray = walletList.OrderBy(i => i.AgentId)
.Select(i => new string[] { i.AgentId.ToString(), i.Coin, i.Quantity.ToString(), i.AvgPrice.ToString(), i.Value.ToString() })
.Distinct()
.ToArray();
foreach (string[] str in NamesArray)
{
if (str[1] != "USDT")
{
PortfolioValue += decimal.Parse(str[4]);
}
else
{
ValueUSDT += decimal.Parse(str[4]);
}
}
TotalValue = PortfolioValue + ValueUSDT;
TextPortfolioValue.Text = Math.Round(PortfolioValue, 8).ToString();
TextValueUSDT.Text = Math.Round(ValueUSDT, 8).ToString();
TextTotalValue.Text = Math.Round(TotalValue, 8).ToString();
SortedWalletList = walletList.OrderBy(o => o.Coin).ToList();
if (WalletListAdapter == null)
{
//Fill the DataSource of the ListView with the Array of Names
WalletListAdapter = new WalletListAdapter(this, SortedWalletList);
GridviewWallet.Adapter = WalletListAdapter;
}
else
{
WalletListAdapter.refresh(SortedWalletList);
AgentInfoNeedsUpdate = true;
}
}
else
{
AgentInfoNeedsUpdate = false;
}
}
And in my WalletListAdapter I created the refresh function:
public void refresh(List<wallet> mItems)
{
this.mItems = mItems;
NotifyDataSetChanged();
}
But the GridviewWallet never get's filled or doesn't get shown. What am I doing wrong?
EDIT:
Maybe there is something wrong in the WalletListAdapter, so here is the code of the class:
public class WalletListAdapter : BaseAdapter<wallet>
{
public List<wallet> mItems;
private Context mContext;
public WalletListAdapter(Context context, List<wallet> items)
{
mItems = items;
mContext = context;
}
public override int Count
{
get { return mItems.Count; }
}
public void refresh(List<wallet> mItems)
{
this.mItems = mItems;
NotifyDataSetChanged();
}
public override long GetItemId(int position)
{
return position;
}
public override wallet this[int position]
{
get { return mItems[position]; }
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
row = LayoutInflater.From(mContext).Inflate(Resource.Layout.walletlist_row, null, false);
var txtWalletCoin = row.FindViewById<TextView>(Resource.Id.txtWalletCoin);
var txtWalletQuantity = row.FindViewById<TextView>(Resource.Id.txtWalletQuantity);
var txtAvgPrice = row.FindViewById<TextView>(Resource.Id.txtWalletAvgPrice);
var txtWalletValue = row.FindViewById<TextView>(Resource.Id.txtWalletValue);
var txtProfitUSDT = row.FindViewById<TextView>(Resource.Id.txtWalletProfitUSDT);
var txtProfitPerc = row.FindViewById<TextView>(Resource.Id.txtWalletProfitPerc);
row.Tag = new WalletViewHolder()
{
txtWalletCoin = txtWalletCoin,
txtWalletQuantity = txtWalletQuantity,
txtAvgPrice = txtAvgPrice,
txtWalletValue = txtWalletValue,
txtProfitUSDT = txtProfitUSDT,
txtProfitPerc = txtProfitPerc
};
}
var holder = (WalletViewHolder)row.Tag;
holder.txtWalletCoin.Text = mItems[position].Coin;
holder.txtWalletQuantity.Text = Math.Round(mItems[position].Quantity, 2).ToString();
holder.txtAvgPrice.Text = Math.Round(mItems[position].AvgPrice, 2).ToString();
holder.txtWalletValue.Text = Math.Round(mItems[position].Value, 2).ToString();
if (mItems[position].Coin != "USDT")
{
holder.txtProfitUSDT.Text = Math.Round(mItems[position].ProfitUSDT, 2).ToString();
holder.txtProfitPerc.Text = Math.Round(mItems[position].ProfitPerc, 1).ToString();
}
else
{
holder.txtProfitUSDT.Text = Math.Round(0.00, 2).ToString();
holder.txtProfitPerc.Text = Math.Round(0.00, 1).ToString();
}
return row;
}
}
Hope this discussion provides some insights to fix the gridview refresh using Xamarin. According to it, the grid has to be recreated.
https://forums.xamarin.com/discussion/115256/refresh-a-gridview
I am pretty new to MOQ and I am in learning right now. I got task that I need to write unit test But I am getting the below error which I couldn't able to find. Please anyone help me with this. Also please review the code and give me some advises if my testcase needs changes.
Expection: IAcronisService.GetActivitiesFromDate("mygroup", 5/24/2016
8:33:34 PM) invocation failed with mock behavior Strict.....
for Save method(I have commented at save method where the exception has been thrown)
Process method calls save method
public int Process()
{
AcronisService = AcronisSvcManager.Get(ClientFactory, DataProviderFactory, LogAdapter);
DataObject backupGroupsDO = GetListOfAllCurrentGroups();
int activitiesSavedCount = Save(backupGroupsDO);
return activitiesSavedCount;
}
When I debug I also have seen the below line when I mouse over at first line on above process method. I thought service object is not calling/mocking. Is this anything to do with above exception? Please suggest some changes.
(IAcronisServiceProxy)AcronisService).AcronisURL threw a exception of type MOQ.MockException.
Save Method
private int Save(DataObject backupGroupsDO)
{
int count = 0;
foreach (DataRecord dr in backupGroupsDO.DataRecord)
{
BackupGroup backupGroup = new BackupGroup(dr);
// Get all activities for each group
AcronisClient.DataModel.Activity.ActivitiesResponse acronisActivities;
if (backupGroup.LastActivityDate == null)
{
// Get all activities for each group
***//Got Exception at this line***
acronisActivities = AcronisService.GetActivitiesFromDate(backupGroup.GroupName, DateTime.Now.AddDays(-90));
}
else
{
acronisActivities = AcronisService.GetActivitiesFromDate(backupGroup.GroupName, backupGroup.LastActivityDate);
}
if (acronisActivities == null || acronisActivities.Activities == null)
{
// Stop processing b/c might be an issue with the connection to Acronis
LogAdapter.LogError(KCBLog.Main, "Stopped processing activities, possible Acronis connection issue with getting Activities");
return -1;
}
var lastBackUpActivity = acronisActivities.Activities.OrderByDescending(z => z.StartTime).FirstOrDefault();
List<string> lastSuccessfulActivities = new List<string>();
List<string> lastActivities = new List<string>();
foreach (var acronisActivity in acronisActivities.Activities)
{
Kaseya.KCB.Common.DataModels.AcronisActivity activity = new AcronisActivity();
activity.BackupPlanId = acronisActivity.BackupPlanId;
activity.BytesProcessed = acronisActivity.BytesProcessed;
activity.BytesSaved = acronisActivity.BytesSaved;
activity.Cause = acronisActivity.CompletionResult == null ? null : acronisActivity.CompletionResult.Cause;
activity.Reason = acronisActivity.CompletionResult == null ? null : acronisActivity.CompletionResult.Reason;
activity.Effect = acronisActivity.CompletionResult == null ? null : acronisActivity.CompletionResult.Effect;
activity.DateCreated = DateTime.Now;
activity.FinishTime = acronisActivity.FinishTime;
activity.GroupId = backupGroup.Id;
activity.Id = acronisActivity.Id;
activity.InitiatedBy = acronisActivity.InitiatedBy;
activity.InstanceId = acronisActivity.InstanceId;
activity.IsRootActivity = (bool)acronisActivity.IsRootActivity;
activity.ParentActivityId = acronisActivity.ParentActivityId;
activity.PartitionId = PartitionId;
activity.StartTime = acronisActivity.StartTime;
activity.State = acronisActivity.State;
activity.Status = acronisActivity.Status;
activity.Title = acronisActivity.Title;
activity.UpdateTime = acronisActivity.UpdateTime;
AcronisActivityDataProvider.AddUpdateAcronisActivity(activity);
AcronisClient.DataModel.Activity.Activity lastSuccessfulActivity = acronisActivities.Activities.Where(z => z.Status == "ok" && z.Title.Contains("Running backup plan") && z.InstanceId==acronisActivity.InstanceId).OrderByDescending(z => z.FinishTime).FirstOrDefault();
var lastActivity = acronisActivities.Activities.Where(z => z.Title.Contains("Running backup plan") && z.InstanceId == acronisActivity.InstanceId).OrderByDescending(z => z.FinishTime).FirstOrDefault();
if (!string.IsNullOrEmpty(acronisActivity.InstanceId))
{
DataRecord assetDR = AssetDataProvider.GetByInstanceId(acronisActivity.InstanceId, PartitionId);
if (assetDR != null)
{
var assetId = assetDR.FindValue<string>("id", "");
if (lastSuccessfulActivity != null && !lastSuccessfulActivities.Contains(acronisActivity.InstanceId))
{
AssetDataProvider.UpdateLastSuccessfulActivityId(assetId, lastSuccessfulActivity.ParentActivityId);
lastSuccessfulActivities.Add(acronisActivity.InstanceId);
}
if (lastActivity != null && !lastActivities.Contains(acronisActivity.InstanceId))
{
AssetDataProvider.UpdateLastActivityId(assetId, lastActivity.ParentActivityId);
lastActivities.Add(acronisActivity.InstanceId);
}
}
}
count++;
}
if (acronisActivities.Activities != null && acronisActivities.Activities.Count>0)
{
//backupGroup.LastActivityDate = lastBackUpActivity.StartTime;
BackupGroupDataProvider.UpdateLastBackupGroupActivityDate(backupGroup.Id, lastBackUpActivity.StartTime);
}
}
return count;
}
Test Method I have writtern,
public void Test()
{
string groupName = "mygroup";
string mybackupAccountName = "mybackupaccount";
decimal PartitionId = 9m;
DateTime lastActivityDate = DateTime.Parse("2016-08-14T20:47:05");
string instanceId = "utinstanceId";
string assetId = "123";
DataRecord asset = new DataRecord();
asset.AddField("id", 123);
DataObject backupGroupsDO = new DataObject();
DataRecord groupDataRecord = new DataRecord();
groupDataRecord.AddField("id", 123);
groupDataRecord.AddField("partitionId", PartitionId);
groupDataRecord.AddField("groupName", groupName);
//groupDataRecord.AddField("lastActivityDate", lastActivityDate);
groupDataRecord.AddField("backupAccountName", mybackupAccountName);
backupGroupsDO.DataRecord.Add(groupDataRecord);
AcronisActivity acronisActivity = new AcronisActivity();
acronisActivity.BackupPlanId = "utBackupPlanId";
ActivitiesResponse activitiesResponse = new ActivitiesResponse();
AcronisClient.DataModel.Activity.Activity activity = new AcronisClient.DataModel.Activity.Activity();
activity.BackupPlanId = "utackupPlanId";
activity.BytesProcessed = 124674;
activity.BytesSaved = 06446;
activity.CompletionResult = new CompletionResult()
{
Cause = "utCause",
Reason = "utReason",
Effect = "utEffect"
};
activity.FinishTime = DateTime.Parse("2016-08-14T20:47:04");
activity.Id = "utId";
activity.InitiatedBy = "utInitiatedBy";
activity.InstanceId = "utInstanceId";
activity.IsRootActivity = true;
activity.ParentActivityId = "utParentActivityId";
activity.StartTime = DateTime.Parse("2016-08-14T20:47:02");
activity.State = "utState";
activity.Status = "utStatus";
activity.Title = "utTitle";
activity.UpdateTime = DateTime.Parse("2016-08-14T20:47:03");
activitiesResponse.Activities = new List<AcronisClient.DataModel.Activity.Activity>();
activitiesResponse.Activities.Add(activity);
var moqFactory = new MockRepository(MockBehavior.Strict);
var moqDataProviderFactory = moqFactory.Create<IDataProviderFactory>();
var moqDataProvider = moqFactory.Create<IDataProvider>();
var moqLogAdapter = moqFactory.Create<ILogAdapter>();
var moqAcronisServiceManager = moqFactory.Create<IAcronisServiceManager>();
var moqAcronisService = moqFactory.Create<IAcronisService>();
var moqAssetDataProvider = moqFactory.Create<IAssetDataProvider>();
var moqAcronisActivityDataProvider = moqFactory.Create<IAcronisActivityDataProvider>();
var moqBackupGroupDataProvider = moqFactory.Create<IBackupGroupDataProvider>();
Credential MSPCredential = new Credential();
moqDataProviderFactory.Setup(m => m.BackupGroupDataProvider.GetBackupGroups()).Returns(backupGroupsDO);
moqAcronisServiceManager.Setup(m => m.Get(It.IsAny<IRestClientFactory>(), It.IsAny<IDataProviderFactory>(), It.IsAny<ILogAdapter>(), "")).Returns(moqAcronisService.Object);
moqDataProvider.Setup(m => m.VerifyPartitionId(ref PartitionId));
moqDataProvider.Setup(m => m.ExecuteNonQuery(It.IsAny<AddUpdateAcronisActivity>())).Returns(1);
moqAcronisService.Setup(m => m.GetActivitiesFromDate(groupName, lastActivityDate)).Returns(activitiesResponse);
moqAcronisActivityDataProvider.Setup(m => m.AddUpdateAcronisActivity(acronisActivity));
moqAssetDataProvider.Setup(m => m.GetByInstanceId(instanceId, PartitionId,1)).Returns(asset);
moqAssetDataProvider.Setup(m => m.UpdateLastActivityId(assetId, activity.ParentActivityId));
moqAssetDataProvider.Setup(m => m.UpdateLastSuccessfulActivityId(assetId, activity.ParentActivityId));
moqBackupGroupDataProvider.Setup(m => m.UpdateLastBackupGroupActivityDate("1234", lastActivityDate));
// moqAcronisService.Setup(m => m.GetActivitiesFromDate(groupName, Convert.ToDateTime("2016-08-18T13:18:40.000Z"))).Returns(activitiesResponse);
ActivityHarvester activityHarvester = new ActivityHarvester();
activityHarvester.PartitionId = PartitionId;
activityHarvester.DataProvider = moqDataProvider.Object;
activityHarvester.LogAdapter = moqLogAdapter.Object;
activityHarvester.AcronisSvcManager = moqAcronisServiceManager.Object;
activityHarvester.DataProviderFactory = moqDataProviderFactory.Object;
activityHarvester.AcronisService = moqAcronisService.Object;
activityHarvester.AssetDataProvider = moqAssetDataProvider.Object;
activityHarvester.BackupGroupDataProvider = moqBackupGroupDataProvider.Object;
activityHarvester.AcronisActivityDataProvider = moqAcronisActivityDataProvider.Object;
activityHarvester.process();//*process method calls above save method method*
moqFactory.VerifyAll();
}
From your example, your setup for IAcronisService.GetActivitiesFromDate shows that it is expecting lastActivityDate of 2016-08-14T20:47:05 based on the code but the error shows that you used a different date 5/24/2016 8:33:34 PM than expected. As the moq behavior is Strict, this
Causes the mock to always throw an exception for invocations that don't have a corresponding setup.
You can make the setup a little more flexible by using It.IsAny<DateTime>()
moqAcronisService
.Setup(m => m.GetActivitiesFromDate(groupName, It.IsAny<DateTime>()))
.Returns(activitiesResponse);
or changing the behavior in your moq factory to use Default or Loose MockBehavior.
I have created database in SqLite in my windows app, now I want to fetch the data from my database. This is the code how I inserted the data in databse.
var dbpath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "scrapbook.sqlite");
using (var db = new SQLite.SQLiteConnection(dbpath))
{
// Create the tables if they don't exist
var bg = listAlbumContainer[0] as AlbumContainer;
var albumbg = bg.BackgroundImageName;
var sk = listAlbumContainer[0].listAlbumContainer;
var _audio = listAlbumContainer[0].listAlbumContainer5;
var _video = listAlbumContainer[0].listAlbumContainer3;
var wa = listAlbumContainer[0].listAlbumContainer4;
var ci = listAlbumContainer[0].listAlbumContainer2;
var gi = listAlbumContainer[0].listAlbumContainer1;
string snodesticker = Serializeanddeserializwhelper.Serialize(sk);
string nodegi = Serializeanddeserializwhelper.Serialize(gi);
string nodeci = Serializeanddeserializwhelper.Serialize(ci);
string nodewa = Serializeanddeserializwhelper.Serialize(wa);
string nodevideo = Serializeanddeserializwhelper.Serialize(_video);
string nodeaudio = Serializeanddeserializwhelper.Serialize(_audio);
var TittledataInsertCheck = db.Table<Title>().Where(x => x.ALBUM_TITLE.Contains(nametxt.Text)).FirstOrDefault();
if (TittledataInsertCheck == null)
{
db.Insert(new Title()
{
ALBUM_TITLE = nametxt.Text
});
var TittledataInsert = db.Table<Title>().Where(x => x.ALBUM_TITLE.Contains(nametxt.Text)).FirstOrDefault();
if (TittledataInsert != null)
{
db.Insert(new PAGE()
{
PAGE_BACKGROUND = albumbg,
TITLE_ID = TittledataInsert.ID
});
}
}
else
{
await new MessageDialog("Tittle Already Found Please change tittle").ShowAsync();
return;
}
var PagedataInsert = db.Table<PAGE>().Where(x => x.PAGE_BACKGROUND.Contains(albumbg)).FirstOrDefault();
if (PagedataInsert != null)
{
db.Insert(new CONTENT
{
PAGE_ID = PagedataInsert.ID,
STICKERS = snodesticker,
AUDIO = nodeaudio,
VIDEO = nodevideo,
GALLERY_IMAGES = nodegi,
CAMERA_IMAGES = nodeci,
WOARD_ART = nodewa
});
}
db.Commit();
db.Dispose();
db.Close();
var line = new MessageDialog("Records Inserted");
await line.ShowAsync();
}
Is this the right way to insert the data?
I have a canvas on which I set the background image. And on this background some images, video and audio.
With ADO.net, if I want to retrieve the ID from combobox I just do such like this :
int idToGet = int.parse(tbCategory.SelectedValue.ToString());
Then done,
But when I bind the combobox with EF, it will show error Input string was not in a correct format. So the current value show { id = 7, category = TESTING } and not as usual.
Here a my code snippet :
public void loadCategory()
{
tbCategory.DataSource = null;
var listCategoryObj = new malsic_inventoryEntities();
var query = from cat in listCategoryObj.Category
//join cat in listItmObj.Category on n.id_category equals cat.id
select new { cat.id,cat.category };
if (query.Count() > 0)
{
tbCategory.DataSource = query.ToList();
tbCategory.DisplayMember = "category";
tbCategory.ValueMember = "id";
tbCategory.Invalidate();
}
else
{
tbSubCategory.Enabled = false;
}
}
public void loadSubcategory()
{
tbSubCategory.DataSource = null;
int id_category_current = int.Parse(tbCategory.SelectedItem.Value.ToString());
var listSubCategoryObj = new malsic_inventoryEntities();
var query = from SubCat in listSubCategoryObj.SubCategories
where SubCat.id_category == id_category_current
select new { SubCat.id, SubCat.subcategory };
if (query.Count() > 0)
{
groupBox1.Enabled = true;
tbSubCategory.DataSource = query.ToList();
tbSubCategory.DisplayMember = "subcategory";
tbSubCategory.ValueMember = "id";
tbSubCategory.Invalidate();
}
else
{
groupBox1.Enabled = false;
}
}
I do something wrong?
I don't think your problem is anything to with ADO.NET or Entity Framework. I think your problem is on the line with int.Parse. Try setting id_category_current this way instead of how you do it now:
int id_category_current;
if(!int.TryParse(tbCategory.SelectedItem.Value.ToString(), out id_category_current))
{
groupBox1.Enabled = false;
return;
}