Esempio n. 1
0
 public ProcessingEngine(
     IPluginsContainer<ICommandImplementation> commandRepository,
     IPluginsContainer<ICommandObserver> commandObservers,
     ILogProvider logProvider,
     IPersistenceTransaction persistenceTransaction,
     IAuthorizationManager authorizationManager,
     XmlUtility xmlUtility,
     IUserInfo userInfo,
     ISqlUtility sqlUtility,
     ILocalizer localizer)
 {
     _commandRepository = commandRepository;
     _commandObservers = commandObservers;
     _logger = logProvider.GetLogger("ProcessingEngine");
     _performanceLogger = logProvider.GetLogger("Performance");
     _requestLogger = logProvider.GetLogger("ProcessingEngine Request");
     _commandsLogger = logProvider.GetLogger("ProcessingEngine Commands");
     _commandsResultLogger = logProvider.GetLogger("ProcessingEngine CommandsResult");
     _persistenceTransaction = persistenceTransaction;
     _authorizationManager = authorizationManager;
     _xmlUtility = xmlUtility;
     _userInfo = userInfo;
     _sqlUtility = sqlUtility;
     _localizer = localizer;
 }
 public ConceptApplicationRepository(
     ISqlExecuter sqlExecuter,
     ILogProvider logProvider,
     XmlUtility xmlUtility)
 {
     _sqlExecuter = sqlExecuter;
     _logger = logProvider.GetLogger("ConceptApplicationRepository");
     _xmlUtility = xmlUtility;
 }
Esempio n. 3
0
 public RhetosService(
     IProcessingEngine processingEngine,
     IEnumerable<ICommandInfo> commands,
     ILogProvider logProvider,
     XmlUtility xmlUtility)
 {
     _processingEngine = processingEngine;
     _commands = commands;
     _performanceLogger = logProvider.GetLogger("Performance");
     _xmlUtility = xmlUtility;
 }
 public override void WriteTo(XElement xE)
 {
     base.WriteTo(xE);
     XmlUtility.SetXsiType(xE, "https://adwords.google.com/api/adwords/cm/v201609", "AdGroupAdCountLimitExceeded");
 }
 public void TestXmlUtilityGlob()
 {
     Assert.Equal(XmlUtility.Sanitize("𠀁𠀂𠀃𪛑𪛒𪛓"), "𠀁𠀂𠀃𪛑𪛒𪛓");
 }
 public void TestXmlUtilityDC00()
 {
     Assert.Equal(XmlUtility.Sanitize("\xD834AB\xDC00C\xDD1E"), "ABC");
 }
Esempio n. 7
0
 /// <summary>
 /// Xml to object
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="xml"></param>
 /// <param name="repository"> Assign repository to load XmlIgnored properties</param>
 /// <returns></returns>
 public static T FromXml <T>(this string xml, IRepository repository = null) where T : class
 {
     return(XmlUtility.FromXml <T>(xml, repository));
 }
Esempio n. 8
0
 /// <summary>
 /// Object to xml
 /// </summary>
 /// <param name="o"></param>
 /// <returns></returns>
 public static string ToXml(this object o)
 {
     return(XmlUtility.ToXml(o));
 }
Esempio n. 9
0
        private IEnumerator <IYieldInstruction> BuildLevelAssetsCoroutine(Asset asset)
        {
            mLevelAsset = (UnityEngineAsset)asset;
            GameObject fashionGameAssets = (GameObject)mLevelAsset.UnityObject;

            mLevelRoot = (GameObject)GameObject.Instantiate(GameObjectUtility.GetNamedChild("Environment", fashionGameAssets));
            mLevelRoot.transform.position = Vector3.zero;

            GameObject stationsRoot = GameObjectUtility.GetNamedChild("Stations", fashionGameAssets);

            mFactory = new FashionGameStationFactory(stationsRoot);

            int           loadingStations = 0;
            List <string> labels          = new List <string>();

            foreach (XmlNode node in mLevelXml.SelectNodes("Level/Stations/Station"))
            {
                XmlNode labelNode = node.Attributes["label"];
                string  label     = null;
                if (labelNode != null)
                {
                    label = labelNode.InnerText;

                    if (labels.Contains(label))
                    {
                        throw new Exception("Fashion Minigame does not support multiple stations with the same label.");
                    }
                    labels.Add(label);
                }

                loadingStations++;
                mFactory.BuildStation
                (
                    node.Attributes["type"].InnerText,
                    XmlUtility.ParsePositionDirection(node),
                    label,
                    delegate(FashionGameStation station)
                {
                    loadingStations--;
                    foreach (Component component in station.UnityGameObject.GetComponentsInChildren(typeof(Collider)))
                    {
                        mStations.Add(component.gameObject, station);
                    }

                    if (station.RequiresWorker)
                    {
                        mLevelTasks.Add(mScheduler.StartCoroutine(AssignNpcWhenAvailable(station)));
                    }
                }
                );
            }

            ClothingMediator clothingMediator = GameFacade.Instance.RetrieveMediator <ClothingMediator>();

            yield return(new YieldWhile(delegate()
            {
                return loadingStations != 0 || !clothingMediator.ClothingLoaded;
            }));

            mLevelGameplay.SetupWaves();
            ReloadStationPositions();

            mLevelSetup = true;
        }
Esempio n. 10
0
        public void DataTransfer_Event(string strMethod, object sender)
        {
            switch (strMethod)
            {
            case "QueryCalibratorinfoTask":
                List <CalibratorinfoTask> lstCalibrationCurveInfo = (List <CalibratorinfoTask>)XmlUtility.Deserialize(typeof(List <CalibratorinfoTask>), sender as string);
                int max = 0;
                for (int i = 0; i < lstCalibrationCurveInfo.Count; i++)
                {
                    int str = System.Convert.ToInt32(lstCalibrationCurveInfo[i].SampleNum.Substring(1));
                    if (str > max)
                    {
                        max = str;
                    }
                }
                this.Invoke(new EventHandler(delegate { txtSumpleNum.Text = "S" + (max + 1).ToString();
                                                        if (this.btnSave.Enabled == true)
                                                        {
                                                            ;
                                                        }

                                                        else
                                                        {
                                                            this.btnSave.Enabled = true;
                                                        } }));

                GridAdd(lstCalibrationCurveInfo);
                break;

            case "QueryCombProjectNameAllInfo":
                lstCombProName = (List <string>)XmlUtility.Deserialize(typeof(List <string>), sender as string);
                calibProCombPage1.LstProjectGroups = lstCombProName;
                calibProCombPage2.LstAssayProInfos = lstCombProName;
                this.BeginInvoke(new EventHandler(delegate { grpCombProject.SelectedTabPageIndex = 0; }));
                break;

            case "QueryProjectAndCombProName":
                lstCombProInfo = (List <CombProjectInfo>)XmlUtility.Deserialize(typeof(List <CombProjectInfo>), sender as string);
                break;

            case "QueryProjectNameInfoByCalib":
                lstQCRelateProject = (List <string[]>)XmlUtility.Deserialize(typeof(List <string[]>), sender as string);

                projectPage1.LstAssayProInfos = lstQCRelateProject;
                projectPage2.LstAssayProInfos = lstQCRelateProject;
                projectPage3.LstAssayProInfos = lstQCRelateProject;
                projectPage4.LstAssayProInfos = lstQCRelateProject;
                this.Invoke(new EventHandler(delegate { grpProject.SelectedTabPageIndex = 0; }));
                if (combSampleType.SelectedItem.ToString() == sampleSerum)
                {
                    lstSerumProject = lstQCRelateProject;
                }
                else if (combSampleType.SelectedItem.ToString() == sampleUrine)
                {
                    lstUrinePeoject = lstQCRelateProject;
                }
                else if (combSampleType.SelectedItem.ToString().Trim() == sampleBlank)
                {
                    lstBlankProject = lstQCRelateProject;
                }

                break;

            default:
                break;
            }
        }
