/// <summary> /// 保存事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void BtnSave_OnClick(object sender, EventArgs e) { if (string.IsNullOrEmpty(StrGuid)) { var info = new DailyInfo(); SetModel(info); info.CreateTime = DateTime.Now; info.IsDraft = false; info.IsSpecial = ConvertHelper.GetInt(ddlSpecial.SelectedValue); var user = HttpContext.Current.Session["UserInfo"] as UserInfo; if (user != null) { info.UserGuid = user.Guid; } var blog = HttpContext.Current.Session["BlogInfo"] as BlogInfo; if (blog != null) { info.BlogGuid = blog.Guid; } DailyBll.Add(info); } else { var info = DailyBll.GetModel(StrGuid); SetModel(info); info.IsDraft = false; DailyBll.Update(info); } Response.Redirect("DailyList.aspx"); }
private void PlotGeneralMonthlyExpenseDataOnChart(List <DailyInfo> dailyInfoList) { MonthlyReportChart.Series["expense"].Points.Clear(); int numOfDays = GetNumberOfDays(); for (int day = 1; day <= numOfDays; day++) { DailyInfo dailyInfo = dailyInfoList.Find(d => d.Day == day); DataPoint point = new DataPoint(); if (dailyInfo != null) { point.SetValueXY(day, dailyInfo.TotalExpense); point.ToolTip = dailyInfo.TotalExpense.ToString(); MonthlyReportChart.Series["expense"].Points.Add(point); } else { point.SetValueXY(day, 0); point.ToolTip = "0.00"; MonthlyReportChart.Series["expense"].Points.Add(point); } } }
public static List <StockPrice> GetPrices(List <DateTime> dates) { List <StockPrice> priceslist = new List <StockPrice>(); var daily = new DailyInfo(); var dynamic = daily.GetCursDynamic(dates[0], dates[1], CODE); bool first = true; foreach (DataRow row in dynamic.Tables[0].Rows) { StockPrice price = new StockPrice(); price.Date = (DateTime)row.ItemArray[0]; price.Price = (decimal)row.ItemArray[3]; if (!first) { float old = (float)priceslist[priceslist.Count - 1].Price; price.Change = 100 * ((float)price.Price - old) / old; } else { first = false; } priceslist.Add(price); price = null; } return(priceslist); }
public async Task <DailyInfo> GeTotalInfoAsync(int shopId) { var info = new DailyInfo(); var dt = DateTime.Now; bills = await _billRepo.GetBillsWithSales(shopId, From, dt); if (bills == null || !bills.Any()) { return(new DailyInfo { averageBill = 0, billsCount = 0, totalProfit = 0, totalRevenue = 0 }); } var sales = new List <Sale>(); foreach (var bill in bills) { sales.AddRange(bill.Sales); } info.averageBill = bills.Average(p => p.sum); info.billsCount = bills.Count(); info.totalRevenue = sales.Sum(p => p.sum); info.totalProfit = sales.Sum(p => p.profit); return(info); }
/// <summary> /// 保存添加数据 Add(DailyInfo entity) /// </summary> /// <param name="entity">实体类(DailyInfo)</param> ///<returns>返回新增的ID</returns> public string Add(DailyInfo entity) { var guid = Guid.NewGuid(); var strSql = new StringBuilder(); strSql.Append("insert into XSBlog_Daily("); strSql.Append("Guid,Name,Content,Create_Time,Blog_Guid,User_Guid,Category_Guid,Is_Draft,Is_Stick,Is_Home,Is_Special, Page_View, Comments_Num"); strSql.Append(") values ("); strSql.Append("@Guid,@Name,@Content,@Create_Time,@Blog_Guid,@User_Guid,@Category_Guid,@Is_Draft,@Is_Stick,@Is_Home,@Is_Special,@Page_View,@Comments_Num"); strSql.Append(") "); DbParameter[] parameters = { SqlHelper.MakeInParam("@Guid", (DbType)SqlDbType.UniqueIdentifier, guid), SqlHelper.MakeInParam("@Name", (DbType)SqlDbType.VarChar, entity.Name), SqlHelper.MakeInParam("@Content", (DbType)SqlDbType.Text, entity.Content), SqlHelper.MakeInParam("@Create_Time", (DbType)SqlDbType.DateTime, entity.CreateTime), SqlHelper.MakeInParam("@Blog_Guid", (DbType)SqlDbType.UniqueIdentifier, ConvertHelper.GetGuid(entity.BlogGuid)), SqlHelper.MakeInParam("@User_Guid", (DbType)SqlDbType.UniqueIdentifier, ConvertHelper.GetGuid(entity.UserGuid)), SqlHelper.MakeInParam("@Category_Guid", (DbType)SqlDbType.UniqueIdentifier, ConvertHelper.GetGuid(entity.CategoryGuid)), SqlHelper.MakeInParam("@Is_Draft", (DbType)SqlDbType.Bit, entity.IsDraft), SqlHelper.MakeInParam("@Is_Stick", (DbType)SqlDbType.Bit, entity.IsStick), SqlHelper.MakeInParam("@Is_Home", (DbType)SqlDbType.Bit, entity.IsHome), SqlHelper.MakeInParam("@Is_Special", (DbType)SqlDbType.Int, entity.IsSpecial), SqlHelper.MakeInParam("@Page_View", (DbType)SqlDbType.Int, entity.PageView), SqlHelper.MakeInParam("@Comments_Num", (DbType)SqlDbType.Int, entity.CommentsNum) }; SqlHelper.ExecuteNonQuery(strSql.ToString(), parameters); return(guid.ToString()); }
/// <summary> /// 获取指定个人日记 /// </summary> /// <param name="dailyId">个人日记标识</param> /// <returns></returns> public DailyInfo GetDailyInfo(string dailyId) { var da = new DailyInfo { DailyId = dailyId }; return(Session.Select(da) ? da : null); }
/// <summary> /// 设置model /// </summary> /// <param name="dailyInfo"></param> private void SetModel(DailyInfo dailyInfo) { dailyInfo.Name = tbName.Text; dailyInfo.Content = Content; dailyInfo.CategoryGuid = ddlCategory.SelectedValue; dailyInfo.IsStick = chkIsStick.Checked; dailyInfo.IsHome = chkIsHome.Checked; dailyInfo.IsSpecial = ConvertHelper.GetInt(ddlSpecial.SelectedValue); }
public static decimal GetExchangeRate(string CurrancyCode) { DailyInfo l_info = new DailyInfo(); DataSet l_data = l_info.GetCursOnDate(DateTime.Now.Date); DataTable l_tbl = l_data.Tables["ValuteCursOnDate"]; decimal l_res = (from row in l_tbl.AsEnumerable() where row.Field <string>("VchCode") == CurrancyCode select row.Field <decimal>("Vcurs") / row.Field <decimal>("Vnom")).First <decimal>(); return(l_res); }
public void ShowMyLogDailyInfoForm(DailyInfo dailyInfo, DataGridViewRow dgvr) { MyLogDailyInfo myLog = new MyLogDailyInfo(dailyInfo); dailyInfo.MainForm.CurrentOpenChildForm = myLog; myLog.ShowDialg(dgvr); if (myLog.DialogResult.Equals(DialogResult.OK)) { dailyInfo.Flush(); } }
/// <summary> /// 初始化控件 /// </summary> private void InitControls() { if (!string.IsNullOrEmpty(Id)) { DailyInfo = DailyManager.GetModelById(ConvertHelper.GetInt(Id)); if (DailyInfo != null) { lblName.Text = DailyInfo.Name; litContent.Text = DailyInfo.Content; lblCreateTime.Text = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DailyInfo.CreateTime); var user = HttpContext.Current.Session["UserInfo"] as UserInfo; //记录除自己以外的浏览量 if (user != null) { if (DailyInfo.UserGuid != user.Guid) { DailyManager.UpdatePageView(DailyInfo.Guid, DailyInfo.PageView + 1); } } else { DailyManager.UpdatePageView(DailyInfo.Guid, DailyInfo.PageView + 1); } //分类信息 CategoryInfo = CategoryManager.GetModel(DailyInfo.CategoryGuid); //上一篇文章和下一篇文章 //var lastDailyList = DailyManager.GetTopList(1, " Create_Time < '" + DailyInfo.CreateTime + "'", "Create_Time desc"); //if (lastDailyList.Count > 0) //{ // litLast1.Text = "<a href=\"/xsblog/" + BlogName + "/daily/" + lastDailyList[0].Id + "\">" + lastDailyList[0].Name + "</a>"; // litLast2.Text = litLast1.Text; //} //var nextDailyList = DailyManager.GetTopList(2, " Create_Time > '" + DailyInfo.CreateTime + "'", "Create_Time asc"); //if (nextDailyList.Count > 1) //{ // litNext1.Text = "<a href=\"/xsblog/" + BlogName + "/daily/" + nextDailyList[1].Id + "\">" + nextDailyList[1].Name + "</a>"; // litNext2.Text = litNext1.Text; //} } } if (CategoryInfo == null) { CategoryInfo = new CategoryInfo() { Id = 0, Name = "" }; } }
public static void UpdateCurrenciesFromCentralBank() { var di = new DailyInfo(); DataSet ds = di.GetCursOnDate(DateTime.Today); try { using (var db = new SQLDataAccess()) { db.cmd.CommandText = "SELECT CurrencyIso3 FROM Catalog.Currency"; db.cmd.CommandType = CommandType.Text; db.cmd.Parameters.Clear(); using (var dbUpd = new SQLDataAccess()) { dbUpd.cmd.CommandText = "UPDATE Catalog.Currency SET CurrencyValue=@CurrencyValue, CurrencyNumIso3=@CurrencyNumIso3 WHERE CurrencyIso3=@CurrencyIso3"; dbUpd.cmd.CommandType = CommandType.Text; db.cnOpen(); using (SqlDataReader read = db.cmd.ExecuteReader()) { while (read.Read()) { foreach (DataRow row in ds.Tables["ValuteCursOnDate"].Rows) { if (read["CurrencyIso3"].ToString().ToLower() != row["VchCode"].ToString().ToLower()) { continue; } dbUpd.cmd.Parameters.Clear(); dbUpd.cmd.Parameters.AddWithValue("@CurrencyValue", Convert.ToDecimal(row["Vcurs"]) / Convert.ToDecimal(row["Vnom"])); dbUpd.cmd.Parameters.AddWithValue("@CurrencyIso3", row["VchCode"].ToString()); dbUpd.cmd.Parameters.AddWithValue("@CurrencyNumIso3", row["VCode"].ToString()); dbUpd.cnOpen(); dbUpd.cmd.ExecuteNonQuery(); dbUpd.cnClose(); } } read.Close(); } } db.cnClose(); } } catch (Exception ex) { Debug.LogError(ex); } }
public mainForm() { InitializeComponent(); di = new DailyInfo(); curs = di.GetCursOnDateXML(DateTime.Today); foreach (XmlNode node in curs.ChildNodes) { CursListBox.Items.Add(node["VchCode"].InnerText + "\t" + node["Vname"].InnerText.Trim()); } CursListBox.SelectedItem = defaultSelectedCur; }
/// <summary> /// 添加或修改 /// </summary> /// <param name="model"></param> /// <returns></returns> public DailyInfo AddOrUpdate(DailyInfo model) { if (model.DailyId.IsNull()) { model.DailyId = ExtendUtil.GuidToString(); model.UpdateTime = DateTime.Now; Session.Insert(model); } else { model.UpdateTime = DateTime.Now; Session.Update(model); } return(model); }
/// <summary> /// 更新数据 Update(DailyInfo entity) /// </summary> /// <param name="entity">实体类(DailyInfo)</param> ///<returns>true:保存成功; false:保存失败</returns> public bool Update(DailyInfo entity) { var strSql = new StringBuilder(); strSql.Append("update XSBlog_Daily set "); strSql.Append(" Guid = @Guid , "); strSql.Append(" Name = @Name , "); strSql.Append(" Content = @Content , "); strSql.Append(" Create_Time = @Create_Time , "); strSql.Append(" Blog_Guid = @Blog_Guid , "); strSql.Append(" User_Guid = @User_Guid , "); strSql.Append(" Category_Guid = @Category_Guid, "); strSql.Append(" Is_Draft = @Is_Draft , "); strSql.Append(" Is_Stick = @Is_Stick , "); strSql.Append(" Is_Home = @Is_Home , "); strSql.Append(" Is_Special = @Is_Special, "); strSql.Append(" Page_View = @Page_View , "); strSql.Append(" Comments_Num = @Comments_Num "); strSql.Append(" where Guid=@Guid "); DbParameter[] parameters = { SqlHelper.MakeInParam("@Id", (DbType)SqlDbType.Decimal, entity.Id), SqlHelper.MakeInParam("@Guid", (DbType)SqlDbType.UniqueIdentifier, ConvertHelper.GetGuid(entity.Guid)), SqlHelper.MakeInParam("@Name", (DbType)SqlDbType.VarChar, entity.Name), SqlHelper.MakeInParam("@Content", (DbType)SqlDbType.Text, entity.Content), SqlHelper.MakeInParam("@Create_Time", (DbType)SqlDbType.DateTime, entity.CreateTime), SqlHelper.MakeInParam("@Blog_Guid", (DbType)SqlDbType.UniqueIdentifier, ConvertHelper.GetGuid(entity.BlogGuid)), SqlHelper.MakeInParam("@User_Guid", (DbType)SqlDbType.UniqueIdentifier, ConvertHelper.GetGuid(entity.UserGuid)), SqlHelper.MakeInParam("@Category_Guid", (DbType)SqlDbType.UniqueIdentifier, ConvertHelper.GetGuid(entity.CategoryGuid)), SqlHelper.MakeInParam("@Is_Draft", (DbType)SqlDbType.Bit, entity.IsDraft), SqlHelper.MakeInParam("@Is_Stick", (DbType)SqlDbType.Bit, entity.IsStick), SqlHelper.MakeInParam("@Is_Home", (DbType)SqlDbType.Bit, entity.IsHome), SqlHelper.MakeInParam("@Is_Special", (DbType)SqlDbType.Int, entity.IsSpecial), SqlHelper.MakeInParam("@Page_View", (DbType)SqlDbType.Int, entity.PageView), SqlHelper.MakeInParam("@Comments_Num", (DbType)SqlDbType.Int, entity.CommentsNum) }; int rows = SqlHelper.ExecuteNonQuery(CommandType.Text, strSql.ToString(), parameters); if (rows > 0) { return(true); } return(false); }
public decimal getRate(DateTime date, currency currency) { if (currency == currency.RUR) { return(1); } DailyInfo cbrClient = new DailyInfo(); cbrClient.Proxy = new WebProxy("http://msk01-wsncls02.uralsibins.ru:8080") { Credentials = new NetworkCredential(@"uralsibins\svcTinkoff", "USER4tinkoff"), }; XmlNode resultXml = cbrClient.GetCursOnDateXML(date); XmlSerializer serializer = new XmlSerializer(typeof(ValuteData)); ValuteData result = (ValuteData)serializer.Deserialize(new StringReader(resultXml.OuterXml)); return(result.ValuteCursOnDate.Single(A => A.VchCode, currency.ToString()).Vcurs); }
private void DailyInfoSet(RectTransform rt, PDailyInfo Dinfo) { DailyInfo dailyInfo = rt.gameObject.GetComponentDefault <DailyInfo>(); PDailyTask info = moduleActive.DailyListTask.Find(a => a.id == Dinfo.taskId);//ID换掉 if (info == null) { Logger.LogError("daily task can not find in modulelist" + Dinfo.taskId); return; } dailyInfo.Click(Dinfo.taskId, DailyGet, Dailygo); uint TimeS = 0; if (moduleActive.LossTime.ContainsKey(Dinfo.taskId)) { TimeS = moduleActive.AlreadyLossTime(moduleActive.LossTime[Dinfo.taskId]); } dailyInfo.DetailsInfo(Dinfo, info, TimeS); }
public void ProcessRequest(HttpContext context) { PointsService ds = new PointsService(); string username = context.User.Identity.Name; DailyInfo di = ds.DoDaily(username); string ret = JsonConvert.SerializeObject(di); context.Response.ContentType = "application/json"; List <string> trustedHosts = new List <string>(); //Add new hosts below if need cors (notice that cors header allow only one domain name) trustedHosts.Add("absmanager.cn-abs.com"); trustedHosts.Add("deallab.cn-abs.com"); string sender = context.Request.UrlReferrer == null ? "" : context.Request.UrlReferrer.Host; if (trustedHosts.Contains(sender)) { context.Response.AddHeader("Access-Control-Allow-Origin", "https://" + sender); } context.Response.AddHeader("Access-Control-Allow-Credentials", "true"); context.Response.Write(ret); }
private void PlotDailyInfo() { //clear previous info NoteTextBox.Text = "Note"; NoteTextBox.ForeColor = Color.Gray; TotalExpenseLabel.Text = "0.00"; TotalEarningLabel.Text = "0.00"; ExpenseDataGridView.Rows.Clear(); EarningDataGridView.Rows.Clear(); //plot info for new selected date DailyInfo daily = GlobalSpace.DailyInfoList.Find( d => d.Day == _selectedDay && d.Month == _selectedMonth && d.Year == _selectedYear); if (daily != null) { NoteTextBox.Text = daily.Note; NoteTextBox.ForeColor = Color.Black; foreach (ExpenseInfo expense in daily.ExpenseList) { ExpenseDataGridView.Rows.Add(expense.Reason, expense.Amount, expense.Category, expense.Comment); } foreach (EarningInfo earning in daily.EarningList) { EarningDataGridView.Rows.Add(earning.Source, earning.Amount, earning.Category, earning.Comment); } } UpdateTotalExpenseLabel(); UpdateTotalEarningLabel(); ExpenseDataGridView.Rows[0].Cells[0].Selected = false; EarningDataGridView.Rows[0].Cells[0].Selected = false; }
public static void UpdateCurrenciesFromCentralBank() { var di = new DailyInfo(); DataSet ds = di.GetCursOnDate(DateTime.Today); try { using (var db = new SQLDataAccess()) { db.cmd.CommandText = "SELECT CurrencyIso3 FROM Catalog.Currency"; db.cmd.CommandType = CommandType.Text; db.cmd.Parameters.Clear(); using (var dbUpd = new SQLDataAccess()) { dbUpd.cmd.CommandText = "UPDATE Catalog.Currency SET CurrencyValue=@CurrencyValue, CurrencyNumIso3=@CurrencyNumIso3 WHERE CurrencyIso3=@CurrencyIso3"; dbUpd.cmd.CommandType = CommandType.Text; db.cnOpen(); using (SqlDataReader read = db.cmd.ExecuteReader()) { while (read.Read()) { foreach (DataRow row in ds.Tables["ValuteCursOnDate"].Rows) { if (read["CurrencyIso3"].ToString().ToLower() != row["VchCode"].ToString().ToLower()) continue; dbUpd.cmd.Parameters.Clear(); dbUpd.cmd.Parameters.AddWithValue("@CurrencyValue", SQLDataHelper.GetDecimal(row["Vcurs"]) / SQLDataHelper.GetDecimal(row["Vnom"])); dbUpd.cmd.Parameters.AddWithValue("@CurrencyIso3", row["VchCode"].ToString()); dbUpd.cmd.Parameters.AddWithValue("@CurrencyNumIso3", row["VCode"].ToString()); dbUpd.cnOpen(); dbUpd.cmd.ExecuteNonQuery(); dbUpd.cnClose(); } } read.Close(); } } db.cnClose(); } } catch (Exception ex) { Debug.LogError(ex); } }
/// <summary> /// 保存添加数据 Add(DailyInfo entity) /// </summary> /// <param name="entity">实体类(DailyInfo)</param> ///<returns>返回新增的ID</returns> public string Add(DailyInfo entity) { return(_daily.Add(entity)); }
public CbrService(string postbody, string uri) : base(postbody, uri) { di = new DailyInfo(); parser = new CbrServiceParser(); }
private string SaveDailyInfo() { if (!_hasUnsavedChanges) { return("No changes to save."); } DailyInfo daily = new DailyInfo(); daily.Note = NoteTextBox.ForeColor == Color.Black ? NoteTextBox.Text : "No note"; daily.Day = _selectedDay; daily.Month = _selectedMonth; daily.Year = _selectedYear; daily.TotalEarning = Convert.ToDouble(TotalEarningLabel.Text); daily.TotalExpense = Convert.ToDouble(TotalExpenseLabel.Text); string source; string reason; string category; string comment; double amount; foreach (DataGridViewRow row in ExpenseDataGridView.Rows) { if (IsLastEmptyRow(ExpenseDataGridView, row.Index)) { break; } try { reason = ExpenseDataGridView.Rows[row.Index].Cells[0].Value.ToString(); reason = FilterString(reason); } catch { reason = ""; } try { if (!double.TryParse(ExpenseDataGridView.Rows[row.Index].Cells[1].Value.ToString(), out amount)) { string message = "The value for amount is not correct on row"; message += (row.Index + 1) + " in the expense table. Please correct" + " the amount in order to save."; MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return("Invalid value entered"); } } catch (NullReferenceException) { string message; message = "Looks like you forgot to enter amount on row "; message += (row.Index + 1) + " in the expense table. "; message += "Do you want to save without changing the amount?"; DialogResult dlgResult = MessageBox.Show(message, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (dlgResult == DialogResult.Yes) { amount = 0; } else { return("Terminated by user"); } } try { category = ExpenseDataGridView.Rows[row.Index].Cells[2].Value.ToString(); category = FilterString(category); } catch { category = "Other"; } try { comment = ExpenseDataGridView.Rows[row.Index].Cells[3].Value.ToString(); comment = FilterString(comment); } catch { comment = ""; } ExpenseInfo expense = new ExpenseInfo { Reason = reason, Amount = amount, Category = category, Comment = comment }; daily.ExpenseList.Add(expense); } foreach (DataGridViewRow row in EarningDataGridView.Rows) { if (IsLastEmptyRow(EarningDataGridView, row.Index)) { break; } try { source = EarningDataGridView.Rows[row.Index].Cells[0].Value.ToString(); source = FilterString(source); } catch { source = ""; } try { if (!double.TryParse(EarningDataGridView.Rows[row.Index].Cells[1].Value.ToString(), out amount)) { string message = "The value for amount is not correct on row" + (row.Index + 1) + " in the earning table. Please correct the amount in order to save."; MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return("Invalid value entered"); } } catch (NullReferenceException) { string message = "Looks like you forgot to enter amount on row " + (row.Index + 1) + " in the earning table. Do you want to save without changing the amount?"; DialogResult dlgResult = MessageBox.Show(message, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (dlgResult == DialogResult.Yes) { amount = 0; } else { return("Terminated by user"); } } try { category = EarningDataGridView.Rows[row.Index].Cells[2].Value.ToString(); category = FilterString(category); } catch { category = "Other"; } try { comment = EarningDataGridView.Rows[row.Index].Cells[3].Value.ToString(); comment = FilterString(comment); } catch { comment = ""; } EarningInfo earning = new EarningInfo { Source = source, Amount = amount, Category = category, Comment = comment, }; daily.EarningList.Add(earning); } string result = WebHandler.SaveDailyInfo(daily); if (result == "SUCCESS") { //if any info on the same date already exists, overwrite that info //otherwise, add this info as new info int index = GlobalSpace.DailyInfoList.FindIndex( d => d.Day == daily.Day && d.Month == daily.Month && d.Year == daily.Year); if (index != -1) { GlobalSpace.DailyInfoList[index] = daily; } else { GlobalSpace.DailyInfoList.Add(daily); } //monthly info should change accordingly since daily info has been modified MonthlyInfo.Fetch(); //MessageBox.Show("The data has been successfully saved!", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information); _hasUnsavedChanges = false; } return(result); }
/// <summary> /// 更新数据 Update(DailyInfo entity) /// </summary> /// <param name="entity">实体类(DailyInfo)</param> ///<returns>true:保存成功; false:保存失败</returns> public bool Update(DailyInfo entity) { return(_daily.Update(entity)); }
/// <summary> /// Executes the workflow activity. /// </summary> /// <param name="executionContext">The execution context.</param> protected override void Execute(CodeActivityContext executionContext) { // Create the tracing service ITracingService tracingService = executionContext.GetExtension <ITracingService>(); if (tracingService == null) { throw new InvalidPluginExecutionException("Failed to retrieve tracing service."); } tracingService.Trace("Entered UpdateFXs.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}", executionContext.ActivityInstanceId, executionContext.WorkflowInstanceId); // Create the context IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); if (context == null) { throw new InvalidPluginExecutionException("Failed to retrieve workflow context."); } tracingService.Trace("UpdateFXs.Execute(), Correlation Id: {0}, Initiating User: {1}", context.CorrelationId, context.InitiatingUserId); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); string serviceBaseCurrency = "RUB"; using (var ctx = new OrganizationServiceContext(service)) { try { // Get exchange rates DailyInfo client = new DailyInfo(); tracingService.Trace("Getting Most recent date available"); DateTime lastestDate = client.GetLatestDateTime(); tracingService.Trace("Getting FX Rates"); var exchangeRates = client.GetCursOnDateXML(lastestDate); string baseCurrencyISO = string.Empty; Guid empty = Guid.Empty; var baseCurrency = (from c in ctx.CreateQuery <TransactionCurrency>() join o in ctx.CreateQuery <Organization>() on c.TransactionCurrencyId equals o.BaseCurrencyId.Id select new TransactionCurrency { TransactionCurrencyId = c.TransactionCurrencyId, ISOCurrencyCode = c.ISOCurrencyCode, }).FirstOrDefault(); if (baseCurrency != null) { baseCurrencyISO = baseCurrency.ISOCurrencyCode.ToUpper(); // Get the rate from service base rate to crm base currency var serviceRateToCrmBase = GetExchangeRate(baseCurrencyISO, exchangeRates); if (serviceRateToCrmBase == null) { throw new Exception(String.Format("Cannot find rate for base rate '{0}'", baseCurrencyISO)); } // Get the currencies that are not the base currency // Only update active currencies var currencies = (from c in ctx.CreateQuery <TransactionCurrency>() where c.TransactionCurrencyId != baseCurrency.TransactionCurrencyId && c.StateCode == TransactionCurrencyState.Active select new TransactionCurrency { TransactionCurrencyId = c.TransactionCurrencyId, ISOCurrencyCode = c.ISOCurrencyCode, }); foreach (TransactionCurrency currency in currencies) { string isoCode = currency.ISOCurrencyCode.ToUpper(); decimal?latestRate = null; // Get rate from service base currency to this currency decimal?serviceRate = 1; if (isoCode != serviceBaseCurrency) { serviceRate = GetExchangeRate(isoCode, exchangeRates); } if (serviceRate != null) { // Get the rate from crm base rate latestRate = serviceRateToCrmBase / serviceRate; } else { // The webserviceX currency service is no longer working - investigating alternatives // latestRate = GetStandardRate(baseCurrencyISO, isoCode); } if (latestRate != null) { // We have a new rate so update it (even if it is the same!) TransactionCurrency update = new TransactionCurrency(); update.TransactionCurrencyId = currency.TransactionCurrencyId; update.ExchangeRate = latestRate; service.Update(update); } } } } catch (FaultException <OrganizationServiceFault> e) { tracingService.Trace("Exception: {0}", e.ToString()); // Handle the exception. throw; } catch (Exception ex) { tracingService.Trace("Exception (will retry): {0}", ex.ToString()); // All exceptions must be retried since this workflow must call it's self to run on a daily basis OrganizationServiceFault fault = new OrganizationServiceFault(); fault.ErrorCode = -2147204346; // This will cause the Async Server to retry up to 10 times before failing fault.Message = ex.ToString(); var networkException = new FaultException <OrganizationServiceFault>(fault); throw networkException; } } tracingService.Trace("Exiting UpdateFXs.Execute(), Correlation Id: {0}", context.CorrelationId); }
public ActionResult Create(Project project, int? WorkCategoryId, string WorkContent, DateTime CreateDate, int WorkingHours, int? EmployeeList ) { DailyInfo dailyinfo = new DailyInfo(); dailyinfo.Project = db.Projects.Find(project.ProjectId); dailyinfo.WorkCategoryId = WorkCategoryId; dailyinfo.WorkContent = WorkContent; dailyinfo.CreateDate = CreateDate; dailyinfo.WorkingHours = WorkingHours; dailyinfo.Employee = db.Employees.Where(e => (EmployeeList == null && e.Account == User.Identity.Name) || (EmployeeList != null && e.EmployeeId == EmployeeList)).FirstOrDefault(); if (ModelState.IsValid) { db.Dailies.Add(dailyinfo); db.SaveChanges(); return RedirectToAction("Index"); } return View(dailyinfo); }
public void UpdateGrid(DailyInfo dailyinfo) { db.Database.ExecuteSqlCommand("UPDATE DailyInfoes SET WorkContent = {0}, WorkingHours = {1} WHERE DailyInfoId = {2}", dailyinfo.WorkContent, dailyinfo.WorkingHours, dailyinfo.DailyInfoId); }
public void LoadLowData() { { TextAsset data = Resources.Load("TestJson/Achievement_Achievement", typeof(TextAsset)) as TextAsset; StringReader sr = new StringReader(data.text); string strSrc = sr.ReadToEnd(); JSONObject Achievement = new JSONObject(strSrc); for (int i = 0; i < Achievement.list.Count; i++) { AchievementInfo tmpInfo = new AchievementInfo(); tmpInfo.Id = (uint)Achievement[i]["Id_ui"].n; tmpInfo.Type = (byte)Achievement[i]["Type_b"].n; tmpInfo.Subtype = (byte)Achievement[i]["Subtype_b"].n; tmpInfo.Phase = (byte)Achievement[i]["Phase_b"].n; tmpInfo.Cleartype = (ushort)Achievement[i]["Cleartype_us"].n; tmpInfo.Clearvalue = (uint)Achievement[i]["Clearvalue_ui"].n; tmpInfo.NextId = (uint)Achievement[i]["NextId_ui"].n; tmpInfo.NameId = (uint)Achievement[i]["NameId_ui"].n; tmpInfo.DescriptionId = (uint)Achievement[i]["DescriptionId_ui"].n; tmpInfo.RewardId = (uint)Achievement[i]["RewardId_ui"].n; tmpInfo.Getpoint = (uint)Achievement[i]["Getpoint_ui"].n; AchievementInfoList.Add(tmpInfo); } } { TextAsset data = Resources.Load("TestJson/Achievement_AchievementCategory", typeof(TextAsset)) as TextAsset; StringReader sr = new StringReader(data.text); string strSrc = sr.ReadToEnd(); JSONObject AchievementCategory = new JSONObject(strSrc); for (int i = 0; i < AchievementCategory.list.Count; i++) { AchievementCategoryInfo tmpInfo = new AchievementCategoryInfo(); tmpInfo.Id = (uint)AchievementCategory[i]["Id_ui"].n; tmpInfo.Type = (byte)AchievementCategory[i]["Type_b"].n; tmpInfo.Clearvalue = (uint)AchievementCategory[i]["Clearvalue_ui"].n; tmpInfo.RewardId = (uint)AchievementCategory[i]["RewardId_ui"].n; AchievementCategoryInfoList.Add(tmpInfo); } } { TextAsset data = Resources.Load("TestJson/Achievement_Daily", typeof(TextAsset)) as TextAsset; StringReader sr = new StringReader(data.text); string strSrc = sr.ReadToEnd(); JSONObject Daily = new JSONObject(strSrc); for (int i = 0; i < Daily.list.Count; i++) { DailyInfo tmpInfo = new DailyInfo(); tmpInfo.Id = (uint)Daily[i]["Id_ui"].n; tmpInfo.NameId = (uint)Daily[i]["NameId_ui"].n; tmpInfo.DescId = (uint)Daily[i]["DescId_ui"].n; tmpInfo.Type = (ushort)Daily[i]["Type_us"].n; tmpInfo.Sort = (byte)Daily[i]["Sort_b"].n; tmpInfo.Phase = (byte)Daily[i]["Phase_b"].n; tmpInfo.MaxCount = (uint)Daily[i]["MaxCount_ui"].n; tmpInfo.PointValue = (uint)Daily[i]["PointValue_ui"].n; tmpInfo.LimitLv = (byte)Daily[i]["LimitLv_b"].n; tmpInfo.NextId = (uint)Daily[i]["NextId_ui"].n; tmpInfo.RewardId = (uint)Daily[i]["RewardId_ui"].n; DailyInfoList.Add(tmpInfo); } } { TextAsset data = Resources.Load("TestJson/Achievement_DailyReward", typeof(TextAsset)) as TextAsset; StringReader sr = new StringReader(data.text); string strSrc = sr.ReadToEnd(); JSONObject DailyReward = new JSONObject(strSrc); for (int i = 0; i < DailyReward.list.Count; i++) { DailyRewardInfo tmpInfo = new DailyRewardInfo(); tmpInfo.Id = (uint)DailyReward[i]["Id_ui"].n; tmpInfo.RewardRank = (byte)DailyReward[i]["RewardRank_b"].n; tmpInfo.PointValue = (uint)DailyReward[i]["PointValue_ui"].n; tmpInfo.RewardId = (uint)DailyReward[i]["RewardId_ui"].n; tmpInfo.VipRewardId = (uint)DailyReward[i]["VipRewardId_ui"].n; tmpInfo.LimitVip = (byte)DailyReward[i]["LimitVip_b"].n; DailyRewardInfoList.Add(tmpInfo); } } }
private void ActionUponFetchDailyInfoSuccess() { string result = _webHandlerObject.Response; string[] rows = result.Split('^'); if (rows[0] == "Server connection error") { //some server error occurred _progressViewerObject.StopProgress(); ShowErrorMessage("Server connection error. Please check your internet connection."); return; } //start fetching categories from database on a seperate thread //before starting to process the fetched daily info FetchCategories(); if (rows[0] == "") { //no daily info found for this user in database //so no need to process the info return; } //process the fetched daily info and store them in StaticStorage class foreach (string row in rows) { string[] cols = row.Split('|'); int day = Convert.ToInt16(cols[0]); int month = Convert.ToInt16(cols[1]); int year = Convert.ToInt16(cols[2]); string note = StringCipher.Decrypt(cols[3], GlobalSpace.CypherKey); string[] expenseReasons = StringCipher.Decrypt(cols[4], GlobalSpace.CypherKey).Split('~'); string[] expenseAmounts = StringCipher.Decrypt(cols[5], GlobalSpace.CypherKey).Split('~'); string[] expenseCategories = StringCipher.Decrypt(cols[6], GlobalSpace.CypherKey).Split('~'); string[] expenseComments = StringCipher.Decrypt(cols[7], GlobalSpace.CypherKey).Split('~'); string[] earningSources = StringCipher.Decrypt(cols[8], GlobalSpace.CypherKey).Split('~'); string[] earningAmounts = StringCipher.Decrypt(cols[9], GlobalSpace.CypherKey).Split('~'); string[] earningCategories = StringCipher.Decrypt(cols[10], GlobalSpace.CypherKey).Split('~'); string[] earningComments = StringCipher.Decrypt(cols[11], GlobalSpace.CypherKey).Split('~'); string totalExpense = StringCipher.Decrypt(cols[12], GlobalSpace.CypherKey); string totalEarning = StringCipher.Decrypt(cols[13], GlobalSpace.CypherKey); DailyInfo daily = new DailyInfo { Day = day, Month = month, Year = year, Note = note, TotalEarning = Convert.ToDouble(totalEarning), TotalExpense = Convert.ToDouble(totalExpense) }; if (expenseAmounts[0] != "") { for (int i = 0; i < expenseReasons.Length; i++) { double amount = Convert.ToDouble(expenseAmounts[i]); string reason = expenseReasons[i]; string category = expenseCategories[i]; string comment = expenseComments[i]; ExpenseInfo expense = new ExpenseInfo { Reason = reason, Amount = amount, Category = category, Comment = comment }; daily.ExpenseList.Add(expense); } } if (earningAmounts[0] != "") { for (int i = 0; i < earningSources.Length; i++) { double amount = Convert.ToDouble(earningAmounts[i]); string source = earningSources[i]; string category = earningCategories[i]; string comment = earningComments[i]; EarningInfo earning = new EarningInfo { Source = source, Amount = amount, Category = category, Comment = comment }; daily.EarningList.Add(earning); } } GlobalSpace.DailyInfoList.Add(daily); } }