//=============================================================== // Function: Page_Load //=============================================================== protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DbConnection conn = new SqlConnection(GlobalSettings.connectionString); try { conn.Open(); DbCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT HomePageContent FROM HomePageContent "; DbDataReader rdr = cmd.ExecuteReader(); rdr.Read(); homePageContentTextBox.Text = (string)rdr["HomePageContent"]; rdr.Close(); } catch (Exception ex) { ErrorLog errorLog = new ErrorLog(); errorLog.WriteLog("", "", ex.Message, logMessageLevel.errorMessage); throw ex; } finally { conn.Close(); } } }
public SelectRemoteSystem(APPLICATION_DATA appData) { InitializeComponent(); m_AppData = appData; m_AppData.AddOnClosing(OnClose, APPLICATION_DATA.CLOSE_ORDER.FIRST); m_Log = (ErrorLog) m_AppData.Logger; m_AppData.CurrentlyLoggedInRemoteServer = (object)new RemoteHosts(m_AppData, true);// assign a nullHost as a place holder until the use selects an actual server MessageGenerators = new MessageGeneratorEvents(this); buttonLogout.Visible = false; buttonLogout.Enabled = false; m_StatsViewer = new StatsViewer(m_AppData); //744, 57 m_StatsViewer.Location = new Point(744, 57); this.Controls.Add(m_StatsViewer); bool hostsLoaded = false; string hostfile = UserSettings.Get(UserSettingTags.REMOTEHOSTS_LastHostFileUsed); if (hostfile != null) { if (File.Exists(hostfile)) { m_HostFile = hostfile; LoadHostsFromFile(hostfile); hostsLoaded = true; } } if ( ! hostsLoaded) AddLocalDefaultHost(); }
public void FillArticle(int SiteId, string keyword, int MatchType) { try { //articleCount = "Your Query <b><i>" + keyword + "</i></b> returned " + customTransactions.GetSearchResults(1, keyword, SortMethod,MatchType).Rows.Count.ToString() + " record(s) "; dtSearchResults = null; dtSearchResults = customTransactions.GetSearchResults(1, keyword, SortMethod, MatchType); articleCount = (MatchType == 1) ? "Your Query <b><i>“" + keyword + "”</i></b> returned " + dtSearchResults.Rows.Count.ToString() + " record(s) " : "Your Query <b><i>" + keyword + "</i></b> returned " + dtSearchResults.Rows.Count.ToString() + " record(s)"; if (customTransactions.GetSearchResults(1, keyword, SortMethod,MatchType).Rows.Count != 0) { gridArticle.DataSource = customTransactions.GetSearchResults(1, keyword, SortMethod, MatchType); gridArticle.DataBind(); } else { // dvArticleCount.InnerHtml = "Your Query <b><i>" + keyword + "</i></b> returned no record(s) for ARTICLE"; gridArticle.DataSource = null; gridArticle.DataBind(); dvArticleCount.InnerText = "No Records Found"; } } catch (Exception ex) { UserInfo info = UserController.GetCurrentUserInfo(); ErrorLog objLog = new ErrorLog(); objLog.ErrorDescription = ex.ToString(); objLog.ErrorDate = DateTime.Now; objLog.ErrorFunctionName = System.Reflection.MethodBase.GetCurrentMethod().Name; objLog.ErrorControlName = (GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").Remove(0, GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").LastIndexOf("_") + 1)); objLog.ErrorLoggedInUser = info.Username; objLog.AddErrorToLog(objLog); } }
protected void Page_Load(object sender, EventArgs e) { try { SqlDataAdapter da = new SqlDataAdapter("sp_section",new SqlConnection(customTransactions.connectionString)); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@Categoryid", Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["News"])); da.SelectCommand.Parameters.AddWithValue("@rows", Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["newsrows"])); DataTable dt = new DataTable(); da.Fill(dt); rptnews.DataSource = dt; rptnews.DataBind(); } catch (Exception ex) { UserInfo info = UserController.GetCurrentUserInfo(); ErrorLog objLog = new ErrorLog(); objLog.ErrorDescription = ex.ToString(); objLog.ErrorDate = DateTime.Now; objLog.ErrorFunctionName = "Page Load"; objLog.ErrorControlName = (GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").Remove(0, GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").LastIndexOf("_") + 1)); objLog.ErrorLoggedInUser = info.Username; objLog.AddErrorToLog(objLog); } }
public static bool LogError(ErrorLog ErrorLog) { try { if (_errorsRepository == null) { _errorsRepository = new ErrorsRepository(); } _errorsRepository.Add(ErrorLog); return _errorsRepository.Save(); } catch (Exception ex) { //Intenta guardar en un log físico try { using (StreamWriter writer = new StreamWriter(System.Web.HttpContext.Current.Server.MapPath("~/")+"errorLog.txt", true)) { StringBuilder errorText = new StringBuilder(); errorText.Append(DateTime.UtcNow.GetCurrentTime().GetCurrentTime().ToShortDateString() + " " + DateTime.UtcNow.GetCurrentTime().ToShortTimeString()); errorText.Append(" | " + ((enumMessageType)ErrorLog.ErrorType).ToString()); errorText.Append(" | " + (string.IsNullOrEmpty(ErrorLog.ErrorCode) ? " " : ErrorLog.ErrorCode)); errorText.Append(" | " + ErrorLog.Message); errorText.Append(" | " + ErrorLog.IP); writer.WriteLine(errorText.ToString()); } return true; } catch (Exception ex2) { //Tampoco pudo guardar en arhivo return false; } } }
public ModuleCompiler(ErrorLog errorLog, SymbolTable symbolTable, IodineModule module) { this.errorLog = errorLog; this.symbolTable = symbolTable; this.module = module; functionCompiler = new FunctionCompiler (errorLog, symbolTable, module.Initializer); }
public SmartSearchLibUC(APPLICATION_DATA appData, ABORT_CLOSE giveup) { InitializeComponent(); m_AppData = appData; m_AppData.AddOnClosing(OnClose,APPLICATION_DATA.CLOSE_ORDER.FIRST); m_Log = (ErrorLog)m_AppData.Logger; GiveUp = giveup; m_PathManager= (PATHS) m_AppData.PathManager ; textBoxMinMatch.Text = "0"; m_SearchTool = new SearchLib(m_AppData); this.Text = "Smart Search"; m_ZoomTrackLock = new object(); trackBarZoomControl.Minimum = 0; trackBarZoomControl.Maximum = 1000; buttonUndoDelete.Enabled = false; dataGridView1.KeyDown += new KeyEventHandler(dataGridView1_KeyDown); dataGridView1.CellClick +=new DataGridViewCellEventHandler(dataGridView1_CellContentClick); // mouse click on cell dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged); // support cell selection changes by keyboard (i.e. not by mouse click) dataGridView1.Columns["time"].DefaultCellStyle.Format = m_AppData.TimeFormatStringForDisplay;// "dd MMM yyyy, HH: mm: ss: ffff"; m_SearchStatusDisplay = new SearchStatusDisplayUC(m_AppData, UserCanceledSearch); m_SearchStatusDisplay.Location = new Point(594, 55); this.Controls.Add(m_SearchStatusDisplay); }
protected void Register(object sender, EventArgs e) { try { if (lnkRegister.Text == "Profile") { Response.Redirect("/profile", false); } else { Response.Redirect("/register", false); } } catch (Exception ex) { UserInfo info = UserController.GetCurrentUserInfo(); ErrorLog objLog = new ErrorLog(); objLog.ErrorDescription = ex.ToString(); objLog.ErrorDate = DateTime.Now; objLog.ErrorFunctionName = System.Reflection.MethodBase.GetCurrentMethod().Name; objLog.ErrorControlName = (GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").Remove(0, GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").LastIndexOf("_") + 1)); objLog.ErrorLoggedInUser = info.Username; objLog.AddErrorToLog(objLog); } }
public bool DeleteErrorLog(ErrorLog errorLog) { if(errorLog==null) return false; _unitOfWork.ErrorLogRepository.Delete(errorLog); _unitOfWork.Save(); return true; }
protected void Page_Load(object sender, EventArgs e) { try { ans1 = Session["answer"]!= null ? Session["answer"].ToString() : ""; if (DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().UserID != -1) { //Response.Write(DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().DisplayName); txtName.Text = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().DisplayName; } else { txtName.Text = "Anonymous"; } BindComment(); } catch (Exception ex) { UserInfo info = UserController.GetCurrentUserInfo(); ErrorLog objLog = new ErrorLog(); objLog.ErrorDescription = ex.ToString(); objLog.ErrorDate = DateTime.Now; objLog.ErrorFunctionName = System.Reflection.MethodBase.GetCurrentMethod().Name; objLog.ErrorControlName = (GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").Remove(0, GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").LastIndexOf("_") + 1)); objLog.ErrorLoggedInUser = info.Username; objLog.AddErrorToLog(objLog); } }
protected void Page_Load(object sender, EventArgs e) { try { SqlDataAdapter da = new SqlDataAdapter("sp_HomeTopRightArticle", new SqlConnection(customTransactions.connectionString)); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@Categoryid", Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ProductReview"])); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count > 0) { title = dt.Rows[0]["Title"].ToString(); thumbnail = "../ImageHandler.ashx?imgpath=" + dt.Rows[0]["Thumbnail"].ToString() + "&w=270&h=130"; url = customTransactions.GenerateFriendlyURL("article", title, "0-" + dt.Rows[0]["Id"].ToString(), 0); teaser = dt.Rows[0]["Teaser"].ToString(); } } catch (Exception ex) { UserInfo info = UserController.GetCurrentUserInfo(); ErrorLog objLog = new ErrorLog(); objLog.ErrorDescription = ex.ToString(); objLog.ErrorDate = DateTime.Now; objLog.ErrorFunctionName = "Page Load"; objLog.ErrorControlName = (GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").Remove(0, GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").LastIndexOf("_") + 1)); objLog.ErrorLoggedInUser = info.Username; objLog.AddErrorToLog(objLog); } }
protected void Page_Load(object sender, EventArgs e) { try { SqlDataAdapter da = new SqlDataAdapter("sp_HomeDepartment_Articles", new SqlConnection(customTransactions.connectionString)); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@Id1", Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["AVSystems"])); da.SelectCommand.Parameters.AddWithValue("@Id2", Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["LawEnforcement"])); da.SelectCommand.Parameters.AddWithValue("@Id3", Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Production"])); da.Fill(ds); dldepartments.DataSource = ds; dldepartments.DataBind(); } catch (Exception ex) { UserInfo info = UserController.GetCurrentUserInfo(); ErrorLog objLog = new ErrorLog(); objLog.ErrorDescription = ex.ToString(); objLog.ErrorDate = DateTime.Now; objLog.ErrorFunctionName = System.Reflection.MethodBase.GetCurrentMethod().Name; objLog.ErrorControlName = (GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").Remove(0, GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").LastIndexOf("_") + 1)); objLog.ErrorLoggedInUser = info.Username; objLog.AddErrorToLog(objLog); } }
protected void rptDataBound(object sender, DataListItemEventArgs e) { try { string str = Server.HtmlDecode(ds.Tables[0].Rows[e.Item.ItemIndex]["Article"].ToString()); Match m = Regex.Match(str, @"<img(.|\n)+?>"); Image ArticleImage = (Image)e.Item.FindControl("img"); if (!string.IsNullOrEmpty(ds.Tables[0].Rows[e.Item.ItemIndex]["Thumbnail"].ToString())) { System.Drawing.Bitmap bmp = customTransactions.RezizeImage(Server.MapPath(ds.Tables[0].Rows[e.Item.ItemIndex]["Thumbnail"].ToString()), 110, 80, ArticleImage); ArticleImage.ImageUrl = ds.Tables[0].Rows[e.Item.ItemIndex]["Thumbnail"].ToString(); } else if (m.Success) { Match inner = Regex.Match(m.Value, "src=[\'|\"](.+?)[\'|\"]"); if (inner.Success) { string imageurl = inner.Value.Substring(5).Substring(0, inner.Value.Substring(5).LastIndexOf("\"")); System.Drawing.Bitmap bmp = customTransactions.RezizeImage(Server.MapPath(imageurl), 110, 80, ArticleImage); ArticleImage.ImageUrl = inner.Value.Substring(5).Substring(0, inner.Value.Substring(5).LastIndexOf("\"")); } } } catch (Exception ex) { UserInfo info = UserController.GetCurrentUserInfo(); ErrorLog objLog = new ErrorLog(); objLog.ErrorDescription = ex.ToString(); objLog.ErrorDate = DateTime.Now; objLog.ErrorFunctionName = "Page Load"; objLog.ErrorControlName = (GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").Remove(0, GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").LastIndexOf("_") + 1)); objLog.ErrorLoggedInUser = info.Username; objLog.AddErrorToLog(objLog); } }
protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["SiteSqlServer"].ToString(); SqlDataAdapter da = new SqlDataAdapter("sp_HomeCoverStory", new SqlConnection(customTransactions.connectionString)); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@PortalId", customTransactions.PortalId); da.Fill(ds); JSON_DataTable_DataHolder.Value = customTransactions.DataTableToJSON(customTransactions.TrimDataTableJSON(ds), "HomeCoverStory"); } } catch (Exception ex) { UserInfo info = UserController.GetCurrentUserInfo(); ErrorLog objLog = new ErrorLog(); objLog.ErrorDescription = ex.ToString(); objLog.ErrorDate = DateTime.Now; objLog.ErrorFunctionName = System.Reflection.MethodBase.GetCurrentMethod().Name; objLog.ErrorControlName = (GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").Remove(0, GetType().ToString().Replace("ASP.", "").Replace("_ascx", ".ascx").LastIndexOf("_") + 1)); objLog.ErrorLoggedInUser = info.Username; objLog.AddErrorToLog(objLog); } }
/// bulk of code written by: Alex Marcum - 11/20/2012 public static void logError(Exception ex) { System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(1, true); //System.IO.FileInfo temp = new System.IO.FileInfo(fileName); //fileName = temp.Name; //Class Name is the Whole path to the Filename string fileName = stackFrame.GetFileName(); string functionName = stackFrame.GetMethod().Name.ToString(); int line = stackFrame.GetFileLineNumber(); try { using (CCSEntities db = new CCSEntities()) { ErrorLog el = new ErrorLog(); el.TimeStamp = DateTime.Now; el.FileName = fileName; el.FunctionName = functionName; el.LineNumber = line.ToString(); el.ErrorText = ex.Message; db.ErrorLogs.Add(el); db.SaveChanges(); } } catch (Exception /*ex*/) { } }
public override void Save(ErrorLog errorLog) { using(var conn = Connection) { conn.Execute(Queries.Save, (DbErrorLog) errorLog); } }
/// constructor /// public WatchLists(APPLICATION_DATA appData) { try { // load stored data mapURL = UserSettings.Get(UserSettingTags.GPSMAPURL); if (mapURL == null) mapURL = "http://maps.google.com/maps?q="; m_AppData = appData; m_Log = (ErrorLog)m_AppData.Logger; m_AppData.AddOnClosing(Stop, APPLICATION_DATA.CLOSE_ORDER.MIDDLE); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.WatchList.WatchList_LastAlert].StatString.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.WatchList.WatchList_NumAlerts].Accumulator.RegisterForUse(true); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.WatchList.Watchlist_NumListsLoaded].Accumulator.RegisterForUse(true); m_Stop = false; m_NewLPRResultQ = new ThreadSafeQueue<FRAME>(60); m_AlertsToBeGeneratedQ = new ThreadSafeQueue<FRAME>(60); m_SettingsTags = new WatchListDynamicTags(); m_LoadListSingleton = new object(); m_WatchLists = LoadListsFromUserConfig(); m_AppData.HealthStatistics[(int)APPLICATION_DATA.HEALTH_STATISTICS.WatchList.Watchlist_NumListsLoaded].Accumulator.SetValue = m_WatchLists.Count; } catch (Exception ex) { m_Log.Trace(ex, ErrorLog.LOG_TYPE.FATAL); } }
public ControlCenterMainForm() { InitializeComponent(); m_ScreenLogger = new ScreenLogger();// debug tool // load up the AppData object so the rest of the app has acccess to global resources m_AppData = new APPLICATION_DATA(); m_AppData.LogToScreen = m_ScreenLogger; m_Log = new ErrorLog(m_AppData); m_AppData.Logger = m_Log; m_ScreenLogger.Show(); m_AppData.RCSProtocol = (object)new RCS_Protocol.RCS_Protocol(m_AppData,null); m_AppData.TCPClient = (object)new RCSClientLib.RCSClient(null, m_AppData); this.FormClosing += new FormClosingEventHandler(Form1_FormClosing); tabControlMain.Click += new EventHandler(tabControlMain_Click); // not logged in m_AppData.LoggedIn = APPLICATION_DATA.LoggedInAs.NOT_LOGGED_IN; // start on the select server tab tabControlMain.SelectedTab = tabPageSelectServer; m_CurrentPage = tabControlMain.SelectedTab; LoadSelectServerUC(); }
public void StartProcess() { timer.Enabled = true; timer.Start(); Worker.RunWorkerAsync(); ErrorLog Log = new ErrorLog(); Log.WriteFiles(DateTime.Now.ToString() + "—" + "GetSVDBDataBuffer" + "—StartProcess"); }
public void Execute(ErrorLog errorLog) { new WebClient { Credentials = Credentials, Headers = new WebHeaderCollection { { "Content-Type", "application/x-www-form-urlencoded" } } }.UploadStringAsync(new Uri(Settings.Url ?? "http://twitter.com/statuses/update.xml"), "POST", Format(errorLog)); }
public static void DisplayErrors(ErrorLog errorLog) { foreach (Error err in errorLog) { Location loc = err.Location; Console.Error.WriteLine ("{0} ({1}:{2}) error: {3}", Path.GetFileName (loc.File), loc.Line, loc.Column, err.Text); } }
public DataSet UserAttentication(ref ErrorLog elog, string Username, String Password) { List<SqlParameter> param = new List<SqlParameter>(); param.Add(dbm.InParam("@Username", SqlDbType.VarChar, 50, Username)); param.Add(dbm.InParam("@Password", SqlDbType.VarChar, 50, Password)); return dbm.GetDS(ref elog, param, "sp_VerfiyingUsers"); }
void Start() { errorLog = gameObject.GetComponent<ErrorLog>(); textStyle = new GUIStyle (); textStyle.normal.textColor = textColour; textStyle.fontSize = 16; }
public Tokenizer(ErrorLog errorLog, string source, string file = "") { this.errorLog = errorLog; this.source = source; this.file = file; position = 0; sourceLen = source.Length; location = new Location (0, 0, file); }
public override void Save(ErrorLog errorLog) { using (var writer = File(errorLog).OpenWrite()) { serializer.Serialize(writer, errorLog); writer.Flush(); } files = null; }
public FunctionCompiler(ErrorLog errorLog, SymbolTable symbolTable, IodineMethod methodBuilder, Stack<IodineLabel> breakLabels, Stack<IodineLabel> continueLabels) { this.errorLog = errorLog; this.symbolTable = symbolTable; this.methodBuilder = methodBuilder; this.breakLabels = breakLabels; this.continueLabels = continueLabels; }
public EmailServices(APPLICATION_DATA appData) { m_AppData = appData; m_AppData.AddOnClosing(Stop, APPLICATION_DATA.CLOSE_ORDER.MIDDLE); m_Log = (ErrorLog) m_AppData.Logger; m_SendMessagesQ = new ThreadSafeQueue<SEND_MESSAGE>(40); m_SendResultEvents = new ThreadSafeHashTable(40); m_SendResultQ = new ThreadSafeQueue<SEND_RESULT>(40); }
void timer_Tick(object sender, EventArgs e) { ErrorLog Log = new ErrorLog(); Log.WriteFiles(DateTime.Now.ToString() + "—" + "GetSVDBDataBuffer" + "—timer_Tick_B"); if (!Worker.IsBusy) { Worker.RunWorkerAsync(); Log.WriteFiles(DateTime.Now.ToString() + "—" + "GetSVDBDataBuffer" + "—timer_Tick_A"); } }
public DataSet fillingPatient(ref ErrorLog elog) { List<SqlParameter> param = new List<SqlParameter>(); //param.Add(dbm.InParam("@Name", SqlDbType.VarChar, 50, patient_name)); param.Add(dbm.InParam("@Name", SqlDbType.VarChar, 50, patient_name)); param.Add(dbm.InParam("@From_Date", SqlDbType.Date, 8, fromDate)); param.Add(dbm.InParam("@To_Date", SqlDbType.Date, 8, toDate)); return dbm.GetDS(ref elog, param, "ShowingPatientRecords"); }
public void Log(Exception exception) { var log = new ErrorLog { Message = exception.ToString(), When = DateTime.Now }; _entities.ErrorLogs.Add(log); _entities.SaveChanges(); }
public ActionResult ContentUpdate(int id, string name, string title, string body, bool?snippet, int?roleid, string contentKeyWords, string stayaftersave = null) { var content = CurrentDatabase.Contents.SingleOrDefault(c => c.Id == id); content.Name = name; content.Title = string.IsNullOrWhiteSpace(title) ? name : title; content.Body = body; content.RemoveGrammarly(); content.RoleID = roleid ?? 0; content.Snippet = snippet; content.SetKeyWords(CurrentDatabase, contentKeyWords.SplitStr(",").Select(vv => vv.Trim()).ToArray()); if (content.TypeID == ContentTypeCode.TypeEmailTemplate) { try { var captureWebPageBytes = CaptureWebPageBytes(body, 100, 150); var ii = CurrentImageDatabase.UpdateImageFromBits(content.ThumbID, captureWebPageBytes); if (ii == null) { content.ThumbID = ImageData.Image.NewImageFromBits(captureWebPageBytes, CurrentImageDatabase).Id; } content.DateCreated = DateTime.Now; } catch (Exception ex) { var errorLog = ErrorLog.GetDefault(null); errorLog.Log(new Error(ex)); } } CurrentDatabase.SubmitChanges(); if (string.Compare(content.Name, "CustomReportsMenu", StringComparison.OrdinalIgnoreCase) == 0) { try { var list = ReportsMenuModel.CustomItems1; } catch (Exception ex) { if (ex is System.Xml.XmlException) { return(Content(Util.EndShowMessage(ex.Message, "javascript: history.go(-1)", "There is invalid XML in this document. Go Back to Repair"))); } } } else if (string.Compare(content.Name, "CustomReports", StringComparison.OrdinalIgnoreCase) == 0) { try { var list = CurrentDatabase.ViewCustomScriptRoles.ToList(); } catch (Exception ex) { if (ex.Message.Contains("XML parsing", ignoreCase: true)) { return(Content(Util.EndShowMessage(ex.InnerException?.Message, "javascript: history.go(-1)", "There is invalid XML in this document. Go Back to Repair"))); } } } else if (string.Compare(content.Name, "StandardExtraValues2", StringComparison.OrdinalIgnoreCase) == 0) { try { CmsData.ExtraValue.Views.GetStandardExtraValues(CurrentDatabase, "People"); } catch (InvalidOperationException ex) { if (ex.InnerException is System.Xml.XmlException) { return(Content(Util.EndShowMessage(ex.InnerException.Message, "javascript: history.go(-1)", "There is invalid XML in this document. Go Back to Repair"))); } } } if (stayaftersave == "true") { return(RedirectToAction("ContentEdit", new { id, snippet })); } var url = GetIndexTabUrl(content); return(Redirect(url)); }
public ActionResult Save(TransactionEditViewModel transEditView) { //Coloca valor do parâmetro show_errors numa var booleana para uso futuro var showErros = true; //Cria lista de erros encontrados durante a validação List <Error> errors = new List <Error>(); TransactionApiInputDto inputTransaction; var transactionType = new TransactionType(); var cardBrand = new CardBrand(); var card = new Card(); var clientInDB = new Client(); decimal transAmountInDecimal = 0m; //A transação é presumida recusada inicialmente var statusCode = Constantes.scRecusada; var statusReason = Constantes.srErroInesperado; //Pega todos os Transactiontypes(tipos de transações) var transactionTypes = _unitOfWork.TransactionTypes.GetAll(); //Pega todos os CardBrands(bandeiras de cartões) var cardBrands = _unitOfWork.CardBrands.GetAll(); //Atribuindo os TransactionTypes e os CardBrands a viewmodel caso tenhamos que voltar para a view transEditView.TransactionTypes = transactionTypes; transEditView.CardBrands = cardBrands; //Se algum erro foi gerado até aqui... if (!ModelState.IsValid) { //Retorna a TransactionEditViewModel para a view TransactionForm(nova transação) return(View("TransactionForm", transEditView)); } //Esse teste é executado somente aqui e antes de chamar o validador (não é executado no validador) var tempAmount = transEditView.Amount.Replace(",", ""); var amountIsDigit = tempAmount.All(char.IsDigit); //Verifica se todos os caracteres do campo card_number são números if (!amountIsDigit) { ModelState.AddModelError("", "410 - O valor informado não é válido."); } if (!ModelState.IsValid) { //Retorna a TransactionEditViewModel para a view TransactionForm(nova transação) return(View("TransactionForm", transEditView)); } var dblAmount = Convert.ToDouble(transEditView.Amount); var intAmount = Convert.ToInt32(dblAmount * 100); //Move os dados da Edit View para a Dto. inputTransaction = new TransactionApiInputDto { amount = intAmount, card_brand = transEditView.CardBrandApiName, card_holder_name = transEditView.CardHolderName, card_number = transEditView.Number, cvv = transEditView.Cvv, expiration_month = transEditView.ExpirationMonth, expiration_year = transEditView.ExpirationYear, installments = transEditView.Installments, password = transEditView.Password, show_errors = showErros, transaction_type = transEditView.TransactionTypeApiName, }; var validador = new Validador(_unitOfWork, showErros); validador.ProcessTransaction(inputTransaction); statusCode = validador.statusCode; statusReason = validador.statusReason; transAmountInDecimal = validador.transAmountInDecimal; transactionType = validador.transactionType; cardBrand = validador.cardBrand; card = validador.card; clientInDB = validador.clientInDB; errors = validador.errors; // *** FIM DAS VALIDAÇÕES *** //Adiciona todos os error do validador ao ModelState if (errors.Count > 0) { foreach (var e in errors) { ModelState.AddModelError("", e.error_code + " - " + e.error_message); } } if (!ModelState.IsValid) { //Retorna a TransactionEditViewModel para a view TransactionForm(nova transação) return(View("TransactionForm", transEditView)); } // Validação Terminada com Sucesso \__________________ var cardNumberFirst = ""; var cardNumberLast = ""; if (!String.IsNullOrEmpty(transEditView.Number)) { cardNumberFirst = transEditView.Number.Substring(1, 4); if (transEditView.Number.Length >= 4) { cardNumberLast = transEditView.Number.Substring(transEditView.Number.Length - 4, 4); } } //Gera registro da transação(transaction log) solicitada para ser salva na base de dados var transactionLog = new TransactionLog { Amount = Convert.ToInt32(transAmountInDecimal * 100), Card_brand = card.CardBrand.ApiName, Card_holder_name = transEditView.CardHolderName, Card_number_first = cardNumberFirst, Card_number_last = cardNumberLast, Installments = transEditView.Installments, Transaction_type = transEditView.TransactionTypeApiName, Status_code = statusCode, Status_reason = statusReason, Creation_timestamp = DateTime.Now, //Errors = null }; //Adiciona registro no log de transações ao banco de dados _unitOfWork.TransactionLogs.Add(transactionLog); if (errors.Count > 0) { foreach (var e in errors) { var errorLog = new ErrorLog { TransactionLogId = transactionLog.Id, Error_code = e.error_code, Error_message = e.error_message }; _unitOfWork.ErrorLogs.Add(errorLog); } } ; //Criar a transação vinculada ao cartão e coloca a data de criação var transaction = new Transaction { Amount = transAmountInDecimal, CardId = card.Id, CreationTimestamp = DateTime.Now, Installments = transEditView.Installments, TransactionTypeId = transactionType.Id, TransactionLogId = transactionLog.Id }; //Adiciona a transação ao banco de dados _unitOfWork.Transactions.Add(transaction); //Atualiza o saldo do cliente com o valor da transação. clientInDB.Saldo = clientInDB.Saldo - transaction.Amount; _unitOfWork.Complete(); //Retorna a TransactionEditViewModel para a view Index(listagem de transações) return(RedirectToAction("Index", new { cardId = transaction.CardId })); }
//To draw initial layout private AutoWiringNodeGroup CreateWiringNodeStructure(ControlGroup controlGroup) { AutoWiringNodeGroup wiringGroup = new AutoWiringNodeGroup(); foreach (Controller controller in Project.CurrentProject.ControllerList) { if (controller.ControlGroupID == controlGroup.Id) { int level = 1; if (controller.Model.Trim() == "CSNET MANAGER 2 T10" || controller.Model.Trim() == "CSNET MANAGER 2 T15") { level = 1; } else if (controller.Model.Trim() == "HC-A64NET" || controller.Model.Trim() == "PSC-A160WEB1") { level = 2; } else { level = 3; } for (int n = 0; n < controller.Quantity; n++) { JCHVRF.Model.NextGen.WiringNodeCentralControl wiringController = new JCHVRF.Model.NextGen.WiringNodeCentralControl(); wiringController.Controller = controller; wiringController.Level = level; if (level == 1) { wiringGroup.ControllerListLevel1.Add(wiringController); } else if (level == 2) { wiringGroup.ControllerListLevel2.Add(wiringController); } else { wiringGroup.ControllerListOthers.Add(wiringController); } } } } foreach (JCHVRF.Model.NextGen.SystemVRF systemVRF in Project.CurrentProject.SystemListNextGen) { if (systemVRF.ControlGroupID != null) { if (systemVRF.ControlGroupID.Contains(controlGroup.Id)) { atleast_1system = true; if (systemVRF.SystemStatus == SystemStatus.VALID) { JCHVRF.Model.NextGen.WiringNodeCentralControl wiringVrf = new JCHVRF.Model.NextGen.WiringNodeCentralControl(); wiringVrf.SystemItem = systemVRF; wiringGroup.SystemList.Add(wiringVrf); if (controlSys.SystemStatus != SystemStatus.VALID) { controlSys.SystemStatus = SystemStatus.WIP; } } else { systemVRF.ControlGroupID.Remove(controlGroup.Id); controlSys.SystemsOnCanvasList.RemoveAll(item => item.System.Equals(systemVRF)); } } } } foreach (RoomIndoor exchanger in Project.CurrentProject.ExchangerList) { if (exchanger.ControlGroupID != null) { if (exchanger.ControlGroupID.Contains(controlGroup.Id)) { if (thisProject.HeatExchangerSystems.Find(he => he.Id == exchanger.SystemID).SystemStatus == SystemStatus.VALID) { JCHVRF.Model.NextGen.WiringNodeCentralControl wiringExchanger = new JCHVRF.Model.NextGen.WiringNodeCentralControl(); wiringExchanger.RoomIndoorItem = exchanger; wiringGroup.SystemList.Add(wiringExchanger); if (controlSys.SystemStatus != SystemStatus.VALID) { controlSys.SystemStatus = SystemStatus.WIP; } } else { exchanger.ControlGroupID.Remove(controlGroup.Id); controlSys.SystemsOnCanvasList.RemoveAll(item => item.System.Equals(exchanger)); } } } } if (wiringGroup.SystemList.Count <= 0) { controlSys.IsValid = false; ErrorLog.LogError(Model.ErrorType.Error, Model.ErrorCategory.WiringError, "No System Selected"); } return(wiringGroup); }
private void btnOK_Click(object sender, EventArgs e) { try { int side = ColorSide == PolygonSides.FrontSide?0:1; switch (tabSelector.SelectedIndex) { case 0: #region Сферический градиент { float dist = 0; float sphR = (float)(this.NudR.Value); float sphInR = (float)(this.NudRin.Value); float delta = 0; Point3D sphC = new Point3D((float)this.NudX.Value, (float)this.NudY.Value, (float)this.NudZ.Value); if ((sphR < 1) | (sphInR < 0) | (sphInR >= sphR)) { break; } for (int i = 0; i < PaintModel.Polygon.Length; i++) { dist = Engine3D.GetDistance(sphC, PaintModel.Polygon[i].Center); if (dist > sphR) { if (!checkOutColor.Checked) { continue; } delta = 1; } else if (dist < sphInR) { if (!checkInColor.Checked) { continue; } delta = 0; } else { delta = (dist - sphInR) / (sphR - sphInR); } if (PaintModel.SetColor(Color.FromArgb((int)Math.Round(PaintModel.Polygon[i].color[side].A * (1 - (float)this.trackTotalOpacity.Value / 100) + ((float)this.trackTotalOpacity.Value / 100) * 2.55 * (this.trackOpacityIn.Value + (this.trackOpacityOut.Value - this.trackOpacityIn.Value) * delta)), (int)Math.Round(PaintModel.Polygon[i].color[side].R * (1 - (float)this.trackTotalOpacity.Value / 100) + ((float)this.trackTotalOpacity.Value / 100) * (this.panelColorIn.BackColor.R + (this.panelColorOut.BackColor.R - this.panelColorIn.BackColor.R) * delta)), (int)Math.Round(PaintModel.Polygon[i].color[side].G * (1 - (float)this.trackTotalOpacity.Value / 100) + ((float)this.trackTotalOpacity.Value / 100) * (this.panelColorIn.BackColor.G + (this.panelColorOut.BackColor.G - this.panelColorIn.BackColor.G) * delta)), (int)Math.Round(PaintModel.Polygon[i].color[side].B * (1 - (float)this.trackTotalOpacity.Value / 100) + ((float)this.trackTotalOpacity.Value / 100) * (this.panelColorIn.BackColor.B + (this.panelColorOut.BackColor.B - this.panelColorIn.BackColor.B) * delta))), i, i, ColorSide) != 0) { throw new Exception(ErrorLog.GetLastError()); } } } #endregion break; case 1: #region Уровневый градиент { float dist = 0; float bottomY = (float)nudLevelBottom.Value; float topY = (float)nudLevelTop.Value; float delta = 0; float dY = topY - bottomY; if (dY <= 0) { break; } for (int i = 0; i < PaintModel.Polygon.Length; i++) { dist = PaintModel.Polygon[i].Center.Y - bottomY; if (dist > dY) { if (!checkLevelTop.Checked) { continue; } delta = 1; } else if (dist < 0) { if (!checkLevelBottom.Checked) { continue; } delta = 0; } else { delta = dist / dY; } if (PaintModel.SetColor(Color.FromArgb((int)Math.Round(PaintModel.Polygon[i].color[side].A * (1 - (float)this.trackLevelTotal.Value / 100) + ((float)this.trackLevelTotal.Value / 100) * 2.55 * (this.trackLevelBottom.Value + (this.trackLevelTop.Value - this.trackLevelBottom.Value) * delta)), (int)Math.Round(PaintModel.Polygon[i].color[side].R * (1 - (float)this.trackLevelTotal.Value / 100) + ((float)this.trackLevelTotal.Value / 100) * (this.panelLevelBottom.BackColor.R + (this.panelLevelTop.BackColor.R - this.panelLevelBottom.BackColor.R) * delta)), (int)Math.Round(PaintModel.Polygon[i].color[side].G * (1 - (float)this.trackLevelTotal.Value / 100) + ((float)this.trackLevelTotal.Value / 100) * (this.panelLevelBottom.BackColor.G + (this.panelLevelTop.BackColor.G - this.panelLevelBottom.BackColor.G) * delta)), (int)Math.Round(PaintModel.Polygon[i].color[side].B * (1 - (float)this.trackLevelTotal.Value / 100) + ((float)this.trackLevelTotal.Value / 100) * (this.panelLevelBottom.BackColor.B + (this.panelLevelTop.BackColor.B - this.panelLevelBottom.BackColor.B) * delta))), i, i, ColorSide) != 0) { throw new Exception(ErrorLog.GetLastError()); } } } #endregion break; case 2: #region Смещение цвета { Color tmpColor = new Color(); for (int i = 0; i < PaintModel.Polygon.Length; i++) { tmpColor = Color.FromArgb(PaintModel.Polygon[i].color[side].ToArgb()); PaintModel.Polygon[i].color[side] = Color.FromArgb(tmpColor.A, Math.Min(255, (int)Math.Round((tmpColor.R * nudRR.Value + tmpColor.G * nudRG.Value + tmpColor.B * nudRB.Value) / 100)), Math.Min(255, (int)Math.Round((tmpColor.R * nudGR.Value + tmpColor.G * nudGG.Value + tmpColor.B * nudGB.Value) / 100)), Math.Min(255, (int)Math.Round((tmpColor.R * nudBR.Value + tmpColor.G * nudBG.Value + tmpColor.B * nudBB.Value) / 100))); } } #endregion break; } dlgResult = DialogResult.OK; this.Close(); } catch (Exception er) { MessageBox.Show("btnOK_Click\nОшибка: " + er.Message); dlgResult = DialogResult.Abort; } }
public void SendPeopleEmail(int queueid, bool onlyProspects = false) { var emailqueue = EmailQueues.Single(ee => ee.Id == queueid); var from = Util.FirstAddress(emailqueue.FromAddr, emailqueue.FromName); if (!emailqueue.Subject.HasValue() || !emailqueue.Body.HasValue()) { SendEmail(from, $"sent emails - error(emailid={emailqueue.Id})", "no subject or body, no emails sent", Util.ToMailAddressList(from), emailqueue.Id); return; } var body = DoClickTracking(emailqueue); var m = new EmailReplacements(this, body, from, queueid); emailqueue.Started = Util.Now; SubmitChanges(); var cc = Util.ToMailAddressList(emailqueue.CClist); if (emailqueue.SendFromOrgId.HasValue) { if (!onlyProspects) { var q2 = from om in OrganizationMembers where om.OrganizationId == emailqueue.SendFromOrgId where om.MemberTypeId != MemberTypeCode.InActive where om.MemberTypeId != MemberTypeCode.Prospect where (om.Pending ?? false) == false let p = om.Person where p.EmailAddress != null where p.EmailAddress != "" where (p.SendEmailAddress1 ?? true) || (p.SendEmailAddress2 ?? false) where p.EmailOptOuts.All(oo => oo.FromEmail != emailqueue.FromAddr) select om.PeopleId; foreach (var pid in q2) { // Protect against duplicate PeopleIDs ending up in the queue if (emailqueue.EmailQueueTos.Any(pp => pp.PeopleId == pid)) { continue; } emailqueue.EmailQueueTos.Add(new EmailQueueTo { PeopleId = pid, OrgId = emailqueue.SendFromOrgId, Guid = Guid.NewGuid(), }); } SubmitChanges(); } } var queue = from t in EmailQueueTos where t.Id == emailqueue.Id where t.Sent == null orderby t.PeopleId select t; foreach (var queueTo in queue) { try { if (m.OptOuts != null && m.OptOuts.Any(vv => vv.PeopleId == queueTo.PeopleId && vv.OptOutX == true)) { continue; } var text = m.DoReplacements(queueTo.PeopleId, queueTo); var aa = m.ListAddresses; if (Setting("sendemail", true)) { SendEmail(from, emailqueue.Subject, text, aa, queueTo, cc); queueTo.Sent = Util.Now; SubmitChanges(); } } catch (Exception ex) { var subject = $"sent emails - error:(emailid={emailqueue.Id}) {CmsHost}"; ErrorLog.GetDefault(null).Log(new Error(new Exception(subject, ex))); SendEmail(from, subject, $"{ex.Message}\n{ex.StackTrace}", Util.ToMailAddressList(from), queueTo); } } // Handle CC MailAddresses. These do not get DoReplacement support. if (cc.Count > 0) { foreach (var ma in cc) { try { if (Setting("sendemail", "true") != "false") { List <MailAddress> mal = new List <MailAddress> { ma }; SendEmail(from, emailqueue.Subject, body, mal, emailqueue.Id, cc: cc); } } catch (Exception ex) { var subject = $"sent emails - error:(emailid={emailqueue.Id}) {CmsHost}"; ErrorLog.GetDefault(null).Log(new Error(new Exception(subject, ex))); SendEmail(from, subject, ex.Message, Util.ToMailAddressList(from)); } } } emailqueue.Sent = Util.Now; if (emailqueue.Redacted ?? false) { emailqueue.Body = "redacted"; } else if (emailqueue.Transactional == false) { var nitems = emailqueue.EmailQueueTos.Count(); if (cc.Count > 0) { nitems += cc.Count; } if (nitems > 1) { NotifySentEmails(from.Address, from.DisplayName, emailqueue.Subject, nitems, emailqueue.Id); } } SubmitChanges(); }
public static List <string> GetItemStringsRevised(TournamentGame tournamentGame, List <ItemObject.ItemTypeEnum> validTypes) { int prizeMin = MathF.Floor(TournamentPrizePoolBehavior.GetMinPrizeValue() * .7f); int prizeMax = MathF.Ceiling(TournamentPrizePoolBehavior.GetMaxPrizeValue() * 1.5f); List <string> allitems = new List <string>(); if (TournamentXPSettings.Instance.PrizeListIncludeLegacy) { var legacyItems = _legacyItems.AsEnumerable(); if (TournamentXPSettings.Instance.PrizeFilterCultureLegacyItems) { legacyItems = legacyItems.Where(x => x.Culture == tournamentGame.Town.Culture); } if (TournamentXPSettings.Instance.PrizeFilterValueLegacyItems) { legacyItems = legacyItems.Where(x => x.Value >= prizeMin && x.Value <= prizeMax); } if (TournamentXPSettings.Instance.PrizeFilterItemTypesLegacyItems) { legacyItems = legacyItems.Where(x => validTypes.Contains(x.ItemType)); } allitems = allitems.Concat(legacyItems.Select(x => x.StringId)).ToList(); } if (TournamentXPSettings.Instance.PrizeListIncludeCustom && TournamentPrizePoolBehavior.CustomTournamentItems != null && TournamentPrizePoolBehavior.CustomTournamentItems.Count > 0) { try { var customItems = _customItems.AsEnumerable(); if (TournamentXPSettings.Instance.PrizeFilterCultureCustomItems) { customItems = customItems.Where(x => x.Culture == tournamentGame.Town.Culture); } if (TournamentXPSettings.Instance.PrizeFilterValueCustomItems) { customItems = customItems.Where(x => x.Value >= prizeMin && x.Value <= prizeMax); } if (TournamentXPSettings.Instance.PrizeFilterItemTypesCustomItems) { customItems = customItems.Where(x => validTypes.Contains(x.ItemType)); } allitems = allitems.Concat(customItems.Select(x => x.StringId).ToList()).ToList(); } catch (Exception ex) { ErrorLog.Log("Error adding custom items to prize pool."); ErrorLog.Log(ex.ToStringFull()); } } if (TournamentXPSettings.Instance.PrizeListIncludeTown) { var roster = tournamentGame.Town.Owner.ItemRoster; roster.RemoveZeroCounts(); var townItems = roster.Where(x => x.Amount > 0 && !x.EquipmentElement.Item.NotMerchandise).Select(x => x.EquipmentElement.Item); if (TournamentXPSettings.Instance.PrizeFilterCultureTownItems) { townItems = townItems.Where(x => x.Culture == tournamentGame.Town.Culture); } if (TournamentXPSettings.Instance.PrizeFilterValueTownItems) { townItems = townItems.Where(x => x.Value >= prizeMin && x.Value <= prizeMax); } if (TournamentXPSettings.Instance.PrizeFilterItemTypesTownItems) { townItems = townItems.Where(x => validTypes.Contains(x.ItemType)); } allitems = allitems.Concat(townItems.Select(x => x.StringId)).ToList(); } if (TournamentXPSettings.Instance.PrizeListIncludeVanilla) { var vanillaItems = ItemObject.All.AsEnumerable(); if (TournamentXPSettings.Instance.PrizeFilterCultureStandardItems) { vanillaItems = vanillaItems.Where(x => x.Culture == tournamentGame.Town.Culture); } if (TournamentXPSettings.Instance.PrizeFilterValueStandardItems) { vanillaItems = vanillaItems.Where(x => x.Value >= prizeMin && x.Value <= prizeMax); } if (TournamentXPSettings.Instance.PrizeFilterItemTypesStandardItems) { vanillaItems = vanillaItems.Where(x => validTypes.Contains(x.ItemType)); } allitems = allitems.Concat(vanillaItems.Select(x => x.StringId)).ToList(); } if (allitems.Count == 0) { //Alert - fix it somehow } return(allitems); }
//Check if refresh token file exists and consume if it does public void Initialize() { try { refreshTokenFilePath = string.Format(@"\user\{0}\", Directory.GetApplicationDirectory().Replace("/", "\\").Split('\\')[2]); if (File.Exists(refreshTokenFilePath + refreshTokenFileName)) { using (StreamReader reader = new StreamReader(File.OpenRead(refreshTokenFilePath + refreshTokenFileName))) { refreshToken = reader.ReadToEnd().Replace("\r\n", string.Empty); } if (refreshToken.Length > 0) { UseRefreshToken(null); } else { if (onErrorMessage != null) { onErrorMessage("Stored refresh token file is empty, please delete file and use authorization code"); } } } else { if (AuthCode.Length > 0) { GetTokenAndRefreshToken(); } else { if (onErrorMessage != null) { onErrorMessage("Authorization code cannot be empty on the first query to the Google API service, please set authorization code"); } } } if (Token.Length > 0) { Initialized = true; if (onIsInitialized != null) { onIsInitialized(1); } GetDevices(); } else { Initialized = false; if (onIsInitialized != null) { onIsInitialized(0); } } } catch (Exception e) { Initialized = false; if (onIsInitialized != null) { onIsInitialized(0); } ErrorLog.Exception("Exception ocurred in Initialize", e); } }
bool isSkip = true; //ProgressDialogIndeterminate 回傳值 略過 private void Button_AutoImport_Click(object sender, RoutedEventArgs e) { if (btnAutoImport.IsChecked == true) { if (PathCheck.IsPathExist(Agencys.Agency_ImagePath) && PathCheck.IsPathExist(Agencys.Agency_WifiCardPath)) { bool isEverChanged = false; ProgressDialogIndeterminate progressDialogIndeterminate = new ProgressDialogIndeterminate(); progressDialogIndeterminate.Dispatcher.Invoke(() => { progressDialogIndeterminate.PText = "圖片偵測中"; progressDialogIndeterminate.PIsIndeterminate = true; progressDialogIndeterminate.ButtonContent = "跳過"; progressDialogIndeterminate.ReturnValueCallback += new ProgressDialogIndeterminate.ReturnValueDelegate(SetReturnValueCallbackFun); progressDialogIndeterminate.Show(); }); Registrations registrations = new Registrations(); Task t = Task.Factory.StartNew(() => { using (var ide = new iDentalEntities()) { CreateBitmapImage createBitmapImage = new CreateBitmapImage(); ObservableCollection <Templates_Images> Templates_ImagesCollect = tableTemplates_Images.QueryTemplatesImagesImportDateAndReturnFullImagePath(Agencys, Patients, SelectedTemplate, functionTemplateViewModel.SelectedDate); //default Image[i] in UserControl Templates int Imagei = 0; //載入樣板設定 int ImageCount = (int)SelectedTemplate.Template_ImageCount; int DecodePixelWidth = (int)SelectedTemplate.Template_DecodePixelWidth; while (Imagei < ImageCount) { progressDialogIndeterminate.Dispatcher.Invoke(() => { progressDialogIndeterminate.PText = "圖片 " + (Imagei + 1) + " 偵測中"; }); //目前處理的Image[i] Image iTarget; TemplateContent.Dispatcher.Invoke(() => { iTarget = new Image(); iTarget = (Image)TemplateContent.FindName("Image" + Imagei); //更換目標圖 //iTarget.Source = new BitmapImage(new Uri(@"/DigiDental;component/Resource/yes.png", UriKind.RelativeOrAbsolute)); }); //set the paramater default bool isChanged = false; bool detecting = true; while (true) { //開始偵測wifi card路徑 foreach (string f in Directory.GetFiles(Agencys.Agency_WifiCardPath)) { Thread.Sleep(1000); //設定病患資料夾 PatientImageFolderInfo patientImageFolderInfo = PatientFolderSetting.PatientImageFolderSetting(Agencys, Patients.Patient_ID, RegistrationDate); //檢查是否存在,不存在就新增 PathCheck.CheckPathAndCreate(patientImageFolderInfo.PatientImageFullPath); string extension = Path.GetExtension(f).ToUpper(); string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff"); string imageFileName = newFileName + extension; //判斷圖片是否為正 //不是,旋轉後儲存 //是,直接File.Copy ImageHelper.RotateImageByExifOrientationData(f, patientImageFolderInfo.PatientImageFullPath + @"\" + newFileName + extension, extension, true); var queryRegistrations = from r in ide.Registrations where r.Patient_ID == Patients.Patient_ID && r.Registration_Date == RegistrationDate.Date select r; if (queryRegistrations.Count() > 0) { registrations = queryRegistrations.First(); } else { registrations.Patient_ID = Patients.Patient_ID; registrations.Registration_Date = RegistrationDate.Date; ide.Registrations.Add(registrations); //寫入Registrations ide.SaveChanges(); } Images images = new Images() { Image_Path = patientImageFolderInfo.PatientImagePath + @"\" + imageFileName, Image_FileName = imageFileName, Image_Extension = extension }; registrations.Images.Add(images); ide.SaveChanges(); //複製完如果刪除發生問題 //嘗試五次每次間隔3秒 int deleteTime = 0; while (deleteTime < 5) { Thread.Sleep(3000); try { File.Delete(f); deleteTime = 5; } catch (Exception ex) { deleteTime++; if (deleteTime == 5) { if (MessageBox.Show("影像搬移中出現問題", "錯誤", MessageBoxButton.OK, MessageBoxImage.Error) == MessageBoxResult.OK) { isStop = true; ErrorLog.ErrorMessageOutput(ex.ToString()); } } } } TemplateContent.Dispatcher.Invoke(() => { //INSERT TemplateImages //寫入資料庫再帶回畫面 string ImageUID = string.Empty; ImageUID = tableTemplates_Images.InsertOrUpdateTemplatesImages(Patients, functionTemplateViewModel.SelectedTemplate, functionTemplateViewModel.SelectedDate, images.Image_ID, images.Image_Path, Imagei.ToString()); iTarget = new Image(); iTarget = (Image)TemplateContent.FindName("Image" + Imagei); iTarget.Uid = ImageUID; iTarget.Source = createBitmapImage.BitmapImageShow(patientImageFolderInfo.PatientImageFullPath + @"\" + imageFileName, DecodePixelWidth); isChanged = true; }); isEverChanged = true; //代表以處理完結束這回合的偵測 detecting = false; } //ProcessingDialog STOP //停止 if (isStop) { isStop = false; TemplateContent.Dispatcher.Invoke(() => { iTarget = new Image(); iTarget = (Image)TemplateContent.FindName("Image" + Imagei); var findOriImage = from tc in Templates_ImagesCollect where tc.Template_Image_Number == Imagei.ToString() select tc; if (findOriImage.Count() > 0) { iTarget.Source = createBitmapImage.BitmapImageShow(findOriImage.First().Image_Path, DecodePixelWidth); } else { //iTarget.Source = new BitmapImage(new Uri(@"/DigiDental;component/Resource/no.png", UriKind.RelativeOrAbsolute)); } }); return; } else { // import pic OR skip import (NEXT) // 匯入之後接下一張,或是按了跳過 if (!detecting || !isSkip) { if (!isChanged) { TemplateContent.Dispatcher.Invoke(() => { iTarget = new Image(); iTarget = (Image)TemplateContent.FindName("Image" + Imagei); var findOriImage = from tc in Templates_ImagesCollect where tc.Template_Image_Number == Imagei.ToString() select tc; if (findOriImage.Count() > 0) { iTarget.Source = createBitmapImage.BitmapImageShow(findOriImage.First().Image_Path, DecodePixelWidth); } else { //iTarget.Source = new BitmapImage(new Uri(@"/DigiDental;component/Resource/no.png", UriKind.RelativeOrAbsolute)); } }); } Imagei++; isSkip = true; break; } } } } } }).ContinueWith(cw => { //結束 progressDialogIndeterminate.Dispatcher.Invoke(() => { progressDialogIndeterminate.PText = "處理完畢"; progressDialogIndeterminate.Close(); }); //委派回傳MainWindow //刷新Registrations 資料 //刷新Images 資料 if (isEverChanged) { ReturnValueCallback(registrations.Registration_Date); } GC.Collect(); btnAutoImport.IsChecked = false; }, TaskScheduler.FromCurrentSynchronizationContext()); } else { MessageBox.Show("影像路徑或Wifi Card路徑有問題,請至<設定>檢查是否有誤", "提示", MessageBoxButton.OK, MessageBoxImage.Warning); } } }
public void SaveDataToExcel() { Microsoft.Office.Interop.Excel.Application app = null; try { string log = Program.infoResource.GetLocalizedString(language.InfoId.DriveGraphData); app = new Microsoft.Office.Interop.Excel.Application(); if (app == null) { XtraMessageBox.Show(Program.infoResource.GetLocalizedString(language.InfoId.NoOffice)); return; } // app.Visible = false; //开启等待窗口 SplashScreenManager.ShowForm(this.ParentForm, typeof(wfMain), false, true); //创建Excel中的工作薄 Workbook wb = (Workbook)app.Workbooks.Add(Missing.Value); //创建Excel工作薄中的第一页 sheet Worksheet sheet = (Worksheet)wb.ActiveSheet; sheet.Name = "紫外设备"; sheet.Cells[1, 1] = "紫外"; sheet.Cells[2, 1] = "紫外背景光谱"; sheet.Cells[2, 2] = "遥测光谱"; sheet.Cells[2, 3] = "NO吸光度"; sheet.Cells[2, 4] = "HC吸光度"; sheet.Cells[2, 5] = "遥测吸光度"; //合并A1-G1,A1-G2标题居中,字号调整,字体调整 sheet.Range["A1", "E1"].Merge(); sheet.Range["A1", "E1"].ColumnWidth = 17; Range rg = sheet.Range["A1", "E2"]; rg.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; rg.Font.Size = 14; rg.Font.Name = "宋体"; //导入数据 if (ResultDataViewModel.VM.ExhaustDetailData.UVSCalParam != null) { DriveDataToSheet(sheet, ResultDataViewModel.VM.ExhaustDetailData.UVSCalParam.ZeroIntensity, 1); } DriveDataToSheet(sheet, ResultDataViewModel.VM.ExhaustDetailData.UVSData, 2); if (ResultDataViewModel.VM.ExhaustDetailData.UVSNOCalParam != null) { DriveDataToSheet(sheet, ResultDataViewModel.VM.ExhaustDetailData.UVSNOCalParam.Absorb, 3); } if (ResultDataViewModel.VM.ExhaustDetailData.UVSHCCalParam != null) { DriveDataToSheet(sheet, ResultDataViewModel.VM.ExhaustDetailData.UVSHCCalParam.Absorb, 4); } DriveDataToSheet(sheet, ResultDataViewModel.VM.ExhaustDetailData.AbsorbData, 5); Worksheet wsRed = (Worksheet)wb.Sheets.Add(Missing.Value, sheet, Missing.Value, Missing.Value); wsRed.Name = "红外设备"; wsRed.Cells[1, 1] = "红外"; wsRed.Cells[2, 1] = "红外背景光谱"; wsRed.Cells[2, 2] = "CO谐波"; wsRed.Cells[2, 3] = "CO2谐波"; wsRed.Cells[2, 4] = "红外背景谐波"; wsRed.Cells[2, 5] = "遥测谐波"; //合并A1-G1 wsRed.Range["A1", "E1"].Merge(); wsRed.Range["A1", "E1"].ColumnWidth = 17; //A1-G2标题居中,字号调整,字体调整 Range rg2 = wsRed.Range["A1", "E2"]; rg2.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; rg2.Font.Size = 14; rg2.Font.Name = "宋体"; //导入数据 if (ResultDataViewModel.VM.ExhaustDetailData.TDLASCalParam != null) { DriveDataToSheet(wsRed, ResultDataViewModel.VM.ExhaustDetailData.TDLASCalParam.ZeroIntensity, 1); } if (ResultDataViewModel.VM.ExhaustDetailData.TDLASCOCalParam != null) { DriveDataToSheet(wsRed, ResultDataViewModel.VM.ExhaustDetailData.TDLASCOCalParam.Harm, 2); } if (ResultDataViewModel.VM.ExhaustDetailData.TDLASCO2CalParam != null) { DriveDataToSheet(wsRed, ResultDataViewModel.VM.ExhaustDetailData.TDLASCO2CalParam.Harm, 3); } if (ResultDataViewModel.VM.ExhaustDetailData.TDLASCalParam != null) { DriveDataToSheet(wsRed, ResultDataViewModel.VM.ExhaustDetailData.TDLASCalParam.Harm, 4); } DriveDataToSheet(wsRed, ResultDataViewModel.VM.ExhaustDetailData.HarmData, 5); //保存工作表,退出 SplashScreenManager.CloseForm(); dlgSave.ShowDialog(); if (!String.IsNullOrEmpty(dlgSave.FileName)) { app.ActiveWorkbook.SaveAs(dlgSave.FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); log += Program.infoResource.GetLocalizedString(language.InfoId.OpearteSuccess); ErrorLog.SystemLog(DateTime.Now, log); } //else // XtraMessageBox.Show(Program.infoResource.GetLocalizedString(language.InfoId.OperateFail)); //app.Save(); app.Quit(); } catch (Exception ex) { //XtraMessageBox.Show(ex.Message+" "+ex.TargetSite.ToString()); // XtraMessageBox.Show(Program.infoResource.GetLocalizedString(language.InfoId.OperateFail)); if (app != null) { app.Quit(); } ErrorLog.Error(ex.ToString()); } }
// effects: Add the set of errors in errorLog to this internal void AddErrors(ErrorLog errorLog) { m_errorLog.Merge(errorLog); }
internal ViewGenResults() { m_views = new KeyToListMap <EntitySetBase, GeneratedView>(EqualityComparer <EntitySetBase> .Default); m_errorLog = new ErrorLog(); }
public async Task <ActionResult> LtiSlide(string courseId, Guid slideId) { if (string.IsNullOrWhiteSpace(courseId)) { return(RedirectToAction("Index", "Home")); } var course = courseManager.GetCourse(courseId); var slide = course.GetSlideById(slideId); string userId; var owinRequest = Request.GetOwinContext().Request; if (await owinRequest.IsAuthenticatedLtiRequestAsync()) { var ltiRequest = await owinRequest.ParseLtiRequestAsync(); log.Info($"Нашёл LTI request в запросе: {ltiRequest.JsonSerialize()}"); userId = Request.GetOwinContext().Authentication.AuthenticationResponseGrant.Identity.GetUserId(); await ltiRequestsRepo.Update(courseId, userId, slide.Id, ltiRequest.JsonSerialize()); /* Substitute http(s) scheme with real scheme from header */ var uriBuilder = new UriBuilder(ltiRequest.Url) { Scheme = owinRequest.GetRealRequestScheme(), Port = owinRequest.GetRealRequestPort() }; return(Redirect(uriBuilder.Uri.AbsoluteUri)); } /* For now user should be authenticated */ if (!User.Identity.IsAuthenticated) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden)); } userId = User.Identity.GetUserId(); var visit = await VisitSlide(courseId, slide.Id, userId); /* Try to send score via LTI immediately after slide visiting */ try { if (visit.IsPassed) { LtiUtils.SubmitScore(courseId, slide, userId, visit); } } catch (Exception e) { ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(new Error(e)); } var exerciseSlide = slide as ExerciseSlide; if (exerciseSlide != null) { var model = new CodeModel { CourseId = courseId, SlideId = exerciseSlide.Id, ExerciseBlock = exerciseSlide.Exercise, Context = CreateRenderContext(course, exerciseSlide, isLti: true) }; return(View("LtiExerciseSlide", model)); } var quizSlide = slide as QuizSlide; if (quizSlide != null) { var model = new LtiQuizModel { CourseId = courseId, Slide = quizSlide, UserId = userId }; return(View("LtiQuizSlide", model)); } return(View()); }
public static BNetCharacterDetails GetCharacterDetails(string region, string server, string name) { BNetCharacterDetails dets = null; string token = GetClientCredentials(region); string apiUrl = string.Format("{0}/wow/character/{1}/{2}?fields=achievements%2Cquests&access_token={3}", Config.DataApiBaseUrl(region), Uri.EscapeDataString(server), Uri.EscapeDataString(name), token); string apiResponse = GetApiResponse(apiUrl); if (!string.IsNullOrWhiteSpace(apiResponse)) { try { JObject detObject = JObject.Parse(apiResponse); dets = new BNetCharacterDetails(); dets.Class = GameData.GetClassNameForId((int)detObject["class"]); dets.Race = GameData.GetRaceNameForId((int)detObject["race"]); dets.Level = (int)detObject["level"]; dets.Name = (string)detObject["name"]; dets.Realm = (string)detObject["realm"]; dets.Faction = GameData.GetFactionForRaceId((int)detObject["race"]); dets.ThumbnailPath = (string)detObject["thumbnail"]; dets.Region = region; int achieveCount = detObject["achievements"]["achievementsCompleted"].Count(); List <CharacterAchiev> lmAchievs = new List <CharacterAchiev>(); for (int i = 0; i < achieveCount; i++) { int aId = (int)detObject["achievements"]["achievementsCompleted"][i]; if (GameData.Loremaster.AllAchievementIds.Contains(aId)) { lmAchievs.Add(new CharacterAchiev() { Id = aId, Timestamp = (long)detObject["achievements"]["achievementsCompletedTimestamp"][i] }); } } dets.Achievements = lmAchievs.ToArray(); Dictionary <int, int> zoneProgress = new Dictionary <int, int>(); foreach (int questId in detObject["quests"]) { int zoneId; if (GameData.TryGetQuestZone(questId, out zoneId)) { if (zoneProgress.ContainsKey(zoneId)) { zoneProgress[zoneId]++; } else { zoneProgress.Add(zoneId, 1); } } } dets.ZoneProgress = zoneProgress; } catch (Exception ex) { dets = null; var context = System.Web.HttpContext.Current; ErrorLog.GetDefault(context).Log(new Error(ex, context)); } } return(dets); }
// effects: Checks that this foreign key constraints for all the // tables are being ensured on the C-side as well. If not, adds // errors to the errorLog internal void CheckConstraint( Set <Cell> cells, QueryRewriter childRewriter, QueryRewriter parentRewriter, ErrorLog errorLog, ConfigViewGenerator config) { if (IsConstraintRelevantForCells(cells) == false) { // if the constraint does not deal with any cell in this group, ignore it return; } if (config.IsNormalTracing) { Trace.WriteLine(String.Empty); Trace.WriteLine(String.Empty); Trace.Write("Checking: "); Trace.WriteLine(this); } if (childRewriter == null && parentRewriter == null) { // Neither table is mapped - so we are fine return; } // If the child table has not been mapped, we used to say that we // are fine. However, if we have SPerson(pid) and SAddress(aid, // pid), where pid is an FK into SPerson, we are in trouble if // SAddress is not mapped - SPerson could get deleted. So we // check for it as well // if the parent table is not mapped, we also have a problem if (childRewriter == null) { var message = Strings.ViewGen_Foreign_Key_Missing_Table_Mapping( ToUserString(), ChildTable.Name); // Get the cells from the parent table var record = new ErrorLog.Record( ViewGenErrorCode.ForeignKeyMissingTableMapping, message, parentRewriter.UsedCells, String.Empty); errorLog.AddEntry(record); return; } if (parentRewriter == null) { var message = Strings.ViewGen_Foreign_Key_Missing_Table_Mapping( ToUserString(), ParentTable.Name); // Get the cells from the child table var record = new ErrorLog.Record( ViewGenErrorCode.ForeignKeyMissingTableMapping, message, childRewriter.UsedCells, String.Empty); errorLog.AddEntry(record); return; } // Note: we do not check if the parent columns correspond to the // table's keys - metadata checks for that //First check if the FK is covered by Foreign Key Association //If we find this, we don't need to check for independent associations. If user maps the Fk to both FK and independent associations, //the regular round tripping validation will catch the error. if (CheckIfConstraintMappedToForeignKeyAssociation(childRewriter, parentRewriter, cells)) { return; } // Check if the foreign key in the child table corresponds to the primary key, i.e., if // the foreign key (e.g., pid, pid2) is a superset of the actual key members (e.g., pid), it means // that the foreign key is also the primary key for this table -- so we can propagate the queries upto C-Space // rather than doing the cell check var initialErrorLogSize = errorLog.Count; if (IsForeignKeySuperSetOfPrimaryKeyInChildTable()) { GuaranteeForeignKeyConstraintInCSpace(childRewriter, parentRewriter, errorLog); } else { GuaranteeMappedRelationshipForForeignKey(childRewriter, parentRewriter, cells, errorLog, config); } if (initialErrorLogSize == errorLog.Count) { // Check if the order of columns in foreign key correponds to the // mappings in m_cellGroup, e.g., if <pid1, pid2> in SAddress is // a foreign key into <pid1, pid2> of the SPerson table, make // sure that this order is preserved through the mappings in m_cellGroup CheckForeignKeyColumnOrder(cells, errorLog); } }
//Use authorization code to retrieve a refresh token and a session token private void GetTokenAndRefreshToken() { try { using (HttpsClient client = new HttpsClient()) { client.TimeoutEnabled = true; client.Timeout = 10; client.HostVerification = false; client.PeerVerification = false; client.AllowAutoRedirect = false; client.IncludeHeaders = false; HttpsClientRequest request = new HttpsClientRequest(); request.Url.Parse("https://www.googleapis.com/oauth2/v4/token?client_id=" + ClientID + "&code=" + AuthCode + "&grant_type=authorization_code&redirect_uri=https://www.google.com&client_secret=" + ClientSecret); request.RequestType = RequestType.Post; HttpsClientResponse response = client.Dispatch(request); // CrestronConsole.PrintLine("GetTokenAndRefreshToken : " + response.ContentString); if (response.ContentString != null) { if (response.ContentString.Length > 0) { char[] charsToTrim = { '"' }; JObject body = JObject.Parse(response.ContentString); if (body["expires_in"] != null) { var seconds = Convert.ToInt16(body["expires_in"].ToString().Replace("\"", string.Empty)) - 10; var milliseconds = seconds * 1000; refreshTimer = new CTimer(UseRefreshToken, milliseconds); } if (body["access_token"] != null) { Token = body["access_token"].ToString().Replace("\"", string.Empty); } if (body["token_type"] != null) { TokenType = body["token_type"].ToString().Replace("\"", string.Empty); } if (body["refresh_token"] != null) { refreshToken = body["refresh_token"].ToString().Replace("\"", string.Empty); using (StreamWriter writer = new StreamWriter(File.Create(refreshTokenFilePath + refreshTokenFileName))) { writer.WriteLine(refreshToken); } } } } } } catch (Exception e) { ErrorLog.Exception("Exception ocurred in GetTokenAndRefreshToken", e); } }
// requires: all columns in constraint.ParentColumns and // constraint.ChildColumns must have been mapped in some cell in m_cellGroup // effects: Given the foreign key constraint, checks if the // constraint.ChildColumns are mapped to the constraint.ParentColumns // in m_cellGroup in the right oder. If not, adds an error to m_errorLog and returns // false. Else returns true private bool CheckForeignKeyColumnOrder(Set <Cell> cells, ErrorLog errorLog) { // Go through every cell and find the cells that are relevant to // parent and those that are relevant to child // Then for each cell pair (parent, child) make sure that the // projected foreign keys columns in C-space are aligned var parentCells = new List <Cell>(); var childCells = new List <Cell>(); foreach (var cell in cells) { if (cell.SQuery.Extent.Equals(ChildTable)) { childCells.Add(cell); } if (cell.SQuery.Extent.Equals(ParentTable)) { parentCells.Add(cell); } } // Make sure that all child cells and parent cells align on // the columns, i.e., for each DISTINCT pair C and P, get the columns // on the S-side. Then get the corresponding fields on the // C-side. The fields on the C-side should match var foundParentCell = false; var foundChildCell = false; foreach (var childCell in childCells) { var allChildSlotNums = GetSlotNumsForColumns(childCell, ChildColumns); if (allChildSlotNums.Count == 0) { // slots in present in S-side, ignore continue; } List <MemberPath> childPaths = null; List <MemberPath> parentPaths = null; Cell errorParentCell = null; foreach (var childSlotNums in allChildSlotNums) { foundChildCell = true; // Get the fields on the C-side childPaths = new List <MemberPath>(childSlotNums.Count); foreach (var childSlotNum in childSlotNums) { // Initial slots only have JoinTreeSlots var childSlot = (MemberProjectedSlot)childCell.CQuery.ProjectedSlotAt(childSlotNum); Debug.Assert(childSlot != null); childPaths.Add(childSlot.MemberPath); } foreach (var parentCell in parentCells) { var allParentSlotNums = GetSlotNumsForColumns(parentCell, ParentColumns); if (allParentSlotNums.Count == 0) { // * Parent and child cell are the same - we do not // need to check since we want to check the foreign // key constraint mapping across cells // * Some slots not in present in S-side, ignore continue; } foreach (var parentSlotNums in allParentSlotNums) { foundParentCell = true; parentPaths = new List <MemberPath>(parentSlotNums.Count); foreach (var parentSlotNum in parentSlotNums) { var parentSlot = (MemberProjectedSlot)parentCell.CQuery.ProjectedSlotAt(parentSlotNum); Debug.Assert(parentSlot != null); parentPaths.Add(parentSlot.MemberPath); } // Make sure that the last member of each of these is the same // or the paths are essentially equivalent via referential constraints // We need to check that the last member is essentially the same because it could // be a regular scenario where aid is mapped to PersonAddress and Address - there // is no ref constraint. So when projected into C-Space, we will get Address.aid // and PersonAddress.Address.aid if (childPaths.Count == parentPaths.Count) { var notAllPathsMatched = false; for (var i = 0; i < childPaths.Count && !notAllPathsMatched; i++) { var parentPath = parentPaths[i]; var childPath = childPaths[i]; if (!parentPath.LeafEdmMember.Equals(childPath.LeafEdmMember)) //Child path did not match { if (parentPath.IsEquivalentViaRefConstraint(childPath)) { //Specifying the referential constraint once in the C space should be enough. //This is the only way possible today. //We might be able to derive more knowledge by using boolean logic return(true); } else { notAllPathsMatched = true; } } } if (!notAllPathsMatched) { return(true); //all childPaths matched parentPaths } else { //If not this one, some other Parent Cell may match. errorParentCell = parentCell; } } } } //foreach parentCell } //If execution is at this point, no parent cell's end has matched (otherwise it would have returned true) Debug.Assert(childPaths != null, "child paths should be set"); Debug.Assert(parentPaths != null, "parent paths should be set"); Debug.Assert(errorParentCell != null, "errorParentCell should be set"); var message = Strings.ViewGen_Foreign_Key_ColumnOrder_Incorrect( ToUserString(), MemberPath.PropertiesToUserString(ChildColumns, false), ChildTable.Name, MemberPath.PropertiesToUserString(childPaths, false), childCell.CQuery.Extent.Name, MemberPath.PropertiesToUserString(ParentColumns, false), ParentTable.Name, MemberPath.PropertiesToUserString(parentPaths, false), errorParentCell.CQuery.Extent.Name); var record = new ErrorLog.Record( ViewGenErrorCode.ForeignKeyColumnOrderIncorrect, message, new[] { errorParentCell, childCell }, String.Empty); errorLog.AddEntry(record); return(false); } Debug.Assert(foundParentCell, "Some cell that mapped the parent's key must be present!"); Debug.Assert( foundChildCell == true, "Some cell that mapped the child's foreign key must be present according to the requires clause!"); return(true); }
private bool CheckIfConstraintMappedToForeignKeyAssociation(QueryRewriter childRewriter, QueryRewriter parentRewriter, Set <Cell> cells, ErrorLog errorLog) { ViewgenContext childContext = childRewriter.ViewgenContext; ViewgenContext parentContext = parentRewriter.ViewgenContext; //First collect the sets of properties that the principal and dependant ends of this FK //are mapped to in the Edm side. var childPropertiesSet = new List <Set <EdmProperty> >(); var parentPropertiesSet = new List <Set <EdmProperty> >(); foreach (Cell cell in cells) { if (cell.CQuery.Extent.BuiltInTypeKind != BuiltInTypeKind.AssociationSet) { var childProperties = cell.GetCSlotsForTableColumns(ChildColumns); if ((childProperties != null) && (childProperties.Count != 0)) { childPropertiesSet.Add(childProperties); } var parentProperties = cell.GetCSlotsForTableColumns(ParentColumns); if ((parentProperties != null) && (parentProperties.Count != 0)) { parentPropertiesSet.Add(parentProperties); } } } //Now Check if the properties on the Edm side are connected via an FK relationship. if ((childPropertiesSet.Count != 0) && (parentPropertiesSet.Count != 0)) { var foreignKeyAssociations = childContext.EntityContainerMapping.EdmEntityContainer.BaseEntitySets.OfType <AssociationSet>().Where(it => it.ElementType.IsForeignKey).Select(it => it.ElementType); foreach (AssociationType association in foreignKeyAssociations) { ReferentialConstraint refConstraint = association.ReferentialConstraints.FirstOrDefault(); //We need to check to see if the dependent properties that were mapped from S side are present as //dependant properties of this ref constraint on the Edm side. We need to do the same for principal side but //we can not enforce equality since the order of the properties participating in the constraint on the S side and //C side could be different. This is OK as long as they are mapped appropriately. We also can not use Existance as a sufficient //condition since it will allow invalid mapping where FK columns could have been flipped when mapping to the Edm side. So //we make sure that the index of the properties in the principal and dependant are same on the Edm side even if they are in //different order for ref constraints for Edm and store side. var childRefPropertiesCollection = childPropertiesSet.Where(it => it.SetEquals(new Set <EdmProperty>(refConstraint.ToProperties))); var parentRefPropertiesCollection = parentPropertiesSet.Where(it => it.SetEquals(new Set <EdmProperty>(refConstraint.FromProperties))); if ((childRefPropertiesCollection.Count() != 0 && parentRefPropertiesCollection.Count() != 0)) { foreach (var parentRefProperties in parentRefPropertiesCollection) { var parentIndexes = GetPropertyIndexes(parentRefProperties, refConstraint.FromProperties); foreach (var childRefProperties in childRefPropertiesCollection) { var childIndexes = GetPropertyIndexes(childRefProperties, refConstraint.ToProperties); if (childIndexes.SequenceEqual(parentIndexes)) { return(true); } } } } } } return(false); }
protected override void InitializeBindings() { try { // RefreshChartInfo(index); mvvmContext1.SetViewModel(typeof(ResultDataViewModel), ResultDataViewModel.VM); fluent = mvvmContext1.OfType <ResultDataViewModel>(); #region AddBinding AddBinding(fluent.SetBinding(lcNODCvalue, lc => lc.Text, x => x.ExhaustDetailData, m => { if (m == null) { return("0"); } return(m.OriginalNO.ToString("f2")); })); AddBinding(fluent.SetBinding(lcHCDCvalue, lc => lc.Text, x => x.ExhaustDetailData, m => { if (m == null) { return("0"); } return(m.OriginalHC.ToString("f2")); })); AddBinding(fluent.SetBinding(lcCODCvalue, lc => lc.Text, x => x.ExhaustDetailData, m => { if (m == null) { return("0"); } return(m.OriginalCO.ToString("f2")); })); AddBinding(fluent.SetBinding(lcCO2DCvalue, lc => lc.Text, x => x.ExhaustDetailData, m => { if (m == null) { return("0"); } return(m.OriginalCO2.ToString("f2")); })); AddBinding(fluent.SetBinding(lcT1Value, lc => lc.Text, x => x.ExhaustDetailData, m => { if (m == null) { return("0"); } return(m.T12.ToString()); })); AddBinding(fluent.SetBinding(lcT2value, lc => lc.Text, x => x.ExhaustDetailData, m => { if (m == null) { return("0"); } return(m.T13.ToString()); })); AddBinding(fluent.SetBinding(lcLightIntensityValue, lc => lc.Text, x => x.ExhaustDetailData, m => { if (m == null) { return("0"); } return(m.RealIntensity.ToString()); })); AddBinding(fluent.SetBinding(lcCOValue, lc => lc.Text, x => x.DetialInfoEntities, m => { try { if (m == null || m.Count == 0) { return("0"); } object o = JsonNewtonsoft.FromJSON(m[0].ToString()); if (o is JObject) { JObject jo = (o as JObject); string value = jo["CO"].ToString(); if (!string.IsNullOrEmpty(value)) { return(Convert.ToDouble(value).ToString("f2")); } } } catch (Exception ex) { ErrorLog.Error(ex.ToString()); } return("0"); })); AddBinding(fluent.SetBinding(lcNOValue, lc => lc.Text, x => x.DetialInfoEntities, m => { try { if (m == null || m.Count == 0) { return("0"); } object o = JsonNewtonsoft.FromJSON(m[0].ToString()); if (o is JObject) { JObject jo = (o as JObject); string value = jo["NO"].ToString(); if (!string.IsNullOrEmpty(value)) { return(Convert.ToDouble(value).ToString("f2")); } } } catch (Exception ex) { ErrorLog.Error(ex.ToString()); } return("0"); })); AddBinding(fluent.SetBinding(lcHCValue, lc => lc.Text, x => x.DetialInfoEntities, m => { try { if (m == null || m.Count == 0) { return("0"); } object o = JsonNewtonsoft.FromJSON(m[0].ToString()); if (o is JObject) { JObject jo = (o as JObject); string value = jo["HC"].ToString(); if (!string.IsNullOrEmpty(value)) { return(Convert.ToDouble(value).ToString("f2")); } } } catch (Exception ex) { ErrorLog.Error(ex.ToString()); } return("0"); })); AddBinding(fluent.SetBinding(lcCO2Value, lc => lc.Text, x => x.DetialInfoEntities, m => { try { if (m == null || m.Count == 0) { return("0"); } object o = JsonNewtonsoft.FromJSON(m[0].ToString()); if (o is JObject) { JObject jo = (o as JObject); string value = jo["CO2"].ToString(); if (!string.IsNullOrEmpty(value)) { return(Convert.ToDouble(value.ToString()).ToString("f2")); } } } catch (Exception ex) { ErrorLog.Error(ex.ToString()); } return("0"); })); AddBinding(fluent.SetBinding(lcOpsmokeValue, lc => lc.Text, x => x.DetialInfoEntities, m => { try { if (m == null || m.Count == 0) { return("0"); } object o = JsonNewtonsoft.FromJSON(m[0].ToString()); if (o is JObject) { JObject jo = (o as JObject); string value = jo["OpSmoke"].ToString(); if (!string.IsNullOrEmpty(value)) { return(Convert.ToDouble(value.ToString()).ToString("f2")); } } } catch (Exception ex) { ErrorLog.Error(ex.ToString()); } return("0"); })); AddBinding(fluent.SetBinding(lcBlacknessValue, lc => lc.Text, x => x.DetialInfoEntities, m => { try { if (m == null || m.Count == 0) { return("0"); } object o = JsonNewtonsoft.FromJSON(m[0].ToString()); if (o is JObject) { JObject jo = (o as JObject); string value = jo["Blackness"].ToString(); if (!string.IsNullOrEmpty(value)) { return(ConvertIntToRoma(value.ToString())); } } } catch (Exception ex) { ErrorLog.Error(ex.ToString()); } return("0"); })); AddBinding(fluent.SetBinding(lcNumberValue, lc => lc.Text, x => x.DetialInfoEntities, m => { try { if (m == null || m.Count == 0) { return("0"); } object o = JsonNewtonsoft.FromJSON(m[0].ToString()); if (o is JObject) { JObject jo = (o as JObject); string value = jo["UniqueKey"].ToString(); if (!string.IsNullOrEmpty(value)) { return(value.ToString()); } } } catch (Exception ex) { ErrorLog.Error(ex.ToString()); } return("0"); })); AddBinding(fluent.SetBinding(lcResultValue, lc => lc.Text, x => x.DetialInfoEntities, m => { try { if (m == null || m.Count == 0) { return("0"); } object o = JsonNewtonsoft.FromJSON(m[0].ToString()); if (o is JObject) { JObject jo = (o as JObject); string value = jo["Result"].ToString(); switch (Convert.ToInt32(value) + 1) { case 1: return(Program.infoResource.GetLocalizedString(language.InfoId.Disqualified)); case 2: return(Program.infoResource.GetLocalizedString(language.InfoId.Qualified)); case 3: return(Program.infoResource.GetLocalizedString(language.InfoId.Invalid)); } } } catch (Exception ex) { ErrorLog.Error(ex.ToString()); } return("0"); })); AddBinding(fluent.SetBinding(lcT1Value, lc => lc.Text, x => x.ExhaustDetailData, m => { return(m.T12.ToString()); })); AddBinding(fluent.SetBinding(lcT2value, lc => lc.Text, x => x.ExhaustDetailData, m => { return(m.T13.ToString()); })); AddBinding(fluent.SetBinding(lcLightIntensityValue, lc => lc.Text, x => x.ExhaustDetailData, m => { return(m.RealIntensity.ToString()); })); ResultDataViewModel.VM.ModelChanged += (sender, arg) => { if (arg.ModelName == typeof(ResultDataViewModel).Name || arg.ModelName == typeof(ResultDataViewModel.ExhaustDetailDataModel).Name) { action(); } }; #endregion base.InitializeBindings(); RefreshChartInfo(index); } catch (Exception ex) { } }
object CiscoCodecRegisterProcess(object threadObject) { while (!programStopping) { try { if (this.HttpClient.StartSession().Length > 0) { ErrorLog.Notice("Codec has connected and received a session id"); } else { ErrorLog.Warn("Codec has connected but did not receive session id"); } break; } catch (Exception e) { ErrorLog.Warn("Could not start session with Cisco codec, {0}", e.Message); } CrestronConsole.PrintLine("Waiting for codec connection... will retry in 30 seconds"); ErrorLog.Warn("Waiting for codec connection... will retry in 30 seconds"); CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(30000); } try { CrestronConsole.PrintLine("Connecting ControlSystem to codec and registering..."); CommandArgs args = new CommandArgs(); args.Add("HardwareInfo", ControlSystem.ControllerPrompt); args.Add("ID", CrestronEthernetHelper.GetEthernetParameter( CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS, CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType( FeedbackServer.AdapterForIPAddress))); args.Add("Name", "Crestron Control System"); args.Add("NetworkAddress", CrestronEthernetHelper.GetEthernetParameter( CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType( FeedbackServer.AdapterForIPAddress))); args.Add("SerialNumber", "Unknown"); args.Add("Type", "ControlSystem"); var assembly = Assembly.GetExecutingAssembly().GetName(); args.Add("SoftwareInfo", assembly.Name + " " + assembly.Version); XDocument response = SendCommand("Peripherals/Connect", args); CrestronConsole.PrintLine("Codec registration {0}", response.Element("Command").Element("PeripheralsConnectResult").Attribute("status").Value == "OK"); } catch (Exception e) { ErrorLog.Exception("Error trying to register control system with Cisco Codec", e); } try { CrestronConsole.PrintLine("Registering for HttpFeedback..."); this.Registerfeedback(); } catch (Exception e) { ErrorLog.Exception("Error trying to register feedback notifications with Cisco Codec", e); } try { CrestronConsole.PrintLine("Getting call status..."); this.Calls.Update(); } catch (Exception e) { ErrorLog.Exception("Error trying to update calls status with Cisco Codec", e); } try { if (this.HasConnected != null) { this.HasConnected(this); } } catch (Exception e) { ErrorLog.Exception("Error calling CiscoCodec.HasConnected thread", e); } try { CrestronConsole.PrintLine("Creating timer to periodically check the codec connection every 60 seconds"); _CheckStatusTimer = new CTimer(CheckStatus, null, 60000, 60000); } catch (Exception e) { CrestronConsole.PrintLine("Error crating CiscoCodec CheckStatus Timer", e.Message); ErrorLog.Error("Error creating CiscoCodec CheckStatus Timer", e.Message); } this.DeviceCommunicating = true; return(null); }
protected void Page_Load(object sender, EventArgs e) { ErrorLog.ErrorRoutine(false, "Crazy?"); }
// effects: Ensures that there is a relationship mapped into the C-space for some cell in m_cellGroup. Else // adds an error to errorLog private void GuaranteeMappedRelationshipForForeignKey( QueryRewriter childRewriter, QueryRewriter parentRewriter, IEnumerable <Cell> cells, ErrorLog errorLog, ConfigViewGenerator config) { var childContext = childRewriter.ViewgenContext; var parentContext = parentRewriter.ViewgenContext; // Find a cell where this foreign key is mapped as a relationship var prefix = new MemberPath(ChildTable); var primaryKey = ExtentKey.GetPrimaryKeyForEntityType(prefix, ChildTable.ElementType); var primaryKeyFields = primaryKey.KeyFields; var foundCell = false; var foundValidParentColumnsForForeignKey = false; //we need to find only one, dont error on any one check being false List <ErrorLog.Record> errorListForInvalidParentColumnsForForeignKey = null; foreach (var cell in cells) { if (cell.SQuery.Extent.Equals(ChildTable) == false) { continue; } // The childtable is mapped to a relationship in the C-space in cell // Check that all the columns of the foreign key and the primary key in the child table are mapped to some // property in the C-space var parentEnd = GetRelationEndForColumns(cell, ChildColumns); if (parentEnd != null && CheckParentColumnsForForeignKey(cell, cells, parentEnd, ref errorListForInvalidParentColumnsForForeignKey) == false) { // Not an error unless we find no valid case continue; } else { foundValidParentColumnsForForeignKey = true; } var childEnd = GetRelationEndForColumns(cell, primaryKeyFields); Debug.Assert( childEnd == null || parentEnd != childEnd, "Ends are same => PKey and child columns are same - code should gone to other method"); // Note: If both of them are not-null, they are mapped to the // same association set -- since we checked that particular cell if (childEnd != null && parentEnd != null && FindEntitySetForColumnsMappedToEntityKeys(cells, primaryKeyFields) != null) { foundCell = true; CheckConstraintWhenParentChildMapped(cell, errorLog, parentEnd, config); break; // Done processing for the foreign key - either it was mapped correctly or it was not } else if (parentEnd != null) { // At this point, we know cell corresponds to an association set var assocSet = (AssociationSet)cell.CQuery.Extent; var parentSet = MetadataHelper.GetEntitySetAtEnd(assocSet, parentEnd); foundCell = CheckConstraintWhenOnlyParentMapped(assocSet, parentEnd, childRewriter, parentRewriter); if (foundCell) { break; } } } //CheckParentColumnsForForeignKey has returned no matches, Error. if (!foundValidParentColumnsForForeignKey) { Debug.Assert( errorListForInvalidParentColumnsForForeignKey != null && errorListForInvalidParentColumnsForForeignKey.Count > 0); foreach (var errorRecord in errorListForInvalidParentColumnsForForeignKey) { errorLog.AddEntry(errorRecord); } return; } if (foundCell == false) { // No cell found -- Declare error var message = Strings.ViewGen_Foreign_Key_Missing_Relationship_Mapping(ToUserString()); IEnumerable <LeftCellWrapper> parentWrappers = GetWrappersFromContext(parentContext, ParentTable); IEnumerable <LeftCellWrapper> childWrappers = GetWrappersFromContext(childContext, ChildTable); var bothExtentWrappers = new Set <LeftCellWrapper>(parentWrappers); bothExtentWrappers.AddRange(childWrappers); var record = new ErrorLog.Record( ViewGenErrorCode.ForeignKeyMissingRelationshipMapping, message, bothExtentWrappers, String.Empty); errorLog.AddEntry(record); } }
public static bool FindMappingErrors(ViewgenContext context, MemberDomainMap domainMap, ErrorLog errorLog) { //Can't get here if Update Views have validation disabled Debug.Assert(context.ViewTarget == ViewTarget.QueryView || context.Config.IsValidationEnabled); if (context.ViewTarget == ViewTarget.QueryView && !context.Config.IsValidationEnabled) { return(false); // Rules for QV under no validation are different } var matcher = new ErrorPatternMatcher(context, domainMap, errorLog); matcher.MatchMissingMappingErrors(); matcher.MatchConditionErrors(); matcher.MatchSplitErrors(); if (matcher.m_errorLog.Count == matcher.m_originalErrorCount) { //this will generate redundant errors if one of the above routine finds an error // so execute it only when we dont have any other errors matcher.MatchPartitionErrors(); } if (matcher.m_errorLog.Count > matcher.m_originalErrorCount) { ExceptionHelpers.ThrowMappingException(matcher.m_errorLog, matcher.m_viewgenContext.Config); } return(false); }
private static void LogException(Exception e) { var context = HttpContext.Current; ErrorLog.GetDefault(context).Log(new Error(e, context)); }
public ElmahCoreLog(LogLevel MinLevel, ErrorLog ErrorLog) { this.errorLog = ErrorLog; this._minLevel = MinLevel; }
/// <summary> /// Gets the achievements from http://steamcommunity.com/id/[customurl]/[game]/?xml=1. /// </summary> /// <param name="steamUserId">The steam user id.</param> /// <param name="closedOnly">if set to <c>true</c> [closed only].</param> /// <param name="language">The language.</param> /// <returns></returns> private ICollection <UserAchievement> GetAchievements(string steamUserId, bool closedOnly, string language) { if (steamUserId == null) { throw new ArgumentNullException("steamUserId"); } List <UserAchievement> achievements = new List <UserAchievement>(); IEnumerable <Game> games = GetGames(steamUserId, language); if (closedOnly) { games = games.Where(g => g.PlayedRecently); } foreach (Game game in games) { Uri xmlStatsUrl = GetStatsUrl(game.StatsUrl, language); Debug.WriteLine(xmlStatsUrl); string xml = _webClient.DownloadString(xmlStatsUrl); if (xml == null) { continue; } IEnumerable <UserAchievement> gameAchievements; try { if (closedOnly) { gameAchievements = _achievementParser.ParseClosed(xml); } else { gameAchievements = _achievementParser.Parse(xml); } } catch (XmlException ex) { // log and ignore invalid achievement xml HttpContext context = HttpContext.Current; if (context != null) { ErrorLog errorLog = ErrorLog.GetDefault(context); if (errorLog != null) { Exception exception = new InvalidStatsXmlException(steamUserId, new Uri(game.StatsUrl), ex); errorLog.Log(new Error(exception)); } } continue; } if (!gameAchievements.Any()) { continue; } List <UserAchievement> achievementList = gameAchievements.ToList(); Game game1 = game; achievementList.ForEach(a => { a.Achievement.Game = game1; a.Achievement.Language = language; }); achievements.AddRange(achievementList); } return(achievements); }
public static SimpleUser Authentication(string UserName, string Password) { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * Procedure Name : UserAuthentication_UserLogIN * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Type: SELECT * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Parameters : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * @UserID - varchar(124) * @Password - varchar(124) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Values : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ApplicationID * Membership * MatrimonialID * * * * * * * * * * * * * * * * * * * * * * * * * * * */ UserName = Crypto.EnCrypto(UserName.ToLower()); SimpleUser objUser = new SimpleUser(); using (SqlConnection objConnection = DBConnection.GetSqlConnection()) { try { //Inserting data into //Creating Command object SqlCommand objCommand = new SqlCommand("UserAuthentication_UserLogIN", objConnection); objCommand.CommandType = CommandType.StoredProcedure; //Adding new Parameters objCommand.Parameters.Add(new SqlParameter("@UserID", SqlDbType.VarChar)); objCommand.Parameters["@UserID"].Value = UserName; objCommand.Parameters.Add(new SqlParameter("@Password", SqlDbType.VarChar)); objCommand.Parameters["@Password"].Value = Password; objConnection.Open(); SqlDataReader objReader = objCommand.ExecuteReader(); objReader.Read(); objUser.ApplicationID = objReader["ApplicationID"].ToString(); objUser.TypeOfUser = Convert.ToSByte(objReader["Membership"]); objUser.MatrimonialID = objReader["MatrimonialID"].ToString(); objUser.UserName = Crypto.DeCrypto(UserName); objUser.AuthenticationStatus = true; objReader.Dispose(); } catch (InvalidOperationException) { objUser.ApplicationID = null; objUser.TypeOfUser = 0; objUser.MatrimonialID = null; objUser.UserName = null; objUser.AuthenticationStatus = false; } catch (Exception Ex) { objUser.ApplicationID = null; objUser.TypeOfUser = 0; objUser.MatrimonialID = null; objUser.UserName = null; objUser.AuthenticationStatus = false; ErrorLog.WriteErrorLog("UserAuthentication()", Ex); } finally { objConnection.Close(); } } return(objUser); }
public ElmahCoreLogProvider(ErrorLog ErrorLog) : this(DefaultMinLevel) => this.errorLog = ErrorLog;
private ErrorPatternMatcher(ViewgenContext context, MemberDomainMap domainMap, ErrorLog errorLog) { m_viewgenContext = context; m_domainMap = domainMap; MemberPath.GetKeyMembers(context.Extent, domainMap); m_errorLog = errorLog; m_originalErrorCount = m_errorLog.Count; }
public static ItemObject GenerateTournamentPrize(TournamentGame tournamentGame, TournamentPrizePool currentPool = null, bool keepTownPrize = true) { var numItemsToGet = TournamentXPSettings.Instance.NumberOfPrizeOptions; bool bRegenAllPrizes = false; if (currentPool == null) { bRegenAllPrizes = true; currentPool = GetTournamentPrizePool(tournamentGame.Town.Settlement); } var allitems = GetItemStringsRevised(tournamentGame, TournamentPrizePoolBehavior.GetActivePrizeTypes()); //Add any existing items if we are filling in missing ones from an already generated pool var pickeditems = new List <string>(); if (keepTownPrize && !string.IsNullOrWhiteSpace((tournamentGame.Prize.StringId))) { pickeditems.Add(tournamentGame.Prize.StringId); currentPool.SelectedPrizeStringId = tournamentGame.Prize.StringId; } try { if (!bRegenAllPrizes) { foreach (ItemRosterElement existingPrize in currentPool.Prizes) { if (!pickeditems.Contains(existingPrize.EquipmentElement.Item.StringId)) { pickeditems.Add(existingPrize.EquipmentElement.Item.StringId); } if (allitems.Contains(existingPrize.EquipmentElement.Item.StringId)) { allitems.Remove(existingPrize.EquipmentElement.Item.StringId); } } } } catch (Exception ex) { ErrorLog.Log("ERROR: GetTournamentPrize existingprizes\n" + ex.ToStringFull()); } //If the totoal pool of unique items is less than our desired number, reduce our pool size. if (allitems.Count() < numItemsToGet) { numItemsToGet = allitems.Count(); } while (pickeditems.Count < numItemsToGet && allitems.Count() > 0) { var randomId = allitems.GetRandomElement <string>(); if (!pickeditems.Contains(randomId)) { pickeditems.Add(randomId); allitems.Remove(randomId); } } currentPool.Prizes = new ItemRoster(); foreach (var id in pickeditems) { ItemModifier itemModifier = null; var pickedPrize = Game.Current.ObjectManager.GetObject <ItemObject>(id); #if VERSION120 if (TournamentXPSettings.Instance.EnableItemModifiersForPrizes) { //var ee = GetEquipmentWithModifier(pickedPrize, TournamentPrizePoolBehavior.GetProsperityModifier(tournamentGame.Town.Settlement)); if (MBRandom.RandomFloatRanged(100f) < 50f) { var ee = GetEquipmentWithModifier(pickedPrize, 1.3f); itemModifier = ee.ItemModifier; } } #endif currentPool.Prizes.Add(new ItemRosterElement(pickedPrize, 1, itemModifier)); // currentPool.Prizes.Add(new ItemRosterElement(pickedPrize, 1, null)); //Turn off random item mods for now; } if (!keepTownPrize) { var selected = currentPool.Prizes.GetRandomElement <ItemRosterElement>(); currentPool.SelectedPrizeStringId = selected.EquipmentElement.Item.StringId; SetTournamentSelectedPrize(tournamentGame, selected.EquipmentElement.Item); } return(currentPool.SelectPrizeItemRosterElement.EquipmentElement.Item); }
public static async Task <bool> ErrorLog(ErrorLog log) { //MongoDbHelper<ErrorLog> mongoDbHelper = new MongoDbHelper<ErrorLog>(); //return await mongoDbHelper.Insert(log); return(true); }