public clTask GetBaseLine4Task(InfoObject task) { clTask baseline = null; if (task != null) dictPlanRecords.TryGetValue(task, out baseline); return baseline; }
private CharSkill(InfoObject obj) { Name = obj.Name; ID = stNextSkillID++; stSkillInfos.Add(Name, new SkillInfo(obj)); }
public static void LoadItemInfos() { InfoObject[] itemInfos = ResourceLib.Info.GetAll("item"); Dictionary <String, List <ItemInfo> > dict = new Dictionary <string, List <ItemInfo> >(); for (int i = 0; i < itemInfos.Length; ++i) { InfoObject info = itemInfos[i]; string itemType = info["type"].AsString(); if (!dict.ContainsKey(itemType)) { dict.Add(itemType, new List <ItemInfo>()); } dict[itemType].Add(new ItemInfo(stNextItemID++, info)); } stItemInfos = new Dictionary <string, Dictionary <ushort, ItemInfo> >(); stItemStrings = new Dictionary <string, Dictionary <string, ItemInfo> >(); foreach (string itemType in dict.Keys) { List <ItemInfo> infos = dict[itemType]; stItemInfos.Add(itemType, infos.ToDictionary(x => x.ID)); stItemStrings.Add(itemType, infos.ToDictionary(x => x.Name)); } }
//CUSTOMIZATION_ORIGINAL_DIGEST:2102F1C24EA74ECC833C1896D1FB017D16F4B3C1 //CUSTOMIZATION_BEGIN // Config SAGA /// <summary> /// Возвращает значение атрибута "TextData" фактического блока, дочернего к объекту obj /// </summary> /// <param name="obj">Объект, для которого ищутся фактические данные</param> /// <param name="nval">Тип блока фактических данных</param> /// <returns>значение атрибута "TextData" фактического блока</returns> /// <remarks>В поле FactAddr может быть ссылка как на одиночный блок фактических данных, /// так и ссылка на блок метаданных типа "Коллекция" /// </remarks> public static string GetFactData(InfoObject obj, NamedValue nval) { var FactData = ""; var FactAddr = obj.GetInfoObject("FactAddr"); if (FactAddr != null) { InfoObject realFactAddr = null; if (FactAddr.Template.NameKey == "FactBlock") { // одиночный блок фактических данных if (FactAddr.GetValue <NamedValue>("BlockType") == nval) { realFactAddr = FactAddr; } } else { // ссылка на блок метаданных типа "Коллекция" realFactAddr = FactAddr.Children.Where(o => o.GetValue <NamedValue>("BlockType") == nval).FirstOrDefault(); } if (realFactAddr != null) { FactData = realFactAddr.GetString("TextData"); } } return(FactData); }
public void Connect(InfoObject o, Color color, AGraphicalPrimitive p) { if (trees.ContainsKey(p.Base())) { if (connectedInfObs.Contains(o)) { foreach (var tree in trees.Values) { if (!tree.Connects(o)) { tree.Connect(this, o, p, color); p.Brush(color); } } } } else { var tree = Instantiate(VisBridgeTreePrefab); tree.Assign(this, p.Base()); trees.Add(p.Base(), tree); tree.Subscribe(this); tree.Connect(this, o, p, color); p.Brush(color); } }
public static InfoObject Map(InfoObjectEditModel model, Guid id) { if (model == null) { return(null); } var result = new InfoObject { Id = id, SubOrder = model.SubOrder, ContentGroupId = model.ContentGroupId }; if (model.Type.IsNotNullOrEmpty()) { var type = Enum.Parse <InfoObjectType>(model.Type, ignoreCase: true); var content = model.Content; if (type == InfoObjectType.Image) { content = Constants.GetRelativePathToImage(model.Content); } result.Type = type; result.Content = content; } return(result); }
// this function forwards the input for validatoin check and for User class to login. // if the it passed all checks the user will be added to the logged in users hash table. public static InfoObject login(string email, string password) { InfoObject info; Log.Info("User: "******" log in attempt with password: "******""); } else { Log.Error("This user doesn't exist. Wrong email or password."); info = new InfoObject(false, "This user doesn't exist. Wrong email or password."); } } else { Log.Error("Login of " + email + " failed. Illegal password"); info = new InfoObject(false, "Login of " + email + " failed. Illegal password"); } return(info); }
public void Connect(VisBridge bridge, InfoObject infO, AGraphicalPrimitive prim, Color color) { if (paths.ContainsKey(infO)) { return; } if (center == null) { center = Services.PrimFactory3D().CreatePhantomPrimitive(); } var bridgeCenter = bridge.centroids[infO]; var offset = Services.PrimFactory3D().CreateBoxPrimitive(); offset.transform.parent = center.transform; offset.transform.localScale = new Vector3(.05f, .005f, .05f); offset.SetColor(color, color); // Connect visBridgeCenter with treeCenter var trunk = Instantiate(branchPrefab); trunk.Init(bridgeCenter, offset, color, infO); var branch = Instantiate(branchPrefab); branch.Init(offset, prim, color, infO); paths.Add(infO, new BridgePath(infO, trunk, branch, offset)); Observe(branch); UpdateCenter(); }
public BridgePath(InfoObject iD, VisBridgeBranch trunk, VisBridgeBranch branch, AGraphicalPrimitive offset) { ID = iD; this.trunk = trunk; this.branch = branch; this.offset = offset; }
private DungeonClass(InfoObject info) { Name = info.Name; FullName = info["name"].AsString(); EvilMin = (byte)info["evil min"].AsInteger(); EvilMax = (byte)info["evil max"].AsInteger(); SavageryMin = (byte)info["savage min"].AsInteger(); SavageryMax = (byte)info["savage max"].AsInteger(); TemperatureMin = (byte)info["temp min"].AsInteger(); TemperatureMax = (byte)info["temp max"].AsInteger(); AreaMin = (int)info["area min"].AsInteger(); AreaMax = (int)info["area max"].AsInteger(); myIconTextureName = info["icon file"].AsString(); myIconTexture = null; InfoValue[] icons = info["icon indexes"].AsArray(); IconIndexes = new byte[icons.Length]; for (int i = 0; i < icons.Length; ++i) { IconIndexes[i] = (byte)icons[i].AsInteger(); } myTileTextureName = info["tile file"].AsString(); myTileTexture = null; DefaultSkinIndex = (byte)info["default skin index"].AsInteger(); }
// Start is called before the first frame update void Start() { transform.position = new Vector3(-3.53f, 0.05f, -2); //EndingText = GameObject.Find("TimeOrCrashed"); infoObject = (InfoObject)UnityEngine.Object.FindObjectOfType(typeof(InfoObject)); SimulationData simData = infoObject.simulationData; History = simData.history; score = simData.score; tps = History.tps; history = History.history; //crashed = (score.successful==false); crashed = true; swpl = history.Length; time = score.time; secTime = time / tps; sentwps = new float[swpl, 2]; Vector2 currentPosition = this.transform.position; var i = 0; while (i < swpl) { var temp = ConvertPos(history[i].pos, currentPosition); sentwps[i, 0] = temp[0]; sentwps[i, 1] = temp[1]; i++; } }
public void Test_AddTaskNullDueDate() { title = "Test"; description = "This is a test."; dueDate = null; output = SystemInterface.addTask(email, title, description, dueDate); Assert.AreEqual(output.getIsSucceeded(), false); }
public void Test_AddTaskEmptyTitle() { title = ""; description = "This is a test."; dueDate = "24/09/2019"; output = SystemInterface.addTask(email, title, description, dueDate); Assert.AreEqual(output.getIsSucceeded(), false); }
public void Test_AddTaskLongTitle() { title = "This title is over 50 charcaters and you can't do that here"; description = "This is a test."; dueDate = "24/09/2019"; output = SystemInterface.addTask(email, title, description, dueDate); Assert.AreEqual(output.getIsSucceeded(), false); }
public void Test_AddTaskNullDescription() { title = "Test"; description = null; dueDate = "24/09/2019"; output = SystemInterface.addTask(email, title, description, dueDate); Assert.AreEqual(output.getIsSucceeded(), false); }
/// <summary> /// Конструктор. /// </summary> /// <param name="GanttParent">Объект ПЛМ, от имени которого запущена диаграмма Гантта</param> /// <param name="GanttDiag">Диаграмма, на которой происходит рисование (передаётся из родительской формы)</param> public HelperPLM(InfoObject GanttParent, Gantt GanttDiag) { this.GanttParent = GanttParent; this.GanttDiag = GanttDiag; this.ResourceWorker = new HelperResource(this.GanttDiag, this); this.CalendarsWorker = new HelperCalendars(); this.StatusWorker = new HelperStatus(); }
public SpellInfo(UInt16 id, InfoObject info) { ID = id; Name = info.Name; CastType = (CastType)Enum.Parse(typeof(CastType), info["cast type"].AsString()); DamageType = DamageType.Magical; if (CastType == CastType.Projectile) { DamageType |= DamageType.Ranged; } else if (CastType == CastType.Touch) { DamageType |= DamageType.Melee; } if (info.ContainsKey("elemental types")) { foreach (InfoValue val in info["elemental types"].AsArray()) { DamageType |= (DamageType)Enum.Parse(typeof(DamageType), val.AsString()); } } myNames = new Dictionary <double, string>(); foreach (InfoValue val in info["names"].AsArray()) { InfoValue[] arr = val.AsArray(); myNames.Add(arr[0].AsDouble(), arr[1].AsString()); } if (info.ContainsKey("colour")) { InfoValue[] arr = info["colour"].AsArray(); Colour = new Color4((byte)arr[0].AsInteger(), (byte)arr[1].AsInteger(), (byte)arr[2].AsInteger(), 255); } else { Colour = Color4.White; } InfoObject quals = info["qualities"] as InfoObject; myQualities = new Dictionary <string, SpellQuality>(); foreach (String key in quals.Keys) { InfoValue[] vals = quals[key].AsArray(); myQualities.Add(key, new SpellQuality(vals[0].AsDouble(), (vals.Length == 1) ? vals[0].AsDouble() : vals[1].AsDouble(), (vals.Length == 3) ? vals[2].AsDouble() : 1.0)); } myDescription = info["description"].AsString(); EffectClassName = info["effect class"].AsString(); }
/// <summary> /// Вызывается в процессе взятия на редактирование /// </summary> /// <param name="swDoc">документ</param> /// <param name="ioVersion">ио версии в плм</param> public void OnCheckOut(string swDoc, InfoObject ioVersion) { //MessageBox.Show("CheckOut"); //SWDocument addinDoc = AddinDocumentCache.ReturnDocument(swDoc, null) as SWDocument; // SWDocument - обёртка документа для использования аддином PrepareTT(swDoc, ioVersion); Trace.TraceInformation(@"OnCheckOut: document:" + swDoc + " ioVersion: " + ioVersion.ToString()); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { var infoObject = new InfoObject { Action = ActionToLog }; filterContext.RequestContext.HttpContext.Request.RequestContext.RouteData.DataTokens[profile] = infoObject; filterContext.RequestContext.HttpContext.Request.RequestContext.RouteData.DataTokens[stopwatch] = Stopwatch.StartNew(); base.OnActionExecuting(filterContext); }
public bool isInPlayerMap; // for checking if the player is using the full map or the player map private void Awake() { infoObject = GameObject.FindObjectOfType <InfoObject>(); logHandler = GameObject.FindObjectOfType <LogHandler>(); chatHandler = GameObject.FindObjectOfType <ChatHandler>(); timerController = GameObject.FindObjectOfType <TimerController>(); gameData = GameObject.FindObjectOfType <GameData>(); isInPlayerMap = true; }
private async Task DoItWithAsyncAndAwait() { var info = new InfoObject { Logger = LogIt, MillisToSleep = GetSimulatedWorkInMillis(), TestCase = "AsyncAndAwait" }; var lenghtyStuff = new LengthyStuff(); await lenghtyStuff.DoItInAsync(info); }
public void PrepareTT(string swDoc, InfoObject ioVersion) { // Чтение атрибутов ИО ПЛМ и запись в кэш var TecchReqGrig = ioVersion.GetAttribute("TecchReqGrig").CollectionElements.OrderBy(i => i.GetValue <int>("IndOrder")); var count = TecchReqGrig.Count(); arrTT.Clear(); arrLinks.Clear(); notes.Clear(); foreach (var element in TecchReqGrig) { //MessageBox.Show(element.GetValue<string>("ttElementLabel")); InfoObject childio = element.GetValue <InfoObject>("ChildIO"); arrTT.Add(childio.GetValue <string>("TextLabel")); // Поиск в элементе ТТ атрибутов типа "Значения" и сохранение их в кэш для синхронизации в ПЛМ var SizeList = childio.GetAttribute("SizeList").CollectionElements; foreach (var sz in SizeList) { arrLinks.Add(new ValElem() { link = sz.GetValue <string>("ttElementSolidSizeLink"), val = "" }); } } // Получение документа SW ModelDoc2 Doc = SWHelper.GetDocByFileName(swDoc); // нужно учитывать что браться на редактирование может документ не открытый в PLM. тогда здесь будет null и нужно либо открывать документ, либо работать через DMDocument if (Doc != null) { // Определяем тип документа. Пока рисуем ТТ только на чертежах int docType = Doc.GetType(); switch (docType) { case (int)swDocumentTypes_e.swDocPART: Debug.Print("swPart"); // отрисовка ТТ на основе атрибутов //PaintNoteOnPart(Doc, arrTT.ToArray()); break; case (int)swDocumentTypes_e.swDocDRAWING: Debug.Print("swDraw"); // Расчёт расположения примечаний на основе атрибутов PreCalcNote(Doc, arrTT.ToArray()); // отрисовка ТТ PaintNoteOnDraw(Doc); break; case (int)swDocumentTypes_e.swDocASSEMBLY: Debug.Print("swAssy"); break; default: //swDocNONE, swDocSDM Debug.Print("another doc"); break; } } }
private void Awake() { if (PhotonNetwork.IsConnected) { infoObject = GameObject.FindObjectOfType <InfoObject>(); players = infoObject.GetCharacters(); playerPosition = new Vector3[4]; } }
// that blocks ui-thread private async Task DoItWithAsyncNoAwaitButWaitWillBlockOnUiThread() { var info = new InfoObject { Logger = LogIt, MillisToSleep = 2000, TestCase = "AsyncNoAwaitWillBlockInUI-Thread" }; var lenghtyStuff = new LengthyStuff(); lenghtyStuff.DoItInAsync(info).Wait(); }
/// <summary> /// Создание календаря GanttCalendar по данным календаря PLM /// </summary> /// <param name="calendPLM">Импортируемый календарь PLM</param> public void ImportCalendarPLM(InfoObject calendarPLM) { CalendarExceptionCollection GanttExceptionsColl; CalendarException GanttCalendarException; WorkingHourCollection WorkHourColl; WorkingHour WorkHour; // Наименование нового календаря this.intCalendar.Text = calendarPLM.GetValue<String>("ScheduleName"); SetWorkingDays(calendarPLM); // Инициализация коллекции исключений для нового календаря GanttExceptionsColl = new KS.Gantt.Calendars.CalendarExceptionCollection(); // Выборка коллекции дней исключений из PLM var ExceptionsPLM = calendarPLM.GetAttribute("Exceptions").CollectionElements.ToArray(); foreach (var cePLM in ExceptionsPLM) { GanttCalendarException = new KS.Gantt.Calendars.CalendarException(); // Дата исключения var TheDay = cePLM.GetValue<DateTime>("TheDay"); GanttCalendarException.Date = TheDay; // Признак по календарю рабочего дня isWorking - true, // выходного дня(суббота, воскресение) isWorking - false bool isWorking = calendarPLM.GetAttribute("Schedule" + ((int)TheDay.DayOfWeek)).CollectionElements.Count > 0; GanttCalendarException.IsWorkingDay = cePLM.GetAttribute("Hours").CollectionElements.Count != 0; // Инициализация коллекции рабочих часов дней исключений WorkHourColl = new KS.Gantt.Calendars.WorkingHourCollection(); // Выборка коллекции рабочих часов текущего исключения из PLM var hoursCollPLM = cePLM.GetAttribute("Hours").CollectionElements. OrderBy(e => e.GetValue<TimeSpan>("TimeSpanFrom").Hours).ToArray(); foreach (var hrPLM in hoursCollPLM) { WorkHour = new KS.Gantt.Calendars.WorkingHour(); var b1 = hrPLM.GetValue<String>("HourFrom"); double hourFrom = 0; double.TryParse(b1.Substring(0, 2), out hourFrom); double minuteFrom = 0; double.TryParse(b1.Substring(2, 2), out minuteFrom); double hour = hourFrom + minuteFrom / 100; WorkHour.StartHour = hour; var b2 = hrPLM.GetValue<String>("HourTo"); hourFrom = 0; double.TryParse(b2.Substring(0, 2), out hourFrom); minuteFrom = 0; double.TryParse(b2.Substring(2, 2), out minuteFrom); hour = hourFrom + minuteFrom / 100; WorkHour.EndHour = hour; WorkHourColl.Add(WorkHour); } GanttCalendarException.WorkingHours = WorkHourColl; GanttExceptionsColl.Add(GanttCalendarException); } this.intCalendar.Exceptions = GanttExceptionsColl; }
/// <summary> /// Removes connections to all representative graphical /// primitives of the given information object. /// </summary> /// <param name="o"></param> public void Disconnect(InfoObject o) { if (connectedInfObs.Contains(o)) { connectedInfObs.Remove(o); var cent = centroids[o]; centroids.Remove(o); Destroy(cent); } }
// Start is called before the first frame update private void Awake() { playerslist = new List <string>(); map = new Dictionary <string, string>(); charTypes = new Queue <string>(); infoObject = GameObject.FindObjectOfType <InfoObject>(); logHandler = GameObject.FindObjectOfType <LogHandler>(); chatHandler = GameObject.FindObjectOfType <ChatHandler>(); chatController = GameObject.FindObjectOfType <ChatController>(); }
/// <summary> /// Вызывается в процессе сохранения документа в PLM /// </summary> /// <param name="swDoc">документ</param> /// <param name="ioVersion">ио версии в плм</param> public void OnCheckIn(string swDoc, InfoObject ioVersion) { //MessageBox.Show("CheckIn"); SWDocument addinDoc = AddinDocumentCache.ReturnDocument(swDoc, null) as SWDocument; // SWDocument - обёртка документа для использования аддином //addinDoc.GetStatus() - определение plm-статуса документа -не сохранен, сохранён, на редактировании, забблокирован. если документ сохранён в плм, свойства PlmDocument и PlmVersion будут содержать ссылки на ио соответственно документа и версии ModelDoc2 Doc = SWHelper.GetDocByFileName(swDoc); // нужно учитывать что сохраняться может документ не открытый в PLM. тогда здесь будет null и нужно либо открывать документ, либо работать через DMDocument if (Doc != null) { // Определяем тип документа. Пока работаем только с чертежами int docType = Doc.GetType(); if (docType == (int)swDocumentTypes_e.swDocDRAWING) { // Ищем в примечании ТТ по кэшу сохранённых ссылок на значения чертежа. // Если находим, то ищем в чертеже соответствующий элемент и считываем его значение для передачи в ПЛМ. // Заполненные значения передаём в ПЛМ. var TecchReqGrig = ioVersion.GetAttribute("TecchReqGrig").CollectionElements; String notetxt = GetNoteTTtext(Doc); foreach (var sz in arrLinks) { String szval = ""; if (notetxt.Contains(sz.link)) { IDimension d1 = (IDimension)Doc.Parameter(sz.link); if (d1 != null) { szval = d1.Value.ToString(); // d1.GetUserValueIn(swDoc).ToString(); } } if (szval != "") { // Ищем ссылку на размер по всем строкам грида ТТ foreach (var element in TecchReqGrig) { InfoObject childio = element.GetValue <InfoObject>("ChildIO"); // Поиск в элементе ТТ атрибутов типа "Значения" и сохранение их значения из чертежа var SizeList = childio.GetAttribute("SizeList").CollectionElements; foreach (var isz in SizeList) { if (sz.link == isz.GetValue <string>("ttElementSolidSizeLink")) { isz["ttElementSolidSizeText"] = szval; childio.Invoke("RecalcVisibleText", null); element["ttElementValue"] = childio.GetAttribute("VisibleLabel").GetValue(); } } } } } } } Trace.TraceInformation(@"OnCheckIn: document:" + swDoc + " ioVersion: " + ioVersion.ToString()); //Trace.TraceInformation(@"OnCheckIn: SWDocument:" + addinDoc.ToString()); }
public BasePlan(InfoObject GanttParent, InfoObject PlanObj) { this.ParentObj = GanttParent; this.PlanObj = PlanObj; if (PlanObj != null) { this.sPlanName = PlanObj.GetValue<string>("Name"); this.Id = PlanObj.Id; } this.IsActual = false; }
public void RefreshTT() { AddinDocument addinDoc = _swAddin.GetActiveDoc(); if (addinDoc != null) { string swDoc = addinDoc.FullFileName; InfoObject ioVersion = addinDoc.PlmVersion; PrepareTT(swDoc, ioVersion); } }
public QualityInfo(InfoObject info) { Name = info.Name; myValues = new Dictionary <string, InfoValue>(); foreach (KeyValuePair <String, InfoValue> keyVal in info) { myValues.Add(keyVal.Key, keyVal.Value); } }
private void Awake() { if (PhotonNetwork.IsConnected) { mail = GameObject.FindObjectOfType <Email>(); gameData = GameObject.FindObjectOfType <GameData>(); logHandler = GameObject.FindObjectOfType <LogHandler>(); infoObject = GameObject.FindObjectOfType <InfoObject>(); chatHandler = GameObject.FindObjectOfType <ChatHandler>(); timerController = GameObject.FindObjectOfType <TimerController>(); } }
private Task DoItInSync() { var info = new InfoObject { Logger = LogIt, MillisToSleep = GetSimulatedWorkInMillis(), TestCase = "Sync" }; var lenghtyStuff = new LengthyStuff(); lenghtyStuff.DoItInSync(info); // in order to match delegate return(Task.Delay(0)); }
public IActionResult Info(string Name) { SearchObject searchObject = searchObjects.First(s => s.Name == Name); List <NewsObject> news = NewsSearchSamples.NewsSearchWithFilters(key, searchObject.Name); InfoObject infoObject = new InfoObject() { searchObject = searchObject, newsObject = news }; return(View(infoObject)); }
static void Main() { UserPass user1 = new UserPass(name: "Alex", age: 26, pass: "******"); User user2 = new User(name: "Alex", age: 26); string s1 = InfoObject.InfoUser(user1); string s2 = InfoObject.InfoUser(user2); Console.WriteLine(s1); Console.WriteLine(s2); Console.ReadLine(); }
/// <summary> /// Функция ищет в справочнике импортированных календарей календарь Гантта по календарю PLM. /// Если у задачи не был задан календарь (calendarPLM == null), то ставим задаче календарь по умолчанию /// </summary> /// <param name="calendarPLM">Календарь PLM</param> public string GetCalendarKey(InfoObject calendarPLM) { string CalendarKey = ""; if (calendarPLM == null) CalendarKey = this.DefCalendarKey; else { ImplCalendar impCalendar = null; dictCalendars.TryGetValue(calendarPLM, out impCalendar); CalendarKey = (impCalendar == null ? this.DefCalendarKey : impCalendar.GetKey()); } return CalendarKey; }
/// <summary> /// Парсинг данных из одной записи объекта ПЛМ Базовый план и сохранение их в справочнике. /// </summary> private void CollectSinglePlan(InfoObject taskobj, int revNumber) { var revisionTask = taskobj.CreateRevisionProxyByNumber(revNumber, true); clTask strTask = new clTask(); strTask.externalTask = false; // Заполнение структуры данных strTask.Obj = taskobj; strTask.Dates.DataBegTask = revisionTask.GetValue<DateTime>("StartDate"); strTask.Dates.DataEndTask = revisionTask.GetValue<DateTime>("FinishDate"); strTask.TaskName = revisionTask.GetValue<string>("TaskName"); // taskobj["TaskName"].ToString(); strTask.idPlm = revisionTask.Id; strTask.Dates.TypeOfDuration = revisionTask.GetValue<NamedValue>("TypeOfDuration"); strTask.Dates.Duration = revisionTask.GetValue<float>("Duration"); if (!dictPlanRecords.ContainsKey(taskobj)) dictPlanRecords.Add(taskobj, strTask); }
/// <summary> /// Функция считывает ресурсы при первичном чтении объекта из PLM и добавляет их в справочники /// </summary> /// <param name="obj">Объект PLM, из которого происходит чтение</param> /// <param name="strTask">Объект - структура задачи, в которую будут записаны ресурсы</param> public void AddResource(InfoObject obj, ref clTask strTask) { // Список трудовых ресурсов, входящих в текущую задачу из таблицы "Ресурсы:" var ResourcesTasks = obj.GetAttribute("Resources", AttributeDefBase.DataTypeEnum.CollectionOfElements); if (ResourcesTasks.CollectionElements.Count == 0) return; // Создание списка трудовых ресурсов для текущей задачи foreach (var resourc in ResourcesTasks.CollectionElements) { // Создание структуры трудовых ресурсов (для задачи) stResource strResource = new stResource(); // Заполнение структуры stResource(ресурсы) strResource.objResurce = resourc.GetValue<InfoObject>("ResourceLink"); strResource.responsible = IsRespUser(strTask, strResource.objResurce); strResource.unit = 1; // Проверка наличия ресурса в словаре ресурсов dictResource var gtRes = GetGTbyIO(strResource.objResurce); if (gtRes == null) { // Создание структуры трудовых ресурсов (для справочника) stResource elemResource = new stResource(); elemResource.objResurce = strResource.objResurce; // Краткое название ресурса var shortName = strResource.GetResourceNamePLM(); // Создание нового ресурса gtRes = this.GanttDiag.AddResource(shortName); // Задание календаря InfoObject resCalendar = strResource.objResurce.GetValue<InfoObject>("BasicCalendar"); gtRes.CalendarKey = ParentHelper.GetCalendarKey(resCalendar); elemResource.Res = gtRes; // Запись нового ресурса в словарь ресурсов dictResource.Add(elemResource); } strResource.Res = gtRes; // Запись в список трудовых ресурсов в структуре strTask strTask.lResourceTask.Add(strResource); } }
private List<stDependents> CreateDepedent(InfoObject obj) { // Чтение строк таблицы Временные зависимости ICollection<CollectionElement> timeDependencies = obj.GetAttribute("ProjectTaskLinks").CollectionElements; // Создание спискаструктур зависимости List<stDependents> ListStDependents = new List<stDependents>(); foreach (var it in timeDependencies) { // Создание структуры зависимости задачи stDependents curStDependents = new stDependents(); // ИО задача, от выполнения которой зависит текущая задача curStDependents.Obj = it.GetValue<InfoObject>("ProjectTask"); // Наименование задачи, от выполнения которой зависит текущая задача curStDependents.TaskName = curStDependents.Obj["TaskName"].ToString(); // Тип временной зависимости задачи curStDependents.ProjectTaskLinkType = it.GetValue<NamedValue>("ProjectTaskLinkType"); if (curStDependents.ProjectTaskLinkType == Service.GetNamedValue(@"WORKORG\ProjectTaskLinkType\l1")) // Следует после (Окончание-начало) curStDependents.typeGantt = TaskRelationTypes.EndStart; else if (curStDependents.ProjectTaskLinkType == Service.GetNamedValue(@"WORKORG\ProjectTaskLinkType\l2")) // Начать вместе с (Начало-начало) curStDependents.typeGantt = TaskRelationTypes.StartStart; else if (curStDependents.ProjectTaskLinkType == Service.GetNamedValue(@"WORKORG\ProjectTaskLinkType\l3")) // Завершить вместе с (Окончание-окончание) curStDependents.typeGantt = TaskRelationTypes.EndEnd; else if (curStDependents.ProjectTaskLinkType == Service.GetNamedValue(@"WORKORG\ProjectTaskLinkType\l4")) // Завершить до (Начало-окончание) curStDependents.typeGantt = TaskRelationTypes.StartEnd; else // Не определен curStDependents.typeGantt = (TaskRelationTypes)4; // Запаздывание (календарное) curStDependents.Delay = it.GetValue<double>("Delay"); // Ед.изм (дни/часы) curStDependents.DelayType = it.GetValue<NamedValue>("DelayType"); // Использываемый календарь curStDependents.UseTaskCalendar = it.GetValue("UseTaskCalendar", true); // Идентификатор задачи, , от выполнения которой зависит текущая задача curStDependents.idPlm = curStDependents.Obj.Id; curStDependents.IsStrict = (it.GetValue("IsStrict", true) == true ? 1 : 0); ListStDependents.Add(curStDependents); } return ListStDependents; }
/// <summary> /// Чтение данных из PLM и сохранение их во внутренних структурах /// </summary> /// <param name="obj">Объект, для которого создаётся диаграмма</param> /// <param name="initialValues">Список значений для инициализации атрибутов объекта</param> /// <returns></returns> public void CollectPLMData(InfoObject obj, ICollection<CollectionElement> attr, bool DoOperChildren) { // Импорт календарей из PLM this.CalendarsWorker.CollectCalendarsPLM(this.GanttDiag); // Импорт справочника статусов задач из ПЛМ this.StatusWorker.CollectStatusesPLM(); // Очистка списка всех задач выбранного проекта mainList.Clear(); // Очистка словаря всех задач выбранного проекта dictTasks.Clear(); if (DoOperChildren) { AddTasks2List(obj, DoOperChildren, null); for (int i = 0; i < mainList.Count; i++) (mainList[i] as clTask).nOrder = i; CollectBasePlans(); AddExternalTask(); // Сортировка элементов списка по возростанию nOrder mainList = mainList.OrderBy(pet => pet.nOrder).ToList(); } else { foreach (var rec in attr) { InfoObject flatobj = rec.GetValue<InfoObject>("ProjectTask"); if (flatobj != null) { AddTasks2List(flatobj, DoOperChildren, null); CollectBasePlans(); } for (int i = 0; i < mainList.Count; i++) (mainList[i] as clTask).nOrder = i; } } // StreamWriter LogFile1 = new StreamWriter("nOrder.txt"); // foreach (stTask st in MyForm.mainList) // { // LogFile1.WriteLine(st.Obj.ToString() + " " + st.nOrder.ToString() + // " " + st.prGroup); // } // LogFile1.Close(); }
/// <summary> /// Заполнение данных объекта PLM в таблице Ресурсы закладки "Расчёт" /// </summary> /// <param name="gtTask"></param>группа или задача Gantt /// <returns></returns> private void FillTabResources(GanttItem gtTask) { // Обновляем ресурсы только у задач (не у групп) if (gtTask.ItemType != GanttItemType.TaskItem) return; InfoObject Obj; clTask curSt = new clTask(); // Поиск структуры stTask для текущей задачи dictTasks.TryGetValue(gtTask.Key, out curSt); Obj = curSt.Obj; var attr = Obj.GetAttribute("Resources"); attr.CollectionElements.Clear(); // Поиск контейнера, содержащего ресурсы DataContainer ResourceCont = null; foreach (var resource in curSt.lResourceTask) if (resource.objResurce != null) { ResourceCont = resource.objResurce.Container; break; } foreach (var resource in curSt.lResourceTask) { var objResurce = resource.objResurce; if (objResurce == null && ResourceCont != null) { objResurce = new InfoObject(ResourceCont, @"InfoObjects\WORKORG\Resources\Resource\WorkingResource"); objResurce["ResourceName"] = resource.GetResourceNameGantt(); objResurce["ShortResourceName"] = resource.GetResourceNameGantt(); objResurce["BasicCalendar"] = Obj.GetValue<InfoObject>("Calendar"); objResurce.Save(); } if (objResurce != null) { var item = attr.CreateCollectionElement(); item["ResourceLink"] = objResurce; attr.CollectionElements.Add(item); } } }
/// <summary> /// Der Haupteinstiegspunkt für die Anwendung. /// </summary> static public void main(InfoObject obj, EntityAttribute attr, String job) { CursorWait(); // var fontMenu = SystemFonts.MenuFont; // var fontCaption = SystemFonts.CaptionFont; // var fontDialog = SystemFonts.DialogFont; // var fontMessageBox = SystemFonts.MessageBoxFont; // var fontSmallCaptionFont = SystemFonts.SmallCaptionFont; // var fontStatusFont = SystemFonts.StatusFont; // Fonts.SystemFontFamilies StartUpUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; string strGUILanguage = KS.Common.Strings.GetSafeString(GetMySetting("GUILanguage", "")); switch (strGUILanguage) { case "de": System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de-DE"); break; case "en": System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); break; case "fr": System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr-FR"); break; case "it": System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("it-IT"); break; case "es": System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("es-ES"); break; case "ru": System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ru-RU"); break; case "zh": //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CHS"); System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CN"); break; default: if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name.StartsWith("de")) System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de-DE"); else if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name.StartsWith("fr")) System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr-FR"); else if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name.StartsWith("it")) System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("it-IT"); else if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name.StartsWith("es")) System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("es-ES"); else if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name.StartsWith("ru")) System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ru-RU"); else if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name.StartsWith("zh")) //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CHS"); System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CN"); else System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); break; } fMainForm = new frmMain(obj, attr, job); FilterByResponce.ClearFilter(); fMainForm.ucGantt1.gantt1.StartDate = DateTime.Now.AddMonths(0); // Установка параметров KS.Gantt.Gantt fMainForm.SetGanttProperties(); // Установка параметров PLM fMainForm.SetPlmProperties(); // Подготовка, соддание данных и создания диаграммы Ганта fMainForm.GenerationGanttData(); fMainForm.toolStrip1.Font = fMainForm.ucGantt1.gantt1.Font; fMainForm.Show(); }
/// <summary> /// Функция определяет, соответствует ли ресурс Ответственному /// </summary> /// <param name="key">Объект ДГ, по которому происходит поиск</param> private bool IsRespUser(clTask strTask, InfoObject objResurce) { bool result = false; // Определение ИО из User if (strTask.ResponsibleUser != null) { var userRes = strTask.ResponsibleUser.GetValue<InfoObject>("WorkingResource"); if (userRes != null && objResurce.Id == userRes.Id) result = true; } return result; }
/// <summary> /// Поиск ИО, у которого в таблице "Состоит из" находится ИО из chlidSt /// и удаление из таблицы ИО в PLM записи о ИО из chlidSt /// </summary> /// <param name="Obj"></param>ИО PLM, в таблицу которого будет вставляться /// <param name="chlidSt"></param>структура задачи ИО, которого надо найти void FindChild(InfoObject Obj, clTask childSt) { var lChildr = mainList.Where(o => o.lChildrTask.Count() != 0).ToArray(); foreach (clTask curSt in lChildr) { for (int i = 0; i < curSt.lChildrTask.Count; i++) { // Есть задачи, входящие в таблицу "Состоит из" var curChlidSt = curSt.lChildrTask[i]; if (childSt.idPlm == curChlidSt.idPlm) // В таблице "Состоит из" есть запись о ИО из chlidSt { if (Obj.Id != curSt.idPlm) // Дочерняя задача была перемещена из curSt.Obj в Obj { // Удаление строки из таблицы "Состоит из" curSt.Obj var listTabSb = curSt.Obj.GetAttribute("SubTaskList"); if (listTabSb == null) continue; foreach (var item in listTabSb.CollectionElements) { InfoObject io = item.GetValue<InfoObject>("ProjectTask"); if (io != null && io.Id == childSt.idPlm) listTabSb.CollectionElements.Remove(item); } /* TODO remove after test for (int j = 0; j < listTabSb.Count; j++) { InfoObject io = (InfoObject)listTabSb.ElementAt(j)["ProjectTask"]; if (io != null && io.Id == chlidSt.idPlm) { listTabSb.Remove(listTabSb.ElementAt(j)); } } */ } } } } }
/// <summary> /// Конструктор. /// </summary> /// <param name="GanttParent">Объект ПЛМ, от имени которого запущена диаграмма Гантта</param> /// <param name="GanttDiag">Диаграмма, на которой происходит рисование (передаётся из родительской формы)</param> /// <param name="InstHelperPLM">Объект ПЛМ, от имени которого запущена диаграмма Гантта</param> public CustExpand(InfoObject GanttParent, Gantt GanttDiag, HelperPLM InstHelperPLM) { this.GanttDiag = GanttDiag; this.GanttParent = GanttParent; this.InstHelperPLM = InstHelperPLM; }
public bool SavePlm() { GanttItem gt; var noObj = mainList.Where(o => o.Obj == null).ToArray(); InfoObject parentObj = this.GanttParent; if (noObj.Count() > 0) { #region Определение алгоритма сохранения новых задач // Новая задача будет создаваться в контейнере родительского объекта. // Далее надо анализировать состав родительского объекта. // Если составе что-то есть - то это группа и надо новую задачу добавлять в состав родительского объекта. // Если нет атрибута Состав, либо он пустой, то ничего добавлять не нужно. DataContainer homecont = parentObj.Container; var SubTaskList = parentObj.GetAttribute("SubTaskList"); bool add2Group = (SubTaskList != null && SubTaskList.CollectionElements.Count() > 0); #endregion #region Cохранение новых задач using (Service.EnterNewGroupOperation()) { foreach (clTask stObj in noObj) { // stObj - структура добавленной задачи int index = mainList.IndexOf(stObj); /*/TODO Остатки кода Ромы. Наверное, можно будет удалить * Новая задача созданная в Ганте // Определение родительского ИО в PLM для созданной задачи stParentTask rabStPar = stObj.lParentTask[0]; // Данные родительской задачи if (rabStPar.Obj == null) // Не указан ИО родительской задачи { // Поиск данных родительской задачи clTask rabSt; dictTasks.TryGetValue(stObj.lParentTask[0].keyGantt, out rabSt); if (rabSt != null && rabSt.Obj != null) { // Найден ИО родительской задачи rabStPar.Obj = rabSt.Obj; stObj.lParentTask[0] = rabStPar; } } parentObj = stObj.lParentTask[0].Obj; */ // Создание новой задачи InfoObject newObj = new InfoObject(homecont, @"InfoObjects\WORKORG\Projects\TaskOfProject"); // Задание "Вид" - - обязательный newObj["KindOfTask"] = GetTaskTypePlm(stObj); // Задание "Наименование" - обязательный newObj["TaskName"] = stObj.TaskName; // Задание "Статус" - Новая - обязательный newObj["State"] = Service.GetNamedValue(@"WORKORG\TaskStatus\ts01"); newObj.Save(); if (add2Group) { var item = SubTaskList.CreateCollectionElement(); item["ProjectTask"] = newObj; SubTaskList.CollectionElements.Add(item); } stObj.Obj = newObj; stObj.idPlm = newObj.Id; mainList[index] = stObj; dictTasks[stObj.keyGantt] = stObj; } Service.SaveChanges(); } #endregion } foreach (var st in mainList) { if (st.externalTask == false) // false - задача внутри выбранного проекта { if (st.bGroup == true) // true - текущая структура для группы gt = this.GanttDiag.Groups.FindItemByKey(st.keyGantt); else // false - текущая структура для задачи gt = this.GanttDiag.Tasks.FindItemByKey(st.keyGantt); try { SaveGroupPlm(st, gt); } catch (Exception ex) { st.Obj.CancelChanges(); string mess = ex.Message + @"/n"; if (ex.InnerException != null) mess += ex.InnerException.Message; Program.ErrMsgBox(mess); return false; } } } return true; }
public String TaskIdent; // Атрибут "Идентификатор" задачи из PLM public clTask() { bGroup = false; nOrder = 0; TaskName = ""; Dates = new clTabDates(); Obj = null; lChildrTask = new List<clTask>(); lParentTask = new List<stParentTask>(); lResourceTask = new List<stResource>(); externalTask = true; Status = null; ResponsibleUser = null; ResponsibleExecutive = ""; Priority = 0; keyGantt = ""; idPlm = 0; Content = ""; Constraints = new stConstraints(); TaskIdent = ""; }
public List<stDependents> lDependentTask; // Список зависимостей задачи public clTabDates() { bData = false; // Признак заданной даты задачи DataBegTask = DateTime.MinValue; // Дата начала задачи RuleForStartDate = null; // Правило для Даты начала DataEndTask = DateTime.MinValue; // Дата окончания задачи RuleForFinishDate = null; // Правило для Даты окончания Duration = 0; // Значение длительности TypeOfDuration = null; // Единица измерения длительности (дни/часы) calendar = null; // Календарь Percentage = 0; // Процент выполнения задач lDependentTask = new List<stDependents>(); // Список зависимостей задачи }
public void FillclTask(InfoObject obj) { this.bGroup = false; this.Obj = obj; this.TaskName = obj["TaskName"].ToString(); var content = obj.GetValue<RichTextProxy>("Content"); this.Content = (content == null ? "" : content.PlainText); this.idPlm = obj.Id; this.Dates.RuleForStartDate = obj.GetValue<NamedValue>("RuleForStartDate"); this.Dates.RuleForFinishDate = obj.GetValue<NamedValue>("RuleForFinishDate"); this.Dates.calendar = obj.GetValue<InfoObject>("Calendar"); this.Dates.TypeOfDuration = obj.GetValue<NamedValue>("TypeOfDuration"); this.Dates.Duration = obj.GetValue<float>("Duration"); this.Constraints.StartDateNoEarlierThan = obj.GetValue<DateTime?>("StartDateNoEarlierThan"); this.Constraints.StartDateNoLaterThan = obj.GetValue<DateTime?>("StartDateNoLaterThan"); this.Constraints.FinishDateNotEarlierThan = obj.GetValue<DateTime?>("FinishDateNotEarlierThan"); this.Constraints.FinishDateNoLaterThan = obj.GetValue<DateTime?>("FinishDateNoLaterThan"); var TaskType = obj.GetValue<Template>("KindOfTask"); this.SetMilestone(TaskType.NameKey == "Milestone"); // Дата начала выполнения задачи if (obj.GetValue<DateTime?>("StartDate").HasValue) { this.Dates.bData = true; this.Dates.DataBegTask = obj.GetValue<DateTime>("StartDate"); } else // Дата не задана this.Dates.DataBegTask = DateTime.Now; // Дата окончания выполнения задачи if (obj.GetValue<DateTime?>("FinishDate").HasValue) { this.Dates.bData = true; this.Dates.DataEndTask = obj.GetValue<DateTime>("FinishDate"); } else // Дата не задана this.Dates.DataEndTask = DateTime.Now; // Определение статуса this.Status = obj.GetValue<NamedValue>("State"); // Процент выполнения задачи this.Dates.Percentage = obj.GetValue<int>("Percentage"); if (this.Status.NameKey != "Finished" && this.Dates.Percentage == 100) this.Dates.Percentage = 99; // Определение ответственного исполнителя this.ResponsibleUser = obj.GetValue<User>("ResponsibleExecutive"); if (this.ResponsibleUser != null) { this.ResponsibleExecutive = (this.ResponsibleUser.GetValue<String>("GivenName") + " " + this.ResponsibleUser.GetValue<string>("FirstName") + " " + this.ResponsibleUser.GetValue<string>("SecondName")).Trim(); } else this.ResponsibleExecutive = ""; // Определение приоритета this.Priority = obj.GetValue<int>("Priority"); // Определение Идентификатора this.TaskIdent = obj.GetValue<string>("Id"); }
/// <summary> /// Задание времени работы по дням недели по данным PLM для календаря Gantt /// </summary> private void SetWorkingDays(InfoObject calendarPLM) { this.intCalendar.InitDefaultWorkingDays(); this.intCalendar.ClearAllWorkingHours(); for (int i = 0; i < 7; i++) { ICollection<CollectionElement> ceSchedule = calendarPLM.GetAttribute("Schedule" + i.ToString()). CollectionElements.OrderBy(e => e.GetValue<TimeSpan>("TimeSpanFrom").Hours).ToList(); if (ceSchedule != null) SetOneDay(i, ceSchedule); } }
/// <summary> /// Функция ищет в справочнике объект ДГ по соответствующему объекту ПЛМ /// </summary> /// <param name="key">Объект ПЛМ, по которому происходит поиск</param> private ResourceItem GetGTbyIO(InfoObject key) { ResourceItem result = null; for (int i = 0; i < this.dictResource.Count; i++) { var element = (stResource)dictResource[i]; if (element.objResurce == key) { result = element.Res; break; } } return result; }
/// <summary> /// Функция ищет в справочнике импортированных календарей календарь Гантта по календарю PLM. /// </summary> /// <param name="calendarPLM">Календарь PLM</param> public string GetCalendarKey(InfoObject calendarPLM) { return this.CalendarsWorker.GetCalendarKey(calendarPLM); }
/// <summary> /// Чтение данных из объекта ПЛМ. /// Создание списка всех задач, входящих в выбранный объект, включаяя задачи, находящиеся вне объекта. /// Объекты могут содержать дерево задач (Задача, Группа задач, Проект) - в этом случае DoOperChildren = true, /// а могут содержать плоский список задач (Ресурсы, Задачи сотрудника) - в этом случае DoOperChildren = false. /// </summary> /// <param name="obj">Объект, который будет считан</param> /// <param name="DoReadChildren">Признак - формировать объекты Гантта изи входящих задач или нет</param> /// <returns> List<stTask> - расширенных список задач </returns> private clTask AddTasks2List(InfoObject obj, bool DoOperChildren, clTask ParentTask) { clTask strTask = new clTask();// Структура дочерней задачи strTask.ParentTask = ParentTask; strTask.externalTask = false; strTask.Dates.bData = false; strTask.FillclTask(obj); strTask.Dates.lDependentTask = CreateDepedent(strTask.Obj); // Список родительских задач(ParentTasks) для задачи obj из таблицы "Входит в:" var ParentTasks = obj.GetAttribute("ParentList", AttributeDefBase.DataTypeEnum.CollectionOfElements); if (ParentTasks != null) { // Создание списка родительских задач в структуре strTask foreach (var task in ParentTasks.CollectionElements) { // Запись в список родительских задач в структуре strTask HelperClasses.stParentTask stPT = new HelperClasses.stParentTask(); stPT.Obj = task.GetValue<InfoObject>("ProjectTask"); stPT.IsPrimary = task.GetValue<bool>("IsPrimary"); // Наименование задачи stPT.TaskName = stPT.Obj["TaskName"].ToString(); // Идентификатор объекта из PLM stPT.idPlm = stPT.Obj.Id; strTask.lParentTask.Add(stPT); } } ResourceWorker.AddResource(obj, ref strTask); mainList.Add(strTask); if (DoOperChildren) { // Если установлен ShowTopLevel, то из ПЛМ считается только один уровень задач DoOperChildren = !this.ShowTopLevel; // Список дочерних задач для задачи obj - listChildr из таблицы "Состоит из:" var listChildr = obj.GetAttribute("SubTaskList").CollectionElements.ToList(); strTask.bGroup = (listChildr.Count() != 0); // Сортировка дочерних задач по Order listChildr = listChildr.OrderBy(pet => pet.GetValue<int>("Order")).ToList(); // Создание списка дочерних задач в структуре strTask foreach (var lC in listChildr) { // Дочерняя задача для задачи obj InfoObject childObj = lC.GetValue<InfoObject>("ProjectTask"); strTask.lChildrTask.Add(AddTasks2List(childObj, DoOperChildren, strTask)); } } else strTask.bGroup = false; return strTask; }
public frmMain(InfoObject obj, EntityAttribute attr, String job) { this.Font = SystemFonts.MessageBoxFont; InitializeComponent(); this.DefGanttComparer = ucGantt1.gantt1.LayoutLogic.ItemComparer; SetFormFont(); MyJob = job; MyObj = obj; if (attr != null) MyAttr = attr.CollectionElements; ucGantt1.gantt1.Project.Text = (MyObj != null ? MyObj["TaskName"].ToString() : ""); if (MyJob != "Project") { // You want a readonly control ? ucGantt1.gantt1.AllowEdit = false; ucGantt1.ganttDataGrid1.AllowEdit = false; ucGantt1.ganttDataGrid1.SelectionMode = GanttDataGrid.GanttDataGridSelectionModes.Row; } ucGantt1.gantt1.SuspendItemLayout(); ucGantt1.ganttDataGrid1.SelectionMode = GanttDataGrid.GanttDataGridSelectionModes.Cell; ucGantt1.gantt1.ItemsChanged += new EventHandler(gantt1_ItemsChanged); ucGantt1.gantt1.SelectionChanged += new Gantt.SelectionChangedEventHandler(gantt1_SelectionChanged); ucGantt1.ganttDataGrid1.UpdateEditMenu += new EventHandler(ganttDataGrid1_UpdateEditMenu); ucGantt1.gantt1.ViewModeChanged += new EventHandler(gantt1_ViewModeChanged); ucGantt1.gantt1.ItemDoubleClick += new KS.Gantt.Gantt.ItemDoubleClickEventHandler(gantt1_ItemDoubleClick); ucGantt1.gantt1.ItemClick += new KS.Gantt.Gantt.ItemClickEventHandler(gantt1_ItemClick); ucGantt1.gantt1.BeforeDelete += new KS.Gantt.Gantt.BeforeDeleteEventHandler(gantt1_BeforeDelete); // ucGantt1.gantt1.Update += new da(gantt1_Updata); ucGantt1.gantt1.MovingItem += new KS.Gantt.Gantt.MovingItemEventHandler(gantt1_MovingItem); ucGantt1.gantt1.ItemsMoved += new EventHandler(gantt1_ItemsMoved); ucGantt1.gantt1.ItemsResized += new EventHandler(gantt1_ItemsResized); ucGantt1.gantt1.ItemHover += new KS.Gantt.Gantt.ItemHoverEventHandler(gantt1_ItemHover); ucGantt1.gantt1.AfterAddItem2Group += new Gantt.AfterAddItem2GroupEventHandler(gantt1_AfterAddItem2Group); SetGanttDefaults(); #region Настройка команд меню mnuSelectAll.Click += new EventHandler(mnuSelectAll_Click); mnuInverseSelection.Click += new EventHandler(mnuInverseSelection_Click); mnuCollapseGroups.Click += new EventHandler(mnuCollapseGroups_Click); mnuExpandGroups.Click += new EventHandler(mnuExpandGroups_Click); mnuUndo.Click += new EventHandler(mnuUndo_Click); mnuUndo1.Click += new EventHandler(mnuUndo_Click); mnuRedo.Click += new EventHandler(mnuRedo_Click); mnuRedo1.Click += new EventHandler(mnuRedo_Click); mnuCut.Click += new EventHandler(mnuCut_Click); mnuCopy.Click += new EventHandler(mnuCopy_Click); mnuPaste.Click += new EventHandler(mnuPaste_Click); mnuDelete.Click += new EventHandler(mnuDelete_Click); mnuTaskView.Click += new EventHandler(mnuTaskView_Click); mnuResourceView.Click += new EventHandler(mnuResourceView_Click); mnuExit.Click += new EventHandler(mnuExit_Click); mnuZoomToFit.Click += new EventHandler(mnuZoomToFit_Click); mnuCenterNow.Click += new EventHandler(mnuCenterNow_Click); mnuZoomIn.Click += new EventHandler(mnuZoomIn_Click); mnuZoomOut.Click += new EventHandler(mnuZoomOut_Click); mnuAddTask.Click += new EventHandler(mnuAddTask_Click); mnuAddTask1.Click += new EventHandler(mnuAddTask_Click); mnuAddGroup.Click += new EventHandler(mnuAddGroup_Click); mnuAddGroup1.Click += new EventHandler(mnuAddGroup_Click); mnuAddResource.Click += new EventHandler(mnuAddResource_Click); mnuAddResource1.Click += new EventHandler(mnuAddResource_Click); mnuNew1.Click += new EventHandler(mnuNew_Click); mnuNew.Click += new EventHandler(mnuNew_Click); mnuNewInstance.Click += new EventHandler(mnuNewInstance_Click); //mnuOpen1.Click += new EventHandler(mnuOpen_Click); //mnuOpen.Click += new EventHandler(mnuOpen_Click); mnuSave1.Click += new EventHandler(mnuSave_Click); mnuSave.Click += new EventHandler(mnuSave_Click); mnuSaveAs.Click += new EventHandler(mnuSaveAs_Click); mnuExportAsImage.Click += new EventHandler(mnuExportAsImage_Click); mnuExportAsXML.Click += new EventHandler(mnuExportAsXML_Click); mnuImportFromXML.Click += new EventHandler(mnuImportFromXML_Click); mnuPrintPageSetup.Click += new EventHandler(mnuPrintPageSetup_Click); mnuPrintPreview.Click += new EventHandler(mnuPrintPreview_Click); mnuPrint.Click += new EventHandler(mnuPrint_Click); mnuAbout.Click += new EventHandler(mnuAbout_Click); mnuAbout1.Click += new EventHandler(mnuAbout_Click); mnuHelpIndex.Click += new EventHandler(mnuHelpIndex_Click); mnuHelpIndex1.Click += new EventHandler(mnuHelpIndex_Click); mnuKrollSoftwareWebsite.Click += new EventHandler(mnuKrollSoftwareWebsite_Click); mnuProjectSettings.Click += new EventHandler(mnuProjectSettings_Click); mnuProjectSettings1.Click += new EventHandler(mnuProjectSettings_Click); mnuProjectCalendars.Click += new EventHandler(mnuProjectCalendars_Click); mnuProjectCalendars1.Click += new EventHandler(mnuProjectCalendars_Click); mnuProjectCost.Click += new EventHandler(mnuProjectCost_Click); mnuProjectCost1.Click += new EventHandler(mnuProjectCost_Click); mnuASAP.Click += new EventHandler(mnuASAP_Click); mnuASAP1.Click += new EventHandler(mnuASAP_Click); mnuSolve.Click += new EventHandler(mnuSolve_Click); mnuSolve1.Click += new EventHandler(mnuSolve_Click); mnuPathDimming.Click += new EventHandler(mnuPathDimming_Click); ucGantt1.gantt1.PathDimmingChanged += new EventHandler(gantt1_PathDimmingChanged); mnuMaxZoomLevelGranularity.Checked = true; mnuMaxZoomLevelGranularity.Click += new EventHandler(mnuMaxZoomLevelGranularity_Click); mnuMaxZoomLevelMinute.Click += new EventHandler(mnuMaxZoomLevelMinute_Click); ucGantt1.gantt1.MaxZoomLevelChanged += new EventHandler(gantt1_MaxZoomLevelChanged); ucGantt1.gantt1.GranularityChanged += new EventHandler(gantt1_GranularityChanged); mnuFind.Click += new EventHandler(mnuFind_Click); mnuFindMore.Click += new EventHandler(mnuFindMore_Click); mnuFind1.Click += new EventHandler(mnuFind_Click); mnuFindMore1.Click += new EventHandler(mnuFindMore_Click); #endregion ucGantt1.gantt1.ResetModified(); ucGantt1.gantt1.HistoryClear(); ucGantt1.gantt1.ResumeItemLayout(); ucGantt1.gantt1.HistoryChanged += new EventHandler(gantt1_HistoryChanged); ucGantt1.gantt1.ShowStatus += new Gantt.ShowStatusEventHandler(gantt1_ShowStatus); tabMain.SelectedIndexChanged += new EventHandler(tabMain_SelectedIndexChanged); SetUpContextMenu(); SetUpContextMenu4DataGrid(); // Test Topo ucGantt1.gantt1.CustomItemTextDisplay += new Gantt.ItemTextDisplayEventHandler(gantt1_CustomItemTextDisplay); this.KeyDown += new KeyEventHandler(frmMain_KeyDown); // *************** Load ****************** ucGantt1.parent = this; ucTasks1.GanttControl = ucGantt1.gantt1; ucTasks1.parent = this; ucResources1.GanttControl = ucGantt1.gantt1; ucGroups1.GanttControl = ucGantt1.gantt1; ucSkills1.GanttControl = ucGantt1.gantt1; ucSchedule1.GanttControl = ucGantt1.gantt1; ucGantt1.gantt1.UndoRedoCalled += new EventHandler(gantt1_UndoRedoCalled); ResetLanguageMenu(); CheckSelectedLanguageMenu(); // Set some language specific texts ucGantt1.gantt1.NewTaskName = Properties.Resources.NewTaskName; ucGantt1.gantt1.WeekPrefix = Properties.Resources.WeekPrefix; ucGantt1.gantt1.PathDimming = Strings.GetSafeBool(Program.GetMySetting("PathDimming", 1)); bool bMaxZoomLevelMinute = Strings.GetSafeBool(Program.GetMySetting("MaxZoomLevelMinute", 1)); if (bMaxZoomLevelMinute) ucGantt1.gantt1.MaxZoomLevel = Gantt.ZoomLevels.Minute; else ucGantt1.gantt1.MaxZoomLevel = Gantt.ZoomLevels.Granularity; KS.Gantt.Helpers.DialogTitle = Program.DialogTitle; // MRU FileList mruManager = new MRUManager(); mruManager.Initialize( this, // owner form mnuFileMRU, // Recent Files menu item Program.C_RegistrySectionKey); // Registry path to keep MRU list // Optional. Call these functions to change default values: //mruManager.CurrentDir = "....."; // default is current directory mruManager.MaxMRULength = 7; // default is 10 mruManager.MaxDisplayNameLength = 60; // default is 40 #region Some Shortcuts // Setting Shortcut Keys by resource, throws errors in different Visual-Studio language versions. // This is, why we set them by code mnuNew.ShortcutKeys = Keys.N | Keys.Control; mnuNewInstance.ShortcutKeys = Keys.N | Keys.Control | Keys.Alt; mnuOpen.ShortcutKeys = Keys.O | Keys.Control; mnuSave.ShortcutKeys = Keys.S | Keys.Control; mnuSaveAs.ShortcutKeys = Keys.S | Keys.Control | Keys.Alt; mnuPrint.ShortcutKeys = Keys.P | Keys.Control; mnuTaskView.ShortcutKeys = Keys.T | Keys.Control; mnuResourceView.ShortcutKeys = Keys.R | Keys.Control; mnuZoomToFit.ShortcutKeys = Keys.M | Keys.Control; mnuCenterNow.ShortcutKeys = Keys.M | Keys.Alt; mnuSelectAll.ShortcutKeys = Keys.A | Keys.Control; mnuUndo.ShortcutKeys = Keys.Z | Keys.Control; mnuRedo.ShortcutKeys = Keys.Y | Keys.Control; mnuDelete.ShortcutKeys = Keys.Delete; mnuCut.ShortcutKeys = Keys.X | Keys.Control; mnuCopy.ShortcutKeys = Keys.C | Keys.Control; mnuPaste.ShortcutKeys = Keys.V | Keys.Control; mnuFind.ShortcutKeys = Keys.F | Keys.Control; mnuASAP.ShortcutKeys = Keys.L | Keys.Control; mnuExpandGroups.ShortcutKeys = Keys.Oemplus | Keys.Control; mnuCollapseGroups.ShortcutKeys = Keys.OemMinus | Keys.Control; mnuExpandGroups.ShortcutKeyDisplayString = "Ctrl + Plus"; mnuCollapseGroups.ShortcutKeyDisplayString = "Ctrl + Minus"; #endregion InstHelperPLM = new HelperPLM(this.MyObj, ucGantt1.gantt1); }