/// <summary> /// Fills the list provided with the element matching the filter provided /// </summary> /// <param name="retVal">The list to be filled with the element matching the condition expressed in the filter</param> /// <param name="filter">The filter to apply</param> public override void fill(List<Utils.INamable> retVal, Filter.AcceptableChoice filter) { if (filter(Value)) { retVal.Add(Value); } }
public static Task<Get> get(int owner_id, long offset = 0, byte count = 100, Filter filter = Filter.owner) { return Task.Run<Get>(() => { try { //Собираем параметры StringBuilder data = new StringBuilder(); data.Append("&owner_id=" + owner_id); data.Append("&offset=" + offset); data.Append("&filter=" + filter.ToString()); data.Append("&extended=1"); if (count > 0 && count <= 100) data.Append("&count=" + count); //Получаем и возвращаем результаты string json = Regex.Replace(result.get("wall.get", data.ToString(), true), "^{\"response\":{\"wall\":\\[([0-9]+),{\"(.*)}$", "{\"count\":$1,\"wall\":[{\"$2"); return JsonConvert.DeserializeObject<Get>(json); } catch (Newtonsoft.Json.JsonReaderException) { } catch { } //Ошибка return new Get(); }); }
private void cmbCardFilter_SelectedIndexChanged(object sender, EventArgs e) { switch (cmbCardFilter.SelectedIndex) { case 0: //"全部" CardFilter = (x) => { return true; }; break; case 1: //"随从" CardFilter = (x) => { return x.卡牌种类 == CardBasicInfo.资源类型枚举.随从; }; break; case 2: //"法术" CardFilter = (x) => { return x.卡牌种类 == CardBasicInfo.资源类型枚举.法术; }; break; case 3: // "武器" CardFilter = (x) => { return x.卡牌种类 == CardBasicInfo.资源类型枚举.武器; }; break; default: break; } SetCardListView(); }
protected void Page_Load(object sender, EventArgs e) { this.Form.Attributes["data-form"] = "filter"; // this.Form.Attributes["class"] = "form-filter"; this.Form.Attributes["novalidate"] = "1"; this.Form.Attributes["onsubmit"] = ""; this.Form.Action = "./Search"; f = GetFilter(); DataSet d = GetUsers(1, f.ToString(), out sql); UserList.DataSource = d; filterjson = d.Tables[1].Rows[0]["json"].ToString(); UserList.DataBind(); warning.Visible = d.Tables[0].Rows.Count == 0 && !f.IsDefault(true); /* sort.Value = f.orderby.ToString(); sort.ClientIDMode = System.Web.UI.ClientIDMode.Static; sort.Attributes["name"] = sort.ID; distance.Value = f.distancemax.ToString(); distance.ClientIDMode = System.Web.UI.ClientIDMode.Static; distance.Attributes["name"] = distance.ID; photos.Value = f.withphotos ? "true" : "false"; photos.ClientIDMode = System.Web.UI.ClientIDMode.Static; */ }
public FilterStorage(string path) { string[] pathes = System.IO.Directory.GetFiles(path, "*.dll"); Filter f; int i = 0, j = 0; foreach (string _path in pathes) { Assembly assembly = Assembly.LoadFrom(_path); Type[] types = assembly.GetTypes(); foreach (Type type in types) { try { f = new Filter(System.IO.Path.GetFileNameWithoutExtension(_path), type); filters.Add(f); for (int k = 0; k < f.Count; k++) { description.Add("#" + j.ToString() + ": " + f.name + "." + k); coords.Add(new coord(i, j, k)); } j++; } catch (TypeLoadException ex) { Exception e = new Exception("В типе " + type.Name + " возникли ошибки:\n" + ex.Message); Warning(e); } } } this.directory = path; loaded = true; }
public ImageFigure(Image Image, Rectangle Source, Rectangle Destination, Filter Filter) { this.Image = Image; this.Source = Source; this.Destination = Destination; this.Filter = Filter; }
internal Filter ToFilter() { Filter f = new Filter(); f.Val = this.Val; return f; }
public void GetFiltersSortsFiltersByOrderFirstThenScope() { // Arrange var context = new ControllerContext(); var descriptor = new Mock<ActionDescriptor>().Object; var actionFilter = new Filter(new Object(), FilterScope.Action, null); var controllerFilter = new Filter(new Object(), FilterScope.Controller, null); var globalFilter = new Filter(new Object(), FilterScope.Global, null); var earlyActionFilter = new Filter(new Object(), FilterScope.Action, -100); var lateGlobalFilter = new Filter(new Object(), FilterScope.Global, 100); var provider = new Mock<IFilterProvider>(MockBehavior.Strict); var collection = new FilterProviderCollection(new[] { provider.Object }); provider.Setup(p => p.GetFilters(context, descriptor)) .Returns(new[] { actionFilter, controllerFilter, globalFilter, earlyActionFilter, lateGlobalFilter }); // Act Filter[] result = collection.GetFilters(context, descriptor).ToArray(); // Assert Assert.Equal(5, result.Length); Assert.Same(earlyActionFilter, result[0]); Assert.Same(globalFilter, result[1]); Assert.Same(controllerFilter, result[2]); Assert.Same(actionFilter, result[3]); Assert.Same(lateGlobalFilter, result[4]); }
public XmlElement GetItemElement(XmlDocument doc, BaseItem item, string deviceId, Filter filter, StreamInfo streamInfo = null) { var element = doc.CreateElement(string.Empty, "item", NS_DIDL); element.SetAttribute("restricted", "1"); element.SetAttribute("id", item.Id.ToString("N")); if (item.Parent != null) { element.SetAttribute("parentID", item.Parent.Id.ToString("N")); } //AddBookmarkInfo(item, user, element); AddGeneralProperties(item, element, filter); // refID? // storeAttribute(itemNode, object, ClassProperties.REF_ID, false); var audio = item as Audio; if (audio != null) { AddAudioResource(element, audio, deviceId, filter, streamInfo); } var video = item as Video; if (video != null) { AddVideoResource(element, video, deviceId, filter, streamInfo); } AddCover(item, element); return element; }
/// <summary> /// Factory function for filtering a <see cref="CsvModel"/>. /// </summary> /// <param name="data">The data to be filtered</param> /// <param name="filterCollection">The filter collection to be applied</param> /// <param name="method">The filter method</param> /// <returns>The filtered data</returns> public static CsvModel filter( CsvModel data, Filter.FilterCollection filterCollection, Filter.FilterMethod method ) { CsvModel model = new CsvModel(data.SupportedValues); // set limits of the activitylevel calculator of the new model model.ActivityLevelCalculator.MinVeryheavy = data.ActivityLevelCalculator.MinVeryheavy; model.ActivityLevelCalculator.MinHeavy = data.ActivityLevelCalculator.MinHeavy; model.ActivityLevelCalculator.MinModerate = data.ActivityLevelCalculator.MinModerate; model.ActivityLevelCalculator.MinLight = data.ActivityLevelCalculator.MinLight; model.ActivityLevelCalculator.MinSedantary = data.ActivityLevelCalculator.MinSedantary; // set filename and supported values model.AbsoluteFileName = data.AbsoluteFileName; model.SupportedValues = data.SupportedValues; // do the filtering //filterCollection.filter(data, model, method); // finish model model.finishParsing(); return model; }
public Word GetWordByNameCategoryAndWordPackID(string Name, int CategoryID, int WordPackID) { Filter[] Filters = new Filter[] { new Filter(FilterType.And, new Field[] { NameField, CategoryIDField, WordPackIDField }, new string[] { "Name", "CategoryID", "WordPackID" }, new object[] { Name, CategoryID, WordPackID }) }; var Words = GetObjectsByFilters(Filters); Word word = Words.Cast<Word>().ToList().FirstOrDefault(); if (word == null) { word = new Word(0, Name, CategoryID, WordPackID); } return word; }
public Filter UpdateFilter(Filter filter, string dataSourceId) { var flt = Mapper.Map<Filter, DynamoDb.Filter>(filter); flt.DataSourceId = dataSourceId; this.Context.Save(flt); return filter; }
public override Control GetFilter(BXCustomField field) { var filter = new Filter(); filter.Key = "@" + field.OwnerEntityId + ":" + field.Name; filter.IBlockId = field.Settings.GetInt("IBlockId"); return filter; }
public FiltersModule() { Get["/Filters"] = parameters => { FiltersModel model = new FiltersModel(); model.Filters.Add(new Filter(1, "test filter 1", true, 1, 1, 1, 0)); model.Filters.Add(new Filter(2, "filter 2", true, 1, 5, 1, 1)); model.Filters.Add(new Filter(2, "filter 3", false, 1, 5, 1, 1)); model.Filters.Add(new Filter(2, "filter 4", true, 1, 5, 1, 1)); model.Filters.Add(new Filter(2, "filter 5", false, 1, 5, 1, 1)); return View["Index", model]; }; Get["/Filters/Edit"] = parameters => { EditFilterModel model = new EditFilterModel(); Filter filter = new Filter(1, "filter 1", true, 0, 0, 0, 0); filter.Codecs.Add("XViD"); model.Filter = filter; return View["EditFilter", model]; }; Post["/Filters/Delete"] = parameters => { return true; }; }
public IEnumerable<HistoryItem> Build(WorkflowObject workflowObject, Filter actEntryFilter) { var clarifyDataSet = _session.CreateDataSet(); var workflowObjectInfo = WorkflowObjectInfo.GetObjectInfo(workflowObject.Type); var workflowGeneric = clarifyDataSet.CreateGenericWithFields(workflowObjectInfo.ObjectName); workflowGeneric.AppendFilter(workflowObjectInfo.IDFieldName, StringOps.Equals, workflowObject.Id); var inverseActivityRelation = workflowObjectInfo.ActivityRelation; var activityRelation = _schemaCache.GetRelation("act_entry", inverseActivityRelation).InverseRelation; var actEntryGeneric = workflowGeneric.Traverse(activityRelation.Name); actEntryGeneric.AppendSort("entry_time", false); if (actEntryFilter != null) { actEntryGeneric.Filter.AddFilter(actEntryFilter); } var templateDictionary = _templatePolicyConfiguration.RenderPolicies(workflowObject); //query generic hierarchy and while using act entry templates transform the results into HistoryItems var assembler = _container.With(templateDictionary).With(workflowObject).GetInstance<HistoryItemAssembler>(); return assembler.Assemble(actEntryGeneric); }
internal static void getAdvanceFilterResult(string SelectedValue, Filter filter, ref List<Listing> output) { switch (filter) { case Filter.Type: getbyFilterType(SelectedValue, ref output); break; case Filter.Status: getbyFilterStatus(SelectedValue, ref output); break; case Filter.SAP: getbyFilterSAPStatus(SelectedValue, ref output); break; case Filter.Title: int SelectedID = Convert.ToInt32(SelectedValue); getbyFilterTitle(SelectedID, ref output); break; case Filter.NotDefined: getbyFilterWorkflow(SelectedValue, ref output); break; case Filter.Supervisors: getByFilterSupervisor(SelectedValue, ref output); break; } }
public MemoryRecord(string _group, double _rxfreq, string _name, DSPMode _dsp_mode, bool _scan, string _tune_step, FMTXMode _repeater_mode, double _fm_tx_offset_mhz, bool _ctcss_on, double _ctcss_freq, int _power, int _deviation, bool _split, double _txfreq, Filter _filter, int _filterlow, int _filterhigh, string _comments, AGCMode _agc_mode, int _agc_thresh) { group = _group; rx_freq = _rxfreq; name = _name; dsp_mode = _dsp_mode; scan = _scan; tune_step = _tune_step; repeater_mode = _repeater_mode; rptr_offset = _fm_tx_offset_mhz; ctcss_on = _ctcss_on; ctcss_freq = _ctcss_freq; power = _power; deviation = _deviation; split = _split; tx_freq = _txfreq; rx_filter = _filter; rx_filter_low = _filterlow; rx_filter_high = _filterhigh; comments = _comments; agc_mode = _agc_mode; agct = _agc_thresh; }
public void ShouldDeserializeComplexWorkflowConfiguration3() { var workFlow = new Workflow(); workFlow.Configuration = "{\"default_filter\":{\"queue\":\"WQccc\"},\"filters\":[{\"expression\":\"1==1\",\"friendly_name\":\"Prioritizing Filter\",\"targets\":[{\"priority\":\"1\",\"queue\":\"WQccc\",\"timeout\":\"300\"}]}]}"; var workFlowConfiguration = new WorkflowConfiguration(); var filter = new Filter { FriendlyName = "Prioritizing Filter", Expression = "1==1", Targets = new List<Target>() { new Target { Queue="WQccc", Priority="1", Timeout="300" } } }; workFlowConfiguration.Filters.Add(filter); workFlowConfiguration.DefaultFilter = new Target() { Queue = "WQccc" }; var config = workFlow.WorkflowConfiguration; Assert.AreEqual(workFlowConfiguration.ToString(), config.ToString()); }
/// <summary> /// Initializes a new instance of the <see cref="Exclusions"/> class. /// </summary> public Exclusions() { TableFilter = new Filter(); ViewFilter = new Filter(); StoredProcedureFilter = new Filter(); PackageFilter = new Filter(); }
static List<int> Filtered(int[] array1, Filter filter1, Filter filter2) { List<int> filtered1 = new List<int>(); foreach (var item in array1) { if (filter1(item)) { filtered1.Add(item); } } List<int> filtered2 = new List<int>(); foreach (var item in array1) { if (filter2(item)) { filtered2.Add(item); } } List<int> filtered = new List<int>(); var array3 = filtered1.ToArray(); var array2 = filtered2.ToArray(); for (int i = 0; i < array3.Length; i++) { filtered.Add(array3[i] * array2[i]); } return filtered; }
public PackageLoaderOption( Filter filter, bool includePrerelease) { Filter = filter; IncludePrerelease = includePrerelease; }
public MipArgs( OpsParsedStatement statement) { OpsParsedArgument srcArg = statement.FindArgument("Start"); if( srcArg != null ) Start = int.Parse( srcArg.Value ); OpsParsedArgument filterArg = statement.FindArgument("Filter"); if( filterArg != null ) { if(0==string.Compare(filterArg.Value, "None", true) ) Filter |= Filter.None; else if(0==string.Compare(filterArg.Value, "Point", true) ) Filter |= Filter.Point; else if(0==string.Compare(filterArg.Value, "Linear", true) ) Filter |= Filter.Linear; else if(0==string.Compare(filterArg.Value, "Triangle", true) ) Filter |= Filter.Triangle; else if(0==string.Compare(filterArg.Value, "Box", true) ) Filter |= Filter.Box; else throw new OpsException("Filter Argument is invalid"); } else Filter |= Filter.Box; OpsParsedArgument ditherArg = statement.FindArgument("Dither"); if( ditherArg != null ) { if(0!=int.Parse(ditherArg.Value) ) Filter |= Filter.Dither; } }
/// <summary> /// Create <see cref="RangeFacetCounts"/> </summary> protected internal RangeFacetCounts(string field, Range[] ranges, Filter fastMatchFilter) { this.field = field; this.ranges = ranges; this.fastMatchFilter = fastMatchFilter; counts = new int[ranges.Length]; }
/// <summary> /// Fills the list provided with the element matching the filter provided /// </summary> /// <param name="retVal">The list to be filled with the element matching the condition expressed in the filter</param> /// <param name="filter">The filter to apply</param> public override void fill(List<Utils.INamable> retVal, Filter.AcceptableChoice filter) { foreach (Expression expr in ListElements) { expr.fill(retVal, filter); } }
public override IDictionary<long, Dictionary<string, string>> Export(IList<Trade> inTrades, Filter inFilter, Stream stream, Market market, IList<Exception> exceps) { var task = _task; var filter = task.Filter; var date = market.Date(_effectiveTime); var trades = Env.Current.Trade.GetTrades2(filter, date, _effectiveTime); using (var writer = new StreamWriter(stream)) { WriteHeader(writer); foreach (var trade in trades) { if (trade.Product == null) { exceps.Add(new ApplicationException(String.Format("Trade {0} is invalid. Missing product.", trade.Id))); continue; } if(trade.TradeTime > _effectiveTime) { continue; } string line = WriteTrade(trade, date, _effectiveTime, exceps); if (!Utilities.IsNullOrEmpty(line)) { writer.WriteLine(line); } } } return null; }
public ManyToManyRelationship(string name, bool isUserDefined, OneToManyRelationship primaryRelationship, ManyToOneRelationship foreignRelationship, Filter filter) : base(name, isUserDefined, primaryRelationship.Parent, primaryRelationship.Parent, primaryRelationship.PrimaryColumns, foreignRelationship.ForeignRelationship.Parent, foreignRelationship.ForeignRelationship.PrimaryColumns, filter) { _intermediatePrimaryRelationship = primaryRelationship; _intermediateForeignRelationship = foreignRelationship; ResetDefaults(); }
public static Continuation LastModified(this ICacheSteps _, Filter<DateTime> lastModifiedFilter) { return step => ctx => { DateTime lastModified, d; var ifModifiedHeader = ctx.Request.Headers["If-Modified-Since"]; // if a valid date has been given as a validator if (!string.IsNullOrEmpty(ifModifiedHeader) && DateTime.TryParseExact(ifModifiedHeader, "R", CultureInfo.CurrentCulture, DateTimeStyles.RoundtripKind, out d)) { // run the filter and check the modified date, lastModified = lastModifiedFilter(ctx, d); // automatically returning 304 Not Modified if date indicates not modified if (roughCompare(lastModified.ToUniversalTime(), d.ToUniversalTime()) <= 0) step = fu.Compose( fu.Http.Header("Last-Modified", lastModified.ToString("R")), fu.Http.NotModified()) (fu.EndAct); } else { lastModified = lastModifiedFilter(ctx, DateTime.MinValue); } fu.Http.Header("Last-Modified", lastModified.ToString("R")) (step)(ctx); }; }
public ChannelParams(AnalogInChannelsEnum channelName, Filter channelFilter, ProgrammableGainAmplifier channelPGA, AnalogInLatch channelLatch) { _channelName = channelName; ChannelFilter = channelFilter; ChannelPGA = channelPGA; CommonLatch = channelLatch; }
private JObject GetCompanies(int rows, int page, string sidx, string sord, Filter filters) { IQueryable<Company> items = Companies.SortBy(filters, sidx, sord); int totalItems = items.Count(); //in a real app Count should probably be retrieved asynchronously //int totalItems = await items.CountAsync(); int totalPages = totalItems / rows; if (totalItems % rows > 0) { totalPages++; } items = items.Skip((page - 1) * rows).Take(rows); List<Company> listOfItems = items.ToList(); //List<Company> listOfItems = await items.ToListAsync(); dynamic result = new JObject(); result.total = totalPages; result.records = totalItems; result.page = page; result.rows = new JArray(listOfItems.Select(c => { dynamic o = new JObject(); o.id = c.CompanyID; o.cell = new JArray(c.CompanyID, c.Name, c.Address); return o; }).ToArray()); return result; }
public Logik() { Database = new DatabaseAdgang(); DAQdata = new IndhentDAQData(); NulpunktObjekt = new Nulpunktsjustering(); KalibreringObjekt = new Kalibrering(); FilterObj = new Filter(); AnalyseKlasse = new Analyse(); updateUI = new Thread(() => updateListe()); UILISTE = new List<double>(); observers = new List<IObserver>(); FiltreretListe = new List<double>(); databasetal = new List<double>(); minKø = new Queue<double>(100); beregnetNværdi = 0.0; counter = 0; kalibreringKoef = KalibreringObjekt.Kalibrer(); DAQdata.Attach(this); for (int i = 0; i < 299; i++) { UILISTE.Add(0); } }
/// <summary> /// Applies data processing (paging, sorting, filtering and aggregates) over IQueryable using Dynamic Linq. /// </summary> /// <typeparam name="T">The type of the IQueryable.</typeparam> /// <param name="queryable">The IQueryable which should be processed.</param> /// <param name="take">Specifies how many items to take. Configurable via the pageSize setting of the Kendo DataSource.</param> /// <param name="skip">Specifies how many items to skip.</param> /// <param name="sort">Specifies the current sort order.</param> /// <param name="filter">Specifies the current filter.</param> /// <param name="aggregates">Specifies the current aggregates.</param> /// <returns>A DataSourceResult object populated from the processed IQueryable.</returns> public static DataSourceResult <T> ToDataSourceResult <T>(this IQueryable <T> queryable, int take, int skip, ICollection <Sort> sort, Filter filter, ICollection <Aggregator> aggregates) { // Filter the data first queryable = queryable.Filter(filter); // Calculate the total number of records (needed for paging) var total = queryable.Count(); // Calculate the aggregates var aggregate = queryable.Aggregate(aggregates); // Sort the data queryable = queryable.Sort(sort); // Finally page the data if (take > 0) { queryable = queryable.Page(take, skip); } return(new DataSourceResult <T> { Data = queryable.ToList(), Total = total, Aggregates = aggregate }); }
public virtual IQueryable ApplyTo(IQueryable query, ODataQuerySettings querySettings) { if (query == null) { throw Error.ArgumentNull("query"); } if (querySettings == null) { throw Error.ArgumentNull("querySettings"); } IQueryable result = query; // First apply $apply // Section 3.15 of the spec http://docs.oasis-open.org/odata/odata-data-aggregation-ext/v4.0/cs01/odata-data-aggregation-ext-v4.0-cs01.html#_Toc378326311 if (IsAvailableODataQueryOption(Apply, AllowedQueryOptions.Apply)) { result = Apply.ApplyTo(result, querySettings); InternalRequest.Context.ApplyClause = Apply.ApplyClause; this.Context.ElementClrType = Apply.ResultClrType; } // Construct the actual query and apply them in the following order: filter, orderby, skip, top if (IsAvailableODataQueryOption(Filter, AllowedQueryOptions.Filter)) { result = Filter.ApplyTo(result, querySettings); } if (IsAvailableODataQueryOption(Count, AllowedQueryOptions.Count)) { if (InternalRequest.Context.TotalCountFunc == null) { Func <long> countFunc = Count.GetEntityCountFunc(result); if (countFunc != null) { InternalRequest.Context.TotalCountFunc = countFunc; } } if (InternalRequest.IsCountRequest()) { return(result); } } OrderByQueryOption orderBy = OrderBy; // $skip or $top require a stable sort for predictable results. // Result limits require a stable sort to be able to generate a next page link. // If either is present in the query and we have permission, // generate an $orderby that will produce a stable sort. if (querySettings.EnsureStableOrdering && (IsAvailableODataQueryOption(Skip, AllowedQueryOptions.Skip) || IsAvailableODataQueryOption(Top, AllowedQueryOptions.Top) || querySettings.PageSize.HasValue)) { // If there is no OrderBy present, we manufacture a default. // If an OrderBy is already present, we add any missing // properties necessary to make a stable sort. // Instead of failing early here if we cannot generate the OrderBy, // let the IQueryable backend fail (if it has to). orderBy = GenerateStableOrder(); } if (IsAvailableODataQueryOption(orderBy, AllowedQueryOptions.OrderBy)) { result = orderBy.ApplyTo(result, querySettings); } if (IsAvailableODataQueryOption(SkipToken, AllowedQueryOptions.SkipToken)) { result = SkipToken.ApplyTo(result, querySettings, this); } AddAutoSelectExpandProperties(); if (SelectExpand != null) { var tempResult = ApplySelectExpand(result, querySettings); if (tempResult != default(IQueryable)) { result = tempResult; } } if (IsAvailableODataQueryOption(Skip, AllowedQueryOptions.Skip)) { result = Skip.ApplyTo(result, querySettings); } if (IsAvailableODataQueryOption(Top, AllowedQueryOptions.Top)) { result = Top.ApplyTo(result, querySettings); } result = ApplyPaging(result, querySettings); return(result); }
public void CreateSubscription(SubscriptionDescription description, Filter filter) { _namespaceManager.CreateSubscription(description, filter); }
public async Task <BeerServiceResponse> GetWithFilter([FromBody] Filter filter) { return(await _getBeers.Value.Execute(filter)); }
/// <summary> /// Gets devices by DeviceGroup Id /// </summary> /// <param name="deviceGroupId"></param> /// <param name="filter">The filter</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns></returns> public async Task <List <Device> > GetDevicesByDeviceGroupIdAsync(int deviceGroupId, Filter <Device> filter, CancellationToken cancellationToken = default) => await GetAllAsync(filter, $"device/groups/{deviceGroupId}/devices", cancellationToken).ConfigureAwait(false);
public FilterChannelBuilder(ChannelBuilder <TChannel> builder, Filter <TChannel> filter) { _builder = builder; _filter = filter; }
Filter ISystemFilter.CreateFilter() { return(Filter.Create("Filter-BuildPathSystem") .With <CalculatePath>() .Push()); }
internal static extern void cairo_pattern_set_filter(IntPtr pattern, Filter filter);
/// <summary> /// Gets all device instances matching the provided filter /// </summary> /// <param name="deviceId">The device id</param> /// <param name="filter">The optional filter</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns></returns> public Task <List <DeviceDataSourceInstance> > GetAllDeviceInstances(int deviceId, Filter <DeviceDataSourceInstance> filter, CancellationToken cancellationToken) => GetAllInternalAsync <DeviceDataSourceInstance>(filter, $"device/devices/{deviceId}/instances", cancellationToken);
/// <summary> /// Get devices by associated datasource /// </summary> /// <param name="dataSourceId">The DataSource Id</param> /// <param name="filter">The filter</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns></returns> public Task <Page <DeviceWithDataSourceInstanceInformation> > GetDevicesAndInstancesAssociatedWithDataSourceByIdPageAsync(int dataSourceId, Filter <DeviceWithDataSourceInstanceInformation> filter, CancellationToken cancellationToken = default) => GetBySubUrlAsync <Page <DeviceWithDataSourceInstanceInformation> >($"setting/datasources/{dataSourceId}/devices?{filter}", cancellationToken);
public void Empty() { this.cFilter = null; this.cPowder = null; }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { IGH_Goo goo = null; Image image = new Image(); if (!DA.GetData(0, ref goo)) { return; } if (!goo.TryGetImage(ref image)) { return; } int mode = 0; DA.GetData(1, ref mode); IGH_Goo gooA = null; Bitmap overlay = new Bitmap(100, 100); if (DA.GetData(2, ref gooA)) { if (goo.TryGetBitmap(ref overlay)) { ; } } double numVal = 1.0; DA.GetData(3, ref numVal); Filter filter = new Filter(); switch ((FilterModes)mode) { case FilterModes.Add: filter = new Add(overlay); image.Filters.Add(new Add(overlay)); break; case FilterModes.Subtract: filter = new Subtract(overlay); image.Filters.Add(new Subtract(overlay)); break; case FilterModes.Multiply: filter = new Multiply(overlay); image.Filters.Add(new Multiply(overlay)); break; case FilterModes.Divide: filter = new Divide(overlay); image.Filters.Add(new Divide(overlay)); break; case FilterModes.Euclidean: filter = new Euclidean(overlay, (int)numVal); image.Filters.Add(new Euclidean(overlay, (int)numVal)); break; case FilterModes.FlatField: filter = new FlatField(overlay); image.Filters.Add(new FlatField(overlay)); break; case FilterModes.Intersect: filter = new Intersect(overlay); image.Filters.Add(new Intersect(overlay)); break; case FilterModes.Merge: filter = new Merge(overlay); image.Filters.Add(new Merge(overlay)); break; case FilterModes.Morph: filter = new Morph(overlay, numVal); image.Filters.Add(new Morph(overlay, numVal)); break; case FilterModes.MoveTowards: filter = new MoveTowards(overlay, (int)numVal); image.Filters.Add(new MoveTowards(overlay, (int)numVal)); break; case FilterModes.Simple: filter = new Simple(overlay, (int)numVal); image.Filters.Add(new Simple(overlay, (int)numVal)); break; } message = ((FilterModes)mode).ToString(); UpdateMessage(); DA.SetData(0, image); DA.SetData(1, filter); }
public void Reset() { SearchTerm = null; CurrentFilter = FilterLoader.Instance.DefaultFilters[0]; }
public void Fill() { this.cPowder.Amount = 100; this.cFilter = new Filter(); }
private ILogEntryFilter CreateFilter(QuickFilters configurationQuickFilters) { return(Filter.Create(configurationQuickFilters.Select(x => x.CreateFilter()))); }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (Loading == null) { Loading = true; } var vmQualifiedName = Vm.Model.GetType().AssemblyQualifiedName; vmQualifiedName = vmQualifiedName.Substring(0, vmQualifiedName.LastIndexOf(", Version=", StringComparison.CurrentCulture)); var tempGridTitleId = Guid.NewGuid().ToNoSplitString(); output.TagName = "table"; output.Attributes.Add("id", Id); output.Attributes.Add("lay-filter", Id); output.TagMode = TagMode.StartTagAndEndTag; if (Limit == null) { Limit = GlobalServices.GetRequiredService <Configs>()?.UiOptions.DataTable.RPP; } if (Limits == null) { Limits = new int[] { 10, 20, 50, 80, 100, 150, 200 }; if (!Limits.Contains(Limit.Value)) { var list = Limits.ToList(); list.Add(Limit.Value); Limits = list.OrderBy(x => x).ToArray(); } } if (UseLocalData) // 不需要分页 { ListVM.NeedPage = false; } else if (string.IsNullOrEmpty(Url)) { Url = "/_Framework/GetPagingData"; if (Filter == null) { Filter = new Dictionary <string, object>(); } Filter.Add("_DONOT_USE_VMNAME", vmQualifiedName); Filter.Add("_DONOT_USE_CS", ListVM.CurrentCS); Filter.Add("SearcherMode", ListVM.SearcherMode); if (ListVM.Ids != null && ListVM.Ids.Count > 0) { Filter.Add("Ids", ListVM.Ids); } // 为首次加载添加Searcher查询参数 if (ListVM.Searcher != null) { var props = ListVM.Searcher.GetType().GetProperties(); props = props.Where(x => !_excludeTypes.Contains(x.PropertyType)).ToArray(); foreach (var prop in props) { if (!_excludeParams.Contains(prop.Name)) { Filter.Add($"Searcher.{prop.Name}", prop.GetValue(ListVM.Searcher)); } } } } // 是否需要分页 var page = ListVM.NeedPage; #region 生成 Layui 所需的表头 var rawCols = ListVM?.GetHeaders(); var maxDepth = (ListVM?.ChildrenDepth) ?? 1; var layuiCols = new List <List <LayuiColumn> >(); var tempCols = new List <LayuiColumn>(); layuiCols.Add(tempCols); // 添加复选框 if (!HiddenCheckbox) { var checkboxHeader = new LayuiColumn() { Type = LayuiColumnTypeEnum.Checkbox, LAY_CHECKED = CheckedAll, Rowspan = maxDepth, Fixed = GridColumnFixedEnum.Left, Width = 45 }; tempCols.Add(checkboxHeader); } // 添加序号列 if (!HiddenGridIndex) { var gridIndex = new LayuiColumn() { Type = LayuiColumnTypeEnum.Numbers, Rowspan = maxDepth, Fixed = GridColumnFixedEnum.Left, Width = 45 }; tempCols.Add(gridIndex); } var nextCols = new List <IGridColumn <TopBasePoco> >();// 下一级列头 generateColHeader(rawCols, nextCols, tempCols, maxDepth); if (nextCols.Count > 0) { CalcChildCol(layuiCols, nextCols, maxDepth, 1); } if (layuiCols.Count > 0 && layuiCols[0].Count > 0) { layuiCols[0][0].TotalRowText = ListVM?.TotalText; } #endregion #region 处理 DataTable 操作按钮 var actionCol = ListVM?.GridActions; var rowBtnStrBuilder = new StringBuilder(); // Grid 行内按钮 var toolBarBtnStrBuilder = new StringBuilder(); // Grid 工具条按钮 var gridBtnEventStrBuilder = new StringBuilder(); // Grid 按钮事件 if (actionCol != null && actionCol.Count > 0) { var vm = Vm.Model as BaseVM; foreach (var item in actionCol) { AddSubButton(vmQualifiedName, rowBtnStrBuilder, toolBarBtnStrBuilder, gridBtnEventStrBuilder, vm, item); } } #endregion #region DataTable var vmName = string.Empty; if (VMType != null) { var vmQualifiedName1 = VMType.AssemblyQualifiedName; vmName = vmQualifiedName1.Substring(0, vmQualifiedName1.LastIndexOf(", Version=", StringComparison.CurrentCulture)); } output.PostElement.AppendHtml($@" <script> var {Id}option = null; /* 监听工具条 */ function wtToolBarFunc_{Id}(obj){{ //注:tool是工具条事件名,test是table原始容器的属性 lay-filter=""对应的值"" var data = obj.data, layEvent = obj.event, tr = obj.tr; //获得当前行 tr 的DOM对象 {(gridBtnEventStrBuilder.Length == 0 ? string.Empty : $@"switch(layEvent){{{gridBtnEventStrBuilder}default:break;}}")} return; }} layui.use(['table'], function(){{ var table = layui.table; {Id}option = {{ elem: '#{Id}' ,id: '{Id}' {(!NeedShowTotal ? string.Empty : ",totalRow:true")} {(string.IsNullOrEmpty(Url) ? string.Empty : $",url: '{Url}'")} {(Filter == null || Filter.Count == 0 ? string.Empty : $",where: {JsonConvert.SerializeObject(Filter)}")} {(Method == null ? ",method:'post'" : $",method: '{Method.Value.ToString().ToLower()}'")} {(Loading ?? true ? string.Empty : ",loading:false")} {(page ? string.Empty : ",page:{layout:['count']}")} {(page ? string.Empty : $",limit:{(UseLocalData ? ListVM.GetEntityList().Count().ToString() : "0")}")} {(page ? (Limits == null || Limits.Length == 0 ? string.Empty : $",limits:[{string.Join(',', Limits)}]" ) : string.Empty)} {(!Width.HasValue ? string.Empty : $",width: {Width.Value}")} {(!Height.HasValue ? string.Empty : (Height.Value >= 0 ? $",height: {Height.Value}" : $",height: 'full{Height.Value}'"))} ,cols:{JsonConvert.SerializeObject(layuiCols, _jsonSerializerSettings)} {(!Skin.HasValue ? string.Empty : $",skin: '{Skin.Value.ToString().ToLower()}'")} {(Even.HasValue && !Even.Value ? $",even: false" : string.Empty)} {(!Size.HasValue ? string.Empty : $",size: '{Size.Value.ToString().ToLower()}'")} ,done: function(res,curr,count){{ var tab = $('#{Id} + .layui-table-view');tab.find('table').css('border-collapse','separate'); {(Height == null ? $"tab.css('overflow','hidden').addClass('donotuse_fill donotuse_pdiv');tab.children('.layui-table-box').addClass('donotuse_fill donotuse_pdiv').css('height','100px');tab.find('.layui-table-main').addClass('donotuse_fill');tab.find('.layui-table-header').css('min-height','40px');ff.triggerResize();" : string.Empty)} {(MultiLine == true ? $"tab.find('.layui-table-cell').css('height','auto').css('white-space','normal');" : string.Empty)} {(string.IsNullOrEmpty(DoneFunc) ? string.Empty : $"{DoneFunc}(res,curr,count)")}
public Items() { this.InitializeComponent(); //start displaying the items records Query q = new Query(); q.GetExtra("SELECT item_name,item_cost,quantity_left,quantity_consumed,date_time,_added_by FROM items"); q.Records(); int items_row = q.CountRows(); Query item_id = new Query(); item_id.Get("items"); item_id.Records(); //AMOUNT OF COLUMN DEFINITIONS int col_num = Convert.ToInt32(items_r.ColumnDefinitions.Count); Filter f = new Filter(); // RowDefinition[] rd = new RowDefinition[q.CountRows()]; // RowDefinition rd; bool check_records = q.CheckRecords(); //STACKPANEL TO HOLD THE ROWS // StackPanel parent_row_panel; //WE'RE ADDING +1 CAUSE THERE'S ALREADY A ROW DEFINED WHICH IT'S VALUE WOULD BE ZERO //SO IF WE DONT INCREMENT IT, IT STARTS WITH 0, WHICH MIGHT BE A BAD IDEA :(. //int i = 0; //now check the number of rows //keep adding rows as long as it doesn't exceed the row limit from the stupid database. int i = 0; if (check_records) { for (i = 0; i < (items_row); i++) { RowDefinition rd = new RowDefinition(); //rd.Height = new GridLength(50); items_r.RowDefinitions.Add(rd); /* * COLUMN DEFINITION * CREATE COLUMNS ACCORDING TO THE PARENT COLUMN OF THE FIRST ROW, WHICH IS col_num. */ ////////////////////////////////// int k = 0; for (k = 0; k < col_num; k++) { ColumnDefinition cd = new ColumnDefinition(); //cd.Width = new GridLength(); //cd.MinWidth = 150; items_r.ColumnDefinitions.Add(cd); //reset column def so that when it starts looping the for again, it creates a new set of column definition //column_def = 0; ////////////////////////////////////////////////////////// Border border = new Border(); TextBlock n = new TextBlock(); n.FontSize = 17.3; n.Foreground = new SolidColorBrush(Color.FromArgb(180, 0, 0, 0)); /////////////////////////////////////// //stackpanel StackPanel pa = new StackPanel(); // pa.Style = new Style(); //StackPanel m_pa = new StackPanel(); // m_pa.Name = "p";// + i.ToString(); StackPanel row_holder = new StackPanel(); //row_holder.Orientation = new Orientation(); // Orientation orie = row_holder1.Orientation; //add //pa. pa.Children.Add(n); pa.Margin = new Thickness(10); //pa.MaxWidth = 115; pa.HorizontalAlignment = HorizontalAlignment.Center; //border.Style = new Windows.UI.Xaml.Style(); //border.Style.TargetType = typeof(Border); border.BorderThickness = new Thickness(0, 0, 0, 1); border.BorderBrush = new SolidColorBrush(Color.FromArgb(50, 0, 0, 0)); //calculate odd and even ish int calc = i % 2; //border.MaxWidth = 115; // border.MinHeight = 61; border.Child = pa; row_holder.Children.Add(border); int calcu = col_num - k; //CHECK WHAT TO INPUT if (calcu == 1) {//LAST VALUE } else if (k == 2 || k == 3) { if (q.Results[i, k] == "0") { n.Text = "None"; } else { n.Text = f.Numbers(Convert.ToInt32(q.Results[i, k])); } } else if (k == 4) { n.Text = f.Date(q.Results[i, k], "dd/MM/yyyy"); } else if (calcu == 2) {//second to the last value, add added by Query inner_q = new Query(); inner_q.Get("staffs", "WHERE staff_id ='" + q.Results[i, 5] + "'"); if (inner_q.CheckRecords() == true) { inner_q.Record(); string person = ""; if ((App.Current as App).User_token.ToString() == inner_q.Result[0]) { person = "You"; } else { person = inner_q.Result[1]; } n.Text = person; } else { n.Text = "Not Available"; } } else { n.Text = q.Results[i, k]; } //TextBlock //////////////OPTION StackPanel option_panel = new StackPanel(); Border option_border = new Border(); ////////////////////////////////////////////////////// ////FOR CHANGING THE ROW BACKGROUND. if (calc == 1) { border.Background = new SolidColorBrush(Color.FromArgb(250, 215, 215, 215)); option_border.Background = new SolidColorBrush(Color.FromArgb(250, 215, 215, 215)); } else { border.Background = new SolidColorBrush(Color.FromArgb(250, 236, 254, 251)); option_border.Background = new SolidColorBrush(Color.FromArgb(250, 226, 246, 241)); } //DETERMINE WHEN TO ADD THE OPTION STUFF if (calcu == 1) {//CREATE THE OPTIONS STUFF StackPanel option_inner_panel = new StackPanel(); //TO MAKE THINGS EASY JARE,LOOP IT THROUGH THE ARRAY string[] stuff_text = { "Edit", "Delete" }; string[] stuff_image = { "", "" }; HyperlinkButton[,] link = new HyperlinkButton[items_row, stuff_text.Length]; int reduce = i; if (i == items_row) { reduce = i - 1; } for (int t = 0; t < stuff_text.Length; t++) { option_border.BorderThickness = new Thickness(0, 0, 0, 1); option_border.BorderBrush = new SolidColorBrush(Color.FromArgb(50, 0, 0, 0)); TextBlock option_txt = new TextBlock(); option_txt.Text = stuff_text[t]; option_txt.Foreground = new SolidColorBrush(Color.FromArgb(150, 0, 0, 0)); option_txt.FontSize = 15; option_txt.Margin = new Thickness(10, 0, 0, 0); option_txt.VerticalAlignment = VerticalAlignment.Center; // Button button = new Button(); link[i, t] = new HyperlinkButton(); //HyperlinkButton[] link = new HyperlinkButton[tests_row]; link[i, t].Content = option_txt.Text; // link.Click = RoutedEventHandler.Combine(sender, RoutedEventArgs e); //button.ClickMode = ClickMode.Hover; //CLICK EVENT int reduce_t = t; if (t == stuff_text.Length) { reduce_t = t - 1; } //link[i].Click += new RoutedEventHandler(EditRecord_Click("E",)); link[i, t].Click += (s, e) => { if ((string)link[reduce, reduce_t].Content == stuff_text[0]) {//IT's edit tracker = new EditTracker("items", "item_id", item_id.Results[(reduce), 0]); //track the row. tracker.Track(); Auth auth = new Auth(); if (auth.CheckOwner("Items", "item_id", item_id.Results[reduce, 0]) != true) { PopUp p = new PopUp("Sorry, You can't edit Item " + tracker.TrackResult[1] + "'s record cause you didn't add the record"); } else { if (!Editing.IsOpen) { //OPEN this.Frame.Opacity = .4; //this.Opacity = .4; parent.IsEnabled = false; //SET THE EDIT TRACKER //I DID (i-1) BECAUSE IT WAS INCREASE BY ONE, THEREFORE OUT OF BOUND ISH. this.i_id = tracker.TrackResult[0];//set the id to the global var, so that we know what to edit. i_name_e.Text = tracker.TrackResult[1]; i_cost_e.Text = tracker.TrackResult[2]; i_quantity_e.Text = tracker.TrackResult[3]; Editing.IsOpen = true; } } } else if ((string)link[reduce, reduce_t].Content == stuff_text[1]) {//it's the delete. tracker = new EditTracker("items", "item_id", item_id.Results[(reduce), 0]); //track the row tracker.Track(); Auth auth = new Auth(); if (auth.CheckOwner("Items", "item_id", item_id.Results[reduce, 0]) != true) { PopUp p = new PopUp("Sorry, You can't delete this item's record cause you didn't add the record"); } else { this.Frame.Opacity = .4; //this.Opacity = .4; parent.IsEnabled = false; Messages msg = new Messages(); msg.Confirm("Are you sure you want to delete this item's record?"); msg.p_container.IsOpen = true; parent_grid.Children.Add(msg.p_container); msg.TrueBtn.Click += (z, x) => { //CALL THE DELETE QUERY Query que = new Query(); que.successMessage = "Item " + tracker.TrackResult[1] + " with id(" + tracker.TrackResult[0] + ") has been deleted."; que.Remove("Items", "Where item_id = '" + item_id.Results[(reduce), 0] + "'"); this.Frame.Opacity = 1; this.Frame.Navigate(typeof(Items), null); }; msg.FalseBtn.Click += (z, x) => { this.Frame.Opacity = 1; parent.IsEnabled = true; }; } } }; ////ADDING option_inner_panel.Children.Add(link[i, t]); } option_panel.Children.Add(option_inner_panel); option_inner_panel.Orientation = Orientation.Horizontal; option_panel.VerticalAlignment = VerticalAlignment.Center; option_border.Child = option_panel; Grid.SetColumn(option_border, k); Grid.SetRow(option_border, i + 1); items_r.Children.Add(option_border); } else { Grid.SetRow(row_holder, i + 1); Grid.SetColumn(row_holder, k); items_r.Children.Add(row_holder); } } } } else { //NO RECORD Messages msg = new Messages(); msg.Note("No items record available."); items_r.Children.Add(msg._b_Container); RowDefinition rd = new RowDefinition(); // rd.Height = new GridLength(50); items_r.RowDefinitions.Add(rd); Grid.SetColumnSpan(msg._b_Container, col_num); Grid.SetColumn(msg._b_Container, 0); Grid.SetRow(msg._b_Container, 1); } }
public FilterChangedEvent(Filter filter) : base(filter) { }
private TypeDefinitionHandle ImportTypeDefinitionSkeleton(TypeDefinitionHandle srcHandle) { var src = _reader.GetTypeDefinition(srcHandle); var dstHandle = _builder.AddTypeDefinition(src.Attributes, ImportValue(src.Namespace), ImportValue(src.Name), Import(src.BaseType), NextFieldHandle(), NextMethodHandle()); Trace?.Invoke($"Imported {_reader.ToString(src)} -> {RowId(dstHandle):X}"); using var _ = WithLogPrefix($"[{_reader.ToString(src)}]"); foreach (var srcFieldHandle in src.GetFields()) { var srcField = _reader.GetFieldDefinition(srcFieldHandle); if (Filter?.AllowImport(srcField, _reader) == false) { Trace?.Invoke($"Not imported {_reader.ToString(srcField)}"); continue; } var dstFieldHandle = _builder.AddFieldDefinition(srcField.Attributes, ImportValue(srcField.Name), ImportSignatureWithHeader(srcField.Signature)); _fieldDefinitionCache.Add(srcFieldHandle, dstFieldHandle); Trace?.Invoke($"Imported {_reader.ToString(srcFieldHandle)} -> {RowId(dstFieldHandle):X}"); } var implementations = src.GetMethodImplementations() .Select(_reader.GetMethodImplementation) .Where(mi => AllowImportType(_reader.GetMethodClass(mi.MethodDeclaration))) .Select(mi => (MethodDefinitionHandle)mi.MethodBody) .ToImmutableHashSet(); foreach (var srcMethodHandle in src.GetMethods()) { var srcMethod = _reader.GetMethodDefinition(srcMethodHandle); if (!implementations.Contains(srcMethodHandle) && Filter?.AllowImport(srcMethod, _reader) == false) { Trace?.Invoke($"Not imported {_reader.ToString(srcMethod)}"); continue; } var dstSignature = ImportSignatureWithHeader(srcMethod.Signature); if (dstSignature.IsNil) { Trace?.Invoke($"Not imported because of signature {_reader.ToString(srcMethod)}"); continue; } var isAbstract = srcMethod.Attributes.HasFlag(MethodAttributes.Abstract); var bodyOffset = !isAbstract && MakeMock?MakeMockBody(srcMethodHandle) : -1; var dstMethodHandle = _builder.AddMethodDefinition(srcMethod.Attributes, srcMethod.ImplAttributes, ImportValue(srcMethod.Name), dstSignature, bodyOffset, NextParameterHandle()); _methodDefinitionCache.Add(srcMethodHandle, dstMethodHandle); Trace?.Invoke($"Imported {_reader.ToString(srcMethod)} -> {RowId(dstMethodHandle):X}"); using var __ = WithLogPrefix($"[{_reader.ToString(srcMethod)}]"); foreach (var srcParameterHandle in srcMethod.GetParameters()) { var srcParameter = _reader.GetParameter(srcParameterHandle); var dstParameterHandle = _builder.AddParameter(srcParameter.Attributes, ImportValue(srcParameter.Name), srcParameter.SequenceNumber); _parameterCache.Add(srcParameterHandle, dstParameterHandle); Trace?.Invoke($"Imported {_reader.ToString(srcParameter)} -> {RowId(dstParameterHandle):X}"); var defaultValue = srcParameter.GetDefaultValue(); if (!defaultValue.IsNil) { ImportDefaultValue(defaultValue, dstParameterHandle); } if (!srcParameter.GetMarshallingDescriptor().IsNil) { _builder.AddMarshallingDescriptor(dstParameterHandle, ImportValue(srcParameter.GetMarshallingDescriptor())); Trace?.Invoke($"Imported marshalling descriptor {_reader.ToString(srcParameter.GetMarshallingDescriptor())}"); } } } return(dstHandle); }
/// <summary> /// Initializes the dialog. /// </summary> private void InitializeDialog() { openFileName = new OpenFileName(); this.charBuffer = NativeMethods.CharBuffer.CreateBuffer(0x2000); openFileName.lStructSize = Marshal.SizeOf(openFileName); openFileName.lpstrFilter = Filter.Replace('|', '\0') + '\0'; openFileName.lpstrFile = this.charBuffer.AllocCoTaskMem(); openFileName.nMaxFile = 0x2000; if (_fileNames != null && _fileNames.Length > 0 && !string.IsNullOrEmpty(_fileNames[0])) { openFileName.lpstrFileTitle = System.IO.Path.GetFileName(_fileNames[0]) + new string ( '\0', 512 ); } else { openFileName.lpstrFileTitle = new string ( '\0', 512 ); } openFileName.nMaxFileTitle = openFileName.lpstrFileTitle.Length; if (this.DialogType == VersionFileDialogType.OpenFileDialog && string.IsNullOrEmpty(this._title)) { openFileName.lpstrTitle = "Open File"; } else if (this.DialogType == VersionFileDialogType.SaveFileDialog && string.IsNullOrEmpty(this._title)) { openFileName.lpstrTitle = "Save File As..."; } else { openFileName.lpstrTitle = this._title; } if (this.DialogType == VersionFileDialogType.OpenFileDialog && string.IsNullOrEmpty(this.OkButtonText)) { this.OkButtonText = "&Open"; } else if (this.DialogType == VersionFileDialogType.SaveFileDialog && string.IsNullOrEmpty(this.OkButtonText)) { this.OkButtonText = "&Save"; } if (string.IsNullOrEmpty(this.CancelButtonText)) { this.CancelButtonText = "&Cancel"; } openFileName.lpstrDefExt = _defaultExt; //position the dialog above the active window openFileName.hwndOwner = _ownerWindow != null ? _ownerWindow.Handle : IntPtr.Zero; //we need to find out the active screen so the dialog box is //centred on the correct display _activeScreen = Screen.FromControl(Form.ActiveForm); SetDialogFlags(); //this is where the hook is set. Note that we can use a C# delegate in place of a C function pointer openFileName.lpfnHook = new WndHookProc(HookProc); //if we're running on Windows 98/ME then the struct is smaller if (System.Environment.OSVersion.Platform != PlatformID.Win32NT) { openFileName.lStructSize -= 12; } }
public static void Initialize() { Filter.Register(new StaffItemFilter()); }
public ReservedBlob <GuidHandle> Import() { if (_reader.IsAssembly) { var srcAssembly = _reader.GetAssemblyDefinition(); _builder.AddAssembly(ImportValue(srcAssembly.Name), srcAssembly.Version, ImportValue(srcAssembly.Culture), ImportValue(srcAssembly.PublicKey), srcAssembly.Flags, srcAssembly.HashAlgorithm); Debug?.Invoke($"Imported assembly {_reader.ToString(srcAssembly)}"); } var srcModule = _reader.GetModuleDefinition(); var mvidBlob = _builder.ReserveGuid(); _builder.AddModule(srcModule.Generation, ImportValue(srcModule.Name), mvidBlob.Handle, ImportValue(srcModule.GenerationId), ImportValue(srcModule.BaseGenerationId)); Debug?.Invoke($"Imported module {_reader.ToString(srcModule)}"); Debug?.Invoke("Importing assembly files"); foreach (var srcHandle in _reader.AssemblyFiles) { Import(srcHandle); } var index = 1; Debug?.Invoke("Preparing type list for import"); var checker = new CachedAttributeChecker(); foreach (var srcHandle in _reader.TypeDefinitions) { bool shouldImport; var src = _reader.GetTypeDefinition(srcHandle); // Special <Module> type if (srcHandle.GetHashCode() == 1 && _reader.GetString(src.Name) == "<Module>") { shouldImport = true; } else if (checker.HasAttribute(_reader, src, FullNames.Embedded) && checker.HasAttribute(_reader, src, FullNames.CompilerGenerated)) { Trace?.Invoke($"Embedded type found {_reader.ToString(srcHandle)}"); shouldImport = true; } else if (_reader.GetString(src.Namespace) == FullNames.CompilerServices && _reader.GetFullname(src.BaseType) == FullNames.Attribute) { Trace?.Invoke($"CompilerServices attribute found {_reader.ToString(srcHandle)}"); shouldImport = true; } else if (_reader.GetString(src.Namespace) == FullNames.CodeAnalysis && _reader.GetFullname(src.BaseType) == FullNames.Attribute) { Trace?.Invoke($"CodeAnalysis attribute found {_reader.ToString(srcHandle)}"); shouldImport = true; } else { shouldImport = Filter?.AllowImport(_reader.GetTypeDefinition(srcHandle), _reader) != false; } if (shouldImport) { _typeDefinitionCache[srcHandle] = MetadataTokens.TypeDefinitionHandle(index++); } else { Trace?.Invoke($"Type filtered and will not be imported {_reader.ToString(srcHandle)}"); } } Debug?.Invoke("Importing type definitions"); foreach (var srcHandle in _reader.TypeDefinitions.Where(_typeDefinitionCache.ContainsKey)) { var dstHandle = ImportTypeDefinitionSkeleton(srcHandle); if (dstHandle != _typeDefinitionCache[srcHandle]) { throw new Exception("WTF: type handle mismatch"); } } Debug?.Invoke("Importing type definition accessories"); foreach (var(srcHandle, dstHandle) in _typeDefinitionCache) { ImportTypeDefinitionAccessories(srcHandle, dstHandle); } Debug?.Invoke("Importing method definition accessories"); foreach (var(srcHandle, dstHandle) in _methodDefinitionCache) { ImportMethodDefinitionAccessories(srcHandle, dstHandle); } Debug?.Invoke("Importing field definition accessories"); foreach (var(srcHandle, dstHandle) in _fieldDefinitionCache) { ImportFieldDefinitionAccessories(srcHandle, dstHandle); } Debug?.Invoke("Importing nested classes"); var nestedTypes = _typeDefinitionCache .Select(kv => Tuple.Create(kv.Value, _reader.GetTypeDefinition(kv.Key).GetNestedTypes())) .SelectMany(x => x.Item2.Select(y => Tuple.Create(x.Item1, y, Import(y)))) .Where(x => !x.Item3.IsNil) .OrderBy(x => RowId(x.Item3)) .ToList(); foreach (var(dstHandle, srcNested, dstNested) in nestedTypes) { _builder.AddNestedType(dstNested, dstHandle); Trace?.Invoke($"Imported nested type {_reader.ToString(srcNested)} -> {RowId(dstNested):X}"); } var generic = _typeDefinitionCache .Select(kv => Tuple.Create((EntityHandle)kv.Value, _reader.GetTypeDefinition(kv.Key).GetGenericParameters())) .Concat(_methodDefinitionCache .Select(kv => Tuple.Create((EntityHandle)kv.Value, _reader.GetMethodDefinition(kv.Key).GetGenericParameters()))) .OrderBy(x => CodedIndex.TypeOrMethodDef(x.Item1)) .ToList(); Debug?.Invoke("Importing generic constraints"); foreach (var(dstHandle, genericParams) in generic) { ImportGenericConstraints(dstHandle, genericParams); } Debug?.Invoke("Importing custom attributes"); foreach (var src in _reader.CustomAttributes) { Import(src); } Debug?.Invoke("Importing declarative security attributes"); foreach (var src in _reader.DeclarativeSecurityAttributes) { Import(src); } Debug?.Invoke("Importing exported types"); foreach (var src in _reader.ExportedTypes) { Import(src); } if (!OmitReferenceAssemblyAttr && !MakeMock && !IsReferenceAssembly()) { AddReferenceAssemblyAttribute(); } if (MakeMock) { _builder.GetOrAddBlob(_ilStream); } Debug?.Invoke("Importing done"); return(mvidBlob); }
public bool CanBind(IBindRequest <ITemplate> request) { return(Filter.MatchesAny(request)); }
private App() { if (AppArguments.GetBool(AppFlag.IgnoreHttps)) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; AppArguments.Set(AppFlag.SyncNavigation, ref ModernFrame.OptionUseSyncNavigation); AppArguments.Set(AppFlag.DisableTransitionAnimation, ref ModernFrame.OptionDisableTransitionAnimation); AppArguments.Set(AppFlag.RecentlyClosedQueueSize, ref LinkGroupFilterable.OptionRecentlyClosedQueueSize); AppArguments.Set(AppFlag.NoProxy, ref KunosApiProvider.OptionNoProxy); var proxy = AppArguments.Get(AppFlag.Proxy); if (!string.IsNullOrWhiteSpace(proxy)) { try { var s = proxy.Split(':'); WebRequest.DefaultWebProxy = new WebProxy(s[0], FlexibleParser.ParseInt(s.ArrayElementAtOrDefault(1), 1080)); } catch (Exception e) { Logging.Error(e); } } // TODO: AppArguments.Set(AppFlag.ScanPingTimeout, ref RecentManagerOld.OptionScanPingTimeout); AppArguments.Set(AppFlag.LanSocketTimeout, ref KunosApiProvider.OptionLanSocketTimeout); AppArguments.Set(AppFlag.LanPollTimeout, ref KunosApiProvider.OptionLanPollTimeout); AppArguments.Set(AppFlag.WebRequestTimeout, ref KunosApiProvider.OptionWebRequestTimeout); AppArguments.Set(AppFlag.DirectRequestTimeout, ref KunosApiProvider.OptionDirectRequestTimeout); AppArguments.Set(AppFlag.CommandTimeout, ref GameCommandExecutorBase.OptionCommandTimeout); AppArguments.Set(AppFlag.WeatherExtMode, ref WeatherProceduralHelper.Option24HourMode); AppArguments.Set(AppFlag.DisableAcRootChecking, ref AcPaths.OptionEaseAcRootCheck); AppArguments.Set(AppFlag.AcObjectsLoadingConcurrency, ref BaseAcManagerNew.OptionAcObjectsLoadingConcurrency); AppArguments.Set(AppFlag.SkinsLoadingConcurrency, ref CarObject.OptionSkinsLoadingConcurrency); AppArguments.Set(AppFlag.KunosCareerIgnoreSkippedEvents, ref KunosCareerEventsManager.OptionIgnoreSkippedEvents); AppArguments.Set(AppFlag.IgnoreMissingSkinsInKunosEvents, ref KunosEventObjectBase.OptionIgnoreMissingSkins); AppArguments.Set(AppFlag.CanPack, ref AcCommonObject.OptionCanBePackedFilter); AppArguments.Set(AppFlag.CanPackCars, ref CarObject.OptionCanBePackedFilter); AppArguments.Set(AppFlag.ForceToastFallbackMode, ref Toast.OptionFallbackMode); AppArguments.Set(AppFlag.SmartPresetsChangedHandling, ref UserPresetsControl.OptionSmartChangedHandling); AppArguments.Set(AppFlag.EnableRaceIniRestoration, ref Game.OptionEnableRaceIniRestoration); AppArguments.Set(AppFlag.EnableRaceIniTestMode, ref Game.OptionRaceIniTestMode); AppArguments.Set(AppFlag.RaceOutDebug, ref Game.OptionDebugMode); AppArguments.Set(AppFlag.NfsPorscheTribute, ref RaceGridViewModel.OptionNfsPorscheNames); AppArguments.Set(AppFlag.KeepIniComments, ref IniFile.OptionKeepComments); AppArguments.Set(AppFlag.AutoConnectPeriod, ref OnlineServer.OptionAutoConnectPeriod); AppArguments.Set(AppFlag.GenericModsLogging, ref GenericModsEnabler.OptionLoggingEnabled); AppArguments.Set(AppFlag.SidekickOptimalRangeThreshold, ref SidekickHelper.OptionRangeThreshold); AppArguments.Set(AppFlag.GoogleDriveLoaderDebugMode, ref GoogleDriveLoader.OptionDebugMode); AppArguments.Set(AppFlag.GoogleDriveLoaderManualRedirect, ref GoogleDriveLoader.OptionManualRedirect); AppArguments.Set(AppFlag.DebugPing, ref ServerEntry.OptionDebugPing); AppArguments.Set(AppFlag.DebugContentId, ref AcObjectNew.OptionDebugLoading); AppArguments.Set(AppFlag.JpegQuality, ref ImageUtilsOptions.JpegQuality); AppArguments.Set(AppFlag.FbxMultiMaterial, ref Kn5.OptionJoinToMultiMaterial); Acd.Factory = new AcdFactory(); Lazier.SyncAction = ActionExtension.InvokeInMainThreadAsync; KeyboardListenerFactory.Register <KeyboardListener>(); LimitedSpace.Initialize(); DataProvider.Initialize(); SteamIdHelper.Initialize(AppArguments.Get(AppFlag.ForceSteamId)); TestKey(); AppDomain.CurrentDomain.ProcessExit += OnProcessExit; if (!AppArguments.GetBool(AppFlag.PreventDisableWebBrowserEmulationMode) && ( ValuesStorage.Get <int>(WebBrowserEmulationModeDisabledKey) < WebBrowserHelper.EmulationModeDisablingVersion || AppArguments.GetBool(AppFlag.ForceDisableWebBrowserEmulationMode))) { try { WebBrowserHelper.DisableBrowserEmulationMode(); ValuesStorage.Set(WebBrowserEmulationModeDisabledKey, WebBrowserHelper.EmulationModeDisablingVersion); } catch (Exception e) { Logging.Warning("Can’t disable emulation mode: " + e); } } JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Include, Culture = CultureInfo.InvariantCulture }; AcToolsLogging.Logger = (s, m, p, l) => Logging.Write($"{s} (AcTools)", m, p, l); AcToolsLogging.NonFatalErrorHandler = (s, c, e, b) => { if (b) { NonfatalError.NotifyBackground(s, c, e); } else { NonfatalError.Notify(s, c, e); } }; AppArguments.Set(AppFlag.ControlsDebugMode, ref ControlsSettings.OptionDebugControlles); AppArguments.Set(AppFlag.ControlsRescanPeriod, ref DirectInputScanner.OptionMinRescanPeriod); var ignoreControls = AppArguments.Get(AppFlag.IgnoreControls); if (!string.IsNullOrWhiteSpace(ignoreControls)) { ControlsSettings.OptionIgnoreControlsFilter = Filter.Create(new StringTester(), ignoreControls); } var sseStart = AppArguments.Get(AppFlag.SseName); if (!string.IsNullOrWhiteSpace(sseStart)) { SseStarter.OptionStartName = sseStart; } AppArguments.Set(AppFlag.SseLogging, ref SseStarter.OptionLogging); FancyBackgroundManager.Initialize(); if (AppArguments.Has(AppFlag.UiScale)) { AppearanceManager.Instance.AppScale = AppArguments.GetDouble(AppFlag.UiScale, 1d); } if (AppArguments.Has(AppFlag.WindowsLocationManagement)) { AppearanceManager.Instance.ManageWindowsLocation = AppArguments.GetBool(AppFlag.WindowsLocationManagement, true); } if (!InternalUtils.IsAllRight) { AppAppearanceManager.OptionCustomThemes = false; } else { AppArguments.Set(AppFlag.CustomThemes, ref AppAppearanceManager.OptionCustomThemes); } AppArguments.Set(AppFlag.FancyHintsDebugMode, ref FancyHint.OptionDebugMode); AppArguments.Set(AppFlag.FancyHintsMinimumDelay, ref FancyHint.OptionMinimumDelay); AppArguments.Set(AppFlag.WindowsVerbose, ref DpiAwareWindow.OptionVerboseMode); AppArguments.Set(AppFlag.ShowroomUiVerbose, ref LiteShowroomFormWrapperWithTools.OptionAttachedToolsVerboseMode); AppArguments.Set(AppFlag.BenchmarkReplays, ref GameDialog.OptionBenchmarkReplays); AppArguments.Set(AppFlag.HideRaceCancelButton, ref GameDialog.OptionHideCancelButton); AppArguments.Set(AppFlag.PatchSupport, ref PatchHelper.OptionPatchSupport); // Shared memory, now as an app flag SettingsHolder.Drive.WatchForSharedMemory = !AppArguments.GetBool(AppFlag.DisableSharedMemory); /*AppAppearanceManager.OptionIdealFormattingModeDefaultValue = AppArguments.GetBool(AppFlag.IdealFormattingMode, * !Equals(DpiAwareWindow.OptionScale, 1d));*/ NonfatalErrorSolution.IconsDictionary = new Uri("/AcManager.Controls;component/Assets/IconData.xaml", UriKind.Relative); AppearanceManager.DefaultValuesSource = new Uri("/AcManager.Controls;component/Assets/ModernUI.Default.xaml", UriKind.Relative); AppAppearanceManager.Initialize(Pages.Windows.MainWindow.GetTitleLinksEntries()); VisualExtension.RegisterInput <WebBlock>(); ContentUtils.Register("AppStrings", AppStrings.ResourceManager); ContentUtils.Register("ControlsStrings", ControlsStrings.ResourceManager); ContentUtils.Register("ToolsStrings", ToolsStrings.ResourceManager); ContentUtils.Register("UiStrings", UiStrings.ResourceManager); AcObjectsUriManager.Register(new UriProvider()); { var uiFactory = new GameWrapperUiFactory(); GameWrapper.RegisterFactory(uiFactory); ServerEntry.RegisterFactory(uiFactory); } GameWrapper.RegisterFactory(new DefaultAssistsFactory()); LapTimesManager.Instance.SetListener(); RaceResultsStorage.Instance.SetListener(); AcError.RegisterFixer(new AcErrorFixer()); AcError.RegisterSolutionsFactory(new SolutionsFactory()); InitializePresets(); SharingHelper.Initialize(); SharingUiHelper.Initialize(AppArguments.GetBool(AppFlag.ModernSharing) ? new Win10SharingUiHelper() : null); { var addonsDir = FilesStorage.Instance.GetFilename("Addons"); var pluginsDir = FilesStorage.Instance.GetFilename("Plugins"); if (Directory.Exists(addonsDir) && !Directory.Exists(pluginsDir)) { Directory.Move(addonsDir, pluginsDir); } else { pluginsDir = FilesStorage.Instance.GetDirectory("Plugins"); } PluginsManager.Initialize(pluginsDir); PluginsWrappers.Initialize( new AssemblyResolvingWrapper(KnownPlugins.Fmod, FmodResolverService.Resolver), new AssemblyResolvingWrapper(KnownPlugins.Fann, FannResolverService.Resolver), new AssemblyResolvingWrapper(KnownPlugins.Magick, ImageUtils.MagickResolver), new AssemblyResolvingWrapper(KnownPlugins.CefSharp, CefSharpResolverService.Resolver)); } { var onlineMainListFile = FilesStorage.Instance.GetFilename("Online Servers", "Main List.txt"); var onlineFavouritesFile = FilesStorage.Instance.GetFilename("Online Servers", "Favourites.txt"); if (File.Exists(onlineMainListFile) && !File.Exists(onlineFavouritesFile)) { Directory.Move(onlineMainListFile, onlineFavouritesFile); } } Storage.TemporaryBackupsDirectory = FilesStorage.Instance.GetTemporaryDirectory("Storages Backups"); CupClient.Initialize(); Superintendent.Initialize(); ModsWebBrowser.Initialize(); AppArguments.Set(AppFlag.OfflineMode, ref AppKeyDialog.OptionOfflineMode); WebBlock.DefaultDownloadListener = new WebDownloadListener(); FlexibleLoader.CmRequestHandler = new CmRequestHandler(); ContextMenus.ContextMenusProvider = new ContextMenusProvider(); PrepareUi(); AppShortcut.Initialize("Content Manager", "Content Manager"); // If shortcut exists, make sure it has a proper app ID set for notifications if (File.Exists(AppShortcut.ShortcutLocation)) { AppShortcut.CreateShortcut(); } AppIconService.Initialize(new AppIconProvider()); Toast.SetDefaultAction(() => (Current.Windows.OfType <ModernWindow>().FirstOrDefault(x => x.IsActive) ?? Current.MainWindow as ModernWindow)?.BringToFront()); BbCodeBlock.ImageClicked += OnBbImageClick; BbCodeBlock.OptionEmojiProvider = new EmojiProvider(); BbCodeBlock.OptionImageCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Images"); BbCodeBlock.OptionEmojiCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Emoji"); BbCodeBlock.AddLinkCommand(new Uri("cmd://findMissing/car"), new DelegateCommand <string>( id => { WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Car)); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://findMissing/track"), new DelegateCommand <string>( id => { WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Track)); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/car"), new DelegateCommand <string>(id => { var s = id.Split('|'); IndexDirectDownloader.DownloadCarAsync(s[0], s.ArrayElementAtOrDefault(1)).Forget(); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/track"), new DelegateCommand <string>(id => { var s = id.Split('|'); IndexDirectDownloader.DownloadTrackAsync(s[0], s.ArrayElementAtOrDefault(1)).Forget(); })); BbCodeBlock.AddLinkCommand(new Uri("cmd://createNeutralLut"), new DelegateCommand <string>(id => NeutralColorGradingLut.CreateNeutralLut(id.As(16)))); BbCodeBlock.DefaultLinkNavigator.PreviewNavigate += (sender, args) => { if (args.Uri.IsAbsoluteUri && args.Uri.Scheme == "acmanager") { ArgumentsHandler.ProcessArguments(new[] { args.Uri.ToString() }, true).Forget(); args.Cancel = true; } }; AppArguments.SetSize(AppFlag.ImagesCacheLimit, ref BetterImage.OptionCacheTotalSize); AppArguments.Set(AppFlag.ImagesMarkCached, ref BetterImage.OptionMarkCached); BetterImage.RemoteUserAgent = CmApiProvider.UserAgent; BetterImage.RemoteCacheDirectory = BbCodeBlock.OptionImageCacheDirectory; GameWrapper.Started += (sender, args) => { BetterImage.CleanUpCache(); GCHelper.CleanUp(); }; AppArguments.Set(AppFlag.UseVlcForAnimatedBackground, ref DynamicBackground.OptionUseVlc); Filter.OptionSimpleMatching = true; GameResultExtension.RegisterNameProvider(new GameSessionNameProvider()); CarBlock.CustomShowroomWrapper = new CustomShowroomWrapper(); CarBlock.CarSetupsView = new CarSetupsView(); SettingsHolder.Content.OldLayout = AppArguments.GetBool(AppFlag.CarsOldLayout); var acRootIsFine = Superintendent.Instance.IsReady && !AcRootDirectorySelector.IsReviewNeeded(); if (acRootIsFine && SteamStarter.Initialize(AcRootDirectory.Instance.Value)) { if (SettingsHolder.Drive.SelectedStarterType != SettingsHolder.DriveSettings.SteamStarterType) { SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.SteamStarterType; Toast.Show("Starter changed to replacement", "Enjoy Steam being included into CM"); } } else if (SettingsHolder.Drive.SelectedStarterType == SettingsHolder.DriveSettings.SteamStarterType) { SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.DefaultStarterType; Toast.Show($"Starter changed to {SettingsHolder.Drive.SelectedStarterType.DisplayName}", "Steam Starter is unavailable", () => { ModernDialog.ShowMessage( "To use Steam Starter, please make sure CM is taken place of the official launcher and AC root directory is valid.", "Steam Starter is unavailable", MessageBoxButton.OK); }); } InitializeUpdatableStuff(); BackgroundInitialization(); ExtraProgressRings.Initialize(); FatalErrorMessage.Register(new AppRestartHelper()); ImageUtils.SafeMagickWrapper = fn => { try { return(fn()); } catch (OutOfMemoryException e) { NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, ToolsStrings.MagickNet_CannotLoad_Commentary, e); } catch (Exception e) { NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, e); } return(null); }; DataFileBase.ErrorsCatcher = new DataSyntaxErrorCatcher(); AppArguments.Set(AppFlag.SharedMemoryLiveReadingInterval, ref AcSharedMemory.OptionLiveReadingInterval); AcSharedMemory.Initialize(); AppArguments.Set(AppFlag.RunRaceInformationWebserver, ref PlayerStatsManager.OptionRunStatsWebserver); AppArguments.Set(AppFlag.RaceInformationWebserverFile, ref PlayerStatsManager.OptionWebserverFilename); PlayerStatsManager.Instance.SetListener(); RhmService.Instance.SetListener(); WheelOptionsBase.SetStorage(new WheelAnglesStorage()); _hibernator = new AppHibernator(); _hibernator.SetListener(); VisualCppTool.Initialize(FilesStorage.Instance.GetDirectory("Plugins", "NativeLibs")); try { SetRenderersOptions(); } catch (Exception e) { VisualCppTool.OnException(e, null); } CommonFixes.Initialize(); CmPreviewsTools.MissingShowroomHelper = new CarUpdatePreviewsDialog.MissingShowroomHelper(); // Paint shop+livery generator? LiteShowroomTools.LiveryGenerator = new LiveryGenerator(); // Discord if (AppArguments.Has(AppFlag.DiscordCmd)) { // Do not show main window and wait for futher instructions? } if (SettingsHolder.Integrated.DiscordIntegration) { AppArguments.Set(AppFlag.DiscordVerbose, ref DiscordConnector.OptionVerboseMode); DiscordConnector.Initialize(AppArguments.Get(AppFlag.DiscordClientId) ?? InternalUtils.GetDiscordClientId(), new DiscordHandler()); DiscordImage.OptionDefaultImage = @"track_ks_brands_hatch"; GameWrapper.Started += (sender, args) => args.StartProperties.SetAdditional(new GameDiscordPresence(args.StartProperties, args.Mode)); } // Reshade? var loadReShade = AppArguments.GetBool(AppFlag.ForceReshade); if (!loadReShade && string.Equals(AppArguments.Get(AppFlag.ForceReshade), "kn5only", StringComparison.OrdinalIgnoreCase)) { loadReShade = AppArguments.Values.Any(x => x.EndsWith(".kn5", StringComparison.OrdinalIgnoreCase)); } if (loadReShade) { var reshade = Path.Combine(MainExecutingFile.Directory, "dxgi.dll"); if (File.Exists(reshade)) { Kernel32.LoadLibrary(reshade); } } // Auto-show that thing InstallAdditionalContentDialog.Initialize(); // Let’s roll ShutdownMode = ShutdownMode.OnExplicitShutdown; new AppUi(this).Run(); }
public Vector3Filter(int size, FloatFilterKernel kernel) { xFilter = new FloatFilter(size, kernel); yFilter = new FloatFilter(size, kernel); zFilter = new FloatFilter(size, kernel); }
public bool Matches(ITemplate template) { return(Filter.MatchesAny(template)); }
async Task <bool> IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { var user = eventArgs.User; var usingItem = eventArgs.Using; if (usingItem == null || usingItem.Deleted || !EntitySystem.Get <ActionBlockerSystem>().CanInteract(user)) { return(false); } if (usingItem.TryGetComponent(out SeedComponent? seeds)) { if (Seed == null) { if (seeds.Seed == null) { user.PopupMessageCursor(Loc.GetString("plant-holder-component-empty-seed-packet-message")); usingItem.QueueDelete(); return(false); } user.PopupMessageCursor(Loc.GetString("plant-holder-component-plant-success-message", ("seedName", seeds.Seed.SeedName), ("seedNoun", seeds.Seed.SeedNoun))); Seed = seeds.Seed; Dead = false; Age = 1; Health = Seed.Endurance; _lastCycle = _gameTiming.CurTime; usingItem.QueueDelete(); CheckLevelSanity(); UpdateSprite(); return(true); } user.PopupMessageCursor(Loc.GetString("plant-holder-component-already-seeded-message", ("name", Owner.Name))); return(false); } if (usingItem.HasTag("Hoe")) { if (WeedLevel > 0) { user.PopupMessageCursor(Loc.GetString("plant-holder-component-remove-weeds-message", ("name", Owner.Name))); user.PopupMessageOtherClients(Loc.GetString("plant-holder-component-remove-weeds-others-message", ("otherName", user.Name))); WeedLevel = 0; UpdateSprite(); } else { user.PopupMessageCursor(Loc.GetString("plant-holder-component-no-weeds-message")); } return(true); } if (usingItem.HasTag("Shovel")) { if (Seed != null) { user.PopupMessageCursor(Loc.GetString("plant-holder-component-remove-plant-message", ("name", Owner.Name))); user.PopupMessageOtherClients(Loc.GetString("plant-holder-component-remove-plant-others-message", ("name", user.Name))); RemovePlant(); } else { user.PopupMessageCursor(Loc.GetString("plant-holder-component-no-plant-message")); } return(true); } if (usingItem.TryGetComponent(out ISolutionInteractionsComponent? solution) && solution.CanDrain) { var amount = ReagentUnit.New(5); var sprayed = false; if (usingItem.TryGetComponent(out SprayComponent? spray)) { sprayed = true; amount = ReagentUnit.New(1); if (!string.IsNullOrEmpty(spray.SpraySound)) { SoundSystem.Play(Filter.Pvs(usingItem), spray.SpraySound, usingItem, AudioHelpers.WithVariation(0.125f)); } } var split = solution.Drain(amount); if (split.TotalVolume == 0) { user.PopupMessageCursor(Loc.GetString("plant-holder-component-empty-message", ("owner", usingItem))); return(true); } user.PopupMessageCursor(Loc.GetString(sprayed ? "plant-holder-component-spray-message" : "plant-holder-component-transfer-message", ("owner", Owner), ("amount", split.TotalVolume))); _solutionContainer?.TryAddSolution(split); ForceUpdateByExternalCause(); return(true); } if (usingItem.HasTag("PlantSampleTaker")) { if (Seed == null) { user.PopupMessageCursor(Loc.GetString("plant-holder-component-nothing-to-sample-message")); return(false); } if (Sampled) { user.PopupMessageCursor(Loc.GetString("plant-holder-component-already-sampled-message")); return(false); } if (Dead) { user.PopupMessageCursor(Loc.GetString("plant-holder-component-dead-plant-message")); return(false); } var seed = Seed.SpawnSeedPacket(user.Transform.Coordinates); seed.RandomOffset(0.25f); user.PopupMessageCursor(Loc.GetString("plant-holder-component-take-sample-message", ("seedName", Seed.DisplayName))); Health -= (_random.Next(3, 5) * 10); if (_random.Prob(0.3f)) { Sampled = true; } // Just in case. CheckLevelSanity(); ForceUpdateByExternalCause(); return(true); } if (usingItem.HasTag("BotanySharp")) { return(DoHarvest(user)); } if (usingItem.HasComponent <ProduceComponent>()) { user.PopupMessageCursor(Loc.GetString("plant-holder-component-compost-message", ("owner", Owner), ("usingItem", usingItem))); user.PopupMessageOtherClients(Loc.GetString("plant-holder-component-compost-others-message", ("user", user), ("usingItem", usingItem), ("owner", Owner))); if (usingItem.TryGetComponent(out SolutionContainerComponent? solution2)) { // This deliberately discards overfill. _solutionContainer?.TryAddSolution(solution2.SplitSolution(solution2.Solution.TotalVolume)); ForceUpdateByExternalCause(); } usingItem.QueueDelete(); return(true); } return(false); }
protected override void OnInteractHand() { SoundSystem.Play(Filter.Pvs(Owner), "/Audio/Effects/thudswoosh.ogg", Owner, AudioHelpers.WithVariation(0.05f)); }
public static List <Resource> GetResources(Catalog catalog, Filter filter, string serverUri, string proxyUrl) { return(GetResources(catalog, filter, serverUri, proxyUrl, null)); }
public Task ClearAsync(IEnumerable <string> currentConsumerNames) { return(Collection.DeleteManyAsync(Filter.Not(Filter.In(NameField, currentConsumerNames)))); }