Esempio n. 11
0
 protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
 {
     writer.WriteStartElement("GetStatus", "http://schemas.xmlsoap.org/ws/2004/09/enumeration");
     XmlUtility.SerializeEnumerationContext(writer, this._enumerationContext);
     writer.WriteEndElement();
 }
Esempio n. 12
0
 private XDocument GetConfiguration()
 {
     return(XmlUtility.GetOrCreateDocument("configuration", _fileSystem, _configurationPath));
 }
        private AuthorizeRecurringTransactionResponse ProcessRecurringResponse(AuthorizeRecurringTransactionRequest authRequest, String sResponse)
        {
            //CREATE THE TRANSACTION OBJECT
            Transaction transaction = new Transaction();

            transaction.PaymentGatewayId = this.PaymentGatewayId;
            transaction.TransactionType  = TransactionType.AuthorizeRecurring;
            LSDecimal transAmount = authRequest.RecurringChargeSpecified ? authRequest.RecurringCharge : authRequest.Amount;

            transaction.Amount = transAmount;

            XmlDocument xmlresponse = new XmlDocument();

            xmlresponse.LoadXml(sResponse);

            string resultCode = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "Page");

            transaction.TransactionStatus     = ((resultCode == "2000") || (resultCode == "90000")) ? TransactionStatus.Successful : TransactionStatus.Failed;
            transaction.ProviderTransactionId = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "ReceiptNumber");
            transaction.TransactionDate       = DateTime.UtcNow;
            string amount = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "TotalAmount");

            if (string.IsNullOrEmpty(amount))
            {
                transaction.Amount = transAmount;
            }
            else
            {
                transaction.Amount = AlwaysConvert.ToDecimal(amount, (decimal)transAmount);
            }
            if (transaction.TransactionStatus != TransactionStatus.Successful)
            {
                string errorMessage = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "Error");
                if (string.IsNullOrEmpty(errorMessage))
                {
                    errorMessage = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "Verbiage");
                }
                transaction.ResponseCode    = resultCode;
                transaction.ResponseMessage = errorMessage;
            }
            transaction.AuthorizationCode = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "ApprovalCode");
            transaction.AVSResultCode     = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "AVSResponseCode");
            if (string.IsNullOrEmpty(transaction.AVSResultCode))
            {
                transaction.AVSResultCode = "U";
            }
            transaction.CVVResultCode = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "CVV2ResponseCode");
            if (string.IsNullOrEmpty(transaction.CVVResultCode))
            {
                transaction.CVVResultCode = "X";
            }
            HttpContext context = HttpContext.Current;

            if (context != null)
            {
                transaction.RemoteIP = context.Request.ServerVariables["REMOTE_ADDR"];
                transaction.Referrer = context.Request.ServerVariables["HTTP_REFERER"];
            }

            return(new AuthorizeRecurringTransactionResponse(transaction));
        }
 public override void WriteTo(XElement xE)
 {
     base.WriteTo(xE);
     XmlUtility.SetXsiType(xE, "https://adwords.google.com/api/adwords/rm/v201609", "CrmBasedUserList");
 }
        private string InitializeAuthRecurringRequest(AuthorizeRecurringTransactionRequest authRequest, string payPeriod, Dictionary <string, string> sensitiveData)
        {
            Payment payment = authRequest.Payment;
            Order   order   = payment.Order;
            User    user    = order.User;

            XmlDocument xmlRequest = new XmlDocument();

            xmlRequest.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><TranxRequest />");

            XmlUtility.SetElementValue(xmlRequest.DocumentElement, "MerchantNumber", MerchantNumber);

            AccountDataDictionary accountData = new AccountDataDictionary(payment.AccountData);

            /*string sCurrencyCode = payment.CurrencyCode;
             * if (!("USD".Equals(sCurrencyCode)))
             * {
             *  sCurrencyCode = "CAD";
             * }*/
            string sCurrencyCode = "CAD";

            if (IsUSD)
            {
                sCurrencyCode = "USD";
            }

            string    recurrFlag    = "{RB ";
            LSDecimal recurAmount   = authRequest.RecurringChargeSpecified ? authRequest.RecurringCharge : authRequest.Amount;
            string    startDtString = GetNextPaymentDateStr(authRequest);
            string    duration      = ((int)(authRequest.NumberOfPayments - 1)).ToString();

            recurrFlag += recurAmount.ToString("F2") + " " + startDtString + " " + payPeriod + " " + duration + " email=2}";

            string ccFlag   = "{" + sCurrencyCode + "}";
            string testFlag = (UseTestMode ? "{TEST}" : "");

            string sFlags       = ccFlag + testFlag + recurrFlag;
            string sDescription = authRequest.SubscriptionName; //order.Notes;
            string sAmount      = String.Format("{0:F2}", authRequest.Amount);

            string pline;

            System.Collections.Generic.List <string> arrProducts = new System.Collections.Generic.List <string>();
            if (IncludeOrderItems)
            {
                OrderItemCollection orderItems = order.Items;
                if (orderItems != null && orderItems.Count > 0)
                {
                    foreach (OrderItem orderItem in orderItems)
                    {
                        if (orderItem.OrderItemType == OrderItemType.Product)
                        {
                            pline = "0.00::" + orderItem.Quantity + "::" + MakeSafe(orderItem.Sku, 30) + "::" + MakeSafe(orderItem.Name, 150) + "::" + sFlags;
                            arrProducts.Add(pline);
                        }
                    }
                }
            }

            pline = sAmount + "::1::" + order.OrderNumber + "::" + sDescription + "::" + sFlags;
            arrProducts.Add(pline);

            XmlUtility.SetElementValue(xmlRequest.DocumentElement, "Products", string.Join("|", (string[])arrProducts.ToArray()));
            if (accountData.ContainsKey("AccountName") && !string.IsNullOrEmpty(accountData["AccountName"]))
            {
                XmlUtility.SetElementValue(xmlRequest.DocumentElement, "xxxName", accountData["AccountName"]);
            }
            else
            {
                XmlUtility.SetElementValue(xmlRequest.DocumentElement, "xxxName", order.BillToFirstName + " " + order.BillToLastName);
            }

            XmlUtility.SetElementValue(xmlRequest.DocumentElement, "xxxCompany", order.BillToCompany);
            XmlUtility.SetElementValue(xmlRequest.DocumentElement, "xxxAddress", order.BillToAddress1);
            XmlUtility.SetElementValue(xmlRequest.DocumentElement, "xxxCity", order.BillToCity);
            XmlUtility.SetElementValue(xmlRequest.DocumentElement, "xxxProvince", order.BillToProvince);
            XmlUtility.SetElementValue(xmlRequest.DocumentElement, "xxxPostal", order.BillToPostalCode);
            XmlUtility.SetElementValue(xmlRequest.DocumentElement, "xxxCountry", order.BillToCountryCode);
            XmlUtility.SetElementValue(xmlRequest.DocumentElement, "xxxPhone", order.BillToPhone);
            XmlUtility.SetElementValue(xmlRequest.DocumentElement, "xxxEmail", order.BillToEmail);


            SetupCreditCardData(xmlRequest, payment, accountData, sensitiveData);

            StringBuilder formData = new StringBuilder();

            formData.Append("xxxRequestMode=X&xxxRequestData=" + HttpUtility.UrlEncode(XmlToString(xmlRequest)));

            return(formData.ToString());
        }
        private Transaction ProcessRefundResponse(string responseData, LSDecimal transactionAmount)
        {
            //CREATE THE TRANSACTION OBJECT
            Transaction transaction = new Transaction();

            transaction.PaymentGatewayId = this.PaymentGatewayId;
            transaction.TransactionType  = TransactionType.Refund;
            //LOAD THE RESPONSE XML
            XmlDocument xmlresponse = new XmlDocument();

            xmlresponse.LoadXml(responseData);
            string resultCode = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "Page");

            transaction.TransactionStatus     = (resultCode == "11000" ? TransactionStatus.Successful : TransactionStatus.Failed);
            transaction.ProviderTransactionId = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "ReceiptNumber");
            transaction.AuthorizationCode     = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "ApprovalCode") + ":" + XmlUtility.GetElementValue(xmlresponse.DocumentElement, "GUID");
            transaction.TransactionDate       = DateTime.UtcNow;
            string amount = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "TotalAmount");

            if (string.IsNullOrEmpty(amount))
            {
                transaction.Amount = transactionAmount;
            }
            else
            {
                transaction.Amount = AlwaysConvert.ToDecimal(amount, (decimal)transactionAmount);
            }
            if (transaction.TransactionStatus != TransactionStatus.Successful)
            {
                string errorMessage = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "Error");
                if (string.IsNullOrEmpty(errorMessage))
                {
                    errorMessage = XmlUtility.GetElementValue(xmlresponse.DocumentElement, "Verbiage");
                }
                transaction.ResponseCode    = resultCode;
                transaction.ResponseMessage = errorMessage;
            }
            HttpContext context = HttpContext.Current;

            if (context != null)
            {
                transaction.RemoteIP = context.Request.ServerVariables["REMOTE_ADDR"];
                transaction.Referrer = context.Request.ServerVariables["HTTP_REFERER"];
            }
            return(transaction);
        }
