//private static bool startup = false; public GameController() { Debug.Log("GameController."); CurrentGameMode = GameMode.NORMAL; GameControlProxy.add(this); WindowConfigure.initAll(); if (Rnd == null) Rnd = new RndGenerator((int)System.DateTime.Now.Ticks); if (GameActionEvent == null) GameActionEvent = new GameActionEvent(); if (PlayingLogger == null) PlayingLogger = new PlayLogger(); if (DungeonInformation == null) DungeonInformation = new DungeonInformation(); if (ObjectList == null) ObjectList = new ObjectList(); if (DgParameterTable == null) DgParameterTable = new DungeonParameterTable(5); if (SoundController == null) SoundController = SoundController.Instance; if (TempGameState == null) TempGameState = new Stack<GameState>(); if (ActCommandController == null) ActCommandController = new ActionCommandController(); if (GlobalGameInformation == null) GlobalGameInformation = new GlobalGameInformation(); if (SystemConfigure == null) SystemConfigure = new SystemConfigure(); if (SystemConfigureMenu == null) SystemConfigureMenu = new GameSystemConfigureMenu(); DataSaveSystem.addGameActionEvent(); //var t = new TagList(); SaveDataConverter.add(this); //PlayerUIController.setVisible(false); gameStateChange(GameState.PRELOAD); filedModeChange(FieldMode.TOWN); }
public DebtListNoticesForm(DebtDocument debtDocument, ObjectList<Account> selectedAccounts) { this.InitializeComponent(); this.set_Font(Manager.WindowFont); this.m_debtDocument = debtDocument; this.m_SelectedAccounts = selectedAccounts; }
public DebtAccountPrintForm(DebtDocument debtDocument, PrintEnum printEnum, ObjectList<Account> selectedAccounts) : this() { this.m_debtDocument = debtDocument; this.m_printEnumType = printEnum; this.m_SelectedAccounts = selectedAccounts; }
protected override void Fill(ObjectWithId obj) { this.m_Area = (Area) obj; this.tbName.set_Text(this.m_Area.Name); this.btnAddresses.set_Enabled(true); this.addressesDest = this.m_Area.GetLocalAddresses(); }
public DebtAccountPrintForm() { this.m_debtDocument = DebtDocument.Null; this.m_SelectedAccounts = new ObjectList<Account>(); this.InitializeComponent(); this.set_Font(Manager.WindowFont); }
private void ApartmentResidentBenefitPropertiesForm_Load(object sender, System.EventArgs e) { this.selectTypeEDK.Faset = FasetsEnum.TypeEDK; this.selectTypeEDK.RefreshValuesWithNull(); this.selectTypeEDK.SelectedFasetItem = FasetItem.Null; this.tbFIO.set_Text(this.m_ApartmentResident.PersonName); ObjectList<Bank> list = new ObjectList<Bank> { Bank.Null }; list.AddRange(Bank.FindAll()); this.bsBank.set_DataSource(list); if (this.m_ApartmentResidentBenefitProperty == null) { this.btOK.set_Text("Добавить"); this.set_Text("Добавление"); } else { this.btOK.set_Text("Изменить"); this.set_Text("Изменение"); this.bsBank.set_Position(this.bsBank.Find("shortName", this.m_ApartmentResidentBenefitProperty.BankName)); this.selectTypeEDK.SelectedFasetItem = this.m_ApartmentResidentBenefitProperty.GetKind(); this.dbxFromDate.Value = this.m_ApartmentResidentBenefitProperty.FromDate; this.dbxCreated.Value = this.m_ApartmentResidentBenefitProperty.Created; } }
public HouseServiceTariffAddChangeForm(AIS.SN.Model.DomainObjects.HouseServiceTariff tariff) { this.InitializeComponent(); this.bsServiceTypes.set_DataSource(ServiceType.GetAllSort()); this.set_Text("Редактирование тарифа на дом"); this.HouseServiceTariff = tariff; this.nudTariffRate.set_Value(tariff.Rate); if (tariff.ServiceId > 0L) { this.rbService.set_Checked(true); this.selectServices.set_Enabled(true); ServiceOld old = ServiceOld.FindById(tariff.ServiceId); ObjectList<ServiceOld> list = new ObjectList<ServiceOld> { old }; this.selectServices.SelectedServices = list; } else { this.selectServices.set_Enabled(false); } ServiceTypeOld old2 = ServiceTypeOld.FindById(tariff.ServiceTypeId); this.cbServiceTypes.set_SelectedItem(old2); OrgDocument document = OrgDocument.FindById(tariff.DocId); this.selectOrgDocument.SelectedOrgDocument = document; this.dbTariffDate.Value = tariff.FromDate; this.flag = false; }
public void AddGroupOrSets(AreaGroup groupSets, ObjectList<Area> area) { foreach (Area area2 in area) { Area area3 = new Area(); AreaGroup group = groupSets; area3.Name = area2.Name; if ((groupSets != null) && (groupSets.Id != -1L)) { area3.AreaGroupId = group.Id; } try { area3.SaveChanges(); area3.SaveAddresses(area2.GetAddresses()); } catch (System.Exception exception) { Messages.ShowException(this, exception); break; } if ((area2 != null) && (area2.Id != -1L)) { this.SetAreas(group.GetAreas()); } } }
public System.Data.DataSet FindByAccount(ObjectList<Organization> providers, ObjectList<Organization> holders, ObjectList<ServiceTypeOld> serviceTypes, ObjectList<ServiceOld> services, Account account, System.DateTime period, bool isReport, long apartmentTypeId, System.DateTime periodPayment, FasetItem cityBoroughs, ObjectList<Organization> accountHolders) { ObjectList<Account> accounts = new ObjectList<Account> { account }; return this.FindByAccounts(providers, holders, serviceTypes, services, accounts, period, Constants.NullDate, isReport, apartmentTypeId, periodPayment, cityBoroughs, accountHolders); }
public void ClearSelected() { this.SelectedBanks = null; if (this.OnBanksSelected != null) { this.OnBanksSelected(null); } }
void Start() { inspector = GameObject.Find ("Inspector").GetComponent ("Inspector") as Inspector; objectList = GameObject.Find ("ObjectList").GetComponent ("ObjectList") as ObjectList; parameterList = GameObject.Find ("ParameterList").GetComponent ("ParameterList") as ParameterList; startPosition = transform.position; startRotation = transform.eulerAngles; }
public ProcessPaymentOtherGroupForm(ObjectList<AccountOther> account, POSView printPOS) { this.m_NumberFormat.set_NumberDecimalSeparator("."); this.m_NumberFormat.set_NumberDecimalDigits(2); this.m_AllAccounts = account; this.m_PrintPOS = printPOS; this.InitializeComponent(); }
public AccountRecalcSelectServicesForSavingForm(ObjectList<AccountService> recalcAccountServices) : this() { if (recalcAccountServices != null) { this.m_RecalcAccountServices = recalcAccountServices; } }
public UjfSelectCommitteeForm() { this.selectedOrgPersonnel = new ObjectList<UjfOrganizationPersonnel>(); this.InitializeComponent(); this.set_Font(Manager.WindowFont); this.organizationId = User.CurrentUser.OrgId; this.UpdateByOrganizationPersonnels(); }
public void Selected(ObjectList<Bank> banks) { this.SelectedBanks = banks; if (this.OnBanksSelected != null) { this.OnBanksSelected(banks); } }
protected override void onPartStart() { if ((windowPos.x == 0) && (windowPos.y == 0))//windowPos is used to position the GUI window, lets set it in the center of the screen { windowPos = new Rect(Screen.width / 2, Screen.height / 2, 10, 10); } objectList = new ObjectList<Vessel>(vessel); }
void Awake() { if (beaconList == null) { beaconList = new ObjectList(); } beaconList.addObject (this.gameObject); }
public PayPaymentOrderSearchForm() { this.InitializeComponent(); if (!base.get_DesignMode()) { this.m_PaymentOrders = new ObjectList<PayPaymentOrder>(); } }
public HouseCommonServicesForm(Apartment apartment, System.DateTime fromDate, System.DateTime toDate, ObjectList<ServiceOld> services) : this() { this.m_Apartment = apartment; this.m_FromDate = fromDate; this.m_ToDate = toDate; this.result = services; }
public void ClearSelected() { this.SelectedOrgPersonnel = null; if (this.OnOrganizationPersonnelSelected != null) { this.OnOrganizationPersonnelSelected(null); } }
public ApartmentResidentBenefitChangeForm(ObjectList<ApartmentResidentBenefit> listApartmentResidentBenefit, bool isFromDateEnable, bool isToDateEnable, System.DateTime apartmentResidentToDate) : this() { this.laprb = listApartmentResidentBenefit; this.m_IsFromDateEnable = isFromDateEnable; this.m_IsToDateEnable = isToDateEnable; this.apToDate = apartmentResidentToDate; }
public ApartmentCounterAddChangeForm() { this.m_ApartmentCounter = ApartmentCounter.Null; this.m_ToDate = Constants.NullDate; this.m_FromDate = Constants.NullDate; this.m_SelectedAccountServiceCounters = new ObjectList<AccountServiceCounter>(); this.m_act = true; this.InitializeComponent(); }
public AccountantMainForm() { base.SuspendLayout(); this.InitializeComponent(); this.set_Font(Manager.WindowFont); this.menuStrip.set_Font(Manager.WindowFont); this.findHistory = new ObjectList<Apartment>(); base.ResumeLayout(); }
public AreaAddressesForm(ObjectList<LocalAddress> AddressesSource, ObjectList<LocalAddress> AddressesDest) : this() { this.addressesSource = new ObjectList<LocalAddress>(); this.addressesSource.AddRange(AddressesSource); this.addressesDest = new ObjectList<LocalAddress>(); this.addressesDest.AddRange(AddressesDest); this.addressesSelectControl1.Fill(this.addressesSource, this.param); }
public void AddTree(AreaAddressesTree areaAddressesTreeSource) { System.Collections.Generic.List<System.Windows.Forms.TreeNode> selectedNodes = areaAddressesTreeSource.SelectedNodes; areaAddressesTreeSource.Remove(); foreach (System.Windows.Forms.TreeNode node in selectedNodes) { AddressesNode node2 = (AddressesNode) node; node2.NullDelete(); if (node2.Nodes.get_Count() == 0) { this.RemoveNode(node2); this.AddNode(new AddressesNode((LocalAddress) node2.get_Tag())); } else { ObjectList<LocalAddress> addresses = new ObjectList<LocalAddress>(); this.GetLeaves(addresses, node2); if (addresses.get_Count() != 0) { foreach (LocalAddress address in addresses) { AddressesNode nodeByAddress = this.GetNodeByAddress(address); if (nodeByAddress != null) { this.RemoveNode(nodeByAddress); } this.AddNode(new AddressesNode(address)); } } } } base.Sort(); this.OnPaintRoots(); areaAddressesTreeSource.OnPaintRoots(); if (selectedNodes.get_Count() != 0) { System.Collections.Generic.List<System.Windows.Forms.TreeNode> list3 = new System.Collections.Generic.List<System.Windows.Forms.TreeNode>(); foreach (System.Windows.Forms.TreeNode node4 in selectedNodes) { AddressesNode node5 = this.GetNode(this, (AddressesNode) node4); if (node5 != null) { list3.Add(node5); if (node5.Parent != null) { node5.Parent.EnsureVisible(); node5.Parent.Expand(); } } } base.SelectedNodes = list3; if (this.OnChangeSelectAddresses != null) { this.OnChangeSelectAddresses(); } } }
public AreaAddressesForm(Area area) : this() { this.m_Area = area ?? Area.Null; if (this.m_Area == Area.Null) { this.addressesSource = new ObjectList<LocalAddress>(); this.addressesDest = new ObjectList<LocalAddress>(); } }
protected override void SelectObject(object sender, System.EventArgs e) { ServicesForm form = new ServicesForm { IsMultiSelect = true }; form.SetFilter(this.FilterServiceProvider, this.FilterServiceTypes, this.addressesSource, this.addressesDest, this.ServicesOld); form.ShowDialog(this); this.ServicesOld = form.SelectedServices; this.FillServices(); }
public void DateTimeListSerializationTest() { ObjectList dataToSerialize = new ObjectList(); byte[] data = SerializationUtil.SerializeData(dataToSerialize); Assert.IsNotNull(data); Assert.AreNotEqual(0, data.Length); ObjectList deserializedData = SerializationUtil.DeserializeData<ObjectList>(data); Assert.IsNotNull(deserializedData); Assert.AreNotSame(dataToSerialize, deserializedData); }
public void Search() { System.DateTime timeBegin = this.dpRangeDates.TimeBegin; System.DateTime timeEnd = this.dpRangeDates.TimeEnd; string account = this.tbxAccount.get_Text().Trim(); this.PayRequestGatesResulting = PayRequestGate.FindBy(account, timeBegin, timeEnd, this.sfdStatuses.SelectedFasetItem, this.rbOnlyConfirmed.get_Checked(), this.rbOnlyNotConfirmed.get_Checked(), (int) this.numTopRecordCount.Value); if (this.OnSearchRequestGates != null) { this.OnSearchRequestGates(this.PayRequestGatesResulting); } }
public static void ShowDialog(System.Windows.Forms.IWin32Window owner, System.DateTime date, ObjectList<LocalAddress> addresses) { System.Data.DataSet accountServiceByAddressesReport = GroupOperation.GetAccountServiceByAddressesReport(date, addresses); accountServiceByAddressesReport.Tables.get_Item(0).set_TableName("dataAccountServices"); accountServiceByAddressesReport.Tables.get_Item(1).set_TableName("date"); StiReport report = new StiReport(); report.Load(Resources.Rep_AccountServicesByAddresses); report.Compile(); report.RegData((System.Data.DataSet) accountServiceByAddressesReport); report.Show((System.Windows.Forms.IWin32Window) owner); }
/// <summary> /// Инициализация /// </summary> protected override void CreatePreDefinedFields() { #region необходимые операции до создания реквизитов и заполнения полей if (NsgSettings.Regime == NsgSoft.Common.NsgViewTypes.Load) { base.CreatePreDefinedFields(); } #endregion //необходимые операции до создания реквизитов и заполнения полей #region создание System.String Расход { NsgDataEnumElement асход = null; if (ObjectList.Contains("Расход")) { асход = ObjectList["Расход"] as NsgDataEnumElement; } else { асход = new NsgDataEnumElement(); } //NsgDataEnumElement асход.IsLoadedFromDll = true; асход.IndexType = NsgSoft.Database.NsgRekvisitIndexType.None; асход.Index = -1; асход.StringFormat = ""; асход.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; асход.IncludeInPredefined = false; асход.PeriodicType = NsgSoft.Database.PeriodicTypes.None; асход.Required = false; асход.EmptyValue = ""; асход.NullAllow = false; асход.FieldName = "Raskhod"; асход.SaveInDatabase = true; асход.InformMetaDataOnValueChanged = false; асход.Visible = true; асход.Name = "Расход"; асход.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); асход.Description = "Расход"; асход.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.ReadOnly; асход.GroupName = ""; асход.Guid = NsgService.StringToGuid("061de208-747c-4a55-a04e-a021f3ba6634"); if (!ObjectList.Contains("Расход")) { ObjectList.Add(асход); } } #endregion //создание System.String Расход #region создание System.String Приход { NsgDataEnumElement Приход = null; if (ObjectList.Contains("Приход")) { Приход = ObjectList["Приход"] as NsgDataEnumElement; } else { Приход = new NsgDataEnumElement(); } //NsgDataEnumElement Приход.IsLoadedFromDll = true; Приход.IndexType = NsgSoft.Database.NsgRekvisitIndexType.None; Приход.Index = 1; Приход.StringFormat = ""; Приход.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; Приход.IncludeInPredefined = false; Приход.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Приход.Required = false; Приход.EmptyValue = ""; Приход.NullAllow = false; Приход.FieldName = "Prikhod"; Приход.SaveInDatabase = true; Приход.InformMetaDataOnValueChanged = false; Приход.Visible = true; Приход.Name = "Приход"; Приход.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Приход.Description = "Приход"; Приход.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.ReadOnly; Приход.GroupName = ""; Приход.Guid = NsgService.StringToGuid("5b0a00dd-3e3f-42cc-b852-401e904cc34d"); if (!ObjectList.Contains("Приход")) { ObjectList.Add(Приход); } } #endregion //создание System.String Приход #region заполнение полей класса //NsgDataEnum IsLoadedFromDll = true; EntityType = NsgSoft.DataObjects.NsgInterfacedObject.EntityTypes.Object; Name = "ВидыДвижений"; Visible = true; Guid = NsgService.StringToGuid("2df52aed-43af-454e-9d12-e5b9181d5de3"); DefaultSortingName = ""; DefaultElementFormName = ""; DefaultListFormName = ""; ValueMask = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "{Представление}" }); SearchType = NsgSoft.Database.NsgComparison.Contain; SearchFieldName = ""; DatabaseName = ""; VisibleAdminOnly = false; TableName = "MovementSign"; Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Description = "Виды движений"; EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Full; GroupName = "Сервис"; #endregion //заполнение полей класса #region необходимые операции после создания реквизитов и заполнения полей #endregion //необходимые операции после создания реквизитов и заполнения полей }
public override void Add(PwDeletedObjectBuffer item) { ObjectList.Add(item.DeletedObject); }
/// <summary>Hides an object within the world</summary> /// <param name="ObjectIndex">The object's index</param> internal static void HideObject(int ObjectIndex) { if (ObjectManager.Objects[ObjectIndex] == null) { return; } int k = ObjectManager.Objects[ObjectIndex].RendererIndex - 1; if (k >= 0) { // remove faces for (int i = 0; i < Objects[k].FaceListReferences.Length; i++) { ObjectListType listType = Objects[k].FaceListReferences[i].Type; if (listType == ObjectListType.StaticOpaque) { /* * For static opaque faces, set the face to be removed * to a null reference. If there are null entries at * the end of the list, update the number of faces used * accordingly. * */ int groupIndex = (int)ObjectManager.Objects[Objects[k].ObjectIndex].GroupIndex; ObjectList list = StaticOpaque[groupIndex].List; int listIndex = Objects[k].FaceListReferences[i].Index; list.Faces[listIndex] = null; if (listIndex == list.FaceCount - 1) { int count = 0; for (int j = list.FaceCount - 2; j >= 0; j--) { if (list.Faces[j] != null) { count = j + 1; break; } } list.FaceCount = count; } StaticOpaque[groupIndex].Update = true; Game.InfoStaticOpaqueFaceCount--; } else { /* * For all other kinds of faces, move the last face into place * of the face to be removed and decrement the face counter. * */ ObjectList list; switch (listType) { case ObjectListType.DynamicOpaque: list = DynamicOpaque; break; case ObjectListType.DynamicAlpha: list = DynamicAlpha; break; case ObjectListType.OverlayOpaque: list = OverlayOpaque; break; case ObjectListType.OverlayAlpha: list = OverlayAlpha; break; default: throw new InvalidOperationException(); } int listIndex = Objects[k].FaceListReferences[i].Index; list.Faces[listIndex] = list.Faces[list.FaceCount - 1]; Objects[list.Faces[listIndex].ObjectListIndex].FaceListReferences[list.Faces[listIndex].FaceIndex].Index = listIndex; list.FaceCount--; } } // remove object if (k == ObjectCount - 1) { ObjectCount--; } else { Objects[k] = Objects[ObjectCount - 1]; ObjectCount--; for (int i = 0; i < Objects[k].FaceListReferences.Length; i++) { ObjectListType listType = Objects[k].FaceListReferences[i].Type; ObjectList list; switch (listType) { case ObjectListType.StaticOpaque: { int groupIndex = (int)ObjectManager.Objects[Objects[k].ObjectIndex].GroupIndex; list = StaticOpaque[groupIndex].List; } break; case ObjectListType.DynamicOpaque: list = DynamicOpaque; break; case ObjectListType.DynamicAlpha: list = DynamicAlpha; break; case ObjectListType.OverlayOpaque: list = OverlayOpaque; break; case ObjectListType.OverlayAlpha: list = OverlayAlpha; break; case ObjectListType.Touch: list = Touch; break; default: throw new InvalidOperationException(); } int listIndex = Objects[k].FaceListReferences[i].Index; list.Faces[listIndex].ObjectListIndex = k; } ObjectManager.Objects[Objects[k].ObjectIndex].RendererIndex = k + 1; } ObjectManager.Objects[ObjectIndex].RendererIndex = 0; } }
private ObjectList<Recording> GetRecordings() { if (recordings == null) { recordings = transaction.Document.GetRecordings(transaction); } return recordings; }
void userfiles_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { kbsellgasbusy.IsBusy = false; busy.IsBusy = false; if (e.Error != null) { MessageBox.Show("查询失败,链接错误!"); return; } //把数据转换成JSON JsonObject item = JsonValue.Parse(e.Result) as JsonObject; if (item.ContainsKey("error")) { string error = item["error"]; MessageBox.Show("查询失败:" + error); busy.IsBusy = false; return; } //把用户数据写到交费界面上 ui_username.Text = (string)item["f_username"]; ui_usertype.Text = (string)item["f_usertype"]; ui_districtname.Text = (string)item["f_districtname"]; ui_gasproperties.Text = (string)item["f_gasproperties"]; ui_stairpricetype.Text = (string)item["f_stairtype"]; zhye.Text = item["f_zhye"].ToString(); ui_address.Text = (string)item["f_address"]; //ui_gaspricetype.Text = (String)item["f_gaspricetype"]; ui_userid.Text = (string)item["infoid"]; zhe.Text = item["f_zherownum"].ToString(); //ui_dibaohu.IsChecked = item["f_dibaohu"].ToString().Equals("1"); ui_userstate.Text = (string)item["f_userstate"]; ui_paytype.Text = (string)item["f_payment"]; // ui_gasprice.Text = item["f_gasprice"].ToString(); //把欠费数据插入到欠费表中 ObjectList list = new ObjectList(); // 当前正在处理的表号 String currentId = ""; // 总的上期指数 decimal lastnum = 0; // 总气量 decimal gasSum = 0; // 总气费 decimal feeSum = 0; //总的滞纳金 decimal zhinajinAll = 0; //余额 decimal f_zhye = decimal.Parse(item["f_zhye"].ToString()); JsonArray bills = item["f_hands"] as JsonArray; foreach (JsonObject json in bills) { GeneralObject go = new GeneralObject(); go.EntityType = "t_handplan"; //默认选中 go.IsChecked = true; //上期指数 decimal lastinputgasnum = (decimal)json["lastinputgasnum"]; go.SetPropertyValue("lastinputgasnum", lastinputgasnum, false); string f_userid = (string)json["f_userid"]; go.SetPropertyValue("f_userid", f_userid, false); // 如果表号变了 if (!f_userid.Equals(currentId)) { currentId = f_userid; lastnum += lastinputgasnum; } //计算总金额 decimal oughtfee = (decimal)json["oughtfee"]; go.SetPropertyValue("oughtfee", oughtfee, false); feeSum += oughtfee; // 计算总气量 decimal oughtamount = (decimal)json["oughtamount"]; gasSum += oughtamount; go.SetPropertyValue("oughtamount", oughtamount, false); int id = (int)json["id"]; go.SetPropertyValue("id", id, false); //计算总滞纳金 decimal f_zhinajin = (decimal)json["f_zhinajin"]; zhinajinAll += f_zhinajin; go.SetPropertyValue("f_zhinajin", f_zhinajin, true); go.SetPropertyValue("lastinputdate", DateTime.Parse(json["lastinputdate"]), false); go.SetPropertyValue("lastrecord", (decimal)json["lastrecord"], false); go.SetPropertyValue("f_endjfdate", DateTime.Parse(json["f_endjfdate"]), false); go.SetPropertyValue("f_zhinajintianshu", (int)json["days"], false); go.SetPropertyValue("f_network", (string)json["f_network"], false); go.SetPropertyValue("f_operator", (string)json["f_operator"], false); go.SetPropertyValue("f_inputdate", DateTime.Parse(json["f_inputdate"]), false); go.SetPropertyValue("f_userid", (string)json["f_userid"], false); go.SetPropertyValue("f_stair1amount", (decimal)json["f_stair1amount"], false); go.SetPropertyValue("f_stair1price", (decimal)json["f_stair1price"], false); go.SetPropertyValue("f_stair1fee", (decimal)json["f_stair1fee"], false); go.SetPropertyValue("f_stair2amount", (decimal)json["f_stair2amount"], false); go.SetPropertyValue("f_stair2price", (decimal)json["f_stair2price"], false); go.SetPropertyValue("f_stair2fee", (decimal)json["f_stair2fee"], false); go.SetPropertyValue("f_stair3amount", (decimal)json["f_stair3amount"], false); go.SetPropertyValue("f_stair3price", (decimal)json["f_stair3price"], false); go.SetPropertyValue("f_stair3fee", (decimal)json["f_stair3fee"], false); go.SetPropertyValue("number", (decimal)json["number"], false); list.Add(go); } dataGrid1.ItemsSource = list; // 计算出来的总气量等放到用户界面上 ui_pregas.Text = gasSum.ToString("0.#"); //总气量 ui_lastinputgasnum.Text = lastnum.ToString("0.#"); //总上期底数 ui_lastrecord.Text = (lastnum + gasSum).ToString("0.#"); //总本期底数 ui_zhinajin.Text = zhinajinAll.ToString("0.##"); //总滞纳金 ui_linshizhinajin.Text = zhinajinAll.ToString("0.##"); //滞纳金 ui_preamount.Text = feeSum.ToString("0.##"); //气费金额 decimal f_totalcost = feeSum - f_zhye + zhinajinAll > 0 ? feeSum - f_zhye + zhinajinAll : 0; ui_totalcost.Text = f_totalcost.ToString("0.##");//应缴金额 decimal f_benqizhye = (decimal)(f_zhye - feeSum - zhinajinAll > 0 ? f_zhye - feeSum - zhinajinAll : 0); ui_benqizhye.Text = f_benqizhye.ToString("0.##");//本期结余 shoukuan.Text = f_totalcost.ToString("0.##"); }
void Start() { ObjectList.AddPuddleList(gameObject); }
/// <summary> /// Return an IEnumerable providing data for use with the /// supplied parameter. /// </summary> /// <param name="parameter">A ParameterInfo representing one /// argument to a parameterized test</param> /// <returns> /// An IEnumerable providing the required data /// </returns> public System.Collections.IEnumerable GetDataFor(System.Reflection.ParameterInfo parameter) { ObjectList datapoints = new ObjectList(); Type parameterType = parameter.ParameterType; Type fixtureType = parameter.Member.ReflectedType; foreach (MemberInfo member in fixtureType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)) { if (member.IsDefined(typeof(DatapointAttribute), true)) { if (GetTypeFromMemberInfo(member) == parameterType && member.MemberType == MemberTypes.Field) { FieldInfo field = member as FieldInfo; if (field.IsStatic) { datapoints.Add(field.GetValue(null)); } else { datapoints.Add(field.GetValue(ProviderCache.GetInstanceOf(fixtureType))); } } } else if (member.IsDefined(typeof(DatapointSourceAttribute), true)) { if (GetElementTypeFromMemberInfo(member) == parameterType) { object instance; switch (member.MemberType) { case MemberTypes.Field: FieldInfo field = member as FieldInfo; instance = field.IsStatic ? null : ProviderCache.GetInstanceOf(fixtureType); foreach (object data in (IEnumerable)field.GetValue(instance)) { datapoints.Add(data); } break; case MemberTypes.Property: PropertyInfo property = member as PropertyInfo; MethodInfo getMethod = property.GetGetMethod(true); instance = getMethod.IsStatic ? null : ProviderCache.GetInstanceOf(fixtureType); foreach (object data in (IEnumerable)property.GetValue(instance, null)) { datapoints.Add(data); } break; case MemberTypes.Method: MethodInfo method = member as MethodInfo; instance = method.IsStatic ? null : ProviderCache.GetInstanceOf(fixtureType); foreach (object data in (IEnumerable)method.Invoke(instance, new Type[0])) { datapoints.Add(data); } break; } } } } if (datapoints.Count == 0) { if (parameterType == typeof(bool)) { datapoints.Add(true); datapoints.Add(false); } else if (parameterType.IsEnum) { datapoints.AddRange(TypeHelper.GetEnumValues(parameterType)); } } return(datapoints); }
public Module(string line) { string param; ObjectType = PCBObjectType.Module; Designator = ""; Comment = ""; Name = GetString(line, "|PATTERN="); ComponentKind = GetString(line, "|COMPONENTKIND="); if (Name.Contains("\\")) { Name = Name.Replace("\\", "_"); // TODO check this out } if (Name.Contains("\"")) { Name = Name.Replace("\"", "_"); } if ((param = GetString(line, "|X=").Trim(charsToTrim)) != "") { X = GetCoordinateX(param); } if ((param = GetString(line, "|Y=").Trim(charsToTrim)) != "") { Y = GetCoordinateY(param); } Layer = ""; if ((param = GetString(line, "|LAYER=")) != "") { Layer = Brd.GetLayer(param); } DesignatorOn = true; if ((param = GetString(line, "|NAMEON=")) != "") { DesignatorOn = param == "TRUE"; } CommentOn = true; if ((param = GetString(line, "|COMMENTON=")) != "") { CommentOn = param == "TRUE"; } Locked = false; if ((param = GetString(line, "|LOCKED=")) != "") { Locked = param == "TRUE"; } PrimitiveLock = false; if ((param = GetString(line, "|PRIMITIVELOCK=")) != "") { PrimitiveLock = param == "TRUE"; } Rotation = 0; if ((param = GetString(line, "|ROTATION=").Trim(charsToTrim)) != "") { Rotation = Convert.ToDouble(param); if (Rotation == 360) { Rotation = 0; } } if (Layer == "F.Cu" || Layer == "B.Cu") { Attr = "smd"; } else { Attr = ""; } if (ComponentKind == "1" || ComponentKind == "2" || ComponentKind == "4") { Attr = "virtual"; } Tedit = "(tedit 0)"; Tstamp = "(tstamp 0)"; // create the object lists for this component Lines = new ObjectList <Line>(); Pads = new ObjectList <Pad>(); Strings = new ObjectList <String>(); ViasL = new ObjectList <Via>(); Arcs = new ObjectList <Arc>(); Fills = new ObjectList <Fill>(); Polygons = new ObjectList <Polygon>(); Regions = new ObjectList <Region>(); ComponentBodies = new ObjectList <ComponentBody>(); ShapeBasedModels = new ObjectList <ShapeBasedModel>(); ID++; // update for next Module }
public override void Add(PwEntryBuffer item) { ObjectList.Add(item.Entry); }
private void AddAdditionalDataObjectsToList() { ObjectList.Add(new TransactionDataObject("BikeType", biketype, true, true)); }
/// <summary> /// Инициализация реквизитов объекта /// </summary> protected override void CreatePreDefinedFields() { #region необходимые операции до создания реквизитов и заполнения полей if (NsgSettings.Regime == NsgSoft.Common.NsgViewTypes.Load) { base.CreatePreDefinedFields(); } #endregion //необходимые операции до создания реквизитов и заполнения полей #region начало инициализации NsgSoft.DataObjects.NsgDataTable #endregion //начало инициализации NsgSoft.DataObjects.NsgDataTable #region создание System.Guid Идентификатор { NsgDataGuid Идентификатор = null; if (ObjectList.Contains("Идентификатор")) { Идентификатор = ObjectList["Идентификатор"] as NsgDataGuid; } else { Идентификатор = new NsgDataGuid(); } //NsgDataGuid Идентификатор.IsLoadedFromDll = true; Идентификатор.StringFormat = ""; Идентификатор.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; Идентификатор.IncludeInPredefined = false; Идентификатор.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Идентификатор.Required = false; Идентификатор.EmptyValue = ""; Идентификатор.NullAllow = false; Идентификатор.IndexType = NsgSoft.Database.NsgRekvisitIndexType.UniqueControl; Идентификатор.FieldName = "_ID"; Идентификатор.SaveInDatabase = true; Идентификатор.InformMetaDataOnValueChanged = false; Идентификатор.Visible = true; Идентификатор.Name = "Идентификатор"; Идентификатор.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Идентификатор.Description = "Идентификатор"; Идентификатор.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.ReadOnly; Идентификатор.GroupName = ""; Идентификатор.Guid = NsgService.StringToGuid("cd5dd92f-53b5-4b7e-b737-cf3b7ea54401"); if (!ObjectList.Contains("Идентификатор")) { ObjectList.Add(Идентификатор); } } #endregion //создание System.Guid Идентификатор #region создание System.Int64 Автоинкремент { NsgDataInteger Автоинкремент = null; if (ObjectList.Contains("Автоинкремент")) { Автоинкремент = ObjectList["Автоинкремент"] as NsgDataInteger; } else { Автоинкремент = new NsgDataInteger(); } //NsgDataInteger Автоинкремент.IsLoadedFromDll = true; Автоинкремент.DefaultValue = 0M; Автоинкремент.MinValue = 0M; Автоинкремент.MaxValue = 0M; Автоинкремент.UseCalculator = true; Автоинкремент.StringFormat = ""; Автоинкремент.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; Автоинкремент.IncludeInPredefined = false; Автоинкремент.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Автоинкремент.Required = false; Автоинкремент.EmptyValue = ""; Автоинкремент.NullAllow = false; Автоинкремент.IndexType = NsgSoft.Database.NsgRekvisitIndexType.UniqueControl; Автоинкремент.FieldName = "_AutoInc"; Автоинкремент.SaveInDatabase = true; Автоинкремент.InformMetaDataOnValueChanged = false; Автоинкремент.Visible = true; Автоинкремент.Name = "Автоинкремент"; Автоинкремент.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Автоинкремент.Description = "Автоинкремент"; Автоинкремент.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Hidden; Автоинкремент.GroupName = ""; Автоинкремент.Guid = NsgService.StringToGuid("76819f73-0800-4214-85d4-a8f68229feac"); if (!ObjectList.Contains("Автоинкремент")) { ObjectList.Add(Автоинкремент); } } #endregion //создание System.Int64 Автоинкремент #region создание NsgSoft.DataObjects.NsgReferencedObject Владелец { NsgDataUntypedReference Владелец = null; if (ObjectList.Contains("Владелец")) { Владелец = ObjectList["Владелец"] as NsgDataUntypedReference; } else { Владелец = new NsgDataUntypedReference(); } //NsgDataUntypedReference Владелец.IsLoadedFromDll = true; Владелец.FilterTypeForConfigurator = NsgSoft.DataObjects.NsgFiltration.List; Владелец.FilterForConfigurator = "Автосервис.РасходнаяНакладная"; Владелец.ReferentName = ""; Владелец.ReferentGroup = ""; Владелец.TypeSelectorName = ""; Владелец.SaveInDatabase = true; Владелец.OwnerName = ""; Владелец.AllowEmptyOwner = false; Владелец.StringFormat = ""; Владелец.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; Владелец.IncludeInPredefined = false; Владелец.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Владелец.Required = false; Владелец.EmptyValue = ""; Владелец.NullAllow = false; Владелец.IndexType = NsgSoft.Database.NsgRekvisitIndexType.Sort; Владелец.FieldName = "_Owner"; Владелец.InformMetaDataOnValueChanged = false; Владелец.Visible = true; Владелец.Name = "Владелец"; Владелец.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Владелец.Description = "Владелец"; Владелец.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.ReadOnly; Владелец.GroupName = ""; Владелец.Guid = NsgService.StringToGuid("83e5b4dc-5d80-492d-aad5-216ca33ca4d2"); if (!ObjectList.Contains("Владелец")) { ObjectList.Add(Владелец); } } #endregion //создание NsgSoft.DataObjects.NsgReferencedObject Владелец #region создание System.Int64 НомерСтроки { NsgDataInteger НомерСтроки = null; if (ObjectList.Contains("НомерСтроки")) { НомерСтроки = ObjectList["НомерСтроки"] as NsgDataInteger; } else { НомерСтроки = new NsgDataInteger(); } //NsgDataInteger НомерСтроки.IsLoadedFromDll = true; НомерСтроки.DefaultValue = 0M; НомерСтроки.MinValue = 0M; НомерСтроки.MaxValue = 0M; НомерСтроки.UseCalculator = true; НомерСтроки.StringFormat = ""; НомерСтроки.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; НомерСтроки.IncludeInPredefined = false; НомерСтроки.PeriodicType = NsgSoft.Database.PeriodicTypes.None; НомерСтроки.Required = false; НомерСтроки.EmptyValue = ""; НомерСтроки.NullAllow = false; НомерСтроки.IndexType = NsgSoft.Database.NsgRekvisitIndexType.None; НомерСтроки.FieldName = "_RowNumber"; НомерСтроки.SaveInDatabase = true; НомерСтроки.InformMetaDataOnValueChanged = false; НомерСтроки.Visible = true; НомерСтроки.Name = "НомерСтроки"; НомерСтроки.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); НомерСтроки.Description = "Номер строки"; НомерСтроки.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Hidden; НомерСтроки.GroupName = ""; НомерСтроки.Guid = NsgService.StringToGuid("b20ce5f9-6d58-419a-b5f0-855e335028f7"); if (!ObjectList.Contains("НомерСтроки")) { ObjectList.Add(НомерСтроки); } } #endregion //создание System.Int64 НомерСтроки #region создание Автосервис.Номенклатура Номенклатура { NsgDataTypedReference Номенклатура = null; if (ObjectList.Contains("Номенклатура")) { Номенклатура = ObjectList["Номенклатура"] as NsgDataTypedReference; } else { Номенклатура = new NsgDataTypedReference(); } //NsgDataTypedReference Номенклатура.IsLoadedFromDll = true; Номенклатура.ReferentGroup = "Автосервис"; Номенклатура.ReferentName = "Номенклатура"; Номенклатура.SaveInDatabase = true; Номенклатура.OwnerName = ""; Номенклатура.AllowEmptyOwner = false; Номенклатура.StringFormat = ""; Номенклатура.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; Номенклатура.IncludeInPredefined = false; Номенклатура.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Номенклатура.Required = false; Номенклатура.EmptyValue = ""; Номенклатура.NullAllow = false; Номенклатура.IndexType = NsgSoft.Database.NsgRekvisitIndexType.None; Номенклатура.FieldName = "Nomenklatura"; Номенклатура.InformMetaDataOnValueChanged = false; Номенклатура.Visible = true; Номенклатура.Name = "Номенклатура"; Номенклатура.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Номенклатура.Description = "Номенклатура"; Номенклатура.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Full; Номенклатура.GroupName = ""; Номенклатура.Guid = NsgService.StringToGuid("6b16fbdd-2f64-4052-b181-55967a876579"); if (!ObjectList.Contains("Номенклатура")) { ObjectList.Add(Номенклатура); } } #endregion //создание Автосервис.Номенклатура Номенклатура #region создание System.Int64 Количество { NsgDataInteger Количество = null; if (ObjectList.Contains("Количество")) { Количество = ObjectList["Количество"] as NsgDataInteger; } else { Количество = new NsgDataInteger(); } //NsgDataInteger Количество.IsLoadedFromDll = true; Количество.DefaultValue = 0M; Количество.MinValue = 0M; Количество.MaxValue = 0M; Количество.UseCalculator = true; Количество.StringFormat = ""; Количество.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; Количество.IncludeInPredefined = false; Количество.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Количество.Required = false; Количество.EmptyValue = ""; Количество.NullAllow = false; Количество.IndexType = NsgSoft.Database.NsgRekvisitIndexType.None; Количество.FieldName = "Kolichestvo"; Количество.SaveInDatabase = true; Количество.InformMetaDataOnValueChanged = false; Количество.Visible = true; Количество.Name = "Количество"; Количество.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Количество.Description = "Количество"; Количество.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Full; Количество.GroupName = ""; Количество.Guid = NsgService.StringToGuid("9033df54-2ec0-49f3-9dfd-b0fdd0808094"); if (!ObjectList.Contains("Количество")) { ObjectList.Add(Количество); } } #endregion //создание System.Int64 Количество #region создание System.Decimal Цена { NsgDataFloat Цена = null; if (ObjectList.Contains("Цена")) { Цена = ObjectList["Цена"] as NsgDataFloat; } else { Цена = new NsgDataFloat(); } //NsgDataFloat Цена.IsLoadedFromDll = true; Цена.Precision = 2; Цена.HideZero = true; Цена.DefaultValue = 0M; Цена.MinValue = -100000000000000000M; Цена.MaxValue = 100000000000000000M; Цена.UseCalculator = true; Цена.StringFormat = ""; Цена.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; Цена.IncludeInPredefined = false; Цена.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Цена.Required = false; Цена.EmptyValue = ""; Цена.NullAllow = false; Цена.IndexType = NsgSoft.Database.NsgRekvisitIndexType.None; Цена.FieldName = "Cena"; Цена.SaveInDatabase = true; Цена.InformMetaDataOnValueChanged = false; Цена.Visible = true; Цена.Name = "Цена"; Цена.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Цена.Description = "Цена"; Цена.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Full; Цена.GroupName = ""; Цена.Guid = NsgService.StringToGuid("8aafa228-95f7-4da3-a5fd-e64cd6631e88"); if (!ObjectList.Contains("Цена")) { ObjectList.Add(Цена); } } #endregion //создание System.Decimal Цена #region создание System.Decimal Сумма { NsgDataFloat Сумма = null; if (ObjectList.Contains("Сумма")) { Сумма = ObjectList["Сумма"] as NsgDataFloat; } else { Сумма = new NsgDataFloat(); } //NsgDataFloat Сумма.IsLoadedFromDll = true; Сумма.Precision = 2; Сумма.HideZero = true; Сумма.DefaultValue = 0M; Сумма.MinValue = -100000000000000000M; Сумма.MaxValue = 100000000000000000M; Сумма.UseCalculator = true; Сумма.StringFormat = ""; Сумма.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; Сумма.IncludeInPredefined = false; Сумма.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Сумма.Required = false; Сумма.EmptyValue = ""; Сумма.NullAllow = false; Сумма.IndexType = NsgSoft.Database.NsgRekvisitIndexType.None; Сумма.FieldName = "Summa"; Сумма.SaveInDatabase = true; Сумма.InformMetaDataOnValueChanged = false; Сумма.Visible = true; Сумма.Name = "Сумма"; Сумма.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Сумма.Description = "Сумма"; Сумма.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Full; Сумма.GroupName = ""; Сумма.Guid = NsgService.StringToGuid("bfd9c988-54ac-48ea-9db8-d12045f12855"); if (!ObjectList.Contains("Сумма")) { ObjectList.Add(Сумма); } } #endregion //создание System.Decimal Сумма #region заполнение полей класса //NsgDataTable IsLoadedFromDll = true; OwnerFullName = "Автосервис.РасходнаяНакладная"; RegisterPeriod = NsgSoft.Common.NsgPeriod.None; RegisterPeriodCount = 0; TableSubType = NsgSoft.Common.NsgTableSubType.TablePart; EntityType = NsgSoft.DataObjects.NsgInterfacedObject.EntityTypes.Object; Name = "АвтосервисРасходнаяНакладнаяТаблица"; Visible = true; Guid = NsgService.StringToGuid("f0db56b1-576b-4309-83bf-d3aa11e951ef"); DefaultSortingName = ""; DefaultElementFormName = ""; DefaultListFormName = ""; ValueMask = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "{Представление}" }); SearchType = NsgSoft.Database.NsgComparison.Contain; SearchFieldName = "Идентификатор"; DatabaseName = ""; VisibleAdminOnly = false; TableName = "Ав_tab_AvtoservisRaskhod"; Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Description = "Автосервис расходная накладная таблица"; EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Full; GroupName = "_SystemTables"; #endregion //заполнение полей класса #region окончание инициализации NsgSoft.DataObjects.NsgDataTable #endregion //окончание инициализации NsgSoft.DataObjects.NsgDataTable #region необходимые операции после создания реквизитов и заполнения полей // внести в кэш полей initFieldsCash(); #endregion //необходимые операции после создания реквизитов и заполнения полей }
/// <summary> /// COmオブジェクトをリストに追加してそのまま返却する拡張メソッド /// </summary> /// <typeparam name="T">追加するオブジェクトの型</typeparam> /// <param name="self">リストに追加するオブジェクト</param> /// <param name="list">追加先リスト</param> /// <returns>追加したオブジェクト自身</returns> public static T WithAddTo <T>(this T self, ObjectList list) { list.Add(self); return(self); }
static public PQS GetPQS(String body) { StaticSetup(); return(ObjectList.Find(pqs => pqs.Body == body)); }
object IGXDLMSBase.GetValue(int index, int selector, object parameters) { if (ObjectList == null) { ObjectList = new GXDLMSObjectCollection(); } if (index == 1) { return(this.LogicalName); } else if (index == 2) { int cnt = ObjectList.Count; List <byte> data = new List <byte>(); data.Add((byte)DataType.Array); //Add count GXCommon.SetObjectCount(cnt, data); if (cnt != 0) { foreach (GXDLMSObject it in ObjectList) { data.Add((byte)DataType.Structure); data.Add((byte)4); //Count GXCommon.SetData(data, DataType.Int16, it.ShortName); //base address. GXCommon.SetData(data, DataType.UInt16, it.ObjectType); //ClassID GXCommon.SetData(data, DataType.UInt8, 0); //Version GXCommon.SetData(data, DataType.OctetString, it.LogicalName); //LN } if (ObjectList.FindBySN(this.ShortName) == null) { data.Add((byte)DataType.Structure); data.Add((byte)4); //Count GXCommon.SetData(data, DataType.Int16, this.ShortName); //base address. GXCommon.SetData(data, DataType.UInt16, this.ObjectType); //ClassID GXCommon.SetData(data, DataType.UInt8, 0); //Version GXCommon.SetData(data, DataType.OctetString, this.LogicalName); //LN } } return(data.ToArray()); } else if (index == 3) { bool lnExists = ObjectList.FindBySN(this.ShortName) != null; //Add count int cnt = ObjectList.Count; if (!lnExists) { ++cnt; } List <byte> data = new List <byte>(); data.Add((byte)DataType.Array); GXCommon.SetObjectCount(cnt, data); foreach (GXDLMSObject it in ObjectList) { GetAccessRights(it, data); } if (!lnExists) { GetAccessRights(this, data); } return(data.ToArray()); } else if (index == 4) { List <byte> data = new List <byte>(); GXCommon.SetData(data, DataType.OctetString, SecuritySetupReference); return(data.ToArray()); } throw new ArgumentException("GetValue failed. Invalid attribute index."); }
private void PostUITask(GeneralObject go) { if (go.GetPropertyValue("CONDITION").ToString().Equals("正常")) { //供暖方式 ObjectCollection oc = this.Resources["WARM"] as ObjectCollection; bool found = false; foreach (Pair pair in oc) { if (pair.CName.Equals(go.GetPropertyValue("WARM").ToString())) { found = true; WARM.SelectedItem = pair; } } if (!found) { WARM_OTHER.Text = go.GetPropertyValue("WARM").ToString(); WARM.SelectedIndex = oc.Count - 1; } //基表厂家型号 oc = this.Resources["JB_METER_NAME"] as ObjectCollection; found = false; foreach (Pair pair in oc) { if (pair.CName.Equals(go.GetPropertyValue("JB_METER_NAME").ToString())) { JB_METER_NAME.SelectedItem = pair; found = true; } } if (!found) { JB_METER_NAME_OTHER.Text = go.GetPropertyValue("JB_METER_NAME").ToString(); JB_METER_NAME.SelectedIndex = oc.Count - 1; } //IC卡表厂家型号 oc = this.Resources["IC_METER_NAME"] as ObjectCollection; found = false; foreach (Pair pair in oc) { if (pair.CName.Equals(go.GetPropertyValue("IC_METER_NAME").ToString())) { found = true; IC_METER_NAME.SelectedItem = pair; } } if (!found) { IC_METER_NAME_OTHER.Text = go.GetPropertyValue("IC_METER_NAME").ToString(); go.SetPropertyValue("IC_METER_NAME", (oc.ElementAt(oc.Count - 1) as Pair).Code, true, true); IC_METER_NAME.SelectedIndex = oc.Count - 1; } ObjectList lines = go.GetPropertyValue("LINES") as ObjectList; //不存在隐患 if (lines == null) { return; } foreach (GeneralObject line in lines) { String EQUIPMENT = line.GetPropertyValue("EQUIPMENT") as string; String CONTENT = line.GetPropertyValue("CONTENT") as string; if (EQUIPMENT.Equals("安全隐患")) { CheckCheckBox(CONTENT, precautionCheckPane); } else if (EQUIPMENT.Equals("燃气表")) { CheckCheckBox(CONTENT, MeterDefectsPane); } else if (EQUIPMENT.Equals("立管")) { CheckPlumbingBox(CONTENT, PlumbingDefectsPane); } else if (EQUIPMENT.Equals("阀门表前阀")) { CheckCheckBox(CONTENT, PlumbingMeterValvePane); } else if (EQUIPMENT.Equals("阀门灶前阀")) { CheckCheckBox(CONTENT, PlumbingCookerValvePane); } else if (EQUIPMENT.Equals("阀门自闭阀")) { CheckCheckBox(CONTENT, PlumbingAutomaticValvePane); } else if (EQUIPMENT.Equals("户内管")) { CheckCheckBox(CONTENT, PlumbingPipePane); } else if (EQUIPMENT.Equals("灶具软管")) { CheckCheckBox(CONTENT, CookerPipePane); } else if (EQUIPMENT.Equals("热水器软管")) { CheckCheckBox(CONTENT, BoilerPipePane); } else if (EQUIPMENT.Equals("热水器安全隐患")) { CheckCheckBox(CONTENT, BoilerDefectsPane); } else if (EQUIPMENT.Equals("壁挂锅炉安全隐患")) { CheckCheckBox(CONTENT, WHEDefectsPane); } } //提取用户档案地址 String card_id = go.GetPropertyValue("CARD_ID") as string; if (IsNullOrEmpty(card_id)) { return; } WebClient wc = new WebClient(); wc.DownloadStringCompleted += wc_GetUserProfileCompleted; wc.DownloadStringAsync(new Uri(go.WebClientInfo.BaseAddress + "/one/from T_IC_USERFILE where CARD_ID='" + card_id + "'")); } }
public string ToString(Perso perso, TranslatedScript.TranslationSettings ts, bool advanced = false) { MapLoader l = MapLoader.Loader; short mask = 0; AITypes aiTypes = Settings.s.aiTypes; Vector3 vector3 = new Vector3 { x = 0, y = 0, z = 0 }; switch (nodeType) { case ScriptNode.NodeType.KeyWord: // KeyWordFunctionPtr if (param < aiTypes.keywordTable.Length) { if (ts.exportMode) { if (aiTypes.keywordTable[param] == "Me") { return("this"); } if (aiTypes.keywordTable[param] == "MainActor") { return("Controller.MainActor"); } if (aiTypes.keywordTable[param] == "Nobody" || aiTypes.keywordTable[param] == "NoInput" || aiTypes.keywordTable[param] == "Nowhere" || aiTypes.keywordTable[param] == "NoGraph" || aiTypes.keywordTable[param] == "NoAction" || aiTypes.keywordTable[param] == "CapsNull") { return("null"); } } return(aiTypes.keywordTable[param]); } return("UnknownKeyword_" + param); case ScriptNode.NodeType.Condition: // GetConditionFunctionPtr if (param < aiTypes.conditionTable.Length) { return(aiTypes.conditionTable[param]); } return("UnknownCondition_" + param); case ScriptNode.NodeType.Operator: // GetOperatorFunctionPtr if (advanced) { if (param < aiTypes.operatorTable.Length) { return(aiTypes.operatorTable[param] + " (" + param + ")"); } } if (param < aiTypes.operatorTable.Length) { return(aiTypes.operatorTable[param]); } return("UnknownOperator_" + param); case ScriptNode.NodeType.Function: // GetFunctionFunctionPtr if (param < aiTypes.functionTable.Length) { return(aiTypes.functionTable[param]); } return("UnknownFunction_" + param); case ScriptNode.NodeType.Procedure: // ProcedureFunctionReturn if (param < aiTypes.procedureTable.Length) { return(aiTypes.procedureTable[param]); } return("UnknownProcedure_" + param); case ScriptNode.NodeType.MetaAction: // meta action if (param < aiTypes.metaActionTable.Length) { return(aiTypes.metaActionTable[param]); } return("UnknownMetaAction_" + param); case ScriptNode.NodeType.BeginMacro: return("BeginMacro"); case ScriptNode.NodeType.EndMacro: return("EndMacro"); case ScriptNode.NodeType.Field: if (param < aiTypes.fieldTable.Length) { return(aiTypes.fieldTable[param]); } return("UnknownField_" + param); case ScriptNode.NodeType.DsgVarRef: // Dsg Var if (perso != null && perso.brain != null && perso.brain.mind != null) { Mind mind = perso.brain.mind; if (mind.dsgMem != null && mind.dsgMem.dsgVar != null) { if (param < mind.dsgMem.dsgVar.dsgVarInfos.Length) { return(mind.dsgMem.dsgVar.dsgVarInfos[param].NiceVariableName); } } else if (mind.AI_model != null && mind.AI_model.dsgVar != null) { if (param < mind.AI_model.dsgVar.dsgVarInfos.Length) { return(mind.AI_model.dsgVar.dsgVarInfos[param].NiceVariableName); } } } return("dsgVar_" + param); case ScriptNode.NodeType.Constant: if (advanced) { return("Constant: " + BitConverter.ToInt32(BitConverter.GetBytes(param), 0)); } return(BitConverter.ToInt32(BitConverter.GetBytes(param), 0).ToString()); case ScriptNode.NodeType.Real: NumberFormatInfo nfi = new NumberFormatInfo() { NumberDecimalSeparator = "." }; if (advanced) { return("Real: " + BitConverter.ToSingle(BitConverter.GetBytes(param), 0).ToString(nfi)); } return(BitConverter.ToSingle(BitConverter.GetBytes(param), 0).ToString(nfi) + "f"); case ScriptNode.NodeType.Button: // Button/entryaction EntryAction ea = EntryAction.FromOffset(param_ptr); if (ea == null) { return("ERR_ENTRYACTION_NOTFOUND"); } string eaName = (advanced ? ea.ToString() : ea.ToBasicString()); if (advanced) { return("Button: " + eaName + "(" + param_ptr + ")"); } if (!ts.expandEntryActions && ea != null) { return("\"" + ea.ExportName + "\""); } return(eaName); case ScriptNode.NodeType.ConstantVector: return("Constant Vector: " + "0x" + param.ToString("x8")); // TODO: get from address case ScriptNode.NodeType.Vector: return("new Vector3"); // TODO: same case ScriptNode.NodeType.Mask: mask = (short)param; // TODO: as short if (advanced) { return("Mask: " + (mask).ToString("x4")); } if (ts.exportMode) { return("\"" + (mask).ToString("x4") + "\""); } return("Mask(" + (mask).ToString("x4") + ")"); case ScriptNode.NodeType.ModuleRef: if (advanced) { return("ModuleRef: " + "0x" + (param).ToString("x8")); } return("GetModule(" + (int)param + ")"); case ScriptNode.NodeType.DsgVarId: if (advanced) { return("DsgVarId: " + "0x" + (param).ToString("x8")); } return("DsgVarId(" + param + ")"); case ScriptNode.NodeType.String: string str = "ERR_STRING_NOTFOUND"; if (l.strings.ContainsKey(param_ptr)) { str = l.strings[param_ptr]; } if (advanced) { return("String: " + param_ptr + " (" + str + ")"); } return("\"" + str + "\""); case ScriptNode.NodeType.LipsSynchroRef: return("LipsSynchroRef: " + param_ptr); case ScriptNode.NodeType.FamilyRef: if (advanced) { return("FamilyRef: " + param_ptr); } Family f = Family.FromOffset(param_ptr); if (f != null) { return("GetFamily(\"" + f.name + "\")"); } else { return("Family.FromOffset(\"" + param_ptr + "\")"); } case ScriptNode.NodeType.PersoRef: Perso argPerso = Perso.FromOffset(param_ptr); if (argPerso != null && perso != null && argPerso.offset == perso.offset) { if (advanced) { return("PersoRef: this"); } return("this"); } string persoName = argPerso == null ? "ERR_PERSO_NOTFOUND" : argPerso.fullName; if (advanced) { return("PersoRef: " + param_ptr + " (" + persoName + ")"); } if (argPerso?.brain?.mind?.AI_model != null) { AIModel aiModel = argPerso.brain.mind.AI_model; // Make sure to add a cast in case the AI Model is accessed return("((" + aiModel.name + ")GetPerso(\"" + argPerso.namePerso + "\"))"); } return("GetPerso(\"" + argPerso.namePerso + "\")"); case ScriptNode.NodeType.ActionRef: State state = State.FromOffset(param_ptr); string stateName = state == null ? "ERR_STATE_NOTFOUND" : state.ShortName; if (advanced) { return("ActionRef: " + param_ptr + " " + stateName); } if (ts.useStateIndex) { return("GetAction(" + state.index.ToString() + ")"); } return(stateName); case ScriptNode.NodeType.SuperObjectRef: if (advanced) { return("SuperObjectRef: " + param_ptr); } SuperObject so = SuperObject.FromOffset(param_ptr); if (so != null) { return("GetSuperObject(\"" + so.Gao.name + "\")"); } else { return("SuperObject.FromOffset(\"" + param_ptr + "\")"); } case ScriptNode.NodeType.WayPointRef: if (advanced) { return("WayPointRef: " + param_ptr); } return("WayPoint.FromOffset(\"" + param_ptr + "\")"); case ScriptNode.NodeType.TextRef: if (l.localization == null) { return("TextRef"); } if (advanced) { return("TextRef: " + param + " (" + l.localization.GetTextForHandleAndLanguageID((int)param, 0) + ")"); } if (ts.expandStrings) { return("\"" + l.localization.GetTextForHandleAndLanguageID((int)param, 0) + "\""); // Preview in english } else { return("new TextReference(" + (int)param + ")"); } case ScriptNode.NodeType.ComportRef: Behavior comportRef = l.FromOffset <Behavior>(param_ptr); if (comportRef == null) { if (advanced) { return("ComportRef: " + param_ptr + " (null)"); } return("null"); } else { return(comportRef.ShortName); //string type = comportRef.type == Behavior.BehaviorType.Normal ? "normalBehavior" : "reflexBehavior"; //return type + "[" + script.behaviorOrMacro.aiModel.GetBehaviorIndex(comportRef) + "]"; } case ScriptNode.NodeType.SoundEventRef: if (advanced) { return("SoundEventRef: " + (int)param); } return("SoundEvent.FromID(0x" + ((int)param).ToString("X8") + ")"); case ScriptNode.NodeType.ObjectTableRef: if (advanced) { return("ObjectTableRef: " + param_ptr); } if (ts.useHashIdentifiers) { string objectListJson = ObjectList.FromOffset(param_ptr).ToJSON(); string objectListHash = HashUtils.MD5Hash(objectListJson); return("ObjectList.FromHash(\"" + objectListHash + "\")"); } return("ObjectTable.FromOffset(\"" + param_ptr + "\")"); case ScriptNode.NodeType.GameMaterialRef: if (advanced) { return("GameMaterialRef: " + param_ptr); } if (ts.useHashIdentifiers) { string gmtJson = GameMaterial.FromOffset(param_ptr).ToJSON(); string gmtHash = HashUtils.MD5Hash(gmtJson); return("GameMaterial.FromHash(\"" + gmtHash + "\")"); } return("GameMaterial.FromOffset(\"" + param_ptr + "\")"); case ScriptNode.NodeType.ParticleGenerator: return("ParticleGenerator: " + "0x" + (param).ToString("x8")); case ScriptNode.NodeType.VisualMaterial: if (advanced) { return("VisualMaterial: " + param_ptr); } if (ts.useHashIdentifiers) { string vmtJson = VisualMaterial.FromOffset(param_ptr).ToJSON(); string vmtHash = HashUtils.MD5Hash(vmtJson); return("VisualMaterial.FromHash(\"" + vmtHash + "\")"); } return("VisualMaterial.FromOffset(\"" + param_ptr + "\")"); case ScriptNode.NodeType.ModelRef: // ModelCast if (advanced) { return("AIModel: " + param_ptr); } AIModel model = l.FromOffset <AIModel>(param_ptr); return(model != null ? model.name : "null"); case ScriptNode.NodeType.DataType42: if (advanced) { return("EvalDataType42: " + "0x" + (param).ToString("x8")); } return("EvalDataType42(" + "0x" + (param).ToString("x8") + ")"); case ScriptNode.NodeType.CustomBits: if (advanced) { return("CustomBits: " + "0x" + (param).ToString("x8")); } if (ts.exportMode) { return("0x" + (param).ToString("x8")); } return("CustomBits(" + "0x" + (param).ToString("x8") + ")"); case ScriptNode.NodeType.Caps: if (advanced) { return("Caps: " + "0x" + (param).ToString("x8")); } if (ts.exportMode) { return("0x" + (param).ToString("x8")); } return("Caps(" + "0x" + (param).ToString("x8") + ")"); case ScriptNode.NodeType.SubRoutine: if (advanced) { return("Eval SubRoutine: " + param_ptr); } Macro macro = l.FromOffset <Macro>(param_ptr); if (macro == null) { return("null"); } return("evalMacro(" + macro.ShortName + ");"); case ScriptNode.NodeType.Null: return("null"); case ScriptNode.NodeType.GraphRef: if (advanced) { return("Graph: " + "0x" + (param).ToString("x8")); } return("Graph.FromOffset(\"" + param_ptr + "\")"); } return("unknown"); }
/// <summary> /// 删除焦点对象 /// </summary> public void DeleteObject(string lb) { //获取焦点对象 PSP_EachList obj = FocusedObject; if (obj == null) { bl = false; return; } int coun = 0; switch (lb) { case "xuqiu": PowerTypes pt = new PowerTypes(); pt.Flag2 = obj.ID.ToString(); IList <PowerTypes> li = Services.BaseService.GetList <PowerTypes>("SelectPowerTypesByFlag2", pt); coun = li.Count; break; } if (coun > 0) { MsgBox.Show("该分类下面有记录,无法删除"); bl = false; return; } //请求确认 if (MsgBox.ShowYesNo(Strings.SubmitDelete) != DialogResult.Yes) { bl = false; return; } //执行删除操作 try { Services.BaseService.Delete <PSP_EachList>(obj); if (lb == "sb") { Services.BaseService.Update("DeletePowerPicSelect1", obj.ID); Services.BaseService.Update("DeletePowerProTypesInFlag2", obj.ID); } } catch { //Debug.Fail(exc.Message); //HandleException.TryCatch(exc); return; } this.gridView.BeginUpdate(); //记住当前焦点行索引 int iOldHandle = this.gridView.FocusedRowHandle; //从链表中删除 ObjectList.Remove(obj); //刷新表格 gridControl.RefreshDataSource(); //设置新的焦点行索引 GridHelper.FocuseRowAfterDelete(this.gridView, iOldHandle); this.gridView.EndUpdate(); }
internal ObjectListItem(ObjectList owner) : this(owner, null) { }
void IGXDLMSBase.SetValue(int index, object value) { if (index == 1) { if (value is string) { LogicalName = value.ToString(); } else { LogicalName = GXDLMSClient.ChangeType((byte[])value, DataType.OctetString).ToString(); } } else if (index == 2) { ObjectList.Clear(); if (value != null) { foreach (Object[] item in (Object[])value) { ushort sn = (ushort)(Convert.ToInt32(item[0]) & 0xFFFF); ObjectType type = (ObjectType)Convert.ToInt32(item[1]); int version = Convert.ToInt32(item[2]); String ln = GXDLMSObject.toLogicalName((byte[])item[3]); GXDLMSObject obj = null; if (Parent != null) { obj = Parent.FindBySN(sn); } if (obj == null) { obj = Gurux.DLMS.GXDLMSClient.CreateObject(type); if (obj != null) { obj.LogicalName = ln; obj.ShortName = sn; obj.Version = version; } } //Unknown objects are not shown. if (obj is IGXDLMSBase) { ObjectList.Add(obj); } } } } else if (index == 3) { if (value == null) { foreach (GXDLMSObject it in ObjectList) { for (int pos = 1; pos != (it as IGXDLMSBase).GetAttributeCount(); ++pos) { it.SetAccess(pos, AccessMode.NoAccess); } } } else { UpdateAccessRights((Object[])value); } } else if (index == 4) { if (value is string) { SecuritySetupReference = value.ToString(); } else { SecuritySetupReference = GXDLMSClient.ChangeType(value as byte[], DataType.OctetString).ToString(); } } else { throw new ArgumentException("SetValue failed. Invalid attribute index."); } }
/// <summary> /// Monitors this instance. /// </summary> private static void Monitor() { while (!Closing) { if (InGame && _processPid != -1) { Thread.Sleep(500); continue; } if (!DoesProcessExsist(_processPid) && !_alearted) { InterfaceHelper.StopUpdate(); Logging.Write(LogType.Info, "没有发现魔兽在运行"); ObjectList.Clear(); ObjectDictionary.Clear(); if (NoAttach != null) { NoAttach(new object(), new NotifyEventNoAttach("魔兽进程注入失败!!")); } _alearted = true; } Initialized = false; if (_refresher != null) { if (_refresher.IsAlive) { _refresher.Abort(); _refresher = null; } } if (DoesProcessExsist(_processPid)) { _alearted = false; ObjectList.Clear(); ObjectDictionary.Clear(); if (NoAttach != null) { NoAttach(new object(), new NotifyEventNoAttach("魔兽进程注入失败!!")); } Logging.Write(LogType.Info, "Not ingame"); Thread.Sleep(1500); while (DoesProcessExsist(_processPid) && !InGame) { Thread.Sleep(1000); } if (InGame) { Initialize(_processPid); } else { _processPid = -1; } } else { _processPid = -1; } Thread.Sleep(2000); } }
void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e) { if (e.Index == 1) { LogicalName = GXCommon.ToLogicalName(e.Value); } else if (e.Index == 2) { ObjectList.Clear(); if (e.Value != null) { foreach (Object[] item in (Object[])e.Value) { ObjectType type = (ObjectType)Convert.ToInt32(item[0]); int version = Convert.ToInt32(item[1]); String ln = GXCommon.ToLogicalName((byte[])item[2]); GXDLMSObject obj = null; if (settings.Objects != null) { obj = settings.Objects.FindByLN(type, ln); } if (obj == null) { obj = Gurux.DLMS.GXDLMSClient.CreateObject(type); obj.LogicalName = ln; obj.Version = version; } //Unknown objects are not shown. if (obj is IGXDLMSBase && item[3] != null) { UpdateAccessRights(obj, (Object[])item[3]); ObjectList.Add(obj); } } } } else if (e.Index == 3) { if (e.Value != null) { ClientSAP = Convert.ToByte(((Object[])e.Value)[0]); ServerSAP = Convert.ToUInt16(((Object[])e.Value)[1]); } } else if (e.Index == 4) { //Value of the object identifier encoded in BER if (e.Value is byte[]) { GXByteBuffer arr = new GXByteBuffer(e.Value as byte[]); if (arr.GetUInt8(0) == 0x60) { ApplicationContextName.JointIsoCtt = 0; ++arr.Position; ApplicationContextName.Country = 0; ++arr.Position; ApplicationContextName.CountryName = 0; ++arr.Position; ApplicationContextName.IdentifiedOrganization = arr.GetUInt8(); ApplicationContextName.DlmsUA = arr.GetUInt8(); ApplicationContextName.ApplicationContext = arr.GetUInt8(); ApplicationContextName.ContextId = arr.GetUInt8(); } else { //Get Tag and Len. if (arr.GetUInt8() != (int)BerType.Integer && arr.GetUInt8() != 7) { throw new ArgumentOutOfRangeException(); } //Get tag if (arr.GetUInt8() != 0x11) { throw new ArgumentOutOfRangeException(); } ApplicationContextName.JointIsoCtt = arr.GetUInt8(); //Get tag if (arr.GetUInt8() != 0x11) { throw new ArgumentOutOfRangeException(); } ApplicationContextName.Country = arr.GetUInt8(); //Get tag if (arr.GetUInt8() != 0x12) { throw new ArgumentOutOfRangeException(); } ApplicationContextName.CountryName = arr.GetUInt16(); //Get tag if (arr.GetUInt8() != 0x11) { throw new ArgumentOutOfRangeException(); } ApplicationContextName.IdentifiedOrganization = arr.GetUInt8(); //Get tag if (arr.GetUInt8() != 0x11) { throw new ArgumentOutOfRangeException(); } ApplicationContextName.DlmsUA = arr.GetUInt8(); //Get tag if (arr.GetUInt8() != 0x11) { throw new ArgumentOutOfRangeException(); } ApplicationContextName.ApplicationContext = arr.GetUInt8(); //Get tag if (arr.GetUInt8() != 0x11) { throw new ArgumentOutOfRangeException(); } ApplicationContextName.ContextId = arr.GetUInt8(); } } else if (e.Value != null) { Object[] arr = (Object[])e.Value; ApplicationContextName.JointIsoCtt = Convert.ToByte(arr[0]); ApplicationContextName.Country = Convert.ToByte(arr[1]); ApplicationContextName.CountryName = Convert.ToUInt16(arr[2]); ApplicationContextName.IdentifiedOrganization = Convert.ToByte(arr[3]); ApplicationContextName.DlmsUA = Convert.ToByte(arr[4]); ApplicationContextName.ApplicationContext = Convert.ToByte(arr[5]); ApplicationContextName.ContextId = Convert.ToByte(arr[6]); } } else if (e.Index == 5) { if (e.Value != null) { Object[] arr = (Object[])e.Value; GXByteBuffer bb = new GXByteBuffer(); GXCommon.SetBitString(bb, arr[0]); bb.SetUInt8(0, 0); XDLMSContextInfo.Conformance = (Conformance)bb.GetUInt32(); XDLMSContextInfo.MaxReceivePduSize = Convert.ToUInt16(arr[1]); XDLMSContextInfo.MaxSendPduSize = Convert.ToUInt16(arr[2]); XDLMSContextInfo.DlmsVersionNumber = Convert.ToByte(arr[3]); XDLMSContextInfo.QualityOfService = Convert.ToSByte(arr[4]); XDLMSContextInfo.CypheringInfo = (byte[])arr[5]; } } else if (e.Index == 6) { //Value of the object identifier encoded in BER if (e.Value is byte[]) { GXByteBuffer arr = new GXByteBuffer(e.Value as byte[]); if (arr.GetUInt8(0) == 0x60) { AuthenticationMechanismName.JointIsoCtt = 0; ++arr.Position; AuthenticationMechanismName.Country = 0; ++arr.Position; AuthenticationMechanismName.CountryName = 0; ++arr.Position; AuthenticationMechanismName.IdentifiedOrganization = arr.GetUInt8(); AuthenticationMechanismName.DlmsUA = arr.GetUInt8(); AuthenticationMechanismName.AuthenticationMechanismName = arr.GetUInt8(); AuthenticationMechanismName.MechanismId = (Authentication)arr.GetUInt8(); } else { //Get Tag and Len. if (arr.GetUInt8() != (int)BerType.Integer && arr.GetUInt8() != 7) { throw new ArgumentOutOfRangeException(); } //Get tag if (arr.GetUInt8() != 0x11) { throw new ArgumentOutOfRangeException(); } AuthenticationMechanismName.JointIsoCtt = arr.GetUInt8(); //Get tag if (arr.GetUInt8() != 0x11) { throw new ArgumentOutOfRangeException(); } AuthenticationMechanismName.Country = arr.GetUInt8(); //Get tag if (arr.GetUInt8() != 0x12) { throw new ArgumentOutOfRangeException(); } AuthenticationMechanismName.CountryName = arr.GetUInt16(); //Get tag if (arr.GetUInt8() != 0x11) { throw new ArgumentOutOfRangeException(); } AuthenticationMechanismName.IdentifiedOrganization = arr.GetUInt8(); //Get tag if (arr.GetUInt8() != 0x11) { throw new ArgumentOutOfRangeException(); } AuthenticationMechanismName.DlmsUA = arr.GetUInt8(); //Get tag if (arr.GetUInt8() != 0x11) { throw new ArgumentOutOfRangeException(); } AuthenticationMechanismName.AuthenticationMechanismName = arr.GetUInt8(); //Get tag if (arr.GetUInt8() != 0x11) { throw new ArgumentOutOfRangeException(); } AuthenticationMechanismName.MechanismId = (Authentication)arr.GetUInt8(); } } else if (e.Value != null) { Object[] arr = (Object[])e.Value; AuthenticationMechanismName.JointIsoCtt = Convert.ToByte(arr[0]); AuthenticationMechanismName.Country = Convert.ToByte(arr[1]); AuthenticationMechanismName.CountryName = Convert.ToUInt16(arr[2]); AuthenticationMechanismName.IdentifiedOrganization = Convert.ToByte(arr[3]); AuthenticationMechanismName.DlmsUA = Convert.ToByte(arr[4]); AuthenticationMechanismName.AuthenticationMechanismName = Convert.ToByte(arr[5]); AuthenticationMechanismName.MechanismId = (Authentication)Convert.ToByte(arr[6]); } } else if (e.Index == 7) { Secret = (byte[])e.Value; } else if (e.Index == 8) { if (e.Value == null) { AssociationStatus = AssociationStatus.NonAssociated; } else { AssociationStatus = (AssociationStatus)Convert.ToInt32(e.Value); } } else if (e.Index == 9) { SecuritySetupReference = GXCommon.ToLogicalName(e.Value); } else { e.Error = ErrorCode.ReadWriteDenied; } }
private void SelectAll(object sender, EventArgs e) { ObjectList.SelectAll(); }
static void Main(string[] args) { string[] arguments = Environment.GetCommandLineArgs(); Game game; string filename; string dir = Environment.CurrentDirectory; bool bigendian = false; if (args.Length == 0) { Console.WriteLine("USplit is a tool that lets you extract any data supported by SA Tools from any binary file."); Console.WriteLine("Usage: usplit <GAME> <FILENAME> <KEY> <TYPE> <ADDRESS> <PARAMETER1> <PARAMETER2> [-name <NAME>]\n"); Console.WriteLine("Argument description:"); Console.WriteLine("<GAME>: SA1, SADX, SA2, SA2B. Add '_b' (e.g. SADX_b) to switch to Big Endian.\n"); Console.WriteLine("<FILENAME>: The name of the binary file, e.g. sonic.exe.\n"); Console.WriteLine("<KEY>: Binary key, e.g. 400000 for sonic.exe or C900000 for SA1 STG file.\n"); Console.WriteLine("<TYPE>: One of the following:\n" + "binary <length> [hex],\nlandtable, model, basicmodel, basicdxmodel, chunkmodel, gcmodel, action, animation <NJS_OBJECT address> [shortrot],\n" + "objlist, startpos, texlist, leveltexlist, triallevellist, bosslevellist, fieldstartpos, soundlist, soundtestlist,\nnextlevellist, " + "levelclearflags, deathzone, levelrankscores, levelranktimes, endpos, levelpathlist, pathlist,\nstagelightdatalist, weldlist" + "bmitemattrlist, creditstextlist, animindexlist, storysequence, musiclist <count>,\n" + "stringarray <count> [language], skyboxscale <count>, stageselectlist <count>, animationlist <count>,\n" + "masterstringlist <count>, cutscenetext <count>, recapscreen <count>, npctext <count>\n"); Console.WriteLine("<ADDRESS>: The location of data in the file.\n"); Console.WriteLine("<PARAMETER1>: length, count, secondary address etc. depending on data type\n"); Console.WriteLine("<PARAMETER2>: 'hex' for binary to read length as hexadecimal, 'shortrot' for animation to read rotation as short\n"); Console.WriteLine("<NAME>: Output file name (optional)\n"); Console.WriteLine("Press ENTER to exit"); Console.ReadLine(); return; } //Args list: game, filename, key, type, address, [address2/count], [language], [name] switch (args[0]) { case "SA1": game = Game.SA1; break; case "SA1_b": game = Game.SA1; bigendian = true; break; case "SADX": game = Game.SADX; break; case "SADX_b": game = Game.SADX; bigendian = true; break; case "SA2": game = Game.SA2; break; case "SA2_b": game = Game.SA2; bigendian = true; break; case "SA2B": game = Game.SA2B; break; case "SA2B_b": game = Game.SA2B; bigendian = true; break; default: return; } string model_extension = ".sa1mdl"; string landtable_extension = ".sa1lvl"; ByteConverter.BigEndian = SonicRetro.SAModel.ByteConverter.BigEndian = bigendian; filename = args[1]; byte[] datafile = File.ReadAllBytes(filename); if (Path.GetExtension(filename).ToLowerInvariant() == ".prs") { datafile = FraGag.Compression.Prs.Decompress(datafile); } Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, Path.GetDirectoryName(filename)); uint imageBase = uint.Parse(args[2], NumberStyles.AllowHexSpecifier); string type = args[3]; int address = int.Parse(args[4], NumberStyles.AllowHexSpecifier); bool SA2 = game == Game.SA2 | game == Game.SA2B; ModelFormat modelfmt = ModelFormat.BasicDX; LandTableFormat landfmt = LandTableFormat.SADX; switch (game) { case Game.SA1: modelfmt = ModelFormat.Basic; landfmt = LandTableFormat.SA1; model_extension = ".sa1mdl"; landtable_extension = ".sa1lvl"; break; case Game.SADX: modelfmt = ModelFormat.BasicDX; landfmt = LandTableFormat.SADX; model_extension = ".sa1mdl"; landtable_extension = ".sa1lvl"; break; case Game.SA2: modelfmt = ModelFormat.Chunk; landfmt = LandTableFormat.SA2; model_extension = ".sa2mdl"; landtable_extension = ".sa2lvl"; break; case Game.SA2B: modelfmt = ModelFormat.Chunk; landfmt = LandTableFormat.SA2B; model_extension = ".sa2mdl"; landtable_extension = ".sa2blvl"; break; } Dictionary <string, MasterObjectListEntry> masterobjlist = new Dictionary <string, MasterObjectListEntry>(); Dictionary <string, Dictionary <string, int> > objnamecounts = new Dictionary <string, Dictionary <string, int> >(); string fileOutputPath = dir + "\\" + address.ToString("X"); Console.WriteLine("Game: {0}, file: {1}, key: 0x{2}, splitting {3} at 0x{4}", game.ToString(), filename, imageBase.ToString("X"), type, address.ToString("X")); if (args[args.Length - 2] == "-name") { fileOutputPath = dir + "\\" + args[args.Length - 1]; Console.WriteLine("Name: {0}", args[args.Length - 1]); } switch (type) { case "landtable": new LandTable(datafile, address, imageBase, landfmt).SaveToFile(fileOutputPath + landtable_extension, landfmt); break; case "model": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, modelfmt, new Dictionary <int, Attach>()); ModelFile.CreateFile(fileOutputPath + model_extension, mdl, null, null, null, null, modelfmt); } break; case "basicmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.Basic, new Dictionary <int, Attach>()); ModelFile.CreateFile(fileOutputPath + ".sa1mdl", mdl, null, null, null, null, ModelFormat.Basic); } break; case "basicdxmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.BasicDX, new Dictionary <int, Attach>()); ModelFile.CreateFile(fileOutputPath + ".sa1mdl", mdl, null, null, null, null, ModelFormat.BasicDX); } break; case "chunkmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.Chunk, new Dictionary <int, Attach>()); ModelFile.CreateFile(fileOutputPath + ".sa2mdl", mdl, null, null, null, null, ModelFormat.Chunk); } break; case "gcmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.GC, new Dictionary <int, Attach>()); ModelFile.CreateFile(fileOutputPath + ".sa2mdl", mdl, null, null, null, null, ModelFormat.GC); } break; case "action": { NJS_ACTION ani = new NJS_ACTION(datafile, address, imageBase, modelfmt, new Dictionary <int, Attach>()); ani.Animation.Save(fileOutputPath + ".saanim"); string[] mdlanis = new string[0]; NJS_OBJECT mdl = ani.Model; mdlanis = (fileOutputPath + ".saanim").Split(','); ModelFile.CreateFile(fileOutputPath + "_model" + model_extension, mdl, mdlanis, null, null, null, modelfmt); } break; case "animation": { bool shortrot_enabled = false; if (args.Length > 6 && args[6] == "shortrot") { shortrot_enabled = true; } NJS_OBJECT mdl = new NJS_OBJECT(datafile, int.Parse(args[5], NumberStyles.AllowHexSpecifier), imageBase, modelfmt, new Dictionary <int, Attach>()); new NJS_MOTION(datafile, address, imageBase, mdl.CountAnimated(), shortrot: shortrot_enabled).Save(fileOutputPath + ".saanim"); string[] mdlanis = new string[0]; mdlanis = (fileOutputPath + ".saanim").Split(','); ModelFile.CreateFile(fileOutputPath + "_model" + model_extension, mdl, mdlanis, null, null, null, modelfmt); } break; case "objlist": { ObjectListEntry[] objs = ObjectList.Load(datafile, address, imageBase, SA2); foreach (ObjectListEntry obj in objs) { if (!masterobjlist.ContainsKey(obj.CodeString)) { masterobjlist.Add(obj.CodeString, new MasterObjectListEntry(obj)); } if (!objnamecounts.ContainsKey(obj.CodeString)) { objnamecounts.Add(obj.CodeString, new Dictionary <string, int>() { { obj.Name, 1 } }); } else if (!objnamecounts[obj.CodeString].ContainsKey(obj.Name)) { objnamecounts[obj.CodeString].Add(obj.Name, 1); } else { objnamecounts[obj.CodeString][obj.Name]++; } } objs.Save(fileOutputPath + ".ini"); } break; case "startpos": if (SA2) { SA2StartPosList.Load(datafile, address).Save(fileOutputPath + ".ini"); } else { SA1StartPosList.Load(datafile, address).Save(fileOutputPath + ".ini"); } break; case "texlist": TextureList.Load(datafile, address, imageBase).Save(fileOutputPath + ".ini"); break; case "leveltexlist": new LevelTextureList(datafile, address, imageBase).Save(fileOutputPath + ".ini"); break; case "triallevellist": TrialLevelList.Save(TrialLevelList.Load(datafile, address, imageBase), fileOutputPath + ".ini"); break; case "bosslevellist": BossLevelList.Save(BossLevelList.Load(datafile, address), fileOutputPath + ".ini"); break; case "fieldstartpos": FieldStartPosList.Load(datafile, address).Save(fileOutputPath + ".ini"); break; case "soundtestlist": SoundTestList.Load(datafile, address, imageBase).Save(fileOutputPath + ".ini"); break; case "musiclist": { int muscnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); MusicList.Load(datafile, address, imageBase, muscnt).Save(fileOutputPath + ".ini"); } break; case "soundlist": SoundList.Load(datafile, address, imageBase).Save(fileOutputPath + ".ini"); break; case "stringarray": { int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); Languages lang = Languages.Japanese; if (args.Length > 6) { lang = (Languages)Enum.Parse(typeof(Languages), args[6], true); } StringArray.Load(datafile, address, imageBase, cnt, lang).Save(fileOutputPath + ".txt"); } break; case "nextlevellist": NextLevelList.Load(datafile, address).Save(fileOutputPath + ".ini"); break; case "cutscenetext": { int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); new CutsceneText(datafile, address, imageBase, cnt).Save(fileOutputPath + ".txt", out string[] hashes); } break; case "recapscreen": { int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); RecapScreenList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath + ".txt", out string[][] hashes); } break; case "npctext": { int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); NPCTextList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath + ".txt", out string[][] hashes); } break; case "levelclearflags": LevelClearFlagList.Save(LevelClearFlagList.Load(datafile, address), fileOutputPath + ".ini"); break; case "deathzone": { List <DeathZoneFlags> flags = new List <DeathZoneFlags>(); string path = Path.GetDirectoryName(fileOutputPath); List <string> hashes = new List <string>(); int num = 0; while (ByteConverter.ToUInt32(datafile, address + 4) != 0) { flags.Add(new DeathZoneFlags(datafile, address)); string file = Path.Combine(path, num++.ToString(NumberFormatInfo.InvariantInfo) + (modelfmt == ModelFormat.Chunk ? ".sa2mdl" : ".sa1mdl")); ModelFile.CreateFile(file, new NJS_OBJECT(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, modelfmt, new Dictionary <int, Attach>()), null, null, null, null, modelfmt); address += 8; } flags.ToArray().Save(fileOutputPath + ".ini"); } break; case "skyboxscale": { int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); SkyboxScaleList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath + ".ini"); } break; case "stageselectlist": { int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); StageSelectLevelList.Load(datafile, address, cnt).Save(fileOutputPath + ".ini"); } break; case "levelrankscores": LevelRankScoresList.Load(datafile, address).Save(fileOutputPath + ".ini"); break; case "levelranktimes": LevelRankTimesList.Load(datafile, address).Save(fileOutputPath + ".ini"); break; case "endpos": SA2EndPosList.Load(datafile, address).Save(fileOutputPath + ".ini"); break; case "animationlist": { int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); SA2AnimationInfoList.Load(datafile, address, cnt).Save(fileOutputPath + ".ini"); } break; case "levelpathlist": { ushort lvlnum = (ushort)ByteConverter.ToUInt32(datafile, address); while (lvlnum != 0xFFFF) { int ptr = ByteConverter.ToInt32(datafile, address + 4); if (ptr != 0) { ptr = (int)((uint)ptr - imageBase); SA1LevelAct level = new SA1LevelAct(lvlnum); string lvldir = Path.Combine(fileOutputPath, level.ToString()); PathList.Load(datafile, ptr, imageBase).Save(lvldir, out string[] lvlhashes); } address += 8; lvlnum = (ushort)ByteConverter.ToUInt32(datafile, address); } } break; case "pathlist": { PathList.Load(datafile, address, imageBase).Save(fileOutputPath, out string[] hashes); } break; case "stagelightdatalist": SA1StageLightDataList.Load(datafile, address).Save(fileOutputPath); break; case "weldlist": WeldList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "bmitemattrlist": BlackMarketItemAttributesList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "creditstextlist": CreditsTextList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "animindexlist": { Directory.CreateDirectory(fileOutputPath); List <string> hashes = new List <string>(); int i = ByteConverter.ToInt16(datafile, address); while (i != -1) { new NJS_MOTION(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, ByteConverter.ToInt16(datafile, address + 2)) .Save(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim"); hashes.Add(i.ToString(NumberFormatInfo.InvariantInfo) + ":" + HelperFunctions.FileHash(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim")); address += 8; i = ByteConverter.ToInt16(datafile, address); } } break; case "storysequence": SA2StoryList.Load(datafile, address).Save(fileOutputPath); break; case "masterstringlist": { int cnt = int.Parse(args[5], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); for (int l = 0; l < 5; l++) { Languages lng = (Languages)l; System.Text.Encoding enc = HelperFunctions.GetEncoding(game, lng); string ld = Path.Combine(fileOutputPath, lng.ToString()); Directory.CreateDirectory(ld); int ptr = datafile.GetPointer(address, imageBase); for (int i = 0; i < cnt; i++) { int ptr2 = datafile.GetPointer(ptr, imageBase); if (ptr2 != 0) { string fn = Path.Combine(ld, $"{i}.txt"); File.WriteAllText(fn, datafile.GetCString(ptr2, enc).Replace("\n", "\r\n")); } ptr += 4; } address += 4; } } break; case "binary": { int length; if (args.Length > 6 && args[6] == "hex") { length = int.Parse(args[5], NumberStyles.AllowHexSpecifier); } else { length = int.Parse(args[5]); } byte[] bin = new byte[length]; Array.Copy(datafile, address, bin, 0, bin.Length); File.WriteAllBytes(fileOutputPath + ".bin", bin); Console.WriteLine("Length: {0} (0x{1}) bytes", length.ToString(), length.ToString("X")); } break; default: break; } }
private async void ToggleSearch(object sender, EventArgs e) { if (_searchCancelToken != null) { _searchCancelToken.Cancel(); _searchCancelToken = null; return; } var levelPattern = LevPatternBox.Text; var errorFiles = new List <string>(); bool searchForFastestReplays; bool searchForAllReplays; var clickedButton = (Button)sender; if (clickedButton.Equals(SearchButton)) { searchForAllReplays = fastestSlowestSelect.SelectedOption == 2; searchForFastestReplays = fastestSlowestSelect.SelectedOption == 0; } else { searchForAllReplays = true; searchForFastestReplays = false; } var searchOnlyMissingLev = clickedButton.Equals(ReplaysWithoutLevFileButton); var searchOnlyWrongLev = clickedButton.Equals(ReplaysIncorrectLevButton); if (!Utils.RecDirectoryExists()) { Utils.ShowError(Constants.RecDirNotFound); return; } var p1Apples = Range <int> .FromNumericBoxes(TextBox1, TextBox14); var p2Apples = Range <int> .FromNumericBoxes(TextBox3, TextBox16); var p1Turns = Range <int> .FromNumericBoxes(TextBox2, TextBox23); var p2Turns = Range <int> .FromNumericBoxes(TextBox10, TextBox15); var p1Gt = Range <int> .FromNumericBoxes(TextBox11, TextBox24); var p2Gt = Range <int> .FromNumericBoxes(TextBox12, TextBox13); var p1Sv = Range <int> .FromNumericBoxes(TextBox4, TextBox21); var p2Sv = Range <int> .FromNumericBoxes(TextBox9, TextBox22); var p1Rv = Range <int> .FromNumericBoxes(TextBox6, TextBox19); var p2Rv = Range <int> .FromNumericBoxes(TextBox7, TextBox20); var p1Lv = Range <int> .FromNumericBoxes(TextBox8, TextBox17); var p2Lv = Range <int> .FromNumericBoxes(TextBox5, TextBox18); Range <double> time; try { time = Utils.GetTimeRange(TimeMinBox.Text, TimeMaxBox.Text); } catch (Exception) { Utils.ShowError("Time bound is in wrong format. Make sure it is 9 characters long."); return; } var size = new Range <int>((int)minFileSizeBox.Value * 1024, (int)maxFileSizeBox.Value * 1024); Regex levFilenameMatcher; try { levFilenameMatcher = new Regex(levelPattern, RegexOptions.IgnoreCase); } catch (Exception) { levFilenameMatcher = new Regex(string.Empty); } var searchParams = new ReplaySearchParameters { InternalRec = SearchParameters.GetBoolOptionFromTriSelect(intExtSelect), AcrossLev = SearchParameters.GetBoolOptionFromTriSelect(elmaAcrossSelect), Date = new Range <DateTime>(minDateTime.Value, maxDateTime.Value), Finished = SearchParameters.GetBoolOptionFromTriSelect(finishedSelect), LevExists = BoolOption.Dontcare, WrongLev = BoolOption.Dontcare, LevFilenameMatcher = levFilenameMatcher, MultiPlayer = SearchParameters.GetBoolOptionFromTriSelect(singleMultiSelect), Size = size, Time = time, P1Bounds = new ReplaySearchParameters.PlayerBounds { Apples = p1Apples, GroundTouches = p1Gt, LeftVolts = p1Lv, RightVolts = p1Rv, SuperVolts = p1Sv, Turns = p1Turns }, P2Bounds = new ReplaySearchParameters.PlayerBounds { Apples = p2Apples, GroundTouches = p2Gt, LeftVolts = p2Lv, RightVolts = p2Rv, SuperVolts = p2Sv, Turns = p2Turns } }; if (searchOnlyMissingLev) { searchParams.ResetOptions(); searchParams.LevExists = BoolOption.False; } if (searchOnlyWrongLev) { searchParams.ResetOptions(); searchParams.WrongLev = BoolOption.True; } var allFiles = Directory.GetFiles(Global.AppSettings.General.ReplayDirectory, "*.rec", Global.AppSettings.ReplayManager.RecDirSearchOption); var replayFiles = searchOnlyMissingLev || searchOnlyWrongLev ? allFiles.ToList() : Utils.FilterByRegex(allFiles, SearchPattern).ToList(); ObjectList.ClearObjects(); var oldButtonText = clickedButton.Text; _searchCancelToken = new CancellationTokenSource(); DuplicateButton.Enabled = false; DuplicateFilenameButton.Enabled = false; ConfigButton.Enabled = false; clickedButton.Text = "Stop"; var foundReplays = new List <Replay>(); ToolStripProgressBar1.Maximum = replayFiles.Count; var recsByLevel = new Dictionary <string, List <Replay> >(); var token = _searchCancelToken.Token; var progressHandler = new Progress <(int progress, int levels, int recs, int phase)>(value => { var(progressValue, levels, recs, phase) = value; ToolStripProgressBar1.Value = progressValue; if (searchForAllReplays) { statusLabel.Text = $"Found {recs} replays so far"; } else { statusLabel.Text = phase == 1 ? $"Phase 1: {levels} levels" : $"Phase 2: {recs} replays"; } }); var progress = (IProgress <(int progress, int levels, int recs, int phase)>)progressHandler; var iter = 0; try { await Task.Run(() => { foreach (var replayFile in replayFiles) { iter++; Replay srp; try { srp = new Replay(replayFile); } catch (ArgumentException) { errorFiles.Add(replayFile); continue; } if (searchParams.Matches(srp)) { if (!searchForAllReplays) { var key = srp.LevelFilename.ToLower() + srp.IsMulti; recsByLevel.TryGetValue(key, out var recs); if (recs == null) { recs = new List <Replay>(); recsByLevel[key] = recs; } recs.Add(srp); } else { foundReplays.Add(srp); } } if (iter % 10 == 0) { progress.Report((iter, recsByLevel.Count, foundReplays.Count, 1)); } token.ThrowIfCancellationRequested(); } }, token); } catch (OperationCanceledException) { Finalize(); return; } if (!searchForAllReplays) { ToolStripProgressBar1.Maximum = recsByLevel.Count; iter = 0; try { await Task.Run(() => { foreach (var rbl in recsByLevel) { iter++; var matchedReplay = rbl.Value[0]; foreach (var z in rbl.Value.Where(z => !z.WrongLevelVersion)) { if (searchForFastestReplays) { if (!matchedReplay.Finished && z.Finished) { matchedReplay = z; } else if (matchedReplay.Finished && z.Finished && z.Time < matchedReplay.Time) { matchedReplay = z; } else if (!matchedReplay.Finished && !z.Finished && z.Player1.Apples > matchedReplay.Player1.Apples) { matchedReplay = z; } } else { if (matchedReplay.Finished && !z.Finished) { matchedReplay = z; } else if (matchedReplay.Finished && z.Finished && z.Time > matchedReplay.Time) { matchedReplay = z; } else if (!matchedReplay.Finished && !z.Finished && (z.Player1.Apples < matchedReplay.Player1.Apples || matchedReplay.Time > z.Time)) { matchedReplay = z; } } } if (searchForFastestReplays || rbl.Value.Count > 1) { foundReplays.Add(matchedReplay); } if (iter % 10 == 0) { progress.Report((iter, recsByLevel.Count, foundReplays.Count, 2)); } token.ThrowIfCancellationRequested(); } }, token); } catch (OperationCanceledException) { } } Finalize(); void Finalize() { ObjectList.SetObjects(foundReplays); statusLabel.Text = "Ready"; ToolStripProgressBar1.Value = 0; _searchCancelToken = null; DuplicateButton.Enabled = true; DuplicateFilenameButton.Enabled = true; ConfigButton.Enabled = true; clickedButton.Text = oldButtonText; DisplaySelectionInfo(); if (errorFiles.Count > 0) { using (var ef = new ErrorForm(errorFiles)) { ef.ShowDialog(); } } } }
// Load a level's object list and compile object definitions private void LoadObjectList(string objectList, bool Mission = false) { bool skipDefsNow = skipDefs; List <ObjectData> objectErrors = new List <ObjectData>(); ObjectListEntry[] objlstini = ObjectList.Load(objectList, false); if (Mission) { LevelData.MisnObjDefs = new List <ObjectDefinition>(); } else { LevelData.ObjDefs = new List <ObjectDefinition>(); Directory.CreateDirectory("dllcache").Attributes |= FileAttributes.Hidden; } List <KeyValuePair <string, string> > compileErrors = new List <KeyValuePair <string, string> >(); for (int ID = 0; ID < objlstini.Length; ID++) { string codeaddr = objlstini[ID].Name; ObjectData defgroup; ObjectDefinition def; if (objdefini == null) { skipDefsNow = true; defgroup = new ObjectData(); } else { if (!objdefini.ContainsKey(codeaddr)) { codeaddr = "0"; } defgroup = objdefini[codeaddr]; } if (!skipDefsNow && !string.IsNullOrEmpty(defgroup.CodeFile)) { if (progress != null) { progress.SetStep("Compiling: " + defgroup.CodeFile); } bool errorOccured = false; string errorText = ""; def = CompileObjectDefinition(defgroup, out errorOccured, out errorText); if (errorOccured) { KeyValuePair <string, string> errorValue = new KeyValuePair <string, string>( defgroup.CodeFile, errorText); log.Add(errorValue.Value); compileErrors.Add(errorValue); } } else { def = new DefaultObjectDefinition(); } if (Mission) { LevelData.MisnObjDefs.Add(def); } else { LevelData.ObjDefs.Add(def); } // The only reason .Model is checked for null is for objects that don't yet have any // models defined for them. It would be annoying seeing that error all the time! if (string.IsNullOrEmpty(defgroup.CodeFile) && !string.IsNullOrEmpty(defgroup.Model)) { if (progress != null) { progress.SetStep("Loading: " + defgroup.Model); } // Otherwise, if the model file doesn't exist and/or no texture file is defined, // load the "default object" instead ("?"). if (!File.Exists(defgroup.Model) || // Model file missing OR string.IsNullOrEmpty(defgroup.Texture) || // Texture file undefined OR LevelData.Textures == null || // Textures not loaded OR ((!LevelData.Textures.ContainsKey(defgroup.Texture) && // Texture file not among loaded textures 1 AND (!LevelData.Textures.ContainsKey(defgroup.Texture.ToLowerInvariant()) && // Texture file not among loaded textures 2 AND (!LevelData.Textures.ContainsKey(defgroup.Texture.ToUpperInvariant())))))) // Texture file not among loaded textures 3 { ObjectData error = new ObjectData { Name = defgroup.Name, Model = defgroup.Model, Texture = defgroup.Texture }; objectErrors.Add(error); defgroup.Model = null; } } def.Init(defgroup, objlstini[ID].Name); def.SetInternalName(objlstini[ID].Name); } if (compileErrors.Count > 0) { DialogResult result = MessageBox.Show(this, "Could not compile object definitions. Would you like to update them to the latest defaults? This will reset any custom object code.", "Object Definitions Compilation Error", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { initerror = true; bool error = CopyDefaultObjectDefinitions(); if (!error) { MessageBox.Show("Please restart SALVL to complete the operation.", "SALVL", MessageBoxButtons.OK); } return; } } if (objectErrors.Count > 0) { int count = objectErrors.Count; List <string> errorStrings = new List <string> { "\nSET object load errors:" }; foreach (ObjectData o in objectErrors) { bool texEmpty = string.IsNullOrEmpty(o.Texture); bool texExists = (!string.IsNullOrEmpty(o.Texture) && LevelData.Textures != null && (LevelData.Textures.ContainsKey(o.Texture) || LevelData.Textures.ContainsKey(o.Texture.ToLowerInvariant()))); errorStrings.Add(""); errorStrings.Add("Object:\t\t" + o.Name); errorStrings.Add("\tModel:"); errorStrings.Add("\t\tName:\t" + o.Model); errorStrings.Add("\t\tExists:\t" + File.Exists(o.Model)); errorStrings.Add("\tTexture:"); errorStrings.Add("\t\tName:\t" + ((texEmpty) ? "(N/A)" : o.Texture)); errorStrings.Add("\t\tExists:\t" + texExists); } log.AddRange(errorStrings); osd.AddMessage(levelName + ":\n" + count + (Mission ? " Mission SET" : " SET") + (count == 1 ? " object " : " objects ") + "failed to load their model(s).\n" + "Please check SET object load errors in the log for details.\n", 300); log.WriteLog(); } LevelData.StateChanged += LevelData_StateChanged; LevelData.InvalidateRenderState(); }
/// <summary> /// Инициализация реквизитов объекта /// </summary> protected override void CreatePreDefinedFields() { #region необходимые операции до создания реквизитов и заполнения полей if (NsgSettings.Regime == NsgSoft.Common.NsgViewTypes.Load) { base.CreatePreDefinedFields(); } #endregion //необходимые операции до создания реквизитов и заполнения полей #region начало инициализации NsgSoft.DataObjects.NsgReportObject #endregion //начало инициализации NsgSoft.DataObjects.NsgReportObject #region создание System.Guid Идентификатор { NsgDataGuid Идентификатор = null; if (ObjectList.Contains("Идентификатор")) { Идентификатор = ObjectList["Идентификатор"] as NsgDataGuid; } else { Идентификатор = new NsgDataGuid(); } //NsgDataGuid Идентификатор.IsLoadedFromDll = true; Идентификатор.StringFormat = ""; Идентификатор.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; Идентификатор.IncludeInPredefined = false; Идентификатор.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Идентификатор.Required = false; Идентификатор.EmptyValue = ""; Идентификатор.NullAllow = false; Идентификатор.IndexType = NsgSoft.Database.NsgRekvisitIndexType.UniqueControl; Идентификатор.FieldName = "_ID"; Идентификатор.SaveInDatabase = false; Идентификатор.InformMetaDataOnValueChanged = false; Идентификатор.Visible = true; Идентификатор.Name = "Идентификатор"; Идентификатор.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Идентификатор.Description = "Идентификатор"; Идентификатор.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.ReadOnly; Идентификатор.GroupName = ""; Идентификатор.Guid = NsgService.StringToGuid("6641581a-f112-449d-8342-f5a8c56064b6"); if (!ObjectList.Contains("Идентификатор")) { ObjectList.Add(Идентификатор); } } #endregion //создание System.Guid Идентификатор #region создание System.Int64 Автоинкремент { NsgDataInteger Автоинкремент = null; if (ObjectList.Contains("Автоинкремент")) { Автоинкремент = ObjectList["Автоинкремент"] as NsgDataInteger; } else { Автоинкремент = new NsgDataInteger(); } //NsgDataInteger Автоинкремент.IsLoadedFromDll = true; Автоинкремент.DefaultValue = 0M; Автоинкремент.MinValue = 0M; Автоинкремент.MaxValue = 0M; Автоинкремент.UseCalculator = true; Автоинкремент.StringFormat = ""; Автоинкремент.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; Автоинкремент.IncludeInPredefined = false; Автоинкремент.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Автоинкремент.Required = false; Автоинкремент.EmptyValue = ""; Автоинкремент.NullAllow = false; Автоинкремент.IndexType = NsgSoft.Database.NsgRekvisitIndexType.UniqueControl; Автоинкремент.FieldName = "_AutoInc"; Автоинкремент.SaveInDatabase = false; Автоинкремент.InformMetaDataOnValueChanged = false; Автоинкремент.Visible = true; Автоинкремент.Name = "Автоинкремент"; Автоинкремент.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Автоинкремент.Description = "Автоинкремент"; Автоинкремент.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Hidden; Автоинкремент.GroupName = ""; Автоинкремент.Guid = NsgService.StringToGuid("6c8f5131-1db2-4f88-a214-180485af86ea"); if (!ObjectList.Contains("Автоинкремент")) { ObjectList.Add(Автоинкремент); } } #endregion //создание System.Int64 Автоинкремент #region создание ОбменникВалют.Метаданные.Обменник.ЗагрузкаКурсовФорма Форма { NsgDataForm Форма = null; if (ObjectList.Contains("Форма")) { Форма = ObjectList["Форма"] as NsgDataForm; } else { Форма = new NsgDataForm(); } //NsgDataForm Форма.IsLoadedFromDll = true; Форма.FormClassName = "ОбменникВалют.Метаданные.Обменник.ЗагрузкаКурсовФорма"; Форма.SaveInDatabase = false; Форма.StringFormat = ""; Форма.SubType = NsgSoft.Common.NsgRekvisitSubType.ElementForm; Форма.IncludeInPredefined = false; Форма.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Форма.Required = false; Форма.EmptyValue = ""; Форма.NullAllow = false; Форма.IndexType = NsgSoft.Database.NsgRekvisitIndexType.None; Форма.FieldName = "Forma"; Форма.InformMetaDataOnValueChanged = false; Форма.Visible = true; Форма.Name = "Форма"; Форма.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Форма.Description = "Форма"; Форма.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Full; Форма.GroupName = ""; Форма.Guid = NsgService.StringToGuid("a81ed0e1-ccb0-4e3a-817a-f0600f90ad55"); if (!ObjectList.Contains("Форма")) { ObjectList.Add(Форма); } } #endregion //создание ОбменникВалют.Метаданные.Обменник.ЗагрузкаКурсовФорма Форма #region создание Обменник.Валюты Валюты { NsgDataTypedReference Валюты = null; if (ObjectList.Contains("Валюты")) { Валюты = ObjectList["Валюты"] as NsgDataTypedReference; } else { Валюты = new NsgDataTypedReference(); } //NsgDataTypedReference Валюты.IsLoadedFromDll = true; Валюты.ReferentGroup = "Обменник"; Валюты.ReferentName = "Валюты"; Валюты.SaveInDatabase = false; Валюты.OwnerName = ""; Валюты.AllowEmptyOwner = false; Валюты.StringFormat = ""; Валюты.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; Валюты.IncludeInPredefined = false; Валюты.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Валюты.Required = false; Валюты.EmptyValue = ""; Валюты.NullAllow = false; Валюты.IndexType = NsgSoft.Database.NsgRekvisitIndexType.None; Валюты.FieldName = "Valjuty"; Валюты.InformMetaDataOnValueChanged = false; Валюты.Visible = true; Валюты.Name = "Валюты"; Валюты.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Валюты.Description = "Валюты"; Валюты.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Full; Валюты.GroupName = ""; Валюты.Guid = NsgService.StringToGuid("a167bd7f-533e-48d7-9cff-62a7b49f2a99"); if (!ObjectList.Contains("Валюты")) { ObjectList.Add(Валюты); } } #endregion //создание Обменник.Валюты Валюты #region создание System.DateTime Период { NsgDataDateTime Период = null; if (ObjectList.Contains("Период")) { Период = ObjectList["Период"] as NsgDataDateTime; } else { Период = new NsgDataDateTime(); } //NsgDataDateTime Период.IsLoadedFromDll = true; Период.Format = NsgSoft.Common.NsgDateTimeFormat.DateTime; Период.StringFormat = ""; Период.SubType = NsgSoft.Common.NsgRekvisitSubType.Common; Период.IncludeInPredefined = false; Период.PeriodicType = NsgSoft.Database.PeriodicTypes.None; Период.Required = false; Период.EmptyValue = ""; Период.NullAllow = false; Период.IndexType = NsgSoft.Database.NsgRekvisitIndexType.None; Период.FieldName = "Period"; Период.SaveInDatabase = false; Период.InformMetaDataOnValueChanged = false; Период.Visible = true; Период.Name = "Период"; Период.Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Период.Description = "Период"; Период.EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Full; Период.GroupName = ""; Период.Guid = NsgService.StringToGuid("58c1caaa-1465-4ec5-a82a-6883fedc31a6"); if (!ObjectList.Contains("Период")) { ObjectList.Add(Период); } } #endregion //создание System.DateTime Период #region заполнение полей класса //NsgReportObject IsLoadedFromDll = true; Name = "ЗагрузкаКурсов"; Visible = true; Guid = NsgService.StringToGuid("3d6925ed-1f20-4348-b448-c67a337f16c4"); DefaultSortingName = ""; DefaultElementFormName = ""; DefaultListFormName = ""; ValueMask = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "{Представление}" }); SearchType = NsgSoft.Database.NsgComparison.Contain; SearchFieldName = ""; DatabaseName = ""; VisibleAdminOnly = false; TableName = "_report_ZagruzkaKursov"; Presentation = new NsgSoft.DataObjects.NsgLanguageString(new System.String[] { "(Default)" }, new System.Object[] { "" }); Description = "Отчет"; EditorVisible = NsgSoft.DataObjects.NsgDataObjectEditorAccess.Full; GroupName = "Обменник"; #endregion //заполнение полей класса #region окончание инициализации NsgSoft.DataObjects.NsgReportObject #endregion //окончание инициализации NsgSoft.DataObjects.NsgReportObject #region необходимые операции после создания реквизитов и заполнения полей // внести в кэш полей this.FieldsCash.Clear(); foreach (NsgSimpleObject obj in ObjectList.All) { if (!string.IsNullOrEmpty(obj.FieldName)) { this.FieldsCash.Add(obj.FieldName, obj.Name); } } #endregion //необходимые операции после создания реквизитов и заполнения полей }
void OnDestroy() { ObjectList.RemoveAtPuddleList(0); }
public WebModule() : base() { Get["/"] = parameters => { RestoreSession(); ApplicationModel appModel = new ApplicationModel(Application.APPLICATION_NAME); return(Render("index.pt", context: appModel, view: new ApplicationView(appModel, CurrentSession))); }; Get["/objs"] = parameters => // Это страница сайта с квартирами. { RestoreSession(); ObjectList objList = new ObjectList(); // Надо отлаживать в монодевелоп... ObjectListView objView = new ObjectListView(objList); return(Render("objlist.pt", context: objList, view: objView)); }; Get["/offers"] = parameters => { RestoreSession(); OfferList model = new OfferList(null); OfferListView view = new OfferListView(model); return(Render("offerlist.pt", context: model, view: view)); }; Get["/offers/{clid}"] = parameters => { int clid = int.Parse(parameters.clid); RestoreSession(); OfferList model = new OfferList(clid: clid); OfferListView view = new OfferListView(model); return(Render("offerlist.pt", context: model, view: view)); }; Get["/offer/{GUID}"] = parameters => // Эта страница с индивидуальной квартирой { RestoreSession(); string GUID = parameters.GUID; IOffer model = Application.Context.Offers.Where(x => x.GUID == GUID).FirstOrDefault(); // По идее в BrightStarDB есть у каждого объекта свой ID и наш // GUID можно к нему привязать. FIXME: Привязать! string msg = "Объект (Offer) не найден!: " + GUID; if (model == null) { Console.WriteLine(msg); // и я НЕ понял почему.... return("msg"); } else { Console.WriteLine(model); } // Надо нудно искать ошибку в основном шаблоне.... // Завтра. Вырубает.... OfferView view = new OfferView(model); return(Render("offer.pt", context: model, view: view)); }; Get["/agents"] = parameters => { RestoreSession(); AgentList model = new AgentList(); AgentListView view = new AgentListView(model); return(Render("agentlist.pt", context: model, view: view)); }; Get["/login"] = parameters => // Эта страница уже лет 20 не нужна. { RestoreSession(); LoginObject model = new LoginObject(); LoginView view = new LoginView(model, this.Request, CurrentSession); // return View["login.pt", testModel]; // Оставим для истории. // Это, к стати правильный вариант отрисовки по шаблону. return(Render("login.pt", context: model, view: view)); }; // Принимаем данные пользователя из формы регистрации Post["/login"] = parameters => { RestoreSession(); LoginObject model = new LoginObject(); LoginView view = new LoginView(model, this.Request, CurrentSession); Response response = null; bool res = view.Process(); CurrentSession = view.Session; // Обновление сессии if (res) { response = Response.AsRedirect("/"); } else // Неуданая идентификация { response = Response.AsRedirect("/login"); } // Перенаправить браузер на домашнюю страницу. return(InSession(response)); }; Get["/logout"] = parameters => // Эта страница уже лет 20 не нужна. { RestoreSession(); LoginObject model = new LoginObject(); LoginView view = new LoginView(model, this.Request, CurrentSession); // return View["login.pt", testModel]; // Оставим для истории. // Это, к стати правильный вариант отрисовки по шаблону. view.Logout(); CurrentSession = view.Session; return(Render("login.pt", context: model, view: view)); }; Post["/clustering"] = parameters => { RestoreSession(); Response response = null; int num = 0; try { num = int.Parse(this.Request.Form.max); int clnum = 5; FlatClusterAnalyzer a = FlatClusterAnalyzer.AnalyzeFlatWithCluster(num); a.Store(clnum); CurrentSession["message"] = info("Обработано для " + num + " квартир, " + clnum + " кластеров", msg: "Успешный запуск"); CurrentSession["analysis_data"] = a; } catch (FormatException) { CurrentSession["message"] = error("Неправильное число квартир", msg: "Неуспешный запуск"); } response = Response.AsRedirect("/analysis"); return(InSession(response)); }; Get["/analysis"] = parameters => { RestoreSession(); ClusterList model = new ClusterList(); ClusterListView view = new ClusterListView(model); return(Render("clusters.pt", context: model, view: view)); }; Post["/analysis"] = parameters => { RestoreSession(); ClusterList model = new ClusterList(); ClusterListView view = new ClusterListView(model); FlatClusterAnalyzer analyzer = null; var form = this.Request.Form; if (form.reconstruct != null) { try { analyzer = (FlatClusterAnalyzer)CurrentSession["analysis_data"]; int k = int.Parse(form.numclusters); Console.WriteLine("---> K=" + k); analyzer.Store(k); CurrentSession["message"] = info("Произведена перестройка кластера", msg: "Удачное завершение операции"); } catch { // В сессии нет данных по кластеру. CurrentSession["message"] = error("Похоже кластер не рассчитан", msg: "Неудачная операция"); } } return(InSession(Response.AsRedirect("/analysis"))); }; }
internal ObjectListItem(ObjectList owner, Object dataItem) : base(dataItem, null, null) { _owner = owner; _fields = new String[owner.AllFields.Count]; }
public static int SplitFile(string datafilename, string inifilename, string projectFolderName) { try { byte[] datafile = File.ReadAllBytes(datafilename); IniData inifile = IniSerializer.Deserialize <IniData>(inifilename); if (inifile.MD5 != null && inifile.MD5.Count > 0) { string datahash = HelperFunctions.FileHash(datafile); if (!inifile.MD5.Any(h => h.Equals(datahash, StringComparison.OrdinalIgnoreCase))) { Console.WriteLine("The file {0} is not valid for use with the INI {1}.", datafilename, inifilename); return((int)ERRORVALUE.InvalidDataMapping); } } ByteConverter.BigEndian = SonicRetro.SAModel.ByteConverter.BigEndian = inifile.BigEndian; Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, Path.GetDirectoryName(datafilename)); if (inifile.Compressed) { datafile = FraGag.Compression.Prs.Decompress(datafile); } uint imageBase = HelperFunctions.SetupEXE(ref datafile) ?? inifile.ImageBase.Value; if (Path.GetExtension(datafilename).Equals(".rel", StringComparison.OrdinalIgnoreCase)) { HelperFunctions.FixRELPointers(datafile); } bool SA2 = inifile.Game == Game.SA2 | inifile.Game == Game.SA2B; ModelFormat modelfmt = 0; LandTableFormat landfmt = 0; switch (inifile.Game) { case Game.SA1: modelfmt = ModelFormat.Basic; landfmt = LandTableFormat.SA1; break; case Game.SADX: modelfmt = ModelFormat.BasicDX; landfmt = LandTableFormat.SADX; break; case Game.SA2: case Game.SA2B: modelfmt = ModelFormat.Chunk; landfmt = LandTableFormat.SA2; break; } int itemcount = 0; Dictionary <string, MasterObjectListEntry> masterobjlist = new Dictionary <string, MasterObjectListEntry>(); Dictionary <string, Dictionary <string, int> > objnamecounts = new Dictionary <string, Dictionary <string, int> >(); Stopwatch timer = new Stopwatch(); timer.Start(); foreach (KeyValuePair <string, SA_Tools.FileInfo> item in inifile.Files) { if (string.IsNullOrEmpty(item.Key)) { continue; } string filedesc = item.Key; SA_Tools.FileInfo data = item.Value; Dictionary <string, string> customProperties = data.CustomProperties; string type = data.Type; int address = data.Address; bool nohash = false; string fileOutputPath = string.Concat(projectFolderName, data.Filename); Console.WriteLine(item.Key + ": " + data.Address.ToString("X") + " → " + fileOutputPath); Directory.CreateDirectory(Path.GetDirectoryName(fileOutputPath)); switch (type) { case "landtable": new LandTable(datafile, address, imageBase, landfmt) { Description = item.Key }.SaveToFile(fileOutputPath, landfmt); break; case "model": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, modelfmt); string[] mdlanis = new string[0]; if (customProperties.ContainsKey("animations")) { mdlanis = customProperties["animations"].Split(','); } string[] mdlmorphs = new string[0]; if (customProperties.ContainsKey("morphs")) { mdlmorphs = customProperties["morphs"].Split(','); } ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, mdlmorphs, null, item.Key, null, modelfmt); } break; case "basicmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.Basic); string[] mdlanis = new string[0]; if (customProperties.ContainsKey("animations")) { mdlanis = customProperties["animations"].Split(','); } string[] mdlmorphs = new string[0]; if (customProperties.ContainsKey("morphs")) { mdlmorphs = customProperties["morphs"].Split(','); } ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, mdlmorphs, null, item.Key, null, ModelFormat.Basic); } break; case "basicdxmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.BasicDX); string[] mdlanis = new string[0]; if (customProperties.ContainsKey("animations")) { mdlanis = customProperties["animations"].Split(','); } string[] mdlmorphs = new string[0]; if (customProperties.ContainsKey("morphs")) { mdlmorphs = customProperties["morphs"].Split(','); } ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, mdlmorphs, null, item.Key, null, ModelFormat.BasicDX); } break; case "chunkmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.Chunk); string[] mdlanis = new string[0]; if (customProperties.ContainsKey("animations")) { mdlanis = customProperties["animations"].Split(','); } string[] mdlmorphs = new string[0]; if (customProperties.ContainsKey("morphs")) { mdlmorphs = customProperties["morphs"].Split(','); } ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, mdlmorphs, null, item.Key, null, ModelFormat.Chunk); } break; case "action": { NJS_ACTION ani = new NJS_ACTION(datafile, address, imageBase, modelfmt); ani.Animation.Name = filedesc; ani.Animation.Save(fileOutputPath); } break; case "animation": new NJS_MOTION(datafile, address, imageBase, int.Parse(customProperties["numparts"], NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo)) { Name = filedesc } .Save(fileOutputPath); break; case "objlist": { ObjectListEntry[] objs = ObjectList.Load(datafile, address, imageBase, SA2); if (inifile.MasterObjectList != null) { foreach (ObjectListEntry obj in objs) { if (!masterobjlist.ContainsKey(obj.CodeString)) { masterobjlist.Add(obj.CodeString, new MasterObjectListEntry(obj)); } if (!objnamecounts.ContainsKey(obj.CodeString)) { objnamecounts.Add(obj.CodeString, new Dictionary <string, int>() { { obj.Name, 1 } }); } else if (!objnamecounts[obj.CodeString].ContainsKey(obj.Name)) { objnamecounts[obj.CodeString].Add(obj.Name, 1); } else { objnamecounts[obj.CodeString][obj.Name]++; } } } objs.Save(fileOutputPath); } break; case "startpos": if (SA2) { SA2StartPosList.Load(datafile, address).Save(fileOutputPath); } else { SA1StartPosList.Load(datafile, address).Save(fileOutputPath); } break; case "texlist": TextureList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "leveltexlist": new LevelTextureList(datafile, address, imageBase).Save(fileOutputPath); break; case "triallevellist": TrialLevelList.Save(TrialLevelList.Load(datafile, address, imageBase), fileOutputPath); break; case "bosslevellist": BossLevelList.Save(BossLevelList.Load(datafile, address), fileOutputPath); break; case "fieldstartpos": FieldStartPosList.Load(datafile, address).Save(fileOutputPath); break; case "soundtestlist": SoundTestList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "musiclist": { int muscnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); MusicList.Load(datafile, address, imageBase, muscnt).Save(fileOutputPath); } break; case "soundlist": SoundList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "stringarray": { int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); Languages lang = Languages.Japanese; if (data.CustomProperties.ContainsKey("language")) { lang = (Languages)Enum.Parse(typeof(Languages), data.CustomProperties["language"], true); } StringArray.Load(datafile, address, imageBase, cnt, lang).Save(fileOutputPath); } break; case "nextlevellist": NextLevelList.Load(datafile, address).Save(fileOutputPath); break; case "cutscenetext": { int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); new CutsceneText(datafile, address, imageBase, cnt).Save(fileOutputPath, out string[] hashes); data.MD5Hash = string.Join(",", hashes); nohash = true; } break; case "recapscreen": { int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); RecapScreenList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath, out string[][] hashes); string[] hash2 = new string[hashes.Length]; for (int i = 0; i < hashes.Length; i++) { hash2[i] = string.Join(",", hashes[i]); } data.MD5Hash = string.Join(":", hash2); nohash = true; } break; case "npctext": { int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); NPCTextList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath, out string[][] hashes); string[] hash2 = new string[hashes.Length]; for (int i = 0; i < hashes.Length; i++) { hash2[i] = string.Join(",", hashes[i]); } data.MD5Hash = string.Join(":", hash2); nohash = true; } break; case "levelclearflags": LevelClearFlagList.Save(LevelClearFlagList.Load(datafile, address), fileOutputPath); break; case "deathzone": { List <DeathZoneFlags> flags = new List <DeathZoneFlags>(); string path = Path.GetDirectoryName(fileOutputPath); List <string> hashes = new List <string>(); int num = 0; while (ByteConverter.ToUInt32(datafile, address + 4) != 0) { flags.Add(new DeathZoneFlags(datafile, address)); string file = Path.Combine(path, num++.ToString(NumberFormatInfo.InvariantInfo) + (modelfmt == ModelFormat.Chunk ? ".sa2mdl" : ".sa1mdl")); ModelFile.CreateFile(file, new NJS_OBJECT(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, modelfmt), null, null, null, null, null, modelfmt); hashes.Add(HelperFunctions.FileHash(file)); address += 8; } flags.ToArray().Save(fileOutputPath); hashes.Insert(0, HelperFunctions.FileHash(fileOutputPath)); data.MD5Hash = string.Join(",", hashes.ToArray()); nohash = true; } break; case "skyboxscale": { int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); SkyboxScaleList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath); } break; case "stageselectlist": { int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); StageSelectLevelList.Load(datafile, address, cnt).Save(fileOutputPath); } break; case "levelrankscores": LevelRankScoresList.Load(datafile, address).Save(fileOutputPath); break; case "levelranktimes": LevelRankTimesList.Load(datafile, address).Save(fileOutputPath); break; case "endpos": SA2EndPosList.Load(datafile, address).Save(fileOutputPath); break; case "animationlist": { int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); SA2AnimationInfoList.Load(datafile, address, cnt).Save(fileOutputPath); } break; case "levelpathlist": { List <string> hashes = new List <string>(); ushort lvlnum = (ushort)ByteConverter.ToUInt32(datafile, address); while (lvlnum != 0xFFFF) { int ptr = ByteConverter.ToInt32(datafile, address + 4); if (ptr != 0) { ptr = (int)((uint)ptr - imageBase); SA1LevelAct level = new SA1LevelAct(lvlnum); string lvldir = Path.Combine(fileOutputPath, level.ToString()); PathList.Load(datafile, ptr, imageBase).Save(lvldir, out string[] lvlhashes); hashes.Add(level.ToString() + ":" + string.Join(",", lvlhashes)); } address += 8; lvlnum = (ushort)ByteConverter.ToUInt32(datafile, address); } data.MD5Hash = string.Join("|", hashes.ToArray()); nohash = true; } break; case "pathlist": { PathList.Load(datafile, address, imageBase).Save(fileOutputPath, out string[] hashes); data.MD5Hash = string.Join(",", hashes.ToArray()); nohash = true; } break; case "stagelightdatalist": SA1StageLightDataList.Load(datafile, address).Save(fileOutputPath); break; case "weldlist": WeldList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "bmitemattrlist": BlackMarketItemAttributesList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "creditstextlist": CreditsTextList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "animindexlist": { Directory.CreateDirectory(fileOutputPath); List <string> hashes = new List <string>(); int i = ByteConverter.ToInt16(datafile, address); while (i != -1) { new NJS_MOTION(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, ByteConverter.ToInt16(datafile, address + 2)) .Save(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim"); hashes.Add(i.ToString(NumberFormatInfo.InvariantInfo) + ":" + HelperFunctions.FileHash(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim")); address += 8; i = ByteConverter.ToInt16(datafile, address); } data.MD5Hash = string.Join("|", hashes.ToArray()); nohash = true; } break; case "storysequence": SA2StoryList.Load(datafile, address).Save(fileOutputPath); break; default: // raw binary { byte[] bin = new byte[int.Parse(customProperties["size"], NumberStyles.HexNumber)]; Array.Copy(datafile, address, bin, 0, bin.Length); File.WriteAllBytes(fileOutputPath, bin); } break; } if (!nohash) { data.MD5Hash = HelperFunctions.FileHash(fileOutputPath); } itemcount++; } if (inifile.MasterObjectList != null) { foreach (KeyValuePair <string, MasterObjectListEntry> obj in masterobjlist) { KeyValuePair <string, int> name = new KeyValuePair <string, int>(); foreach (KeyValuePair <string, int> it in objnamecounts[obj.Key]) { if (it.Value > name.Value) { name = it; } } obj.Value.Name = name.Key; obj.Value.Names = objnamecounts[obj.Key].Select((it) => it.Key).ToArray(); } string masterObjectListOutputPath = string.Concat(projectFolderName, inifile.MasterObjectList); IniSerializer.Serialize(masterobjlist, masterObjectListOutputPath); } IniSerializer.Serialize(inifile, Path.Combine(projectFolderName, Path.GetFileNameWithoutExtension(datafilename) + "_data.ini")); timer.Stop(); Console.WriteLine("Split " + itemcount + " items in " + timer.Elapsed.TotalSeconds + " seconds."); Console.WriteLine(); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); Console.WriteLine("Press any key to exit."); Console.ReadLine(); return((int)ERRORVALUE.UnhandledException); } return((int)ERRORVALUE.Success); }