Esempio n. 1
0
        private void DeleteExistingMenuItem()
        {
            // Show all menu items
            ViewAllMenuItems();

            // Get the number of the item to remove
            Console.WriteLine("Enter the number of the Menu Item to remove.");
            int mealNumberInput = Utilites.GetIntFromUser();

            // Call the delete method
            bool wasDeleted = _menuRepo.RemoveMenuFromList(mealNumberInput);

            // If the item was deleted, say so. otherwise say so.
            if (wasDeleted)
            {
                Console.WriteLine("The menu item was successfully deleted.");
            }
            else
            {
                Console.WriteLine("The menu item could not be deleted");
            }
        }
Esempio n. 2
0
 private bool SetFilter(string sys2Detect)
 {
     if (sys2Detect.ToLower().Equals("spn43"))
     {
         preselector.Set3_5Filter();
     }
     else if (sys2Detect.ToLower().Equals("boatnav"))
     {
         preselector.Set3_0Filter();
     }
     else if (sys2Detect.ToLower().Equals("asr"))
     {
         preselector.SetBypass();
     }
     else
     {
         Utilites.LogMessage("invalid sys2Detect " +
                             "in Measurement parameters object");
         return(true);
     }
     return(false);
 }
Esempio n. 3
0
        /// <summary>
        /// Отправить ответ на заказ в систему EDI
        /// </summary>
        /// <param name="order">отправляемый заказ</param>
        internal static void SendOrdrsp(DocumentOrderResponse order)
        {
            if (order == null)
            {
                Utilites.Error("При отправке ответа на заказ: не выбран заказ"); return;
            }
            if (order.DocumentParties == null)
            {
                Utilites.Error("При отправке ответа на заказ: отсутсвуют части документа(DocumentParties)"); return;
            }
            if (order.DocumentParties?.Receiver == null)
            {
                Utilites.Error("При отправке ответа на заказ: отсутствует отправитель"); return;
            }
            if (String.IsNullOrEmpty(order.DocumentParties.Receiver.ILN))
            {
                Utilites.Error("При отправке ответа на заказ: у отправителя отсутствует GLN"); return;
            }
            if (SelectedRelationship == null || SelectedRelationship.documentType == null)
            {
                Utilites.Error("При отправке ответа на заказ: не выбран клиент"); return;
            }
            if (SelectedRelationship.partnerIln == null)
            {
                Utilites.Error("Невозможная ошибка: у клиента отсутствует GLN (звоните в IT-отдел!)"); return;
            }
            if (order.DocumentParties.Receiver.ILN != SelectedRelationship.partnerIln)
            {
                Utilites.Error("Нельзя отправить документ другому клиенту! Выберите соответствующего документу клиента и повторите отправку."); return;
            }

            var sendOrder = XmlService <DocumentOrderResponse> .Serialize(order);

            EdiService.Send(SelectedRelationship.partnerIln, "ORDRSP", "", "", "", "", sendOrder, 20);
            var sql = SqlConfiguratorService.Sql_UpdateEdiDocSetIsInEdiAsORDRSP(order.OrderResponseHeader.OrderResponseNumber);

            DbService.Insert(sql);
        }
        /// <summary>
        /// Отправить извещение об отгрузке в систему EDI
        /// </summary>
        /// <param name="advice">отправляемый заказ</param>
        internal static void SendDesadv(DocumentDespatchAdvice advice)
        {
            if (advice == null)
            {
                Utilites.Error("При отправке уведомления об отгрузке: не выбран заказ"); return;
            }
            if (advice.DocumentParties == null)
            {
                Utilites.Error("При отправке уведомления об отгрузке: отсутсвуют части документа(DocumentParties)"); return;
            }
            if (advice.DocumentParties?.Receiver == null)
            {
                Utilites.Error("При отправке уведомления об отгрузке: отсутствует отправитель"); return;
            }
            if (String.IsNullOrEmpty(advice.DocumentParties.Receiver.ILN))
            {
                Utilites.Error("При отправке уведомления об отгрузке: у отправителя отсутствует GLN"); return;
            }
            if (SelectedRelationship == null)
            {
                Utilites.Error("При отправке уведомления об отгрузке: не выбран покупатель"); return;
            }
            if (SelectedRelationship.partnerIln == null)
            {
                Utilites.Error("Невозможная ошибка: у покупателя отсутствует GLN (звоните в IT-отдел!)"); return;
            }
            if (advice.DocumentParties.Receiver.ILN != SelectedRelationship.partnerIln)
            {
                Utilites.Error("Нельзя отправить документ другому покупателю! Выберите соответствующего документу покупателя и повторите отправку."); return;
            }

            var doc = XmlService <DocumentDespatchAdvice> .Serialize(advice);

            EdiService.Send(SelectedRelationship?.partnerIln, "DESADV", "", "", "", "", doc, 200);
            var sql = SqlConfiguratorService.Sql_UpdateEdiDocSetIsInEdiAsDESADV(advice.DespatchAdviceHeader.DespatchAdviceNumber);

            DbService.Insert(sql);
        }
