// Start is called before the first frame update void Start() { if (current != null) { Destroy(current.gameObject); } current = this; DontDestroyOnLoad(gameObject); EventManager.Instance.AddEventListener <int>("UpdateScrap", UpdateScrapText); MiscData.LoadGame(); currentLevelMax = MiscData.level; topRight = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 10)); bottomLeft = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 10)); highscoreText.text = "Highscore: " + MiscData.highscore.ToString(); finishLogo.rectTransform.position -= new Vector3(-(Screen.width / 2 + finishLogo.rectTransform.rect.width / 2), 0, 0); boostLogo.rectTransform.position = finishLogo.rectTransform.position; menuUI.sizeDelta = new Vector2(Screen.width, Screen.height); boosts.Add("Damage Increase", 0); boosts.Add("Extra Repair Kit", 0); boosts.Add("Extra Impact Shield", 0); boosts.Add("Health Increase", 0); boosts.Add("Speed Increase", 0); boosts.Add("Scrap Collection Increase", 0); hitsThreshold = 10; }
private void butESign_Click(object sender, EventArgs e) { Userod curUser = _userSig ?? Security.CurUser; Provider provCur = Providers.GetProv(curUser.ProvNum); string digitalSignature = Lan.g(this, "Digitally Signed by "); if (provCur != null) { digitalSignature += provCur.GetLongDesc(); } else if (curUser != null) { digitalSignature += curUser.UserName + " (UserNum:" + curUser.UserNum + ")"; } else { //should never happen digitalSignature = Lan.g(this, "Digitally signed by unknown user."); } digitalSignature += "\r\n" + Lan.g(this, "Date Signed") + ": " + MiscData.GetNowDateTime().ToString(); List <Point> pList = sigBox.EncryptString(digitalSignature); sigBox.SetPointList(pList); OnSignatureChanged(); sigBox.Enabled = false; }
private ResourceFilesData() { ArmorData armorData; WeaponsData weaponsData; MiscData miscData; ItemStatCostData itemStatCostData; using (Stream s = GetResource("ItemStatCost.txt")) { itemStatCostData = ItemStatCostData.Read(s); } using (Stream s = GetResource("Armor.txt")) { armorData = ArmorData.Read(s); } using (Stream s = GetResource("Weapons.txt")) { weaponsData = WeaponsData.Read(s); } using (Stream s = GetResource("Misc.txt")) { miscData = MiscData.Read(s); } MetaData = new MetaData(itemStatCostData, new ItemsData(armorData, weaponsData, miscData)); }
public static MiscData Read(Stream data) { var misc = new MiscData(); misc.ReadData(data); return(misc); }
public DB_SubCalendarEvent(CalendarEvent calendarEvent, TilerUser Creator, TilerUserGroup users, string timeZone, string MySubEventID, EventName name, BusyTimeLine MyBusylot, DateTimeOffset EventStart, DateTimeOffset EventDeadline, TimeSpan EventPrepTime, string myParentID, bool Rigid, bool Enabled, EventDisplay UiParam, MiscData Notes, bool completeFlag, TilerElements.Location EventLocation = null, TimeLine calendarEventRange = null, ConflictProfile conflicts = null) { if (EventDeadline < EventStart) { throw new Exception("SubCalendar Event cannot have an end time earlier than the start time"); } _TimeZone = timeZone; _Name = name; _Creator = Creator; _Users = users; if (conflicts == null) { conflicts = new ConflictProfile(); } _ConflictingEvents = conflicts; _CalendarEventRange = calendarEventRange; //string eventName, TimeSpan EventDuration, DateTimeOffset EventStart, DateTimeOffset EventDeadline, TimeSpan EventPrepTime, TimeSpan PreDeadline, bool EventRigidFlag, bool EventRepetition, int EventSplit updateStartTime(EventStart); updateEndTime(EventDeadline); _EventDuration = MyBusylot.End - MyBusylot.Start; BusyFrame = MyBusylot; _PrepTime = EventPrepTime; UniqueID = new EventID(MySubEventID); this._LocationInfo = EventLocation; _UiParams = UiParam; _DataBlob = Notes; _Complete = completeFlag; this._Enabled = Enabled; //EventSequence = new EventTimeLine(UniqueID.ToString(), StartDateTime, EndDateTime); _RigidSchedule = Rigid; _LastReasonStartTimeChanged = this.Start; _calendarEvent = calendarEvent; }
private IEnumerator EndLevel(bool cleared, bool endless) { if (!cleared) { finishLogo.text = "Failed!"; } if (endless) { finishLogo.text = "Final Score: " + score + "!"; } CurrentState = State.MainMenu; RectTransform rectTransform = finishLogo.rectTransform; while (rectTransform.position.x > Screen.width / 2) { rectTransform.position -= new Vector3(50, 0, 0); yield return(null); } yield return(new WaitForSeconds(2)); while (rectTransform.position.x < Screen.width + rectTransform.rect.width / 2) { rectTransform.position += new Vector3(50, 0, 0); yield return(null); } if (cleared) { //Pull up cutscene, add cutscene to player, play cutscene, finish PlayerController.current.EndLevel(); while (CutsceneManager.Instance.playingCutscene) { yield return(new WaitForEndOfFrame()); } Transform playerTrans = PlayerController.current.transform; Destroy(PlayerController.current); Vector3 oldPosition = playerTrans.position; Vector3 newPosition = playerTrans.position + new Vector3(0, 0, 15); float j = 0; while (playerTrans.position != newPosition) { playerTrans.position = Vector3.Lerp(oldPosition, newPosition, j); j += Time.deltaTime; yield return(null); } } yield return(new WaitForSeconds(1)); CurrentState = State.MainMenu; MiscData.SaveGame(); SceneManager.LoadScene(0); yield return(null); }
public JsonWallpaperData(ImageData[] imageData, Dictionary <string, bool> imageFolders) { //! This handles SAVING!!! | Don't go to this code segment for modifying how data is loaded! miscData = new MiscData(); // values are updated in the constructor themeOptions = OptionsData.ThemeOptions; this.imageFolders = imageFolders; tagData = TaggingInfo.GetAllCategories(); this.imageData = imageData; }
//[Authorize] public async Task <IActionResult> Create([FromBody] MiscData data) { return(await this.Execute(false, true, async() => { string dataKey = await this.miscDataService.CreateOrUpdateAsync(data.Key, data.Value); return this.Ok(new { key = dataKey }); })); }
MiscData getMiscData(XmlNode Arg1) { XmlNode var1 = Arg1.SelectSingleNode("MiscData"); string stringData = (var1.SelectSingleNode("UserNote").InnerText); int NoteData = Convert.ToInt32(var1.SelectSingleNode("TypeSelection").InnerText); MiscData retValue = new MiscData(stringData, NoteData); return(retValue); }
public void Back() { if (SceneManager.GetActiveScene().name == "MainMenu") { menuUI.gameObject.SetActive(true); levelSelectionUI.SetActive(false); return; } MiscData.SaveGame(); SceneManager.LoadScene(0); Destroy(gameObject); }
public void InitSaveData() { if (miscData == null) { miscData = new MiscData(); } if (playerRuntimeData == null) { playerRuntimeData = new PlayerRuntimeData(); } miscData.Init(); playerRuntimeData.InitPlayerRuntimeData(playerData); }
/* * Example Argument.ini * [Patient Info = 00] * PATIENT_APPLYNO=0120525150324003 * PATIENT_ID=20120525 * PATIENT_NAME=김유성 * PATIENT_ENAME= * PATIENT_SEX=M * PATIENT_AGE=30 * PATIENT_BIRTH_DATE=19831020 * PATIENT_ADDR= * PATIENT_PID= * PATIENT_IPDOPD= * PATIENT_DOCTOR= * PATIENT_PHON1= * PATIENT_PHON2= * PATIENT_EXAMNAME=TESTEXAM * INPUT_DATE=20120531 */ ///<summary>Launches the program using a command line tools.</summary> public static void SendData(Program ProgramCur, Patient pat) { string path = Programs.GetProgramPath(ProgramCur); try { if (pat != null) { List <ProgramProperty> listProgramProperties = ProgramProperties.GetForProgram(ProgramCur.ProgramNum); ProgramProperty propIniFileLocation = ProgramProperties.GetCur(listProgramProperties, "System path to HDX WILL Argument ini file"); string patientId = pat.PatNum.ToString(); string patientId2 = pat.ChartNumber.ToString(); if (ProgramProperties.GetPropValFromList(listProgramProperties, "Enter 0 to use PatientNum, or 1 to use ChartNum") == "1") { patientId = pat.ChartNumber; patientId2 = pat.PatNum.ToString(); } string filename = propIniFileLocation.PropertyValue; StringBuilder txt = new StringBuilder(); txt.AppendLine("[Patient Info = 00]"); txt.AppendLine("PATIENT_APPLYNO=" + MiscData.GetNowDateTimeWithMilli().ToString("yyyyMMddhhmmssfff").Right(16)); txt.AppendLine("PATIENT_ID=" + patientId); txt.AppendLine("PATIENT_NAME=" + pat.FName + " " + pat.LName); txt.AppendLine("PATIENT_ENAME="); txt.AppendLine("PATIENT_SEX=" + pat.Gender.ToString().Left(1)); txt.AppendLine("PATIENT_AGE=" + pat.Age); txt.AppendLine("PATIENT_BIRTH_DATE=" + pat.Birthdate.ToString("yyyyMMdd")); txt.AppendLine("PATIENT_ADDR=" + pat.Address); txt.AppendLine("PATIENT_PID=" + patientId2); txt.AppendLine("PATIENT_IPDOPD="); txt.AppendLine("PATIENT_DOCTOR=" + Providers.GetFormalName(pat.PriProv)); txt.AppendLine("PATIENT_PHON1=" + pat.WirelessPhone); txt.AppendLine("PATIENT_PHON2=" + pat.HmPhone); txt.AppendLine("PATIENT_EXAMNAME="); txt.AppendLine("INPUT_DATE=" + MiscData.GetNowDateTime().ToString("yyyyMMdd")); ODFileUtils.WriteAllTextThenStart(filename, txt.ToString(), path); return; } } catch (Exception e) { MessageBox.Show(e.Message); } try { ODFileUtils.ProcessStart(path); } catch (Exception e) { MessageBox.Show(path + " is not available."); } }
public async Task <string> CreateOrUpdateAsync(string key, string content) { if (String.IsNullOrEmpty(key) || String.IsNullOrWhiteSpace(key)) { throw new ArgumentException(ErrorMessages.InvalidArguments); } if (String.IsNullOrEmpty(content)) { throw new ArgumentException(ErrorMessages.InvalidArguments); } MiscData data = await this.db.MiscData .Where(d => d.Key == key.ToLower()) .FirstOrDefaultAsync(); if (data == null) { MiscData newData = new MiscData(); newData.Key = key.ToLower(); newData.Value = content; try { await this.db.AddAsync(newData); await this.db.SaveChangesAsync(); } catch (Exception) { throw new InvalidOperationException(ErrorMessages.UnableToWriteToDb); } return(newData.Key); } else { data.Value = content; await this.db.SaveChangesAsync(); return(data.Key); } }
public async Task <string> GetAsync(string key) { if (String.IsNullOrEmpty(key) || String.IsNullOrWhiteSpace(key)) { throw new ArgumentException(ErrorMessages.InvalidArguments); } MiscData data = await this.db.MiscData .Where(d => d.Key == key.ToLower()) .FirstOrDefaultAsync(); if (data == null) { throw new ArgumentException(ErrorMessages.InvalidArguments); } else { return(data.Value); } }
public ItemsData(ArmorData armorData, WeaponsData weaponsData, MiscData miscData) { ArmorData = armorData; WeaponsData = weaponsData; MiscData = miscData; }
public DB_CalendarEventFly(string EventIDData, string Name, DateTimeOffset StartData, DateTimeOffset EndData, int PriorityData, Repetition RepetitionData, Location_Elements LocationData, TimeSpan TImePerSplitData, DateTimeOffset OriginalStartData, TimeSpan EventPrepTimeData, TimeSpan Event_PreDeadlineData, bool EventRigidFlagData, int SplitData, EventDisplay UiData, MiscData NoteData, bool CompletionFlagData, long RepeatIndexData, Procrastination ProcrastinationData, NowProfile NowProfileData, int CompleteCountData, int DeletionCountData, List <string> AllUserIDs) { EventName = Name; StartDateTime = StartData; EndDateTime = EndData; EventRepetition = RepetitionData; LocationInfo = LocationData; TimePerSplit = TImePerSplitData; OriginalStart = OriginalStartData; PrepTime = EventPrepTimeData; EventPreDeadline = Event_PreDeadlineData; ProfileOfNow = NowProfileData; RigidSchedule = EventRigidFlagData; Complete = CompletionFlagData; CompletedCount = CompleteCountData; DeletedCount = DeletionCountData; ProfileOfProcrastination = ProcrastinationData; SubEvents = new Dictionary <EventID, SubCalendarEvent>(); Priority = PriorityData; isRestricted = false; RepetitionSequence = 0; Splits = SplitData; UniqueID = new EventID(EventIDData); UserIDs = AllUserIDs; if (EventRepetition.Enable) { EventRepetition.PopulateRepetitionParameters(this); } else { DateTimeOffset SubEventEndData = EndData; DateTimeOffset SubEventStartData = SubEventEndData - TimePerSplit; int i = 0; int SubEventCount = Splits - (CompletedCount + DeletedCount); for (int j = 0; j < SubEventCount; i++, j++) { EventID SubEventID = EventID.GenerateSubCalendarEvent(UniqueID.ToString(), i + 1); SubCalendarEvent newSubCalEvent = new DB_SubCalendarEventFly(SubEventID, Name, SubEventStartData, SubEventEndData, PriorityData, LocationInfo.CreateCopy(), OriginalStart, EventPrepTimeData, Event_PreDeadlineData, EventRigidFlagData, UiData.createCopy(), NoteData.createCopy(), Complete, ProcrastinationData, NowProfileData, this.RangeTimeLine, EventRepetition.Enable, false, true, AllUserIDs.ToList(), i); SubEvents.Add(newSubCalEvent.SubEvent_ID, newSubCalEvent); } /* * for (int j = 0; j < CompletedCount; i++, j++) * { * EventID SubEventID = EventID.GenerateSubCalendarEvent(UniqueID.ToString(), i + 1); * SubCalendarEvent newSubCalEvent = new DB_SubCalendarEventFly(SubEventID, Name, SubEventStartData, SubEventEndData, PriorityData, LocationInfo.CreateCopy(), OriginalStart, EventPrepTimeData, Event_PreDeadlineData, EventRigidFlagData, UiData.createCopy(), NoteData.createCopy(), Complete, ProcrastinationData, NowProfileData, this.RangeTimeLine, EventRepetition.Enable, true, true, AllUserIDs.ToList(), 0); * SubEvents.Add(newSubCalEvent.SubEvent_ID, newSubCalEvent); * } * * for (int j = 0; j < DeletedCount; i++, j++) * { * EventID SubEventID = EventID.GenerateSubCalendarEvent(UniqueID.ToString(), i + 1); * SubCalendarEvent newSubCalEvent = new DB_SubCalendarEventFly(SubEventID, Name, SubEventStartData, SubEventEndData, PriorityData, LocationInfo.CreateCopy(), OriginalStart, EventPrepTimeData, Event_PreDeadlineData, EventRigidFlagData, UiData.createCopy(), NoteData.createCopy(), Complete, ProcrastinationData, NowProfileData, this.RangeTimeLine, EventRepetition.Enable, true, false, AllUserIDs.ToList(), 0); * SubEvents.Add(newSubCalEvent.SubEvent_ID, newSubCalEvent); * } */ } UpdateLocationMatrix(myLocation); }
static public CalendarEvent InstantiateRepeatedCandidate(EventID EventIDEntry, string EventName, TimeSpan Event_Duration, DateTimeOffset EventStart, DateTimeOffset EventDeadline, DateTimeOffset OriginalStartData, TimeSpan EventPrepTime, TimeSpan Event_PreDeadline, bool EventRigidFlag, Repetition EventRepetitionEntry, int EventSplit, Location_Elements EventLocation, bool enabledFlag, EventDisplay UiData, MiscData NoteData, bool CompletionFlag, long RepeatIndex, ConcurrentDictionary <DateTimeOffset, CalendarEvent> OrginalStartToCalendarEvent, CalendarEvent RepeatRootData) { DB_CalendarEventFly RetValue = new DB_CalendarEventFly(); RetValue.EventName = EventName; RetValue.StartDateTime = EventStart; RetValue.EndDateTime = EventDeadline; RetValue.EventDuration = Event_Duration; RetValue.Enabled = enabledFlag; RetValue.EventRepetition = EventRepetitionEntry; RetValue.PrepTime = EventPrepTime; RetValue.EventPreDeadline = Event_PreDeadline; RetValue.RigidSchedule = EventRigidFlag; RetValue.LocationInfo = EventLocation; RetValue.UniqueID = EventIDEntry; RetValue.UiParams = UiData; RetValue.DataBlob = NoteData; RetValue.Complete = CompletionFlag; RetValue.RepetitionSequence = RepeatIndex; RetValue.OriginalStart = OriginalStartData; RetValue.Splits = EventSplit; RetValue.TimePerSplit = TimeSpan.FromTicks(((RetValue.EventDuration.Ticks / RetValue.Splits))); RetValue.FromRepeatEvent = true; /* * if (RetValue.EventRepetition.Enable) * { * RetValue.Splits = EventSplit; * RetValue.TimePerSplit = new TimeSpan(); * } * else * { * RetValue.Splits = EventSplit; * } */ RetValue.SubEvents = new Dictionary <EventID, SubCalendarEvent>(); if (!RetValue.EventRepetition.Enable) { for (int i = 0; i < RetValue.Splits; i++) { //(TimeSpan Event_Duration, DateTimeOffset EventStart, DateTimeOffset EventDeadline, TimeSpan EventPrepTime, string myParentID, bool Rigid, Location EventLocation =null, TimeLine RangeOfSubCalEvent = null) EventID SubEventID = EventID.GenerateSubCalendarEvent(RetValue.UniqueID.ToString(), i + 1); SubCalendarEvent newSubCalEvent = new DB_SubCalendarEventFly(SubEventID, RetValue.EventName, (RetValue.EndDateTime - RetValue.TimePerSplit), RetValue.EndDateTime, RetValue.Priority, RetValue.myLocation, RetValue.OriginalStart, RetValue.Preparation, RetValue.PreDeadline, RetValue.Rigid, RetValue.UIParam.createCopy(), RetValue.Notes.createCopy(), false, RetValue.ProcrastinationInfo, RetValue.NowInfo, RetValue.RangeTimeLine, true, false, true, RetValue.UserIDs, i); //SubCalendarEvent newSubCalEvent = new SubCalendarEvent(RetValue.TimePerSplit, (RetValue.EndDateTime - RetValue.TimePerSplit), RetValue.End, new TimeSpan(), OriginalStartData, RetValue.UniqueID.ToString(), RetValue.RigidSchedule, RetValue.isEnabled, RetValue.UiParams, RetValue.Notes, RetValue.Complete, i+1, EventLocation, RetValue.RangeTimeLine); RetValue.SubEvents.Add(newSubCalEvent.SubEvent_ID, newSubCalEvent); } } RetValue.EventSequence = new TimeLine(RetValue.StartDateTime, RetValue.EndDateTime); RetValue.RepeatRoot = RepeatRootData; RetValue.UpdateLocationMatrix(RetValue.LocationInfo); while (!OrginalStartToCalendarEvent.TryAdd(OriginalStartData, RetValue)) { Thread.Sleep(10); } return(RetValue); }
public override Task <Tuple <CustomErrors, Dictionary <string, CalendarEvent> > > BundleChangeUpdate(string EventId, EventName NewName, DateTimeOffset newStart, DateTimeOffset newEnd, int newSplitCount, string notes, bool forceRecalculation = false, SubCalendarEvent triggerSubEvent = null) { Task <TilerEvent> pendingNameAndMisc = null; //dynamic pendingNameAndMisc = null; bool useSubEvent = triggerSubEvent != null && triggerSubEvent.NameId.isNot_NullEmptyOrWhiteSpace() && triggerSubEvent.DataBlobId.isNot_NullEmptyOrWhiteSpace(); if (useSubEvent) { if (this.myAccount.ScheduleLogControl.Database != null) { pendingNameAndMisc = Task <TilerEvent> .Run(async() => { SubCalendarEvent subRetValue = await this.myAccount.ScheduleLogControl.Database.SubEvents .Include(eachSubEvent => eachSubEvent.DataBlob_EventDB) .Include(eachSubEvent => eachSubEvent.Name) .Include(eachSubEvent => eachSubEvent.SentimentAnalysis_DB) .FirstAsync(eachSubEvent => eachSubEvent.Id == triggerSubEvent.Id).ConfigureAwait(false); TilerEvent tileRetValue = (TilerEvent)subRetValue; return(tileRetValue); }); } } else { var calEent = getCalendarEvent(EventId); if (calEent != null) { if (this.myAccount.ScheduleLogControl.Database != null) { pendingNameAndMisc = Task <TilerEvent> .Run(async() => { CalendarEvent calRetValue = await this.myAccount.ScheduleLogControl.Database.CalEvents .Include(eachSubEvent => eachSubEvent.DataBlob_EventDB) .Include(eachSubEvent => eachSubEvent.Name) .FirstAsync(eachSubEvent => eachSubEvent.Id == calEent.Id).ConfigureAwait(false); TilerEvent tileRetValue = (TilerEvent)calRetValue; return(tileRetValue); }); } } } var retValue = base.BundleChangeUpdate(EventId, NewName, newStart, newEnd, newSplitCount, notes, forceRecalculation, triggerSubEvent); TilerEvent tilerEvent = null; if (!useSubEvent) { tilerEvent = getCalendarEvent(EventId); } else { tilerEvent = triggerSubEvent; } if (pendingNameAndMisc != null) { pendingNameAndMisc.Wait(); var pendingNameAndMiscResult = pendingNameAndMisc.Result; EventName oldName = pendingNameAndMiscResult.getName; MiscData miscData = pendingNameAndMiscResult.Notes; SentimentAnalysis sentimentAnalysis = pendingNameAndMiscResult.SentimentAnalysis_DB; bool isNameChange = NewName.NameValue != oldName?.NameValue; if (isNameChange) { string emojiString = Task.Run(async() => await OpenAIService.Instance().getEmojis(NewName.NameValue)).GetAwaiter().GetResult(); if (sentimentAnalysis != null) { sentimentAnalysis.updateEmoji(emojiString); } else { sentimentAnalysis = new SentimentAnalysis(); tilerEvent.SentimentAnalysis_DB = sentimentAnalysis; sentimentAnalysis.updateEmoji(emojiString); } tilerEvent.updateEventName(NewName.NameValue); } var note = miscData; if (note != null) { note.UserNote = notes; } } return(retValue); }
/// <summary> /// <para> /// Saves an object to the database. If the IsNew propery of the object is set to false, an existing /// row will be updated. If the IsNew property is set to true, a new row will be created. /// </para> /// <para> /// If the object contains a single PrimaryKey field, with AutoNumber set to true, a new primary key /// will be generated. Depending on the current settings, this may be a new, random key or an incremental /// key. /// </summary> /// <remarks> /// <para> /// When an existing object is saved to the database, only modified values are being sent to the database. /// This is to avoid concurrency issues as much as possible. /// </para> /// <para> /// This method is not thread safe. /// </para> /// </remarks> /// <param name="value">The object to be saved.</param> /// <param name="overrideAutoNumber"> /// Sometimes a new object will be added to the database, but the primary key will be set beforehand. /// To prevent the code (or database) from auto-assigning a new key, this parameter should be set. /// </param> public static void WriteObject(T value, bool overrideAutoNumber) { if (value == null) { throw new ArgumentNullException("value"); } if (value.IsDeleted) { throw new InvalidOperationException(Resources.CannotSaveDeletedObject); } // If the value is not new, and none of the values has changed, there is nothing we // should do. if (!value.IsNew && !value.IsDirty) { return; } // Should we update the primary key? Yes, if the value is new and the data object has a primary key // which is auto-numbered (IDENTITY in SQL). bool updatePrimaryKey = value.IsNew && DataObjectInfo <T> .HasPrimaryKeyWithAutoNumber(); // Make sure the overrideAutoNumber parameter is set only if the code would attempt // to update the primary key. if (overrideAutoNumber && !updatePrimaryKey) { throw new InvalidOperationException(Resources.CannotOverridePrimaryKey); } // If overrideAutoNumber is set, we don't update the primary key -- obviously! if (overrideAutoNumber) { updatePrimaryKey = false; } // Should we generate a new, random key? bool generateRandomKey = updatePrimaryKey && PrefB.RandomKeys; if (generateRandomKey) { int key = MiscData.GetKey(DataObjectInfo <T> .GetTableName(), DataObjectInfo <T> .GetPrimaryKeyFieldName()); DataObjectInfo <T> .SetPrimaryKey(value, key); // The primary key as already been updated. No need to retrieve it from the database. updatePrimaryKey = false; } if (!RemotingClient.OpenDentBusinessIsLocal) { DtoObjectInsertedAck ack = (DtoObjectInsertedAck)FactoryClient <T> .SendRequest("WriteObject", value, new object[] { overrideAutoNumber }); DataObjectInfo <T> .SetPrimaryKeys(value, ack.PrimaryKeys); value.OnSaved(EventArgs.Empty); return; } Collection <DataFieldInfo> dataFields = DataObjectInfo <T> .GetDataFields(DataFieldMask.Data); Collection <DataFieldInfo> primaryKeyFields = DataObjectInfo <T> .GetDataFields(DataFieldMask.PrimaryKey); Collection <DataFieldInfo> allFields = DataObjectInfo <T> .GetDataFields(); if (allFields.Count == 0) { throw new InvalidOperationException(Resources.NoFields); } // In queries, the first field always is special (because of the use of commas). This helper variable // helps us generate correct queries. bool isFirstField = true; using (IDbConnection connection = DataSettings.GetConnection()) using (IDbCommand command = connection.CreateCommand()) { if (useParameters) { // For each field, create a parameter foreach (DataFieldInfo dataField in allFields) { IDbDataParameter parameter = command.CreateParameter(); parameter.ParameterName = ParameterPrefix + dataField.DatabaseName; // Get the value of the field object fieldValue = dataField.Field.GetValue(value); // If the value is of type string and the value is null, we replace it // by an empty string. if (fieldValue == null && dataField.Field.FieldType == typeof(string)) { fieldValue = string.Empty; } parameter.Value = fieldValue; command.Parameters.Add(parameter); } } // Create the SQL query. If it is a new field, create an "INSERT" statement, else // an "UPDATE" statement. StringBuilder commandTextBuilder = new StringBuilder(); if (value.IsNew) { // Create a new row, using an INSERT statement. // The values to set always include the data values (not part of the PK) commandTextBuilder.Append(string.Format("INSERT INTO {0} (", DataObjectInfo <T> .GetTableName())); foreach (DataFieldInfo field in dataFields) { if (isFirstField) { isFirstField = false; } else { commandTextBuilder.Append(','); } commandTextBuilder.Append(field.DatabaseName); } // If the PK is auto-generated, it it shouldn't be included. If the PK is generated by the code // (be it that is some external variable or that the PK is a random number generated previously); // it should be included if (!updatePrimaryKey) { foreach (DataFieldInfo primaryKeyField in primaryKeyFields) { if (isFirstField) { isFirstField = false; } else { commandTextBuilder.Append(','); } commandTextBuilder.Append(primaryKeyField.DatabaseName); } } commandTextBuilder.Append(") VALUES ("); isFirstField = true; foreach (DataFieldInfo field in dataFields) { if (isFirstField) { isFirstField = false; } else { commandTextBuilder.Append(','); } if (useParameters) { commandTextBuilder.Append(ParameterPrefix + field.DatabaseName); } else { commandTextBuilder.AppendFormat("{0}", POut.PObject(field.Field.GetValue(value))); } } if (!updatePrimaryKey) { foreach (DataFieldInfo primaryKeyField in primaryKeyFields) { if (isFirstField) { isFirstField = false; } else { commandTextBuilder.Append(','); } if (useParameters) { commandTextBuilder.Append(ParameterPrefix + primaryKeyField.DatabaseName); } else { commandTextBuilder.AppendFormat("{0}", POut.PObject(primaryKeyField.Field.GetValue(value))); } } } commandTextBuilder.Append(')'); } else { // Update an existing row, using the UPDATE statement. // The WHERE clause contains all PK fields, other data fields go directly into // the SET clause. commandTextBuilder.Append(string.Format("UPDATE {0} SET ", DataObjectInfo <T> .GetTableName())); foreach (DataFieldInfo field in dataFields) { // If the data field has not changed, we don't need to update it -- obviously if (!DataObjectInfo <T> .HasChanged(field, value)) { continue; } if (isFirstField) { isFirstField = false; } else { commandTextBuilder.Append(','); } if (useParameters) { commandTextBuilder.Append(string.Format("{0} = {1}{0}", field.DatabaseName, ParameterPrefix)); } else { commandTextBuilder.Append(string.Format("{0} = {1}", field.DatabaseName, POut.PObject(field.Field.GetValue(value)))); } } commandTextBuilder.Append(" WHERE "); isFirstField = true; foreach (DataFieldInfo field in primaryKeyFields) { if (isFirstField) { isFirstField = false; } else { commandTextBuilder.Append(','); } if (useParameters) { commandTextBuilder.Append(string.Format("{0} = {1}{0}", field.DatabaseName, ParameterPrefix)); } else { commandTextBuilder.Append(string.Format("{0} = {1}", field.DatabaseName, POut.PObject(field.Field.GetValue(value)))); } } } command.CommandText = commandTextBuilder.ToString(); connection.Open(); // This executes the UPDATE/INSERT command. command.ExecuteNonQuery(); // Update the PK if required if (updatePrimaryKey) { // This is currently not implemented for Oracle. Open Dental uses a special mechanism, OracleInsertId, // but using a SEQUENCE might be better. See http://coldfusion.sys-con.com/read/43794.htm . // // For MS SQL (not implemented, either), this would be SCOPE_IDENTITY() if (DataSettings.DbType != DatabaseType.MySql) { throw new NotImplementedException(); } command.CommandText = "SELECT LAST_INSERT_ID()"; // The type returned by command.ExecuteScalar() is System.Int64. // We need to cast it to System.Int32, that's what we use here. int key = Convert.ToInt32(command.ExecuteScalar()); DataObjectInfo <T> .SetPrimaryKey(value, key); } connection.Close(); // The object has been saved value.OnSaved(EventArgs.Empty); } }
internal DB_SubCalendarEventFly(EventID EventIDData, string Name, DateTimeOffset StartData, DateTimeOffset EndData, int PriorityData, Location_Elements LocationData, DateTimeOffset OriginalStartData, TimeSpan EventPrepTimeData, TimeSpan Event_PreDeadlineData, bool EventRigidFlagData, EventDisplay UiData, MiscData NoteData, bool CompletionFlagData, Procrastination ProcrastinationData, NowProfile NowProfileData, TimeLine CalendarEventRangeData, bool FromRepeatFlagData, bool ElapsedFlagData, bool EnabledFlagData, List <string> UserIDData, long Sequence) { this.BusyFrame = new BusyTimeLine(EventIDData.ToString(), StartData, EndData); this.CalendarEventRange = CalendarEventRangeData; this.FromRepeatEvent = FromRepeatFlagData; this.EventName = Name; this.EventDuration = BusyFrame.BusyTimeSpan; this.Complete = CompletionFlagData; this.ConflictingEvents = new ConflictProfile(); this.DataBlob = NoteData; this.DeadlineElapsed = ElapsedFlagData; this.Enabled = EnabledFlagData; this.StartDateTime = StartData; this.EndDateTime = EndData; this.EventPreDeadline = Event_PreDeadlineData; this.RepetitionSequence = Sequence; this.LocationInfo = LocationData; //this.OldPreferredIndex = mySubCalEvent.OldUniversalIndex; //this.otherPartyID = mySubCalEvent.ThirdPartyID; //this.preferredDayIndex = mySubCalEvent.UniversalDayIndex; this.PrepTime = EventPrepTimeData; this.Priority = PriorityData; this.ProfileOfNow = NowProfileData; this.ProfileOfProcrastination = ProcrastinationData; //this.RepetitionFlag = mySubCalEvent.FromRepeat; this.RigidSchedule = EventRigidFlagData; this.UiParams = UiData; this.UniqueID = EventIDData; this.UserIDs = UserIDData; this.OriginalStart = OriginalStartData; }
private void LoadFileData() { Cursor = Cursors.WaitCursor; Metadata = null; DataStream = null; MC02Header = null; OriginalInventoryData = null; NewInventoryData = null; OriginalSafeData = null; NewSafeData = null; OriginalShopData = null; NewShopData = null; OriginalWeaponsData = null; NewWeaponsData = null; MiscData = null; try { using (var fs = File.OpenRead(SaveFilePath)) { DataStream = new MemoryStream(); fs.CopyTo(DataStream); } if (!ValidateSaveFile()) { return; } DataStream.Seek(0x2034, SeekOrigin.Begin); var meta = DataStream.ReadUnicodeString(); var re = new Regex(@"^\D*(\d{1,2})\D*(\d{1,2})\D*(\d{1,2})\D*(\d{1,2})\D*(\d{1,2})\D*(\d{1,2})\D*(\d{1,2})\D*$"); var match = re.Match(meta); if (match.Success) { Metadata = new FileMetadata { Slot = match.Groups[1].Value, HoursPlayed = match.Groups[2].Value, MinutesPlayed = match.Groups[3].Value, SecondsPlayed = match.Groups[4].Value, Difficulty = match.Groups[5].Value, Chapter = match.Groups[6].Value, Round = match.Groups[7].Value }; } OriginalInventoryData = new InventoryData(DataStream); NewInventoryData = new InventoryData { Unk1 = OriginalInventoryData.Unk1, Credits = OriginalInventoryData.Credits, Items = new List <InventoryEntity>(OriginalInventoryData.Items) }; OriginalSafeData = new SafeData(DataStream); NewSafeData = new SafeData { SafeCapacity = OriginalSafeData.SafeCapacity, Unk1 = OriginalSafeData.Unk1, Items = new List <SafeEntity>(OriginalSafeData.Items) }; OriginalShopData = new ShopData(DataStream); NewShopData = new ShopData { Unk1 = OriginalShopData.Unk1, Items = new List <ShopEntity>(OriginalShopData.Items) }; OriginalWeaponsData = new WeaponsData(DataStream); NewWeaponsData = new WeaponsData { ActiveSlots = OriginalWeaponsData.ActiveSlots, Unk1 = OriginalWeaponsData.Unk1, Items = new List <WeaponEntity>(OriginalWeaponsData.Items) }; MiscData = new MiscData(DataStream); } catch (Exception ex) { MessageBox.Show("Sorry, an error occurred while reading from file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } finally { Cursor = Cursors.Default; } }
public DB_ProcrastinateCalendarEvent(EventID procrasstinaeAllId, EventName NameEntry, DateTimeOffset StartData, DateTimeOffset EndData, TimeSpan EventDuration, TimeSpan eventPrepTime, TimeSpan PreDeadlineTimeSpan, Repetition EventRepetitionEntry, TilerElements.Location EventLocation, EventDisplay UiData, MiscData NoteData, bool EnabledEventFlag, bool CompletionFlag, TilerUser creator, TilerUserGroup users, string timeZone, int splitCount, NowProfile nowProfile) : base(procrasstinaeAllId, NameEntry, StartData, EndData, EventDuration, eventPrepTime, PreDeadlineTimeSpan, EventRepetitionEntry, EventLocation, UiData, NoteData, EnabledEventFlag, CompletionFlag, creator, users, timeZone, splitCount, nowProfile) { UniqueID = procrasstinaeAllId; }
public bool OpenConnection(string connectionString) { if (string.IsNullOrWhiteSpace(connectionString)) { Logger.Log(this, "Unable to connect to the SQL database: No connection specified.", LogLevel.Error); return(false); } internalState = ConnectionState.Connecting; connection = PostgreSQLTools.CreateDataConnection(connectionString); internalState = ConnectionState.Open; connection.OnClosing += (sender, args) => internalState = ConnectionState.Closed; connection.OnClosed += (sender, args) => internalState = ConnectionState.Closed; metadata = connection.GetTable <Metadata>(); try { var version = from entry in metadata where entry.Key == "version" select entry.Value; var count = version.Count(); if (count != 1) { Logger.Log(this, "Zero or multiple 'version' entries found in the Metadata table. The database connection will be dropped.", LogLevel.Error); HandleConnectionFailure(); return(false); } if (version.First() != Bot.DatabaseVersion) { Logger.Log(this, $"Bot and database version do not match (bot is at {Bot.DatabaseVersion}, database is at {version.First()}). The database will now be upgraded.", LogLevel.Info); if (!UpgradeDatabase(version.First())) { Logger.Log(this, "Upgrade failed. The database connection will be dropped.", LogLevel.Warning); HandleConnectionFailure(); return(false); } } } catch (NpgsqlException e) { if (e.Message.ToLower().Contains("metadata") && e.Message.ToLower().Contains("does not exist")) { Logger.Log(this, "Metadata table not found. A new tableset will be created.", LogLevel.Warning); try { DropTables(); CreateTables(); } catch (NpgsqlException f) { Logger.Log(this, $"Unable to create a new tableset: An exception occurred({f.GetType()}: {f.Message}). The database connection will be dropped.", LogLevel.Error); HandleConnectionFailure(); return(false); } AddMetadata(); Logger.Log(this, "Writing metadata...", LogLevel.Info); } else { Logger.Log(this, $"Unable to retrieve the database version: An exception occurred ({e.GetType()}: {e.Message}). The database connection will be dropped.", LogLevel.Error); HandleConnectionFailure(); return(false); } } //UserCredentials = connection.GetTable<UserCredential>(); Quotes = connection.GetTable <Quote>(); UserStatistics = connection.GetTable <UserStatistic>(); Emoticons = connection.GetTable <UsedEmoticon>(); KeyValuePairs = connection.GetTable <KeyValuePair>(); LinkedUrls = connection.GetTable <LinkedUrl>(); Users = connection.GetTable <User>(); Words = connection.GetTable <UsedWord>(); ChatLog = connection.GetTable <ChatLog>(); MiscData = connection.GetTable <MiscData>(); try { // These methods are actually not pure, because they'll throw an exception // if their backing database tables are not found. It's a bit of a hack, // but this is the easiest way to check whether those tables exist. // ReSharper disable ReturnValueOfPureMethodIsNotUsed //UserCredentials.FirstOrDefault(); Quotes.FirstOrDefault(); UserStatistics.FirstOrDefault(); Emoticons.FirstOrDefault(); KeyValuePairs.FirstOrDefault(); LinkedUrls.FirstOrDefault(); Users.FirstOrDefault(); Words.FirstOrDefault(); ChatLog.FirstOrDefault(); MiscData.FirstOrDefault(); // ReSharper restore ReturnValueOfPureMethodIsNotUsed } catch (Exception e) { Logger.Log(this, $"Database integrity check failed ({e.GetType().Name}: {e.Message})", LogLevel.Error); HandleConnectionFailure(); return(false); } return(true); }