Inheritance: MonoBehaviour
Ejemplo n.º 1
0
 public override void sendMessage(Messages.AbstractMessage message)
 {
     foreach (AbstractTransever trans in base.connections)
     {
         trans.sendMessage(message);
     }
 }
Ejemplo n.º 2
0
        public void Parse(HabboHotel.GameClients.GameClient Session, Messages.ClientMessage Packet)
        {
            uint RoomId = Packet.PopWiredUInt();
            string Password = Packet.PopFixedString();

            Session.GetMessageHandler().PrepareRoomForUser(RoomId, Password);
        }
Ejemplo n.º 3
0
 private void HandleChatMessage(Messages.ChatMessage chatMessageMsg)
 {
     if (chatMessageMsg.From == _userName)
         _serverActor.Tell(chatMessageMsg);
     else
        _consoleActor.Tell(new Messages.StatusMessage(chatMessageMsg.Message,StatusMessageType.Success));
 }
Ejemplo n.º 4
0
        public void Invoke(Network.Session Session, Messages.PacketEvent Packet)
        {
            bool RemoveAll = Packet.PopBoolean();

            if (RemoveAll)
            {
                Session.Character.MessengerRequests.Clear();
                System.MySQLManager.InvokeQuery(new MessengerDeclineAllFriendQuery(Session.Character.Id));
            }
            else
            {
                foreach (int TargetId in Packet.PopCollection())
                {
                    if (TargetId < 1 || TargetId == Session.Character.Id)
                    {
                        continue;
                    }

                    if (!Session.Character.MessengerRequests.Contains(TargetId))
                    {
                        continue;
                    }

                    Session.Character.MessengerRequests.Remove(TargetId);
                    System.MySQLManager.InvokeQuery(new MessengerDeclineFriendQuery(TargetId, Session.Character.Id));
                }
            }
        }
 public void InterceptResponse(ref Messages.InterDomainMessageResponse response)
 {
     RoutedInterDomainMessage ridm = (RoutedInterDomainMessage)response.Message;
     lock (_postRequestors)
     {
         foreach (sRoute srt in ridm.PostInterceptRoutes)
         {
             if (_postRequestors.ContainsKey(srt))
             {
                 foreach (IInterDomainMessagePostRequestInterceptor idmpri in _postRequestors[srt])
                 {
                     if (!response.HasIntercepted(idmpri.GetType()))
                     {
                         object tmp;
                         idmpri.InterceptResponse(response, out tmp);
                         if (tmp != null)
                         {
                             response = Messages.InterDomainMessageResponse.SwapResponse(response, tmp);
                             response.MarkInterceptor(idmpri.GetType());
                         }
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 6
0
 public void subCallback(Messages.std_msgs.String msg)
 {
     Dispatcher.Invoke(new Action(() =>
     {
         l.Content = "Receieved:\n" + msg.data;
     }), new TimeSpan(0,0,1));
 }
Ejemplo n.º 7
0
 public void Invoke(Session Session, Messages.PacketEvent Packet)
 {
     if (System.Configuration.PopBoolean("MOTD.Notifitation.Enabled"))
     {
         Session.WriteComposer(new MOTDNotificationComposer(System.Configuration.PopString("MOTD.Notifitation.Message")));
     }
 }
Ejemplo n.º 8
0
 internal SearchReceivedEventArgs(Messages.DiscoveryMessage message, System.Net.IPEndPoint sender)
 {
     ServiceType = message.Service.ServiceType;
     MaxWaitTime = message.MaxWaitTime;
     ReceivedContent = message.Content;
     Sender = sender;
 }
Ejemplo n.º 9
0
        public void Parse(HabboHotel.GameClients.GameClient Session, Messages.ClientMessage Packet)
        {
            Silverwave.HabboHotel.Users.Habbo targetHabbo = Session.GetHabbo();
            if (targetHabbo == null)
            {
                return;
            }

            uint Id = Packet.PopWiredUInt();

            RoomData Data = SilverwaveEnvironment.GetGame().GetRoomManager().GenerateRoomData(Id);

            if (Data == null || Session.GetHabbo().FavoriteRooms.Count >= 30 || Session.GetHabbo().FavoriteRooms.Contains(Id))
            {
                // send packet that favourites is full.
                return;
            }

            Session.GetHabbo().FavoriteRooms.Add(Id);
            Session.SendMessage(new UpdateFavouriteRoomComposer(Id, true));

            using (IQueryAdapter dbClient = SilverwaveEnvironment.GetDatabaseManager().getQueryreactor())
            {
                dbClient.runFastQuery("INSERT INTO user_favorites (user_id,room_id) VALUES (" + Session.GetHabbo().Id + "," + Id + ")");
            }
        }
Ejemplo n.º 10
0
        public void Parse(HabboHotel.GameClients.GameClient Session, Messages.ClientMessage Packet)
        {
            Session.SendMessage(new UserObjectComposer(Session.GetHabbo()));
            Session.SendMessage(new UserPerksComposer());

            Session.GetHabbo().InitMessenger(); // Temporary fixxx
        }
Ejemplo n.º 11
0
 private static Response Process(string input, string[] args)
 {
     try
     {
         switch (args[0])
         {
             case "compile":
                 return Compiler.Compile(JsonConvert.DeserializeObject<CompileRequest>(input));
             case "nunit":
                 return NUnitTester.Test(JsonConvert.DeserializeObject<TestRequest>(input));
             case "nugetpack":
                 return NuGetter.Pack(JsonConvert.DeserializeObject<NuGetPackRequest>(input));
             case "nugetpush":
                 return NuGetter.Push(JsonConvert.DeserializeObject<NuGetPushRequest>(input));
             case "nugetrestore":
                 return NuGetter.Restore(JsonConvert.DeserializeObject<NuGetRestoreRequest>(input));
             default:
                 throw new ApplicationException("Unsupported type '" + args[0] + "'");
         }
     }
     catch (Exception e)
     {
         var messages = new Messages();
         messages.Add(Message.CreateError(e.ToString()));
         return new Response(messages);
     }
 }
Ejemplo n.º 12
0
        public MessagesResponse Post(Messages request)
        {
            if (request.Message.Id > 0)
              {
            Bm2s.Data.Common.BLL.User.Message item = Datas.Instance.DataStorage.Messages[request.Message.Id];
            item.Body = request.Message.Body;
            item.IsShortMessage = request.Message.IsShortMessage;
            item.SendDate = request.Message.SendDate;
            item.Subject = request.Message.Subject;
            item.UserId = request.Message.User.Id;
              }
              else
              {
            Bm2s.Data.Common.BLL.User.Message item = new Data.Common.BLL.User.Message()
            {
              Body = request.Message.Body,
              IsShortMessage = request.Message.IsShortMessage,
              SendDate = request.Message.SendDate,
              Subject = request.Message.Subject,
              UserId = request.Message.User.Id
            };

            Datas.Instance.DataStorage.Messages.Add(item);
            request.Message.Id = item.Id;
              }

              MessagesResponse response = new MessagesResponse();
              response.Messages.Add(request.Message);
              return response;
        }
Ejemplo n.º 13
0
 public static void rosoutCallback(Messages.rosgraph_msgs.Log msg)
 {
     string pfx = "[?]";
     switch (msg.level)
     {
         case Log.DEBUG:
             pfx = "[DEBUG]";
             break;
         case Log.ERROR:
             pfx = "[ERROR]";
             break;
         case Log.FATAL:
             pfx = "[FATAL]";
             break;
         case Log.INFO:
             pfx = "[INFO]";
             break;
         case Log.WARN:
             pfx = "[WARN]";
             break;
     }
     TimeData td = ROS.GetTime().data;
     Console.WriteLine("["+td.sec+"."+td.nsec+"]: "+pfx+": "+msg.msg+" ("+msg.file+" ("+msg.function+" @"+msg.line+"))");
     pub.publish(msg);
 }
Ejemplo n.º 14
0
 private void HandleChatMessage(Messages.ChatMessage chatMessage)
 {
     foreach(var participant in _participants.Where(x=>x.Key != chatMessage.From))
     {
         participant.Value.Tell(chatMessage);
     }
 }
Ejemplo n.º 15
0
        public void Invoke(Session Session, Messages.PacketEvent Packet)
        {
            int A = Packet.PopInt32();
            int B = Packet.PopInt32();

            Session.UpdateLatencyPing(((A + B) / 2));
        }
Ejemplo n.º 16
0
        public string Resolve(Messages.Field field)
        {
            var f = spec.Fields.Single(c => c.Name == field.Name);
            var fixType = f.Type;
            var clrType = typeMap[fixType];
            var @enum = f.Values.Any();
            if (@enum && clrType == "bool")
            {
                return clrType;
            }
            else if (@enum)
            {
                return field.Name;
            }
            else
            {
                var nullableMark = string.Empty;
                
                if (field.Required == false && clrType != "string")
                {
                    nullableMark = "?";
                }

                return string.Format("{0}{1}", clrType, nullableMark);
            }
        }
Ejemplo n.º 17
0
        //
        // GET: /account/messages/{accountName}/{number}
        // GET: /account/messages/name={accountName}/{number}
        // GET: /account/messages/id={accountId}/{number}
        public ActionResult Messages(string accountName, Guid? accountId, int number)
        {
            Answer output;

            try
            {
                if (accountId == null && accountName == null)
                {
                    output = new Answer(new Error("Account missing"));
                    Response.StatusCode = 400; // Bad Request
                }
                else
                {
                    var realId = accountId ?? Storage.Account.GetId(accountName);

                    // get lasts messages from account accoutName
                    var personalListId = Storage.List.GetPersonalList(realId);
                    var listMsgs = Storage.Msg.GetListsMsgTo(new HashSet<Guid> {personalListId}, DateTime.Now, number);

                    // convert, looking forward XML serialization
                    var listMsgsOutput = new Messages(listMsgs, Storage);
                    output = new Answer(listMsgsOutput);
                }
            }

            catch (Exception exception)
            {
                // Result is an non-empty error XML element
                output = new Answer(HandleError(exception));
            }

            return Serialize(output);
        }
Ejemplo n.º 18
0
 public void MessageSent(int chatId, int UsrId, Messages message)
 {
     if (_connections.IfExists(UsrId))
     {
         Clients.Client(_connections.GetConnection(UsrId)).NewChatCreated(message);
     }
 }
 static ProtobufMessageEncodingBindingElement()
 {
     //TODO: use http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx
     //TODO: or http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx
     //NOTE: used compiled messages to save start uo time
     _proto = new Messages();
 }
Ejemplo n.º 20
0
        public void Invoke(Session Session, Messages.PacketEvent Packet)
        {
            string Name = Packet.PopString();
            string Model = Packet.PopString();

            System.IOStreamer.AppendLine("Caption: {0}, Model: {1}", Name, Model);
        }
Ejemplo n.º 21
0
        public void Parse(HabboHotel.GameClients.GameClient Session, Messages.ClientMessage Packet)
        {
            string Junk = Packet.PopFixedString();
            string MachineId = Packet.PopFixedString();

            Session.MachineId = MachineId;
        }
 private void HandleRegisterUser(Messages.RegisterUser x)
 {
     if(!string.IsNullOrEmpty(x.UserName))
     {
         registeredUsers.Add(x.UserName);
     }
 }
Ejemplo n.º 23
0
 public Response(Messages messages)
 {
     Messages = messages.ToArray(message => new ResponseMessage
     {
         Type = message.Type,
         Body = message.Body,
     });
 }
Ejemplo n.º 24
0
        /// <summary>
        /// new
        /// </summary>
        /// <param name="response"></param>
        public IndexQueryResult(Messages.RpbIndexResp response)
        {
            if (response == null) { this.Results = new IndexTerm[0]; return; }

            this.Continuation = response.continuation;
            if (response.keys.Count > 0) this.Results = response.keys.Select(c => new IndexTerm(c.GetString())).ToArray();
            else this.Results = response.results.Select(c => new IndexTerm(c.value.GetString(), c.key.GetString())).ToArray();
        }
Ejemplo n.º 25
0
        public Presenter()
        {
            string[] files = { "settings.json", "contacts.xml", "messages.bin" };

            _settings = JsonSerialization.ReadFromJsonFile<Settings>(files[0]);
            _contacts = XmlSerialization.ReadFromXmlFile<Contacts>(files[1]);
            _messages = BinarySerialization.ReadFromBinaryFile<Messages>(files[2]);
        }
        public void TestMoveInstructionsMessage()
        {
            Messages message = new Messages();
            string actualMessage = message.MoveInstructionsMessage();
            string expectedMesage = "Enter your move (L=left, R=right, U=up, D=down): ";

            Assert.AreEqual(expectedMesage, actualMessage);
        }
        public void TestWelcomeMessage()
        {
            Messages message = new Messages();
            string actualMessage = message.WelcomeMessage();
            string expectedMesage = "Welcome to \"Labyrinth\" game. Please try to escape. Use 'top' to view the top scoreboard, 'restart' to start a new game and 'exit' to quit the game.";

            Assert.AreEqual(expectedMesage, actualMessage);
        }
        public void TestInvalidMoveMessage()
        {
            Messages message = new Messages();
            string actualMessage = message.InvalidMoveMessage();
            string expectedMesage = "Invalid move!";

            Assert.AreEqual(expectedMesage, actualMessage);
        }
Ejemplo n.º 29
0
        public MainPageViewModel(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;
            Messages = new Messages();

            this.WireUpCommands();
            this.WireUpEvents();
        }
        public void TestNewLine()
        {
            Messages message = new Messages();
            string actualMessage = message.NewLine();
            string expectedMesage = Environment.NewLine;

            Assert.AreEqual(expectedMesage, actualMessage);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// 엑셀다운로드
        /// </summary>
        /// <param name="obj"></param>
        private void ExcelDownAction(object obj)
        {
            try
            {
                /// 데이터조회
                Hashtable conditions = new Hashtable();
                conditions.Add("RCV_NUM", splyCmplListView.txtRCV_NUM.Text.Trim());
                conditions.Add("APL_HJD", cbHJD_CDE.EditValue);
                conditions.Add("APL_CDE", cbAPL_CDE.EditValue);
                conditions.Add("PRO_CDE", cbPRO_CDE.EditValue);
                conditions.Add("RCV_YMD_FROM", splyCmplListView.dtRCV_YMD_FROM.EditValue == null ? "" : Convert.ToDateTime(splyCmplListView.dtRCV_YMD_FROM.EditValue).ToString("yyyyMMdd"));
                conditions.Add("RCV_YMD_TO", splyCmplListView.dtRCV_YMD_TO.EditValue == null ? "" : Convert.ToDateTime(splyCmplListView.dtRCV_YMD_TO.EditValue).ToString("yyyyMMdd"));
                conditions.Add("PRO_YMD_FROM", splyCmplListView.dtPRO_YMD_FROM.EditValue == null ? "" : Convert.ToDateTime(splyCmplListView.dtPRO_YMD_FROM.EditValue).ToString("yyyyMMdd"));
                conditions.Add("PRO_YMD_TO", splyCmplListView.dtPRO_YMD_TO.EditValue == null ? "" : Convert.ToDateTime(splyCmplListView.dtPRO_YMD_TO.EditValue).ToString("yyyyMMdd"));


                conditions.Add("page", 0);
                conditions.Add("rows", 1000000);

                conditions.Add("sqlId", "SelectSplyCmplList");


                exceldt = BizUtil.SelectList(conditions);


                //그리드헤더정보 추출
                columnList = new GridColumn[grid.Columns.Count];
                grid.Columns.CopyTo(columnList, 0);
                listCols = new List <string>(); //컬럼헤더정보 가져오기
                foreach (GridColumn gcol in columnList)
                {
                    try
                    {
                        if ("PrintN".Equals(gcol.Tag.ToString()))
                        {
                            continue;                                       //엑셀출력제외컬럼
                        }
                    }
                    catch (Exception) { }

                    listCols.Add(gcol.FieldName.ToString());
                }


                saveFileDialog       = null;
                saveFileDialog       = new System.Windows.Forms.SaveFileDialog();
                saveFileDialog.Title = "저장경로를 지정하세요.";

                //초기 파일명 지정
                saveFileDialog.FileName = DateTime.Now.ToString("yyyyMMdd") + "_" + "급수공사 민원목록.xlsx";

                saveFileDialog.OverwritePrompt = true;
                saveFileDialog.Filter          = "Excel|*.xlsx";

                if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    strFileName = saveFileDialog.FileName;
                    thread      = new Thread(new ThreadStart(ExcelExportFX));
                    thread.Start();
                }
            }
            catch (Exception ex)
            {
                Messages.ShowErrMsgBoxLog(ex);
            }
        }
Ejemplo n.º 32
0
        public override void DoWindowContents(Rect inRect)
        {
            Text.Font = GameFont.Medium;
            Rect rect = new Rect(0f, 0f, 400f, 50f);

            Widgets.Label(rect, this.bill.LabelCap);
            float width = (float)((int)((inRect.width - 34f) / 3f));
            Rect  rect2 = new Rect(0f, 80f, width, inRect.height - 80f);
            Rect  rect3 = new Rect(rect2.xMax + 17f, 50f, width, inRect.height - 50f - this.CloseButSize.y);
            Rect  rect4 = new Rect(rect3.xMax + 17f, 50f, 0f, inRect.height - 50f - this.CloseButSize.y);

            rect4.xMax = inRect.xMax;
            Text.Font  = GameFont.Small;
            Listing_Standard listing_Standard = new Listing_Standard();

            listing_Standard.Begin(rect3);
            Listing_Standard listing_Standard2 = listing_Standard.BeginSection((float)Dialog_BillConfig.RepeatModeSubdialogHeight);

            if (listing_Standard2.ButtonText(this.bill.repeatMode.LabelCap, null))
            {
                BillRepeatModeUtility.MakeConfigFloatMenu(this.bill);
            }
            listing_Standard2.Gap(12f);
            if (this.bill.repeatMode == BillRepeatModeDefOf.RepeatCount)
            {
                listing_Standard2.Label("RepeatCount".Translate(new object[]
                {
                    this.bill.repeatCount
                }), -1f, null);
                listing_Standard2.IntEntry(ref this.bill.repeatCount, ref this.repeatCountEditBuffer, 1);
            }
            else if (this.bill.repeatMode == BillRepeatModeDefOf.TargetCount)
            {
                string text = "CurrentlyHave".Translate() + ": ";
                text += this.bill.recipe.WorkerCounter.CountProducts(this.bill);
                text += " / ";
                text += ((this.bill.targetCount >= 999999) ? "Infinite".Translate().ToLower() : this.bill.targetCount.ToString());
                string text2 = this.bill.recipe.WorkerCounter.ProductsDescription(this.bill);
                if (!text2.NullOrEmpty())
                {
                    string text3 = text;
                    text = string.Concat(new string[]
                    {
                        text3,
                        "\n",
                        "CountingProducts".Translate(),
                        ": ",
                        text2
                    });
                }
                listing_Standard2.Label(text, -1f, null);
                int targetCount = this.bill.targetCount;
                listing_Standard2.IntEntry(ref this.bill.targetCount, ref this.targetCountEditBuffer, this.bill.recipe.targetCountAdjustment);
                this.bill.unpauseWhenYouHave = Mathf.Max(0, this.bill.unpauseWhenYouHave + (this.bill.targetCount - targetCount));
                ThingDef producedThingDef = this.bill.recipe.ProducedThingDef;
                if (producedThingDef != null)
                {
                    if (producedThingDef.IsWeapon || producedThingDef.IsApparel)
                    {
                        listing_Standard2.CheckboxLabeled("IncludeEquipped".Translate(), ref this.bill.includeEquipped, null);
                    }
                    if (producedThingDef.IsApparel && producedThingDef.apparel.careIfWornByCorpse)
                    {
                        listing_Standard2.CheckboxLabeled("IncludeTainted".Translate(), ref this.bill.includeTainted, null);
                    }
                    Widgets.Dropdown <Bill_Production, Zone_Stockpile>(listing_Standard2.GetRect(30f), this.bill, (Bill_Production b) => b.includeFromZone, (Bill_Production b) => this.GenerateStockpileInclusion(), (this.bill.includeFromZone != null) ? "IncludeSpecific".Translate(new object[]
                    {
                        this.bill.includeFromZone.label
                    }) : "IncludeFromAll".Translate(), null, null, null, null, false);
                    Widgets.FloatRange(listing_Standard2.GetRect(28f), 10, ref this.bill.hpRange, 0f, 1f, "HitPoints", ToStringStyle.PercentZero);
                    if (producedThingDef.HasComp(typeof(CompQuality)))
                    {
                        Widgets.QualityRange(listing_Standard2.GetRect(28f), 2, ref this.bill.qualityRange);
                    }
                    if (producedThingDef.MadeFromStuff)
                    {
                        listing_Standard2.CheckboxLabeled("LimitToAllowedStuff".Translate(), ref this.bill.limitToAllowedStuff, null);
                    }
                }
            }
            if (this.bill.repeatMode == BillRepeatModeDefOf.TargetCount)
            {
                listing_Standard2.Gap(12f);
                listing_Standard2.Gap(12f);
                listing_Standard2.CheckboxLabeled("PauseWhenSatisfied".Translate(), ref this.bill.pauseWhenSatisfied, null);
                if (this.bill.pauseWhenSatisfied)
                {
                    listing_Standard2.Label("UnpauseWhenYouHave".Translate() + ": " + this.bill.unpauseWhenYouHave.ToString("F0"), -1f, null);
                    listing_Standard2.IntEntry(ref this.bill.unpauseWhenYouHave, ref this.unpauseCountEditBuffer, this.bill.recipe.targetCountAdjustment);
                    if (this.bill.unpauseWhenYouHave >= this.bill.targetCount)
                    {
                        this.bill.unpauseWhenYouHave = this.bill.targetCount - 1;
                        this.unpauseCountEditBuffer  = this.bill.unpauseWhenYouHave.ToStringCached();
                    }
                }
            }
            listing_Standard.EndSection(listing_Standard2);
            listing_Standard.Gap(12f);
            Listing_Standard listing_Standard3 = listing_Standard.BeginSection((float)Dialog_BillConfig.StoreModeSubdialogHeight);
            string           text4             = string.Format(this.bill.GetStoreMode().LabelCap, (this.bill.GetStoreZone() == null) ? "" : this.bill.GetStoreZone().SlotYielderLabel());

            if (this.bill.GetStoreZone() != null && !this.bill.recipe.WorkerCounter.CanPossiblyStoreInStockpile(this.bill, this.bill.GetStoreZone()))
            {
                text4    += string.Format(" ({0})", "IncompatibleLower".Translate());
                Text.Font = GameFont.Tiny;
            }
            if (listing_Standard3.ButtonText(text4, null))
            {
                Text.Font = GameFont.Small;
                List <FloatMenuOption> list = new List <FloatMenuOption>();
                foreach (BillStoreModeDef billStoreModeDef in from bsm in DefDatabase <BillStoreModeDef> .AllDefs
                         orderby bsm.listOrder
                         select bsm)
                {
                    if (billStoreModeDef == BillStoreModeDefOf.SpecificStockpile)
                    {
                        List <SlotGroup> allGroupsListInPriorityOrder = this.bill.billStack.billGiver.Map.haulDestinationManager.AllGroupsListInPriorityOrder;
                        int count = allGroupsListInPriorityOrder.Count;
                        for (int i = 0; i < count; i++)
                        {
                            SlotGroup      group          = allGroupsListInPriorityOrder[i];
                            Zone_Stockpile zone_Stockpile = group.parent as Zone_Stockpile;
                            if (zone_Stockpile != null)
                            {
                                if (!this.bill.recipe.WorkerCounter.CanPossiblyStoreInStockpile(this.bill, zone_Stockpile))
                                {
                                    list.Add(new FloatMenuOption(string.Format("{0} ({1})", string.Format(billStoreModeDef.LabelCap, group.parent.SlotYielderLabel()), "IncompatibleLower".Translate()), null, MenuOptionPriority.Default, null, null, 0f, null, null));
                                }
                                else
                                {
                                    list.Add(new FloatMenuOption(string.Format(billStoreModeDef.LabelCap, group.parent.SlotYielderLabel()), delegate()
                                    {
                                        this.bill.SetStoreMode(BillStoreModeDefOf.SpecificStockpile, (Zone_Stockpile)group.parent);
                                    }, MenuOptionPriority.Default, null, null, 0f, null, null));
                                }
                            }
                        }
                    }
                    else
                    {
                        BillStoreModeDef smLocal = billStoreModeDef;
                        list.Add(new FloatMenuOption(smLocal.LabelCap, delegate()
                        {
                            this.bill.SetStoreMode(smLocal, null);
                        }, MenuOptionPriority.Default, null, null, 0f, null, null));
                    }
                }
                Find.WindowStack.Add(new FloatMenu(list));
            }
            Text.Font = GameFont.Small;
            listing_Standard.EndSection(listing_Standard3);
            listing_Standard.Gap(12f);
            Listing_Standard listing_Standard4 = listing_Standard.BeginSection((float)Dialog_BillConfig.WorkerSelectionSubdialogHeight);

            Widgets.Dropdown <Bill_Production, Pawn>(listing_Standard4.GetRect(30f), this.bill, (Bill_Production b) => b.pawnRestriction, (Bill_Production b) => this.GeneratePawnRestrictionOptions(), (this.bill.pawnRestriction != null) ? this.bill.pawnRestriction.LabelShortCap : "AnyWorker".Translate(), null, null, null, null, false);
            if (this.bill.pawnRestriction == null && this.bill.recipe.workSkill != null)
            {
                listing_Standard4.Label("AllowedSkillRange".Translate(new object[]
                {
                    this.bill.recipe.workSkill.label
                }), -1f, null);
                listing_Standard4.IntRange(ref this.bill.allowedSkillRange, 0, 20);
            }
            listing_Standard.EndSection(listing_Standard4);
            listing_Standard.End();
            Rect rect5 = rect4;

            rect5.yMin = rect5.yMax - (float)Dialog_BillConfig.IngredientRadiusSubdialogHeight;
            rect4.yMax = rect5.yMin - 17f;
            bool flag = this.bill.GetStoreZone() == null || this.bill.recipe.WorkerCounter.CanPossiblyStoreInStockpile(this.bill, this.bill.GetStoreZone());

            ThingFilterUI.DoThingFilterConfigWindow(rect4, ref this.thingFilterScrollPosition, this.bill.ingredientFilter, this.bill.recipe.fixedIngredientFilter, 4, null, this.bill.recipe.forceHiddenSpecialFilters, this.bill.recipe.GetPremultipliedSmallIngredients(), this.bill.Map);
            bool flag2 = this.bill.GetStoreZone() == null || this.bill.recipe.WorkerCounter.CanPossiblyStoreInStockpile(this.bill, this.bill.GetStoreZone());

            if (flag && !flag2)
            {
                Messages.Message("MessageBillValidationStoreZoneInsufficient".Translate(new object[]
                {
                    this.bill.LabelCap,
                    this.bill.billStack.billGiver.LabelShort.CapitalizeFirst(),
                    this.bill.GetStoreZone().label
                }), this.bill.billStack.billGiver as Thing, MessageTypeDefOf.RejectInput, false);
            }
            Listing_Standard listing_Standard5 = new Listing_Standard();

            listing_Standard5.Begin(rect5);
            listing_Standard5.Label("IngredientSearchRadius".Translate() + ": " + ((this.bill.ingredientSearchRadius != 999f) ? this.bill.ingredientSearchRadius.ToString("F0") : "Unlimited".Translate()), -1f, null);
            this.bill.ingredientSearchRadius = listing_Standard5.Slider(this.bill.ingredientSearchRadius, 3f, 100f);
            if (this.bill.ingredientSearchRadius >= 100f)
            {
                this.bill.ingredientSearchRadius = 999f;
            }
            listing_Standard5.End();
            Listing_Standard listing_Standard6 = new Listing_Standard();

            listing_Standard6.Begin(rect2);
            if (this.bill.suspended)
            {
                if (listing_Standard6.ButtonText("Suspended".Translate(), null))
                {
                    this.bill.suspended = false;
                    SoundDefOf.Click.PlayOneShotOnCamera(null);
                }
            }
            else if (listing_Standard6.ButtonText("NotSuspended".Translate(), null))
            {
                this.bill.suspended = true;
                SoundDefOf.Click.PlayOneShotOnCamera(null);
            }
            StringBuilder stringBuilder = new StringBuilder();

            if (this.bill.recipe.description != null)
            {
                stringBuilder.AppendLine(this.bill.recipe.description);
                stringBuilder.AppendLine();
            }
            stringBuilder.AppendLine("WorkAmount".Translate() + ": " + this.bill.recipe.WorkAmountTotal(null).ToStringWorkAmount());
            for (int j = 0; j < this.bill.recipe.ingredients.Count; j++)
            {
                IngredientCount ingredientCount = this.bill.recipe.ingredients[j];
                if (!ingredientCount.filter.Summary.NullOrEmpty())
                {
                    stringBuilder.AppendLine(this.bill.recipe.IngredientValueGetter.BillRequirementsDescription(this.bill.recipe, ingredientCount));
                }
            }
            stringBuilder.AppendLine();
            string text5 = this.bill.recipe.IngredientValueGetter.ExtraDescriptionLine(this.bill.recipe);

            if (text5 != null)
            {
                stringBuilder.AppendLine(text5);
                stringBuilder.AppendLine();
            }
            if (!this.bill.recipe.skillRequirements.NullOrEmpty <SkillRequirement>())
            {
                stringBuilder.AppendLine("MinimumSkills".Translate());
                stringBuilder.AppendLine(this.bill.recipe.MinSkillString);
            }
            Text.Font = GameFont.Small;
            string text6 = stringBuilder.ToString();

            if (Text.CalcHeight(text6, rect2.width) > rect2.height)
            {
                Text.Font = GameFont.Tiny;
            }
            listing_Standard6.Label(text6, -1f, null);
            Text.Font = GameFont.Small;
            listing_Standard6.End();
            if (this.bill.recipe.products.Count == 1)
            {
                ThingDef thingDef = this.bill.recipe.products[0].thingDef;
                Widgets.InfoCardButton(rect2.x, rect4.y, thingDef, GenStuff.DefaultStuffFor(thingDef));
            }
        }
Ejemplo n.º 33
0
        static void Postfix()
        {
            if (Settings.AllowTechAdvance == true)
            {
                TechLevel currentTechLevel = Faction.OfPlayer.def.techLevel;
#if DEBUG
                Log.Warning("Tech Level: " + currentTechLevel);
#endif
                int totalCurrentAndPast = 0;
                int finishedResearch    = 0;

                foreach (ResearchProjectDef def in DefDatabase <ResearchProjectDef> .AllDefs)
                {
                    if (def.IsFinished)
                    {
                        ++finishedResearch;
                        //if (def.techLevel <= currentTechLevel)
                        //    ++finishedCurrentAndPast;
                        //else
                        //    ++finishedFuture;
                    }


                    if (def.techLevel <= currentTechLevel)
                    {
                        ++totalCurrentAndPast;
                    }
                }

                int  neededTechsToAdvance = 0;
                bool useStatisPerTier     = Settings.StaticNumberResearchPerTier;
                if (useStatisPerTier)
                {
                    switch (Faction.OfPlayer.def.techLevel)
                    {
                    case TechLevel.Neolithic:
                        neededTechsToAdvance = Settings.NeolithicNeeded;
                        break;

                    case TechLevel.Medieval:
                        neededTechsToAdvance = Settings.MedievalNeeded;
                        break;

                    case TechLevel.Industrial:
                        neededTechsToAdvance = Settings.IndustrialNeeded;
                        break;

                    case TechLevel.Spacer:
                        neededTechsToAdvance = Settings.SpacerNeeded;
                        break;
                    }
                }

#if DEBUG
                Log.Warning("Current Tech Level: " + Faction.OfPlayer.def.techLevel);
                Log.Warning("neededTechsToAdvance: " + neededTechsToAdvance);
                Log.Warning("totalCurrentAndPast: " + totalCurrentAndPast);
                Log.Warning("finishedResearch: " + finishedResearch);
#endif

                if ((useStatisPerTier && neededTechsToAdvance < finishedResearch) ||
                    (!useStatisPerTier && totalCurrentAndPast + 1 < finishedResearch))
                {
                    if (Faction.OfPlayer.def.techLevel < TechLevel.Spacer)
                    {
                        if (Scribe.mode == LoadSaveMode.Inactive)
                        {
                            // Only display this message is not loading
                            Messages.Message(
                                "Advancing Tech Level from [" + currentTechLevel.ToString() + "] to [" + (currentTechLevel + 1).ToString() + "].",
                                MessageTypeDefOf.PositiveEvent);
                        }

                        Faction.OfPlayer.def.techLevel = currentTechLevel + 1;
                    }
                }
                else
                {
                    int needed = (useStatisPerTier) ? neededTechsToAdvance - finishedResearch : totalCurrentAndPast + 1 - finishedResearch;
                    Log.Message("Tech Advance: Need to research [" + needed + "] more technologies");
                }
            }
            if (Settings.ChangeBaseCosts)
            {
                foreach (var cost in Settings.ResearchBaseCosts)
                {
                    var techDef = ResearchTimeUtil.GetResearchDef(cost.Key);
                    if (techDef != null)
                    {
                        techDef.baseCost = cost.Value;
                    }
                }
            }
        }
Ejemplo n.º 34
0
        private async void SendMessage()
        {
            if (string.IsNullOrWhiteSpace(MessageToSend) && AttachmentUploads.Count == 0)
            {
                return;
            }

            var message = MessageToSend?.Trim();

            MessageToSend = null;

            var newMessage = new Message(new VkMessage()
            {
                Body = message, IsOut = true, Date = DateTime.Now
            },
                                         ViewModelLocator.Main.CurrentUser);

            newMessage.IsNew = true;

            try
            {
                newMessage.IsSent = false;

                bool hasPendingUploads = AttachmentUploads.Any(a => a.IsUploading);
                bool isChat            = Dialog.Message.ChatId != 0;

                if (AttachmentUploads.Count > 0)
                {
                    if (hasPendingUploads)
                    {
                        await Task.Run(() => _uploadsEvent.Wait()); //ждем завершение загрузок
                    }
                    newMessage.MessageContent.Attachments = new List <VkAttachment>();

                    foreach (var attachment in AttachmentUploads)
                    {
                        if (attachment is PhotoAttachmentUpload)
                        {
                            var photo = (PhotoAttachmentUpload)attachment;

                            newMessage.MessageContent.Attachments.Add(new VkPhotoAttachment(photo.VkPhoto));
                        }
                        else if (attachment is DocumentAttachmentUpload)
                        {
                            var document = (DocumentAttachmentUpload)attachment;

                            newMessage.MessageContent.Attachments.Add(document.VkDocument);
                        }
                        else if (attachment is VideoAttachmentUpload)
                        {
                            var video = (VideoAttachmentUpload)attachment;

                            newMessage.MessageContent.Attachments.Add(new VkVideoAttachment(video.VkVideo));
                        }
                        else if (attachment is ForwardMessagesAttachmentUpload)
                        {
                            var forwardMessages = (ForwardMessagesAttachmentUpload)attachment;

                            newMessage.MessageContent.ForwardMessages = forwardMessages.Messages.Select(m => m.MessageContent).ToList();

                            long dialogId = isChat ? Dialog.Message.ChatId : Dialog.User.Profile.Id;
                            ForwardMessagesHelper.PendingForwardMessages[dialogId].Clear();
                            ForwardMessagesHelper.PendingForwardMessages[dialogId] = null;
                            ForwardMessagesHelper.PendingForwardMessages.Remove(dialogId);
                        }
                    }

                    AttachmentUploads.Clear();
                }

                Messages.Add(newMessage);
                _lastSentMessages.Add(newMessage);

                var newMessageId = await ServiceLocator.Vkontakte.Messages.Send(!isChat?Dialog.User.Profile.Id : 0, isChat?Dialog.Message.ChatId : 0, message, newMessage.MessageContent.Attachments, newMessage.MessageContent.ForwardMessages);

                newMessage.MessageContent.Id = newMessageId;
                newMessage.IsSent            = true;
                _lastSentMessages.Remove(newMessage);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Unable to send message");

                newMessage.IsFailed = true;
            }
        }
Ejemplo n.º 35
0
        public static string RestoreFromHistory(
            Context context, SiteSettings ss, long wikiId)
        {
            if (!Parameters.History.Restore)
            {
                return(Error.Types.InvalidRequest.MessageJson(context: context));
            }
            var wikiModel = new WikiModel(context, ss, wikiId);
            var invalid   = WikiValidators.OnUpdating(
                context: context,
                ss: ss,
                wikiModel: wikiModel);

            switch (invalid)
            {
            case Error.Types.None: break;

            default: return(invalid.MessageJson(context: context));
            }
            var ver = context.Forms.Data("GridCheckedItems")
                      .Split(',')
                      .Where(o => !o.IsNullOrEmpty())
                      .ToList();

            if (ver.Count() != 1)
            {
                return(Error.Types.SelectOne.MessageJson(context: context));
            }
            wikiModel.SetByModel(new WikiModel().Get(
                                     context: context,
                                     ss: ss,
                                     tableType: Sqls.TableTypes.History,
                                     where : Rds.WikisWhere()
                                     .SiteId(ss.SiteId)
                                     .WikiId(wikiId)
                                     .Ver(ver.First())));
            wikiModel.VerUp = true;
            var error = wikiModel.Update(
                context: context,
                ss: ss,
                otherInitValue: true);

            switch (error)
            {
            case Error.Types.None:
                SessionUtilities.Set(
                    context: context,
                    message: Messages.RestoredFromHistory(
                        context: context,
                        data: ver.First().ToString()));
                return(new ResponseCollection()
                       .SetMemory("formChanged", false)
                       .Href(Locations.ItemEdit(
                                 context: context,
                                 id: wikiId))
                       .ToJson());

            default:
                return(error.MessageJson(context: context));
            }
        }
Ejemplo n.º 36
0
 private void StartAssignStess(int diceRerolledCount)
 {
     Messages.ShowInfo(string.Format("Maul's Ability: You gain {0} stress tokens", diceRerolledCount));
     AssignStressRecursive(diceRerolledCount);
 }
Ejemplo n.º 37
0
 private void RollExtraDice(ref int count)
 {
     count++;
     Messages.ShowInfo("Defender is stressed. Roll 1 additional attack die.");
     HostShip.AfterGotNumberOfAttackDice -= RollExtraDice;
 }
Ejemplo n.º 38
0
        protected override void ReadCore(DateTime t1, DateTime t2)
        {
            try
            {
                var ws = new AwdbWebServiceClient();
                System.Net.ServicePointManager.Expect100Continue = false;
                //var ws = new AwdbWebService();

                var dur = duration.DAILY;


                if (NetworkFromTriplet(m_triplet) == "SNOW")
                {
                    dur = duration.SEMIMONTHLY;
                }



                var data = ws.getData(new string[] { m_triplet }, Parameter, 1, null,
                                      dur, true, t1.ToString("yyyy-MM-dd"), t2.ToString("yyyy-MM-dd"), false);

                Console.Write(Parameter + " " + "duration = " + dur + " " + m_triplet);
                Console.Write(" " + t1.ToString("yyyy-MM-dd"));
                Console.Write(" " + t2.ToString("yyyy-MM-dd"));


                if (data.Length == 0)
                {
                    return;
                }

                //Logger.WriteLine("data.Length ="+data.Length);
                if (data[0].beginDate == null)
                {
                    Logger.WriteLine("Error: no data at " + m_triplet);
                    return;
                }
                if (data[0].duration != dur)
                {
                    throw new InvalidOperationException("duration returned does not match requested");
                }

                if (data[0].values == null)
                {
                    Console.WriteLine("Error: data[0].vals == null ");
                }
                var vals = data[0].values;
                Console.WriteLine(" " + vals.Length + " records");
                // Logger.WriteLine("Values Length = "+vals.Length);

                var      flags = data[0].flags;
                DateTime t     = DateTime.Parse(data[0].beginDate).Date;

                for (int i = 0; i < vals.Count(); i++)
                {
                    if (vals[i].HasValue)
                    {
                        Add(t, Convert.ToDouble(vals[i].Value), flags[i]);
                    }
                    else
                    {
                        AddMissing(t);
                    }

                    if (dur == duration.DAILY)
                    {
                        t = t.AddDays(1);
                    }
                    else if (dur == duration.SEMIMONTHLY)
                    {
                        if (t.Date.Day == 1)
                        {
                            t = t.AddDays(15);
                        }
                        else
                        {
                            t = t.EndOfMonth().AddDays(1);
                        }
                        //Console.WriteLine(data[0].collectionDates[i]);
                        //t = DateTime.Parse(data[0].collectionDates[i]);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.WriteLine(e.Message + "\n" + e.StackTrace);
                Console.WriteLine(e.Message + "\n" + e.StackTrace);
                Messages.Add(e.Message);
                Clear();
            }
        }
Ejemplo n.º 39
0
 public virtual void AddMessage(string name)
 {
     Messages.Add(name);
 }
Ejemplo n.º 40
0
 public void Add(String message)
 {
     Messages.Add(message);
 }
Ejemplo n.º 41
0
        public void Read(string file)
        {
            Clear();

            FileInfo fi = new FileInfo(file);

            _Tokenizer = new FileTokenizer(file);
            bool eof       = false;
            bool havetoken = false;

            while (!eof)
            {
                try
                {
                    if (!havetoken)
                    {
                        eof = _Tokenizer.GetToken();
                    }
                    havetoken = false;

                    switch (_Tokenizer.Token.ToLower())
                    {
                        #region " Animation "
                    case CommandAnimation.Command:
                        CommandAnimation animation = new CommandAnimation();
                        _Tokenizer.GetToken();
                        animation.Name = _Tokenizer.Token;
                        _Tokenizer.GetToken();
                        animation.File = _Tokenizer.Token;
                        int anidepth = 0;
                        while (!_Tokenizer.GetToken())
                        {
                            // Ran into another command, get out.
                            if (_Tokenizer.Token.StartsWith("$"))
                            {
                                havetoken = true;
                                break;
                            }

                            switch (_Tokenizer.Token.ToLower())
                            {
                                #region " Depth "
                            case "{":
                                anidepth++;
                                break;

                            case "}":
                                anidepth--;
                                break;
                                #endregion

                                #region " Fps "
                            case OptionFps.Option:
                                _Tokenizer.GetToken();
                                animation.Fps = new OptionFps(Convert.ToSingle(_Tokenizer.Token));
                                break;
                                #endregion

                                #region " Loop "
                            case OptionLoop.Option:
                                animation.Loop = new OptionLoop(true);
                                break;
                                #endregion
                            }
                        }
                        _AnimationCollection.Add(animation);
                        break;
                        #endregion

                        #region " Attachment "
                    case CommandAttachment.Command:
                        CommandAttachment attach = new CommandAttachment();
                        _Tokenizer.GetToken();
                        attach.Name = _Tokenizer.Token;
                        _Tokenizer.GetToken();
                        attach.Bone = _Tokenizer.Token;
                        _Tokenizer.GetToken();
                        attach.Position.X = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        attach.Position.Y = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        attach.Position.Z = Convert.ToSingle(_Tokenizer.Token);
                        _AttachmentCollection.Add(attach);
                        break;
                        #endregion

                        #region " BBox "
                    case CommandBBox.Command:
                        _BBox = new CommandBBox();
                        _Tokenizer.GetToken();
                        _BBox.Min.X = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        _BBox.Min.Y = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        _BBox.Min.Z = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        _BBox.Max.X = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        _BBox.Max.Y = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        _BBox.Max.Z = Convert.ToSingle(_Tokenizer.Token);
                        break;
                        #endregion

                        #region " Body "
                    case CommandBody.Command:
                        CommandBody body = new CommandBody();
                        _Tokenizer.GetToken();
                        body.Name = _Tokenizer.Token;
                        _Tokenizer.GetToken();
                        body.File             = _Tokenizer.Token;
                        StaticMethods.SmdFile = fi.DirectoryName + "\\" + StaticMethods.StripExtension(body.File) + ".smd";
                        _BodyCollection.Add(body);
                        break;
                        #endregion

                        #region " Body Group "
                    case CommandBodyGroup.Command:
                        CommandBodyGroup bodygroup = new CommandBodyGroup();
                        _Tokenizer.GetToken();
                        bodygroup.Name = _Tokenizer.Token;
                        _Tokenizer.GetToken();
                        if (_Tokenizer.Token == "{")
                        {
                            while (true)
                            {
                                _Tokenizer.GetToken();
                                if (_Tokenizer.Token != "}")
                                {
                                    if (_Tokenizer.Token.ToLower() != "blank")
                                    {
                                        BodyGroupItem bgi = new BodyGroupItem();
                                        bgi.Name = _Tokenizer.Token;
                                        _Tokenizer.GetToken();
                                        bgi.File = _Tokenizer.Token;
                                        StaticMethods.SmdFile = fi.DirectoryName + "\\" + StaticMethods.StripExtension(bgi.File) + ".smd";
                                        bodygroup.BodyCollection.Add(bgi);
                                    }
                                    else
                                    {
                                        BodyGroupItem bgi = new BodyGroupItem();
                                        bgi.Name = _Tokenizer.Token;
                                        bodygroup.BodyCollection.Add(bgi);
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                        _BodyGroupCollection.Add(bodygroup);
                        break;
                        #endregion

                        #region " CBox "
                    case CommandCBox.Command:
                        _CBox = new CommandCBox();
                        _Tokenizer.GetToken();
                        _CBox.Min.X = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        _CBox.Min.Y = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        _CBox.Min.Z = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        _CBox.Max.X = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        _CBox.Max.Y = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        _CBox.Max.Z = Convert.ToSingle(_Tokenizer.Token);
                        break;
                        #endregion

                        #region " Cd "
                    case CommandCd.Command:
                        _Tokenizer.GetToken();
                        _Cd = new CommandCd(_Tokenizer.Token);
                        break;
                        #endregion

                        #region " Cd Texture "
                    case CommandCdTexture.Command:
                        _Tokenizer.GetToken();
                        _CdTexture = new CommandCdTexture(_Tokenizer.Token);
                        break;
                        #endregion

                        #region " Controller "
                    case CommandController.Command:
                        CommandController controller = new CommandController();
                        _Tokenizer.GetToken();
                        if (_Tokenizer.Token == "mouth")
                        {
                            controller.Index = 4;
                        }
                        else
                        {
                            controller.Index = Convert.ToInt32(_Tokenizer.Token);
                        }
                        _Tokenizer.GetToken();
                        controller.Bone = _Tokenizer.Token;
                        _Tokenizer.GetToken();
                        controller.Type = Enumerators.ToMotionFlags(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        controller.Start = Convert.ToInt32(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        controller.End = Convert.ToInt32(_Tokenizer.Token);
                        _ControllerCollection.Add(controller);
                        break;
                        #endregion

                        #region " Eye Position "
                    case CommandEyePosition.Command:
                        CommandEyePosition eyeposition = new CommandEyePosition();
                        _Tokenizer.GetToken();
                        eyeposition.Value.X = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        eyeposition.Value.Y = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        eyeposition.Value.Z = Convert.ToSingle(_Tokenizer.Token);
                        _EyePosition        = eyeposition;
                        break;
                        #endregion

                        #region " Flags "
                    case CommandFlags.Command:
                        _Tokenizer.GetToken();
                        _Flags = new CommandFlags((TypeFlag)Convert.ToInt32(_Tokenizer.Token));
                        break;
                        #endregion

                        #region " Gamma "
                    case CommandGamma.Command:
                        _Tokenizer.GetToken();
                        _Gamma = new CommandGamma(Convert.ToSingle(_Tokenizer.Token));
                        break;
                        #endregion

                        #region " HBox "
                    case CommandHBox.Command:
                        CommandHBox hbox = new CommandHBox();
                        _Tokenizer.GetToken();
                        hbox.Group = Convert.ToInt32(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        hbox.Bone = _Tokenizer.Token;
                        _Tokenizer.GetToken();
                        hbox.Min.X = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        hbox.Min.Y = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        hbox.Min.Z = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        hbox.Max.X = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        hbox.Max.Y = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        hbox.Max.Z = Convert.ToSingle(_Tokenizer.Token);
                        _HBoxCollection.Add(hbox);
                        break;
                        #endregion

                        #region " Mirror Bone "
                    case CommandMirrorBone.Command:
                        _Tokenizer.GetToken();
                        _MirrorBone = new CommandMirrorBone(_Tokenizer.Token);
                        break;
                        #endregion

                        #region " Model "
                    case CommandModel.Command:
                        CommandModel model = new CommandModel();
                        _Tokenizer.GetToken();
                        model.Name = _Tokenizer.Token;
                        _Tokenizer.GetToken();
                        model.File = _Tokenizer.Token;
                        _ModelCollection.Add(model);
                        break;
                        #endregion

                        #region " Model Name "
                    case CommandModelName.Command:
                        _Tokenizer.GetToken();
                        _ModelName = new CommandModelName(_Tokenizer.Token);
                        break;
                        #endregion

                        #region " Origin "
                    case CommandOrigin.Command:
                        CommandOrigin origin = new CommandOrigin();
                        _Tokenizer.GetToken();
                        origin.Value.X = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        origin.Value.Y = Convert.ToSingle(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        origin.Value.Z = Convert.ToSingle(_Tokenizer.Token);
                        _Origin        = origin;
                        break;
                        #endregion

                        #region " Pivot "
                    case CommandPivot.Command:
                        CommandPivot pivot = new CommandPivot();
                        _Tokenizer.GetToken();
                        pivot.Index = Convert.ToInt32(_Tokenizer.Token);
                        _Tokenizer.GetToken();
                        pivot.Bone = _Tokenizer.Token;
                        _Pivot     = pivot;
                        break;
                        #endregion

                        #region " Rename Bone "
                    case CommandRenameBone.Command:
                        CommandRenameBone renamebone = new CommandRenameBone();
                        _Tokenizer.GetToken();
                        renamebone.OldName = _Tokenizer.Token;
                        _Tokenizer.GetToken();
                        renamebone.NewName = _Tokenizer.Token;
                        break;
                        #endregion

                        #region " Root "
                    case CommandRoot.Command:
                        _Tokenizer.GetToken();
                        _Root = new CommandRoot(_Tokenizer.Token);
                        break;
                        #endregion

                        #region " Scale "
                    case CommandScale.Command:
                        _Tokenizer.GetToken();
                        _Scale = new CommandScale(Convert.ToSingle(_Tokenizer.Token));
                        break;
                        #endregion

                        #region " Sequence "
                    case CommandSequenceV44.Command:
                        CommandSequenceV44 sequence = new CommandSequenceV44();
                        _Tokenizer.GetToken();
                        sequence.Name = _Tokenizer.Token;
                        int seqdepth = 0;
                        while (!_Tokenizer.GetToken())
                        {
                            // Ran into another command, get out.
                            if (_Tokenizer.Token.StartsWith("$"))
                            {
                                havetoken = true;
                                break;
                            }

                            switch (_Tokenizer.Token.ToLower())
                            {
                                #region " Depth "
                            case "{":
                                seqdepth++;
                                break;

                            case "}":
                                seqdepth--;
                                break;
                                #endregion

                                #region " Animation "
                            case OptionAnimation.Option:
                                _Tokenizer.GetToken();
                                sequence.Animation = new OptionAnimation(_Tokenizer.Token);
                                break;
                                #endregion

                                #region " BlendWidth "
                            case OptionBlendWidth.Option:
                                _Tokenizer.GetToken();
                                sequence.BlendWidth = new OptionBlendWidth(Convert.ToInt32(_Tokenizer.Token));
                                break;
                                #endregion

                                #region " Blend "
                            case OptionBlend.Option:
                                OptionBlend blend = new OptionBlend();
                                _Tokenizer.GetToken();
                                blend.Type = Enumerators.ToMotionFlags(_Tokenizer.Token);
                                _Tokenizer.GetToken();
                                blend.Start = Convert.ToSingle(_Tokenizer.Token);
                                _Tokenizer.GetToken();
                                blend.End = Convert.ToSingle(_Tokenizer.Token);
                                sequence.BlendCollection.Add(blend);
                                break;
                                #endregion

                                #region " Event "
                            case OptionEvent.Option:
                                OptionEvent @event = new OptionEvent();
                                _Tokenizer.GetToken();
                                @event.EventValue = Convert.ToInt32(_Tokenizer.Token);
                                _Tokenizer.GetToken();
                                @event.Frame = Convert.ToInt32(_Tokenizer.Token);
                                _Tokenizer.GetToken();
                                @event.Options = _Tokenizer.Token;
                                sequence.EventCollection.Add(@event);
                                break;
                                #endregion

                                #region " Fps "
                            case OptionFps.Option:
                                _Tokenizer.GetToken();
                                sequence.Fps = new OptionFps(Convert.ToSingle(_Tokenizer.Token));
                                break;
                                #endregion

                                #region " Frame "
                            case OptionFrame.Option:
                                OptionFrame frame = new OptionFrame();
                                _Tokenizer.GetToken();
                                frame.Start = Convert.ToInt32(_Tokenizer.Token);
                                _Tokenizer.GetToken();
                                frame.End      = Convert.ToInt32(_Tokenizer.Token);
                                sequence.Frame = frame;
                                break;
                                #endregion

                                #region " Loop "
                            case OptionLoop.Option:
                                sequence.Loop = new OptionLoop(true);
                                break;
                                #endregion

                                #region " Node "
                            case OptionNodeV44.Option:
                                _Tokenizer.GetToken();
                                sequence.Node = new OptionNodeV44(_Tokenizer.Token);
                                break;
                                #endregion

                                #region " Pivot "
                            case OptionPivot.Option:
                                OptionPivot pivot2 = new OptionPivot();
                                _Tokenizer.GetToken();
                                pivot2.Index = Convert.ToInt32(_Tokenizer.Token);
                                _Tokenizer.GetToken();
                                pivot2.Start = Convert.ToInt32(_Tokenizer.Token);
                                _Tokenizer.GetToken();
                                pivot2.End = Convert.ToInt32(_Tokenizer.Token);
                                sequence.PivotCollection.Add(pivot2);
                                break;
                                #endregion

                                #region " Rotate "
                            case OptionRotate.Option:
                                _Tokenizer.GetToken();
                                sequence.Rotate = new OptionRotate(Convert.ToInt32(_Tokenizer.Token));
                                break;
                                #endregion

                                #region " RTransition "
                            case OptionRTransition.Option:
                                OptionRTransition rtransition = new OptionRTransition();
                                _Tokenizer.GetToken();
                                rtransition.EntryBone = Convert.ToInt32(_Tokenizer.Token);
                                _Tokenizer.GetToken();
                                rtransition.ExitBone = Convert.ToInt32(_Tokenizer.Token);
                                sequence.RTransition = rtransition;
                                break;
                                #endregion

                                #region " Scale "
                            case OptionScale.Option:
                                _Tokenizer.GetToken();
                                sequence.Scale = new OptionScale(Convert.ToSingle(_Tokenizer.Token));
                                break;
                                #endregion

                                #region " Transition "
                            case OptionTransition.Option:
                                OptionTransition transition = new OptionTransition();
                                _Tokenizer.GetToken();
                                transition.EntryBone = Convert.ToInt32(_Tokenizer.Token);
                                _Tokenizer.GetToken();
                                transition.ExitBone = Convert.ToInt32(_Tokenizer.Token);
                                sequence.Transition = transition;
                                break;
                                #endregion

                                #region " Control, Activity, and SMD "
                            default:
                                MotionFlags controltemp = Enumerators.ToMotionFlags(_Tokenizer.Token);
                                ActivityV44 activitytemp;
                                try { activitytemp = (ActivityV44)Enum.Parse(typeof(ActivityV44), _Tokenizer.Token); }
                                catch (ArgumentException) { activitytemp = ActivityV44.ACT_INVALID; }

                                if (controltemp != MotionFlags.Invalid)
                                {
                                    sequence.Control.Flags |= controltemp;
                                }
                                else if (activitytemp != ActivityV44.ACT_INVALID)
                                {
                                    OptionActivityV44 activity = new OptionActivityV44();
                                    activity.Activity = activitytemp;
                                    _Tokenizer.GetToken();
                                    activity.ActivityWeight = Convert.ToSingle(_Tokenizer.Token);
                                    sequence.Activity       = activity;
                                }
                                else
                                {
                                    StaticMethods.SmdFile = fi.DirectoryName + "\\" + StaticMethods.StripExtension(_Tokenizer.Token) + ".smd";
                                    sequence.FileCollection.Add(_Tokenizer.Token);
                                }
                                break;
                                #endregion
                            }
                        }
                        _SequenceCollection.Add(sequence);
                        break;
                        #endregion

                        #region " Texture Group "
                    case CommandTextureGroup.Command:
                        CommandTextureGroup texturegroup = new CommandTextureGroup();
                        _Tokenizer.GetToken();
                        texturegroup.Name = _Tokenizer.Token;
                        int           depth      = 0;
                        List <string> references = new List <string>();

                        while (!_Tokenizer.GetToken())
                        {
                            if (_Tokenizer.Token == "{")
                            {
                                depth++;
                            }
                            else if (_Tokenizer.Token == "}")
                            {
                                depth--;
                                if (depth == 0)
                                {
                                    break;
                                }
                                texturegroup.SkinCollection.Add(references);
                                references = new List <string>();
                            }
                            else if (depth == 2)
                            {
                                references.Add(_Tokenizer.Token);
                            }
                        }
                        break;
                        #endregion

                        #region " Default "
                    default:
                        if (_Tokenizer.Token.StartsWith("$"))
                        {
                            _OmittedCommands.Add(new OmittedCommand(_Tokenizer.Line, _Tokenizer.Token));
                        }
                        break;
                        #endregion
                    }
                }
                catch (Exception e)
                {
                    Messages.ThrowException("Qc.QcFileV44.Read(string)", e.Message + " (" + Messages.LINE + _Tokenizer.Line + ", " + Messages.TOKEN + _Tokenizer.Token + ")");
                }
            }
        }
Ejemplo n.º 42
0
        private void SetMessage(Exception exception)
        {
            string title   = String.Empty;
            string message = exception.Message;

            // Erreur Vidéotron
            if (exception is VideotronException)
            {
                VideotronException videotronException = exception as VideotronException;
                if (videotronException.Status == VideotronExceptionStatus.AuthentificationFailed)
                {
                    title = CIV.strings.ClientDashboard_AuthentificationFailedException;
                }
                else if (videotronException.Status == VideotronExceptionStatus.ResponseEmpty)
                {
                    title = CIV.strings.ClientDashboard_WebResponseException;
                }
            }

            // Erreur de décodage
            else if (exception is DecodeFailedException)
            {
                title = CIV.strings.ClientDashboard_DecodeFailedException;

                // Traduire le message d'erreur pour l'utilisateur
                switch ((exception as DecodeFailedException).Type)
                {
                case DecodeFailedTypes.Download:
                    message = strings.DecodeDownload;
                    break;

                case DecodeFailedTypes.Upload:
                    message = strings.DecodeUpload;
                    break;

                case DecodeFailedTypes.Unit:
                    message = strings.DecodeUnit;
                    break;

                case DecodeFailedTypes.TotalCombined:
                    message = strings.DecodeTotalCombined;
                    break;

                case DecodeFailedTypes.ShowPeriods:
                    message = strings.DecodeShowPeriods;
                    break;

                case DecodeFailedTypes.BillPeriods:
                    message = strings.DecodeBillPeriods;
                    break;

                case DecodeFailedTypes.History:
                    message = strings.DecodeHistory;
                    break;

                case DecodeFailedTypes.Unexpected:
                    message = strings.DecodeUnexpected;
                    break;
                }
            }
            else if (exception.Message.Length > 70)
            {
                title = String.Format("{0}...", exception.Message.Substring(0, 70));
            }
            else
            {
                title = exception.Message;
            }

            Messages.Add(new ScreenMessage(title, String.Format("{0}\r\n{1}", exception.GetType(), message), ScreenMessageType.Exception));

            imgInformation.Visibility = System.Windows.Visibility.Visible;

            lblStatus.Text = title;
        }
Ejemplo n.º 43
0
        private void Arrived()
        {
            if (this.arrived)
            {
                return;
            }

            this.arrived = true;
            if (TravelingShipsUtility.TryAddToLandedFleet(this, this.destinationTile))
            {
                return;
            }
            if (this.arrivalAction == TravelingShipArrivalAction.BombingRun)
            {
                MapParent parent = Find.World.worldObjects.MapParentAt(this.destinationTile);
                if (parent != null)
                {
                    Messages.Message("MessageBombedSettlement".Translate(new object[] { parent.ToString(), parent.Faction.Name }), parent, MessageTypeDefOf.NeutralEvent);
                    Find.World.worldObjects.Remove(parent);
                }
                this.SwitchOriginToDest();

                //TravelingShips travelingShips = (TravelingShips)WorldObjectMaker.MakeWorldObject(ShipNamespaceDefOfs.TravelingSuborbitalShip);
                //travelingShips.ships.AddRange(this.ships);
                //travelingShips.Tile = this.destinationTile;
                //travelingShips.SetFaction(Faction.OfPlayer);
                //travelingShips.destinationTile = this.initialTile;
                //travelingShips.destinationCell = this.launchCell;
                //travelingShips.arriveMode = this.arriveMode;
                //travelingShips.arrivalAction = TravelingShipArrivalAction.EnterMapFriendly;
                //Find.WorldObjects.Add(travelingShips);
                //Find.WorldObjects.Remove(this);
            }
            else
            {
                Map map = Current.Game.FindMap(this.destinationTile);
                if (map != null)
                {
                    this.SpawnShipsInMap(map, null);
                }
                else if (!this.LandedShipHasCaravanOwner)
                {
                    for (int i = 0; i < this.ships.Count; i++)
                    {
                        this.ships[i].GetDirectlyHeldThings().ClearAndDestroyContentsOrPassToWorld(DestroyMode.Vanish);
                    }
                    this.RemoveAllPods();
                    Find.WorldObjects.Remove(this);
                    Messages.Message("MessageTransportPodsArrivedAndLost".Translate(), new GlobalTargetInfo(this.destinationTile), MessageTypeDefOf.NegativeEvent);
                }
                else
                {
                    FactionBase factionBase = Find.WorldObjects.FactionBases.Find((FactionBase x) => x.Tile == this.destinationTile);
                    
                    if (factionBase != null && factionBase.Faction != Faction.OfPlayer && this.arrivalAction != TravelingShipArrivalAction.StayOnWorldMap)
                    {
                        LongEventHandler.QueueLongEvent(delegate
                        {
                            Map map2 = GetOrGenerateMapUtility.GetOrGenerateMap(factionBase.Tile, Find.World.info.initialMapSize, null); ;
                            
                            string extraMessagePart = null;
                            if (this.arrivalAction == TravelingShipArrivalAction.EnterMapAssault && !factionBase.Faction.HostileTo(Faction.OfPlayer))
                            {
                                factionBase.Faction.SetHostileTo(Faction.OfPlayer, true);
                                extraMessagePart = "MessageTransportPodsArrived_BecameHostile".Translate(new object[]
                                {
                                factionBase.Faction.Name
                                }).CapitalizeFirst();
                            }
                            Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
                            Current.Game.VisibleMap = map2;
                            Find.CameraDriver.JumpToVisibleMapLoc(map2.Center);
                            this.SpawnShipsInMap(map2, extraMessagePart);
                        }, "GeneratingMapForNewEncounter", false, null);
                    }
                    else
                    {
                        this.SpawnCaravanAtDestinationTile();
                    }
                }
            }
        }
Ejemplo n.º 44
0
        protected void ImportXmlTemplates(XElement root)
        {
            Log.Add("import xml templates");
            var templates = root.Element(XmlConstants.Templates);

            if (templates == null)
            {
                return;
            }

            //var appState = DataSource.GetCache(DataSource.GetIdentity(ZoneId, AppId));
            //var cache = Factory.Resolve<IAppsCache>();
            var appState = /*Factory.GetAppState*/ Eav.Apps.State.Get(new AppIdentity(ZoneId, AppId));

            foreach (var template in templates.Elements(XmlConstants.Template))
            {
                var name = "";
                try
                {
                    name = template.Attribute(XmlConstants.Name).Value;
                    var path = template.Attribute(View.FieldPath).Value;

                    var contentTypeStaticName = template.Attribute(XmlConstants.AttSetStatic).Value;

                    Log.Add($"template:{name}, type:{contentTypeStaticName}, path:{path}");

                    if (!string.IsNullOrEmpty(contentTypeStaticName) && appState.GetContentType(contentTypeStaticName) == null)
                    {
                        Messages.Add(new Message($"Content Type for Template \'{name}\' could not be found. The template has not been imported.",
                                                 Message.MessageTypes.Warning));
                        continue;
                    }

                    var demoEntityGuid = template.Attribute(XmlConstants.TemplateDemoItemGuid).Value;
                    var demoEntityId   = new int?();

                    if (!String.IsNullOrEmpty(demoEntityGuid))
                    {
                        var entityGuid = Guid.Parse(demoEntityGuid);
                        if (RepositoryHasEntity(entityGuid))
                        {
                            demoEntityId = GetLatestRepositoryId(entityGuid);//.EntityId;
                        }
                        else
                        {
                            Messages.Add(new Message($"Demo Entity for Template \'{name}\' could not be found. (Guid: {demoEntityGuid})", Message.MessageTypes.Information));
                        }
                    }

                    var type        = template.Attribute(XmlConstants.EntityTypeAttribute).Value;
                    var isHidden    = Boolean.Parse(template.Attribute(View.FieldIsHidden).Value);
                    var location    = template.Attribute(View.FieldLocation).Value;
                    var publishData =
                        Boolean.Parse(template.Attribute(View.FieldPublishEnable) == null
                            ? "False"
                            : template.Attribute(View.FieldPublishEnable).Value);
                    var streamsToPublish = template.Attribute(View.FieldPublishStreams) == null
                        ? ""
                        : template.Attribute(View.FieldPublishStreams).Value;
                    var viewNameInUrl = template.Attribute(View.FieldNameInUrl) == null
                        ? null
                        : template.Attribute(View.FieldNameInUrl).Value;

                    var queryEntityGuid = template.Attribute(XmlConstants.TemplateQueryGuidField);
                    var queryEntityId   = new int?();

                    if (!String.IsNullOrEmpty(queryEntityGuid?.Value))
                    {
                        var entityGuid = Guid.Parse(queryEntityGuid.Value);
                        if (RepositoryHasEntity(entityGuid))
                        {
                            queryEntityId = GetLatestRepositoryId(entityGuid);//.EntityId;
                        }
                        else
                        {
                            Messages.Add(new Message($"Query Entity for Template \'{name}\' could not be found. (Guid: {queryEntityGuid.Value})", Message.MessageTypes.Information));
                        }
                    }

                    var useForList = false;
                    if (template.Attribute(View.FieldUseList) != null)
                    {
                        useForList = Boolean.Parse(template.Attribute(View.FieldUseList).Value);
                    }

                    var lstTemplateDefaults = template.Elements(XmlConstants.Entity).Select(e =>
                    {
                        var xmlItemType =
                            e.Elements(XmlConstants.ValueNode)
                            .FirstOrDefault(v =>
                                            v.Attribute(XmlConstants.KeyAttr).Value == XmlConstants.TemplateItemType)?
                            .Attribute(XmlConstants.ValueAttr)
                            .Value;
                        var xmlContentTypeStaticName =
                            e.Elements(XmlConstants.ValueNode)
                            .FirstOrDefault(v =>
                                            v.Attribute(XmlConstants.KeyAttr).Value == XmlConstants.TemplateContentTypeId)?
                            .Attribute(XmlConstants.ValueAttr)
                            .Value;
                        var xmlDemoEntityGuidString =
                            e.Elements(XmlConstants.ValueNode)
                            .FirstOrDefault(v =>
                                            v.Attribute(XmlConstants.KeyAttr).Value == XmlConstants.TemplateDemoItemId)?
                            .Attribute(XmlConstants.ValueAttr)
                            .Value;
                        if (xmlItemType == null || xmlContentTypeStaticName == null || xmlDemoEntityGuidString == null)
                        {
                            Messages.Add(new Message(
                                             $"trouble with template '{name}' - either type, static or guid are null",
                                             Message.MessageTypes.Error));
                            return(null);
                        }
                        var xmlDemoEntityId = new int?();
                        if (xmlDemoEntityGuidString != "0" && xmlDemoEntityGuidString != "")
                        {
                            var xmlDemoEntityGuid = Guid.Parse(xmlDemoEntityGuidString);
                            if (RepositoryHasEntity(xmlDemoEntityGuid))
                            {
                                xmlDemoEntityId = GetLatestRepositoryId(xmlDemoEntityGuid);
                            }
                        }

                        return(new TemplateDefault
                        {
                            ItemType = xmlItemType,
                            ContentTypeStaticName =
                                xmlContentTypeStaticName == "0" || xmlContentTypeStaticName == ""
                                    ? ""
                                    : xmlContentTypeStaticName,
                            DemoEntityId = xmlDemoEntityId
                        });
                    }).ToList();

                    // note: Array lstTemplateDefaults has null objects, so remove null objects
                    var templateDefaults = lstTemplateDefaults.Where(lstItem => lstItem != null).ToList();

                    var presentationTypeStaticName = "";
                    var presentationDemoEntityId   = new int?();
                    //if list templateDefaults would have null objects, we would have an exception
                    var presentationDefault = templateDefaults.FirstOrDefault(t => t.ItemType == ViewParts.Presentation);
                    if (presentationDefault != null)
                    {
                        presentationTypeStaticName = presentationDefault.ContentTypeStaticName;
                        presentationDemoEntityId   = presentationDefault.DemoEntityId;
                    }

                    var listContentTypeStaticName = "";
                    var listContentDemoEntityId   = new int?();
                    var listContentDefault        = templateDefaults.FirstOrDefault(t => t.ItemType == ViewParts.ListContent);
                    if (listContentDefault != null)
                    {
                        listContentTypeStaticName = listContentDefault.ContentTypeStaticName;
                        listContentDemoEntityId   = listContentDefault.DemoEntityId;
                    }

                    var listPresentationTypeStaticName = "";
                    var listPresentationDemoEntityId   = new int?();
                    var listPresentationDefault        = templateDefaults.FirstOrDefault(t => t.ItemType == ViewParts.ListPresentation);
                    if (listPresentationDefault != null)
                    {
                        listPresentationTypeStaticName = listPresentationDefault.ContentTypeStaticName;
                        listPresentationDemoEntityId   = listPresentationDefault.DemoEntityId;
                    }

                    new CmsManager(GetCurrentAppManager(), true, false, Log).Views
                    .CreateOrUpdate(
                        null, name, path, contentTypeStaticName, demoEntityId, presentationTypeStaticName,
                        presentationDemoEntityId, listContentTypeStaticName, listContentDemoEntityId,
                        listPresentationTypeStaticName, listPresentationDemoEntityId, type, isHidden, location,
                        useForList, publishData, streamsToPublish, queryEntityId, viewNameInUrl);

                    Messages.Add(new Message($"Template \'{name}\' successfully imported.",
                                             Message.MessageTypes.Information));
                }

                catch (Exception)
                {
                    Messages.Add(new Message($"Import for template \'{name}\' failed.",
                                             Message.MessageTypes.Information));
                }
            }
            Log.Add("import xml templates - completed");
        }
Ejemplo n.º 45
0
 void AddMessageInternal(string message)
 {
     Messages.Add(message);
     CurrentLine = message;
 }
Ejemplo n.º 46
0
 private void ClearLog()
 {
     Messages.Clear();
     BinaryMessages.Clear();
 }
Ejemplo n.º 47
0
        /// <summary>
        /// Callback method called upon the delegate timer.  Rebuilds the list
        /// or appends new entries based upon the state of <c>clearPending</c>,
        /// <c>rebuildList</c> or the <c>pendingActions</c> collection containing
        /// entries.
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Argument for the timer callback.</param>
        private void UpdateTick(object sender, EventArgs e)
        {
            if (Logger == null)
            {
                return;
            }

            if (clearPending || rebuildList)
            {
                // If rebuilding the list, any additions to the pendingAdditions
                // made since the "rebuildList" variable was set to true will
                // not be needed, throw them away to avoid duplication.
                lock (pendingAdditions)
                {
                    pendingAdditions.Clear();
                }

                lock (Messages)
                {
                    Messages.Clear();

                    lock (Logger.Entries)
                    {
                        if (clearPending)
                        {
                            Logger.Clear();
                        }

                        foreach (var entry in Logger.Entries)
                        {
                            AddIfPassesFilters(entry);
                        }
                    }
                }

                // Reset the counters.
                FilteredCount   = 0;
                UnfilteredCount = 0;

                rebuildList = clearPending = false;
            }
            else if (pendingAdditions.Count > 0)
            {
                lock (pendingAdditions)
                {
                    lock (Messages)
                    {
                        while (pendingAdditions.Count > 0)
                        {
                            var entry = pendingAdditions.Dequeue();
                            AddIfPassesFilters(entry);
                        }
                    }
                }

                if (autoscroll)
                {
                    presenter.ScrollToEnd();
                }
            }

            FilteredCount   = Messages.Count;
            UnfilteredCount = Logger.Entries.Count();
        }
Ejemplo n.º 48
0
 private static ResponseCollection ResponseByUpdate(
     WikisResponseCollection res,
     Context context,
     SiteSettings ss,
     WikiModel wikiModel)
 {
     if (context.Forms.Bool("IsDialogEditorForm"))
     {
         var view = Views.GetBySession(
             context: context,
             ss: ss,
             setSession: false);
         var gridData = new GridData(
             context: context,
             ss: ss,
             view: view,
             where : Rds.WikisWhere().WikiId(wikiModel.WikiId));
         var columns = ss.GetGridColumns(
             context: context,
             checkPermission: true);
         return(res
                .ReplaceAll(
                    $"[data-id=\"{wikiModel.WikiId}\"]",
                    gridData.TBody(
                        hb: new HtmlBuilder(),
                        context: context,
                        ss: ss,
                        columns: columns,
                        checkAll: false))
                .CloseDialog()
                .Message(Messages.Updated(
                             context: context,
                             data: wikiModel.Title.DisplayValue)));
     }
     else
     {
         return(res
                .Ver(context: context, ss: ss)
                .Timestamp(context: context, ss: ss)
                .FieldResponse(context: context, ss: ss, wikiModel: wikiModel)
                .Val("#VerUp", false)
                .Disabled("#VerUp", false)
                .Html("#HeaderTitle", wikiModel.Title.DisplayValue)
                .Html("#RecordInfo", new HtmlBuilder().RecordInfo(
                          context: context,
                          baseModel: wikiModel,
                          tableName: "Wikis"))
                .Html("#Links", new HtmlBuilder().Links(
                          context: context,
                          ss: ss,
                          id: wikiModel.WikiId))
                .SetMemory("formChanged", false)
                .Message(Messages.Updated(
                             context: context,
                             data: wikiModel.Title.DisplayValue))
                .Comment(
                    context: context,
                    ss: ss,
                    column: ss.GetColumn(context: context, columnName: "Comments"),
                    comments: wikiModel.Comments,
                    deleteCommentId: wikiModel.DeleteCommentId)
                .ClearFormData());
     }
 }
Ejemplo n.º 49
0
        public static void SetPlayerSquadFromImportedJson(string name, JSONObject squadJson, PlayerNo playerNo, Action callBack)
        {
            ClearShipsOfPlayer(playerNo);

            try
            {
                SquadList squadList = GetSquadList(playerNo);

                if (squadJson.HasField("name"))
                {
                    squadList.Name = squadJson["name"].str;
                }

                string  factionNameXws = squadJson["faction"].str;
                Faction faction        = XWSToFaction(factionNameXws);
                squadList.SquadFaction = faction;

                squadList.Points = (int)squadJson["points"].i;

                if (squadJson.HasField("pilots"))
                {
                    JSONObject pilotJsons = squadJson["pilots"];
                    foreach (JSONObject pilotJson in pilotJsons.list)
                    {
                        string shipNameXws     = pilotJson["ship"].str;
                        string shipNameGeneral = AllShips.Find(n => n.ShipNameCanonical == shipNameXws).ShipName;

                        string pilotNameXws = pilotJson["name"].str;
                        if (!AllPilots.Any(n => n.PilotNameCanonical == pilotNameXws))
                        {
                            Debug.Log("Cannot find pilot: " + pilotNameXws);
                            Console.Write("Cannot find pilot: " + pilotNameXws, LogTypes.Errors, true, "red");
                        }
                        string pilotNameGeneral = AllPilots.Find(n => n.PilotNameCanonical == pilotNameXws).PilotName;

                        PilotRecord pilotRecord     = AllPilots.Find(n => n.PilotName == pilotNameGeneral && n.PilotShip.ShipName == shipNameGeneral && n.PilotFaction == faction);
                        GenericShip newShipInstance = (GenericShip)Activator.CreateInstance(Type.GetType(pilotRecord.PilotTypeName));
                        Edition.Current.AdaptShipToRules(newShipInstance);
                        SquadBuilderShip newShip = AddPilotToSquad(newShipInstance, playerNo);

                        List <string> upgradesThatCannotBeInstalled = new List <string>();

                        JSONObject upgradeJsons = pilotJson["upgrades"];
                        foreach (string upgradeType in upgradeJsons.keys)
                        {
                            JSONObject upgradeNames = upgradeJsons[upgradeType];
                            foreach (JSONObject upgradeRecord in upgradeNames.list)
                            {
                                if (!AllUpgrades.Any(n => n.UpgradeNameCanonical == upgradeRecord.str))
                                {
                                    Debug.Log("Cannot find upgrade: " + upgradeRecord.str);
                                    Console.Write("Cannot find upgrade: " + upgradeRecord.str, LogTypes.Errors, true, "red");
                                }
                                string upgradeName = AllUpgrades.Find(n => n.UpgradeNameCanonical == upgradeRecord.str).UpgradeName;
                                bool   upgradeInstalledSucessfully = InstallUpgrade(newShip, upgradeName);
                                if (!upgradeInstalledSucessfully)
                                {
                                    upgradesThatCannotBeInstalled.Add(upgradeName);
                                }
                            }
                        }

                        while (upgradeJsons.Count != 0)
                        {
                            List <string> upgradesThatCannotBeInstalledCopy = new List <string>(upgradesThatCannotBeInstalled);

                            bool wasSuccess = false;
                            foreach (var upgradeName in upgradesThatCannotBeInstalledCopy)
                            {
                                bool upgradeInstalledSucessfully = InstallUpgrade(newShip, upgradeName);
                                if (upgradeInstalledSucessfully)
                                {
                                    wasSuccess = true;
                                    upgradesThatCannotBeInstalled.Remove(upgradeName);
                                }
                            }

                            if (!wasSuccess)
                            {
                                break;
                            }
                        }

                        if (pilotJson.HasField("vendor"))
                        {
                            JSONObject vendorData = pilotJson["vendor"];
                            if (vendorData.HasField("Sandrem.FlyCasual"))
                            {
                                JSONObject myVendorData = vendorData["Sandrem.FlyCasual"];
                                if (myVendorData.HasField("skin"))
                                {
                                    newShip.Instance.ModelInfo.SkinName = myVendorData["skin"].str;
                                }
                            }
                        }
                    }
                }
                else
                {
                    Messages.ShowError("No pilots");
                }

                callBack();
            }
            catch (Exception)
            {
                Messages.ShowError("Error during creation of squadron '" + name + "'");
                ClearShipsOfPlayer(playerNo);
                //throw;
            }
        }
Ejemplo n.º 50
0
        /// <summary>
        /// 생성자
        /// </summary>
        public WtlPipeListViewModel()
        {
            LoadedCommand = new DelegateCommand <object>(OnLoaded);
            SearchCommand = new DelegateCommand <object>(SearchAction);
            ResetCommand  = new DelegateCommand <object>(ResetAction);
            ExcelCmd      = new DelegateCommand <object>(ExcelDownAction);

            // 시설물 지도상 위치찾아가기
            cellPosCmd = new DelegateCommand <object>(delegate(object obj) {
                DataRowView row    = obj as DataRowView;
                string FTR_IDN     = row["FTR_IDN"].ToString();
                string FTR_CDE     = row["FTR_CDE"].ToString();
                string IS_GEOMETRY = row["IS_GEOMETRY"].ToString();

                //MessageBox.Show("지도상 위치찾아가기..FTR_IDN - " + FTR_IDN + ", FTR_CDE - " + FTR_CDE);

                if ("IS_GEOMETRY".Equals(IS_GEOMETRY))
                {
                    Messages.ShowInfoMsgBox("시설물 위치정보가 없습니다.");
                    return;
                }


                IRegionManager regionManager = FmsUtil.__regionManager;
                ViewsCollection views        = regionManager.Regions["ContentRegion"].ActiveViews as ViewsCollection;

                //MapMainViewMocel 인스턴스불러오기
                foreach (var v in views)
                {
                    MapArcObjView mapMainView = v as MapArcObjView;
                    MapArcObjViewModel vm     = mapMainView.DataContext as MapArcObjViewModel;

                    //Find 메소드수행
                    vm.findFtr(FTR_CDE, FTR_IDN);
                    break;
                }
            });



            // 조회데이터 초기화
            this.PagedCollection = new ObservableCollection <DataTable>();
            // 프로퍼티변경이벤트 처리핸들러 등록
            PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
            {
                switch (e.PropertyName)
                {
                case "PageIndex":
                    if (PageIndex < 0)     //초기이벤트는 걸른다
                    {
                        this.pageIndex = 0;
                    }
                    else
                    {
                        SearchAction(PageIndex);
                    }
                    break;

                default:
                    break;
                }
            };
        }
Ejemplo n.º 51
0
        public static bool RunlUpdate(VCFile vcFile, EnvDTE.Project pro)
        {
            if (!HelperFunctions.IsQtProject(pro))
            {
                return(false);
            }

            string cmdLine = "";
            string options = QtVSIPSettings.GetLUpdateOptions(pro);

            if (!string.IsNullOrEmpty(options))
            {
                cmdLine += options + " ";
            }
            List <string> headers = HelperFunctions.GetProjectFiles(pro, FilesToList.FL_HFiles);
            List <string> sources = HelperFunctions.GetProjectFiles(pro, FilesToList.FL_CppFiles);
            List <string> uifiles = HelperFunctions.GetProjectFiles(pro, FilesToList.FL_UiFiles);

            foreach (string file in headers)
            {
                cmdLine += file + " ";
            }

            foreach (string file in sources)
            {
                cmdLine += file + " ";
            }

            foreach (string file in uifiles)
            {
                cmdLine += file + " ";
            }

            cmdLine += "-ts " + vcFile.RelativePath;

            int    cmdLineLength    = cmdLine.Length + Resources.lupdateCommand.Length + 1;
            string temporaryProFile = null;

            if (cmdLineLength > HelperFunctions.GetMaximumCommandLineLength())
            {
                string codec = "";
                if (!string.IsNullOrEmpty(options))
                {
                    int cc4tr_location = options.IndexOf("-codecfortr", System.StringComparison.CurrentCultureIgnoreCase);
                    if (cc4tr_location != -1)
                    {
                        codec = options.Substring(cc4tr_location).Split(' ')[1];
                        string remove_this = options.Substring(cc4tr_location, "-codecfortr".Length + 1 + codec.Length);
                        options = options.Replace(remove_this, "");
                    }
                }
                VCProject vcPro = (VCProject)pro.Object;
                temporaryProFile = System.IO.Path.GetTempFileName();
                temporaryProFile = System.IO.Path.GetDirectoryName(temporaryProFile) + "\\" +
                                   System.IO.Path.GetFileNameWithoutExtension(temporaryProFile) + ".pro";
                if (System.IO.File.Exists(temporaryProFile))
                {
                    System.IO.File.Delete(temporaryProFile);
                }
                System.IO.StreamWriter sw = new System.IO.StreamWriter(temporaryProFile);
                writeFilesToPro(sw, "HEADERS",
                                ProjectExporter.ConvertFilesToFullPath(headers, vcPro.ProjectDirectory));
                writeFilesToPro(sw, "SOURCES",
                                ProjectExporter.ConvertFilesToFullPath(sources, vcPro.ProjectDirectory));
                writeFilesToPro(sw, "FORMS",
                                ProjectExporter.ConvertFilesToFullPath(uifiles, vcPro.ProjectDirectory));

                List <string> tsFiles = new List <string>(1);
                tsFiles.Add(vcFile.FullPath);
                writeFilesToPro(sw, "TRANSLATIONS", tsFiles);

                if (!string.IsNullOrEmpty(codec))
                {
                    sw.WriteLine("CODECFORTR = " + codec);
                }
                sw.Close();

                cmdLine = "";
                if (!string.IsNullOrEmpty(options))
                {
                    cmdLine += options + " ";
                }
                cmdLine += "\"" + temporaryProFile + "\"";
            }

            bool success = true;

            try
            {
                Messages.PaneMessage(pro.DTE, "--- (lupdate) file: " + vcFile.FullPath);

                HelperFunctions.StartExternalQtApplication(Resources.lupdateCommand, cmdLine,
                                                           ((VCProject)vcFile.project).ProjectDirectory, pro, true, null);
            }
            catch (QtVSException e)
            {
                success = false;
                Messages.DisplayErrorMessage(e.Message);
            }

            if (temporaryProFile != null && System.IO.File.Exists(temporaryProFile))
            {
                System.IO.File.Delete(temporaryProFile);
                temporaryProFile  = temporaryProFile.Substring(0, temporaryProFile.Length - 3);
                temporaryProFile += "TMP";
                if (System.IO.File.Exists(temporaryProFile))
                {
                    System.IO.File.Delete(temporaryProFile);
                }
            }

            return(success);
        }
Ejemplo n.º 52
0
        /// <summary>
        /// 조회
        /// </summary>
        /// <param name="obj"></param>
        private void SearchAction(object obj)
        {
            try
            {
                //if (treeList.FocusedNode == null) return;

                Hashtable conditions = new Hashtable();
                conditions.Add("MNG_CDE", cbMNG_CDE.EditValue);
                conditions.Add("HJD_CDE", cbHJD_CDE.EditValue);
                conditions.Add("MOP_CDE", cbMOP_CDE.EditValue);
                conditions.Add("JHT_CDE", cbJHT_CDE.EditValue);
                conditions.Add("FTR_IDN", FmsUtil.Trim(txtFTR_IDN.EditValue));
                conditions.Add("CNT_NUM", txtCNT_NUM.Text.Trim());
                conditions.Add("SHT_NUM", txtSHT_NUM.Text.Trim());
                conditions.Add("PIP_DIP", txtPIP_DIP.Text.Trim());
                try
                {
                    conditions.Add("IST_YMD_FROM", dtIST_YMD_FROM.EditValue == null ? null : Convert.ToDateTime(dtIST_YMD_FROM.EditValue).ToString("yyyyMMdd"));
                    conditions.Add("IST_YMD_TO", dtIST_YMD_TO.EditValue == null ? null : Convert.ToDateTime(dtIST_YMD_TO.EditValue).ToString("yyyyMMdd"));
                }
                catch (Exception) { }
                if (!BizUtil.ValidDateBtw(conditions["IST_YMD_FROM"], conditions["IST_YMD_TO"]))
                {
                    Messages.ShowInfoMsgBox("설치일자 범위를 확인하세요");
                    return;
                }


                //dtresult = pipeWork.SelectWtlPipeList(conditions);
                conditions.Add("sqlId", "SelectWtlPipeList");
                //dtresult = BizUtil.SelectList(conditions);
                //grid.ItemsSource = dtresult;

                /*
                 *  조회후 페이징소스 업데이트
                 */
                int page_idx = 0;
                //페이지버튼으로 조회
                if (obj is int)
                {
                    page_idx = (int)obj;
                }
                //조회버튼으로 조회는 버튼위치(PageIndex) 초기화
                else
                {
                    PageIndex = -1;
                }
                BizUtil.SelectListPage(conditions, page_idx, delegate(DataTable dt) {
                    // TotalCnt 설정
                    try
                    {
                        this.TotalCnt = Convert.ToInt32(dt.Rows[0]["ROWCNT"]);
                        this.ItemCnt  = (int)Math.Ceiling((double)this.TotalCnt / FmsUtil.PageSize);
                    }
                    catch (Exception)
                    {
                        this.TotalCnt = 0;
                        this.ItemCnt  = 0;
                    }

                    this.PagedCollection.Clear();
                    this.PagedCollection.Add(dt);
                });
            }
            catch (Exception ex)
            {
                Messages.ShowErrMsgBoxLog(ex);
            }
        }
Ejemplo n.º 53
0
        private async void Load()
        {
            var t = TaskStarted("history");

            try
            {
                bool isChat = Dialog.Message.ChatId != 0;
                if (isChat)
                {
                    var users = await ServiceLocator.UserService.GetChatUsers(Dialog.Message.ChatId);

                    Dialog.Users = users;

                    if (Dialog.Users == null)
                    {
                        Dialog.Users = new List <VkProfile>();
                    }

                    if (!Dialog.Users.Contains(ViewModelLocator.Main.CurrentUser))
                    {
                        Dialog.Users.Add(ViewModelLocator.Main.CurrentUser);
                    }
                }

                var vkMessages = await ServiceLocator.Vkontakte.Execute.GetChatHistoryAndMarkAsRead(!isChat?Dialog.User.Profile.Id : 0, chatId : isChat?Dialog.Message.ChatId : 0, count : DeviceHelper.IsMobile()? 20 : 50, markAsRead : !AppSettings.DontMarkMessagesAsRead);

                if (!vkMessages.Items.IsNullOrEmpty())
                {
                    if (isChat)
                    {
                        var userIds = vkMessages.Items.Where(m => !Dialog.Users.Any(u => m.UserId == u.Id)).Select(m => m.UserId).ToList();

                        var users = await ServiceLocator.UserService.GetById(userIds);

                        if (!users.IsNullOrEmpty())
                        {
                            Dialog.Users.AddRange(users);
                        }
                    }

                    Messages.AddRange(vkMessages.Items.Select(m =>
                    {
                        VkProfile sender = null;
                        if (!isChat)
                        {
                            sender = !m.IsOut ? Dialog.User.Profile : null;
                        }
                        else
                        {
                            sender = Dialog.Users?.FirstOrDefault(u => u.Id == m.UserId);
                        }
                        return(new Message(m, sender));
                    }).Reverse().ToList());
                    _totalCount = vkMessages.TotalCount;
                    //Messages.OnMoreItemsRequested = LoadMoreMessages;
                    //Messages.HasMoreItemsRequested = () => _totalCount > Messages.Count;
                }
            }
            catch (VkInvalidTokenException)
            {
                Messenger.Default.Send(new LoginStateChangedMessage()
                {
                    IsLoggedIn = false
                });

                Navigator.Main.Navigate(typeof(LoginView), clearHistory: true);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Unable to load messages in coversation");

                t.Error = Localizator.String("Errors/ChatHistoryCommonError");
            }

            t.IsWorking = false;
        }
Ejemplo n.º 54
0
        /// <summary>
        /// 엑셀다운로드
        /// </summary>
        /// <param name="obj"></param>
        private void ExcelDownAction(object obj)
        {
            try
            {
                /// 데이터조회
                Hashtable conditions = new Hashtable();
                conditions.Add("MNG_CDE", cbMNG_CDE.EditValue);
                conditions.Add("HJD_CDE", cbHJD_CDE.EditValue);
                conditions.Add("MOP_CDE", cbMOP_CDE.EditValue);
                conditions.Add("JHT_CDE", cbJHT_CDE.EditValue);
                conditions.Add("FTR_IDN", FmsUtil.Trim(txtFTR_IDN.EditValue));
                conditions.Add("CNT_NUM", txtCNT_NUM.Text.Trim());
                conditions.Add("SHT_NUM", txtSHT_NUM.Text.Trim());
                conditions.Add("PIP_DIP", txtPIP_DIP.Text.Trim());
                try
                {
                    conditions.Add("IST_YMD_FROM", dtIST_YMD_FROM.EditValue == null ? null : Convert.ToDateTime(dtIST_YMD_FROM.EditValue).ToString("yyyyMMdd"));
                    conditions.Add("IST_YMD_TO", dtIST_YMD_TO.EditValue == null ? null : Convert.ToDateTime(dtIST_YMD_TO.EditValue).ToString("yyyyMMdd"));
                }
                catch (Exception) { }
                if (!BizUtil.ValidDateBtw(conditions["IST_YMD_FROM"], conditions["IST_YMD_TO"]))
                {
                    Messages.ShowInfoMsgBox("설치일자 범위를 확인하세요");
                    return;
                }


                conditions.Add("page", 0);
                conditions.Add("rows", 1000000);

                conditions.Add("sqlId", "SelectWtlPipeList");


                exceldt = BizUtil.SelectList(conditions);



                saveFileDialog       = null;
                saveFileDialog       = new System.Windows.Forms.SaveFileDialog();
                saveFileDialog.Title = "저장경로를 지정하세요.";

                //초기 파일명 지정
                saveFileDialog.FileName = DateTime.Now.ToString("yyyyMMdd") + "_" + "상수관로.xlsx";

                saveFileDialog.OverwritePrompt = true;
                saveFileDialog.Filter          = "Excel|*.xlsx";


                //그리드헤더정보 추출
                columnList = new GridColumn[grid.Columns.Count];
                grid.Columns.CopyTo(columnList, 0);
                listCols = new List <string>(); //컬럼헤더정보 가져오기
                foreach (GridColumn gcol in columnList)
                {
                    try
                    {
                        if ("PrintN".Equals(gcol.Tag.ToString()))
                        {
                            continue;                                       //엑셀출력제외컬럼
                        }
                    }
                    catch (Exception) { }

                    listCols.Add(gcol.FieldName.ToString());
                }


                if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    strFileName = saveFileDialog.FileName;
                    thread      = new Thread(new ThreadStart(ExcelExportFX));
                    thread.Start();
                }
            }
            catch (Exception ex)
            {
                Messages.ShowErrMsgBoxLog(ex);
            }
        }
 private void HandlePlayerKilled(object sender, EventArgs e)
 {
     Messages.Add("You were killed");
 }
Ejemplo n.º 56
0
 public AddFriendCommandResult(bool isSuccessful, bool data, Messages messages)
 {
     this.IsSuccessful = isSuccessful;
     this.Data         = data;
     this.Messages     = messages;
 }
Ejemplo n.º 57
0
        public static void PowersGUIHandler(Rect inRect, CompVampire compVampire, Discipline discipline)
        {
            float buttonXOffset = inRect.x;

            if (discipline?.Def?.abilities is List <VitaeAbilityDef> abilities && !abilities.NullOrEmpty())
            {
                Rect rectLabel = new Rect(inRect.x, inRect.y, inRect.width * 0.7f, TextSize);
                Text.Font = GameFont.Small;
                Widgets.Label(rectLabel, discipline.Def.LabelCap);
                Text.Font = GameFont.Small;
                int count    = 0;
                int pntCount = 0;

                foreach (VitaeAbilityDef ability in discipline.Def.abilities)
                {
                    Rect buttonRect = new Rect(buttonXOffset, rectLabel.yMax, VampButtonSize, VampButtonSize);
                    TooltipHandler.TipRegion(buttonRect, () => ability.LabelCap + "\n\n" + ability.description, 398452); //"\n\n" + "PJ_CheckStarsForMoreInfo".Translate()


                    Texture2D abilityTex        = ability.uiIcon;
                    bool      disabledForGhouls =
                        compVampire.IsGhoul && (int)compVampire.GhoulHediff.ghoulPower < discipline.Level;
                    if (disabledForGhouls)
                    {
                        GUI.color = Color.gray;
                    }
                    if (compVampire.AbilityPoints == 0 || discipline.Level >= 4)
                    {
                        Widgets.DrawTextureFitted(buttonRect, abilityTex, 1.0f);
                    }
                    else if (Widgets.ButtonImage(buttonRect, abilityTex) && compVampire.AbilityUser.Faction == Faction.OfPlayer)
                    {
                        if (compVampire.AbilityUser.story != null && compVampire.AbilityUser.story.WorkTagIsDisabled(WorkTags.Violent) && ability.MainVerb.isViolent)
                        {
                            Messages.Message("IsIncapableOfViolenceLower".Translate(new object[]
                            {
                                compVampire.parent.LabelShort
                            }), MessageTypeDefOf.RejectInput);
                            return;
                        }
                        if (disabledForGhouls)
                        {
                            Messages.Message("ROMV_DomitorVitaeIsTooWeak".Translate(new object[]
                            {
                                compVampire.parent.LabelShort
                            }), MessageTypeDefOf.RejectInput);
                            return;
                        }

                        discipline.Notify_PointsInvested(1); //LevelUpPower(power);
                        compVampire.Notify_UpdateAbilities();
                        compVampire.AbilityPoints -= 1;      //powerDef.abilityPoints;
                    }

                    float drawXOffset = buttonXOffset - ButtonSize;
                    float modifier    = 0f;
                    switch (count)
                    {
                    case 0: break;

                    case 1: modifier = 0.75f; break;

                    case 2: modifier = 0.72f; break;

                    case 3: modifier = 0.60f; break;
                    }
                    if (count != 0)
                    {
                        drawXOffset -= VampButtonPointSize * count * modifier;
                    }
                    else
                    {
                        drawXOffset -= 2;
                    }

                    for (int j = 0; j < count + 1; j++)
                    {
                        ++pntCount;
                        float drawYOffset = VampButtonSize + TextSize + Padding;
                        Rect  powerRegion = new Rect(inRect.x + drawXOffset + VampButtonPointSize * j, inRect.y + drawYOffset, VampButtonPointSize, VampButtonPointSize);
                        if (discipline.Points >= pntCount)
                        {
                            Widgets.DrawTextureFitted(powerRegion, TexButton.ROMV_PointFull, 1.0f);
                        }
                        else
                        {
                            Widgets.DrawTextureFitted(powerRegion, TexButton.ROMV_PointEmpty, 1.0f);
                        }

                        TooltipHandler.TipRegion(powerRegion, () => ability.GetDescription() + "\n" + compVampire.PostAbilityVerbCompDesc(ability.MainVerb), 398462);
                    }
                    ++count;
                    buttonXOffset += ButtonSize * 3f + Padding;
                    if (disabledForGhouls)
                    {
                        GUI.color = Color.white;
                    }
                }
            }
        }
Ejemplo n.º 58
0
        protected override bool TryCastShot()
        {
            CellRect cellRect = CellRect.CenteredOn(this.currentTarget.Cell, 1);
            Map      map      = base.CasterPawn.Map;

            cellRect.ClipInsideMap(map);

            IntVec3 centerCell      = cellRect.CenterCell;
            Thing   summonableThing = new Thing();
            //FlyingObject flyingPawn = new FlyingObject();
            Pawn summonablePawn = new Pawn();

            bool pflag = true;

            summonableThing = centerCell.GetFirstPawn(map);
            if (summonableThing == null)
            {
                pflag           = false;
                summonableThing = centerCell.GetFirstItem(map);
            }
            else
            {
                pVect          = summonableThing.TrueCenter();
                pVect.x        = base.caster.TrueCenter().x;
                pVect.z        = base.caster.TrueCenter().z;
                pVect.y        = 0f;
                summonablePawn = summonableThing as Pawn;
                if (summonablePawn != base.CasterPawn)
                {
                    //flyingPawn = (FlyingObject)GenSpawn.Spawn(ThingDef.Named("TM_SummonedPawn"), summonableThing.Position, summonableThing.Map);
                }
                else
                {
                    //flyingPawn = null;
                    summonableThing = null;
                    Messages.Message("TM_CantSummonSelf".Translate(), MessageTypeDefOf.NegativeEvent);
                }
            }

            bool result = false;
            bool arg_40_0;

            if (this.currentTarget != null && base.CasterPawn != null)
            {
                IntVec3 arg_29_0 = this.currentTarget.Cell;
                arg_40_0 = this.currentTarget.Cell.IsValid;
            }
            else
            {
                arg_40_0 = false;
            }
            bool flag = arg_40_0;

            if (flag)
            {
                if (summonableThing != null)
                {
                    if (pflag)// && flyingPawn != null)
                    {
                        //Thing p = summonablePawn;
                        if (!summonablePawn.RaceProps.Humanlike || summonablePawn.Faction == this.CasterPawn.Faction)
                        {
                            summonablePawn.DeSpawn();
                            GenSpawn.Spawn(summonablePawn, base.CasterPawn.Position, map);
                        }
                        else if (summonablePawn.RaceProps.Humanlike && summonablePawn.Faction != this.CasterPawn.Faction && Rand.Chance(TM_Calc.GetSpellSuccessChance(this.CasterPawn, summonablePawn, true)))
                        {
                            //summonablePawn.DeSpawn();
                            //GenSpawn.Spawn(p, base.caster.Position, base.CasterPawn.Map, Rot4.North, false);

                            //Pawn p = summonablePawn;
                            summonablePawn.DeSpawn();
                            //p.SetPositionDirect(this.currentTarget.Cell);
                            GenSpawn.Spawn(summonablePawn, base.CasterPawn.Position, map);
                            //flyingPawn = null;
                            if (summonablePawn.IsColonist && !base.CasterPawn.IsColonist)
                            {
                                TM_Action.SpellAffectedPlayerWarning(summonablePawn);
                            }
                            //summonablePawn.Position = base.CasterPawn.Position;
                            //p.jobs.StopAll(false);
                        }
                        else
                        {
                            MoteMaker.ThrowText(summonablePawn.DrawPos, summonablePawn.Map, "TM_ResistedSpell".Translate(), -1);
                        }
                    }
                    else
                    {
                        summonableThing.DeSpawn(DestroyMode.Vanish);
                        GenPlace.TryPlaceThing(summonableThing, this.CasterPawn.Position, this.CasterPawn.Map, ThingPlaceMode.Near);
                        //summonableThing.Position = base.CasterPawn.Position;
                        //summonableThing.Rotation = Rot4.North;
                        //summonableThing.SetPositionDirect(base.CasterPawn.InteractionCell);
                    }
                    result = true;
                }
            }
            else
            {
                Log.Warning("failed to TryCastShot");
            }
            this.burstShotsLeft = 0;
            //this.ability.TicksUntilCasting = (int)base.UseAbilityProps.SecondsToRecharge * 60;
            return(result);
        }
Ejemplo n.º 59
0
        protected override bool TryCastShot()
        {

            Pawn caster = this.CasterPawn;
            CompAbilityUserMagic comp = caster.GetComp<CompAbilityUserMagic>();
            MagicPowerSkill ver = caster.GetComp<CompAbilityUserMagic>().MagicData.MagicPowerSkill_ConsumeCorpse.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_ConsumeCorpse_ver");
            MagicPowerSkill manaRegen = caster.GetComp<CompAbilityUserMagic>().MagicData.MagicPowerSkill_global_regen.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_global_regen_pwr");

            Thing undeadThing = this.currentTarget.Thing;
            if (undeadThing is Pawn)
            {
                Pawn undead = (Pawn)undeadThing;

                bool flag = undead != null && !undead.Dead;
                if (flag)
                {
                    if (undead.health.hediffSet.HasHediff(TorannMagicDefOf.TM_UndeadHD))
                    {
                        comp.Mana.CurLevel += (Rand.Range(.19f, .23f) + (manaRegen.level * .003f) + (ver.level * .005f));
                        ConsumeHumanoid(undead);
                        if (ver.level > 0)
                        {
                            HealCaster(caster, 1 + ver.level, 1, 4f + ver.level);
                        }
                        undead.Destroy();
                    }
                    else if (undead.health.hediffSet.HasHediff(TorannMagicDefOf.TM_UndeadAnimalHD))
                    {
                        comp.Mana.CurLevel += (Rand.Range(.14f, .17f) + (manaRegen.level * .003f) + (ver.level * .005f));
                        ConsumeAnimalKind(undead);
                        if (ver.level > 0)
                        {
                            HealCaster(caster, 1, 2, 1 + ver.level);
                        }
                        undead.Destroy();
                    }
                    else
                    {
                        Messages.Message("TM_CannotUseOnLiving".Translate(), MessageTypeDefOf.RejectInput);
                    }
                }
            }

            
            IntVec3 target = this.currentTarget.Cell;
            Thing corpseThing = null;
            Corpse corpse = null;
            List<Thing> thingList;
            thingList = target.GetThingList(caster.Map);
            int i=0;
            while(i < thingList.Count)
            {
                corpseThing = thingList[i];
                if (corpseThing != null)
                {
                    bool validator = corpseThing is Corpse;
                    if (validator)
                    {
                        corpse = corpseThing as Corpse;
                        Pawn undeadPawn = corpse.InnerPawn;
                        if (undeadPawn.RaceProps.IsFlesh)
                        {
                            if (undeadPawn.RaceProps.Humanlike && !undeadPawn.RaceProps.Animal)
                            {
                                if (!corpse.IsNotFresh())
                                {
                                    comp.Mana.CurLevel += (Rand.Range(.07f, .11f) + (manaRegen.level * .001f) + (ver.level * .003f));
                                    caster.needs.rest.CurLevel += .2f;
                                    caster.needs.mood.CurLevel += .2f;
                                    ConsumeHumanoid(corpse);
                                    if (ver.level > 0)
                                    {
                                        HealCaster(caster, 1, 1 + ver.level, 2f + ver.level);
                                    }
                                }
                                else
                                {
                                    comp.Mana.CurLevel += (Rand.Range(.05f, .09f) + (manaRegen.level * .001f) + (ver.level * .003f));
                                    ConsumeHumanoid(corpse);
                                }
                                corpse.Destroy();
                            }
                            else if (undeadPawn.RaceProps.Animal)
                            {
                                if (!corpse.IsNotFresh())
                                {
                                    comp.Mana.CurLevel += (Rand.Range(.05f, .08f) + (manaRegen.level * .0005f) + (ver.level * .002f));
                                    caster.needs.food.CurLevel += .4f;
                                    ConsumeAnimalKind(corpse);
                                }
                                else
                                {
                                    comp.Mana.CurLevel += (Rand.Range(.03f, .05f) + (manaRegen.level * .0005f) + (ver.level * .002f));
                                    ConsumeAnimalKind(corpse);
                                }
                                corpse.Destroy();
                            }
                            else
                            {
                                Messages.Message("TM_CannontConsumeCorpseType".Translate(), MessageTypeDefOf.RejectInput);
                            }
                        }
                        else
                        {
                            Messages.Message("TM_InvalidCorpseType".Translate(), MessageTypeDefOf.RejectInput);
                        }
                    }
                }
                i++;
            }        
            
            return false;
        }
Ejemplo n.º 60
0
        private void AddPsionicShock(Pawn pawn)
        {
            System.Random rand = new System.Random();

            int  psychicSensitivity    = 0;
            bool?shouldGiveHeartAttack = null;
            bool?shouldSedate          = null;

            if (pawn.story?.traits != null && pawn.story.traits.HasTrait(TraitDef.Named("PsychicSensitivity")))
            {
                Trait psychicSensitivityTrait = pawn.story.traits.GetTrait(TraitDef.Named("PsychicSensitivity"));
                psychicSensitivity = psychicSensitivityTrait.Degree;
            }

            // If they're Psychically Deaf, do nothing:
            if (psychicSensitivity == -2)
            {
                return;
            }
            // If they're Psychically Dull, don't give them a heart attack.
            else if (psychicSensitivity == -1)
            {
                shouldGiveHeartAttack = false;
            }
            // If they're Psychically Sensitive, make sure they're passed out for a few hours.
            else if (psychicSensitivity == 1)
            {
                shouldSedate = true;
            }
            // If they're Psychically Hypersensitive, unfortunately, it will mean instant death :-(
            else if (psychicSensitivity >= 2)
            {
                if (pawn.IsColonist)
                {
                    Messages.Message(pawn.Name.ToStringShort + " was psychically supersensitive and died because of the psionic blast.", MessageTypeDefOf.ThreatSmall);
                }

                HealthUtility.DamageUntilDead(pawn);
            }

            Hediff shock = HediffMaker.MakeHediff(HediffDefOf.PsychicShock, pawn, null);

            pawn.health.AddHediff(shock, null, null);

            if (shouldGiveHeartAttack == null)
            {
                shouldGiveHeartAttack = rand.Next(1, 11) >= 3;
            }

            if (shouldGiveHeartAttack == true)
            {
                this.CauseHeartAttack(pawn);
            }

            if (shouldSedate == null)
            {
                int likelihood = rand.Next(1, 11);
                if (pawn.Name?.ToStringShort != null)
                {
                    Log.Message(pawn.Name.ToStringShort + " should sedate? " + likelihood);
                }
                else
                {
                    Log.Message(pawn.def.label + " should sedate? " + likelihood);
                }

                shouldSedate = likelihood >= 6;
            }

            if (shouldSedate == true)
            {
                this.CauseSedation(pawn);
            }

            DamageInfo psionicIntensity = new DamageInfo(DamageDefOf.Stun, 50);

            pawn.TakeDamage(psionicIntensity);
        }