Esempio n. 5
0
 public WindowsImage(DismImageInfo info)
 {
     this._imageType        = info.ImageType;
     this._imageIndex       = info.ImageIndex;
     this._imageName        = info.ImageName;
     this._imageDescription = info.ImageDescription;
     this._imageSize        = info.ImageSize;
     this._architecture     = info.Architecture;
     this._productName      = info.ProductName;
     this._editionId        = info.EditionId;
     this._installationType = info.InstallationType;
     this._hal          = info.Hal;
     this._productType  = info.ProductType;
     this._productSuite = info.ProductSuite;
     this._version      = new Version(
         (int)info.MajorVersion,
         (int)info.MinorVersion,
         (int)info.Build
         );
     this._spBuild    = info.SpBuild;
     this._spLevel    = info.SpLevel;
     this._bootable   = info.Bootable;
     this._systemRoot = info.SystemRoot;
     this._languages  = new Collection <string>(
         Utilites.PtrToArray <DismString>(
             info.Language,
             info.LanguageCount
             )
         .Select(l => l.Value)
         .ToList()
         );
     this._defaultLanguageIndex = info.DefaultLanguageIndex;
     this._customizedInfo       = info.CustomizedInfo == IntPtr.Zero
         ? null
         : new WimCustomizedInfo(
         Marshal.PtrToStructure <DismWimCustomizedInfo>(info.CustomizedInfo)
         );
 }
Esempio n. 6
0
 public static void LoginScript(HtmlContainerControl div, String username, String password)
 {
     try
     {
         using (Helpdesk.Entities.Agences.AgenceEntities db = new Helpdesk.Entities.Agences.AgenceEntities())
         {
             String encryptedpass = Utilitaire.Encryption.AESEncryption.Encrypt(password);
             var    req           = from valeur in db.Responsables where (valeur.Username == username && valeur.Password == encryptedpass && (valeur.Niveau == 1 || valeur.Niveau == 2) && valeur.Role == 1) select valeur;
             var    r             = req.FirstOrDefault();
             if (r != null)
             {
                 Utilites.MSG(div, "Login Successfull", "Successful");
                 HttpCookie userck = new HttpCookie("userInfo");
                 userck.Values["ID"]       = r.ID.ToString();
                 userck.Values["Password"] = r.Password;
                 userck.Values["Username"] = r.Username;
                 userck.Values["Nom"]      = r.Nom;
                 userck.Values["Email"]    = r.Email;
                 userck.Values["Prenom"]   = r.Prenom;
                 userck.Values["Level"]    = r.Niveau.ToString();
                 userck.Expires            = DateTime.Now.AddDays(30);
                 System.Web.HttpContext.Current.Response.Cookies.Add(userck);
                 Helpdesk.Entities.Agences.Historique_Login hislog = new Entities.Agences.Historique_Login()
                 {
                     ID_User = r.ID, Time = DateTime.Now.TimeOfDay, Date = DateTime.Now.Date, Hostname = Helpdesk.Utilitaire.Reseau.Network.GetHostname(), IPAdresse = Helpdesk.Utilitaire.Reseau.Network.GetIpLocale()
                 };
                 db.AddToHistorique_Login(hislog);
                 db.SaveChanges();
                 Utilites.redirect("Dashboard.aspx");
             }
             else
             {
                 Utilites.MSG(div, "Your login was not found in database", "Invalid Login");
             }
         }
     }
     catch (System.Data.SqlClient.SqlException sql) { Utilites.MSG(div, sql.Message, sql.Errors.ToString()); }
 }
Esempio n. 7
0
 protected MetroSetForm()
 {
     SetStyle(
         ControlStyles.UserPaint |
         ControlStyles.AllPaintingInWmPaint |
         ControlStyles.ResizeRedraw |
         ControlStyles.OptimizedDoubleBuffer |
         ControlStyles.ContainerControl |
         ControlStyles.SupportsTransparentBackColor, true);
     UpdateStyles();
     _mth            = new Methods();
     _utl            = new Utilites();
     _user32         = new User32();
     Padding         = new Padding(12, 70, 12, 12);
     FormBorderStyle = FormBorderStyle.None;
     _backgroundImageTransparency = 0.90f;
     base.Font        = MetroSetFonts.SemiLight(13);
     DropShadowEffect = true;
     _showLeftRect    = true;
     _showHeader      = false;
     AllowResize      = true;
     ApplyTheme();
 }
