public static long ParseNumberId(string sNumberId) { lock (locker) { try { //StationSettings settings = StationSettings.GetSettings; //ExcpHelper.ThrowIf(settings == null, "Settings IS NULL"); ExcpHelper.ThrowIf(string.IsNullOrEmpty(m_sStationNumber), "Station Number is invalid"); ExcpHelper.ThrowIf(string.IsNullOrEmpty(sNumberId) || m_sStationNumber.Length >= sNumberId.Length, "Parsed Number is invalid"); int iStationNumberPos = sNumberId.IndexOf(m_sStationNumber, StringComparison.OrdinalIgnoreCase); ExcpHelper.ThrowIf(iStationNumberPos != 0, "Cannot find current Station Number ('{0}') in incoming Number ('{1}')", m_sStationNumber, sNumberId); string sLongToParse = sNumberId.Substring(m_sStationNumber.Length); return(Convert.ToInt64(sLongToParse)); } catch (Exception excp) { Log.Error(ExcpHelper.FormatException(excp, "CRITICAL ERROR: SetLastTransactionId() - Cannot set last Transaction ID"), excp); } return(ERROR_NUMBER); } }
public string GetNextTransactionId() { lock (locker) { try { //StationSettings settings = StationSettings.GetSettings; //ExcpHelper.ThrowIf(settings == null, "Settings IS NULL"); //ExcpHelper.ThrowIf(string.IsNullOrEmpty(settings.StationNumber), "Station Number is invalid"); //ExcpHelper.ThrowIf(string.IsNullOrEmpty(sStationNumber), "Station Number is invalid"); m_lLastTransactionID = m_lLastTransactionID + 1; string sFormat = string.Format("D{0}", TRANSACTION_INDEX_LENGTH); //string sTransactionId = settings.StationNumber + m_lLastTransactionID.ToString(sFormat); string sTransactionId = m_sStationNumber + m_lLastTransactionID.ToString(sFormat); Log.InfoFormat("GetNextTransactionId('{0}') = '{1}'", m_sStationNumber, sTransactionId); return(sTransactionId); } catch (Exception excp) { Log.Error(ExcpHelper.FormatException(excp, "CRITICAL ERROR: GetNextTransactionId()"), excp); } return(string.Empty); } }
public static eExistResult OneOfRequiredTablesExist(IDbConnection conn, IDbTransaction transaction) { try { string[] arrRequiredTables = DatabaseManager.Schema.RequiredTables.Split(new char[] { ',', ' ', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string sRequiredTableName in arrRequiredTables) { eExistResult err = DoesTableExist(conn, sRequiredTableName); ExcpHelper.ThrowIf(err == eExistResult.Error, "Cannot recognize if table '{0}' exists.", sRequiredTableName); if (err == eExistResult.Exists) { return(eExistResult.Exists); } } return(eExistResult.DoesNotExist); } catch (Exception excp) { m_logger.Error(ExcpHelper.FormatException(excp, "OneOfRequiredTablesExist() ERROR"), excp); } return(eExistResult.Error); }
public static X509Certificate2Collection GetCertificateCollectionBySubject(string sCertificateSubject) { try { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.MaxAllowed); return(store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, sCertificateSubject, false)); } catch (Exception excp) { Log.Error(ExcpHelper.FormatException(excp, "GetCertificateCollectionBySubject(sCertificateSubject='{0}') ERROR", sCertificateSubject), excp); } return(null); }
public static void DropDatabase(bool isTestMode) { string sDatabaseName = ConfigurationManager.AppSettings["database_name"]; string sConnectionString = ConfigurationManager.AppSettings["database_connection_string"]; if (isTestMode) { sConnectionString.Replace(sDatabaseName, "test_" + sDatabaseName); sDatabaseName = "test_" + sDatabaseName; } try { using (IDbConnection conn = new NpgsqlConnection(sConnectionString.Replace(sDatabaseName, ConnectionManager.SystemDatabaseName))) { //conn.Open(); eExistResult eerDatabase = DatabaseManager.DoesDatabaseExist(conn, sDatabaseName); ExcpHelper.ThrowIf(eerDatabase == eExistResult.Error, "Cannot recognize if database '{0}' exists.", sDatabaseName); if (eerDatabase == eExistResult.Exists) { try { DataCopy.ExecuteScalar(conn, null, "select pg_terminate_backend(procpid) from pg_stat_activity where datname='{0}';", sDatabaseName); using (IDbConnection conn2 = new NpgsqlConnection(sConnectionString.Replace(sDatabaseName, ConnectionManager.SystemDatabaseName))) { DataCopy.ExecuteScalar(conn2, null, DatabaseManager.Schema.DeleteDatabaseStatement, sDatabaseName); } m_logger.InfoFormat("Database '{0}' Successfully deleted", sDatabaseName); } catch (Exception excp) { m_logger.Error(ExcpHelper.FormatException(excp, "EnsureDatabase() ERROR - cannot delete {0} Database '{1}'", ConnectionManager.Dialect, sDatabaseName), excp); throw; } } } } catch (System.Exception excpInner) { string sError = string.Format("Cannot verify PostGreSQL Server. Either Server is not installed or invalid priveleges ({0}).\r\n{1}\r\n{2}", sConnectionString, excpInner.Message, excpInner.StackTrace); //MessageBox.Show(sError, "Station Start Error", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new Exception(sError, excpInner); } }
public void Write(Type type, eLoggerLevel level, string sMessage, object[] args) { int iLevel = (int)level; if ((iLevel & m_iAllowedLevels) > 0) { try { LoggerRecord record = new LoggerRecord(type, level, sMessage, args); m_sqMessages.Enqueue(record); } catch (Exception excp) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ExcpHelper.FormatException(excp, "LiveLog.WriteConsole('{0}') ERROR", m_sLogleFilePath)); } } }
public static bool DeleteFromTables() { bool bResult = false; ConnectionManager.ProcessTransaction(delegate(IDbConnection conn, IDbTransaction transaction) { try { DataCopy.ExecuteScalar(conn, transaction, DatabaseManager.Schema.DeleteFromTablesStatement); bResult = true; } catch (Exception excp) { m_logger.Error(ExcpHelper.FormatException(excp, "DeleteFromTables() ERROR"), excp); throw; } }); return(bResult); }
private static void ReaderThread(ThreadContext tc) { RemoveLiveMatches(eServerSourceType.BtrPre); RemoveLiveMatches(eServerSourceType.BtrLive); DateTime dtLastReceived = DateTime.Now; bool bDisabled = false; bool bRemoved = false; var lineReseiveCopy = ""; while (m_bRunning && !tc.IsToStop) { m_dtConnected = DateTime.Now; try { string sServerMessage = ""; while (m_bRunning && !tc.IsToStop && m_liveClient.IsAlive) { lineReseiveCopy = LinesToReceive; //if (m_liveClient.HaveData) sServerMessage = m_liveClient.ReadLine(); ExcpHelper.ThrowIf(string.IsNullOrEmpty(sServerMessage), "Received Empty Message"); m_logger.Debug("received live message " + sServerMessage.Length); m_liveClient.WriteLine(lineReseiveCopy); if (sServerMessage == LIVEBET_MSG_HELLO || sServerMessage == LIVEBET_MSG_EMPTY) { m_logger.DebugFormat("Received '{0}'", sServerMessage); dtLastReceived = DateTime.Now; LineSr.LiveBetConnected = true; } else { try { var originalLength = sServerMessage.Length; if (sServerMessage.StartsWith(COMPRESSED)) { string sPrefix = sServerMessage.Substring(0, COMPRESSED_MASK_SIZE); string sSize = sPrefix.Substring(COMPRESSED.Length); int iCompressedMessageSize = 0; bool bSizeParsed = int.TryParse(sSize, out iCompressedMessageSize); Debug.Assert(bSizeParsed && iCompressedMessageSize > 0); //Debug.Assert(iCompressedMessageSize + COMPRESSED_MASK_SIZE == sServerMessage.Length); sServerMessage = TextUtil.DecompressBase64String(sServerMessage.Substring(COMPRESSED_MASK_SIZE)); } int startIndex = sServerMessage.IndexOf('<'); ExcpHelper.ThrowIf(startIndex < 0, "Cannot find start xml point '<'"); sServerMessage = sServerMessage.Substring(startIndex); TimeSpan tsDuration = DateTime.Now - m_dtConnected; LineContainer lc = LineContainer.FromXml(sServerMessage); ExcpHelper.ThrowIf <NullReferenceException>(lc == null, "LineContainer is Null"); //lc.Duration = tsDuration; m_sqMessages.Enqueue(lc); int iQueueCount = m_sqMessages.Count; ExcpHelper.ThrowIf(iQueueCount > DalStationSettings.Instance.LiveErrorQueueSize, "Live Client Queue size ({0}) is too big.", iQueueCount); if (iQueueCount > DalStationSettings.Instance.LiveWarnQueueSize) { m_logger.Warn("Live Client Queue size = " + iQueueCount); } dtLastReceived = DateTime.Now; bDisabled = false; bRemoved = false; string sType = lc.Attributes.ContainsKey("line") ? lc.Attributes["line"] : "none"; m_logger.DebugFormat("Enqueueing message {0} (Total messages in queue {1}; Connected {2}; Duration {3},type {4},length {5},compressedLength {6})", lc.GetDocId(), m_sqMessages.Count, m_dtConnected, tsDuration, sType, sServerMessage.Length, originalLength); } catch (Exception excp) { m_logger.Warn(ExcpHelper.FormatException(excp, "Could not process incoming server message (Size={0})", sServerMessage.Length)); throw; } } LineSr.LiveBetConnected = true; Thread.Sleep(10); } } catch (Exception excp) { m_logger.Error(excp.Message, excp); m_sqMessages.Clear(); m_logger.Excp(excp, "Connection to server lost after importing time ({0}) ms bacause of {1}", DateTime.Now - m_dtConnected, excp.GetType()); LineSr.LiveBetConnected = false; } if (dtLastReceived + LIVE_TIME_OUT_TO_DISABLE < DateTime.Now && !bDisabled) { LineSr.SyncRoutines(eUpdateType.LiveBet, "Connection lost. SportRadar LiveMarket is disabled.", DalStationSettings.Instance.UseDatabaseForLiveMatches, null, delegate(object obj) { LineSr.Instance.DisableLiveMatches(eServerSourceType.BtrLive); return(false); }); LineSr.ProcessDataSqlUpdateSucceeded(eUpdateType.LiveBet, "Connection lost. SportRadar LiveMarket is cleared."); bDisabled = true; } else if (dtLastReceived + LIVE_TIME_OUT_TO_REMOVE < DateTime.Now && !bRemoved) { m_logger.ErrorFormat("Removing all live matches because last message ('{0}') were too long time ago (TimeOut='{1}')", new Exception(), dtLastReceived, LIVE_TIME_OUT_TO_REMOVE); RemoveLiveMatches(eServerSourceType.BtrPre); RemoveLiveMatches(eServerSourceType.BtrLive); bRemoved = true; } Thread.Sleep(10); EnsureConnection(); } }
protected void LoggerThread(ThreadContext tc) { FileInfo fi = new FileInfo(m_sLogleFilePath); StringBuilder sb = new StringBuilder(); try { while (!tc.IsToStop) { if (fi.Exists && fi.Length > m_lMaxSize) { string sExtension = Path.GetExtension(m_sLogleFilePath); string sNewFileName = string.Format("{0}.backup__{1:dd-MMM-yyyy__HH-mm-ss}{2}.", m_sLogleFilePath, DateTime.Now, sExtension); File.Move(m_sLogleFilePath, sNewFileName); } using (StreamWriter sw = new StreamWriter(m_sLogleFilePath, true)) { while (!tc.IsToStop) { if (m_sqMessages.Count > 0) { LoggerRecord record = m_sqMessages.Dequeue(); sb.AppendFormat("{0} {1:dd-MMM-yyyy HH:mm:ss.ffffff} ", record.LoggerLevel, record.Time); if (record.Args != null && record.Args.Length > 0) { sb.AppendFormat(record.Message, record.Args); } else { sb.Append(record.Message); } sb.Append("\r\n"); sw.Write(sb.ToString()); sw.Flush(); } sb.Clear(); fi.Refresh(); if (fi.Length > m_lMaxSize) { break; } Thread.Sleep(1); } } } } catch (Exception excp) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ExcpHelper.FormatException(excp, "LiveLog.WriteConsole('{0}') ERROR", m_sLogleFilePath)); } }
/* * private static bool DeleteMatches(IDbConnection conn, IDbTransaction transaction) * { * LineObjectCollection<MatchLn> locMatches = LineSr.Instance.ObjectsToRemove.GetLineObjectCollection<MatchLn>(); * * if (locMatches != null && locMatches.Count > 0) * { * IdentityList il = new IdentityList(); * * foreach (MatchLn mtch in locMatches.Values) * { * il.AddUnique(mtch.MatchId); * } * * string sMatchIds = il.FormatIds(); * * DataCopy.ExecuteScalar(conn, transaction, DELETE_MATCH_ODDS_QUERY, sMatchIds); * DataCopy.ExecuteScalar(conn, transaction, DELETE_MATCH_BETDOMAIN_QUERY, sMatchIds); * DataCopy.ExecuteScalar(conn, transaction, DELETE_MATCH_TO_GROUP_QUERY, sMatchIds); * DataCopy.ExecuteScalar(conn, transaction, DELETE_LIVE_MATCH_INFO_QUERY, sMatchIds); * DataCopy.ExecuteScalar(conn, transaction, DELETE_MATCHES_QUERY, sMatchIds); * * return true; * } * * return false; * } */ public static eFileSyncResult UpdateDatabase(IDbConnection conn, eUpdateType eut, string sProviderDescription, UpdateStatistics us) { eFileSyncResult fsr = eFileSyncResult.Failed; DateTime dtStart = DateTime.Now; string sErrorString = string.Empty; DataCopy dc = null; string sUpdateDescription = eut.ToString(); CheckTime ct = new CheckTime("UpdateAll({0}) Entered", sUpdateDescription); DictionaryOfLineObjectCollectionLight dlocToModify = LineSr.Instance.NewOrChangedObjects; DictionaryOfLineObjectCollectionLight dlocToDelete = LineSr.Instance.ObjectsToRemove; try { using (IDbTransaction transaction = conn.BeginTransaction()) { dc = new DataCopy(conn, transaction, sUpdateDescription); try { UpdatesLn updatesLn = new UpdatesLn(eut, string.Format("Saving {0} and Deleting {1} line tables", dlocToModify.Count, dlocToDelete.Count), sProviderDescription); updatesLn.Save(conn, transaction); Debug.Assert(updatesLn.UpdateId > 0); // Insert or Update objects dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <TaggedStringLn>(), TaggedStringLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <TimeTypeLn>(), TimeTypeLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <ScoreTypeLn>(), ScoreTypeLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <BetTypeLn>(), BetTypeLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <BetDomainTypeLn>(), BetDomainTypeLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <GroupLn>(), GroupLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <CompetitorLn>(), CompetitorLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <MatchLn>(), MatchLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <CompetitorToOutrightLn>(), CompetitorToOutrightLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <LiveMatchInfoLn>(), LiveMatchInfoLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <MatchResultLn>(), MatchResultLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <MatchToGroupLn>(), MatchToGroupLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <BetDomainLn>(), BetDomainLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <ResourceRepositoryLn>(), ResourceRepositoryLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <ResourceAssignmentLn>(), ResourceAssignmentLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <CompetitorInfosLn>(), CompetitorInfosLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <MatchInfosLn>(), MatchInfosLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <TournamentInfosLn>(), TournamentInfosLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <OddLn>(), OddLn.TableSpec, updatesLn); //dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection<LiabilityLn>(), LiabilityLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <LanguageLn>(), LanguageLn.TableSpec, updatesLn); dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection <MultistringGroupLn>(), MultistringGroupLn.TableSpec, updatesLn); //dc.InsertOrUpdate(dlocToModify.GetLineObjectCollection<TournamentMatchLocksLn>(), TournamentMatchLocksLn.TableSpec, updatesLn); // Delete Objects dc.DeleteObjects(dlocToDelete.GetLineObjectCollection <OddLn>(), OddLn.TableSpec); dc.DeleteObjects(dlocToDelete.GetLineObjectCollection <BetDomainLn>(), BetDomainLn.TableSpec); dc.DeleteObjects(dlocToDelete.GetLineObjectCollection <MatchToGroupLn>(), MatchToGroupLn.TableSpec); dc.DeleteObjects(dlocToDelete.GetLineObjectCollection <LiveMatchInfoLn>(), LiveMatchInfoLn.TableSpec); dc.DeleteObjects(dlocToDelete.GetLineObjectCollection <CompetitorToOutrightLn>(), CompetitorToOutrightLn.TableSpec); dc.DeleteObjects(dlocToDelete.GetLineObjectCollection <MatchLn>(), MatchLn.TableSpec); if (dc.Statistics.IsInsrtedOrUpdatedOrDeleted) { // DK: If You like to test data import then uncomment line bellow: // throw new SystemException("Developer Exception: Always rollback transaction for test purposes"); transaction.Commit(); fsr = eFileSyncResult.Succeeded; ct.AddEvent("Commited"); } else { transaction.Rollback(); fsr = eFileSyncResult.Skipped; ct.AddEvent("Rolled Back"); } if (us != null) { us.Append(dc.Statistics); } } catch (Exception excp) { transaction.Rollback(); m_logger.Excp(excp, "UpdateAllWithSqlBulkCopy General Transaction Exception"); } finally { DateTime dtEnd = DateTime.Now; if (fsr != eFileSyncResult.Skipped) { // DK: Let's write to log ONLY Succeeded or Failed file syncrhonization info. string sInfo = @" {7} UpdateAllWithSqlBulkCopy({0}) {1} {2} {3} Start: {4}; End: {5}; Time: {6}; "; m_logger.InfoFormat( sInfo, // Format sProviderDescription, // Provider Description fsr, // Result sErrorString, // Errors if any dc.Statistics, // Statistic dtStart, dtEnd, dtEnd - dtStart, // Time sUpdateDescription); // LiveBet or PreMatch } else { m_logger.InfoFormat("{0} UpdateAllWithSqlBulkCopy Skipped. Time: {1}", sUpdateDescription, dtEnd - dtStart); } if (fsr == eFileSyncResult.Succeeded) { } ct.AddEvent("UpdateAll({0}) completed", sUpdateDescription); ct.Info(m_logger); } } // } } catch (Exception excp) { sErrorString += ExcpHelper.FormatException(excp, "UpdateAllWithSqlBulkCopy General Exception"); m_logger.Error(sErrorString, excp); } return(fsr); }