Ejemplo n.º 1
0
        public static System.Array setData(System.Collections.Generic.IEnumerable <System.Data.DataRow> Data, bool expHeader = true)
        {
            int rStart = 1;

            if (!expHeader)
            {
                rStart = 0;
            }
            var data = new object[Data.Count() + rStart, Data.First().Table.Columns.Count];
            int iR   = 0;

            if (expHeader)
            {
                for (int iC = 0; iC < Data.First().Table.Columns.Count; iC++)
                {
                    data[iR, iC] = Data.First().Table.Columns[iC].Caption;
                }
                iR++;
            }
            foreach (DataRow dr in Data)
            {
                for (int iC = 0; iC < Data.First().Table.Columns.Count; iC++)
                {
                    data[iR, iC] = dr.Field <dynamic>(iC);
                }
                iR++;
            }
            return(data);
        }
Ejemplo n.º 2
0
        public async Task Servers()
        {
            if (Context.User.Id != 264811248552640522)
            {
                await Context.Message.DeleteAsync();

                return;
            }
            System.Collections.Generic.IEnumerable <SocketGuild> guilds = Program._client.Guilds;
            Console.WriteLine(guilds.First());
            Thread thread = new Thread(x =>
            {
                foreach (SocketGuild guild in guilds)
                {
                    Context.Channel.SendMessageAsync("", false, new EmbedBuilder()
                                                     .WithTitle(Text("server_head").ToString())
                                                     .WithDescription(
                                                         Text("server_1").ToString() + guild.Name +
                                                         Text("server_2").ToString() + guild.CreatedAt.ToLocalTime() + "\n\n" +
                                                         Text("server_3").ToString() + guild.Users.Count +
                                                         Text("server_4").ToString() + guild.Roles.Count +
                                                         Text("server_5").ToString() + guild.Channels.Count +
                                                         Text("server_6").ToString())
                                                     .WithCurrentTimestamp()
                                                     .WithThumbnailUrl(guild.IconUrl)
                                                     .WithColor(Color.DarkPurple)
                                                     .Build());
                }
            });

            thread.Start();
        }
Ejemplo n.º 3
0
        public void Update(DuelMastersModels.Duel duel, Zone zone)
        {
            foreach (Card cardToAdd in zone.Cards.Where(handCard => Cards.All(viewModelCard => viewModelCard.GameId != handCard.GameId)))
            {
                if (cardToAdd is Creature creature)
                {
                    Cards.Add(new CreatureViewModel(creature, duel));
                }
                else if (cardToAdd is Spell spell)
                {
                    Cards.Add(new SpellViewModel(spell));
                }
                else
                {
                    throw new System.NotImplementedException();
                }
            }
            System.Collections.Generic.IEnumerable <CardViewModel> cardsToRemove = Cards.Where(viewModelCard => zone.Cards.All(handCard => handCard.GameId != viewModelCard.GameId));
            while (cardsToRemove.Count() > 0)
            {
                Cards.Remove(cardsToRemove.First());
            }

            for (int i = 0; i < Cards.Count; ++i)
            {
                Cards[i].Update(zone.Cards[i], duel);
            }
        }
Ejemplo n.º 4
0
        public string GetAuthUserToken(string redirectURL = null)
        {
            string headerToken = "";

            System.Collections.Generic.IEnumerable <string> keys = null;

            if (Request.Headers.TryGetValues("authToken", out keys))
            {
                headerToken = keys.First();
            }

            //Check for Authentication Token in Request Header
            if (!string.IsNullOrEmpty(headerToken))
            {
                //Validate User and Token
                string appUserID = headerToken.Split(';')[0], userToken = headerToken.Split(';')[1];
                var    retVal = _IAppUserRepository.ConfirmAppUserToken(userToken, long.Parse(appUserID));
                //User and Token Match
                if (retVal.isSuccess)
                {
                    return(redirectURL ?? "/Home/Index");
                }
                else
                {
                    return("/Home/Index;Access Denied");
                }
            }
            else
            {
                return("/Home/Index;Access Denied");
            }
        }