Esempio n. 8
0
        /// <summary>
        /// Create cell.
        /// </summary>
        /// <param name="parent">Parent gameobject.</param>
        /// <param name="name">Cell name.</param>
        /// <param name="alignment">Cell layout alignment.</param>
        /// <returns>Cell transform.</returns>
        protected static Transform CreateCell(Transform parent, string name, TextAnchor alignment = TextAnchor.MiddleLeft)
        {
            var image = CreateObject <Image>(parent, name);

            image.color = Color.black;

            var lg = Utilites.GetOrAddComponent <HorizontalLayoutGroup>(image.gameObject);

#if UNITY_5_5_OR_NEWER
            lg.childControlWidth  = true;
            lg.childControlHeight = true;
#endif
            lg.childForceExpandWidth  = false;
            lg.childForceExpandHeight = false;
            lg.childAlignment         = alignment;
            lg.padding = new RectOffset(5, 5, 5, 5);
            lg.spacing = 5;

            var le = Utilites.GetOrAddComponent <LayoutElement>(image.gameObject);
            le.minWidth = 100;

            return(image.transform);
        }
Esempio n. 9
0
        public async Task <State> ProcessCompletedTranscribeJobsAsync(State state, ILambdaContext context)
        {
            var request = new GetTranscriptionJobRequest
            {
                TranscriptionJobName = state.TranscriptionJobName
            };

            context.Logger.LogLine($"Processing transcription job completion: {state.TranscriptionJobName}");
            var response = await this._transcribeClient.GetTranscriptionJobAsync(request);

            context.Logger.LogLine($"... Download transcript");
            var transcript = await _httpClient.GetStringAsync(response.TranscriptionJob.Transcript.TranscriptFileUri);

            context.Logger.LogLine("... Uploading transcript to S3 bucket");
            await _s3Client.PutObjectAsync(new PutObjectRequest
            {
                BucketName  = Utilites.BUCKET,
                Key         = Utilites.GetTranscriptKey(state.Id),
                ContentBody = transcript
            });

            return(state);
        }
Esempio n. 10
0
        /// <summary>
        /// Formats the value of the current instance using the specified format.
        /// </summary>
        /// <param name="format">The format to use.</param>
        /// <param name="formatProvider">The provider to use to format the value.</param>
        /// <returns>The value of the current instance in the specified format.</returns>
        public string ToString(string format, IFormatProvider formatProvider)
        {
            switch (format)
            {
            case "FieldName":
                return(FieldName);

            case "WidgetFieldName":
                return(WidgetFieldName);

            case "WidgetClass":
                return(Utilites.GetFriendlyTypeName(WidgetClass));

            case "WidgetValueField":
                return(WidgetValueField);

            case "FieldFormat":
                return(FieldFormat);

            default:
                throw new ArgumentOutOfRangeException("Unsupported format: " + format);
            }
        }
Esempio n. 11
0
    private void CheckClick(GameObject go)
    {
        var item = go.GetComponent <ClickBehaviour>();

        curDice = item;

        if (lastDice == null)
        {
            lastDice = item;
            var diceI = dices.Find(diceItem => ReferenceEquals(diceItem, lastDice));
            diceI.ToggleHold();
            lastDiceIndex = dices.IndexOf(diceI);
            return;
        }
        int lastDiceValue = int.Parse(lastDice.name);

        lastDiceIndex = dices.IndexOf(lastDice);
        var moveTo = lastDiceIndex + lastDiceValue;

        if (moveTo >= dicesLength)
        {
            moveTo = Mathf.Abs(dicesLength - moveTo);
        }

        if (ReferenceEquals(curDice, dices[moveTo]))
        {
            curDice.ToggleHold();
            lastDice      = curDice;
            lastDiceIndex = dices.IndexOf(curDice);
        }
        else
        {
            lastDice = null;
            Utilites.ResetButtonsState(dices);
        }
        CheckWin();
    }
Esempio n. 12
0
 public WindowsPackage(DismPackageInfo pkg)
 {
     this._packageName        = pkg.PackageName;
     this._packageState       = pkg.PackageState;
     this._releaseType        = pkg.ReleaseType;
     this._installTime        = pkg.InstallTime.ToDateTime();
     this._applicable         = pkg.Applicable;
     this._copyright          = pkg.Copyright;
     this._company            = pkg.Company;
     this._creationTime       = pkg.CreationTime.ToDateTime();
     this._displayName        = pkg.DisplayName;
     this._description        = pkg.Description;
     this._installClient      = pkg.InstallClient;
     this._installPackageName = pkg.InstallPackageName;
     this._lastUpdatedTime    = pkg.LastUpdateTime.ToDateTime();
     this._productName        = pkg.ProductName;
     this._productVersion     = pkg.ProductVersion;
     this._restartRequired    = pkg.RestartRequired;
     this._fullyOffline       = pkg.FullyOffline;
     this._supportInformation = pkg.SupportInformation;
     this._customProperties   =
         Utilites.PtrToArray <DismCustomProperty>(
             pkg.CustomProperty,
             pkg.CustomPropertyCount
             ).ToDictionary(
             p => string.Format("{0}\\{1}", p.Path, p.Name),
             p => p.Value
             );
     this._features = new Collection <WindowsFeature>(
         Utilites.PtrToArray <DismFeature>(
             pkg.Feature,
             pkg.FeatureCount
             )
         .Select(f => new WindowsFeature(f))
         .ToList()
         );
 }