Esempio n. 17
0
        static void OnMachineStateChangedEvent(object sender)
        {
            string str = XmlUtility.Serializer(typeof(MachineState), Analyzer.MachineState);

            TcpServer.SendCMD(str);
        }
Esempio n. 18
0
 /// <summary>
 /// Replaces all special characters with encoded HTML sequences.
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static string HtmlEncode(string s)
 {
     return(XmlUtility.EncodeText(s)); // todo: implement HtmlEncode(s)
 }
Esempio n. 19
0
        /// <summary>
        /// Loads the specified file name.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="imageName">default name of the image.</param>
        /// <returns></returns>
        public static List <NetworkProfile> Load(string fileName, string imageName = NetworkProfile.DEFAULT_PROFILE_IMAGE_NAME)
        {
            List <NetworkProfile> profiles = new List <NetworkProfile>();

            if (!File.Exists(fileName))
            {
                return(null);
            }

            profiles.Clear();
            XmlTextReader reader = null;

            try
            {
                reader = new XmlTextReader(fileName);
                NetworkProfile currentProfile = null;

                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:     // The node is an element.
                        switch (reader.Name)
                        {
                        case "profile":
                            currentProfile           = new NetworkProfile();
                            currentProfile.Id        = Int32.Parse(reader.GetAttribute("id"));
                            currentProfile.Name      = reader.GetAttribute("name");
                            currentProfile.ImageName = XmlUtility.ReadAttributeIfPresent(reader, "imageName", imageName);
                            profiles.Add(currentProfile);
                            break;

                        case "networkcard":
                            currentProfile.NetworkCardInfo    = new WindowsNetworkCard();
                            currentProfile.NetworkCardInfo.Id = XmlUtility.ReadAttributeIfPresent(reader, "id", "");

                            currentProfile.NetworkCardInfo.ViewId = XmlUtility.ReadAttributeIfPresent(reader, "viewId", "");
                            currentProfile.NetworkCardInfo.Name   = XmlUtility.ReadAttributeIfPresent(reader, "name", "");

                            currentProfile.NetworkCardInfo.Dhcp           = Boolean.Parse(XmlUtility.ReadAttributeIfPresent(reader, "dhcp", Boolean.FalseString));
                            currentProfile.NetworkCardInfo.IpAddress      = XmlUtility.ReadAttributeIfPresent(reader, "ipAddress", "");
                            currentProfile.NetworkCardInfo.SubnetMask     = XmlUtility.ReadAttributeIfPresent(reader, "subnetMask", "");
                            currentProfile.NetworkCardInfo.GatewayAddress = XmlUtility.ReadAttributeIfPresent(reader, "defaultGateway", "");

                            currentProfile.NetworkCardInfo.MacAddress = XmlUtility.ReadAttributeIfPresent(reader, "macAddress", "");
                            currentProfile.NetworkCardInfo.DynamicDNS = Boolean.Parse(XmlUtility.ReadAttributeIfPresent(reader, "dynamicDns", Boolean.FalseString));
                            currentProfile.NetworkCardInfo.Dns        = XmlUtility.ReadAttributeIfPresent(reader, "dns", "");
                            currentProfile.NetworkCardInfo.Dns2       = XmlUtility.ReadAttributeIfPresent(reader, "dns2", "");

                            currentProfile.NetworkCardInfo.HardwareName = XmlUtility.ReadAttributeIfPresent(reader, "hardwareName", "");

                            currentProfile.NetworkCardInfo.WinsPrimaryServer   = XmlUtility.ReadAttributeIfPresent(reader, "winsPrimaryServer", "");
                            currentProfile.NetworkCardInfo.WinsSecondaryServer = XmlUtility.ReadAttributeIfPresent(reader, "winsSecondaryServer", "");

                            break;

                        case "proxy":
                            currentProfile.ProxyConfig                      = new ProxyConfiguration();
                            currentProfile.ProxyConfig.Enabled              = Boolean.Parse(XmlUtility.ReadAttributeIfPresent(reader, "enabled", Boolean.FalseString));
                            currentProfile.ProxyConfig.ServerAddress        = XmlUtility.ReadAttributeIfPresent(reader, "serverAddress", "");
                            currentProfile.ProxyConfig.Port                 = Int32.Parse(XmlUtility.ReadAttributeIfPresent(reader, "port", "80"));
                            currentProfile.ProxyConfig.ProxyOverrideEnabled = Boolean.Parse(XmlUtility.ReadAttributeIfPresent(reader, "overrideEnabled", Boolean.FalseString));
                            currentProfile.ProxyConfig.ProxyOverride        = XmlUtility.ReadAttributeIfPresent(reader, "proxyOverride", "");
                            break;

                        case "application":
                            WindowsExecutable application = new WindowsExecutable();
                            application.Name        = XmlUtility.ReadAttributeIfPresent(reader, "name", "");
                            application.Arguments   = XmlUtility.ReadAttributeIfPresent(reader, "arguments", "");
                            application.Description = XmlUtility.ReadAttributeIfPresent(reader, "description", "");
                            application.Directory   = XmlUtility.ReadAttributeIfPresent(reader, "directory", "");
                            application.File        = XmlUtility.ReadAttributeIfPresent(reader, "fileName", "");
                            application.WaitForExit = Boolean.Parse(XmlUtility.ReadAttributeIfPresent(reader, "wait", Boolean.TrueString));
                            application.Kill        = Boolean.Parse(XmlUtility.ReadAttributeIfPresent(reader, "kill", Boolean.TrueString));

                            currentProfile.ExecList.Add(application);
                            break;

                        case "service":
                            WindowsServiceInfoImpl service = new WindowsServiceInfoImpl();

                            service.ServiceName = XmlUtility.ReadAttributeIfPresent(reader, "name", "");

                            string temp = XmlUtility.ReadAttributeIfPresent(reader, "status", ServiceForcedStatus.STOPPED.ToString());

                            if (temp.Equals(ServiceForcedStatus.RUNNING.ToString()))
                            {
                                service.ForcedStatus = ServiceForcedStatus.RUNNING;
                            }
                            else if (temp.Equals(ServiceForcedStatus.STOPPED.ToString()))
                            {
                                service.ForcedStatus = ServiceForcedStatus.STOPPED;
                            }
                            else
                            {
                                service.ForcedStatus = ServiceForcedStatus.NONE;
                            }
                            currentProfile.ServiceList.Add(service);

                            break;

                        case "driveMap":
                            DriveMap drive = new DriveMap();
                            drive.Name        = XmlUtility.ReadAttributeIfPresent(reader, "name", "");
                            drive.Drive       = XmlUtility.ReadAttributeIfPresent(reader, "drive", "");
                            drive.Description = XmlUtility.ReadAttributeIfPresent(reader, "description", "");
                            drive.Username    = XmlUtility.ReadAttributeIfPresent(reader, "username", "");
                            drive.Password    = XmlUtility.ReadAttributeIfPresent(reader, "password", "");
                            drive.RealPath    = XmlUtility.ReadAttributeIfPresent(reader, "realPath", "");
                            string temp1 = XmlUtility.ReadAttributeIfPresent(reader, "type", DriveMapType.MOUNT.ToString());

                            if (temp1.Equals(DriveMapType.MOUNT.ToString()))
                            {
                                drive.Type = DriveMapType.MOUNT;
                            }
                            else
                            {
                                drive.Type = DriveMapType.UNMOUNT;
                            }

                            currentProfile.DriveMapList.Add(drive);
                            break;

                        case "printer":
                            currentProfile.DefaultPrinter = XmlUtility.ReadAttributeIfPresent(reader, "defaultPrinter", "");
                            break;

                        case "forcedNic":
                            // disabled nic
                            WindowsNetworkCard disabledNIC;

                            disabledNIC              = new WindowsNetworkCard();
                            disabledNIC.Id           = XmlUtility.ReadAttributeIfPresent(reader, "id", "");
                            disabledNIC.HardwareName = XmlUtility.ReadAttributeIfPresent(reader, "hardwareName", "");

                            currentProfile.DisabledNetworkCards.Add(disabledNIC);
                            break;

                        case "wifi":
                            // wifi
                            string associatedSSID = XmlUtility.ReadAttributeIfPresent(reader, "associatedSSID", "");

                            currentProfile.AssociatedWifiSSID = associatedSSID;
                            break;
                        }
                        break;

                    case XmlNodeType.Text:     //Display the text in each element.
                        Console.WriteLine(reader.Value);
                        break;

                    case XmlNodeType.EndElement:     //Display the end of the element.
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }

            return(profiles);
        }