Ejemplo n.º 5
0
        public override async System.Threading.Tasks.Task <System.Collections.Generic.IEnumerable <Lpp.Dns.DTO.RequestObserverDTO> > InsertOrUpdate(System.Collections.Generic.IEnumerable <Lpp.Dns.DTO.RequestObserverDTO> values)
        {
            //This no longer works as we are setting the ID on the new observers at the portal side.
            //The update base code doesn't inser those entities in the database, thus we need to manually update/insert.
            //var result = await base.InsertOrUpdate(values);

            Guid        requestID   = values.First().RequestID;
            List <Guid> observerIDs = values.Select(p => p.ID.Value).ToList();

            //PMNDEV-4548 - We are only inserting new Observers via the Observer Add dialog and will not be handling deletions/removals.
            //Check if we need to delete any entities
            //if (DataContext.RequestObservers.Any(p => p.RequestID == requestID && observerIDs.Contains(p.ID) == false))
            //{
            //    var toDelete = DataContext.RequestObservers.Where(p => p.RequestID == requestID && observerIDs.Contains(p.ID) == false);
            //    DataContext.RequestObservers.RemoveRange(toDelete);
            //}

            foreach (var observer in values)
            {
                if (DataContext.RequestObservers.Any(p => p.ID == observer.ID))
                {
                    //Existing Observer
                    await base.Update(values.Where(p => p.ID == observer.ID));
                }
                else
                {
                    //New Observer
                    RequestObserver newObserver = DataContext.RequestObservers.Create();
                    newObserver.ID              = observer.ID.Value;
                    newObserver.DisplayName     = observer.DisplayName;
                    newObserver.Email           = observer.Email;
                    newObserver.RequestID       = observer.RequestID;
                    newObserver.SecurityGroupID = observer.SecurityGroupID;
                    newObserver.UserID          = observer.UserID;
                    DataContext.RequestObservers.Add(newObserver);
                }
            }
            await DataContext.SaveChangesAsync();

            if (values.Any(p => p.EventSubscriptions.Any(es => es.RequestObserverID == Guid.Empty)))
            {
                var toInsertCollection = values.Where(p => p.EventSubscriptions.Any(es => es.RequestObserverID == Guid.Empty));
                foreach (var observer in toInsertCollection)
                {
                    foreach (var observerEventSubscription in observer.EventSubscriptions.Where(p => p.RequestObserverID == Guid.Empty))
                    {
                        var obj = DataContext.RequestObserverEventSubscriptions.Create();
                        obj.EventID           = observerEventSubscription.EventID;
                        obj.Frequency         = observerEventSubscription.Frequency.HasValue ? observerEventSubscription.Frequency.Value : DTO.Enums.Frequencies.Immediately;
                        obj.RequestObserverID = observer.ID.Value;
                        DataContext.RequestObserverEventSubscriptions.Add(obj);
                    }
                }

                await DataContext.SaveChangesAsync();
            }
            return(values);
        }
Ejemplo n.º 6
0
        public override void ExecuteWithResourceItems(System.Collections.Generic.IEnumerable <ResourceEditor.ViewModels.ResourceItem> resourceItems)
        {
            var firstSelectedItem = resourceItems.First();

            if (firstSelectedItem != null)
            {
                Clipboard.SetText(firstSelectedItem.Name);
            }
        }
        private void BeforeQueryStatus(object sender, EventArgs e)
        {
            var button = (OleMenuCommand)sender;

            System.Collections.Generic.IEnumerable <string> files = ProjectHelpers.GetSelectedItemPaths();

            bool isSprite = files.Count() == 1 && Path.GetExtension(files.First()).Equals(Constants.FileExtension, StringComparison.OrdinalIgnoreCase);

            button.Enabled = button.Visible = isSprite;
        }
        public override System.Collections.Generic.IEnumerable <Item> Perform(System.Collections.Generic.IEnumerable <Item> items, System.Collections.Generic.IEnumerable <Item> modItems)
        {
            WindowItem item = items.First() as WindowItem;

            if (item != null)
            {
                Utils.ActiveWindow(item.MyWindow);
            }
            yield break;
        }
Ejemplo n.º 9
0
 /// <summary>Unicode表における一つ次のcodeを返す</summary>
 /// <param name="hand">対象の手</param>
 /// <returns>次の手</returns>
 public Hands.Unicode Next(Hands.Unicode hand)
 {
     // https://stackoverflow.com/questions/642542/how-to-get-next-or-previous-enum-value-in-c-sharp
     // https://stackoverflow.com/questions/11222256/string-does-not-contain-a-definition-for-cast
     System.Collections.Generic.IEnumerable <Hands.Unicode> hands = Enum.GetValues(typeof(Hands.Unicode)).Cast <Hands.Unicode>();
     if (hand == Enum.GetValues(typeof(Hands.Unicode)).Cast <Hands.Unicode>().Last())
     {
         return(hands.First());
     }
     return(hands.Where(e => (int)e > (int)hand).OrderBy(e => e).First());
 }