Esempio n. 13
0
        private void CreateNewOuting()
        {
            // get date of outing
            Console.Write("Enter the date Of outing (MM/dd/yyyy): ");
            DateTime newOutingDate = Utilites.GetDateFromUser();

            // get event type and make sure it is valid
            int newEventType;

            do
            {
                Console.WriteLine("Enter the type Of outing: ");
                foreach (var eventType in Enum.GetValues(typeof(TypeOfEvent)))
                {
                    Console.WriteLine($"{(int)eventType} for {eventType}.");
                }
                newEventType = Utilites.GetIntFromUser();
                if (Enum.IsDefined(typeof(TypeOfEvent), newEventType) == false)
                {
                    Console.WriteLine("Please enter a valid number.");
                }
            } while (Enum.IsDefined(typeof(TypeOfEvent), newEventType) == false);

            // get Attendance
            Console.Write("Enter the number in attendance: ");
            int newAttendance = Utilites.GetIntFromUser();

            // get cost per person
            Console.Write("Enter the cost per person: ");
            decimal newCostPerPerson = Utilites.GetDecimalFromUser();

            // add event to list
            _outingRepo.AddOutingToList(new Outing((TypeOfEvent)newEventType, newAttendance, newOutingDate, newCostPerPerson));

            // show event was added
            Console.WriteLine("The event was added.");
        }
        private async void BtnAcceptNewDirAdding_Clicked(object sender, EventArgs e)
        {
            var newDirName = "";

            if (string.IsNullOrEmpty(EntryNewDirectoryField.Text) || string.IsNullOrWhiteSpace(EntryNewDirectoryField.Text))
            {
                return;
            }
            try {
                newDirName = Path.Combine(currentDirectory.FullName, EntryNewDirectoryField.Text.Trim());
                if (Directory.Exists(newDirName))
                {
                    ShowErrorMessage($"Folder: [{newDirName}] already exist!");
                    return;
                }
                if (RenameWindowShown)
                {
                    await Task.Run(() => Utilites.RenameDirItem(DirList.FirstOrDefault(x => x.ItemChecked)?.FullPath, newDirName)).ContinueWith((arg) => {
                        if (!arg.Result)
                        {
                            ShowErrorMessage($"Something goes wrong");
                        }
                    });
                }
                else
                {
                    // Try to create the directory.
                    DirectoryInfo di = Directory.CreateDirectory(newDirName);
                }
                GetDir(currentDirectory.GetFileSystemInfoFullName());

                EntryNewDirectoryField.Unfocus();
                EntryNewDirectoryField.Text = "";
                ModalBackGroundShown        = false;
                AddDirModalWinShown         = false;
            } catch (Exception ex) { }
        }
Esempio n. 15
0
 //To use in Responsable.aspx
 public static void LoginStatut(HtmlContainerControl div, System.Web.UI.WebControls.Label LoginName)
 {
     if (System.Web.HttpContext.Current.Request.Cookies["userInfo"] != null)
     {
         int ID = Int32.Parse(System.Web.HttpContext.Current.Request.Cookies["userInfo"]["ID"]);
         using (Helpdesk.Entities.Agences.AgenceEntities db = new Helpdesk.Entities.Agences.AgenceEntities())
         {
             var req = from value in db.Responsables where (value.ID == ID) select value;
             var r   = req.FirstOrDefault();
             if (r != null)
             {
                 HttpCookie userck = new HttpCookie("userInfo");
                 userck.Values["ID"]       = r.ID.ToString();
                 userck.Values["Password"] = r.Password;
                 userck.Values["Username"] = r.Username;
                 userck.Values["Nom"]      = r.Nom;
                 userck.Values["Email"]    = r.Email;
                 userck.Values["Prenom"]   = r.Prenom;
                 userck.Values["Level"]    = r.Niveau.ToString();
                 userck.Expires            = System.Web.HttpContext.Current.Request.Cookies["userInfo"].Expires;
                 System.Web.HttpContext.Current.Response.Cookies.Add(userck);
                 LoginName.Text = r.Nom + " " + r.Prenom;
             }
             else
             {
                 HttpCookie userck = new HttpCookie("userInfo");
                 userck.Expires = DateTime.Now.AddDays(-30);
                 System.Web.HttpContext.Current.Response.Cookies.Add(userck);
                 Utilites.redirect("Account/login.aspx");
             }
         }
     }
     else
     {
         Utilites.redirect("Account/login.aspx");
     }
 }