Esempio n. 20
0
        public FashionLevel(string levelDataPath, FashionNpcMediator fashionNpcMediator, bool firstTimePlayed, float requiredEnergy)
        {
            mScheduler = GameFacade.Instance.RetrieveMediator <SchedulerMediator>().Scheduler;

            mLevelXmlPath = levelDataPath;
            mLevelXml     = XmlUtility.LoadXmlDocument(mLevelXmlPath);

            XmlNode backgroundNode = mLevelXml.SelectSingleNode("Level/RunwayBackground");

            if (backgroundNode != null)
            {
                mRunwayBackgroundPath = backgroundNode.InnerText;
            }
            else
            {
                Debug.LogError("No background url node in level xml.");
            }

            XmlNode locationNode = mLevelXml.SelectSingleNode("Level/LocationName");

            if (backgroundNode != null)
            {
                mLocationName = locationNode.InnerText;
            }
            else
            {
                Debug.LogError("No location node in level xml.");
            }

            XmlNode runwayMusicNode = mLevelXml.SelectSingleNode("Level/RunwayMusic");

            if (runwayMusicNode != null)
            {
                mRunwayMusicPath = runwayMusicNode.InnerText;
            }
            else
            {
                Debug.LogError("No runway music node in level xml.");
            }

            XmlNode levelAssetsPath = mLevelXml.SelectSingleNode("Level/@path");

            if (levelAssetsPath == null)
            {
                throw new Exception("Cannot load level from " + levelDataPath + ", no Level/@path attribute found.");
            }

            ClientAssetRepository clientAssetRepo = GameFacade.Instance.RetrieveProxy <ClientAssetRepository>();

            clientAssetRepo.LoadAssetFromPath <UnityEngineAsset>(levelAssetsPath.InnerText, BuildLevelAssets);

            XmlNode startNode = mLevelXml.SelectSingleNode("Level/ModelSpawn");

            mStartWidth     = float.Parse(startNode.Attributes["width"].InnerText);
            mEnd            = XmlUtility.ParsePositionDirection(mLevelXml.SelectSingleNode("Level/ModelDrain"));
            mEndWidth       = float.Parse(startNode.Attributes["width"].InnerText);
            mName           = mLevelXml.SelectSingleNode("Level/@name").InnerText;
            mStart          = XmlUtility.ParsePositionDirection(startNode);
            mModelsRequired = int.Parse(mLevelXml.SelectSingleNode("Level/Waves/@requiredModels").InnerText);

            mLevelGui = new LevelGui(mLevelXml, this);
            if (fashionNpcMediator == null)
            {
                throw new ArgumentNullException("fashionModelMediator");
            }
            mFashionNpcMediator = fashionNpcMediator;
            mLevelGameplay      = new LevelGameplay(mLevelXml, this, mFashionNpcMediator);
            mFirstTimePlayed    = firstTimePlayed;

            mRequiredEnergy = requiredEnergy;
        }
