public ConfigStore(string connectString, TimeSpan timeout) { if (string.IsNullOrEmpty(connectString)) { throw new ArgumentException("connectString"); } if (timeout.Ticks <= 0) { throw new ArgumentException("timeout"); } m_timeout = timeout; m_connectString = connectString; m_domains = new DomainManager(this); m_addresses = new AddressManager(this); m_certificates = new CertificateManager(this); m_anchors = new AnchorManager(this); m_dnsRecords = new DnsRecordManager(this); m_administrators = new AdministratorManager(this); m_properties = new PropertyManager(this); m_blobs = new NamedBlobManager(this); m_Mdns = new MdnManager(this); m_bundles = new BundleManager(this); m_certPolicies = new CertPolicyManager(this, new CertPolicyParseValidator()); m_certPolicyGroups = new CertPolicyGroupManager(this); }
/// <summary> /// Constructs the PluginDebuggerHelper. /// </summary> /// <param name="dte">Automation object from Visual Studio.</param> /// <param name="properties">PropertyManager set to a valid project/platform.</param> protected PluginDebuggerBase(DTE2 dte, PropertyManager properties) { if (dte == null) { throw new ArgumentNullException("dte"); } if (properties == null) { throw new ArgumentNullException("properties"); } Dte = dte; // Every second, check for a new instance of the plug-in to attach to. // Note that although the timer itself runs on a separate thread, the event // is fired from the main UI thread during message processing, thus we do not // need to worry about threading issues. pluginFinderTimer_ = new Timer(); pluginFinderTimer_.Tick += new EventHandler(FindAndAttachToPlugin); pluginFinderForbiddenPids_ = new List<uint>(); processSearcher_ = new ProcessSearcher(); pluginFinderTimer_.Interval = InitialPluginCheckFrequency; pluginFinderTimer_.Start(); }
protected Tile () { _uid = Guid.NewGuid(); _dependents = new List<DependentTile>(); _propertyManager = new PropertyManager(_propertyClassManager, this); _propertyManager.CustomProperties.Modified += (s, e) => OnModified(EventArgs.Empty); }
public ObjectClass(string name) { _uid = Guid.NewGuid(); _name = new ResourceName(this, name); _origin = Point.Zero; _propertyManager = new PropertyManager(_propertyClassManager, this); _propertyManager.CustomProperties.Modified += (s, e) => OnModified(EventArgs.Empty); }
/// <summary> /// Initializes the object and all control elements of the game. /// </summary> private GameObjectManager() { teamMgr = new TeamManager(); fightMgr = new FightManager(); objectCreator = new ObjectCreator(); moveMgr = new MoveManager(); groupMgr = new GroupManager(); propertyMgr = new PropertyManager(); hitTest = new HitTest(); solarSystemMgr = new SolarSystemManager(); gameSerializer = new GameSerializer(); }
public void TestDeserialise() { var id = new IdTable(); var refs = new ReferenceTable(); var props = new PropertyManager(); var lessees = new LesseeManager(); var projects = new ProjectManager(); Xml.Read("D:\\Projects\\Olivia2\\Olivia2.Persistence.Test\\Properties.xml", props, refs, id); Xml.Read("D:\\Projects\\Olivia2\\Olivia2.Persistence.Test\\Lessees.xml", lessees, refs, id); Xml.Read("D:\\Projects\\Olivia2\\Olivia2.Persistence.Test\\Abrechnung 2011.xml", projects, refs, id); refs.Update(id); Equals(props[0].Name, "Haus1"); Equals(props[0].Flats[0].Name, "Wohnung A"); Equals(projects.Current.Assignments[0].Flat, props[0].Flats[0]); }
private void button1_Click(object sender, EventArgs e) { var exception = new HttpException("This is an exception", "This is why the exception happened"); var assemblyManager = new AssemblyManager(); var typeManager = new TypeManager(); var constructorManager = new ConstructorManager(); var ilManager = new ILManager(); var propertyManager = new PropertyManager(); var assembly = assemblyManager.InstantiateAssemblyBuilder(); var module = assemblyManager.GenerateModuleBuilder(assembly); var builder = typeManager.InstantiateTypeBuilder(module, "MyFirstType"); var ctor = constructorManager.GenerateParameterlessConstructor(builder); ilManager.EmitConstrucorIL(ctor); propertyManager.DefineProperty(builder, typeof(System.String), "Type"); propertyManager.DefineProperty(builder, typeof(System.String), "Title"); propertyManager.DefineProperty(builder, typeof(System.String), "Detail"); // Some reflective shit here. // Find the properties unique to this exception var properties = exception.GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (PropertyInfo property in properties) { propertyManager.DefineProperty(builder, property.PropertyType, property.Name); } var type = builder.CreateType(); var iAccessor = TypeAccessor.Create(type); var eAccessor = TypeAccessor.Create(exception.GetType()); ConstructorInfo ctorInfo = type.GetConstructor(new Type[] { }); var instance = ctorInfo.Invoke(new object[] { }); iAccessor[instance, "Type"] = "http://problems.rakuten.co.uk/internal-server-error"; iAccessor[instance, "Title"] = "Internal Server Error"; iAccessor[instance, "Detail"] = exception.Message; foreach (PropertyInfo property in properties) { iAccessor[instance, property.Name] = eAccessor[exception, property.Name]; } //// assembly.Save(assembly.GetName().Name + ".dll"); }
public static void Main(string[] args) { Console.WriteLine("Collecting updates from weather server…"); var domainMapper = new DomainMapper(); var propertyManager = new PropertyManager(); var repository = new ZmqRepository(domainMapper, propertyManager, @"C:\temp\data"); var cities = repository.GetAll<City>(); foreach (var city in cities) { Console.WriteLine(string.Format("Received: {0}, Weather: {1}", city.ToInfo(), city.Weather.ToInfo())); } }
public ObjectInstance(ObjectClass objClass, int posX, int posY) { _uid = Guid.NewGuid(); _class = objClass; _posX = posX; _posY = posY; _rotation = 0; _scaleX = 1f; _scaleY = 1f; _propertyManager = new PropertyManager(_propertyClassManager, this); _propertyManager.PropertyParent = objClass; _propertyManager.CustomProperties.Modified += (s, e) => OnModified(EventArgs.Empty); UpdateBounds(); }
public ObjectInstance(SerializationInfo info, StreamingContext context) { _uid = (Guid)info.GetValue("Uid", typeof(Guid)); _classId = (Guid)info.GetValue("ClassID", typeof(Guid)); _posX = info.GetInt32("PosX"); _posY = info.GetInt32("PosY"); _rotation = info.GetSingle("Rotation"); _scaleX = info.GetSingle("ScaleX"); _scaleY = info.GetSingle("ScaleY"); _propertyManager = new Framework.PropertyManager(_propertyClassManager, this); PropertyCollection props = info.GetValue("Properties", typeof(PropertyCollection)) as PropertyCollection; foreach (Property p in props) _propertyManager.CustomProperties.Add(p.Clone() as Property); }
protected Layer (string name) { Uid = Guid.NewGuid(); _opacity = 1f; _visible = true; _rasterMode = RasterMode.Point; _gridWidth = 16; _gridHeight = 16; _gridColor = new Color(0, 0, 0, 128); _name = name; _propertyManager = new PropertyManager(_propertyClassManager, this); _propertyManager.CustomProperties.Modified += (s, e) => OnModified(EventArgs.Empty); }
public static void Write(PropertyManager properties, string filepath, IdTable ids) { var f = new XmlWriter(filepath); f.Begin("Properties"); var list = new Olivia2.Model.Property[properties.Count]; lock ( properties ) properties.CopyTo(list, 0); foreach (var p in list) { f.Begin(p, ids); f.Begin("Flats"); var flatlist = new Flat[p.Flats.Count]; lock ( p.Flats ) p.Flats.CopyTo(flatlist, 0); foreach ( var flat in flatlist ) f.Write(flat, ids); f.End("Flats"); f.End(p); } f.End("Properties"); f.Close(); }
public static void Read(string filepath, PropertyManager properties, ReferenceTable references, IdTable ids) { var xml = new XPathDocument(filepath).CreateNavigator(); var pi = xml.Select("/Properties/Property"); while ( pi.MoveNext() ) { var pnode = pi.Current; var p = properties.Create(); ids[p] = new Guid(pnode.GetAttribute("id", "")); AssignProperties(pnode, p, references); var fi = pnode.Select("Flats/Flat"); while ( fi.MoveNext() ) { var fnode = fi.Current; var f = p.CreateFlat(); ids[f] = new Guid(fnode.GetAttribute("id", "")); AssignProperties(fnode, f, references); } } }
public void TestSerialise() { var id = new IdTable(); var props = new PropertyManager(); var lessees = new LesseeManager(); Xml.Write(props, "Properties.xml", id); Xml.Write(lessees, "Lessees.xml", id); var projects = new ProjectManager(); projects.Add(new Project()); projects.Current.Property = props[0]; projects.Current.CreateCost(); var fac = projects.Current.Assignments.First(a => a.Flat == props[0].Flats[0]); var assignment = new FlatAssignment(projects.Current); assignment.Start = DateTime.Now; assignment.End = DateTime.Now.AddMonths(3); assignment.Lessee = lessees[0]; fac.Add(assignment); Xml.Write(projects, "", id); }
public static void Main(string[] args) { IDictionary<int, City> cities = new Dictionary<int, City>(); var domainMapper = new DomainMapper(); var propertyManager = new PropertyManager(); var repository = new ZmqRepository(domainMapper, propertyManager, @"C:\temp\data"); IUnitOfWork unitOfWork = new ChangeTrackUoW(propertyManager, repository); var randomizer = new Random(DateTime.Now.Millisecond); var weather = new Weather { Temperature = randomizer.Next(-80, 135), RelativeHumidity = randomizer.Next(10, 60) }; for (var i = 0; i < 3; i++) { var city = new City { CitySize = CitySize.Medium, Name = "Test", ZipCode = randomizer.Next(1, 100000), Weather = weather }; unitOfWork.StartTransaction(city); try { unitOfWork.Commit(); } catch (System.Exception exception) { unitOfWork.Rollback(); Console.WriteLine("Error: " + exception.Message); } } }
public Utility(Int32 index, Int32 price, String group, Banker banker, PropertyManager propertyManager, Dice dice) : base(index, price, 0, group, banker, propertyManager) { this.dice = dice; }
void Awake() { _instance = this; }
/// <summary> /// Import products from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual void ImportProductsFromXlsx(Stream stream) { //var start = DateTime.Now; using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) throw new NopException("No worksheet found"); //the columns var properties = new List<PropertyByName<Product>>(); var poz = 1; while (true) { try { var cell = worksheet.Cells[1, poz]; if (cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())) break; poz += 1; properties.Add(new PropertyByName<Product>(cell.Value.ToString())); } catch { break; } } var manager = new PropertyManager<Product>(properties.ToArray()); var attributProperties = new[] { new PropertyByName<ExportProductAttribute>("AttributeId"), new PropertyByName<ExportProductAttribute>("AttributeName"), new PropertyByName<ExportProductAttribute>("AttributeTextPrompt"), new PropertyByName<ExportProductAttribute>("AttributeIsRequired"), new PropertyByName<ExportProductAttribute>("AttributeControlType") { DropDownElements = AttributeControlType.TextBox.ToSelectList(useLocalization: false) }, new PropertyByName<ExportProductAttribute>("AttributeDisplayOrder"), new PropertyByName<ExportProductAttribute>("ProductAttributeValueId"), new PropertyByName<ExportProductAttribute>("ValueName"), new PropertyByName<ExportProductAttribute>("AttributeValueType") { DropDownElements = AttributeValueType.Simple.ToSelectList(useLocalization: false) }, new PropertyByName<ExportProductAttribute>("AssociatedProductId"), new PropertyByName<ExportProductAttribute>("ColorSquaresRgb"), new PropertyByName<ExportProductAttribute>("ImageSquaresPictureId"), new PropertyByName<ExportProductAttribute>("PriceAdjustment"), new PropertyByName<ExportProductAttribute>("WeightAdjustment"), new PropertyByName<ExportProductAttribute>("Cost"), new PropertyByName<ExportProductAttribute>("Quantity"), new PropertyByName<ExportProductAttribute>("IsPreSelected"), new PropertyByName<ExportProductAttribute>("DisplayOrder"), new PropertyByName<ExportProductAttribute>("PictureId") }; var managerProductAttribute = new PropertyManager<ExportProductAttribute>(attributProperties); var endRow = 2; var allCategoriesNames = new List<string>(); var allSku = new List<string>(); var tempProperty = manager.GetProperty("Categories"); var categoryCellNum = tempProperty.Return(p => p.PropertyOrderPosition, -1); tempProperty = manager.GetProperty("SKU"); var skuCellNum = tempProperty.Return(p => p.PropertyOrderPosition, -1); var allManufacturersNames = new List<string>(); tempProperty = manager.GetProperty("Manufacturers"); var manufacturerCellNum = tempProperty.Return(p => p.PropertyOrderPosition, -1); manager.SetSelectList("ProductType", ProductType.SimpleProduct.ToSelectList(useLocalization: false)); manager.SetSelectList("GiftCardType", GiftCardType.Virtual.ToSelectList(useLocalization: false)); manager.SetSelectList("DownloadActivationType", DownloadActivationType.Manually.ToSelectList(useLocalization: false)); manager.SetSelectList("ManageInventoryMethod", ManageInventoryMethod.DontManageStock.ToSelectList(useLocalization: false)); manager.SetSelectList("LowStockActivity", LowStockActivity.Nothing.ToSelectList(useLocalization: false)); manager.SetSelectList("BackorderMode", BackorderMode.NoBackorders.ToSelectList(useLocalization: false)); manager.SetSelectList("RecurringCyclePeriod", RecurringProductCyclePeriod.Days.ToSelectList(useLocalization: false)); manager.SetSelectList("RentalPricePeriod", RentalPricePeriod.Days.ToSelectList(useLocalization: false)); manager.SetSelectList("Vendor", _vendorService.GetAllVendors(showHidden: true).Select(v => v as BaseEntity).ToSelectList(p => (p as Vendor).Return(v => v.Name, String.Empty))); manager.SetSelectList("ProductTemplate", _productTemplateService.GetAllProductTemplates().Select(pt => pt as BaseEntity).ToSelectList(p => (p as ProductTemplate).Return(pt => pt.Name, String.Empty))); manager.SetSelectList("DeliveryDate", _shippingService.GetAllDeliveryDates().Select(dd => dd as BaseEntity).ToSelectList(p => (p as DeliveryDate).Return(dd => dd.Name, String.Empty))); manager.SetSelectList("TaxCategory", _taxCategoryService.GetAllTaxCategories().Select(tc => tc as BaseEntity).ToSelectList(p => (p as TaxCategory).Return(tc => tc.Name, String.Empty))); manager.SetSelectList("BasepriceUnit", _measureService.GetAllMeasureWeights().Select(mw => mw as BaseEntity).ToSelectList(p =>(p as MeasureWeight).Return(mw => mw.Name, String.Empty))); manager.SetSelectList("BasepriceBaseUnit", _measureService.GetAllMeasureWeights().Select(mw => mw as BaseEntity).ToSelectList(p => (p as MeasureWeight).Return(mw => mw.Name, String.Empty))); var allAttributeIds = new List<int>(); var attributeIdCellNum = managerProductAttribute.GetProperty("AttributeId").PropertyOrderPosition + ExportProductAttribute.ProducAttributeCellOffset; //find end of data while (true) { var allColumnsAreEmpty = manager.GetProperties .Select(property => worksheet.Cells[endRow, property.PropertyOrderPosition]) .All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())); if (allColumnsAreEmpty) break; if (new[] { 1, 2 }.Select(cellNum => worksheet.Cells[endRow, cellNum]).All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())) && worksheet.Row(endRow).OutlineLevel == 0) { var cellValue = worksheet.Cells[endRow, attributeIdCellNum].Value; try { var aid = cellValue.Return(Convert.ToInt32, -1); var productAttribute = _productAttributeService.GetProductAttributeById(aid); if (productAttribute != null) worksheet.Row(endRow).OutlineLevel = 1; } catch (FormatException) { if (cellValue.Return(cv => cv.ToString(), String.Empty) == "AttributeId") worksheet.Row(endRow).OutlineLevel = 1; } } if (worksheet.Row(endRow).OutlineLevel != 0) { managerProductAttribute.ReadFromXlsx(worksheet, endRow, ExportProductAttribute.ProducAttributeCellOffset); if (!managerProductAttribute.IsCaption) { var aid = worksheet.Cells[endRow, attributeIdCellNum].Value.Return(Convert.ToInt32, -1); allAttributeIds.Add(aid); } endRow++; continue; } if (categoryCellNum > 0) { var categoryIds = worksheet.Cells[endRow, categoryCellNum].Value.Return(p => p.ToString(), string.Empty); if (!categoryIds.IsEmpty()) allCategoriesNames.AddRange(categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim())); } if (skuCellNum > 0) { var sku = worksheet.Cells[endRow, skuCellNum].Value.Return(p => p.ToString(), string.Empty); if (!sku.IsEmpty()) allSku.Add(sku); } if (manufacturerCellNum > 0) { var manufacturerIds = worksheet.Cells[endRow, manufacturerCellNum].Value.Return(p => p.ToString(), string.Empty); if (!manufacturerIds.IsEmpty()) allManufacturersNames.AddRange(manufacturerIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim())); } endRow++; } //performance optimization, the check for the existence of the categories in one SQL request var notExistingCategories = _categoryService.GetNotExistingCategories(allCategoriesNames.ToArray()); if (notExistingCategories.Any()) { throw new ArgumentException(string.Format("The following category name(s) don't exist - {0}", string.Join(", ", notExistingCategories))); } //performance optimization, the check for the existence of the manufacturers in one SQL request var notExistingManufacturers = _manufacturerService.GetNotExistingManufacturers(allManufacturersNames.ToArray()); if (notExistingManufacturers.Any()) { throw new ArgumentException(string.Format("The following manufacturer name(s) don't exist - {0}", string.Join(", ", notExistingManufacturers))); } //performance optimization, the check for the existence of the product attributes in one SQL request var notExistingProductAttributes = _productAttributeService.GetNotExistingAttributes(allAttributeIds.ToArray()); if (notExistingProductAttributes.Any()) { throw new ArgumentException(string.Format("The following product attribute ID(s) don't exist - {0}", string.Join(", ", notExistingProductAttributes))); } //performance optimization, load all products by SKU in one SQL request var allProductsBySku = _productService.GetProductsBySku(allSku.ToArray()); //performance optimization, load all categories IDs for products in one SQL request var allProductsCategoryIds = _categoryService.GetProductCategoryIds(allProductsBySku.Select(p => p.Id).ToArray()); //performance optimization, load all categories in one SQL request var allCategories = _categoryService.GetAllCategories(showHidden: true); //performance optimization, load all manufacturers IDs for products in one SQL request var allProductsManufacturerIds = _manufacturerService.GetProductManufacturerIds(allProductsBySku.Select(p => p.Id).ToArray()); //performance optimization, load all manufacturers in one SQL request var allManufacturers = _manufacturerService.GetAllManufacturers(showHidden: true); //product to import images var productPictureMetadata = new List<ProductPictureMetadata>(); Product lastLoadedProduct = null; for (var iRow = 2; iRow < endRow; iRow++) { //imports product attributes if (worksheet.Row(iRow).OutlineLevel != 0) { if (_catalogSettings.ExportImportProductAttributes) { managerProductAttribute.ReadFromXlsx(worksheet, iRow, ExportProductAttribute.ProducAttributeCellOffset); if (lastLoadedProduct == null || managerProductAttribute.IsCaption) continue; var productAttributeId = managerProductAttribute.GetProperty("AttributeId").IntValue; var attributeControlTypeId = managerProductAttribute.GetProperty("AttributeControlType").IntValue; var productAttributeValueId = managerProductAttribute.GetProperty("ProductAttributeValueId").IntValue; var associatedProductId = managerProductAttribute.GetProperty("AssociatedProductId").IntValue; var valueName = managerProductAttribute.GetProperty("ValueName").StringValue; var attributeValueTypeId = managerProductAttribute.GetProperty("AttributeValueType").IntValue; var colorSquaresRgb = managerProductAttribute.GetProperty("ColorSquaresRgb").StringValue; var imageSquaresPictureId = managerProductAttribute.GetProperty("ImageSquaresPictureId").IntValue; var priceAdjustment = managerProductAttribute.GetProperty("PriceAdjustment").DecimalValue; var weightAdjustment = managerProductAttribute.GetProperty("WeightAdjustment").DecimalValue; var cost = managerProductAttribute.GetProperty("Cost").DecimalValue; var quantity = managerProductAttribute.GetProperty("Quantity").IntValue; var isPreSelected = managerProductAttribute.GetProperty("IsPreSelected").BooleanValue; var displayOrder = managerProductAttribute.GetProperty("DisplayOrder").IntValue; var pictureId = managerProductAttribute.GetProperty("PictureId").IntValue; var textPrompt = managerProductAttribute.GetProperty("AttributeTextPrompt").StringValue; var isRequired = managerProductAttribute.GetProperty("AttributeIsRequired").BooleanValue; var attributeDisplayOrder = managerProductAttribute.GetProperty("AttributeDisplayOrder").IntValue; var productAttributeMapping = lastLoadedProduct.ProductAttributeMappings.FirstOrDefault(pam => pam.ProductAttributeId == productAttributeId); if (productAttributeMapping == null) { //insert mapping productAttributeMapping = new ProductAttributeMapping { ProductId = lastLoadedProduct.Id, ProductAttributeId = productAttributeId, TextPrompt = textPrompt, IsRequired = isRequired, AttributeControlTypeId = attributeControlTypeId, DisplayOrder = attributeDisplayOrder }; _productAttributeService.InsertProductAttributeMapping(productAttributeMapping); } else { productAttributeMapping.AttributeControlTypeId = attributeControlTypeId; productAttributeMapping.TextPrompt = textPrompt; productAttributeMapping.IsRequired = isRequired; productAttributeMapping.DisplayOrder = attributeDisplayOrder; _productAttributeService.UpdateProductAttributeMapping(productAttributeMapping); } var pav = _productAttributeService.GetProductAttributeValueById(productAttributeValueId); var attributeControlType = (AttributeControlType) attributeControlTypeId; if (pav == null) { switch (attributeControlType) { case AttributeControlType.Datepicker: case AttributeControlType.FileUpload: case AttributeControlType.MultilineTextbox: case AttributeControlType.TextBox: continue; } pav = new ProductAttributeValue { ProductAttributeMappingId = productAttributeMapping.Id, AttributeValueType = (AttributeValueType) attributeValueTypeId, AssociatedProductId = associatedProductId, Name = valueName, PriceAdjustment = priceAdjustment, WeightAdjustment = weightAdjustment, Cost = cost, IsPreSelected = isPreSelected, DisplayOrder = displayOrder, ColorSquaresRgb = colorSquaresRgb, ImageSquaresPictureId = imageSquaresPictureId, Quantity = quantity, PictureId = pictureId }; _productAttributeService.InsertProductAttributeValue(pav); } else { pav.AttributeValueTypeId = attributeValueTypeId; pav.AssociatedProductId = associatedProductId; pav.Name = valueName; pav.ColorSquaresRgb = colorSquaresRgb; pav.ImageSquaresPictureId = imageSquaresPictureId; pav.PriceAdjustment = priceAdjustment; pav.WeightAdjustment = weightAdjustment; pav.Cost = cost; pav.Quantity = quantity; pav.IsPreSelected = isPreSelected; pav.DisplayOrder = displayOrder; pav.PictureId = pictureId; _productAttributeService.UpdateProductAttributeValue(pav); } } continue; } manager.ReadFromXlsx(worksheet, iRow); var product = skuCellNum > 0 ? allProductsBySku.FirstOrDefault(p => p.Sku == manager.GetProperty("SKU").StringValue) : null; var isNew = product == null; product = product ?? new Product(); if (isNew) product.CreatedOnUtc = DateTime.UtcNow; foreach (var property in manager.GetProperties) { switch (property.PropertyName) { case "ProductType": product.ProductTypeId = property.IntValue; break; case "ParentGroupedProductId": product.ParentGroupedProductId = property.IntValue; break; case "VisibleIndividually": product.VisibleIndividually = property.BooleanValue; break; case "Name": product.Name = property.StringValue; break; case "ShortDescription": product.ShortDescription = property.StringValue; break; case "FullDescription": product.FullDescription = property.StringValue; break; case "Vendor": product.VendorId = property.IntValue; break; case "ProductTemplate": product.ProductTemplateId = property.IntValue; break; case "ShowOnHomePage": product.ShowOnHomePage = property.BooleanValue; break; case "MetaKeywords": product.MetaKeywords = property.StringValue; break; case "MetaDescription": product.MetaDescription = property.StringValue; break; case "MetaTitle": product.MetaTitle = property.StringValue; break; case "AllowCustomerReviews": product.AllowCustomerReviews = property.BooleanValue; break; case "Published": product.Published = property.BooleanValue; break; case "SKU": product.Sku = property.StringValue; break; case "ManufacturerPartNumber": product.ManufacturerPartNumber = property.StringValue; break; case "Gtin": product.Gtin = property.StringValue; break; case "IsGiftCard": product.IsGiftCard = property.BooleanValue; break; case "GiftCardType": product.GiftCardTypeId = property.IntValue; break; case "OverriddenGiftCardAmount": product.OverriddenGiftCardAmount = property.DecimalValue; break; case "RequireOtherProducts": product.RequireOtherProducts = property.BooleanValue; break; case "RequiredProductIds": product.RequiredProductIds = property.StringValue; break; case "AutomaticallyAddRequiredProducts": product.AutomaticallyAddRequiredProducts = property.BooleanValue; break; case "IsDownload": product.IsDownload = property.BooleanValue; break; case "DownloadId": product.DownloadId = property.IntValue; break; case "UnlimitedDownloads": product.UnlimitedDownloads = property.BooleanValue; break; case "MaxNumberOfDownloads": product.MaxNumberOfDownloads = property.IntValue; break; case "DownloadActivationType": product.DownloadActivationTypeId = property.IntValue; break; case "HasSampleDownload": product.HasSampleDownload = property.BooleanValue; break; case "SampleDownloadId": product.SampleDownloadId = property.IntValue; break; case "HasUserAgreement": product.HasUserAgreement = property.BooleanValue; break; case "UserAgreementText": product.UserAgreementText = property.StringValue; break; case "IsRecurring": product.IsRecurring = property.BooleanValue; break; case "RecurringCycleLength": product.RecurringCycleLength = property.IntValue; break; case "RecurringCyclePeriod": product.RecurringCyclePeriodId = property.IntValue; break; case "RecurringTotalCycles": product.RecurringTotalCycles = property.IntValue; break; case "IsRental": product.IsRental = property.BooleanValue; break; case "RentalPriceLength": product.RentalPriceLength = property.IntValue; break; case "RentalPricePeriod": product.RentalPricePeriodId = property.IntValue; break; case "IsShipEnabled": product.IsShipEnabled = property.BooleanValue; break; case "IsFreeShipping": product.IsFreeShipping = property.BooleanValue; break; case "ShipSeparately": product.ShipSeparately = property.BooleanValue; break; case "AdditionalShippingCharge": product.AdditionalShippingCharge = property.DecimalValue; break; case "DeliveryDate": product.DeliveryDateId = property.IntValue; break; case "IsTaxExempt": product.IsTaxExempt = property.BooleanValue; break; case "TaxCategory": product.TaxCategoryId = property.IntValue; break; case "IsTelecommunicationsOrBroadcastingOrElectronicServices": product.IsTelecommunicationsOrBroadcastingOrElectronicServices = property.BooleanValue; break; case "ManageInventoryMethod": product.ManageInventoryMethodId = property.IntValue; break; case "UseMultipleWarehouses": product.UseMultipleWarehouses = property.BooleanValue; break; case "WarehouseId": product.WarehouseId = property.IntValue; break; case "StockQuantity": product.StockQuantity = property.IntValue; break; case "DisplayStockAvailability": product.DisplayStockAvailability = property.BooleanValue; break; case "DisplayStockQuantity": product.DisplayStockQuantity = property.BooleanValue; break; case "MinStockQuantity": product.MinStockQuantity = property.IntValue; break; case "LowStockActivity": product.LowStockActivityId = property.IntValue; break; case "NotifyAdminForQuantityBelow": product.NotifyAdminForQuantityBelow = property.IntValue; break; case "BackorderModeId": product.BackorderModeId = property.IntValue; break; case "AllowBackInStockSubscriptions": product.AllowBackInStockSubscriptions = property.BooleanValue; break; case "OrderMinimumQuantity": product.OrderMinimumQuantity = property.IntValue; break; case "OrderMaximumQuantity": product.OrderMaximumQuantity = property.IntValue; break; case "AllowedQuantities": product.AllowedQuantities = property.StringValue; break; case "AllowAddingOnlyExistingAttributeCombinations": product.AllowAddingOnlyExistingAttributeCombinations = property.BooleanValue; break; case "NotReturnable": product.NotReturnable = property.BooleanValue; break; case "DisableBuyButton": product.DisableBuyButton = property.BooleanValue; break; case "DisableWishlistButton": product.DisableWishlistButton = property.BooleanValue; break; case "AvailableForPreOrder": product.AvailableForPreOrder = property.BooleanValue; break; case "PreOrderAvailabilityStartDateTimeUtc": product.PreOrderAvailabilityStartDateTimeUtc = property.DateTimeNullable; break; case "CallForPrice": product.CallForPrice = property.BooleanValue; break; case "Price": product.Price = property.DecimalValue; break; case "OldPrice": product.OldPrice = property.DecimalValue; break; case "ProductCost": product.ProductCost = property.DecimalValue; break; case "SpecialPrice": product.SpecialPrice = property.DecimalValueNullable; break; case "SpecialPriceStartDateTimeUtc": product.SpecialPriceStartDateTimeUtc = property.DateTimeNullable; break; case "SpecialPriceEndDateTimeUtc": product.SpecialPriceEndDateTimeUtc = property.DateTimeNullable; break; case "CustomerEntersPrice": product.CustomerEntersPrice = property.BooleanValue; break; case "MinimumCustomerEnteredPrice": product.MinimumCustomerEnteredPrice = property.DecimalValue; break; case "MaximumCustomerEnteredPrice": product.MaximumCustomerEnteredPrice = property.DecimalValue; break; case "BasepriceEnabled": product.BasepriceEnabled = property.BooleanValue; break; case "BasepriceAmount": product.BasepriceAmount = property.DecimalValue; break; case "BasepriceUnit": product.BasepriceUnitId = property.IntValue; break; case "BasepriceBaseAmount": product.BasepriceBaseAmount = property.DecimalValue; break; case "BasepriceBaseUnit": product.BasepriceBaseUnitId = property.IntValue; break; case "MarkAsNew": product.MarkAsNew = property.BooleanValue; break; case "MarkAsNewStartDateTimeUtc": product.MarkAsNewStartDateTimeUtc = property.DateTimeNullable; break; case "MarkAsNewEndDateTimeUtc": product.MarkAsNewEndDateTimeUtc = property.DateTimeNullable; break; case "Weight": product.Weight = property.DecimalValue; break; case "Length": product.Length = property.DecimalValue; break; case "Width": product.Width = property.DecimalValue; break; case "Height": product.Height = property.DecimalValue; break; } } //set default product type id if (isNew && properties.All(p => p.PropertyName != "ProductTypeId")) product.ProductType = ProductType.SimpleProduct; product.UpdatedOnUtc = DateTime.UtcNow; if (isNew) { _productService.InsertProduct(product); } else { _productService.UpdateProduct(product); } tempProperty = manager.GetProperty("SeName"); if (tempProperty != null) { var seName = tempProperty.StringValue; //search engine name _urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), 0); } tempProperty = manager.GetProperty("Categories"); if (tempProperty != null) { var categoryNames = tempProperty.StringValue; //category mappings var categories = isNew || !allProductsCategoryIds.ContainsKey(product.Id) ? new int[0] : allProductsCategoryIds[product.Id]; foreach (var categoryId in categoryNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => allCategories.First(c => c.Name == x.Trim()).Id)) { if (categories.Any(c => c == categoryId)) continue; var productCategory = new ProductCategory { ProductId = product.Id, CategoryId = categoryId, IsFeaturedProduct = false, DisplayOrder = 1 }; _categoryService.InsertProductCategory(productCategory); } } tempProperty = manager.GetProperty("Manufacturers"); if (tempProperty != null) { var manufacturerNames = tempProperty.StringValue; //manufacturer mappings var manufacturers = isNew || !allProductsManufacturerIds.ContainsKey(product.Id) ? new int[0] : allProductsManufacturerIds[product.Id]; foreach (var manufacturerId in manufacturerNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => allManufacturers.First(m => m.Name == x.Trim()).Id)) { if (manufacturers.Any(c => c == manufacturerId)) continue; var productManufacturer = new ProductManufacturer { ProductId = product.Id, ManufacturerId = manufacturerId, IsFeaturedProduct = false, DisplayOrder = 1 }; _manufacturerService.InsertProductManufacturer(productManufacturer); } } var picture1 = manager.GetProperty("Picture1").Return(p => p.StringValue, String.Empty); var picture2 = manager.GetProperty("Picture2").Return(p => p.StringValue, String.Empty); var picture3 = manager.GetProperty("Picture3").Return(p => p.StringValue, String.Empty); productPictureMetadata.Add(new ProductPictureMetadata { ProductItem = product, Picture1Path = picture1, Picture2Path = picture2, Picture3Path = picture3, IsNew = isNew }); lastLoadedProduct = product; //update "HasTierPrices" and "HasDiscountsApplied" properties //_productService.UpdateHasTierPricesProperty(product); //_productService.UpdateHasDiscountsApplied(product); } if (_mediaSettings.ImportProductImagesUsingHash && _pictureService.StoreInDb && _dataProvider.SupportedLengthOfBinaryHash() > 0) ImportProductImagesUsingHash(productPictureMetadata, allProductsBySku); else ImportProductImagesUsingServices(productPictureMetadata); } //Trace.WriteLine(DateTime.Now-start); }
/// <summary> /// Destroys the current game (mission) and sets a new empty control elements of the game. /// </summary> public void DestroyGame() { // Destroys targeted group (destroys pointers). groupMgr.UntargetGroup(); // Destroys all object in the game. foreach (var item in objectCreator.GetInicializedSolarSystems()) { item.Destroy(); } // Creates a new empty control elements of the game. teamMgr = new TeamManager(); fightMgr = new FightManager(); objectCreator = new ObjectCreator(); moveMgr = new MoveManager(); groupMgr = new GroupManager(); propertyMgr = new PropertyManager(); hitTest = new HitTest(); solarSystemMgr = new SolarSystemManager(); }
private void OnViewerIndexChanged(int oldIndex, int newIndex) { PropertyManager.Refresh(); }
private void propertyManagerToolStripMenuItem_Click_1(object sender, EventArgs e) { PropertyManager m = new PropertyManager(); lang.SetLang(m); m.MdiParent = this; m.WindowState = FormWindowState.Maximized; m.Show(); taskbar.AddTool(m, Properties.Resources.property_manager_64x64); }
private static int GetNumMajorCantrips(TreasureDeath profile) { int numMajors = 0; var dropRate = PropertyManager.GetDouble("major_cantrip_drop_rate").Item; if (dropRate <= 0) { return(0); } var dropRateMod = 1.0 / dropRate; double lootQualityMod = 1.0f; if (PropertyManager.GetBool("loot_quality_mod").Item&& profile.LootQualityMod > 0 && profile.LootQualityMod < 1) { lootQualityMod = 1.0f - profile.LootQualityMod; } switch (profile.Tier) { case 1: numMajors = 0; break; case 2: if (ThreadSafeRandom.Next(1, (int)(500 * dropRateMod * lootQualityMod)) == 1) { numMajors = 1; } break; case 3: if (ThreadSafeRandom.Next(1, (int)(500 * dropRateMod * lootQualityMod)) == 1) { numMajors = 1; } if (ThreadSafeRandom.Next(1, (int)(10000 * dropRateMod * lootQualityMod)) == 1) { numMajors = 2; } break; case 4: case 5: case 6: if (ThreadSafeRandom.Next(1, (int)(500 * dropRateMod * lootQualityMod)) == 1) { numMajors = 1; } if (ThreadSafeRandom.Next(1, (int)(5000 * dropRateMod * lootQualityMod)) == 1) { numMajors = 2; } break; case 7: default: if (ThreadSafeRandom.Next(1, (int)(500 * dropRateMod * lootQualityMod)) == 1) { numMajors = 1; } if (ThreadSafeRandom.Next(1, (int)(5000 * dropRateMod * lootQualityMod)) == 1) { numMajors = 2; } if (ThreadSafeRandom.Next(1, (int)(15000 * dropRateMod * lootQualityMod)) == 1) { numMajors = 3; } break; } return(numMajors); }
public override void ActOnUse(WorldObject activator) { if (!(activator is Player player)) { return; } if (IsBusy) { player.Session.Network.EnqueueSend(new GameEventWeenieErrorWithString(player.Session, WeenieErrorWithString.The_IsCurrentlyInUse, Name)); return; } IsBusy = true; player.IsBusy = true; if (player.AdvocateQuest || player.PkLevel != PKLevel.NPK || player is Admin || player.WeenieType == WeenieType.Admin || player is Sentinel || player.WeenieType == WeenieType.Sentinel) // PlayerKillers, Admins and Sentinels can't be Advocates. { var actionChain = new ActionChain(); var failMotion = UseTargetFailureAnimation != MotionCommand.Invalid ? UseTargetFailureAnimation : MotionCommand.Twitch2; EnqueueBroadcastMotion(new Motion(this, failMotion)); var motionTable = DatManager.PortalDat.ReadFromDat <MotionTable>(MotionTableId); var useTime = motionTable.GetAnimationLength(failMotion); player.LastUseTime += useTime; actionChain.AddDelaySeconds(useTime); actionChain.AddAction(player, () => { player.IsBusy = false; Reset(); }); actionChain.EnqueueChain(); return; } var faneTimer = new ActionChain(); if (player.CombatMode != CombatMode.NonCombat) { var stanceTime = player.SetCombatMode(CombatMode.NonCombat); faneTimer.AddDelaySeconds(stanceTime); player.LastUseTime += stanceTime; } var useMotion = UseTargetSuccessAnimation != MotionCommand.Invalid ? UseUserAnimation : MotionCommand.BowDeep; var animTime = player.EnqueueMotion(faneTimer, useMotion); player.LastUseTime += animTime; var successMotion = UseTargetSuccessAnimation != MotionCommand.Invalid ? UseTargetSuccessAnimation : MotionCommand.Twitch1; var successTime = EnqueueMotion(faneTimer, successMotion); player.LastUseTime += successTime; faneTimer.AddAction(player, () => { player.AdvocateQuest = true; player.Session.Network.EnqueueSend(new GameMessageSystemChat(GetProperty(PropertyString.UseMessage), ChatMessageType.Broadcast)); if (UseCreateItem != null) { var useCreateItem = WorldObjectFactory.CreateNewWorldObject(UseCreateItem.Value); if (useCreateItem != null) { player.TryCreateInInventoryWithNetworking(useCreateItem); } } if (PropertyManager.GetBool("advocate_fane_auto_bestow").Item) { Advocate.Bestow(player, (int)PropertyManager.GetDouble("advocate_fane_auto_bestow_level").Item); } }); faneTimer.AddAction(player, () => { player.IsBusy = false; Reset(); }); faneTimer.EnqueueChain(); }
/// <summary> /// Import products from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual void ImportProductsFromXlsx(Stream stream) { using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) { throw new NopException("No worksheet found"); } //the columns var properties = GetPropertiesByExcelCells <Product>(worksheet); var manager = new PropertyManager <Product>(properties); var endRow = 2; var allCategoriesNames = new List <string>(); var allSku = new List <string>(); var tempProperty = manager.GetProperty("Categories"); var categoryCellNum = tempProperty.Return(p => p.PropertyOrderPosition, -1); tempProperty = manager.GetProperty("SKU"); var skuCellNum = tempProperty.Return(p => p.PropertyOrderPosition, -1); var allManufacturersNames = new List <string>(); tempProperty = manager.GetProperty("Manufacturers"); var manufacturerCellNum = tempProperty.Return(p => p.PropertyOrderPosition, -1); manager.SetSelectList("ProductType", ProductType.SimpleProduct.ToSelectList(useLocalization: false)); var countProductsInFile = 0; //find end of data while (true) { var allColumnsAreEmpty = manager.GetProperties .Select(property => worksheet.Cells[endRow, property.PropertyOrderPosition]) .All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())); if (allColumnsAreEmpty) { break; } if (categoryCellNum > 0) { var categoryIds = worksheet.Cells[endRow, categoryCellNum].Value.Return(p => p.ToString(), string.Empty); if (!categoryIds.IsEmpty()) { allCategoriesNames.AddRange(categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim())); } } if (skuCellNum > 0) { var sku = worksheet.Cells[endRow, skuCellNum].Value.Return(p => p.ToString(), string.Empty); if (!sku.IsEmpty()) { allSku.Add(sku); } } if (manufacturerCellNum > 0) { var manufacturerIds = worksheet.Cells[endRow, manufacturerCellNum].Value.Return(p => p.ToString(), string.Empty); if (!manufacturerIds.IsEmpty()) { allManufacturersNames.AddRange(manufacturerIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim())); } } //counting the number of products countProductsInFile += 1; endRow++; } //performance optimization, the check for the existence of the categories in one SQL request var notExistingCategories = _categoryService.GetNotExistingCategories(allCategoriesNames.ToArray()); if (notExistingCategories.Any()) { throw new ArgumentException(string.Format("The following category name(s) don't exist - {0}", string.Join(", ", notExistingCategories))); } //performance optimization, load all products by SKU in one SQL request var allProductsBySku = _productService.GetProductsBySku(allSku.ToArray()); //performance optimization, load all categories IDs for products in one SQL request var allProductsCategoryIds = _categoryService.GetProductCategoryIds(allProductsBySku.Select(p => p.Id).ToArray()); //performance optimization, load all categories in one SQL request var allCategories = _categoryService.GetAllCategories(showHidden: true); //product to import images var productPictureMetadata = new List <ProductPictureMetadata>(); Product lastLoadedProduct = null; for (var iRow = 2; iRow < endRow; iRow++) { manager.ReadFromXlsx(worksheet, iRow); var product = skuCellNum > 0 ? allProductsBySku.FirstOrDefault(p => p.Sku == manager.GetProperty("SKU").StringValue) : null; var isNew = product == null; product = product ?? new Product(); if (isNew) { product.CreatedOnUtc = DateTime.UtcNow; } foreach (var property in manager.GetProperties) { switch (property.PropertyName) { case "ProductType": product.ProductTypeId = property.IntValue; break; case "ParentGroupedProductId": product.ParentGroupedProductId = property.IntValue; break; case "VisibleIndividually": product.VisibleIndividually = property.BooleanValue; break; case "Name": product.Name = property.StringValue; break; case "ShortDescription": product.ShortDescription = property.StringValue; break; case "FullDescription": product.FullDescription = property.StringValue; break; case "ProductTemplate": product.ProductTemplateId = property.IntValue; break; case "ShowOnHomePage": product.ShowOnHomePage = property.BooleanValue; break; case "MetaKeywords": product.MetaKeywords = property.StringValue; break; case "MetaDescription": product.MetaDescription = property.StringValue; break; case "MetaTitle": product.MetaTitle = property.StringValue; break; case "AllowCustomerReviews": product.AllowCustomerReviews = property.BooleanValue; break; case "Published": product.Published = property.BooleanValue; break; case "SKU": product.Sku = property.StringValue; break; case "MarkAsNew": product.MarkAsNew = property.BooleanValue; break; case "MarkAsNewStartDateTimeUtc": product.MarkAsNewStartDateTimeUtc = property.DateTimeNullable; break; case "MarkAsNewEndDateTimeUtc": product.MarkAsNewEndDateTimeUtc = property.DateTimeNullable; break; } } //set some default default values if not specified if (isNew && properties.All(p => p.PropertyName != "ProductType")) { product.ProductType = ProductType.SimpleProduct; } if (isNew && properties.All(p => p.PropertyName != "VisibleIndividually")) { product.VisibleIndividually = true; } if (isNew && properties.All(p => p.PropertyName != "Published")) { product.Published = true; } product.UpdatedOnUtc = DateTime.UtcNow; if (isNew) { _productService.InsertProduct(product); } else { _productService.UpdateProduct(product); } tempProperty = manager.GetProperty("SeName"); if (tempProperty != null) { var seName = tempProperty.StringValue; //search engine name _urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), 0); } tempProperty = manager.GetProperty("Categories"); if (tempProperty != null) { var categoryNames = tempProperty.StringValue; //category mappings var categories = isNew || !allProductsCategoryIds.ContainsKey(product.Id) ? new int[0] : allProductsCategoryIds[product.Id]; var importedCategories = categoryNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => allCategories.First(c => c.Name == x.Trim()).Id).ToList(); foreach (var categoryId in importedCategories) { if (categories.Any(c => c == categoryId)) { continue; } var productCategory = new ProductCategory { ProductId = product.Id, CategoryId = categoryId, IsFeaturedProduct = false, DisplayOrder = 1 }; _categoryService.InsertProductCategory(productCategory); } //delete product categories var deletedProductCategories = categories.Where(categoryId => !importedCategories.Contains(categoryId)) .Select(categoryId => product.ProductCategories.First(pc => pc.CategoryId == categoryId)); foreach (var deletedProductCategory in deletedProductCategories) { _categoryService.DeleteProductCategory(deletedProductCategory); } } tempProperty = manager.GetProperty("ProductTags"); if (tempProperty != null) { var productTags = tempProperty.StringValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray(); //product tag mappings _productTagService.UpdateProductTags(product, productTags); } var picture1 = manager.GetProperty("Picture1").Return(p => p.StringValue, String.Empty); var picture2 = manager.GetProperty("Picture2").Return(p => p.StringValue, String.Empty); var picture3 = manager.GetProperty("Picture3").Return(p => p.StringValue, String.Empty); productPictureMetadata.Add(new ProductPictureMetadata { ProductItem = product, Picture1Path = picture1, Picture2Path = picture2, Picture3Path = picture3, IsNew = isNew }); lastLoadedProduct = product; //update "HasTierPrices" and "HasDiscountsApplied" properties //_productService.UpdateHasTierPricesProperty(product); //_productService.UpdateHasDiscountsApplied(product); } if (_mediaSettings.ImportProductImagesUsingHash && _pictureService.StoreInDb && _dataProvider.SupportedLengthOfBinaryHash() > 0) { ImportProductImagesUsingHash(productPictureMetadata, allProductsBySku); } else { ImportProductImagesUsingServices(productPictureMetadata); } //activity log _customerActivityService.InsertActivity("ImportProducts", _localizationService.GetResource("ActivityLog.ImportProducts"), countProductsInFile); } }
/// <summary> /// Import categories from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual void ImportCategoriesFromXlsx(Stream stream) { using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) { throw new NopException("No worksheet found"); } //the columns var properties = GetPropertiesByExcelCells <Category>(worksheet); var manager = new PropertyManager <Category>(properties); var iRow = 2; var setSeName = properties.Any(p => p.PropertyName == "SeName"); while (true) { var allColumnsAreEmpty = manager.GetProperties .Select(property => worksheet.Cells[iRow, property.PropertyOrderPosition]) .All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())); if (allColumnsAreEmpty) { break; } manager.ReadFromXlsx(worksheet, iRow); var category = _categoryService.GetCategoryById(manager.GetProperty("Id").IntValue); var isNew = category == null; category = category ?? new Category(); if (isNew) { category.CreatedOnUtc = DateTime.UtcNow; //default values category.PageSize = _catalogSettings.DefaultCategoryPageSize; category.PageSizeOptions = _catalogSettings.DefaultCategoryPageSizeOptions; category.Published = true; category.IncludeInTopMenu = true; category.AllowCustomersToSelectPageSize = true; } var seName = string.Empty; foreach (var property in manager.GetProperties) { switch (property.PropertyName) { case "Name": category.Name = property.StringValue; break; case "Description": category.Description = property.StringValue; break; case "CategoryTemplateId": category.CategoryTemplateId = property.IntValue; break; case "MetaKeywords": category.MetaKeywords = property.StringValue; break; case "MetaDescription": category.MetaDescription = property.StringValue; break; case "MetaTitle": category.MetaTitle = property.StringValue; break; case "ParentCategoryId": category.ParentCategoryId = property.IntValue; break; case "Picture": var picture = LoadPicture(manager.GetProperty("Picture").StringValue, category.Name, isNew ? null : (int?)category.PictureId); if (picture != null) { category.PictureId = picture.Id; } break; case "PageSize": category.PageSize = property.IntValue; break; case "AllowCustomersToSelectPageSize": category.AllowCustomersToSelectPageSize = property.BooleanValue; break; case "PageSizeOptions": category.PageSizeOptions = property.StringValue; break; case "ShowOnHomePage": category.ShowOnHomePage = property.BooleanValue; break; case "IncludeInTopMenu": category.IncludeInTopMenu = property.BooleanValue; break; case "Published": category.Published = property.BooleanValue; break; case "DisplayOrder": category.DisplayOrder = property.IntValue; break; case "SeName": seName = property.StringValue; break; } } category.UpdatedOnUtc = DateTime.UtcNow; if (isNew) { _categoryService.InsertCategory(category); } else { _categoryService.UpdateCategory(category); } //search engine name if (setSeName) { _urlRecordService.SaveSlug(category, category.ValidateSeName(seName, category.Name, true), 0); } iRow++; } //activity log _customerActivityService.InsertActivity("ImportCategories", _localizationService.GetResource("ActivityLog.ImportCategories"), iRow - 2); } }
private void propertyManagerToolStripMenuItem_Click_1(object sender, EventArgs e) { PropertyManager m = new PropertyManager(); lang.SetLang(m); m.MdiParent = this; m.WindowState = FormWindowState.Maximized; m.Show(); taskbar.AddTool(m, imageList1.Images[7]); }
public void Decay(TimeSpan elapsed) { // http://asheron.wikia.com/wiki/Item_Decay if (decayCompleted) { return; } var previousTTR = TimeToRot; if (!TimeToRot.HasValue) { TimeToRot = DefaultTimeToRot.TotalSeconds; if (this is Corpse && Level.HasValue) { log.Debug($"[CORPSE] {Name} (0x{Guid.ToString()}).Decay: TimeToRot had no value, set to {TimeToRot}"); } return; } var corpse = this as Corpse; if (corpse != null) { if (!corpse.InventoryLoaded) { return; } if (corpse.Inventory.Count == 0 && TimeToRot.Value > Corpse.EmptyDecayTime) { TimeToRot = Corpse.EmptyDecayTime; if (Level.HasValue && PropertyManager.GetBool("corpse_decay_tick_logging").Item) { log.Debug($"[CORPSE] {corpse.Name} (0x{corpse.Guid.ToString()}).Decay({elapsed.ToString()}): InventoryLoaded = {corpse.InventoryLoaded} | Inventory.Count = {corpse.Inventory.Count} | previous TimeToRot: {previousTTR} | current TimeToRot: {TimeToRot}"); } return; } } if (TimeToRot > 0) { TimeToRot -= elapsed.TotalSeconds; if (this is Corpse && Level.HasValue && PropertyManager.GetBool("corpse_decay_tick_logging").Item) { log.Debug($"[CORPSE] {corpse.Name} (0x{corpse.Guid.ToString()}).Decay({elapsed.ToString()}): previous TimeToRot: {previousTTR} | current TimeToRot: {TimeToRot}"); } // Is there still time left? if (TimeToRot > 0) { return; } TimeToRot = -2; // We force it to -2 to make sure it doesn't end up at 0 or -1. 0 indicates instant rot. -1 indicates no rot. 0 and -1 can be found in weenie defaults if (this is Corpse && Level.HasValue && PropertyManager.GetBool("corpse_decay_tick_logging").Item) { log.Debug($"[CORPSE] {corpse.Name} (0x{corpse.Guid.ToString()}).Decay({elapsed.ToString()}): previous TimeToRot: {previousTTR} | current TimeToRot: {TimeToRot}"); } } if (this is Container container && container.IsOpen) { // If you wanted to add a grace period to the container to give Player B more time to open it after Player A closes it, it would go here. return; } // Time to rot has elapsed, time to disappear... decayCompleted = true; // If this is a player corpse, puke out the corpses contents onto the landblock if (corpse != null && !corpse.IsMonster) { var inventoryGUIDs = corpse.Inventory.Keys.ToList(); var pukedItems = ""; foreach (var guid in inventoryGUIDs) { if (corpse.TryRemoveFromInventory(guid, out var item)) { item.Location = new Position(corpse.Location); item.Placement = ACE.Entity.Enum.Placement.Resting; // This is needed to make items lay flat on the ground. CurrentLandblock.AddWorldObject(item); item.SaveBiotaToDatabase(); pukedItems += $"{item.Name} (0x{item.Guid.Full.ToString("X8")}), "; } } if (pukedItems.EndsWith(", ")) { pukedItems = pukedItems.Substring(0, pukedItems.Length - 2); } log.Debug($"[CORPSE] {corpse.Name} (0x{corpse.Guid.ToString()}) at {corpse.Location.ToLOCString()} has decayed{((pukedItems == "") ? "" : $" and placed the following items on the landblock: {pukedItems}")}."); } if (corpse != null) { EnqueueBroadcast(new GameMessageScript(Guid, PlayScript.Destroy)); var actionChain = new ActionChain(); actionChain.AddDelaySeconds(1.0f); actionChain.AddAction(this, () => Destroy()); actionChain.EnqueueChain(); } else { Destroy(); } }
private static void CharacterCreateEx(ClientMessage message, Session session) { var characterCreateInfo = new CharacterCreateInfo(); characterCreateInfo.Unpack(message.Payload); // TODO: Check for Banned Name Here //DatabaseManager.Shard.IsCharacterNameBanned(characterCreateInfo.Name, isBanned => //{ // if (!isBanned) // { // SendCharacterCreateResponse(session, CharacterGenerationVerificationResponse.NameBanned); // return; // } //}); // Disable OlthoiPlay characters for now. They're not implemented yet. // FIXME: Restore OlthoiPlay characters when properly handled. if (characterCreateInfo.Heritage == (int)HeritageGroup.Olthoi || characterCreateInfo.Heritage == (int)HeritageGroup.OlthoiAcid) { SendCharacterCreateResponse(session, CharacterGenerationVerificationResponse.Pending); return; } Weenie weenie; if (ConfigManager.Config.Server.Accounts.OverrideCharacterPermissions) { if (session.AccessLevel >= AccessLevel.Developer && session.AccessLevel <= AccessLevel.Admin) { weenie = DatabaseManager.World.GetCachedWeenie("admin"); } else if (session.AccessLevel >= AccessLevel.Sentinel && session.AccessLevel <= AccessLevel.Envoy) { weenie = DatabaseManager.World.GetCachedWeenie("sentinel"); } else { weenie = DatabaseManager.World.GetCachedWeenie("human"); } if (characterCreateInfo.Heritage == (int)HeritageGroup.Olthoi && weenie.WeenieType == WeenieType.Admin) { weenie = DatabaseManager.World.GetCachedWeenie("olthoiadmin"); } if (characterCreateInfo.Heritage == (int)HeritageGroup.OlthoiAcid && weenie.WeenieType == WeenieType.Admin) { weenie = DatabaseManager.World.GetCachedWeenie("olthoiacidadmin"); } } else { weenie = DatabaseManager.World.GetCachedWeenie("human"); } if (characterCreateInfo.Heritage == (int)HeritageGroup.Olthoi && weenie.WeenieType == WeenieType.Creature) { weenie = DatabaseManager.World.GetCachedWeenie("olthoiplayer"); } if (characterCreateInfo.Heritage == (int)HeritageGroup.OlthoiAcid && weenie.WeenieType == WeenieType.Creature) { weenie = DatabaseManager.World.GetCachedWeenie("olthoiacidplayer"); } if (characterCreateInfo.IsSentinel && session.AccessLevel >= AccessLevel.Sentinel) { weenie = DatabaseManager.World.GetCachedWeenie("sentinel"); } if (characterCreateInfo.IsAdmin && session.AccessLevel >= AccessLevel.Developer) { weenie = DatabaseManager.World.GetCachedWeenie("admin"); } if (weenie == null) { weenie = DatabaseManager.World.GetCachedWeenie("human"); // Default catch-all } if (weenie == null) // If it is STILL null after the above catchall, the database is missing critical data and cannot continue with character creation. { SendCharacterCreateResponse(session, CharacterGenerationVerificationResponse.DatabaseDown); log.Error("Database does not contain the weenie for human (1). Characters cannot be created until the missing weenie is restored."); return; } // Removes the generic knife and buckler, hidden Javelin, 30 stack of arrows, and 5 stack of coins that are given to all characters // Starter Gear from the JSON file are added to the character later in the CharacterCreateEx() process weenie.PropertiesCreateList = null; var guid = GuidManager.NewPlayerGuid(); var weenieType = weenie.WeenieType; // If Database didn't have Sentinel/Admin weenies, alter the weenietype coming in. if (ConfigManager.Config.Server.Accounts.OverrideCharacterPermissions) { if (session.AccessLevel >= AccessLevel.Developer && session.AccessLevel <= AccessLevel.Admin && weenieType != WeenieType.Admin) { weenieType = WeenieType.Admin; } else if (session.AccessLevel >= AccessLevel.Sentinel && session.AccessLevel <= AccessLevel.Envoy && weenieType != WeenieType.Sentinel) { weenieType = WeenieType.Sentinel; } } var result = PlayerFactory.Create(characterCreateInfo, weenie, guid, session.AccountId, weenieType, out var player); if (result != PlayerFactory.CreateResult.Success || player == null) { SendCharacterCreateResponse(session, CharacterGenerationVerificationResponse.Corrupt); return; } if (PropertyManager.GetBool("taboo_table").Item&& DatManager.PortalDat.TabooTable.ContainsBadWord(characterCreateInfo.Name.ToLowerInvariant())) { SendCharacterCreateResponse(session, CharacterGenerationVerificationResponse.NameBanned); return; } DatabaseManager.Shard.IsCharacterNameAvailable(characterCreateInfo.Name, isAvailable => { if (!isAvailable) { SendCharacterCreateResponse(session, CharacterGenerationVerificationResponse.NameInUse); return; } var possessions = player.GetAllPossessions(); var possessedBiotas = new Collection <(Biota biota, ReaderWriterLockSlim rwLock)>(); foreach (var possession in possessions) { possessedBiotas.Add((possession.Biota, possession.BiotaDatabaseLock)); }
public static void Activate(BaseBuilding b) { UpdateStats(b); PropertyManager.MakeActive(_Property); }
public void PlayerEnterWorld() { PlayerManager.SwitchPlayerFromOfflineToOnline(this); Teleporting = true; // Save the the LoginTimestamp var lastLoginTimestamp = Time.GetUnixTime(); LoginTimestamp = lastLoginTimestamp; LastTeleportStartTimestamp = lastLoginTimestamp; Character.LastLoginTimestamp = lastLoginTimestamp; Character.TotalLogins++; CharacterChangesDetected = true; Sequences.SetSequence(SequenceType.ObjectInstance, new UShortSequence((ushort)Character.TotalLogins)); if (BarberActive) { BarberActive = false; } if (AllegianceNode != null) { AllegianceRank = (int)AllegianceNode.Rank; } else { AllegianceRank = null; } if (!Account15Days) { var accountTimeSpan = DateTime.UtcNow - Account.CreateTime; if (accountTimeSpan.TotalDays >= 15) { Account15Days = true; } } // SendSelf will trigger the entrance into portal space SendSelf(); // Update or override certain properties sent to client. SendPropertyUpdatesAndOverrides(); // Init the client with the chat channel ID's, and then notify the player that they've choined the associated channels. UpdateChatChannels(); var general = new GameEventWeenieErrorWithString(Session, WeenieErrorWithString.YouHaveEnteredThe_Channel, "General"); var trade = new GameEventWeenieErrorWithString(Session, WeenieErrorWithString.YouHaveEnteredThe_Channel, "Trade"); var lfg = new GameEventWeenieErrorWithString(Session, WeenieErrorWithString.YouHaveEnteredThe_Channel, "LFG"); var roleplay = new GameEventWeenieErrorWithString(Session, WeenieErrorWithString.YouHaveEnteredThe_Channel, "Roleplay"); Session.Network.EnqueueSend(general, trade, lfg, roleplay); // check if vassals earned XP while offline HandleAllegianceOnLogin(); HandleHouseOnLogin(); // retail appeared to send the squelch list very early, // even before the CreatePlayer, but doing it here if (SquelchManager.HasSquelches) { SquelchManager.SendSquelchDB(); } AuditItemSpells(); HandleMissingXp(); HandleSkillCreditRefund(); if (PlayerKillerStatus == PlayerKillerStatus.PKLite && !PropertyManager.GetBool("pkl_server").Item) { var actionChain = new ActionChain(); actionChain.AddDelaySeconds(3.0f); actionChain.AddAction(this, () => { UpdateProperty(this, PropertyInt.PlayerKillerStatus, (int)PlayerKillerStatus.NPK, true); Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.YouAreNonPKAgain)); }); actionChain.EnqueueChain(); } HandleDBUpdates(); }
/// <summary> /// Called when a player dies, in conjunction with Die() /// </summary> /// <param name="lastDamager">The last damager that landed the death blow</param> /// <param name="damageType">The damage type for the death message</param> public override DeathMessage OnDeath(DamageHistoryInfo lastDamager, DamageType damageType, bool criticalHit = false) { var topDamager = DamageHistory.GetTopDamager(false); HandlePKDeathBroadcast(lastDamager, topDamager); var deathMessage = base.OnDeath(lastDamager, damageType, criticalHit); var lastDamagerObj = lastDamager?.TryGetAttacker(); if (lastDamagerObj != null) { lastDamagerObj.EmoteManager.OnKill(this); } var playerMsg = ""; if (lastDamager != null) { playerMsg = string.Format(deathMessage.Victim, Name, lastDamager.Name); } else { playerMsg = deathMessage.Victim; } var msgYourDeath = new GameEventYourDeath(Session, playerMsg); Session.Network.EnqueueSend(msgYourDeath); // broadcast to nearby players var nearbyMsg = ""; if (lastDamager != null) { nearbyMsg = string.Format(deathMessage.Broadcast, Name, lastDamager.Name); } else { nearbyMsg = deathMessage.Broadcast; } var broadcastMsg = new GameMessageSystemChat(nearbyMsg, ChatMessageType.Broadcast); log.Debug("[CORPSE] " + nearbyMsg); var excludePlayers = new List <Player>(); if (lastDamagerObj is Player lastDamagerPlayer) { excludePlayers.Add(lastDamagerPlayer); } var nearbyPlayers = EnqueueBroadcast(excludePlayers, false, broadcastMsg); excludePlayers.AddRange(nearbyPlayers); excludePlayers.Add(this); // exclude self if (Fellowship != null) { Fellowship.OnDeath(this); } // if the player's lifestone is in a different landblock, also broadcast their demise to that landblock if (PropertyManager.GetBool("lifestone_broadcast_death").Item&& Sanctuary != null && Location.Landblock != Sanctuary.Landblock) { // ActionBroadcastKill might not work if other players around lifestone aren't aware of this player yet... // this existing broadcast method is also based on the current visible objects to the player, // and the player hasn't entered portal space or teleported back to the lifestone yet, so this doesn't work //ActionBroadcastKill(nearbyMsg, Guid, lastDamager.Guid); // instead, we get all of the players in the lifestone landblock + adjacent landblocks, // and possibly limit that to some radius around the landblock? var lifestoneBlock = LandblockManager.GetLandblock(new LandblockId(Sanctuary.Landblock << 16 | 0xFFFF), true); lifestoneBlock.EnqueueBroadcast(excludePlayers, true, Sanctuary, LocalBroadcastRangeSq, broadcastMsg); } return(deathMessage); }
public static void TurbineChatReceived(ClientMessage clientMessage, Session session) { if (!PropertyManager.GetBool("use_turbine_chat").Item) { return; } clientMessage.Payload.ReadUInt32(); // Bytes to follow var chatBlobType = (ChatNetworkBlobType)clientMessage.Payload.ReadUInt32(); var chatBlobDispatchType = (ChatNetworkBlobDispatchType)clientMessage.Payload.ReadUInt32(); clientMessage.Payload.ReadUInt32(); // Always 1 clientMessage.Payload.ReadUInt32(); // Always 0 clientMessage.Payload.ReadUInt32(); // Always 0 clientMessage.Payload.ReadUInt32(); // Always 0 clientMessage.Payload.ReadUInt32(); // Always 0 clientMessage.Payload.ReadUInt32(); // Bytes to follow if (session.Player.IsGagged) { session.Player.SendGagError(); return; } if (chatBlobType == ChatNetworkBlobType.NETBLOB_REQUEST_BINARY) { var contextId = clientMessage.Payload.ReadUInt32(); // 0x01 - 0x71 (maybe higher), typically though 0x01 - 0x0F clientMessage.Payload.ReadUInt32(); // Always 2 clientMessage.Payload.ReadUInt32(); // Always 2 var channelID = clientMessage.Payload.ReadUInt32(); int messageLen = clientMessage.Payload.ReadByte(); if ((messageLen & 0x80) > 0) // PackedByte { byte lowbyte = clientMessage.Payload.ReadByte(); messageLen = ((messageLen & 0x7F) << 8) | lowbyte; } var messageBytes = clientMessage.Payload.ReadBytes(messageLen * 2); var message = Encoding.Unicode.GetString(messageBytes); clientMessage.Payload.ReadUInt32(); // Always 0x0C var senderID = clientMessage.Payload.ReadUInt32(); clientMessage.Payload.ReadUInt32(); // Always 0 var chatType = (ChatType)clientMessage.Payload.ReadUInt32(); var adjustedChannelID = channelID; var adjustedchatType = chatType; if (chatBlobDispatchType == ChatNetworkBlobDispatchType.ASYNCMETHOD_SENDTOROOMBYNAME) { adjustedChannelID = chatType switch { ChatType.Allegiance => TurbineChatChannel.Allegiance, ChatType.General => TurbineChatChannel.General, ChatType.Trade => TurbineChatChannel.Trade, ChatType.LFG => TurbineChatChannel.LFG, ChatType.Roleplay => TurbineChatChannel.Roleplay, ChatType.Society => TurbineChatChannel.Society, ChatType.SocietyCelHan => TurbineChatChannel.Society, ChatType.SocietyEldWeb => TurbineChatChannel.Society, ChatType.SocietyRadBlo => TurbineChatChannel.Society, ChatType.Olthoi => TurbineChatChannel.Olthoi, _ => TurbineChatChannel.General }; adjustedchatType = (ChatType)adjustedChannelID; } else if (chatBlobDispatchType == ChatNetworkBlobDispatchType.ASYNCMETHOD_SENDTOROOMBYID) { if (channelID > TurbineChatChannel.Olthoi || channelID == TurbineChatChannel.Allegiance) // Channel must be an allegiance channel { adjustedchatType = ChatType.Allegiance; } else if (channelID == TurbineChatChannel.Olthoi) // Channel must be the Olthoi play channel { adjustedchatType = ChatType.Olthoi; } else if (channelID >= TurbineChatChannel.Society) // Channel must be a society restricted channel { adjustedchatType = ChatType.Society; } else // Channel must be one of the channels available to all players { if (channelID == TurbineChatChannel.General) { adjustedchatType = ChatType.General; } else if (channelID == TurbineChatChannel.Trade) { adjustedchatType = ChatType.Trade; } else if (channelID == TurbineChatChannel.LFG) { adjustedchatType = ChatType.LFG; } else if (channelID == TurbineChatChannel.Roleplay) { adjustedchatType = ChatType.Roleplay; } } } if (channelID != adjustedChannelID) { log.Debug($"[CHAT] ChannelID ({channelID}) was adjusted to {adjustedChannelID} | ChatNetworkBlobDispatchType: {chatBlobDispatchType}"); } if (chatType != adjustedchatType) { log.Debug($"[CHAT] ChatType ({chatType}) was adjusted to {adjustedchatType} | ChatNetworkBlobDispatchType: {chatBlobDispatchType}"); } var gameMessageTurbineChat = new GameMessageTurbineChat(ChatNetworkBlobType.NETBLOB_EVENT_BINARY, ChatNetworkBlobDispatchType.ASYNCMETHOD_SENDTOROOMBYNAME, adjustedChannelID, session.Player.Name, message, senderID, adjustedchatType); if (adjustedChannelID > TurbineChatChannel.Olthoi || adjustedChannelID == TurbineChatChannel.Allegiance) // Channel must be an allegiance channel { //var allegiance = AllegianceManager.FindAllegiance(channelID); var allegiance = AllegianceManager.GetAllegiance(session.Player); if (allegiance != null) { // is sender booted / gagged? if (!allegiance.IsMember(session.Player.Guid)) { return; } if (allegiance.IsFiltered(session.Player.Guid)) { return; } // iterate through all allegiance members foreach (var member in allegiance.Members.Keys) { // is this allegiance member online? var online = PlayerManager.GetOnlinePlayer(member); if (online == null) { continue; } // is this member booted / gagged? if (allegiance.IsFiltered(member) || online.SquelchManager.Squelches.Contains(session.Player, ChatMessageType.Allegiance)) { continue; } // does this player have allegiance chat filtered? if (!online.GetCharacterOption(CharacterOption.ListenToAllegianceChat)) { continue; } online.Session.Network.EnqueueSend(gameMessageTurbineChat); } session.Network.EnqueueSend(new GameMessageTurbineChat(ChatNetworkBlobType.NETBLOB_RESPONSE_BINARY, ChatNetworkBlobDispatchType.ASYNCMETHOD_SENDTOROOMBYNAME, contextId, null, null, 0, adjustedchatType)); } } else if (adjustedChannelID == TurbineChatChannel.Olthoi) // Channel must be the Olthoi play channel { if (!session.Player.IsOlthoiPlayer) { return; } if (PropertyManager.GetBool("chat_disable_olthoi").Item) { HandleChatReject(session, contextId, chatType, gameMessageTurbineChat, string.Empty); return; } if (PropertyManager.GetBool("chat_echo_only").Item) { session.Network.EnqueueSend(gameMessageTurbineChat); session.Network.EnqueueSend(new GameMessageTurbineChat(ChatNetworkBlobType.NETBLOB_RESPONSE_BINARY, ChatNetworkBlobDispatchType.ASYNCMETHOD_SENDTOROOMBYNAME, contextId, null, null, 0, adjustedchatType)); return; } if (PropertyManager.GetBool("chat_requires_account_15days").Item&& !session.Player.Account15Days) { HandleChatReject(session, contextId, chatType, gameMessageTurbineChat, "because this account is not 15 days old"); return; } var chat_requires_account_time_seconds = PropertyManager.GetLong("chat_requires_account_time_seconds").Item; if (chat_requires_account_time_seconds > 0 && (DateTime.UtcNow - session.Player.Account.CreateTime).TotalSeconds < chat_requires_account_time_seconds) { HandleChatReject(session, contextId, chatType, gameMessageTurbineChat, "because this account is not old enough"); return; } var chat_requires_player_age = PropertyManager.GetLong("chat_requires_player_age").Item; if (chat_requires_player_age > 0 && session.Player.Age < chat_requires_player_age) { HandleChatReject(session, contextId, chatType, gameMessageTurbineChat, "because this character has not been played enough"); return; } var chat_requires_player_level = PropertyManager.GetLong("chat_requires_player_level").Item; if (chat_requires_player_level > 0 && session.Player.Level < chat_requires_player_level) { HandleChatReject(session, contextId, chatType, gameMessageTurbineChat, $"because this character has reached level {chat_requires_player_level}"); return; } foreach (var recipient in PlayerManager.GetAllOnline()) { // handle filters if (!recipient.IsOlthoiPlayer && !recipient.IsAdmin) { continue; } if (PropertyManager.GetBool("chat_disable_olthoi").Item) { if (PropertyManager.GetBool("chat_echo_reject").Item) { session.Network.EnqueueSend(gameMessageTurbineChat); } session.Network.EnqueueSend(new GameMessageTurbineChat(ChatNetworkBlobType.NETBLOB_RESPONSE_BINARY, ChatNetworkBlobDispatchType.ASYNCMETHOD_SENDTOROOMBYNAME, contextId, null, null, 0, adjustedchatType)); return; } if (recipient.SquelchManager.Squelches.Contains(session.Player, ChatMessageType.AllChannels)) { continue; } recipient.Session.Network.EnqueueSend(gameMessageTurbineChat); } session.Network.EnqueueSend(new GameMessageTurbineChat(ChatNetworkBlobType.NETBLOB_RESPONSE_BINARY, ChatNetworkBlobDispatchType.ASYNCMETHOD_SENDTOROOMBYNAME, contextId, null, null, 0, adjustedchatType)); } else if (adjustedChannelID >= TurbineChatChannel.Society) // Channel must be a society restricted channel { var senderSociety = session.Player.Society; //var adjustedChatType = senderSociety switch //{ // FactionBits.CelestialHand => ChatType.SocietyCelHan, // FactionBits.EldrytchWeb => ChatType.SocietyEldWeb, // FactionBits.RadiantBlood => ChatType.SocietyRadBlo, // _ => ChatType.Society //}; //gameMessageTurbineChat = new GameMessageTurbineChat(ChatNetworkBlobType.NETBLOB_EVENT_BINARY, channelID, session.Player.Name, message, senderID, adjustedChatType); if (senderSociety == FactionBits.None) { ChatPacket.SendServerMessage(session, "You do not belong to a society.", ChatMessageType.Broadcast); // I don't know if this is how it was done on the live servers return; } foreach (var recipient in PlayerManager.GetAllOnline()) { // handle filters if (senderSociety != recipient.Society && !recipient.IsAdmin) { continue; } if (!recipient.GetCharacterOption(CharacterOption.ListenToSocietyChat)) { continue; } if (recipient.SquelchManager.Squelches.Contains(session.Player, ChatMessageType.AllChannels)) { continue; } recipient.Session.Network.EnqueueSend(gameMessageTurbineChat); } session.Network.EnqueueSend(new GameMessageTurbineChat(ChatNetworkBlobType.NETBLOB_RESPONSE_BINARY, ChatNetworkBlobDispatchType.ASYNCMETHOD_SENDTOROOMBYNAME, contextId, null, null, 0, adjustedchatType)); } else // Channel must be one of the channels available to all players { if (session.Player.IsOlthoiPlayer) { //HandleChatReject(session, contextId, chatType, gameMessageTurbineChat, "because this account is not 15 days old"); return; } if (PropertyManager.GetBool("chat_echo_only").Item) { session.Network.EnqueueSend(gameMessageTurbineChat); session.Network.EnqueueSend(new GameMessageTurbineChat(ChatNetworkBlobType.NETBLOB_RESPONSE_BINARY, ChatNetworkBlobDispatchType.ASYNCMETHOD_SENDTOROOMBYNAME, contextId, null, null, 0, adjustedchatType)); return; } if (PropertyManager.GetBool("chat_requires_account_15days").Item&& !session.Player.Account15Days) { HandleChatReject(session, contextId, chatType, gameMessageTurbineChat, "because this account is not 15 days old"); return; } var chat_requires_account_time_seconds = PropertyManager.GetLong("chat_requires_account_time_seconds").Item; if (chat_requires_account_time_seconds > 0 && (DateTime.UtcNow - session.Player.Account.CreateTime).TotalSeconds < chat_requires_account_time_seconds) { HandleChatReject(session, contextId, chatType, gameMessageTurbineChat, "because this account is not old enough"); return; } var chat_requires_player_age = PropertyManager.GetLong("chat_requires_player_age").Item; if (chat_requires_player_age > 0 && session.Player.Age < chat_requires_player_age) { HandleChatReject(session, contextId, chatType, gameMessageTurbineChat, "because this character has not been played enough"); return; } var chat_requires_player_level = PropertyManager.GetLong("chat_requires_player_level").Item; if (chat_requires_player_level > 0 && session.Player.Level < chat_requires_player_level) { HandleChatReject(session, contextId, chatType, gameMessageTurbineChat, $"because this character has reached level {chat_requires_player_level}"); return; } foreach (var recipient in PlayerManager.GetAllOnline()) { // handle filters if (channelID == TurbineChatChannel.General && !recipient.GetCharacterOption(CharacterOption.ListenToGeneralChat) || channelID == TurbineChatChannel.Trade && !recipient.GetCharacterOption(CharacterOption.ListenToTradeChat) || channelID == TurbineChatChannel.LFG && !recipient.GetCharacterOption(CharacterOption.ListenToLFGChat) || channelID == TurbineChatChannel.Roleplay && !recipient.GetCharacterOption(CharacterOption.ListenToRoleplayChat)) { continue; } if ((channelID == TurbineChatChannel.General && PropertyManager.GetBool("chat_disable_general").Item) || (channelID == TurbineChatChannel.Trade && PropertyManager.GetBool("chat_disable_trade").Item) || (channelID == TurbineChatChannel.LFG && PropertyManager.GetBool("chat_disable_lfg").Item) || (channelID == TurbineChatChannel.Roleplay && PropertyManager.GetBool("chat_disable_roleplay").Item)) { if (PropertyManager.GetBool("chat_echo_reject").Item) { session.Network.EnqueueSend(gameMessageTurbineChat); } session.Network.EnqueueSend(new GameMessageTurbineChat(ChatNetworkBlobType.NETBLOB_RESPONSE_BINARY, ChatNetworkBlobDispatchType.ASYNCMETHOD_SENDTOROOMBYNAME, contextId, null, null, 0, adjustedchatType)); return; } if (recipient.IsOlthoiPlayer) { continue; } if (recipient.SquelchManager.Squelches.Contains(session.Player, ChatMessageType.AllChannels)) { continue; } recipient.Session.Network.EnqueueSend(gameMessageTurbineChat); } session.Network.EnqueueSend(new GameMessageTurbineChat(ChatNetworkBlobType.NETBLOB_RESPONSE_BINARY, ChatNetworkBlobDispatchType.ASYNCMETHOD_SENDTOROOMBYNAME, contextId, null, null, 0, adjustedchatType)); } LogTurbineChat(adjustedChannelID, session.Player.Name, message, senderID, adjustedchatType); } else { Console.WriteLine($"Unhandled TurbineChatHandler ChatNetworkBlobType: 0x{(uint)chatBlobType:X4}"); } }
/// <summary> /// Import products from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual void ImportProductsFromXlsx(Stream stream) { //the columns var properties = new[] { new PropertyByName<Product>("ProductTypeId"), new PropertyByName<Product>("ParentGroupedProductId"), new PropertyByName<Product>("VisibleIndividually"), new PropertyByName<Product>("Name"), new PropertyByName<Product>("ShortDescription"), new PropertyByName<Product>("FullDescription"), new PropertyByName<Product>("VendorId"), new PropertyByName<Product>("ProductTemplateId"), new PropertyByName<Product>("ShowOnHomePage"), new PropertyByName<Product>("MetaKeywords"), new PropertyByName<Product>("MetaDescription"), new PropertyByName<Product>("MetaTitle"), new PropertyByName<Product>("SeName"), new PropertyByName<Product>("AllowCustomerReviews"), new PropertyByName<Product>("Published"), new PropertyByName<Product>("SKU"), new PropertyByName<Product>("ManufacturerPartNumber"), new PropertyByName<Product>("Gtin"), new PropertyByName<Product>("IsGiftCard"), new PropertyByName<Product>("GiftCardTypeId"), new PropertyByName<Product>("OverriddenGiftCardAmount"), new PropertyByName<Product>("RequireOtherProducts"), new PropertyByName<Product>("RequiredProductIds"), new PropertyByName<Product>("AutomaticallyAddRequiredProducts"), new PropertyByName<Product>("IsDownload"), new PropertyByName<Product>("DownloadId"), new PropertyByName<Product>("UnlimitedDownloads"), new PropertyByName<Product>("MaxNumberOfDownloads"), new PropertyByName<Product>("DownloadActivationTypeId"), new PropertyByName<Product>("HasSampleDownload"), new PropertyByName<Product>("SampleDownloadId"), new PropertyByName<Product>("HasUserAgreement"), new PropertyByName<Product>("UserAgreementText"), new PropertyByName<Product>("IsRecurring"), new PropertyByName<Product>("RecurringCycleLength"), new PropertyByName<Product>("RecurringCyclePeriodId"), new PropertyByName<Product>("RecurringTotalCycles"), new PropertyByName<Product>("IsRental"), new PropertyByName<Product>("RentalPriceLength"), new PropertyByName<Product>("RentalPricePeriodId"), new PropertyByName<Product>("IsShipEnabled"), new PropertyByName<Product>("IsFreeShipping"), new PropertyByName<Product>("ShipSeparately"), new PropertyByName<Product>("AdditionalShippingCharge"), new PropertyByName<Product>("DeliveryDateId"), new PropertyByName<Product>("IsTaxExempt"), new PropertyByName<Product>("TaxCategoryId"), new PropertyByName<Product>("IsTelecommunicationsOrBroadcastingOrElectronicServices"), new PropertyByName<Product>("ManageInventoryMethodId"), new PropertyByName<Product>("UseMultipleWarehouses"), new PropertyByName<Product>("WarehouseId"), new PropertyByName<Product>("StockQuantity"), new PropertyByName<Product>("DisplayStockAvailability"), new PropertyByName<Product>("DisplayStockQuantity"), new PropertyByName<Product>("MinStockQuantity"), new PropertyByName<Product>("LowStockActivityId"), new PropertyByName<Product>("NotifyAdminForQuantityBelow"), new PropertyByName<Product>("BackorderModeId"), new PropertyByName<Product>("AllowBackInStockSubscriptions"), new PropertyByName<Product>("OrderMinimumQuantity"), new PropertyByName<Product>("OrderMaximumQuantity"), new PropertyByName<Product>("AllowedQuantities"), new PropertyByName<Product>("AllowAddingOnlyExistingAttributeCombinations"), new PropertyByName<Product>("DisableBuyButton"), new PropertyByName<Product>("DisableWishlistButton"), new PropertyByName<Product>("AvailableForPreOrder"), new PropertyByName<Product>("PreOrderAvailabilityStartDateTimeUtc"), new PropertyByName<Product>("CallForPrice"), new PropertyByName<Product>("Price"), new PropertyByName<Product>("OldPrice"), new PropertyByName<Product>("ProductCost"), new PropertyByName<Product>("SpecialPrice"), new PropertyByName<Product>("SpecialPriceStartDateTimeUtc"), new PropertyByName<Product>("SpecialPriceEndDateTimeUtc"), new PropertyByName<Product>("CustomerEntersPrice"), new PropertyByName<Product>("MinimumCustomerEnteredPrice"), new PropertyByName<Product>("MaximumCustomerEnteredPrice"), new PropertyByName<Product>("BasepriceEnabled"), new PropertyByName<Product>("BasepriceAmount"), new PropertyByName<Product>("BasepriceUnitId"), new PropertyByName<Product>("BasepriceBaseAmount"), new PropertyByName<Product>("BasepriceBaseUnitId"), new PropertyByName<Product>("MarkAsNew"), new PropertyByName<Product>("MarkAsNewStartDateTimeUtc"), new PropertyByName<Product>("MarkAsNewEndDateTimeUtc"), new PropertyByName<Product>("Weight"), new PropertyByName<Product>("Length"), new PropertyByName<Product>("Width"), new PropertyByName<Product>("Height"), new PropertyByName<Product>("CategoryIds"), new PropertyByName<Product>("ManufacturerIds"), new PropertyByName<Product>("Picture1"), new PropertyByName<Product>("Picture2"), new PropertyByName<Product>("Picture3") }; var manager = new PropertyManager<Product>(properties); // ok, we can run the real code of the sample now using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) throw new NopException("No worksheet found"); int iRow = 2; while (true) { var allColumnsAreEmpty = manager.GetProperties .Select(property => worksheet.Cells[iRow, property.PropertyOrderPosition]) .All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())); if (allColumnsAreEmpty) break; manager.ReadFromXlsx(worksheet, iRow); var product = _productService.GetProductBySku(manager.GetProperty("SKU").StringValue); var isNew = product == null; product = product ?? new Product(); if (isNew) product.CreatedOnUtc = DateTime.UtcNow; product.ProductTypeId = manager.GetProperty("ProductTypeId").IntValue; product.ParentGroupedProductId = manager.GetProperty("ParentGroupedProductId").IntValue; product.VisibleIndividually = manager.GetProperty("VisibleIndividually").BooleanValue; product.Name = manager.GetProperty("Name").StringValue; product.ShortDescription = manager.GetProperty("ShortDescription").StringValue; product.FullDescription = manager.GetProperty("FullDescription").StringValue; product.VendorId = manager.GetProperty("VendorId").IntValue; product.ProductTemplateId = manager.GetProperty("ProductTemplateId").IntValue; product.ShowOnHomePage = manager.GetProperty("ShowOnHomePage").BooleanValue; product.MetaKeywords = manager.GetProperty("MetaKeywords").StringValue; product.MetaDescription = manager.GetProperty("MetaDescription").StringValue; product.MetaTitle = manager.GetProperty("MetaTitle").StringValue; var seName = manager.GetProperty("SeName").StringValue; product.AllowCustomerReviews = manager.GetProperty("AllowCustomerReviews").BooleanValue; product.Published = manager.GetProperty("Published").BooleanValue; product.Sku = manager.GetProperty("SKU").StringValue; product.ManufacturerPartNumber = manager.GetProperty("ManufacturerPartNumber").StringValue; product.Gtin = manager.GetProperty("Gtin").StringValue; product.IsGiftCard = manager.GetProperty("IsGiftCard").BooleanValue; product.GiftCardTypeId = manager.GetProperty("GiftCardTypeId").IntValue; product.OverriddenGiftCardAmount = manager.GetProperty("OverriddenGiftCardAmount").DecimalValue; product.RequireOtherProducts = manager.GetProperty("RequireOtherProducts").BooleanValue; product.RequiredProductIds = manager.GetProperty("RequiredProductIds").StringValue; product.AutomaticallyAddRequiredProducts = manager.GetProperty("AutomaticallyAddRequiredProducts").BooleanValue; product.IsDownload = manager.GetProperty("IsDownload").BooleanValue; product.DownloadId = manager.GetProperty("DownloadId").IntValue; product.UnlimitedDownloads = manager.GetProperty("UnlimitedDownloads").BooleanValue; product.MaxNumberOfDownloads = manager.GetProperty("MaxNumberOfDownloads").IntValue; product.DownloadActivationTypeId = manager.GetProperty("DownloadActivationTypeId").IntValue; product.HasSampleDownload = manager.GetProperty("HasSampleDownload").BooleanValue; product.SampleDownloadId = manager.GetProperty("SampleDownloadId").IntValue; product.HasUserAgreement = manager.GetProperty("HasUserAgreement").BooleanValue; product.UserAgreementText = manager.GetProperty("UserAgreementText").StringValue; product.IsRecurring = manager.GetProperty("IsRecurring").BooleanValue; product.RecurringCycleLength = manager.GetProperty("RecurringCycleLength").IntValue; product.RecurringCyclePeriodId = manager.GetProperty("RecurringCyclePeriodId").IntValue; product.RecurringTotalCycles = manager.GetProperty("RecurringTotalCycles").IntValue; product.IsRental = manager.GetProperty("IsRental").BooleanValue; product.RentalPriceLength = manager.GetProperty("RentalPriceLength").IntValue; product.RentalPricePeriodId = manager.GetProperty("RentalPricePeriodId").IntValue; product.IsShipEnabled = manager.GetProperty("IsShipEnabled").BooleanValue; product.IsFreeShipping = manager.GetProperty("IsFreeShipping").BooleanValue; product.ShipSeparately = manager.GetProperty("ShipSeparately").BooleanValue; product.AdditionalShippingCharge = manager.GetProperty("AdditionalShippingCharge").DecimalValue; product.DeliveryDateId = manager.GetProperty("DeliveryDateId").IntValue; product.IsTaxExempt = manager.GetProperty("IsTaxExempt").BooleanValue; product.TaxCategoryId = manager.GetProperty("TaxCategoryId").IntValue; product.IsTelecommunicationsOrBroadcastingOrElectronicServices = manager.GetProperty("IsTelecommunicationsOrBroadcastingOrElectronicServices").BooleanValue; product.ManageInventoryMethodId = manager.GetProperty("ManageInventoryMethodId").IntValue; product.UseMultipleWarehouses = manager.GetProperty("UseMultipleWarehouses").BooleanValue; product.WarehouseId = manager.GetProperty("WarehouseId").IntValue; product.StockQuantity = manager.GetProperty("StockQuantity").IntValue; product.DisplayStockAvailability = manager.GetProperty("DisplayStockAvailability").BooleanValue; product.DisplayStockQuantity = manager.GetProperty("DisplayStockQuantity").BooleanValue; product.MinStockQuantity = manager.GetProperty("MinStockQuantity").IntValue; product.LowStockActivityId = manager.GetProperty("LowStockActivityId").IntValue; product.NotifyAdminForQuantityBelow = manager.GetProperty("NotifyAdminForQuantityBelow").IntValue; product.BackorderModeId = manager.GetProperty("BackorderModeId").IntValue; product.AllowBackInStockSubscriptions = manager.GetProperty("AllowBackInStockSubscriptions").BooleanValue; product.OrderMinimumQuantity = manager.GetProperty("OrderMinimumQuantity").IntValue; product.OrderMaximumQuantity = manager.GetProperty("OrderMaximumQuantity").IntValue; product.AllowedQuantities = manager.GetProperty("AllowedQuantities").StringValue; product.AllowAddingOnlyExistingAttributeCombinations = manager.GetProperty("AllowAddingOnlyExistingAttributeCombinations").BooleanValue; product.DisableBuyButton = manager.GetProperty("DisableBuyButton").BooleanValue; product.DisableWishlistButton = manager.GetProperty("DisableWishlistButton").BooleanValue; product.AvailableForPreOrder = manager.GetProperty("AvailableForPreOrder").BooleanValue; product.PreOrderAvailabilityStartDateTimeUtc = manager.GetProperty("PreOrderAvailabilityStartDateTimeUtc").DateTimeNullable; product.CallForPrice = manager.GetProperty("CallForPrice").BooleanValue; product.Price = manager.GetProperty("Price").DecimalValue; product.OldPrice = manager.GetProperty("OldPrice").DecimalValue; product.ProductCost = manager.GetProperty("ProductCost").DecimalValue; product.SpecialPrice = manager.GetProperty("SpecialPrice").DecimalValueNullable; product.SpecialPriceStartDateTimeUtc = manager.GetProperty("SpecialPriceStartDateTimeUtc").DateTimeNullable; product.SpecialPriceEndDateTimeUtc = manager.GetProperty("SpecialPriceEndDateTimeUtc").DateTimeNullable; product.CustomerEntersPrice = manager.GetProperty("CustomerEntersPrice").BooleanValue; product.MinimumCustomerEnteredPrice = manager.GetProperty("MinimumCustomerEnteredPrice").DecimalValue; product.MaximumCustomerEnteredPrice = manager.GetProperty("MaximumCustomerEnteredPrice").DecimalValue; product.BasepriceEnabled = manager.GetProperty("BasepriceEnabled").BooleanValue; product.BasepriceAmount = manager.GetProperty("BasepriceAmount").DecimalValue; product.BasepriceUnitId = manager.GetProperty("BasepriceUnitId").IntValue; product.BasepriceBaseAmount = manager.GetProperty("BasepriceBaseAmount").DecimalValue; product.BasepriceBaseUnitId = manager.GetProperty("BasepriceBaseUnitId").IntValue; product.MarkAsNew = manager.GetProperty("MarkAsNew").BooleanValue; product.MarkAsNewStartDateTimeUtc = manager.GetProperty("MarkAsNewStartDateTimeUtc").DateTimeNullable; product.MarkAsNewEndDateTimeUtc = manager.GetProperty("MarkAsNewEndDateTimeUtc").DateTimeNullable; product.Weight = manager.GetProperty("Weight").DecimalValue; product.Length = manager.GetProperty("Length").DecimalValue; product.Width = manager.GetProperty("Width").DecimalValue; product.Height = manager.GetProperty("Height").DecimalValue; var categoryIds = manager.GetProperty("CategoryIds").StringValue; var manufacturerIds = manager.GetProperty("ManufacturerIds").StringValue; var picture1 = manager.GetProperty("Picture1").StringValue; var picture2 = manager.GetProperty("Picture2").StringValue; var picture3 = manager.GetProperty("Picture3").StringValue; product.UpdatedOnUtc = DateTime.UtcNow; if (isNew) { _productService.InsertProduct(product); } else { _productService.UpdateProduct(product); } //search engine name _urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), 0); var _seName = product.ValidateSeName(seName, product.Name, true); //search engine name _urlRecordService.SaveSlug(product, _seName, 0); product.SeName = _seName; _productService.UpdateProduct(product); //category mappings if (!String.IsNullOrEmpty(categoryIds)) { foreach (var id in categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))) { if (product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) == null) { //ensure that category exists var category = _categoryService.GetCategoryById(id); if (category != null) { var productCategory = new ProductCategory { _id = ObjectId.GenerateNewId().ToString(), Id = product.ProductCategories.Count > 0 ? product.ProductCategories.Max(x => x.Id) + 1 : 1, ProductId = product.Id, CategoryId = category.Id, IsFeaturedProduct = false, DisplayOrder = 1 }; _categoryService.InsertProductCategory(productCategory); } } } } //manufacturer mappings if (!String.IsNullOrEmpty(manufacturerIds)) { foreach (var id in manufacturerIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))) { if (product.ProductManufacturers.FirstOrDefault(x => x.ManufacturerId == id) == null) { //ensure that manufacturer exists var manufacturer = _manufacturerService.GetManufacturerById(id); if (manufacturer != null) { var productManufacturer = new ProductManufacturer { _id = ObjectId.GenerateNewId().ToString(), Id = product.ProductManufacturers.Count > 0 ? product.ProductManufacturers.Max(x => x.Id) + 1 : 1, ProductId = product.Id, ManufacturerId = manufacturer.Id, IsFeaturedProduct = false, DisplayOrder = 1 }; _manufacturerService.InsertProductManufacturer(productManufacturer); } } } } //pictures foreach (var picturePath in new[] { picture1, picture2, picture3 }) { if (String.IsNullOrEmpty(picturePath)) continue; var mimeType = GetMimeTypeFromFilePath(picturePath); var newPictureBinary = File.ReadAllBytes(picturePath); var pictureAlreadyExists = false; if (!isNew) { //compare with existing product pictures var existingPictures = product.ProductPictures; foreach (var existingPicture in existingPictures) { var pp = _pictureService.GetPictureById(existingPicture.PictureId); var existingBinary = _pictureService.LoadPictureBinary(pp); //picture binary after validation (like in database) var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType); if (existingBinary.SequenceEqual(validatedPictureBinary) || existingBinary.SequenceEqual(newPictureBinary)) { //the same picture content pictureAlreadyExists = true; break; } } } if (!pictureAlreadyExists) { var picture = _pictureService.InsertPicture(newPictureBinary, mimeType, _pictureService.GetPictureSeName(product.Name)); var productPicture = new ProductPicture { Id = product.ProductPictures.Count > 0 ? product.ProductPictures.Max(x => x.Id) + 1 : 1, _id = ObjectId.GenerateNewId().ToString(), PictureId = picture.Id, ProductId = product.Id, DisplayOrder = 1, }; //product.ProductPictures.Add(; _productService.InsertProductPicture(productPicture); } } //update "HasTierPrices" and "HasDiscountsApplied" properties _productService.UpdateHasTierPricesProperty(product.Id); _productService.UpdateHasDiscountsApplied(product.Id); //next product iRow++; } } }
public void PropertyManager_GetListName_NoDataSource_ThrowsArgumentException() { var manager = new PropertyManager(); Assert.Throws <ArgumentException>(null, () => manager.GetListName()); }
public static CreateResult Create(CharacterCreateInfo characterCreateInfo, Weenie weenie, ObjectGuid guid, uint accountId, WeenieType weenieType, out Player player) { var heritageGroup = DatManager.PortalDat.CharGen.HeritageGroups[characterCreateInfo.Heritage]; if (weenieType == WeenieType.Admin) { player = new Admin(weenie, guid, accountId); } else if (weenieType == WeenieType.Sentinel) { player = new Sentinel(weenie, guid, accountId); } else { player = new Player(weenie, guid, accountId); } player.SetProperty(PropertyInt.HeritageGroup, (int)characterCreateInfo.Heritage); player.SetProperty(PropertyString.HeritageGroup, heritageGroup.Name); player.SetProperty(PropertyInt.Gender, (int)characterCreateInfo.Gender); player.SetProperty(PropertyString.Sex, characterCreateInfo.Gender == 1 ? "Male" : "Female"); //player.SetProperty(PropertyDataId.Icon, cgh.IconImage); // I don't believe this is used anywhere in the client, but it might be used by a future custom launcher // pull character data from the dat file var sex = heritageGroup.Genders[(int)characterCreateInfo.Gender]; player.SetProperty(PropertyDataId.MotionTable, sex.MotionTable); player.SetProperty(PropertyDataId.SoundTable, sex.SoundTable); player.SetProperty(PropertyDataId.PhysicsEffectTable, sex.PhysicsTable); player.SetProperty(PropertyDataId.Setup, sex.SetupID); player.SetProperty(PropertyDataId.PaletteBase, sex.BasePalette); player.SetProperty(PropertyDataId.CombatTable, sex.CombatTable); // Check the character scale if (sex.Scale != 100u) { player.SetProperty(PropertyFloat.DefaultScale, (sex.Scale / 100f)); // Scale is stored as a percentage } // Get the hair first, because we need to know if you're bald, and that's the name of that tune! var hairstyle = sex.HairStyleList[Convert.ToInt32(characterCreateInfo.Apperance.HairStyle)]; // Olthoi and Gear Knights have a "Body Style" instead of a hair style. These styles have multiple model/texture changes, instead of a single head/hairstyle. // Storing this value allows us to send the proper appearance ObjDesc if (hairstyle.ObjDesc.AnimPartChanges.Count > 1) { player.SetProperty(PropertyInt.Hairstyle, (int)characterCreateInfo.Apperance.HairStyle); } // Certain races (Undead, Tumeroks, Others?) have multiple body styles available. This is controlled via the "hair style". if (hairstyle.AlternateSetup > 0) { player.SetProperty(PropertyDataId.Setup, hairstyle.AlternateSetup); } player.SetProperty(PropertyDataId.EyesTexture, sex.GetEyeTexture(characterCreateInfo.Apperance.Eyes, hairstyle.Bald)); player.SetProperty(PropertyDataId.DefaultEyesTexture, sex.GetDefaultEyeTexture(characterCreateInfo.Apperance.Eyes, hairstyle.Bald)); player.SetProperty(PropertyDataId.NoseTexture, sex.GetNoseTexture(characterCreateInfo.Apperance.Nose)); player.SetProperty(PropertyDataId.DefaultNoseTexture, sex.GetDefaultNoseTexture(characterCreateInfo.Apperance.Nose)); player.SetProperty(PropertyDataId.MouthTexture, sex.GetMouthTexture(characterCreateInfo.Apperance.Mouth)); player.SetProperty(PropertyDataId.DefaultMouthTexture, sex.GetDefaultMouthTexture(characterCreateInfo.Apperance.Mouth)); player.Character.HairTexture = sex.GetHairTexture(characterCreateInfo.Apperance.HairStyle); player.Character.DefaultHairTexture = sex.GetDefaultHairTexture(characterCreateInfo.Apperance.HairStyle); // HeadObject can be null if we're dealing with GearKnight or Olthoi var headObject = sex.GetHeadObject(characterCreateInfo.Apperance.HairStyle); if (headObject != null) { player.SetProperty(PropertyDataId.HeadObject, (uint)headObject); } // Skin is stored as PaletteSet (list of Palettes), so we need to read in the set to get the specific palette var skinPalSet = DatManager.PortalDat.ReadFromDat <PaletteSet>(sex.SkinPalSet); player.SetProperty(PropertyDataId.SkinPalette, skinPalSet.GetPaletteID(characterCreateInfo.Apperance.SkinHue)); player.SetProperty(PropertyFloat.Shade, characterCreateInfo.Apperance.SkinHue); // Hair is stored as PaletteSet (list of Palettes), so we need to read in the set to get the specific palette var hairPalSet = DatManager.PortalDat.ReadFromDat <PaletteSet>(sex.HairColorList[Convert.ToInt32(characterCreateInfo.Apperance.HairColor)]); player.SetProperty(PropertyDataId.HairPalette, hairPalSet.GetPaletteID(characterCreateInfo.Apperance.HairHue)); // Eye Color player.SetProperty(PropertyDataId.EyesPalette, sex.EyeColorList[Convert.ToInt32(characterCreateInfo.Apperance.EyeColor)]); if (characterCreateInfo.Apperance.HeadgearStyle < 0xFFFFFFFF) // No headgear is max UINT { var hat = GetClothingObject(sex.GetHeadgearWeenie(characterCreateInfo.Apperance.HeadgearStyle), characterCreateInfo.Apperance.HeadgearColor, characterCreateInfo.Apperance.HeadgearHue); if (hat != null) { player.TryEquipObject(hat, hat.ValidLocations ?? 0); } else { player.TryAddToInventory(CreateIOU(sex.GetHeadgearWeenie(characterCreateInfo.Apperance.HeadgearStyle))); } } var shirt = GetClothingObject(sex.GetShirtWeenie(characterCreateInfo.Apperance.ShirtStyle), characterCreateInfo.Apperance.ShirtColor, characterCreateInfo.Apperance.ShirtHue); if (shirt != null) { player.TryEquipObject(shirt, shirt.ValidLocations ?? 0); } else { player.TryAddToInventory(CreateIOU(sex.GetShirtWeenie(characterCreateInfo.Apperance.ShirtStyle))); } var pants = GetClothingObject(sex.GetPantsWeenie(characterCreateInfo.Apperance.PantsStyle), characterCreateInfo.Apperance.PantsColor, characterCreateInfo.Apperance.PantsHue); if (pants != null) { player.TryEquipObject(pants, pants.ValidLocations ?? 0); } else { player.TryAddToInventory(CreateIOU(sex.GetPantsWeenie(characterCreateInfo.Apperance.PantsStyle))); } var shoes = GetClothingObject(sex.GetFootwearWeenie(characterCreateInfo.Apperance.FootwearStyle), characterCreateInfo.Apperance.FootwearColor, characterCreateInfo.Apperance.FootwearHue); if (shoes != null) { player.TryEquipObject(shoes, shoes.ValidLocations ?? 0); } else { player.TryAddToInventory(CreateIOU(sex.GetFootwearWeenie(characterCreateInfo.Apperance.FootwearStyle))); } string templateName = heritageGroup.Templates[characterCreateInfo.TemplateOption].Name; //player.SetProperty(PropertyString.Title, templateName); player.SetProperty(PropertyString.Template, templateName); player.AddTitle(heritageGroup.Templates[characterCreateInfo.TemplateOption].Title, true); // attributes var result = ValidateAttributeCredits(characterCreateInfo, heritageGroup.AttributeCredits); if (result != CreateResult.Success) { return(result); } player.Strength.StartingValue = characterCreateInfo.StrengthAbility; player.Endurance.StartingValue = characterCreateInfo.EnduranceAbility; player.Coordination.StartingValue = characterCreateInfo.CoordinationAbility; player.Quickness.StartingValue = characterCreateInfo.QuicknessAbility; player.Focus.StartingValue = characterCreateInfo.FocusAbility; player.Self.StartingValue = characterCreateInfo.SelfAbility; // data we don't care about //characterCreateInfo.CharacterSlot; //characterCreateInfo.ClassId; // characters start with max vitals player.Health.Current = player.Health.Base; player.Stamina.Current = player.Stamina.Base; player.Mana.Current = player.Mana.Base; // set initial skill credit amount. 52 for all but "Olthoi", which have 68 player.SetProperty(PropertyInt.AvailableSkillCredits, (int)heritageGroup.SkillCredits); if (characterCreateInfo.SkillAdvancementClasses.Count != 55) { return(CreateResult.ClientServerSkillsMismatch); } for (int i = 0; i < characterCreateInfo.SkillAdvancementClasses.Count; i++) { var sac = characterCreateInfo.SkillAdvancementClasses[i]; if (sac == SkillAdvancementClass.Inactive) { continue; } if (!DatManager.PortalDat.SkillTable.SkillBaseHash.ContainsKey((uint)i)) { log.ErrorFormat("Character {0} tried to create with skill {1} that was not found in Portal dat.", characterCreateInfo.Name, i); return(CreateResult.InvalidSkillRequested); } var skill = DatManager.PortalDat.SkillTable.SkillBaseHash[(uint)i]; var trainedCost = skill.TrainedCost; var specializedCost = skill.UpgradeCostFromTrainedToSpecialized; foreach (var skillGroup in heritageGroup.Skills) { if (skillGroup.SkillNum == i) { trainedCost = skillGroup.NormalCost; specializedCost = skillGroup.PrimaryCost; break; } } if (sac == SkillAdvancementClass.Specialized) { if (!player.TrainSkill((Skill)i, trainedCost)) { return(CreateResult.FailedToTrainSkill); } if (!player.SpecializeSkill((Skill)i, specializedCost)) { return(CreateResult.FailedToSpecializeSkill); } } else if (sac == SkillAdvancementClass.Trained) { if (!player.TrainSkill((Skill)i, trainedCost, true)) { return(CreateResult.FailedToTrainSkill); } } else if (sac == SkillAdvancementClass.Untrained) { player.UntrainSkill((Skill)i, 0); } } var isDualWieldTrainedOrSpecialized = player.Skills[Skill.DualWield].AdvancementClass > SkillAdvancementClass.Untrained; // Set Heritage based Melee and Ranged Masteries GetMasteries(player.HeritageGroup, out WeaponType meleeMastery, out WeaponType rangedMastery); player.SetProperty(PropertyInt.MeleeMastery, (int)meleeMastery); player.SetProperty(PropertyInt.RangedMastery, (int)rangedMastery); // Set innate augs SetInnateAugmentations(player); // grant starter items based on skills var starterGearConfig = StarterGearFactory.GetStarterGearConfiguration(); var grantedWeenies = new List <uint>(); foreach (var skillGear in starterGearConfig.Skills) { var charSkill = player.Skills[(Skill)skillGear.SkillId]; if (charSkill.AdvancementClass == SkillAdvancementClass.Trained || charSkill.AdvancementClass == SkillAdvancementClass.Specialized) { foreach (var item in skillGear.Gear) { if (grantedWeenies.Contains(item.WeenieId)) { var existingItem = player.Inventory.Values.FirstOrDefault(i => i.WeenieClassId == item.WeenieId); if (existingItem == null || (existingItem.MaxStackSize ?? 1) <= 1) { continue; } existingItem.SetStackSize(existingItem.StackSize + item.StackSize); continue; } var loot = WorldObjectFactory.CreateNewWorldObject(item.WeenieId); if (loot != null) { if (loot.StackSize.HasValue && loot.MaxStackSize.HasValue) { loot.SetStackSize((item.StackSize <= loot.MaxStackSize) ? item.StackSize : loot.MaxStackSize); } } else { player.TryAddToInventory(CreateIOU(item.WeenieId)); } if (loot != null && player.TryAddToInventory(loot)) { grantedWeenies.Add(item.WeenieId); } if (isDualWieldTrainedOrSpecialized && loot != null) { if (loot.WeenieType == WeenieType.MeleeWeapon) { var dualloot = WorldObjectFactory.CreateNewWorldObject(item.WeenieId); if (dualloot != null) { player.TryAddToInventory(dualloot); } else { player.TryAddToInventory(CreateIOU(item.WeenieId)); } } } } var heritageLoot = skillGear.Heritage.FirstOrDefault(sh => sh.HeritageId == characterCreateInfo.Heritage); if (heritageLoot != null) { foreach (var item in heritageLoot.Gear) { if (grantedWeenies.Contains(item.WeenieId)) { var existingItem = player.Inventory.Values.FirstOrDefault(i => i.WeenieClassId == item.WeenieId); if (existingItem == null || (existingItem.MaxStackSize ?? 1) <= 1) { continue; } existingItem.SetStackSize(existingItem.StackSize + item.StackSize); continue; } var loot = WorldObjectFactory.CreateNewWorldObject(item.WeenieId); if (loot != null) { if (loot.StackSize.HasValue && loot.MaxStackSize.HasValue) { loot.SetStackSize((item.StackSize <= loot.MaxStackSize) ? item.StackSize : loot.MaxStackSize); } } else { player.TryAddToInventory(CreateIOU(item.WeenieId)); } if (loot != null && player.TryAddToInventory(loot)) { grantedWeenies.Add(item.WeenieId); } if (isDualWieldTrainedOrSpecialized && loot != null) { if (loot.WeenieType == WeenieType.MeleeWeapon) { var dualloot = WorldObjectFactory.CreateNewWorldObject(item.WeenieId); if (dualloot != null) { player.TryAddToInventory(dualloot); } else { player.TryAddToInventory(CreateIOU(item.WeenieId)); } } } } } foreach (var spell in skillGear.Spells) { // Olthoi Spitter is a special case if (characterCreateInfo.Heritage == (int)HeritageGroup.OlthoiAcid) { player.AddKnownSpell(spell.SpellId); // Continue to next spell as Olthoi spells do not have the SpecializedOnly field continue; } if (charSkill.AdvancementClass == SkillAdvancementClass.Trained && spell.SpecializedOnly == false) { player.AddKnownSpell(spell.SpellId); } else if (charSkill.AdvancementClass == SkillAdvancementClass.Specialized) { player.AddKnownSpell(spell.SpellId); } } } } player.Name = characterCreateInfo.Name; player.Character.Name = characterCreateInfo.Name; player.Instantiation = new Position(8323335, 260.085388f, -20.421343f, -59.994999f, 0.0f, -0.0f, -0.707107f, -0.707107f); player.Sanctuary = new Position(8323335, 260.085388f, -20.421343f, -59.994999f, 0.0f, -0.0f, -0.707107f, -0.707107f); player.SetProperty(PropertyBool.RecallsDisabled, false); player.AvailableSkillCredits = 50; player.AvailableExperience += 191226310247; player.TotalExperience += 191226310247; player.Level = 275; if (PropertyManager.GetBool("pk_server").Item) { player.SetProperty(PropertyInt.PlayerKillerStatus, (int)PlayerKillerStatus.PK); } else if (PropertyManager.GetBool("pkl_server").Item) { player.SetProperty(PropertyInt.PlayerKillerStatus, (int)PlayerKillerStatus.NPK); } if ((PropertyManager.GetBool("pk_server").Item || PropertyManager.GetBool("pkl_server").Item) && PropertyManager.GetBool("pk_server_safe_training_academy").Item) { player.SetProperty(PropertyFloat.MinimumTimeSincePk, -PropertyManager.GetDouble("pk_new_character_grace_period").Item); player.SetProperty(PropertyInt.PlayerKillerStatus, (int)PlayerKillerStatus.NPK); } if (player is Sentinel || player is Admin) { player.Character.IsPlussed = true; player.CloakStatus = CloakStatus.Off; player.ChannelsAllowed = player.ChannelsActive; } CharacterCreateSetDefaultCharacterOptions(player); return(CreateResult.Success); }
public void HandleActionEnterPkLite() { // ensure permanent npk if (PlayerKillerStatus != PlayerKillerStatus.NPK || MinimumTimeSincePk != null) { Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.OnlyNonPKsMayEnterPKLite)); return; } if (TooBusyToRecall) { Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.YoureTooBusy)); return; } EnqueueBroadcast(new GameMessageSystemChat($"{Name} is looking for a fight!", ChatMessageType.Broadcast), LocalBroadcastRange); // perform pk lite entry motion / effect IsBusy = true; var prevStance = CurrentMotionState.Stance; var actionChain = new ActionChain(); var animTime = 0.0f; animTime += EnqueueMotion_Force(actionChain, MotionStance.NonCombat, MotionCommand.EnterPKLite); actionChain.AddAction(this, () => { if (PropertyManager.GetBool("allow_pkl_bump").Item) { // check for collisions PlayerKillerStatus = PlayerKillerStatus.PKLite; var colliding = PhysicsObj.ethereal_check_for_collisions(); if (colliding) { // try initial placement var result = PhysicsObj.SetPositionSimple(PhysicsObj.Position, true); if (result == SetPositionError.OK) { // handle landblock update? SyncLocation(); // force broadcast Sequences.GetNextSequence(SequenceType.ObjectForcePosition); SendUpdatePosition(); } } } UpdateProperty(this, PropertyInt.PlayerKillerStatus, (int)PlayerKillerStatus.PKLite, true); Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.YouAreNowPKLite)); }); // return to previous stance, if applicable if (prevStance != MotionStance.NonCombat) { animTime += EnqueueMotion_Force(actionChain, prevStance, MotionCommand.Ready, MotionCommand.NonCombat); } actionChain.AddAction(this, () => IsBusy = false); actionChain.EnqueueChain(); }
/// <summary> /// Constructs the PluginDebuggerHelper. /// </summary> /// <param name="dte">Automation object from Visual Studio.</param> /// <param name="properties">PropertyManager pointing to a valid project/platform.</param> public PluginDebuggerGDB(DTE2 dte, PropertyManager properties) : base(dte, properties) { string arch = "i686"; if (Environment.Is64BitOperatingSystem) arch = "x86_64"; if (!properties.IsPNaCl()) { if (properties.TargetArchitecture != arch) { MessageBox.Show(string.Format("Debugging of {0} NaCl modules is not possible on this system ({1}).", properties.TargetArchitecture, arch)); } } // check chrome version string chrome_path = properties.LocalDebuggerCommand; FileVersionInfo version_info = FileVersionInfo.GetVersionInfo(chrome_path); string file_version = version_info.FileVersion; if (file_version != null) { string major_version = file_version.Split('.')[0]; int major_version_int = 0; try { major_version_int = Convert.ToInt32(major_version); } catch { } if (major_version_int < 22) { MessageBox.Show("Chrome 22 or above required for NaCl debugging (your version is " + major_version + ")"); return; } } // We look for the IRT in several ways, mimicing what chrome itself // does in chrome/app/client_util.cc:MakeMainDllLoader. // First look for the IRT alongside chrome.exe string irt_basename = "nacl_irt_" + arch + ".nexe"; irtPath_ = Path.Combine(Path.GetDirectoryName(chrome_path), irt_basename); if (!File.Exists(irtPath_)) { // Next look for a folder alongside chrome.exe with the same name // as the version embedded in chrome.exe. if (file_version == null) { if (!File.Exists(irtPath_)) { MessageBox.Show("NaCl IRT not found in chrome install.\nLooking for: " + irtPath_); irtPath_ = null; } } else { irtPath_ = Path.Combine(Path.GetDirectoryName(chrome_path), file_version, irt_basename); if (!File.Exists(irtPath_)) { MessageBox.Show("NaCl IRT not found in chrome install.\nLooking for: " + irtPath_); irtPath_ = null; } } } manifestPath_ = properties.ManifestPath; targetNexe_ = properties.PluginAssembly; if (properties.IsPNaCl()) { string basename = Path.GetFileNameWithoutExtension(targetNexe_); string suffix = "32"; if (Environment.Is64BitOperatingSystem) suffix = "64"; targetNexe_ = Path.Combine(Path.GetDirectoryName(targetNexe_), basename + "_" + suffix + ".nexe"); if (!File.Exists(targetNexe_)) { MessageBox.Show( string.Format("Failed to find nexe to debug: {0}", targetNexe_)); } } projectDirectory_ = properties.ProjectDirectory; gdbPath_ = Path.Combine( properties.SDKRootDirectory, "toolchain", string.Concat("win_x86_", properties.ToolchainName), @"bin\x86_64-nacl-gdb.exe"); Debug.WriteLine("Found gdb: {0}", gdbPath_); PluginFoundEvent += new EventHandler<PluginFoundEventArgs>(Attach); }
public void LogOut_Inner(bool clientSessionTerminatedAbruptly = false) { IsBusy = true; IsLoggingOut = true; if (Fellowship != null) { FellowshipQuit(false); } if (IsTrading && TradePartner != null) { var tradePartner = PlayerManager.GetOnlinePlayer(TradePartner); if (tradePartner != null) { tradePartner.HandleActionCloseTradeNegotiations(); } } if (!clientSessionTerminatedAbruptly) { if (PropertyManager.GetBool("use_turbine_chat").Item) { if (GetCharacterOption(CharacterOption.ListenToGeneralChat)) { LeaveTurbineChatChannel("General"); } if (GetCharacterOption(CharacterOption.ListenToTradeChat)) { LeaveTurbineChatChannel("Trade"); } if (GetCharacterOption(CharacterOption.ListenToLFGChat)) { LeaveTurbineChatChannel("LFG"); } if (GetCharacterOption(CharacterOption.ListenToRoleplayChat)) { LeaveTurbineChatChannel("Roleplay"); } if (GetCharacterOption(CharacterOption.ListenToAllegianceChat) && Allegiance != null) { LeaveTurbineChatChannel("Allegiance"); } if (GetCharacterOption(CharacterOption.ListenToSocietyChat) && Society != FactionBits.None) { LeaveTurbineChatChannel("Society"); } } } if (CurrentActivePet != null) { CurrentActivePet.Destroy(); } if (CurrentLandblock != null) { var logout = new Motion(MotionStance.NonCombat, MotionCommand.LogOut); EnqueueBroadcastMotion(logout); EnqueueBroadcastPhysicsState(); var logoutChain = new ActionChain(); var motionTable = DatManager.PortalDat.ReadFromDat <MotionTable>((uint)MotionTableId); float logoutAnimationLength = motionTable.GetAnimationLength(MotionCommand.LogOut); logoutChain.AddDelaySeconds(logoutAnimationLength); // remove the player from landblock management -- after the animation has run logoutChain.AddAction(this, () => { if (CurrentLandblock == null) { log.Debug($"0x{Guid}:{Name}.LogOut_Inner.logoutChain: CurrentLandblock is null, unable to remove from a landblock..."); if (Location != null) { log.Debug($"0x{Guid}:{Name}.LogOut_Inner.logoutChain: Location is not null, Location = {Location.ToLOCString()}"); } } CurrentLandblock?.RemoveWorldObject(Guid, false); SetPropertiesAtLogOut(); SavePlayerToDatabase(); PlayerManager.SwitchPlayerFromOnlineToOffline(this); }); // close any open landblock containers (chests / corpses) if (LastOpenedContainerId != ObjectGuid.Invalid) { var container = CurrentLandblock.GetObject(LastOpenedContainerId) as Container; if (container != null) { container.Close(this); } } logoutChain.EnqueueChain(); } else { log.Debug($"0x{Guid}:{Name}.LogOut_Inner: CurrentLandblock is null"); if (Location != null) { log.Debug($"0x{Guid}:{Name}.LogOut_Inner: Location is not null, Location = {Location.ToLOCString()}"); var validLoadedLandblock = LandblockManager.GetLandblock(Location.LandblockId, false); if (validLoadedLandblock.GetObject(Guid.Full) != null) { log.Debug($"0x{Guid}:{Name}.LogOut_Inner: Player is still on landblock, removing..."); validLoadedLandblock.RemoveWorldObject(Guid, false); } else { log.Debug($"0x{Guid}:{Name}.LogOut_Inner: Player is not found on the landblock Location references."); } } else { log.Debug($"0x{Guid}:{Name}.LogOut_Inner: Location is null"); } SetPropertiesAtLogOut(); SavePlayerToDatabase(); PlayerManager.SwitchPlayerFromOnlineToOffline(this); } }
/// <summary> /// A friendly (internationalized) name for the SR type. /// </summary> public static string getFriendlyTypeName(SRTypes srType) { return(PropertyManager.GetFriendlyName(string.Format("Label-SR.SRTypes-{0}", srType.ToString()), "Label-SR.SRTypes-unknown")); }
public void Dispose() { PropertyManager.Clear(template); MethodManager.Clear(template); }
public void OnRemoveItem(object sender, ExecutedRoutedEventArgs e) { PropertyManager.Remove(Property); }
/// <summary> /// Import manufacturers from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual void ImportManufacturersFromXlsx(Stream stream) { //property array var properties = new[] { new PropertyByName <Manufacturer>("Id"), new PropertyByName <Manufacturer>("Name"), new PropertyByName <Manufacturer>("Description"), new PropertyByName <Manufacturer>("ManufacturerTemplateId"), new PropertyByName <Manufacturer>("MetaKeywords"), new PropertyByName <Manufacturer>("MetaDescription"), new PropertyByName <Manufacturer>("MetaTitle"), new PropertyByName <Manufacturer>("Picture"), new PropertyByName <Manufacturer>("PageSize"), new PropertyByName <Manufacturer>("AllowCustomersToSelectPageSize"), new PropertyByName <Manufacturer>("PageSizeOptions"), new PropertyByName <Manufacturer>("PriceRanges"), new PropertyByName <Manufacturer>("Published"), new PropertyByName <Manufacturer>("DisplayOrder") }; var manager = new PropertyManager <Manufacturer>(properties); using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) { throw new NopException("No worksheet found"); } var iRow = 2; while (true) { var allColumnsAreEmpty = manager.GetProperties .Select(property => worksheet.Cells[iRow, property.PropertyOrderPosition]) .All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())); if (allColumnsAreEmpty) { break; } manager.ReadFromXlsx(worksheet, iRow); var manufacturer = _manufacturerService.GetManufacturerById(manager.GetProperty("Id").IntValue); var isNew = manufacturer == null; manufacturer = manufacturer ?? new Manufacturer(); if (isNew) { manufacturer.CreatedOnUtc = DateTime.UtcNow; } manufacturer.Name = manager.GetProperty("Name").StringValue; manufacturer.Description = manager.GetProperty("Description").StringValue; manufacturer.ManufacturerTemplateId = manager.GetProperty("ManufacturerTemplateId").IntValue; manufacturer.MetaKeywords = manager.GetProperty("MetaKeywords").StringValue; manufacturer.MetaDescription = manager.GetProperty("MetaDescription").StringValue; manufacturer.MetaTitle = manager.GetProperty("MetaTitle").StringValue; var picture = LoadPicture(manager.GetProperty("Picture").StringValue, manufacturer.Name, isNew ? null : (int?)manufacturer.PictureId); manufacturer.PageSize = manager.GetProperty("PageSize").IntValue; manufacturer.AllowCustomersToSelectPageSize = manager.GetProperty("AllowCustomersToSelectPageSize").BooleanValue; manufacturer.PageSizeOptions = manager.GetProperty("PageSizeOptions").StringValue; manufacturer.PriceRanges = manager.GetProperty("PriceRanges").StringValue; manufacturer.Published = manager.GetProperty("Published").BooleanValue; manufacturer.DisplayOrder = manager.GetProperty("DisplayOrder").IntValue; if (picture != null) { manufacturer.PictureId = picture.Id; } manufacturer.UpdatedOnUtc = DateTime.UtcNow; if (isNew) { _manufacturerService.InsertManufacturer(manufacturer); } else { _manufacturerService.UpdateManufacturer(manufacturer); } iRow++; } } }
private static void OnProcessExit(object sender, EventArgs e) { PropertyManager.StopUpdating(); DatabaseManager.Stop(); }
/// <summary> /// Import categories from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual void ImportCategoriesFromXlsx(Stream stream) { var properties = new[] { new PropertyByName <Category>("Id"), new PropertyByName <Category>("Name"), new PropertyByName <Category>("Description"), new PropertyByName <Category>("CategoryTemplateId"), new PropertyByName <Category>("MetaKeywords"), new PropertyByName <Category>("MetaDescription"), new PropertyByName <Category>("MetaTitle"), new PropertyByName <Category>("ParentCategoryId"), new PropertyByName <Category>("Picture"), new PropertyByName <Category>("PageSize"), new PropertyByName <Category>("AllowCustomersToSelectPageSize"), new PropertyByName <Category>("PageSizeOptions"), new PropertyByName <Category>("PriceRanges"), new PropertyByName <Category>("ShowOnHomePage"), new PropertyByName <Category>("IncludeInTopMenu"), new PropertyByName <Category>("Published"), new PropertyByName <Category>("DisplayOrder") }; var manager = new PropertyManager <Category>(properties); using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) { throw new NopException("No worksheet found"); } var iRow = 2; while (true) { var allColumnsAreEmpty = manager.GetProperties .Select(property => worksheet.Cells[iRow, property.PropertyOrderPosition]) .All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())); if (allColumnsAreEmpty) { break; } manager.ReadFromXlsx(worksheet, iRow); var category = _categoryService.GetCategoryById(manager.GetProperty("Id").IntValue); var isNew = category == null; category = category ?? new Category(); if (isNew) { category.CreatedOnUtc = DateTime.UtcNow; } category.Name = manager.GetProperty("Name").StringValue; category.Description = manager.GetProperty("Description").StringValue; category.CategoryTemplateId = manager.GetProperty("CategoryTemplateId").IntValue; category.MetaKeywords = manager.GetProperty("MetaKeywords").StringValue; category.MetaDescription = manager.GetProperty("MetaDescription").StringValue; category.MetaTitle = manager.GetProperty("MetaTitle").StringValue; category.ParentCategoryId = manager.GetProperty("ParentCategoryId").IntValue; var picture = LoadPicture(manager.GetProperty("Picture").StringValue, category.Name, isNew ? null : (int?)category.PictureId); category.PageSize = manager.GetProperty("PageSize").IntValue; category.AllowCustomersToSelectPageSize = manager.GetProperty("AllowCustomersToSelectPageSize").BooleanValue; category.PageSizeOptions = manager.GetProperty("PageSizeOptions").StringValue; category.PriceRanges = manager.GetProperty("PriceRanges").StringValue; category.ShowOnHomePage = manager.GetProperty("ShowOnHomePage").BooleanValue; category.IncludeInTopMenu = manager.GetProperty("IncludeInTopMenu").BooleanValue; category.Published = manager.GetProperty("Published").BooleanValue; category.DisplayOrder = manager.GetProperty("DisplayOrder").IntValue; if (picture != null) { category.PictureId = picture.Id; } category.UpdatedOnUtc = DateTime.UtcNow; if (isNew) { _categoryService.InsertCategory(category); } else { _categoryService.UpdateCategory(category); } iRow++; } } }
public static IList <TObject> BubbleSortBy <TObject, TMember>( this IList <TObject> collection, Expression <Func <TObject, TMember> > expression, bool ascending) where TMember : struct, IComparable, IComparable <TMember>, IConvertible, IEquatable <TMember>, IFormattable { var itemCount = collection.Count; var propertyName = PropertyManager.GetMemberName(expression.Body); var isComplete = false; while (!isComplete) { var swapped = false; for (var i = 1; i < itemCount; i++) { var comparason = PropertyManager.GetMemberValue <TObject, TMember>(collection[i - 1], propertyName).CompareTo(PropertyManager.GetMemberValue <TObject, TMember>(collection[i], propertyName)); if (ascending ? (comparason > 0) : (comparason < 0)) { collection = collection.Swap(i - 1, i); swapped = true; } } if (!swapped) { isComplete = true; } } return(collection); }
public static void HandleReportbug(Session session, params string[] parameters) { if (!PropertyManager.GetBool("reportbug_enabled").Item) { session.Network.EnqueueSend(new GameMessageSystemChat("The command \"reportbug\" is not currently enabled on this server.", ChatMessageType.Broadcast)); return; } var category = parameters[0]; var description = ""; for (var i = 1; i < parameters.Length; i++) { description += parameters[i] + " "; } description.Trim(); switch (category.ToLower()) { case "creature": case "npc": case "quest": case "item": case "recipe": case "landblock": case "mechanic": case "code": case "other": break; default: category = "Other"; break; } var sn = ConfigManager.Config.Server.WorldName; var c = session.Player.Name; var st = "ACE"; //var versions = ServerBuildInfo.GetVersionInfo(); var databaseVersion = DatabaseManager.World.GetVersion(); var sv = ServerBuildInfo.FullVersion; var pv = databaseVersion.PatchVersion; //var ct = PropertyManager.GetString("reportbug_content_type").Item; var cg = category.ToLower(); var w = ""; var g = ""; if (cg == "creature" || cg == "npc" || cg == "item" || cg == "item") { var objectId = new ObjectGuid(); if (session.Player.HealthQueryTarget.HasValue || session.Player.ManaQueryTarget.HasValue || session.Player.CurrentAppraisalTarget.HasValue) { if (session.Player.HealthQueryTarget.HasValue) { objectId = new ObjectGuid((uint)session.Player.HealthQueryTarget); } else if (session.Player.ManaQueryTarget.HasValue) { objectId = new ObjectGuid((uint)session.Player.ManaQueryTarget); } else { objectId = new ObjectGuid((uint)session.Player.CurrentAppraisalTarget); } //var wo = session.Player.CurrentLandblock?.GetObject(objectId); var wo = session.Player.FindObject(objectId.Full, Player.SearchLocations.Everywhere); if (wo != null) { w = $"{wo.WeenieClassId}"; g = $"0x{wo.Guid:X8}"; } } } var l = session.Player.Location.ToLOCString(); var issue = description; var urlbase = $"https://www.accpp.net/bug?"; var url = urlbase; if (sn.Length > 0) { url += $"sn={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sn))}"; } if (c.Length > 0) { url += $"&c={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(c))}"; } if (st.Length > 0) { url += $"&st={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(st))}"; } if (sv.Length > 0) { url += $"&sv={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sv))}"; } if (pv.Length > 0) { url += $"&pv={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(pv))}"; } //if (ct.Length > 0) // url += $"&ct={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ct))}"; if (cg.Length > 0) { if (cg == "npc") { cg = cg.ToUpper(); } else { cg = char.ToUpper(cg[0]) + cg.Substring(1); } url += $"&cg={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cg))}"; } if (w.Length > 0) { url += $"&w={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(w))}"; } if (g.Length > 0) { url += $"&g={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(g))}"; } if (l.Length > 0) { url += $"&l={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(l))}"; } if (issue.Length > 0) { url += $"&i={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(issue))}"; } var msg = "\n\n\n\n"; msg += "Bug Report - Copy and Paste the following URL into your browser to submit a bug report\n"; msg += "-=-\n"; msg += $"{url}\n"; msg += "-=-\n"; msg += "\n\n\n\n"; session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.AdminTell)); }
public void DeathItemLog(List <WorldObject> dropItems, Corpse corpse) { if (dropItems.Count == 0) { return; } var msg = $"[CORPSE] {Name} dropped items on corpse (0x{corpse.Guid}): "; foreach (var dropItem in dropItems) { msg += $"{(dropItem.StackSize.HasValue && dropItem.StackSize > 1 ? dropItem.StackSize.Value.ToString("N0") + " " + dropItem.GetPluralName() : dropItem.Name)} (0x{dropItem.Guid}){(dropItem.WeenieClassId == 273 && PropertyManager.GetBool("corpse_destroy_pyreals").Item ? $" which {(dropItem.StackSize.HasValue && dropItem.StackSize > 1 ? "were" : "was")} destroyed" : "")}, "; } msg = msg.Substring(0, msg.Length - 2); log.Debug(msg); }
public static void HandleConfig(Session session, params string[] parameters) { if (!PropertyManager.GetBool("player_config_command").Item) { session.Network.EnqueueSend(new GameMessageSystemChat("The command \"config\" is not currently enabled on this server.", ChatMessageType.Broadcast)); return; } // /config list - show character options if (parameters[0].Equals("list", StringComparison.OrdinalIgnoreCase)) { foreach (var line in configList) { session.Network.EnqueueSend(new GameMessageSystemChat(line, ChatMessageType.Broadcast)); } return; } // translate GDLE CharacterOptions for existing plugins if (!translateOptions.TryGetValue(parameters[0], out var param) || !Enum.TryParse(param, out CharacterOption characterOption)) { session.Network.EnqueueSend(new GameMessageSystemChat($"Unknown character option: {parameters[0]}", ChatMessageType.Broadcast)); return; } var option = session.Player.GetCharacterOption(characterOption); // modes of operation: // on / off / toggle // - if none specified, default to toggle var mode = "toggle"; if (parameters.Length > 1) { if (parameters[1].Equals("on", StringComparison.OrdinalIgnoreCase)) { mode = "on"; } else if (parameters[1].Equals("off", StringComparison.OrdinalIgnoreCase)) { mode = "off"; } } // set character option if (mode.Equals("on")) { option = true; } else if (mode.Equals("off")) { option = false; } else { option = !option; } session.Player.SetCharacterOption(characterOption, option); session.Network.EnqueueSend(new GameMessageSystemChat($"Character option {parameters[0]} is now {(option ? "on" : "off")}.", ChatMessageType.Broadcast)); // update client session.Network.EnqueueSend(new GameEventPlayerDescription(session)); }
public Railroad(Int32 index, Int32 price, Int32 baseRent, String group, Banker banker, PropertyManager propertyManager) : base(index, price, baseRent, group, banker, propertyManager) { }
public static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); // Typically, you wouldn't force the current culture on an entire application unless you know sure your application is used in a specific region (which ACE is not) // We do this because almost all of the client/user input/output code does not take culture into account, and assumes en-US formatting. // Without this, many commands that require special characters like , and . will break Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); // Init our text encoding options. This will allow us to use more than standard ANSI text, which the client also supports. System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); // Look for the log4net.config first in the current environment directory, then in the ExecutingAssembly location var log4netFileInfo = new FileInfo("log4net.config"); if (!log4netFileInfo.Exists) { log4netFileInfo = new FileInfo(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "log4net.config")); } var logRepository = LogManager.GetRepository(System.Reflection.Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, log4netFileInfo); if (Environment.ProcessorCount < 2) { log.Warn("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server."); } // Do system specific initializations here try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // On many windows systems, the default resolution for Thread.Sleep is 15.6ms. This allows us to command a tighter resolution MM_BeginPeriod(1); } } catch (Exception ex) { log.Error(ex.ToString()); } log.Info("Starting ACEmulator..."); Console.Title = @"ACEmulator"; log.Info("Initializing ConfigManager..."); ConfigManager.Initialize(); if (ConfigManager.Config.Offline.PurgeDeletedCharacters) { log.Info($"Purging deleted characters, and their possessions, older than {ConfigManager.Config.Offline.PurgeDeletedCharactersDays} days ({DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays)})..."); ShardDatabaseOfflineTools.PurgeCharactersInParallel(ConfigManager.Config.Offline.PurgeDeletedCharactersDays, out var charactersPurged, out var playerBiotasPurged, out var possessionsPurged); log.Info($"Purged {charactersPurged:N0} characters, {playerBiotasPurged:N0} player biotas and {possessionsPurged:N0} possessions."); } if (ConfigManager.Config.Offline.PurgeOrphanedBiotas) { log.Info($"Purging orphaned biotas..."); ShardDatabaseOfflineTools.PurgeOrphanedBiotasInParallel(out var numberOfBiotasPurged); log.Info($"Purged {numberOfBiotasPurged:N0} biotas."); } log.Info("Initializing ServerManager..."); ServerManager.Initialize(); log.Info("Initializing DatManager..."); DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory, true); log.Info("Initializing DatabaseManager..."); DatabaseManager.Initialize(); log.Info("Starting DatabaseManager..."); DatabaseManager.Start(); log.Info("Starting PropertyManager..."); PropertyManager.Initialize(); log.Info("[Custom Code] Starting CustomPropertyManager..."); CustomPropertiesManager.Initialize(); log.Info("Initializing GuidManager..."); GuidManager.Initialize(); if (ConfigManager.Config.Server.ServerPerformanceMonitorAutoStart) { log.Info("Server Performance Monitor auto starting..."); ServerPerformanceMonitor.Start(); } if (ConfigManager.Config.Server.WorldDatabasePrecaching) { log.Info("Precaching Weenies..."); DatabaseManager.World.CacheAllWeeniesInParallel(); log.Info("Precaching House Portals..."); DatabaseManager.World.CacheAllHousePortals(); log.Info("Precaching Points Of Interest..."); DatabaseManager.World.CacheAllPointsOfInterest(); log.Info("Precaching Spells..."); DatabaseManager.World.CacheAllSpells(); log.Info("Precaching Events..."); DatabaseManager.World.GetAllEvents(); log.Info("Precaching Death Treasures..."); DatabaseManager.World.CacheAllDeathTreasures(); log.Info("Precaching Wielded Treasures..."); DatabaseManager.World.CacheAllWieldedTreasuresInParallel(); log.Info("Precaching Treasure Materials..."); DatabaseManager.World.CacheAllTreasuresMaterialBaseInParallel(); DatabaseManager.World.CacheAllTreasuresMaterialGroupsInParallel(); log.Info("Precaching Treasure Colors..."); DatabaseManager.World.CacheAllTreasuresMaterialColorInParallel(); log.Info("Precaching Cookbooks..."); DatabaseManager.World.CacheAllCookbooksInParallel(); } else { log.Info("Precaching World Database Disabled..."); } log.Info("Initializing PlayerManager..."); PlayerManager.Initialize(); log.Info("Initializing HouseManager..."); HouseManager.Initialize(); log.Info("Initializing InboundMessageManager..."); InboundMessageManager.Initialize(); log.Info("Initializing SocketManager..."); SocketManager.Initialize(); log.Info("Initializing WorldManager..."); WorldManager.Initialize(); log.Info("Initializing EventManager..."); EventManager.Initialize(); // This should be last log.Info("Initializing CommandManager..."); CommandManager.Initialize(); log.Info("Initializing Riptide API Portal..."); GlobalEventManager.AuthWebPortal(); if (!PropertyManager.GetBool("world_closed", false).Item) { WorldManager.Open(null); } }
/// <summary> /// Import manufacturers from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual void ImportManufacturerFromXlsx(Stream stream) { //property array var properties = new[] { new PropertyByName<Manufacturer>("Id"), new PropertyByName<Manufacturer>("Name"), new PropertyByName<Manufacturer>("Description"), new PropertyByName<Manufacturer>("ManufacturerTemplateId"), new PropertyByName<Manufacturer>("MetaKeywords"), new PropertyByName<Manufacturer>("MetaDescription"), new PropertyByName<Manufacturer>("MetaTitle"), new PropertyByName<Manufacturer>("SeName"), new PropertyByName<Manufacturer>("Picture"), new PropertyByName<Manufacturer>("PageSize"), new PropertyByName<Manufacturer>("AllowCustomersToSelectPageSize"), new PropertyByName<Manufacturer>("PageSizeOptions"), new PropertyByName<Manufacturer>("PriceRanges"), new PropertyByName<Manufacturer>("Published"), new PropertyByName<Manufacturer>("DisplayOrder") }; var manager = new PropertyManager<Manufacturer>(properties); using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) throw new NopException("No worksheet found"); var iRow = 2; while (true) { var allColumnsAreEmpty = manager.GetProperties .Select(property => worksheet.Cells[iRow, property.PropertyOrderPosition]) .All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())); if (allColumnsAreEmpty) break; manager.ReadFromXlsx(worksheet, iRow); var manufacturer = _manufacturerService.GetManufacturerById(manager.GetProperty("Id").IntValue); var isNew = manufacturer == null; manufacturer = manufacturer ?? new Manufacturer(); if (isNew) manufacturer.CreatedOnUtc = DateTime.UtcNow; manufacturer.Name = manager.GetProperty("Name").StringValue; manufacturer.Description = manager.GetProperty("Description").StringValue; manufacturer.ManufacturerTemplateId = manager.GetProperty("ManufacturerTemplateId").IntValue; manufacturer.MetaKeywords = manager.GetProperty("MetaKeywords").StringValue; manufacturer.MetaDescription = manager.GetProperty("MetaDescription").StringValue; manufacturer.MetaTitle = manager.GetProperty("MetaTitle").StringValue; var _seName = manager.GetProperty("SeName").StringValue; var picture = LoadPicture(manager.GetProperty("Picture").StringValue, manufacturer.Name, isNew ? null : (int?)manufacturer.PictureId); manufacturer.PageSize = manager.GetProperty("PageSize").IntValue; manufacturer.AllowCustomersToSelectPageSize = manager.GetProperty("AllowCustomersToSelectPageSize").BooleanValue; manufacturer.PageSizeOptions = manager.GetProperty("PageSizeOptions").StringValue; manufacturer.PriceRanges = manager.GetProperty("PriceRanges").StringValue; manufacturer.Published = manager.GetProperty("Published").BooleanValue; manufacturer.DisplayOrder = manager.GetProperty("DisplayOrder").IntValue; if (picture != null) manufacturer.PictureId = picture.Id; manufacturer.UpdatedOnUtc = DateTime.UtcNow; if (isNew) _manufacturerService.InsertManufacturer(manufacturer); else _manufacturerService.UpdateManufacturer(manufacturer); _seName = manufacturer.ValidateSeName(_seName, manufacturer.Name, true); manufacturer.SeName = _seName; _manufacturerService.UpdateManufacturer(manufacturer); _urlRecordService.SaveSlug(manufacturer, manufacturer.SeName, 0); iRow++; } } }
public void Refuel(Client player, int fuel = 0) { var prop = PropertyManager.IsAtPropertyInteraction(player); if (prop?.Type == PropertyManager.PropertyTypes.GasStation) { if (API.IsPlayerInAnyVehicle(player) && API.GetPlayerVehicleSeat(player) == -1) { var vehEntity = API.GetPlayerVehicle(player); Vehicle veh = API.GetEntityData(vehEntity, "Vehicle"); if (API.GetVehicleEngineStatus(vehEntity)) { API.SendChatMessageToPlayer(player, "Vehicle engine must be off."); return; } if (player.hasData("FUELING_VEHICLE")) { API.SendChatMessageToPlayer(player, "You're already refueling a vehicle."); return; } if (fuel == 0) { fuel = 100 - veh.Fuel; } var pendingFuel = fuel; if (pendingFuel > 100 || pendingFuel + veh.Fuel > 100 || pendingFuel < 0) { API.SendChatMessageToPlayer(player, "Vehicle fuel can't be above 100 or negative."); return; } if (Money.GetCharacterMoney(player.GetCharacter()) < pendingFuel * prop.ItemPrices["gas"] && player.GetCharacter().Group.CommandType != group_manager.Group.CommandTypeLspd) { API.SendChatMessageToPlayer(player, $"You don't have enough money to get ~r~{pendingFuel}~w~ units of fuel.~n~It's worth ~g~${pendingFuel * prop.ItemPrices["gas"]}~w~."); return; } API.SendChatMessageToPlayer(player, $"You will be charged ~g~${pendingFuel * prop.ItemPrices["gas"]}~w~ for ~r~{pendingFuel}~w~ units of fuel."); API.FreezePlayer(player, true); API.SetEntityData(vehEntity, "PENDING_FUEL", pendingFuel); veh.RefuelProp = prop; FuelVeh(new[] { player, vehEntity }); if (API.HasEntityData(vehEntity, "PENDING_FUEL")) { API.SetEntityData(player, "FUELING_VEHICLE", vehEntity); veh.FuelingTimer = new System.Threading.Timer(FuelVeh, new[] { player, vehEntity }, 3000, 3000); return; } } else { API.SendChatMessageToPlayer(player, "You must be driving a vehicle."); } } else { API.SendChatMessageToPlayer(player, "You must be at a gas station."); } }
/// <summary> /// Import categories from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual void ImportCategoryFromXlsx(Stream stream) { var properties = new[] { new PropertyByName<Category>("Id"), new PropertyByName<Category>("Name"), new PropertyByName<Category>("Description"), new PropertyByName<Category>("CategoryTemplateId"), new PropertyByName<Category>("MetaKeywords"), new PropertyByName<Category>("MetaDescription"), new PropertyByName<Category>("MetaTitle"), new PropertyByName<Category>("SeName"), new PropertyByName<Category>("ParentCategoryId"), new PropertyByName<Category>("Picture"), new PropertyByName<Category>("PageSize"), new PropertyByName<Category>("AllowCustomersToSelectPageSize"), new PropertyByName<Category>("PageSizeOptions"), new PropertyByName<Category>("PriceRanges"), new PropertyByName<Category>("ShowOnHomePage"), new PropertyByName<Category>("IncludeInTopMenu"), new PropertyByName<Category>("Published"), new PropertyByName<Category>("DisplayOrder") }; var manager = new PropertyManager<Category>(properties); using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) throw new NopException("No worksheet found"); var iRow = 2; while (true) { var allColumnsAreEmpty = manager.GetProperties .Select(property => worksheet.Cells[iRow, property.PropertyOrderPosition]) .All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())); if (allColumnsAreEmpty) break; manager.ReadFromXlsx(worksheet, iRow); var category = _categoryService.GetCategoryById(manager.GetProperty("Id").IntValue); var isNew = category == null; category = category ?? new Category(); if (isNew) category.CreatedOnUtc = DateTime.UtcNow; category.Name = manager.GetProperty("Name").StringValue; category.Description = manager.GetProperty("Description").StringValue; category.CategoryTemplateId = manager.GetProperty("CategoryTemplateId").IntValue; category.MetaKeywords = manager.GetProperty("MetaKeywords").StringValue; category.MetaDescription = manager.GetProperty("MetaDescription").StringValue; category.MetaTitle = manager.GetProperty("MetaTitle").StringValue; var _seName = manager.GetProperty("SeName").StringValue; category.ParentCategoryId = manager.GetProperty("ParentCategoryId").IntValue; var picture = LoadPicture(manager.GetProperty("Picture").StringValue, category.Name, isNew ? null : (int?)category.PictureId); category.PageSize = manager.GetProperty("PageSize").IntValue; category.AllowCustomersToSelectPageSize = manager.GetProperty("AllowCustomersToSelectPageSize").BooleanValue; category.PageSizeOptions = manager.GetProperty("PageSizeOptions").StringValue; category.PriceRanges = manager.GetProperty("PriceRanges").StringValue; category.ShowOnHomePage = manager.GetProperty("ShowOnHomePage").BooleanValue; category.IncludeInTopMenu = manager.GetProperty("IncludeInTopMenu").BooleanValue; category.Published = manager.GetProperty("Published").BooleanValue; category.DisplayOrder = manager.GetProperty("DisplayOrder").IntValue; if (picture != null) category.PictureId = picture.Id; category.UpdatedOnUtc = DateTime.UtcNow; if (isNew) _categoryService.InsertCategory(category); else _categoryService.UpdateCategory(category); _seName = category.ValidateSeName(_seName, category.Name, true); category.SeName = _seName; _categoryService.UpdateCategory(category); _urlRecordService.SaveSlug(category, _seName, 0); iRow++; } } }
public List <WorldObject> CalculateDeathItems(Corpse corpse) { // https://web.archive.org/web/20140712134108/http://support.turbine.com/link/portal/24001/24001/Article/464/How-do-death-items-work-in-Asheron-s-Call-Could-you-explain-how-the-game-decides-what-you-drop-when-you-die-in-Asheron-s-Call // Original formula: // - When you are level 5 or under, you don't drop anything when you die. // - From level 6 to level 10, you lose half your coins (not trade notes) and nothing else. // - From level 11 to level 20, you lose half your coins and possibly one non-wielded item (that is, something that you were neither wearing nor holding in your hands). // - From level 21 to level 35, you lose half your coins and some number of non-wielded items. // - After level 35, you lose half your coins and some number of items. At this point, you can drop items that you were wearing or holding. // Now, in those last two cases, I said 'some number'. Some number here is equal to your level divided by 10, rounded down, plus a random number between 0 and 2. // So from level 21 to 29 you can lose between 2 and 4 items; from level 30 to 39 you can lose 3-5 items; from 40-49 you can lose 4-6 items, and so forth. // By level 126 you can be losing up to 14 items. // (one caveat here: if you were killed in a PK battle, you always lose items as if you were over level 35, although the exact number you lose // is still determined by your real level / 10. In other words, PK deaths do not get the special protection from item loss that NPK deaths get under level 35.) // So that's how many items you lose on death -- but how do we determine which items are lost? This is where the categories come into it. // Each item in the game has a particular item type associated with it. The actual types (categories) are listed below. // When we are deciding what items you drop on death, we make a list of all the items you are carrying, sorted by value (high value first). // But we may adjust their values in two ways. If the item is not the most valuable item in that category, then we cut its value in half. // And whether or not it is the most valuable item in its category, we randomize its value a little bit to mix things up. // (To answer your first question explicitly, the cutting-the-value-in-half is not cumulative -- the second- and third- and fourth-most valuable items // of one category all have their values halved, not halved and then quartered and then eighthed). // Now note that we still keep these things in a list sorted by adjusted value -- so its possible to have your two expensive weapons // listed first and second, if the value of the second weapon cut in half is still higher than the value of the third item. What I am trying to get at here is // that we do not segregate the list based on item type; we only use item type to determine how we adjust the value of the item. // Finally, we go down the list and mark the first # things as dropped, where # is the number of items we have calculated that you are going to drop this death. // For instance, if you are level 48, you will drop the first 4-6 items on that list. // The categories of items are: // - Melee weapons // - Missile weapons // - Magic casters (like orbs & wands) // - Armor // - Clothing // - Jewelry // - Food // - Gems // - Components // - Mana stones // - Crafting ingredients // - Parchments & books // - Keys // - Tradenotes // - Miscellaneous // A few categories are left out such as lifestones -- because you aren't likely to be carrying an item of that type. // http://asheron.wikia.com/wiki/Death_Penalty // The first item to drop will be the highest value item regardless of type. // All items of the same type will now be counted at half their face value. This process repeats (next highest value item, // if an item of the same type has already dropped, the face value is halved.) // The number of items you drop can be reduced with the Clutch of the Miser augmentation. If you get the // augmentation three times you will no longer drop any items (except half of your Pyreals and all Rares except if you're a PK). // If you drop no items, you will not leave a corpse. // Some players use gems, particularly the Archmage Portal Gems as death items, so it's important to note how // stackable items work with the death system. When you die, a stack is considered to be one item for the purposes // of death items. However if that stack is selected, only one item off the stack will drop. For example, let's say you // can currently cover all of your items with 5 Portal Gems. After the event, if you do not stack these gems, there // will be no change. However, if you combine the 5 Gems into a single stack, you would drop 1 gem and 4 other items on death. // When you die there is a notification in your chat dialog stating what items you dropped, and your corpse location // (if on the landscape). If you do not leave a corpse the notification will state so. // Accounts with the Throne of Destiny expansion received a new formula for death items to prevent losing a // pack per death at high levels. The formula was changed to divide by 20 levels instead of 10, thereby making // the maximum dropped items the same. // Tier 1 and 2 Rares will always drop, and do not count toward your death item count, so store them in a safe place. // PKLite - no items or pyreals are lost on PKL death. // Death items // You can protect important items like your armor and weapons by carrying death items. These are items that are // ideally light weight as well as high in value. You can tinker loot items with bags of Salvaged Gold to raise their // face value. Although tinkering special items can remove some of the beneift, as you feel obligated to recover // them. Items that can be purchased can just be left if the corpse would be too difficult to recover. // Popular items to use as Death Items: // - Massive Mana Charges (most common death item) // - Pristine Mana Shards // - Crowns (tinkered with gold) // - Robes sold by the Mastermages // - Nanner Island Portal Gems (somewhat difficult to obtain) // Bonded items: // Items that have the Special Property Bonded will never drop on death. Some notable bonded items include: // - Academy Weapons (Starter weapons) // - Augmentation Gems (Asheron's Benediction and Blackmoor's Favor) // - Pathwarden Armor (Starter armor) // - Trade Notes // http://acpedia.org/wiki/Recovering_from_Death // Recovering from Death // Fortunately, you won't be in immediate danger of being killed again, because you're invulnerable to attack for a full minute if you don't attack another // creature of cast any spells. Also, your secondary attributes, even if all had been reduced to 0 when you died, will be at 75 percent of their new // maximum score, and any poisons or harmful enchantments afflicting you just before you died will be gone, giving you a fighting chance of making it // back to town or meeting up with your allies. // You can also find the location of your last corpse outdoors by typing @corpse. // Corpse timer = Math.Max(1 hour, 5 mins * level) // TODO: @permit and @consent commands // You can have up to 20 people in your consent list at once. However, when you log off, all permissions to loot corpses will be removed. // First, we sort the inventory by order of value. // Second, we go back through the inventory starting at the most expensive item and look at each item's category. // If we've seen the item category before, we divide the value of the item in half. // At this point, we add a random 0-10% variance to each item's value. // http://acpedia.org/wiki/Death_Item // A Reign of Stone (April 2001) - Corpse permission commands added. // The Changing of the Ways (May 2001) - Players are now given the coordinates of their characters' corpses when they die. // Hidden Vein (May 2002) - Many changes made on the way item loss on death works. See http://acpedia.org/wiki/Hidden_Vein and http://acpedia.org/wiki/Announcements_-_2002/05_-_Hidden_Vein#Letter_to_the_Players for more details // Throne of Destiny expansion (July 2005) - The formula used for working out how many items a character drops was updated. For details on the old formula and how it changed see http://acpedia.org/wiki/Announcements_-_2005/07_-_Throne_of_Destiny_(expansion)#FAQ_-_AC:TD_Level_Cap_Update // if player dies in a PKLite battle, // they don't drop any items, and revert back to NPK status var killer = CurrentLandblock?.GetObject(new ObjectGuid(KillerId ?? 0)); if (PlayerKillerStatus == PlayerKillerStatus.PKLite) { if (killer is Player) { PlayerKillerStatus = PlayerKillerStatus.NPK; EnqueueBroadcast(new GameMessagePublicUpdatePropertyInt(this, PropertyInt.PlayerKillerStatus, (int)PlayerKillerStatus)); return(new List <WorldObject>()); } } var numItemsDropped = GetNumItemsDropped(killer); var numCoinsDropped = GetNumCoinsDropped(); var level = Level ?? 1; var canDropWielded = level >= 35; // get all items in inventory var inventory = GetAllPossessions(); // exclude pyreals from randomized death item calculation inventory = inventory.Where(i => !i.Name.Equals("Pyreal")).ToList(); // exclude wielded items if < level 35 if (!canDropWielded) { inventory = inventory.Where(i => i.CurrentWieldedLocation != null).ToList(); } // exclude bonded items inventory = inventory.Where(i => (i.GetProperty(PropertyInt.Bonded) ?? 0) == 0).ToList(); // handle items with BondedStatus.Destroy var destroyedItems = HandleDestroyBonded(); // construct the list of death items var sorted = new DeathItems(inventory); var dropItems = new List <WorldObject>(); if (numCoinsDropped > 0) { // add pyreals to dropped items var pyreals = SpendCurrency((uint)numCoinsDropped, WeenieType.Coin); dropItems.AddRange(pyreals); //Console.WriteLine($"Dropping {numCoinsDropped} pyreals"); } // Remove the items from inventory for (var i = 0; i < numItemsDropped && i < sorted.Inventory.Count; i++) { var deathItem = sorted.Inventory[i]; // split stack if needed if ((deathItem.WorldObject.StackSize ?? 1) > 1) { var stack = FindObject(deathItem.WorldObject.Guid, SearchLocations.MyInventory | SearchLocations.MyEquippedItems, out var foundInContainer, out var rootContainer, out _); if (stack != null) { AdjustStack(stack, -1, foundInContainer, rootContainer); Session.Network.EnqueueSend(new GameMessageSetStackSize(stack)); var dropItem = WorldObjectFactory.CreateNewWorldObject(deathItem.WorldObject.WeenieClassId); //Console.WriteLine("Dropping " + deathItem.WorldObject.Name + " (stack)"); dropItems.Add(dropItem); } else { log.WarnFormat("Couldn't find death item stack 0x{0:X8}:{1} for player {2}", deathItem.WorldObject.Guid.Full, deathItem.WorldObject.Name, Name); } } else { if (TryRemoveFromInventoryWithNetworking(deathItem.WorldObject.Guid, out _, RemoveFromInventoryAction.ToCorpseOnDeath) || TryDequipObjectWithNetworking(deathItem.WorldObject.Guid, out _, DequipObjectAction.ToCorpseOnDeath)) { //Console.WriteLine("Dropping " + deathItem.WorldObject.Name); dropItems.Add(deathItem.WorldObject); } else { log.WarnFormat("Couldn't find death item 0x{0:X8}:{1} for player {2}", deathItem.WorldObject.Guid.Full, deathItem.WorldObject.Name, Name); } } } // handle items with BondedStatus.Slippery: always drop on death var slipperyItems = GetSlipperyItems(); dropItems.AddRange(slipperyItems); var destroyCoins = PropertyManager.GetBool("corpse_destroy_pyreals").Item; // add items to corpse foreach (var dropItem in dropItems) { // coins already removed from SpendCurrency if (destroyCoins && dropItem.WeenieType == WeenieType.Coin) { continue; } if (!corpse.TryAddToInventory(dropItem)) { log.Warn($"Player_Death: couldn't add item to {Name}'s corpse: {dropItem.Name}"); if (!TryAddToInventory(dropItem)) { log.Warn($"Player_Death: couldn't re-add item to {Name}'s inventory: {dropItem.Name}"); } } } // notify player of destroyed items? dropItems.AddRange(destroyedItems); // send network messages var dropList = DropMessage(dropItems, numCoinsDropped); Session.Network.EnqueueSend(new GameMessageSystemChat(dropList, ChatMessageType.WorldBroadcast)); return(dropItems); }
/// <summary> /// Import products from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual void ImportProductsFromXlsx(Stream stream) { //var start = DateTime.Now; //the columns var properties = new [] { new PropertyByName <Product>("ProductTypeId"), new PropertyByName <Product>("ParentGroupedProductId"), new PropertyByName <Product>("VisibleIndividually"), new PropertyByName <Product>("Name"), new PropertyByName <Product>("ShortDescription"), new PropertyByName <Product>("FullDescription"), new PropertyByName <Product>("VendorId"), new PropertyByName <Product>("ProductTemplateId"), new PropertyByName <Product>("ShowOnHomePage"), new PropertyByName <Product>("MetaKeywords"), new PropertyByName <Product>("MetaDescription"), new PropertyByName <Product>("MetaTitle"), new PropertyByName <Product>("SeName"), new PropertyByName <Product>("AllowCustomerReviews"), new PropertyByName <Product>("Published"), new PropertyByName <Product>("SKU"), new PropertyByName <Product>("ManufacturerPartNumber"), new PropertyByName <Product>("Gtin"), new PropertyByName <Product>("IsGiftCard"), new PropertyByName <Product>("GiftCardTypeId"), new PropertyByName <Product>("OverriddenGiftCardAmount"), new PropertyByName <Product>("RequireOtherProducts"), new PropertyByName <Product>("RequiredProductIds"), new PropertyByName <Product>("AutomaticallyAddRequiredProducts"), new PropertyByName <Product>("IsDownload"), new PropertyByName <Product>("DownloadId"), new PropertyByName <Product>("UnlimitedDownloads"), new PropertyByName <Product>("MaxNumberOfDownloads"), new PropertyByName <Product>("DownloadActivationTypeId"), new PropertyByName <Product>("HasSampleDownload"), new PropertyByName <Product>("SampleDownloadId"), new PropertyByName <Product>("HasUserAgreement"), new PropertyByName <Product>("UserAgreementText"), new PropertyByName <Product>("IsRecurring"), new PropertyByName <Product>("RecurringCycleLength"), new PropertyByName <Product>("RecurringCyclePeriodId"), new PropertyByName <Product>("RecurringTotalCycles"), new PropertyByName <Product>("IsRental"), new PropertyByName <Product>("RentalPriceLength"), new PropertyByName <Product>("RentalPricePeriodId"), new PropertyByName <Product>("IsShipEnabled"), new PropertyByName <Product>("IsFreeShipping"), new PropertyByName <Product>("ShipSeparately"), new PropertyByName <Product>("AdditionalShippingCharge"), new PropertyByName <Product>("DeliveryDateId"), new PropertyByName <Product>("IsTaxExempt"), new PropertyByName <Product>("TaxCategoryId"), new PropertyByName <Product>("IsTelecommunicationsOrBroadcastingOrElectronicServices"), new PropertyByName <Product>("ManageInventoryMethodId"), new PropertyByName <Product>("UseMultipleWarehouses"), new PropertyByName <Product>("WarehouseId"), new PropertyByName <Product>("StockQuantity"), new PropertyByName <Product>("DisplayStockAvailability"), new PropertyByName <Product>("DisplayStockQuantity"), new PropertyByName <Product>("MinStockQuantity"), new PropertyByName <Product>("LowStockActivityId"), new PropertyByName <Product>("NotifyAdminForQuantityBelow"), new PropertyByName <Product>("BackorderModeId"), new PropertyByName <Product>("AllowBackInStockSubscriptions"), new PropertyByName <Product>("OrderMinimumQuantity"), new PropertyByName <Product>("OrderMaximumQuantity"), new PropertyByName <Product>("AllowedQuantities"), new PropertyByName <Product>("AllowAddingOnlyExistingAttributeCombinations"), new PropertyByName <Product>("DisableBuyButton"), new PropertyByName <Product>("DisableWishlistButton"), new PropertyByName <Product>("AvailableForPreOrder"), new PropertyByName <Product>("PreOrderAvailabilityStartDateTimeUtc"), new PropertyByName <Product>("CallForPrice"), new PropertyByName <Product>("Price"), new PropertyByName <Product>("OldPrice"), new PropertyByName <Product>("ProductCost"), new PropertyByName <Product>("SpecialPrice"), new PropertyByName <Product>("SpecialPriceStartDateTimeUtc"), new PropertyByName <Product>("SpecialPriceEndDateTimeUtc"), new PropertyByName <Product>("CustomerEntersPrice"), new PropertyByName <Product>("MinimumCustomerEnteredPrice"), new PropertyByName <Product>("MaximumCustomerEnteredPrice"), new PropertyByName <Product>("BasepriceEnabled"), new PropertyByName <Product>("BasepriceAmount"), new PropertyByName <Product>("BasepriceUnitId"), new PropertyByName <Product>("BasepriceBaseAmount"), new PropertyByName <Product>("BasepriceBaseUnitId"), new PropertyByName <Product>("MarkAsNew"), new PropertyByName <Product>("MarkAsNewStartDateTimeUtc"), new PropertyByName <Product>("MarkAsNewEndDateTimeUtc"), new PropertyByName <Product>("Weight"), new PropertyByName <Product>("Length"), new PropertyByName <Product>("Width"), new PropertyByName <Product>("Height"), new PropertyByName <Product>("CategoryIds"), new PropertyByName <Product>("ManufacturerIds"), new PropertyByName <Product>("Picture1"), new PropertyByName <Product>("Picture2"), new PropertyByName <Product>("Picture3") }; var manager = new PropertyManager <Product>(properties); using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) { throw new NopException("No worksheet found"); } var endRow = 2; var allCategoriesIds = new List <int>(); var allSku = new List <string>(); var categoryCellNum = manager.GetProperty("CategoryIds").PropertyOrderPosition; var skuCellNum = manager.GetProperty("SKU").PropertyOrderPosition; var allManufacturersIds = new List <int>(); var manufacturerCellNum = manager.GetProperty("ManufacturerIds").PropertyOrderPosition; //find end of data while (true) { var allColumnsAreEmpty = manager.GetProperties .Select(property => worksheet.Cells[endRow, property.PropertyOrderPosition]) .All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())); if (allColumnsAreEmpty) { break; } var categoryIds = worksheet.Cells[endRow, categoryCellNum].Value.Return(p => p.ToString(), string.Empty); if (!categoryIds.IsEmpty()) { allCategoriesIds.AddRange(categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))); } var sku = worksheet.Cells[endRow, skuCellNum].Value.Return(p => p.ToString(), string.Empty); if (!sku.IsEmpty()) { allSku.Add(sku); } var manufacturerIds = worksheet.Cells[endRow, manufacturerCellNum].Value.Return(p => p.ToString(), string.Empty); if (!manufacturerIds.IsEmpty()) { allManufacturersIds.AddRange(manufacturerIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))); } endRow++; } //performance optimization, the check for the existence of the categories in one SQL request var notExistingCategories = _categoryService.GetNotExistingCategories(allCategoriesIds.ToArray()); if (notExistingCategories.Any()) { throw (new ArgumentException(string.Format("The following category ID(s) don't exist - {0}", string.Join(", ", notExistingCategories)))); } //performance optimization, the check for the existence of the manufacturers in one SQL request var notExistingManufacturers = _manufacturerService.GetNotExistingManufacturers(allManufacturersIds.ToArray()); if (notExistingManufacturers.Any()) { throw new ArgumentException(string.Format("The following manufacturer ID(s) don't exist - {0}", string.Join(", ", notExistingManufacturers))); } //performance optimization, load all products by SKU in one SQL request var allProductsBySku = _productService.GetProductsBySku(allSku.ToArray()); //performance optimization, load all categories IDs for products in one SQL request var allProductsCategoryIds = _categoryService.GetProductCategoryIds(allProductsBySku.Select(p => p.Id).ToArray()); //performance optimization, load all manufacturers IDs for products in one SQL request var allProductsManufacturerIds = _manufacturerService.GetProductManufacturerIds(allProductsBySku.Select(p => p.Id).ToArray()); for (var iRow = 2; iRow < endRow; iRow++) { manager.ReadFromXlsx(worksheet, iRow); var product = allProductsBySku.FirstOrDefault(p => p.Sku == manager.GetProperty("SKU").StringValue); var isNew = product == null; product = product ?? new Product(); if (isNew) { product.CreatedOnUtc = DateTime.UtcNow; } product.ProductTypeId = manager.GetProperty("ProductTypeId").IntValue; product.ParentGroupedProductId = manager.GetProperty("ParentGroupedProductId").IntValue; product.VisibleIndividually = manager.GetProperty("VisibleIndividually").BooleanValue; product.Name = manager.GetProperty("Name").StringValue; product.ShortDescription = manager.GetProperty("ShortDescription").StringValue; product.FullDescription = manager.GetProperty("FullDescription").StringValue; product.VendorId = manager.GetProperty("VendorId").IntValue; product.ProductTemplateId = manager.GetProperty("ProductTemplateId").IntValue; product.ShowOnHomePage = manager.GetProperty("ShowOnHomePage").BooleanValue; product.MetaKeywords = manager.GetProperty("MetaKeywords").StringValue; product.MetaDescription = manager.GetProperty("MetaDescription").StringValue; product.MetaTitle = manager.GetProperty("MetaTitle").StringValue; var seName = manager.GetProperty("SeName").StringValue; product.AllowCustomerReviews = manager.GetProperty("AllowCustomerReviews").BooleanValue; product.Published = manager.GetProperty("Published").BooleanValue; product.Sku = manager.GetProperty("SKU").StringValue; product.ManufacturerPartNumber = manager.GetProperty("ManufacturerPartNumber").StringValue; product.Gtin = manager.GetProperty("Gtin").StringValue; product.IsGiftCard = manager.GetProperty("IsGiftCard").BooleanValue; product.GiftCardTypeId = manager.GetProperty("GiftCardTypeId").IntValue; product.OverriddenGiftCardAmount = manager.GetProperty("OverriddenGiftCardAmount").DecimalValue; product.RequireOtherProducts = manager.GetProperty("RequireOtherProducts").BooleanValue; product.RequiredProductIds = manager.GetProperty("RequiredProductIds").StringValue; product.AutomaticallyAddRequiredProducts = manager.GetProperty("AutomaticallyAddRequiredProducts").BooleanValue; product.IsDownload = manager.GetProperty("IsDownload").BooleanValue; product.DownloadId = manager.GetProperty("DownloadId").IntValue; product.UnlimitedDownloads = manager.GetProperty("UnlimitedDownloads").BooleanValue; product.MaxNumberOfDownloads = manager.GetProperty("MaxNumberOfDownloads").IntValue; product.DownloadActivationTypeId = manager.GetProperty("DownloadActivationTypeId").IntValue; product.HasSampleDownload = manager.GetProperty("HasSampleDownload").BooleanValue; product.SampleDownloadId = manager.GetProperty("SampleDownloadId").IntValue; product.HasUserAgreement = manager.GetProperty("HasUserAgreement").BooleanValue; product.UserAgreementText = manager.GetProperty("UserAgreementText").StringValue; product.IsRecurring = manager.GetProperty("IsRecurring").BooleanValue; product.RecurringCycleLength = manager.GetProperty("RecurringCycleLength").IntValue; product.RecurringCyclePeriodId = manager.GetProperty("RecurringCyclePeriodId").IntValue; product.RecurringTotalCycles = manager.GetProperty("RecurringTotalCycles").IntValue; product.IsRental = manager.GetProperty("IsRental").BooleanValue; product.RentalPriceLength = manager.GetProperty("RentalPriceLength").IntValue; product.RentalPricePeriodId = manager.GetProperty("RentalPricePeriodId").IntValue; product.IsShipEnabled = manager.GetProperty("IsShipEnabled").BooleanValue; product.IsFreeShipping = manager.GetProperty("IsFreeShipping").BooleanValue; product.ShipSeparately = manager.GetProperty("ShipSeparately").BooleanValue; product.AdditionalShippingCharge = manager.GetProperty("AdditionalShippingCharge").DecimalValue; product.DeliveryDateId = manager.GetProperty("DeliveryDateId").IntValue; product.IsTaxExempt = manager.GetProperty("IsTaxExempt").BooleanValue; product.TaxCategoryId = manager.GetProperty("TaxCategoryId").IntValue; product.IsTelecommunicationsOrBroadcastingOrElectronicServices = manager.GetProperty("IsTelecommunicationsOrBroadcastingOrElectronicServices").BooleanValue; product.ManageInventoryMethodId = manager.GetProperty("ManageInventoryMethodId").IntValue; product.UseMultipleWarehouses = manager.GetProperty("UseMultipleWarehouses").BooleanValue; product.WarehouseId = manager.GetProperty("WarehouseId").IntValue; product.StockQuantity = manager.GetProperty("StockQuantity").IntValue; product.DisplayStockAvailability = manager.GetProperty("DisplayStockAvailability").BooleanValue; product.DisplayStockQuantity = manager.GetProperty("DisplayStockQuantity").BooleanValue; product.MinStockQuantity = manager.GetProperty("MinStockQuantity").IntValue; product.LowStockActivityId = manager.GetProperty("LowStockActivityId").IntValue; product.NotifyAdminForQuantityBelow = manager.GetProperty("NotifyAdminForQuantityBelow").IntValue; product.BackorderModeId = manager.GetProperty("BackorderModeId").IntValue; product.AllowBackInStockSubscriptions = manager.GetProperty("AllowBackInStockSubscriptions").BooleanValue; product.OrderMinimumQuantity = manager.GetProperty("OrderMinimumQuantity").IntValue; product.OrderMaximumQuantity = manager.GetProperty("OrderMaximumQuantity").IntValue; product.AllowedQuantities = manager.GetProperty("AllowedQuantities").StringValue; product.AllowAddingOnlyExistingAttributeCombinations = manager.GetProperty("AllowAddingOnlyExistingAttributeCombinations").BooleanValue; product.DisableBuyButton = manager.GetProperty("DisableBuyButton").BooleanValue; product.DisableWishlistButton = manager.GetProperty("DisableWishlistButton").BooleanValue; product.AvailableForPreOrder = manager.GetProperty("AvailableForPreOrder").BooleanValue; product.PreOrderAvailabilityStartDateTimeUtc = manager.GetProperty("PreOrderAvailabilityStartDateTimeUtc").DateTimeNullable; product.CallForPrice = manager.GetProperty("CallForPrice").BooleanValue; product.Price = manager.GetProperty("Price").DecimalValue; product.OldPrice = manager.GetProperty("OldPrice").DecimalValue; product.ProductCost = manager.GetProperty("ProductCost").DecimalValue; product.SpecialPrice = manager.GetProperty("SpecialPrice").DecimalValueNullable; product.SpecialPriceStartDateTimeUtc = manager.GetProperty("SpecialPriceStartDateTimeUtc").DateTimeNullable; product.SpecialPriceEndDateTimeUtc = manager.GetProperty("SpecialPriceEndDateTimeUtc").DateTimeNullable; product.CustomerEntersPrice = manager.GetProperty("CustomerEntersPrice").BooleanValue; product.MinimumCustomerEnteredPrice = manager.GetProperty("MinimumCustomerEnteredPrice").DecimalValue; product.MaximumCustomerEnteredPrice = manager.GetProperty("MaximumCustomerEnteredPrice").DecimalValue; product.BasepriceEnabled = manager.GetProperty("BasepriceEnabled").BooleanValue; product.BasepriceAmount = manager.GetProperty("BasepriceAmount").DecimalValue; product.BasepriceUnitId = manager.GetProperty("BasepriceUnitId").IntValue; product.BasepriceBaseAmount = manager.GetProperty("BasepriceBaseAmount").DecimalValue; product.BasepriceBaseUnitId = manager.GetProperty("BasepriceBaseUnitId").IntValue; product.MarkAsNew = manager.GetProperty("MarkAsNew").BooleanValue; product.MarkAsNewStartDateTimeUtc = manager.GetProperty("MarkAsNewStartDateTimeUtc").DateTimeNullable; product.MarkAsNewEndDateTimeUtc = manager.GetProperty("MarkAsNewEndDateTimeUtc").DateTimeNullable; product.Weight = manager.GetProperty("Weight").DecimalValue; product.Length = manager.GetProperty("Length").DecimalValue; product.Width = manager.GetProperty("Width").DecimalValue; product.Height = manager.GetProperty("Height").DecimalValue; var categoryIds = manager.GetProperty("CategoryIds").StringValue; var manufacturerIds = manager.GetProperty("ManufacturerIds").StringValue; var picture1 = manager.GetProperty("Picture1").StringValue; var picture2 = manager.GetProperty("Picture2").StringValue; var picture3 = manager.GetProperty("Picture3").StringValue; product.UpdatedOnUtc = DateTime.UtcNow; if (isNew) { _productService.InsertProduct(product); } else { _productService.UpdateProduct(product); } //search engine name _urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), 0); //category mappings var categories = isNew || !allProductsCategoryIds.ContainsKey(product.Id) ? new int[0] : allProductsCategoryIds[product.Id]; foreach (var categoryId in categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))) { if (categories.Any(c => c == categoryId)) { continue; } var productCategory = new ProductCategory { ProductId = product.Id, CategoryId = categoryId, IsFeaturedProduct = false, DisplayOrder = 1 }; _categoryService.InsertProductCategory(productCategory); } //manufacturer mappings var manufacturers = isNew || !allProductsManufacturerIds.ContainsKey(product.Id) ? new int[0] : allProductsManufacturerIds[product.Id]; foreach (var manufacturerId in manufacturerIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))) { if (manufacturers.Any(c => c == manufacturerId)) { continue; } var productManufacturer = new ProductManufacturer { ProductId = product.Id, ManufacturerId = manufacturerId, IsFeaturedProduct = false, DisplayOrder = 1 }; _manufacturerService.InsertProductManufacturer(productManufacturer); } //pictures foreach (var picturePath in new[] { picture1, picture2, picture3 }) { if (String.IsNullOrEmpty(picturePath)) { continue; } var mimeType = GetMimeTypeFromFilePath(picturePath); var newPictureBinary = File.ReadAllBytes(picturePath); var pictureAlreadyExists = false; if (!isNew) { //compare with existing product pictures var existingPictures = _pictureService.GetPicturesByProductId(product.Id); foreach (var existingPicture in existingPictures) { var existingBinary = _pictureService.LoadPictureBinary(existingPicture); //picture binary after validation (like in database) var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType); if (!existingBinary.SequenceEqual(validatedPictureBinary) && !existingBinary.SequenceEqual(newPictureBinary)) { continue; } //the same picture content pictureAlreadyExists = true; break; } } if (pictureAlreadyExists) { continue; } var newPicture = _pictureService.InsertPicture(newPictureBinary, mimeType, _pictureService.GetPictureSeName(product.Name)); product.ProductPictures.Add(new ProductPicture { //EF has some weird issue if we set "Picture = newPicture" instead of "PictureId = newPicture.Id" //pictures are duplicated //maybe because entity size is too large PictureId = newPicture.Id, DisplayOrder = 1, }); _productService.UpdateProduct(product); } //update "HasTierPrices" and "HasDiscountsApplied" properties //_productService.UpdateHasTierPricesProperty(product); //_productService.UpdateHasDiscountsApplied(product); } } //Trace.WriteLine(DateTime.Now-start); }
/// <summary> /// Vendor has validated the transactions and sent a list of items for processing. /// </summary> public void FinalizeBuyTransaction(Vendor vendor, List <WorldObject> genericItems, List <WorldObject> uniqueItems, uint cost) { // transaction has been validated by this point var currencyWcid = vendor.AlternateCurrency ?? coinStackWcid; SpendCurrency(currencyWcid, cost, true); vendor.MoneyIncome += (int)cost; foreach (var item in genericItems) { var service = item.GetProperty(PropertyBool.VendorService) ?? false; if (!service) { // errors shouldn't be possible here, since the items were pre-validated, but just in case... if (!TryCreateInInventoryWithNetworking(item)) { log.Error($"[VENDOR] {Name}.FinalizeBuyTransaction({vendor.Name}) - couldn't add {item.Name} ({item.Guid}) to player inventory after validation, this shouldn't happen!"); item.Destroy(); // cleanup for guid manager } vendor.NumItemsSold++; } else { vendor.ApplyService(item, this); } } foreach (var item in uniqueItems) { if (TryCreateInInventoryWithNetworking(item)) { vendor.UniqueItemsForSale.Remove(item.Guid); // this was only for when the unique item was sold to the vendor, // to determine when the item should rot on the vendor. it gets removed now item.SoldTimestamp = null; vendor.NumItemsSold++; } else { log.Error($"[VENDOR] {Name}.FinalizeBuyTransaction({vendor.Name}) - couldn't add {item.Name} ({item.Guid}) to player inventory after validation, this shouldn't happen!"); } } Session.Network.EnqueueSend(new GameMessageSound(Guid, Sound.PickUpItem)); if (PropertyManager.GetBool("player_receive_immediate_save").Item) { RushNextPlayerSave(5); } var altCurrencySpent = vendor.AlternateCurrency != null ? cost : 0; vendor.ApproachVendor(this, VendorType.Buy, altCurrencySpent); }