Esempio n. 16
0
        /// <summary>
        /// Open.
        /// </summary>
        public void Open()
        {
            if (IsOpen)
            {
                return;
            }

            IsOpen = true;

            var parent = Utilites.FindTopmostCanvas(gameObject.transform);

            if (parent != null)
            {
                Parent = transform.parent;
                transform.SetParent(parent, true);
            }

            SiblingIndex = transform.GetSiblingIndex();

            ModalKey = ModalHelper.Open(this, ModalSprite, ModalColor, Close);

            transform.SetAsLastSibling();
            AdditionalButtonsBlock.SetActive(true);
        }
Esempio n. 17
0
        public MetroSetRadioButton()
        {
            SetStyle(
                ControlStyles.ResizeRedraw |
                ControlStyles.OptimizedDoubleBuffer |
                ControlStyles.SupportsTransparentBackColor, true);
            DoubleBuffered = true;
            UpdateStyles();
            Font = MetroSetFonts.SemiBold(10);
            //BackColor = Color.Transparent;
            Font   = new Font("Segoe UI", 10);
            mth    = new Methods();
            utl    = new Utilites();
            Alpha  = 0;
            Cursor = Cursors.Hand;
            timer  = new Timer()
            {
                Interval = 10,
                Enabled  = false
            };
            timer.Tick += SetCheckedChanged;

            ApplyTheme();
        }
Esempio n. 18
0
        /// <summary>
        /// Create ClassField from specified property.
        /// </summary>
        /// <param name="property">Property.</param>
        /// <returns>ClassField instance if property type is allowed; otherwise null.</returns>
        public static ClassField Create(PropertyInfo property)
        {
            if (!property.CanRead)
            {
                return(null);
            }

            if (!IsAllowedType(property.PropertyType))
            {
                return(null);
            }

            var result = new ClassField()
            {
                FieldName       = property.Name,
                WidgetFieldName = property.Name,
                FieldTypeName   = Utilites.GetFriendlyTypeName(property.PropertyType),
                FieldType       = property.PropertyType,
                CanRead         = property.CanRead,
                CanWrite        = property.CanWrite,
            };

            return(result);
        }
Esempio n. 19
0
    private void CheckWin()
    {
        var  tiles      = GameObject.FindGameObjectsWithTag("Tile");
        bool outOfField = Array.Exists(tiles, tile => tile.transform.position == player.transform.position);

        if (!Utilites.IsTargetVisible(Camera.main, player) || !outOfField)
        {
            Utilites.RestartScene();
        }

        Array.ForEach(skeletons, skeleton =>
        {
            if (skeleton.transform.position == player.transform.position)
            {
                Utilites.RestartScene();
            }
        });

        if (player.transform.position == winPoint.transform.position)
        {
            Debug.Log("Win");
            GameManager.instance.NextLevel();
        }
    }
Esempio n. 20
0
 public static void ConfigureEdi()
 {
     try { EdiService.Configure(); }
     catch (Exception ex) { Utilites.Error(ex); }
 }
Esempio n. 21
0
    // Use this for initialization
    void Start()
    {
        Utilites.PrintCharger();

        UIStuff.DoUI();
    }
Esempio n. 22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClassInfo"/> class.
        /// </summary>
        /// <param name="type">Type.</param>
        public ClassInfo(Type type)
        {
            if (type == null)
            {
                return;
            }

            // ignore Unity objects except scriptable objects
            var is_unity_object            = typeof(UnityEngine.Object).IsAssignableFrom(type);
            var is_unity_scriptable_object = typeof(ScriptableObject).IsAssignableFrom(type);

            if (is_unity_object && !is_unity_scriptable_object)
            {
                return;
            }

            // ignore static types
            if (type.IsAbstract && type.IsSealed)
            {
                return;
            }

            // ignore generic type
            if (type.IsGenericTypeDefinition)
            {
                return;
            }

            InfoType = type;

            Namespace     = type.Namespace;
            FullTypeName  = type.FullName;
            ShortTypeName = type.Name;

            InputField = typeof(UnityEngine.UI.InputField);
            InputText  = typeof(UnityEngine.UI.Text);

#if UIWIDGETS_TMPRO_SUPPORT
            IsTMProText       = true;
            TextFieldType     = typeof(TMPro.TextMeshProUGUI);
            TMProInputField   = Utilites.GetType("TMPro.TMP_InputField");
            IsTMProInputField = TMProInputField != null;
            if (IsTMProInputField)
            {
                InputField = TMProInputField;
                InputText  = TextFieldType;
            }
#else
            IsTMProText       = false;
            TextFieldType     = typeof(UnityEngine.UI.Text);
            TMProInputField   = null;
            IsTMProInputField = false;
#endif

            var prohibited_names = new HashSet <string>();

            if (typeof(ScriptableObject).IsAssignableFrom(type))
            {
                prohibited_names.Add("name");
                prohibited_names.Add("hideFlags");
            }

            foreach (var field in type.GetFields())
            {
                if (prohibited_names.Contains(field.Name))
                {
                    continue;
                }

                var option = ClassField.Create(field);
                if (option != null)
                {
                    Fields.Add(option);
                }
            }

            foreach (var property in type.GetProperties())
            {
                if (prohibited_names.Contains(property.Name))
                {
                    continue;
                }

                var option = ClassField.Create(property);
                if (option != null)
                {
                    Fields.Add(option);
                }
            }
        }