Ejemplo n.º 10
0
        public static Food Cook()
        {
            Assembly[] asses = AppDomain.CurrentDomain.GetAssemblies();
            System.Collections.Generic.IEnumerable <Type> types = asses.SelectMany(s => s.GetTypes().Where(w => w.GetInterfaces().Contains(typeof(Food)))).ToList();
            Type type = types.First(f => f.Name == name);


            //Assembly ass = Assembly.Load("简单工厂模式");
            //Type type = ass.GetType("简单工厂模式.Food");
            return(Activator.CreateInstance(type) as Food);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Touchs down.
        /// </summary>
        /// <param name="point">Point.</param>
        /// <returns><c>true</c>, if began was touchesed, <c>false</c> otherwise.</returns>
        /// <param name="points">Points.</param>
        public override bool TouchesBegan(System.Collections.Generic.IEnumerable <NGraphics.Point> points)
        {
            base.TouchesBegan(points);

            var p = points.First();

            if (p.Y < TopHeight + DayNamesHeight)
            {
                return(false);
            }

            var col = (int)(p.X * 7 / _calendar.Width);
            var row = (int)((p.Y - TopHeight - DayNamesHeight) * 6 / _calendar.Height);


            var choosenDate = _firstDate.AddDays(col + (row * 7));

            if (choosenDate > _lastDate)
            {
                return(true);
            }

            if (choosenDate < _currentMonth && _currentMonth > MinDate - MinDate.TimeOfDay)
            {
                _currentMonth = _currentMonth.AddMonths(-1);
            }
            else if (choosenDate >= _currentMonth.AddMonths(1) && _currentMonth.AddMonths(1) <= MaxDate)
            {
                _currentMonth = _currentMonth.AddMonths(1);
            }
            else if (choosenDate >= MinDate - MinDate.TimeOfDay && choosenDate <= MaxDate)
            {
                _ellipse.TranslationX = (col * _calendar.Width / 7);
                _ellipse.TranslationY = (row * _calendar.Height / 6);

                _ellipse.Scale   = 0.0;
                _ellipse.Opacity = 1.0;

                _ellipse.ScaleTo(2);
                _ellipse.FadeTo(0.0);

                SelectedDate = choosenDate + SelectedDate.TimeOfDay;
                if (OnDateSelected != null)
                {
                    OnDateSelected(this, EventArgs.Empty);
                }

                return(true);
            }

            UpdateCalendar();

            return(true);
        }
Ejemplo n.º 12
0
        public static ScenarioProcessingClass GetFeature(string featureName, string narrative)
        {
            //ScenarioProcessingClass feature = null;

            System.Collections.Generic.IEnumerable <Tmx.ScenarioProcessingClass> features =
                from f in Features
                where f.FeatureCreated.Title == featureName && f.FeatureCreated.Narrative == narrative
                select f;

            return(features.First());
        }
        public override void ExecuteWithResourceItems(System.Collections.Generic.IEnumerable <ResourceEditor.ViewModels.ResourceItem> resourceItems)
        {
            var    selectedItem = resourceItems.First();
            string newValue     = SD.MessageService.ShowInputBox("${res:ResourceEditor.ResourceEdit.ContextMenu.EditComment}",
                                                                 "${res:ResourceEditor.ResourceEdit.ContextMenu.EditCommentText}",
                                                                 selectedItem.Comment);

            if (newValue != null && newValue != selectedItem.Comment)
            {
                selectedItem.Comment = newValue;
            }
        }
Ejemplo n.º 14
0
        private static Option <int> Solve(
            int currentFrequency,
            System.Collections.Generic.IEnumerable <Option <int> > frequencies,
            int finalFrequency,
            HashSet <int> partialFrequencies
            )
        {
            int newFinalFrequency = finalFrequency + currentFrequency;

            return(partialFrequencies.Contains(newFinalFrequency) ?
                   newFinalFrequency :
                   Solve(frequencies.First(), frequencies.Skip(1), newFinalFrequency, partialFrequencies.Add(newFinalFrequency)));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Assert a collection is sorted
        /// </summary>
        public static void IsSorted <T>(System.Collections.Generic.IEnumerable <T> sorted) where T : IComparable <T>
        {
            var previous = sorted.First();

            foreach (var item in sorted.Skip(1))
            {
                if (item.CompareTo(previous) < 0)
                {
                    throw new Exception($"Collection is not sorted. {item} is not greater than {previous}.");
                }
                previous = item;
            }
        }
Ejemplo n.º 16
0
        public async Task <System.Linq.IQueryable <Lpp.Dns.DTO.DataMartClient.Request> > GetRequests(System.Collections.Generic.IEnumerable <System.Guid> ID, Guid dataMartID, string oDataQuery = null)
        {
            string identifier;

            _log.Debug(ExecutingMessage($"GetRequests?ID={ ID.First().ToString("D") }&DataMartID={ dataMartID.ToString("D")}", out identifier));

            Lpp.Dns.DTO.DataMartClient.Criteria.RequestCriteria criteria = new DTO.DataMartClient.Criteria.RequestCriteria {
                ID = ID, DatamartID = dataMartID
            };
            var result = await this.Post <Lpp.Dns.DTO.DataMartClient.Criteria.RequestCriteria, Lpp.Dns.DTO.DataMartClient.Request>(Path + "/GetRequests", criteria);

            if (result.IsSuccess)
            {
                _log.Debug(CompletionMessage(identifier, $"GetRequests?ID={ ID.First().ToString("D") }&DataMartID={ dataMartID.ToString("D")}", result.IsSuccess));
            }
            else
            {
                _log.Error(CompletionMessage(identifier, $"GetRequests?ID={ ID.First().ToString("D") }&DataMartID={ dataMartID.ToString("D")}", result.IsSuccess) + "\r\n" + result.ReturnErrorsAsString());
            }

            return(result.ReturnList());
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Touchs down.
        /// </summary>
        /// <param name="point">Point.</param>
        /// <returns><c>true</c>, if began was touchesed, <c>false</c> otherwise.</returns>
        /// <param name="points">Points.</param>
        public override bool TouchesBegan(System.Collections.Generic.IEnumerable <NGraphics.Point> points)
        {
            base.TouchesBegan(points);

            var p = points.First();

            if (p.Y < TopHeight + DayNamesHeight)
            {
                return(false);
            }

            _ellipse.Scale   = 0.0;
            _ellipse.Opacity = 1.0;

            p.Y += ((_calendar.Height / 6) / 2);

            _ellipse.TranslationX = Math.Floor(p.X / (_calendar.Width / 7)) * (_calendar.Width / 7);
            _ellipse.TranslationY = Math.Floor(p.Y / (_calendar.Height / 6)) *
                                    (_calendar.Height / 6) - (TopHeight + DayNamesHeight + ((_calendar.Height / 6) / 2));

            _ellipse.ScaleTo(2);
            _ellipse.FadeTo(0.0);

            // Update selected date
            var col         = (int)Math.Round(_ellipse.TranslationX / (_calendar.Width / 7));
            var row         = (int)Math.Round(_ellipse.TranslationY / (_calendar.Height / 6));
            var choosenDate = StartDate.AddDays(col + (row * 7));

            System.Diagnostics.Debug.WriteLine(choosenDate);
            var callEvent = (choosenDate.Month == SelectedDate.Month);

            SelectedDate = choosenDate;

            // Call event
            if (callEvent && OnDateSelected != null)
            {
                OnDateSelected(this, EventArgs.Empty);
            }

            return(true);
        }
Ejemplo n.º 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            //services.AddMvc(option => option.EnableEndpointRouting = false);
            services.AddServerSideBlazor();
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSingleton <Helpers.Authentication>(new Helpers.Authentication(Configuration));
            System.Collections.Generic.IEnumerable <ServiceDescriptor> lookup = from s in services where s.ServiceType == typeof(Helpers.Authentication) select s;
            Helpers.Authentication authenticationHelper = (Helpers.Authentication)lookup.First().ImplementationInstance;

            // Add authentication services
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect("Auth0", options => authenticationHelper.SetOpenIdConnectOptions(options));

            services.AddHttpContextAccessor();

            services.AddAuthorization(options => { Helpers.Policies.SetPolicies(options); });
            services.AddScoped <HttpContextAccessor>();
            //services.AddScoped<AuthenticationStateProvider, Helpers.TestAuthStateProvider>();
            Helpers.Requirements.RegisterRequirements(services);

            services.AddScoped <Service.Need4Service>();
            services.AddScoped <XYZ.Utility>();
        }
Ejemplo n.º 19
0
        public override void ExecuteWithResourceItems(System.Collections.Generic.IEnumerable <ResourceEditor.ViewModels.ResourceItem> resourceItems)
        {
            var firstSelectedItem = resourceItems.First();

            var sdialog = new Microsoft.Win32.SaveFileDialog();

            sdialog.AddExtension = true;
            sdialog.FileName     = firstSelectedItem.Name;

            if (firstSelectedItem.ResourceValue is System.Drawing.Bitmap)
            {
                sdialog.Filter     = StringParser.Parse("${res:SharpDevelop.FileFilter.ImageFiles} (*.png)|*.png");
                sdialog.DefaultExt = ".png";
            }
            else if (firstSelectedItem.ResourceValue is System.Drawing.Icon)
            {
                sdialog.Filter     = StringParser.Parse("${res:SharpDevelop.FileFilter.Icons}|*.ico");
                sdialog.DefaultExt = ".ico";
            }
            else if (firstSelectedItem.ResourceValue is System.Windows.Forms.Cursor)
            {
                sdialog.Filter     = StringParser.Parse("${res:SharpDevelop.FileFilter.CursorFiles} (*.cur)|*.cur");
                sdialog.DefaultExt = ".cur";
            }
            else if (firstSelectedItem.ResourceValue is byte[])
            {
                sdialog.Filter     = StringParser.Parse("${res:SharpDevelop.FileFilter.BinaryFiles} (*.*)|*.*");
                sdialog.DefaultExt = ".bin";
            }
            else
            {
                return;
            }

            bool?dr = sdialog.ShowDialog();

            if (!dr.HasValue || !dr.Value)
            {
                return;
            }

            try {
                if (firstSelectedItem.ResourceValue is Icon)
                {
                    FileStream fstr = new FileStream(sdialog.FileName, FileMode.Create);
                    ((Icon)firstSelectedItem.ResourceValue).Save(fstr);
                    fstr.Close();
                }
                else if (firstSelectedItem.ResourceValue is Image)
                {
                    Image img = (Image)firstSelectedItem.ResourceValue;
                    img.Save(sdialog.FileName);
                }
                else
                {
                    FileStream   fstr = new FileStream(sdialog.FileName, FileMode.Create);
                    BinaryWriter wr   = new BinaryWriter(fstr);
                    wr.Write((byte[])firstSelectedItem.ResourceValue);
                    fstr.Close();
                }
            } catch (Exception ex) {
                SD.MessageService.ShowWarning("Can't save resource to " + sdialog.FileName + ": " + ex.Message);
            }
        }
Ejemplo n.º 20
0
        TryToResolveDuplicate(
            PackageDefinition masterDefinitionFile,
            string dupName,
            System.Collections.Generic.IEnumerable <PackageDefinition> duplicates,
            Array <PackageDefinition> packageDefinitions,
            Array <StringArray> packageVersionSpecifiers,
            Array <PackageDefinition> toRemove)
        {
            // command line specifications take precedence to resolve a duplicate
            foreach (var specifier in packageVersionSpecifiers)
            {
                if (!specifier.Contains(dupName))
                {
                    continue;
                }

                foreach (var dupPackage in duplicates)
                {
                    if (specifier[1] == dupPackage.Version)
                    {
                        toRemove.AddRange(packageDefinitions.Where(item => (item.Name == dupName) && (item != dupPackage)));
                        return(dupPackage);
                    }
                }

                var noMatchMessage = new System.Text.StringBuilder();
                noMatchMessage.AppendFormat("Command line version specified, {0}, could not resolve to one of the available versions of package {1}:", specifier[1], duplicates.First().Name);
                noMatchMessage.AppendLine();
                foreach (var dup in duplicates)
                {
                    noMatchMessage.AppendFormat("\t{0}", dup.Version);
                    noMatchMessage.AppendLine();
                }
                throw new Exception(noMatchMessage.ToString());
            }

            // now look at the master dependency file, for any 'default' specifications
            var masterDependency = masterDefinitionFile.Dependents.FirstOrDefault(item => item.Item1 == dupName && item.Item3.HasValue && item.Item3.Value);

            if (null != masterDependency)
            {
                toRemove.AddRange(packageDefinitions.Where(item => (item.Name == dupName) && (item.Version != masterDependency.Item2)));
                return(packageDefinitions.First(item => (item.Name == dupName) && (item.Version == masterDependency.Item2)));
            }

            return(null);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Insert an icon into a specific folder
        /// </summary>
        /// <param name="_currentIcon"></param>
        /// <param name="folderOfInterest"></param>
        public void InsertIntoFolder(Icon _currentIcon, System.Collections.Generic.IEnumerable <Icon> folderOfInterest)
        {
            if (folderOfInterest != null && _currentIcon != null && folderOfInterest.Count() > 0)
            {
                System.Diagnostics.Debug.WriteLineIf(App.OutputVerbose, "In Completed: Insertable into folder: " + _currentIcon.Tag);

                var folderToInsertInto = folderOfInterest.First();

                var startPoint = _currentIcon.Location;

                float xDiff = (folderToInsertInto.Location.X + folderToInsertInto.Bounds.Width / 2f) - (startPoint.X + _currentIcon.Bounds.Width / 2f);
                float yDiff = (folderToInsertInto.Location.Y + folderToInsertInto.Bounds.Height / 2f) - (startPoint.Y + _currentIcon.Bounds.Height / 2f);

                new Xamarin.Forms.Animation((value) =>
                {
                    if (_currentIcon != null)
                    {
                        try
                        {
                            _currentIcon.Location = new SKPoint((startPoint.X) + (xDiff * (float)value),
                                                                (startPoint.Y) + (yDiff * (float)value));
                        }
                        catch (System.Exception e)
                        {
                            System.Diagnostics.Debug.WriteLineIf(App.OutputVerbose, e.ToString());
                        }
                    }
                }).Commit(Xamarin.Forms.Application.Current.MainPage, "Anim", length: Constants.DeviceLayout.AnimationMoveMillis, finished: (v, c) =>
                {
                    new Xamarin.Forms.Animation((value) =>
                    {
                        try
                        {
                            if (_currentIcon != null)
                            {
                                _currentIcon.Transformation = SKMatrix.MakeScale(1 - (float)value, 1 - (float)value);
                            }
                        }
                        catch (System.Exception e)
                        {
                            System.Diagnostics.Debug.WriteLineIf(App.OutputVerbose, e.ToString());
                        }
                    }).Commit(Xamarin.Forms.Application.Current.MainPage, "Anim", length: Constants.DeviceLayout.AnimationShrinkMillis, finished: (v2, c2) =>
                    {
                        try
                        {
                            if (_currentIcon != null)
                            {
                                _currentIcon.IsStoredInAFolder = true;
                                _currentIcon.Transformation    = SKMatrix.MakeScale(1, 1);
                                _currentIcon.StoredFolderTag   = folderToInsertInto.Text;

                                canvasRef.Icons.SendToBack(_currentIcon);
                                canvasRef.Controller.PromptResave();
                            }
                        }
                        catch (System.Exception e)
                        {
                            System.Diagnostics.Debug.WriteLineIf(App.OutputVerbose, e.ToString());
                        }
                    });
                });
            }
        }
Ejemplo n.º 22
0
        SharedSettings(
            System.Collections.Generic.IEnumerable <Bam.Core.Module> objectFiles,
            System.Type convertExtensionClassType,
            System.Type conversionInterfaceType,
            Bam.Core.TypeArray convertParameterTypes)
        {
            var sharedInterfaces      = SharedInterfaces(objectFiles);
            var implementedInterfaces = new Bam.Core.TypeArray(sharedInterfaces);

            implementedInterfaces.Add(conversionInterfaceType);

            // define a new type, that contains just the shared interfaces between all object files
            // (any interface not shared, must be cloned later)
            var typeSignature          = "IDESharedSettings";
            var assemblyName           = new System.Reflection.AssemblyName(typeSignature);
            var assemblyBuilder        = System.AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, System.Reflection.Emit.AssemblyBuilderAccess.Run);
            var moduleBuilder          = assemblyBuilder.DefineDynamicModule("MainModule", true);
            var sharedSettingsTypeDefn = moduleBuilder.DefineType(typeSignature,
                                                                  System.Reflection.TypeAttributes.Public |
                                                                  System.Reflection.TypeAttributes.Class |
                                                                  System.Reflection.TypeAttributes.AutoClass |
                                                                  System.Reflection.TypeAttributes.AnsiClass |
                                                                  System.Reflection.TypeAttributes.BeforeFieldInit |
                                                                  System.Reflection.TypeAttributes.AutoLayout,
                                                                  typeof(C.SettingsBase),
                                                                  implementedInterfaces.ToArray());

            // TODO: is this necessary?
#if false
            sharedSettingsTypeDefn.DefineDefaultConstructor(
                System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.SpecialName | System.Reflection.MethodAttributes.RTSpecialName);
#endif

            // implement 'automatic property' setter and getters for each property in each interface
            foreach (var i in sharedInterfaces)
            {
                var properties = i.GetProperties();
                foreach (var prop in properties)
                {
                    var dynamicProperty = sharedSettingsTypeDefn.DefineProperty(prop.Name,
                                                                                System.Reflection.PropertyAttributes.None,
                                                                                prop.PropertyType,
                                                                                System.Type.EmptyTypes);
                    var field = sharedSettingsTypeDefn.DefineField("m" + prop.Name,
                                                                   prop.PropertyType,
                                                                   System.Reflection.FieldAttributes.Private);
                    var methodAttrs = System.Reflection.MethodAttributes.Public |
                                      System.Reflection.MethodAttributes.HideBySig |
                                      System.Reflection.MethodAttributes.Virtual;
                    if (prop.IsSpecialName)
                    {
                        methodAttrs |= System.Reflection.MethodAttributes.SpecialName;
                    }
                    var getter = sharedSettingsTypeDefn.DefineMethod("get_" + prop.Name,
                                                                     methodAttrs,
                                                                     prop.PropertyType,
                                                                     System.Type.EmptyTypes);
                    var setter = sharedSettingsTypeDefn.DefineMethod("set_" + prop.Name,
                                                                     methodAttrs,
                                                                     null,
                                                                     new[] { prop.PropertyType });
                    var getIL = getter.GetILGenerator();
                    getIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                    getIL.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                    getIL.Emit(System.Reflection.Emit.OpCodes.Ret);
                    dynamicProperty.SetGetMethod(getter);
                    var setIL = setter.GetILGenerator();
                    setIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                    setIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                    setIL.Emit(System.Reflection.Emit.OpCodes.Stfld, field);
                    setIL.Emit(System.Reflection.Emit.OpCodes.Ret);
                    dynamicProperty.SetSetMethod(setter);
                }
            }

            var projectSettingsConvertMethod = sharedSettingsTypeDefn.DefineMethod("Convert",
                                                                                   System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Final | System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.NewSlot | System.Reflection.MethodAttributes.Virtual,
                                                                                   null,
                                                                                   convertParameterTypes.ToArray());
            var convertIL = projectSettingsConvertMethod.GetILGenerator();
            foreach (var i in sharedInterfaces)
            {
                var extConvertParameterTypes = new Bam.Core.TypeArray(i);
                extConvertParameterTypes.AddRange(convertParameterTypes);
                var methInfo = convertExtensionClassType.GetMethod("Convert", extConvertParameterTypes.ToArray());
                if (null == methInfo)
                {
                    throw new Bam.Core.Exception("Unable to locate the function {0}.{1}(this {2})", convertExtensionClassType.FullName, "Convert", i.Name);
                }
                // TODO: can this be simplified, using the ldarg opcode? a simple loop would suffice
                convertIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                if (extConvertParameterTypes.Count > 1)
                {
                    convertIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                }
                if (extConvertParameterTypes.Count > 2)
                {
                    convertIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
                }
                if (extConvertParameterTypes.Count > 3)
                {
                    convertIL.Emit(System.Reflection.Emit.OpCodes.Ldarg_3);
                }
                convertIL.Emit(System.Reflection.Emit.OpCodes.Call, methInfo);
            }
            convertIL.Emit(System.Reflection.Emit.OpCodes.Ret);

            var sharedSettingsType = sharedSettingsTypeDefn.CreateType();
            var attributeType      = typeof(Bam.Core.SettingsExtensionsAttribute);

            // now that we have an instance of the shared settings type, calculate the values of the individual settings across all object files
            // for all shared interfaces
            var commonSettings = System.Activator.CreateInstance(sharedSettingsType) as SettingsBase;
            commonSettings.InitializeAllInterfaces(objectFiles.First(), true, false);
            foreach (var i in sharedInterfaces)
            {
                var attributeArray = i.GetCustomAttributes(attributeType, false);
                if (0 == attributeArray.Length)
                {
                    throw new Bam.Core.Exception("Settings interface {0} is missing attribute {1}", i.ToString(), attributeType.ToString());
                }

                var attribute = attributeArray[0] as Bam.Core.SettingsExtensionsAttribute;

                var cloneSettingsMethod = attribute.GetMethod("Clone", new[] { i, i });
                if (null == cloneSettingsMethod)
                {
                    throw new Bam.Core.Exception("Unable to find extension method {0}.Clone(this {1}, {1}, {1}, {1})",
                                                 attribute.ExtensionsClassName,
                                                 i.ToString());
                }

                var intersectSettingsMethod = attribute.GetMethod("Intersect", new[] { i, i });
                if (null == intersectSettingsMethod)
                {
                    throw new Bam.Core.Exception("Unable to find extension method {0}.Intersect(this {1}, {1})",
                                                 attribute.ExtensionsClassName,
                                                 i.ToString());
                }

                var objectFileCount = objectFiles.Count();
                cloneSettingsMethod.Invoke(null, new[] { commonSettings, objectFiles.First().Settings });
                for (int objIndex = 1; objIndex < objectFileCount; ++objIndex)
                {
                    intersectSettingsMethod.Invoke(null, new[] { commonSettings, objectFiles.ElementAt(objIndex).Settings });
                }
            }
            return(commonSettings);
        }
 private async void Execute(object sender, EventArgs e)
 {
     System.Collections.Generic.IEnumerable <string> files = ProjectHelpers.GetSelectedItemPaths();
     await SpriteService.GenerateSpriteAsync(files.First());
 }
Ejemplo n.º 24
0
        public static async Task <bool> Run()
        {
            PluginContainer plugin = PluginManager.Plugins.Where(p => p.Plugin.Name == "SideStep" || p.Plugin.Name == "回避").First();

            // 检测附近 对象是否有特定读条技能
            System.Collections.Generic.IEnumerable <BattleCharacter> num = GameObjectManager.GetObjectsOfType <BattleCharacter>()
                                                                           .Where(r => r.CastingSpellId != 0 && !r.IsMe && r.Distance() < 50 &&
                                                                                  (
                                                                                      r.CastingSpellId == 15594 ||
                                                                                      r.CastingSpellId == 15590 ||
                                                                                      r.CastingSpellId == 15591 ||
                                                                                      r.CastingSpellId == 15592 ||
                                                                                      r.CastingSpellId == 15593 ||
                                                                                      r.CastingSpellId == 15602 ||
                                                                                      r.CastingSpellId == 15605 ||
                                                                                      r.CastingSpellId == 15606 ||
                                                                                      r.CastingSpellId == 15607 ||
                                                                                      r.CastingSpellId == 15610 ||
                                                                                      r.CastingSpellId == 15609
                                                                                  )
                                                                                  );

            if (num != null && num.Count() > 0)
            {
                BattleCharacter spell = num.First();
                Logging.Write(Colors.Aquamarine, $"跟随");

                if (spell.NpcId == 8299)
                {
                    if (plugin != null)
                    {
                        if (plugin.Enabled == true)
                        {
                            plugin.Enabled = false;
                        }
                    }
                }

                BattleCharacter Obj = GameObjectManager.GetObjectsOfType <BattleCharacter>(true).Where(r =>
                                                                                                       r.NpcId == 729 || r.NpcId == 8378 || // "雅·修特拉"
                                                                                                       r.NpcId == 1492 ||                   // "于里昂热"
                                                                                                       r.NpcId == 4130 ||                   // "阿尔菲诺"
                                                                                                       r.NpcId == 5239 ||                   // "阿莉塞"
                                                                                                       r.NpcId == 8889 ||                   // 琳
                                                                                                       r.Name == "阿莉塞" ||
                                                                                                       r.Name == "琳" ||
                                                                                                       r.Name == "水晶公" ||
                                                                                                       r.Name == "敏菲利亚" ||
                                                                                                       r.Name == "桑克瑞德"
                                                                                                       ).OrderBy(r => r.Distance()).First();

                //当距离大于跟随距离 再处理跟随
                if (Obj.Location.Distance2D(Core.Me.Location) >= 0.2)
                {
                    if (Core.Me.IsCasting)
                    {
                        ActionManager.StopCasting();  //断读条
                    }
                    // 选中跟随最近的队友
                    Obj.Target();

                    Logging.Write(Colors.Aquamarine, $"队友{Obj.Name}距离:{Obj.Location.Distance2D(Core.Me.Location)}");

                    while (Obj.Location.Distance2D(Core.Me.Location) >= 0.2)
                    {
                        Navigator.PlayerMover.MoveTowards(Obj.Location);
                        await Coroutine.Sleep(50);
                    }
                    Navigator.PlayerMover.MoveStop();
                    await Coroutine.Sleep(50);

                    return(true);
                }
            }

            if (Core.Target != null)
            {
                System.Collections.Generic.IEnumerable <BattleCharacter> sC = GameObjectManager.GetObjectsOfType <BattleCharacter>().Where(
                    r => !r.IsMe && r.Distance() < 50 && r.NpcId == 8250
                    );  //77BOSS2

                // /77BOSS2 移动
                if (sC.Any() == true)
                {
                    if (plugin != null)
                    {
                        if (plugin.Enabled == true)
                        {
                            plugin.Enabled = false;
                        }
                    }

                    Logging.Write(Colors.Aquamarine, $"boss2");
                    BattleCharacter spellCaster = sC.First();


                    if (spellCaster != null && spellCaster.Name == Core.Target.Name)
                    {
                        BattleCharacter Obj = GameObjectManager.GetObjectsOfType <BattleCharacter>(true).Where(r =>
                                                                                                               r.NpcId == 729 || r.NpcId == 8378 || // "雅·修特拉"
                                                                                                               r.NpcId == 1492 ||                   // "于里昂热"
                                                                                                               r.NpcId == 4130 ||                   // "阿尔菲诺"
                                                                                                               r.NpcId == 5239 ||                   // "阿莉塞"
                                                                                                               r.NpcId == 8889 ||                   // 琳
                                                                                                               r.Name == "阿莉塞" ||
                                                                                                               r.Name == "琳" ||
                                                                                                               r.Name == "水晶公" ||
                                                                                                               r.Name == "敏菲利亚" ||
                                                                                                               r.Name == "桑克瑞德"
                                                                                                               ).OrderBy(r => r.Distance()).First();

                        //当距离大于跟随距离 再处理跟随
                        if (Obj.Location.Distance2D(Core.Me.Location) >= 0.2)
                        {
                            if (Core.Me.IsCasting)
                            {
                                ActionManager.StopCasting();  //断读条
                            }
                            // 选中跟随最近的队友
                            Obj.Target();

                            Logging.Write(Colors.Aquamarine, $"队友{Obj.Name}距离:{Obj.Location.Distance2D(Core.Me.Location)}");

                            while (Obj.Location.Distance2D(Core.Me.Location) >= 0.2)
                            {
                                Navigator.PlayerMover.MoveTowards(Obj.Location);
                                await Coroutine.Sleep(50);
                            }
                            Navigator.PlayerMover.MoveStop();
                            await Coroutine.Sleep(50);

                            return(true);
                        }
                    }
                }
            }
            return(false);
        }