Esempio n. 21
0
        /// <summary>
        /// Saves the specified filename.
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <param name="document">The document.</param>
        public static bool Save(List <NetworkProfile> profiles, string filename = "Profiles.xml")
        {
            XmlTextWriter writer = new XmlTextWriter(filename, null);

            writer.WriteStartDocument();
            writer.Indentation = 1;
            writer.IndentChar  = '\t';

            writer.WriteStartElement("profiles");

            foreach (NetworkProfile item in profiles)
            {
                writer.WriteStartElement("profile");
                writer.WriteAttributeString("name", item.Name);
                writer.WriteAttributeString("id", item.Id.ToString());
                writer.WriteAttributeString("imageName", item.ImageName);

                {
                    WindowsNetworkCard nic = item.NetworkCardInfo;

                    writer.WriteStartElement("networkcard");

                    if (nic.Id.Length > 0)
                    {
                        XmlUtility.WriteAttributeIfPresent(writer, "id", nic.Id);
                        XmlUtility.WriteAttributeIfPresent(writer, "viewId", nic.ViewId);
                        XmlUtility.WriteAttributeIfPresent(writer, "hardwareName", nic.HardwareName);
                        XmlUtility.WriteAttributeIfPresent(writer, "name", nic.Name);
                        XmlUtility.WriteAttributeIfPresent(writer, "dhcp", nic.Dhcp.ToString());
                        XmlUtility.WriteAttributeIfPresent(writer, "ipAddress", nic.IpAddress);
                        XmlUtility.WriteAttributeIfPresent(writer, "subnetMask", nic.SubnetMask);
                        XmlUtility.WriteAttributeIfPresent(writer, "defaultGateway", nic.GatewayAddress);
                        XmlUtility.WriteAttributeIfPresent(writer, "macAddress", nic.MacAddress);
                        XmlUtility.WriteAttributeIfPresent(writer, "dynamicDns", nic.DynamicDNS.ToString());
                        XmlUtility.WriteAttributeIfPresent(writer, "dns", nic.Dns);
                        XmlUtility.WriteAttributeIfPresent(writer, "dns2", nic.Dns2);
                        XmlUtility.WriteAttributeIfPresent(writer, "winsPrimaryServer", nic.WinsPrimaryServer);
                        XmlUtility.WriteAttributeIfPresent(writer, "winsSecondaryServer", nic.WinsSecondaryServer);
                    }
                    writer.WriteEndElement();
                }

                {
                    ProxyConfiguration proxy = item.ProxyConfig;

                    writer.WriteStartElement("proxy");
                    writer.WriteAttributeString("enabled", proxy.Enabled.ToString());
                    XmlUtility.WriteAttributeIfPresent(writer, "serverAddress", proxy.ServerAddress);
                    XmlUtility.WriteAttributeIfPresent(writer, "port", proxy.Port.ToString());
                    writer.WriteAttributeString("overrideEnabled", proxy.ProxyOverrideEnabled.ToString());
                    XmlUtility.WriteAttributeIfPresent(writer, "proxyOverride", proxy.ProxyOverride.ToString());
                    writer.WriteEndElement();
                }

                {
                    writer.WriteStartElement("driveMaps");

                    List <DriveMap> listDriveMap = item.DriveMapList;

                    foreach (DriveMap itemDriveMap in listDriveMap)
                    {
                        writer.WriteStartElement("driveMap");
                        writer.WriteAttributeString("name", itemDriveMap.Name);
                        XmlUtility.WriteAttributeIfPresent(writer, "drive", itemDriveMap.Drive);
                        XmlUtility.WriteAttributeIfPresent(writer, "description", itemDriveMap.Description);
                        XmlUtility.WriteAttributeIfPresent(writer, "username", itemDriveMap.Username);
                        XmlUtility.WriteAttributeIfPresent(writer, "password", itemDriveMap.Password);
                        XmlUtility.WriteAttributeIfPresent(writer, "realPath", itemDriveMap.RealPath);
                        XmlUtility.WriteAttributeIfPresent(writer, "type", itemDriveMap.Type.ToString());
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                }

                {
                    writer.WriteStartElement("applications");

                    List <WindowsExecutable> listExe = item.ExecList;

                    foreach (WindowsExecutable itemExec in listExe)
                    {
                        writer.WriteStartElement("application");
                        writer.WriteAttributeString("name", itemExec.Name);
                        XmlUtility.WriteAttributeIfPresent(writer, "description", itemExec.Description);

                        XmlUtility.WriteAttributeIfPresent(writer, "directory", itemExec.Directory);
                        XmlUtility.WriteAttributeIfPresent(writer, "fileName", itemExec.File);
                        XmlUtility.WriteAttributeIfPresent(writer, "arguments", itemExec.Arguments);
                        XmlUtility.WriteAttributeIfPresent(writer, "wait", itemExec.WaitForExit.ToString());
                        XmlUtility.WriteAttributeIfPresent(writer, "kill", itemExec.Kill.ToString());
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                }

                {
                    writer.WriteStartElement("services");

                    List <IWindowsServiceInfo> listService = item.ServiceList;

                    foreach (IWindowsServiceInfo itemService in listService)
                    {
                        writer.WriteStartElement("service");
                        writer.WriteAttributeString("name", itemService.ServiceName);

                        XmlUtility.WriteAttributeIfPresent(writer, "status", itemService.ForcedStatus.ToString());
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                }

                // Printer
                {
                    writer.WriteStartElement("printer");
                    XmlUtility.WriteAttributeIfPresent(writer, "defaultPrinter", item.DefaultPrinter);
                    writer.WriteEndElement();
                }

                // disabled nic
                {
                    writer.WriteStartElement("forcedNics");

                    IList <WindowsNetworkCard> listDisabledNics = item.DisabledNetworkCards;

                    foreach (WindowsNetworkCard itemNIC in listDisabledNics)
                    {
                        writer.WriteStartElement("forcedNic");
                        writer.WriteAttributeString("id", itemNIC.Id);
                        writer.WriteAttributeString("hardwareName", itemNIC.HardwareName);
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                }

                // wifi
                {
                    writer.WriteStartElement("wifi");
                    writer.WriteAttributeString("associatedSSID", item.AssociatedWifiSSID);
                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
            }

            writer.WriteEndElement();

            writer.WriteEndDocument();
            writer.Close();

            return(true);
        }
        /// <summary>
        /// Initializes Job BEO
        /// </summary>
        /// <param name="jobId">Job Identifier</param>
        /// <param name="jobRunId">Job Run Identifier</param>
        /// <param name="bootParameters">Boot parameters</param>
        /// <param name="createdBy">Job created by</param>
        /// <returns>Job Business Entity</returns>
        protected override CompareSavedSearchResultsJobBEO Initialize(int jobId, int jobRunId, string bootParameters,
                                                                      string createdBy)
        {
            try
            {
                LogMessage(Constants.InitializationStartMessage, GetType(), Constants.InitializeMethodFullName,
                           EventLogEntryType.Information, jobId, jobRunId);
                //using job framework Logging
                LogMessage(Constants.InitializationStartMessage, false, LogCategory.Job, null);
                try
                {
                    // Set level of logging
                    _fileType     = (ApplicationConfigurationManager.GetValue(Constants.RequiredFileType));
                    _encodingType = (ApplicationConfigurationManager.GetValue(Constants.RequiredEncoding));
                    _xslFilePathForComparisonReport =
                        (CmgServiceConfigBO.GetServiceConfigurationsforConfig(Constants.XslFilePathForComparisonReport));
                    LogMessage(Constants.InitializationDoneForConfigurableItemMessage, false, LogCategory.Job, null);
                    LogMessage(Constants.InitializationDoneForConfigurableItemMessage, GetType(),
                               Constants.InitializeMethodFullName, EventLogEntryType.Information, jobId, jobRunId);
                }
                catch
                {
                    _isJobFailed = true;
                    LogMessage(Constants.InitializationDoneForConfigurableItemErrorMessage, true, LogCategory.Job, null);
                    LogMessage(Constants.InitializationDoneForConfigurableItemErrorMessage, GetType(),
                               Constants.InitializeMethodFullName, EventLogEntryType.Information, jobId, jobRunId);
                }

                //Constructing Search Results property Beo from passed boot paramter
                _searchResultsProperty =
                    (SearchResultsPropertiesDataContract)
                    XmlUtility.DeserializeObject(bootParameters, typeof(SearchResultsPropertiesDataContract));

                //Initialize the JobBEO object
                _jobBeo.JobName = string.Format("Compare Job - {0} at {1}", _searchResultsProperty.SearchResultsName,
                                                DateTime.UtcNow.ConvertToUserTime());
                _jobBeo.JobDescription = _searchResultsProperty.SearchResultsDescription;
                _jobBeo.FileType       = _fileType;

                _jobBeo.JobTypeName = Constants.JobTypeName;
                _jobBeo.JobId       = jobId;
                _jobBeo.JobRunId    = jobRunId;

                // Obtain User BEO of job owner -> will be used for audit log purpose
                _userEntityOfJobOwner        = UserBO.GetUserUsingGuid(createdBy);
                _jobBeo.JobScheduleCreatedBy = (_userEntityOfJobOwner.DomainName.Equals("N/A"))
                    ? _userEntityOfJobOwner.UserId
                    : _userEntityOfJobOwner.DomainName + "\\" + _userEntityOfJobOwner.UserId;
            }
            catch (EVException ex)
            {
                _isJobFailed = true;
                WriteToEventViewer(ex, GetType(), MethodBase.GetCurrentMethod().Name, jobId, jobRunId);
                HandleJobException(null, ErrorCodes.ProblemInJobInitialization);
            }
            catch (Exception ex)
            {
                _isJobFailed = true;
                // Handle exception in initialize
                LogMessage(ex, GetType(), MethodBase.GetCurrentMethod().Name, EventLogEntryType.Error, jobId, jobRunId);
                HandleJobException(ex, ErrorCodes.ProblemInJobInitialization);
            }
            return(_jobBeo);
        }
Esempio n. 23
0
 public override void WriteTo(XElement xE)
 {
     base.WriteTo(xE);
     XmlUtility.SetXsiType(xE, "https://adwords.google.com/api/adwords/cm/v201609", "UnknownProductDimension");
 }
Esempio n. 24
0
        /// <summary>
        /// 保存校准任务点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (getopid != null)
            {
                if (!getopid())
                {
                    MessageBox.Show("当前任务正在测试,暂停后方可继续下任务!");
                    return;
                }
            }
            this.btnSave.Enabled = false;
            if (projectPage1.GetSelectedProjects().Count == 0 &&
                projectPage2.GetSelectedProjects().Count == 0 &&
                projectPage3.GetSelectedProjects().Count == 0 &&
                projectPage4.GetSelectedProjects().Count == 0)
            {
                MessageBox.Show("请选择校准项目!");
                this.btnSave.Enabled = true;
                return;
            }
            if (intPos >= System.Convert.ToInt32(txtSumpleNum.Text.Substring(1)))
            {
                MessageBox.Show("此任务已经存在!");
                this.btnSave.Enabled = true;
                return;
            }

            List <CalibratorinfoTask> lstCalibratorinfoTask = new List <CalibratorinfoTask>();
            DateTime dt = DateTime.Now;

            foreach (string qcName in projectPage1.GetSelectedProjects())
            {
                CalibratorinfoTask qcTaskInfo = new CalibratorinfoTask();
                qcTaskInfo.CreateDate  = dt;
                qcTaskInfo.ProjectName = qcName;
                qcTaskInfo.SampleType  = combSampleType.Text;
                qcTaskInfo.SampleNum   = txtSumpleNum.Text;
                lstCalibratorinfoTask.Add(qcTaskInfo);
            }
            foreach (string qcName in projectPage2.GetSelectedProjects())
            {
                CalibratorinfoTask qcTaskInfo = new CalibratorinfoTask();
                qcTaskInfo.CreateDate  = dt;
                qcTaskInfo.ProjectName = qcName;
                qcTaskInfo.SampleType  = combSampleType.Text;
                qcTaskInfo.SampleNum   = txtSumpleNum.Text;
                lstCalibratorinfoTask.Add(qcTaskInfo);
            }
            foreach (string qcName in projectPage3.GetSelectedProjects())
            {
                CalibratorinfoTask qcTaskInfo = new CalibratorinfoTask();
                qcTaskInfo.CreateDate  = dt;
                qcTaskInfo.ProjectName = qcName;
                qcTaskInfo.SampleType  = combSampleType.Text;
                qcTaskInfo.SampleNum   = txtSumpleNum.Text;
                lstCalibratorinfoTask.Add(qcTaskInfo);
            }
            foreach (string qcName in projectPage4.GetSelectedProjects())
            {
                CalibratorinfoTask qcTaskInfo = new CalibratorinfoTask();
                qcTaskInfo.CreateDate  = dt;
                qcTaskInfo.ProjectName = qcName;
                qcTaskInfo.SampleType  = combSampleType.Text;
                qcTaskInfo.SampleNum   = txtSumpleNum.Text;
                lstCalibratorinfoTask.Add(qcTaskInfo);
            }
            sampleBlank = null;
            sampleSerum = null;
            sampleUrine = null;
            lstBlankProject.Clear();
            lstUrinePeoject.Clear();
            lstSerumProject.Clear();
            calibDictionary.Clear();
            //保存任务信息
            calibDictionary.Add("QueryCalibratorinfoTask", new object[] { XmlUtility.Serializer(typeof(List <CalibratorinfoTask>), lstCalibratorinfoTask) });
            combSampleType_SelectedIndexChanged(null, null);
            ClientSendDataToServices(calibDictionary);
        }
Esempio n. 25
0
        /// <summary>
        /// Perform the file processing while timing the operation.
        /// </summary>
        protected override void Execute()
        {
            DirectoryInfo directory = new DirectoryInfo(Environment.CurrentDirectory);
            ArrayList     files     = new ArrayList();

            try {
                for (int index = 0; index < Arguments.Length; ++index)
                {
                    String location = directory.ToString();
                    string target   = Arguments [index];

                    while (target.StartsWith(@"..\"))
                    {
                        location = location.Substring(0, location.LastIndexOf(Path.DirectorySeparatorChar));
                        target   = target.Substring(3);
                    }
                    FindFiles(files, Path.Combine(location, target));
                }
            }
            catch (Exception error) {
                log.Fatal("Invalid command line argument", error);

                Finished = true;
                return;
            }

            XmlDocument document;
            NodeIndex   nodeIndex;

            try {
                for (int index = 0; index < files.Count; ++index)
                {
                    string     filename = (files [index] as FileInfo).FullName;
                    FileStream stream   = File.OpenRead(filename);

                    document = XmlUtility.NonValidatingParse(stream);

                    System.Console.WriteLine(">> " + filename);

                    Release release = Specification.ReleaseForDocument(document);

                    if (release != null)
                    {
                        if (release is DTDRelease)
                        {
                            System.Console.WriteLine("= " + release
                                                     + " {" + (release as DTDRelease).PublicId + "}");
                        }
                        else if (release is SchemaRelease)
                        {
                            System.Console.WriteLine("= " + release
                                                     + " {" + (release as SchemaRelease).NamespaceUri + "}");
                        }
                        else
                        {
                            System.Console.WriteLine("= " + release);
                        }
                    }

                    if (isdaOption.Present)
                    {
                        if (release != Releases.R5_3_CONFIRMATION)
                        {
                            Conversion conversion = Conversion.ConversionFor(release, Releases.R5_3_CONFIRMATION);

                            if (conversion == null)
                            {
                                Console.WriteLine("!! The contents of the file can not be converted to FpML 5.3 (Confirmation)");
                                continue;
                            }
                            document = conversion.Convert(document, new DefaultHelper());

                            if (document == null)
                            {
                                Console.WriteLine("!! Automatic conversion to FpML 5.3 (Confirmation) failed");
                                continue;
                            }
                        }

                        nodeIndex = new NodeIndex(document);

                        DoIsdaClassify(nodeIndex.GetElementsByName("trade"));
                    }
                    else
                    {
                        nodeIndex = new NodeIndex(document);

                        DoClassify(nodeIndex.GetElementsByName("trade"), "Trade");
                        DoClassify(nodeIndex.GetElementsByName("contract"), "Contract");
                    }
                    stream.Close();
                }
            }
            catch (Exception error) {
                log.Fatal("Unexpected exception during processing", error);
            }

            Finished = true;
        }
Esempio n. 26
0
 /// <summary>
 /// Xml to object
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="xml"></param>
 /// <param name="repository"> Assign repository to load XmlIgnored properties</param>
 /// <returns></returns>
 public static object FromXml(this string xml, IRepository repository = null)
 {
     return(XmlUtility.FromXml(xml, repository));
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="maxRecordCount"></param>
        /// <param name="postData">需要传入到Init的参数</param>
        public MessageHandler(Stream inputStream, int maxRecordCount = 0, object postData = null)
        {
            var postDataDocument = XmlUtility.Convert(inputStream);

            CommonInitialize(postDataDocument, maxRecordCount, postData);
        }
Esempio n. 28
0
        public static object Regiser()
        {
            string configXmlPath = Rally.Framework.Authorization.ModuleConfiguration.DefaultResourceACConfigurationFilePath;
            string configXml     = "";

            if (!IO.File.Exists(configXmlPath))
            {
                return(null);
            }

            using (FileStream stream = new FileStream(configXmlPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    configXml = reader.ReadToEnd();
                }
            }

            ResourceAuthConfiguration authConf = XmlUtility.XmlDeserialize <ResourceAuthConfiguration>(configXml, new Type[] { typeof(Resource), typeof(Subject), typeof(Scope), typeof(Action) }, "utf-8");

            IAuthorization authorizationManager = Facade.CreateAuthorizationManager();

            string regiseredOpId = null, registeredScopeId = null;

            string[] ops = authorizationManager.GetDataTypeOperations(null), scopes = authorizationManager.GetDataScopes(null);

            List <string> opsRegistered = null, scopesRegistered = null, rolesRegistered = null, allRoles = new List <string>();

            List <object> identityResults = null;

            if (authConf != null)
            {
                opsRegistered    = new List <string>();
                scopesRegistered = new List <string>();
                //rolesRegistered = new List<string>();

                foreach (var resource in authConf.Resources)
                {
                    if (resource != null)
                    {
                        if ((resource.Actions != null) && (resource.Actions.Length > 0))
                        {
                            if (ops == null)
                            {
                                ops = new string[] { };
                            }

                            ops = ops.Select(o => o.ToLower()).ToArray();

                            foreach (var action in resource.Actions)
                            {
                                if ((action != null) && (!ops.Contains(action.ID.ToLower())) && (!opsRegistered.Contains(action.ID.ToLower())))
                                {
                                    regiseredOpId = (int)authorizationManager.RegisterOperation(resource.Name, action.ID, action.Name) >= 0 ? action.ID : null;

                                    if (!String.IsNullOrEmpty(regiseredOpId))
                                    {
                                        opsRegistered.Add(regiseredOpId.ToLower());
                                    }
                                }
                            }

                            if (Rally.Framework.Authorization.ModuleConfiguration.ShouldDeleteObsoleteOperationsOnRegistration)
                            {
                                var obsoleteRoleOps = authorizationManager.GetRoleOperations(null) as IList <IDictionary <string, object> >;
                                obsoleteRoleOps = obsoleteRoleOps == null ? null : obsoleteRoleOps.Where(ro => !opsRegistered.Contains((string)ro["OperationId"]) && !ops.Contains((string)ro["OperationId"])) as IList <IDictionary <string, object> >;

                                if (obsoleteRoleOps != null && obsoleteRoleOps.Count > 0)
                                {
                                    for (int i = 0; i < obsoleteRoleOps.Count; i++)
                                    {
                                        authorizationManager.DeleteOperation((string)obsoleteRoleOps[i]["OperationId"]);
                                    }
                                }

                                var obsoleteObjectAuthItems = authorizationManager.GetObjectAuthItems() as IList <IDictionary <string, object> >;
                                obsoleteObjectAuthItems = obsoleteObjectAuthItems == null ? null : obsoleteObjectAuthItems.Where(oo => !opsRegistered.Contains((string)oo["OperationId"]) && !ops.Contains((string)oo["OperationId"])) as IList <IDictionary <string, object> >;

                                if (obsoleteObjectAuthItems != null && obsoleteObjectAuthItems.Count > 0)
                                {
                                    for (int i = 0; i < obsoleteObjectAuthItems.Count; i++)
                                    {
                                        authorizationManager.DeleteOperation((string)obsoleteObjectAuthItems[i]["OperationId"]);
                                    }
                                }

                                var obsoleteOps = authorizationManager.GetOperations() as IList <IDictionary <string, object> >;
                                obsoleteOps = obsoleteOps == null ? null : obsoleteOps.Where(o => !opsRegistered.Contains((string)o["Id"]) && !ops.Contains((string)o["Id"])) as IList <IDictionary <string, object> >;

                                if (obsoleteOps != null && obsoleteOps.Count > 0)
                                {
                                    for (int i = 0; i < obsoleteOps.Count; i++)
                                    {
                                        authorizationManager.DeleteOperation((string)obsoleteOps[i]["Id"]);
                                    }
                                }
                            }
                        }

                        if ((resource.Scopes != null) && (resource.Scopes.Length > 0))
                        {
                            if (scopes == null)
                            {
                                scopes = new string[] { };
                            }

                            scopes = scopes.Select(s => s.ToLower()).ToArray();

                            foreach (var scope in resource.Scopes)
                            {
                                if ((scope != null) && (!scopes.Contains(scope.ID.ToLower())) && (!scopesRegistered.Contains(scope.ID.ToLower())))
                                {
                                    registeredScopeId = (int)authorizationManager.RegisterDataScope(resource.Name, scope.ID, scope.Name, scope.Type, resource.Key) >= 0 ? scope.ID : null;

                                    if (!String.IsNullOrEmpty(registeredScopeId))
                                    {
                                        scopesRegistered.Add(registeredScopeId.ToLower());
                                    }
                                }
                            }

                            if (Rally.Framework.Authorization.ModuleConfiguration.ShouldDeleteObsoleteDataScopesOnRegistration)
                            {
                                var obsoleteRoleDataScopes = authorizationManager.GetRoleDataScopes(null) as IList <IDictionary <string, object> >;
                                obsoleteRoleDataScopes = obsoleteRoleDataScopes == null ? null : obsoleteRoleDataScopes.Where(rd => !!scopesRegistered.Contains((string)rd["DataScopeId"]) && !scopes.Contains((string)rd["DataScopeId"])) as IList <IDictionary <string, object> >;

                                if (obsoleteRoleDataScopes != null && obsoleteRoleDataScopes.Count > 0)
                                {
                                    for (int i = 0; i < obsoleteRoleDataScopes.Count; i++)
                                    {
                                        authorizationManager.DeleteDataScope((string)obsoleteRoleDataScopes[i]["DataScopeId"]);
                                    }
                                }

                                var obsoleteDataScopes = authorizationManager.GetDataScopes(null) as string[];
                                obsoleteDataScopes = obsoleteDataScopes == null ? null : obsoleteDataScopes.Where(ds => !scopesRegistered.Contains(ds) && !scopes.Contains(ds)) as string[];

                                if (obsoleteDataScopes != null && obsoleteDataScopes.Length > 0)
                                {
                                    for (int i = 0; i < obsoleteDataScopes.Length; i++)
                                    {
                                        authorizationManager.DeleteDataScope(obsoleteDataScopes[i]);
                                    }
                                }
                            }
                        }

                        if ((resource.Subjects != null) && (resource.Subjects.Length > 0))
                        {
                            var accountManager = Facade.CreateAccountManager();
                            var userManager    = Facade.CreateUserManager();

                            IDictionary <string, string> rolesToRegister  = new Dictionary <string, string>();
                            IDictionary <string, string> roleDescriptions = new Dictionary <string, string>();

                            foreach (var subject in resource.Subjects)
                            {
                                if (subject.Type.ToLower() == "fixedrole")
                                {
                                    allRoles.Add(subject.ID);

                                    if (!authorizationManager.RoleExists(subject.ID, subject.Name))
                                    {
                                        rolesToRegister.Add(subject.ID, subject.Name);
                                        roleDescriptions.Add(subject.ID, subject.Description);
                                    }
                                }
                                else if (subject.Type.ToLower() == "fixeduser")
                                {
                                    bool userExists   = userManager.UserExists(subject.ID, subject.Name);
                                    var  identityUser = accountManager.GetAccount(subject.ID);

                                    if (identityUser == null)
                                    {
                                        identityUser = accountManager.GetAccountByNickName(subject.Name);
                                    }

                                    if ((identityUser != null) && userExists && Rally.Framework.Authorization.ModuleConfiguration.ShouldDeleteObsoleteUsersOnRegistration)
                                    {
                                    }

                                    if (identityUser == null && !userExists)
                                    {
                                        userManager.AddUser <Core.DomainModel.Account>(subject.ID, subject.Name, Rally.Framework.Authentication.ModuleConfiguration.DefaultFixedUserPassword, (u) => {
                                            string userId = u.ToString();

                                            var account = new Core.DomainModel.Account()
                                            {
                                                ID       = userId,
                                                Name     = subject.Name,
                                                NickName = subject.Name
                                            };

                                            accountManager.AddAccount(account);

                                            return(account);
                                        });
                                    }
                                }
                            }

                            rolesRegistered = (int)authorizationManager.AddRoles(rolesToRegister, roleDescriptions) >= 0 ? rolesRegistered : null;

                            if (rolesRegistered == null)
                            {
                                rolesRegistered = new List <string>();
                            }

                            if (Rally.Framework.Authorization.ModuleConfiguration.ShouldDeleteObsoleteRolesOnRegistration)
                            {
                                var obsoleteRoleDataScopes = authorizationManager.GetRoleDataScopes(null) as IList <IDictionary <string, object> >;
                                obsoleteRoleDataScopes = obsoleteRoleDataScopes == null ?  null : obsoleteRoleDataScopes.Where(rd => !rolesRegistered.Contains((string)rd["RoleId"])) as IList <IDictionary <string, object> >;

                                if (obsoleteRoleDataScopes != null && obsoleteRoleDataScopes.Count > 0)
                                {
                                    for (int i = 0; i < obsoleteRoleDataScopes.Count; i++)
                                    {
                                        authorizationManager.DeleteDataScope((string)obsoleteRoleDataScopes[i]["DataScopeId"]);
                                    }
                                }

                                var obsoleteRoleOps = authorizationManager.GetRoleOperations(null) as IList <IDictionary <string, object> >;
                                obsoleteRoleOps = obsoleteRoleOps == null ? null : obsoleteRoleOps.Where(ro => !opsRegistered.Contains((string)ro["RoleId"]) && !ops.Contains((string)ro["RoleId"])) as IList <IDictionary <string, object> >;

                                if (obsoleteRoleOps != null && obsoleteRoleOps.Count > 0)
                                {
                                    for (int i = 0; i < obsoleteRoleOps.Count; i++)
                                    {
                                        authorizationManager.DeleteOperation((string)obsoleteRoleOps[i]["OperationId"]);
                                    }
                                }

                                var obsoleteRoles = authorizationManager.GetRoles() as IList <IDictionary <string, object> >;
                                obsoleteRoles = obsoleteRoles == null ? null : obsoleteRoles.Where(r => !rolesRegistered.Contains((string)r["Id"]) && !allRoles.Contains((string)r["Id"])) as IList <IDictionary <string, object> >;

                                if (obsoleteRoles != null && obsoleteRoles.Count > 0)
                                {
                                    for (int i = 0; i < obsoleteRoles.Count; i++)
                                    {
                                        authorizationManager.DeleteRole((string)obsoleteRoles[i]["Id"]);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(((opsRegistered != null) || (scopesRegistered != null) || (rolesRegistered != null) || (identityResults != null)) ? new object[] { opsRegistered, scopesRegistered, rolesRegistered, identityResults } : null);
        }
Esempio n. 29
0
 public static string GetUserConfig(string nodename)
 {
     XmlUtility.filename = "SMTPXML.xml";
     return(XmlUtility.GetUserConfig(nodename));
 }
Esempio n. 30
0
 public void TestXmlUtilityEmptyString()
 {
     Assert.Equal(XmlUtility.Sanitize("\u0000\u0001\u000b\u000e\u007f\u0086\uFFFE"), String.Empty);
 }
Esempio n. 31
0
 public static void SetUserConfig(string nodeName, string nodeInnerText)
 {
     XmlUtility.filename = "SMTPXML.xml";
     XmlUtility.SetUserConfig(nodeName, nodeInnerText);
 }
Esempio n. 32
0
        private void WriteXmlValue(XmlWriter writer, IHierarchy <object> node)
        {
            if (node.IsNodeEnumerable())
            {
                return;
            }

            var converter = Converters.FirstOrDefaultWriterConverter(node.InstanceType);

            if (converter != null)
            {
                converter.WriteXml(writer, node.Instance);
                return;
            }

            bool hasAttributeAttribute = node.HasMemberReference && TypeUtility.ContainsAttributeType(node.MemberReference, typeof(XmlAttributeAttribute));
            bool hasElementAttribute   = node.HasMemberReference && TypeUtility.ContainsAttributeType(node.MemberReference, typeof(XmlElementAttribute));
            bool hasTextAttribute      = node.HasMemberReference && TypeUtility.ContainsAttributeType(node.MemberReference, typeof(XmlTextAttribute));

            bool   isType   = node.Instance is Type;
            Type   nodeType = isType ? (Type)node.Instance : node.InstanceType;
            string attributeOrElementName = XmlUtility.SanitizeElementName(node.HasMemberReference ? node.MemberReference.Name : StringConverter.FromType(nodeType));

            if (!hasAttributeAttribute && !hasElementAttribute && !hasTextAttribute)
            {
                hasElementAttribute = true; // default serialization value for legacy Cuemon
                if ((!TypeUtility.IsComplex(nodeType) || isType) && !node.HasChildren && (isType))
                {
                    if (!node.HasParent)
                    {
                        hasElementAttribute = false;
                    }
                    hasTextAttribute = true;
                }
            }
            else
            {
                string elementName = null;
                if (hasAttributeAttribute)
                {
                    elementName = node.MemberReference.GetCustomAttribute <XmlAttributeAttribute>().AttributeName;
                }
                if (hasElementAttribute)
                {
                    elementName = node.MemberReference.GetCustomAttribute <XmlElementAttribute>().ElementName;
                }

                if (!string.IsNullOrEmpty(elementName))
                {
                    attributeOrElementName = elementName;
                }
            }

            var value = Wrapper.ParseInstance(node);

            if (hasAttributeAttribute)
            {
                writer.WriteAttributeString(attributeOrElementName, value);
            }
            else if (hasElementAttribute)
            {
                if (node.HasMemberReference)
                {
                    writer.WriteElementString(attributeOrElementName, value);
                }
                else
                {
                    writer.WriteValue(value);
                }
            }
            else if (hasTextAttribute)
            {
                writer.WriteString(value);
            }
        }
Esempio n. 33
0
 /// <summary>
 /// 确定保存按钮
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnConfirm_Click(object sender, EventArgs e)
 {
     if (txtProShortName.Text.Trim() == "")
     {
         MessageBoxDraw.ShowMsg("项目名称为必填项,请填写项目名称!", MsgType.Warning);
         return;
     }
     else if (cboSampleType.SelectedIndex < 0)
     {
         MessageBoxDraw.ShowMsg("请选择项目样本类型!", MsgType.Warning);
         return;
     }
     else
     {
         AssayProjectInfo assayProInfo = new AssayProjectInfo();
         assayProInfo.ProjectName = txtProShortName.Text.Trim();
         assayProInfo.SampleType  = cboSampleType.SelectedItem.ToString();
         if (txtProLongName.Text.Trim() != null)
         {
             assayProInfo.ProFullName = txtProLongName.Text.Trim();
         }
         if (txtChannelNumber.Text.Trim() != null)
         {
             assayProInfo.ChannelNum = txtChannelNumber.Text.Trim();
         }
         if (this.Text == "新建项目")
         {
             if (!_LstAssayProjectInfo.Exists(x => x.ProjectName == assayProInfo.ProjectName && x.SampleType == assayProInfo.SampleType))
             {
                 if (DataHandleEvent != null)
                 {
                     cheProAddOrEditDic.Clear();
                     cheProAddOrEditDic.Add("AssayProjectAdd", new object[] { XmlUtility.Serializer(typeof(AssayProjectInfo), assayProInfo) });
                     DataHandleEvent(cheProAddOrEditDic);
                 }
             }
             else
             {
                 MessageBox.Show("该项目已存在,请重新输入!");
                 txtProShortName.Focus();
             }
         }
         if (this.Text == "编辑项目")
         {
             if (DataHandleEvent != null)
             {
                 cheProAddOrEditDic.Clear();
                 cheProAddOrEditDic.Add("AssayProjectEdit", new object[] { XmlUtility.Serializer(typeof(AssayProjectInfo), assayProInfoOld), XmlUtility.Serializer(typeof(AssayProjectInfo), assayProInfo) });
                 DataHandleEvent(cheProAddOrEditDic);
             }
         }
     }
 }