Esempio n. 23
0
        public async Task GetMembersAsync()
        {
            var s = await Utilites.GetOrderedMembersAsync(Clash, Guild.ClanTag);

            await SendMessageAsync(s == ""? "API is currently under maintenance" : s);
        }
Esempio n. 24
0
        public override void UpdateView()
        {
            if (EdiService.SelectedRelationship == null)
            {
                Utilites.Error("Необходимо выбрать клиента"); return;
            }
            IsCanRefresh = false;
            var watch = System.Diagnostics.Stopwatch.StartNew();

            try
            {
                base.UpdateView();
                Documents = OrdersRepository.GetOrders(DateFrom, DateTo);
                if (Documents == null)
                {
                    return;
                }
                if (Documents?.Count > 0)
                {
                    var docsAlredyInBufferTable = OrdersRepository.GetOrdersLocatedInBufferTable();
                    //var docsHasFailedDetails = OrdersRepository.GetOrdersFailed();

                    var docNums = "";

                    foreach (var doc in Documents)
                    {
                        doc.EdiIdDoc     = "";
                        doc.EdiIdDoc     = DbService.SelectSingleValue($"select ID from HPCSERVICE.EDI_DOC WHERE order_number = '{doc?.OrderHeader?.OrderNumber}'");
                        doc.TraderNumber = DbService.SelectSingleValue($"select CODE from ABT.DOC_JOURNAL WHERE id in (select id_trader from hpcservice.edi_doc where id = '{doc?.EdiIdDoc}')");
                        OrdersRepository.UpdateFailedDetails(doc?.EdiIdDoc);
                        if (doc == null)
                        {
                            continue;
                        }
                        if (doc.OrderHeader == null)
                        {
                            continue;
                        }
                        if (doc.OrderHeader.OrderNumber == null)
                        {
                            continue;
                        }

                        docNums += $",'{doc.OrderHeader.OrderNumber}'";
                    }
                    docNums = docNums?.Trim(',');

                    var detailsFailed = OrdersRepository.GetDetailsFailed(docNums);

                    if (docsAlredyInBufferTable != null)
                    {
                        foreach (var doc in Documents)
                        {
                            if (docsAlredyInBufferTable.Contains(doc?.OrderHeader?.OrderNumber))
                            {
                                doc.IsInDatabase = true;
                            }
                            if (detailsFailed != null)
                            {
                                foreach (var line in doc.OrderLines.Lines)
                                {
                                    if (detailsFailed.Contains(line?.LineItem?.BuyerItemCode))
                                    {
                                        line.IsFailed = true;
                                        doc.IsFailed  = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utilites.Error(ex);
            }
            finally
            {
                watch.Stop();
                Time         = ((double)(((double)watch.ElapsedMilliseconds) / 1000)).ToString() + " сек";
                IsCanRefresh = true;
            }
        }
Esempio n. 25
0
        public void ParseData()
        {
            AbilityType         = Utilites.CastStringTuEnum <Enumerators.AbilityType>(Type);
            AbilityActivityType = Utilites.CastStringTuEnum <Enumerators.AbilityActivityType>(ActivityType);
            AbilityCallType     = Utilites.CastStringTuEnum <Enumerators.AbilityCallType>(CallType);

            if (!string.IsNullOrEmpty(TargetType))
            {
                AbilityTargetTypes = Utilites.CastList <Enumerators.AbilityTargetType>(TargetType);
            }
            else
            {
                AbilityTargetTypes = new List <Enumerators.AbilityTargetType>();
            }

            if (!string.IsNullOrEmpty(StatType))
            {
                AbilityStatType = Utilites.CastStringTuEnum <Enumerators.StatType>(StatType);
            }
            else
            {
                AbilityStatType = Enumerators.StatType.NONE;
            }

            if (!string.IsNullOrEmpty(SetType))
            {
                AbilitySetType = Utilites.CastStringTuEnum <Enumerators.SetType>(SetType);
            }
            else
            {
                AbilitySetType = Enumerators.SetType.NONE;
            }

            if (!string.IsNullOrEmpty(EffectType))
            {
                AbilityEffectType = Utilites.CastStringTuEnum <Enumerators.AbilityEffectType>(EffectType);
            }
            else
            {
                AbilityEffectType = Enumerators.AbilityEffectType.NONE;
            }

            if (!string.IsNullOrEmpty(AttackInfo))
            {
                AttackInfoType = Utilites.CastStringTuEnum <Enumerators.AttackInfoType>(AttackInfo);
            }
            else
            {
                AttackInfoType = Enumerators.AttackInfoType.ANY;
            }

            if (!string.IsNullOrEmpty(CardType))
            {
                TargetCardType = Utilites.CastStringTuEnum <Enumerators.CardType>(CardType);
            }
            else
            {
                TargetCardType = Enumerators.CardType.NONE;
            }

            if (!string.IsNullOrEmpty(UnitStatus))
            {
                TargetUnitStatusType = Utilites.CastStringTuEnum <Enumerators.UnitStatusType>(UnitStatus);
            }
            else
            {
                TargetUnitStatusType = Enumerators.UnitStatusType.NONE;
            }

            if (!string.IsNullOrEmpty(UnitType))
            {
                TargetUnitType = Utilites.CastStringTuEnum <Enumerators.CardType>(UnitType);
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Загрузка библиотеки в сессию
        /// </summary>
        /// <param name="asmFile"></param>
        /// <returns></returns>
        internal SeparatedAssembly LoadAssembly(FileInfo asmFile)
        {
            try
            {
                string pathName = asmFile.FullName;
                //получение информации о сборке без загрузки в домен
                //https://stackoverflow.com/questions/30306702/assemblyinfo-without-loading
                var name = AssemblyName.GetAssemblyName(pathName);

                /*
                 * получение уникального HASH'а файла
                 * на случай, если грузятся разные файлы (даже по названию), но это одна сборка
                 * по хешу смотрим, одинаковые ли файлы или нет
                 *
                 * теоретически, возможны ложные срабатывания проверки
                 * когда одну сборку переименовали в другую и их хэш совпал
                 * но вероятность подобного крайне мала ;)
                 */
                var asmHash = Utilites.GetFileHash(pathName);

                SeparatedAppDomain domain = null;
                bool same = false; //флаг, что нашли домен с такой же сборкой (и таким же файлом)
                lock (SessionLocker)
                {
                    foreach (var dom in Domains)
                    {
                        var loadedState = dom.HasLoaded(name, asmHash);

                        switch (loadedState)
                        {
                        case LoadedState.NotLoaded:
                            //если текущий домен свободен - грузим сюда

                            domain = dom;
                            break;

                        case LoadedState.LoadedDifferent:
                            //если занят - проверяем следующий. Может быть свободен
                            continue;

                        case LoadedState.LoadedSame:
                            //если точно такая же уже загружена - выдаём её же
                            domain = dom;
                            same   = true;
                            break;
                        }

                        //если есть куда
                        if (domain != null)
                        {
                            break;
                        }
                    }
                }

                //если имеющиеся домены не подходят для загрузки
                //в них уже есть сборки со схожим именем, но из других файлов
                if (domain == null)
                {
                    //создаём новый домен в текущей сессии
                    domain = CreateDomain();
                }

                //загрузка новой сборки в домен
                return(same
                    ? domain.GetAssembly(name)                      //выдаём уже загруженный ранее файл
                    : domain.LoadAssembly(asmFile, name, asmHash)); //загружаем новую сборку
            }
            catch (Exception ex)
            {
                return(new SeparatedAssembly(ex));
            }
        }
Esempio n. 27
0
 public void EvaluateVars()
 {
     mth = new Methods();
     utl = new Utilites();
 }
Esempio n. 28
0
 public static void ConfigureOracle()
 {
     try { OracleConnectionService.Configure(); }
     catch (Exception ex) { Utilites.Error(ex); }
 }
Esempio n. 29
0
 private void CheckClick(GameObject go)
 {
     scaler = StartCoroutine(Utilites.ScaleYByTime(scale, 5.7f, 7f));
 }
Esempio n. 30
0
        /// <summary>
        ///
        /// </summary>
        public static void MainLoop()
        {
            // verify needed paths exists
            if (!Directory.Exists(Constants.MESSAGE_FILES_DIR))
            {
                Directory.CreateDirectory(Constants.MESSAGE_FILES_DIR);
            }

            if (!Directory.Exists(Constants.LOG_FILE_DIR))
            {
                Directory.CreateDirectory(Constants.LOG_FILE_DIR);
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Config config =
                serializer.Deserialize <Config>(
                    File.ReadAllText(Constants.ConfigFile));

            SensorDriver sensor = new SensorDriver(config.PreselectorIp,
                                                   config.SensorHostName);

            TimedCount timer              = new TimedCount();
            Stopwatch  stopwatch          = new Stopwatch();
            bool       initialCalComplete = false;
            YfactorCal yFactorCal         = null;
            int        numOfMeasurements  = 0;

            // create and write initial location message
            string     locString  = File.ReadAllText(Constants.LocMessage);
            LocMessage locMessage =
                serializer.Deserialize <LocMessage>(locString);

            locMessage.loadMessageFields();
            Utilites.WriteMessageToFile(locMessage);

            while (true)
            {
                if (timer.elaspedTime() >= SECONDS_IN_HOUR ||
                    !initialCalComplete)
                {
                    // reset stopwatch to zero but do not start
                    stopwatch.Reset();
                    // read in parameters for calibration
                    SweepParams calParams;
                    string      jsonString =
                        File.ReadAllText(Constants.Spn43CalSweepParamsFile);
                    calParams =
                        serializer.Deserialize <SweepParams>(
                            jsonString);

                    SysMessage sysMessage = new SysMessage();
                    sysMessage.loadMessageFields();
                    sysMessage.version = config.Version;
                    sysMessage.calibration.byteOrder               = config.ByteOrder;
                    sysMessage.calibration.compression             = config.Compression;
                    sysMessage.calibration.dataType                = config.DataType;
                    sysMessage.calibration.numOfMeasurementsPerCal =
                        numOfMeasurements;
                    sysMessage.calibration.measurementType =
                        calParams.MeasurementType;
                    sysMessage.calibration.calsPerHour =
                        Constants.CALS_PER_HOUR;
                    sysMessage.calibration.compression =
                        Constants.COMPRESSION;
                    sysMessage.calibration.byteOrder =
                        Constants.BYTE_ORDER;
                    sysMessage.calibration.dataType =
                        Constants.DATA_TYPE;
                    sysMessage.calibration.measurementParameters.detector =
                        calParams.Detector;
                    sysMessage.calibration.measurementParameters.window =
                        calParams.Window;
                    sysMessage.calibration.measurementParameters.attenuation =
                        calParams.Attenuation;
                    sysMessage.calibration.measurementParameters.videoBw   = -1;
                    sysMessage.calibration.measurementParameters.dwellTime =
                        calParams.DwellTime;

                    // if yFactorCall == null and error occured while performing cal
                    sensor.PerformCal(calParams, sysMessage, out yFactorCal);
                    if (yFactorCal == null)
                    {
                        Utilites.LogMessage("Error performing calibration, " +
                                            "cal aborted");
                        // don't write message, start the loop again
                        continue;
                    }
                    Utilites.WriteMessageToFile(sysMessage);
                    initialCalComplete = true;
                    timer.reset();
                    numOfMeasurements = 0;
                }
                else
                {
                    // need to have completed cal to perform sweep
                    if (yFactorCal == null)
                    {
                        continue;
                    }

                    // get last time from stop watch
                    TimeSpan elapsedTime = stopwatch.Elapsed;
                    stopwatch.Restart();

                    SweepParams sweepParams;
                    string      jsonString =
                        File.ReadAllText(Constants.Spn43MeasurementFile);
                    sweepParams =
                        serializer.Deserialize <SweepParams>(
                            jsonString);

                    DataMessage dataMessage = new DataMessage();
                    dataMessage.loadMessageFields();
                    dataMessage.version   = config.Version;
                    dataMessage.byteOrder = config.ByteOrder;
                    dataMessage.dataType  = config.DataType;
                    dataMessage.comment   = config.Compression;
                    dataMessage.timeBetweenAcquisitions =
                        elapsedTime.TotalSeconds;
                    dataMessage.sysToDetect     = sweepParams.sys2Detect;
                    dataMessage.measurementType = sweepParams.MeasurementType;
                    dataMessage.compression     = Constants.COMPRESSION;
                    dataMessage.dataType        = Constants.DATA_TYPE;
                    dataMessage.byteOrder       = Constants.BYTE_ORDER;
                    dataMessage.measurementParameters.attenuation =
                        sweepParams.Attenuation;
                    dataMessage.measurementParameters.detector =
                        sweepParams.Detector;
                    dataMessage.measurementParameters.dwellTime =
                        sweepParams.DwellTime;
                    dataMessage.measurementParameters.window =
                        sweepParams.Window;

                    bool err = sensor.PerformMeasurement(sweepParams,
                                                         dataMessage, yFactorCal);
                    if (err)
                    {
                        throw new Exception("Error performing measurement");
                        // don't write message, start the loop again
                        continue;
                    }

                    numOfMeasurements++;
                    Utilites.WriteMessageToFile(dataMessage);
                }
            }
        }