예제 #1
0
        public void ShouldAddFormsAsChildrenOfShopElement()
        {
            var shop = new ShopBuilder(new Uri("http://localhost"))
                .AddForm(new Form("request-for-quote", new Uri("/quotes", UriKind.Relative), "post", RestbucksMediaType.Value, new Uri("http://schemas.restbucks.com/shop")))
                .AddForm(new Form("order", new Uri("/orders", UriKind.Relative), "put", RestbucksMediaType.Value, new ShopBuilder(new Uri("http://localhost"))
                                                                                                                                      .Build()))
                .Build();

            var output = new XmlOutput(new ShopFormatter(shop).CreateXml());

            Assert.AreEqual(2, output.GetNodeCount("r:shop/x:model"));

            Assert.AreEqual("http://schemas.restbucks.com/shop", output.GetNodeValue("r:shop/x:model[1]/@schema"));
            Assert.AreEqual("request-for-quote", output.GetNodeValue("r:shop/x:model[1]/@id"));
            Assert.AreEqual("/quotes", output.GetNodeValue("r:shop/x:model[1]/x:submission/@resource"));
            Assert.AreEqual("post", output.GetNodeValue("r:shop/x:model[1]/x:submission/@method"));
            Assert.AreEqual(RestbucksMediaType.Value, output.GetNodeValue("r:shop/x:model[1]/x:submission/@mediatype"));
            Assert.AreEqual(string.Empty, output.GetNodeValue("r:shop/x:model[1]/x:instance"));

            Assert.IsNull(output.GetNode("r:shop/x:model[2]/@schema"));
            Assert.AreEqual("order", output.GetNodeValue("r:shop/x:model[2]/@id"));
            Assert.AreEqual("/orders", output.GetNodeValue("r:shop/x:model[2]/x:submission/@resource"));
            Assert.AreEqual("put", output.GetNodeValue("r:shop/x:model[2]/x:submission/@method"));
            Assert.AreEqual(RestbucksMediaType.Value, output.GetNodeValue("r:shop/x:model[2]/x:submission/@mediatype"));
            Assert.AreEqual(string.Empty, output.GetNodeValue("r:shop/x:model[2]/x:instance/r:shop"));
        }
예제 #2
0
        public string GetAPIVersion()
        {
            var xo = new XmlOutput()
                     .XmlDeclaration()
                     .Node("NETBOX-API").Attribute("sessionid", SessionID).Within()
                     .Node("COMMAND").Attribute("name", "GetAPIVersion").Attribute("num", "1");

            var doc = HttpPost(xo);

            if (CallWasSuccessful(doc))
            {
                var results = doc.GetElementsByTagName("APIVERSION");
                return(results.Count == 1 ? string.Format("API Version: {0}", results[0].InnerXml) : doc.InnerXml);
            }

            return("call failed");
        }
예제 #3
0
        /// <summary>
        /// Performs XSL Transformation.
        /// </summary>
        private void Transform(XmlReader srcReader, MvpXslTransform xslt, XmlResolver resolver)
        {
            Stopwatch transformTimer = null;

            if (options.ShowTiming)
            {
                transformTimer = new Stopwatch();
                transformTimer.Start();
            }
            if (options.OutFile != null)
            {
                //Transform to a file
                FileStream fs;
                try
                {
                    fs = File.Open(options.OutFile, FileMode.Create);
                }
                catch
                {
                    throw new NXsltException(NXsltStrings.ErrorCreatingFile, options.OutFile);
                }
                try
                {
                    XmlOutput results = new XmlOutput(fs);
                    results.XmlResolver = new OutputResolver(Path.GetDirectoryName(options.OutFile));
                    TransformImpl(srcReader, xslt, resolver, results);
                }
                finally
                {
                    fs.Close();
                }
            }
            else
            {
                //Transform to Console
                XmlOutput results = new XmlOutput(Console.Out);
                results.XmlResolver = new OutputResolver(Directory.GetCurrentDirectory());
                TransformImpl(srcReader, xslt, resolver, results);
            }
            //Save transfomation time
            if (options.ShowTiming)
            {
                transformTimer.Stop();
                timings.XsltExecutionTime = transformTimer.ElapsedMilliseconds;
            }
        }
예제 #4
0
        public void ShouldAddCompactUriLinkRelationNamespacesToRootShopElement()
        {
            const string ns1 = "http://restbucks/relations/";
            const string ns2 = "http://thoughtworks/relations/";

            var rel1 = new CompactUriLinkRelation("rb", new Uri(ns1, UriKind.Absolute), "rel1");
            var rel2 = new CompactUriLinkRelation("tw", new Uri(ns2, UriKind.Absolute), "rel2");

            var shop = new ShopBuilder(new Uri("http://locahost/"))
                .AddLink(new Link(new Uri("/quotes", UriKind.Relative), RestbucksMediaType.Value, rel1, rel2))
                .Build();

            var xml = new XmlOutput(new ShopFormatter(shop).CreateXml());

            Assert.AreEqual(ns1, xml.GetNamespaceValue("rb"));
            Assert.AreEqual(ns2, xml.GetNamespaceValue("tw"));
        }
예제 #5
0
        public override void xslTransformer(XPathNavigator xNav, XsltArgumentList xArgs)
        {
            XsltSettings   settings = new XsltSettings(true, true);
            XmlUrlResolver r        = new XmlUrlResolver();

            MvpXslTransform xslObj = new MvpXslTransform();

            xslObj.Load(classXSLObjectSource, settings, r);
            XmlInput  xm = new XmlInput(xNav);
            XmlOutput xo;

            if (!(clsFileIO == null))
            {
                xo = new XmlOutput(clsFileIO);
                xslObj.Transform(xm, xArgs, xo);
                clsTEXTResult = "FILE SAVED";
            }
            else if (!(clsHTTPResponse == null))
            {
                xo = new XmlOutput(clsHTTPResponse.OutputStream);
                xslObj.Transform(xm, xArgs, xo);
                clsTEXTResult = "OUTPUT STREAMED TO HTTP RESPONSE";
            }
            else if (!(clsXMLObjectReturn == null))
            {
                StringWriter sWrit = new StringWriter();
                xo = new XmlOutput(sWrit);

                xslObj.Transform(xm, xArgs, xo);
                clsXMLObjectReturn.LoadXml(sWrit.ToString());
            }
            else
            {
                StringWriter sWrit = new StringWriter();
                xo = new XmlOutput(sWrit);

                xslObj.Transform(xm, xArgs, xo);

                // default - results to text
                clsTEXTResult = sWrit.ToString();
            }
        }
예제 #6
0
        public XmlNode GetAccessHistory(DateTime from, string nextId = null, string startFromId = null)
        {
            var xo = new XmlOutput()
                     .XmlDeclaration()
                     .Node("NETBOX-API").Attribute("sessionid", SessionID).Within()
                     .Node("COMMAND").Attribute("name", "GetAccessHistory").Attribute("num", "1").Within();

            var param = xo.Node("PARAMS").Within();

            param.Node("OLDESTDTTM").InnerText(from.ToString(DateFormat));
            //optional NEWESTDTTM

            if (nextId != null || startFromId != null)
            {
                if (!string.IsNullOrEmpty(nextId))
                {
                    param.Node("STARTLOGID").InnerText(nextId);
                }

                if (!string.IsNullOrEmpty(startFromId))
                {
                    param.Node("AFTERLOGID").InnerText(startFromId);
                }
            }

            var sw = new StringWriter();
            var tx = new XmlTextWriter(sw);

            xo.GetXmlDocument().WriteTo(tx);

            var doc = HttpPost(xo);

            var code = doc.SelectSingleNode("NETBOX/RESPONSE/CODE");

            if (code != null &&
                (code.InnerXml == "SUCCESS" || code.InnerXml == "NOT FOUND"))
            {
                return(code.InnerXml == "SUCCESS" ? doc["NETBOX"]["RESPONSE"]["DETAILS"] : code);
            }

            return(null);
        }
예제 #7
0
        /// <summary>
        /// Processes the HTTP request.
        /// </summary>
        /// <param name="context">Context of the HTTP operation.</param>
        protected override void InternalProcessRequest(HttpContext context)
        {
            Reminder2DataContext dataCtx = new Reminder2DataContext();
            var query = from User u in dataCtx.Users
                        where u.UserName == context.User.Identity.Name
                        select u.idUser;

            if (query.Count() > 0)
            {
                try
                {
                    Task task = new Task()
                    {
                        Message  = this.Message,
                        DateTime = this.DateTime,
                        idUser   = query.First()
                    };
                    dataCtx.Tasks.InsertOnSubmit(task);
                    dataCtx.SubmitChanges();
                    WriteOutputStatus(200, "OK.");

                    XmlOutput.WriteStartElement("task");
                    try
                    {
                        XmlOutput.WriteAttributeString("id", task.idTask.ToString());
                    }
                    finally
                    {
                        XmlOutput.WriteEndElement();
                    }
                }
                catch (Exception ex)
                {
                    WriteOutputStatus(CommonStatusCode.ServerError, string.Format("Couldn't add task. {0}", ex.Message));
                }
            }
            else
            {
                WriteOutputStatus(CommonStatusCode.ServerError, "Invalid user Id.");
            }
        }
예제 #8
0
        public string ParseFile(string path)
        {
            var parser  = new TxtParser();
            var content = parser.ParseFile(path);

            if (content == null)
            {
                return(string.Empty);
            }

            var       concordance = new Concordanse();
            const int count       = 50;

            concordance.CreateConcordanse(content, count);
            var pathOutput = path;
            //var output = new TxtOutput();
            //output.Output(concordance.GetConcordanseResult(), pathOutput);
            var output = new XmlOutput();

            return(output.Output(concordance, path));
        }
        public int Save(Output output)
        {
            int       id        = 0;
            XmlOutput xmlOutput = new XmlOutput();

            try
            {
                context.Outputs.Add(output);
                context.SaveChanges();

                id = output.Id;

                if (id > 0)
                {
                    foreach (OutputDetail detail in output.Details)
                    {
                        detail.OutputId = id;
                        context.OutputDetails.Add(detail);
                    }

                    context.SaveChanges();

                    bool result = xmlOutput.Create(id); //Create XML

                    //Update Amounts
                    //IWarehouseProductRepository _warehouseProductRepository = new WarehouseProductRepository();

                    //foreach (OutputDetail detail in output.Details)
                    //{
                    //  _warehouseProductRepository.UpdateAmountByCode(detail.Warehouse, detail.Quantity, detail.ProductCode);
                    //}
                }
            }
            catch (Exception ex)
            {
                id = 0;
                Debug.Write(@"Error " + ex.Message);
            }
            return(id);
        }
        public XmlDocument GetXml()
        {
            XmlOutput xo = new XmlOutput()
           .XmlDeclaration()
           .Node("package").Attribute("xmlns", "http://soap.sforce.com/2006/04/metadata").Within();

            foreach (var salesForceChange in Types)
            {
                XmlOutput xmlOutput = xo.Node("types").Within();
                foreach (var member in salesForceChange.Members)
                {
                    xmlOutput.Node("members").InnerText(member);
                }
                xmlOutput.Node("name").InnerText(salesForceChange.Name)
                       .EndWithin();
            }

            xo.EndWithin()
            .Node("version").InnerText(this.Version);

            return xo.GetXmlDocument();
        }
예제 #11
0
        public void ShouldAddItemElementsAsChildrenOfItems()
        {
            var shop = new ShopBuilder(new Uri("http://localhost/"))
                .AddItem(new Item("item1", new Amount("g", 250)))
                .AddItem(new Item("item2", new Amount("g", 500), new Cost("GBP", 5.50)))
                .Build();

            var xml = new XmlOutput(new ShopFormatter(shop).CreateXml());

            Assert.AreEqual(2, xml.GetNodeCount("r:shop/r:items/r:item"));

            Assert.AreEqual("item1", xml.GetNodeValue("r:shop/r:items/r:item[1]/r:description"));
            Assert.AreEqual("g", xml.GetNodeValue("r:shop/r:items/r:item[1]/r:amount/@measure"));
            Assert.AreEqual("250", xml.GetNodeValue("r:shop/r:items/r:item[1]/r:amount"));
            Assert.IsNull(xml.GetNode("r:shop/r:items/r:item[1]/r:price"));

            Assert.AreEqual("item2", xml.GetNodeValue("r:shop/r:items/r:item[2]/r:description"));
            Assert.AreEqual("g", xml.GetNodeValue("r:shop/r:items/r:item[2]/r:amount/@measure"));
            Assert.AreEqual("500", xml.GetNodeValue("r:shop/r:items/r:item[2]/r:amount"));
            Assert.AreEqual("GBP", xml.GetNodeValue("r:shop/r:items/r:item[2]/r:price/@currency"));
            Assert.AreEqual("5.50", xml.GetNodeValue("r:shop/r:items/r:item[2]/r:price"));
        }
        public XmlDocument GetXml()
        {
            XmlOutput xo = new XmlOutput()
                           .XmlDeclaration()
                           .Node("package").Attribute("xmlns", "http://soap.sforce.com/2006/04/metadata").Within();

            foreach (var salesForceChange in Types)
            {
                XmlOutput xmlOutput = xo.Node("types").Within();
                foreach (var member in salesForceChange.Members)
                {
                    xmlOutput.Node("members").InnerText(member);
                }
                xmlOutput.Node("name").InnerText(salesForceChange.Name)
                .EndWithin();
            }

            xo.EndWithin()
            .Node("version").InnerText(this.Version);

            return(xo.GetXmlDocument());
        }
        public static void SendMT(LoginParams secureParams, MtParams mtParams, PhoneParams phoneParams)
        {
            var doc = new XmlOutput();
            doc.XmlDeclaration().Node("request").Within()
                .Node("transaction").InnerText(secureParams.TransactionID.ToString())
                .Node("user").Within()
                    .Node("login").InnerText(secureParams.Login)
                    .Node("pwd").InnerText(secureParams.Password)
                .EndWithin()
                .Node("msg").Within()
                    .Node("format").InnerText(mtParams.Format)
                    .Node("text").InnerText(mtParams.Text, true)
                    .Node("url").InnerText(mtParams.URL)
                    .Node("nc").InnerText(mtParams.NumeroCorto)
                .EndWithin()
                .Node("phone").Within()
                    .Node("ani").InnerText(phoneParams.ANI)
                    .Node("op").InnerText(phoneParams.Op)
                .EndWithin()
            .EndWithin();

            SecureRequest(secureParams, doc.GetOuterXml());
        }
예제 #14
0
        public string[] GetLevelIDS()
        {
            string[] ids = null;

            XmlOutput xo = new XmlOutput()
                           .XmlDeclaration()
                           .Node("NETBOX-API").Attribute("sessionid", _sessionID).Within()
                           .Node("COMMAND").Attribute("name", "GetAccessLevels").Attribute("num", "1").Within()
                           .Node("PARAMS").Within()
                           .Node("WANTKEY").InnerText("TRUE");


            StringWriter  sw = new StringWriter();
            XmlTextWriter tx = new XmlTextWriter(sw);

            xo.GetXmlDocument().WriteTo(tx);

            //string data = sw.ToString();


            XmlDocument doc = HttpPost(xo);

            if (CallWasSuccessful(doc))
            {
                XmlNodeList results = doc.GetElementsByTagName("ACCESSLEVEL");
                if (results.Count > 0)
                {
                    ids = new string[results.Count];
                    for (int x = 0; x < results.Count; x++)
                    {
                        ids[x] = results[x].InnerText;
                    }
                }
            }

            return(ids);
        }
예제 #15
0
        public XmlNode GetAccessLevel(string key)
        {
            var xo = new XmlOutput()
                     .XmlDeclaration()
                     .Node("NETBOX-API").Attribute("sessionid", SessionID).Within()
                     .Node("COMMAND").Attribute("name", "GetAccessLevel").Attribute("num", "1").Within()
                     .Node("PARAMS").Within()
                     .Node("ACCESSLEVELKEY").InnerText(key);

            var sw = new StringWriter();
            var tx = new XmlTextWriter(sw);

            xo.GetXmlDocument().WriteTo(tx);

            var doc = HttpPost(xo);

            if (CallWasSuccessful(doc))
            {
                XmlNode details = doc["NETBOX"]["RESPONSE"]["DETAILS"];
                return(details);
            }

            return(null);
        }
        public string Deploy(string folder, DeployOptions options)
        {
            if (!Directory.Exists(folder))
            {
                throw new DirectoryNotFoundException();
            }

            var staticResourceFolder = Path.Combine(folder, "package\\staticresources");

            if (!Directory.Exists(staticResourceFolder))
            {
                throw new DirectoryNotFoundException("Couldn't find static resources subfolder under package folder.");
            }

            var directories = Directory.EnumerateDirectories(staticResourceFolder);

            IList <IDeployableItem> members = new List <IDeployableItem>();

            foreach (var directory in directories)
            {
                var      splits  = directory.Split('\\');
                var      zipName = splits[splits.Length - 1];
                string[] files   = Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories);

                var directoryPlusZipName = Path.Combine(staticResourceFolder, zipName);

                using (ZipFile zip = new ZipFile())
                {
                    foreach (var file in files)
                    {
                        var zipFileNamePlusDirectory = file.Replace(directoryPlusZipName, String.Empty);
                        var zipDirectory             = Path.GetDirectoryName(zipFileNamePlusDirectory);
                        zip.AddFile(file, zipDirectory);
                    }

                    MemoryStream memoryStream = new MemoryStream();
                    zip.Save(memoryStream);

                    members.Add(new StaticResourceDeployableItem
                    {
                        FileBody = memoryStream.ToArray(),
                        FileName = String.Format("{0}\\{1}.resource", directory, zipName),
                        FileNameWithoutExtension = String.Format("{0}", zipName)
                    });

                    XmlOutput xo = new XmlOutput()
                                   .XmlDeclaration()
                                   .Node("StaticResource").Attribute("xmlns", "http://soap.sforce.com/2006/04/metadata").Within()
                                   .Node("cacheControl").InnerText("Public")
                                   .Node("contentType").InnerText("application/zip").EndWithin();

                    members.Add(new StaticResourceDeployableItem
                    {
                        FileBody = System.Text.Encoding.Default.GetBytes(xo.GetOuterXml()),
                        FileName = String.Format("{0}\\{1}.resource-meta.xml", directory, zipName),
                        FileNameWithoutExtension = String.Format("{0}.resource-meta.xml", zipName),
                        AddToPackage             = false
                    });
                }
            }

            PackageEntity pe = new PackageEntity
            {
                Types = new[]
                {
                    new PackageTypeEntity
                    {
                        Members = members.Where(w => w.AddToPackage).Select(s => s.FileNameWithoutExtension).ToArray(),
                        Name    = "StaticResource"
                    }
                },
                Version = "29.0"
            };

            var zipFile = UnzipPackageFilesHelper.ZipObjectsForDeploy(members, pe.GetXml().OuterXml);

            SalesforceFileProcessing.SaveByteArray(String.Format("{0}\\package_{1}.zip", folder, Guid.NewGuid()), zipFile);

            var id = Context.MetadataServiceAdapter.Deploy(zipFile, options).id;

            return(id);
        }
예제 #17
0
        public override void xslTransformer(XPathNavigator xNav, XsltArgumentList xArgs)
        {
            XsltSettings   settings = new XsltSettings(true, true);
            XmlUrlResolver r        = new XmlUrlResolver();

            r.Credentials = System.Net.CredentialCache.DefaultCredentials;

            MvpXslTransform xslObj = new MvpXslTransform();

            xslObj.SupportCharacterMaps = false;            // causes error reading
            var readersettings = new XmlReaderSettings();

            using (XmlReader xslreader = XmlReader.Create(classXSLObjectSource, readersettings))
            {
                xslObj.Load(xslreader, settings, r);
                XmlInput  xm = new XmlInput(xNav);
                XmlOutput xo;

                try
                {
                    if (!(clsFileIO == null))
                    {
                        xo = new XmlOutput(clsFileIO);
                        xslObj.Transform(xm, xArgs, xo);
                        clsTEXTResult = "FILE SAVED";
                    }
                    else if (!(clsHTTPResponse == null))
                    {
                        xo = new XmlOutput(clsHTTPResponse.OutputStream);
                        xslObj.Transform(xm, xArgs, xo);
                        clsTEXTResult = "OUTPUT STREAMED TO HTTP RESPONSE";
                    }
                    else if (!(clsXMLObjectReturn == null))
                    {
                        using (StringWriter sWrit = new StringWriter())
                        {
                            xo = new XmlOutput(sWrit);

                            xslObj.Transform(xm, xArgs, xo);
                            clsXMLObjectReturn.LoadXml(sWrit.ToString());
                        }
                    }
                    else
                    {
                        using (StringWriter sWrit = new StringWriter())
                        {
                            xo = new XmlOutput(sWrit);

                            xslObj.Transform(xm, xArgs, xo);

                            // default - results to text
                            clsTEXTResult = sWrit.ToString();
                        }
                    }
                }
                catch (Exception unhandled)
                {
                    throw unhandled;
                }
                finally
                {
                    xslObj = null;
                    xm     = null;
                    xo     = null;
                }
            }
        }
예제 #18
0
        public bool ModifyPerson(Person person)
        {
            var db = new RSMDataModelDataContext();

            string personDispCredentials;
            string jobDisplayDescription;
            string jobDescription;

            try
            {
                personDispCredentials = person.DisplayCredentials;

                if (personDispCredentials == " ")
                {
                    personDispCredentials = string.Empty;
                }
            }
            catch (Exception)
            {
                personDispCredentials = string.Empty;
            }

            try
            {
                jobDescription = person.Job.JobDescription;
            }
            catch (Exception)
            {
                jobDescription = string.Empty;
            }

            try
            {
                jobDisplayDescription = person.Job.DisplayDescription;
                if (jobDisplayDescription.Length < 1)
                {
                    jobDisplayDescription = jobDescription;
                }
            }
            catch (Exception)
            {
                jobDisplayDescription = jobDescription;
            }

            var jobDescr = personDispCredentials.Length > 0
                                                ? string.Format("{0}, {1}", jobDisplayDescription, personDispCredentials)
                                                : jobDisplayDescription;

            XmlOutput xo;

            try
            {
                xo = new XmlOutput()
                     .XmlDeclaration()
                     .Node("NETBOX-API").Attribute("sessionid", SessionID).Within()
                     .Node("COMMAND").Attribute("name", "ModifyPerson").Attribute("num", "1").Within()
                     .Node("PARAMS").Within()
                     .Node("PERSONID").InnerText(person.PersonID.ToString())
                     .Node("LASTNAME").InnerText(person.LastName)

                     .Node("FIRSTNAME").InnerText(person.NickFirst)
                     .Node("MIDDLENAME").InnerText(person.MiddleName)
                     .Node("CONTACTLOCATION").InnerText(person.Facility)
                     //.Node("DELETED").InnerText((person.Active == true ? "FALSE" : "TRUE"))
                     .Node("DELETED").InnerText("FALSE")
                     .Node("UDF1").InnerText(person.JobCode)
                     .Node("UDF2").InnerText(jobDescr)
                     .Node("UDF3").InnerText(person.DeptID)
                     .Node("UDF4").InnerText(person.DeptDescr)
                     .Node("UDF5").InnerText(person.Facility)
                     .Node("UDF6").InnerText(person.BadgeNumber)
                     .Node("UDF7").InnerText(person.JobDescr)
                     .Node("UDF8").InnerText(personDispCredentials)
                     .Node("UDF9").InnerText(person.EmployeeID)
                     .Node("ACCESSLEVELS").Within();
            }
            catch (Exception)
            {
                throw (new Exception(string.Format("Exception building API XML for {0}, {1}", person.LastName, person.FirstName)));
            }

            try
            {
                var levels     = db.LevelsAssignedToPerson(person.PersonID);
                var levelCount = 0;

                foreach (var l in levels)
                {
                    levelCount++;
                    if (levelCount < MAX_LEVELS_S2_SUPPORTS)
                    {
                        xo.Node("ACCESSLEVEL").InnerText(l.AccessLevelName);
                    }
                }

                if (person.Active == false)
                {
                    xo.Node("ACCESSLEVEL").InnerText("TERMINATED ASSOCIATE");
                }

                //if (levelCount > MAX_LEVELS_S2_SUPPORTS)
                //{
                //    db.Syslog(OwningSystem,
                //              RSMDataModelDataContext.LogSeverity.ERROR,
                //              string.Format("{0}, {1} {2} has too many levels assigned.", person.LastName, person.FirstName, person.MiddleName),
                //              string.Format("The S2 hardware has a limit of {0} access levels per person.  This person has {1}.  You will need to remove some roles or consolidate multiple levels into one on the S2 hardware.", MAX_LEVELS_S2_SUPPORTS, levelCount));

                //    return false;
                //}
            }
            catch (Exception)
            {
                throw (new Exception(string.Format("Exception adding levels for {0}, {1}", person.LastName, person.FirstName)));
            }

            try
            {
                var doc = HttpPost(xo);

                if (CallWasSuccessful(doc))
                {
                    db.Syslog(ExportSystem,
                              Severity.Informational,
                              string.Format("Exported associate \"{0}, {1} {2}\" to S2.", person.LastName, person.FirstName,
                                            person.MiddleName),
                              "");

                    return(true);
                }

                db.Syslog(ExportSystem,
                          Severity.Error,
                          string.Format("FAILED exporting associate \"{0}, {1} {2}\" to S2.", person.LastName, person.FirstName,
                                        person.MiddleName),
                          doc["NETBOX"]["RESPONSE"]["DETAILS"]["ERRMSG"].InnerText);
            }
            catch (Exception)
            {
                throw (new Exception(string.Format("Exception parsing response for {0}, {1}", person.LastName, person.FirstName)));
            }

            return(false);
        }
예제 #19
0
        public bool AddPerson(Person person)
        {
            string personDispCredentials;
            string jobDisplayDescription;
            string jobDescription;

            try
            {
                personDispCredentials = person.DisplayCredentials;

                if (personDispCredentials == " ")
                {
                    personDispCredentials = string.Empty;
                }
            }
            catch (Exception)
            {
                personDispCredentials = string.Empty;
            }

            try
            {
                jobDescription = person.Job.JobDescription;
            }
            catch (Exception)
            {
                jobDescription = string.Empty;
            }

            try
            {
                jobDisplayDescription = person.Job.DisplayDescription;
                if (jobDisplayDescription.Length < 1)
                {
                    jobDisplayDescription = jobDescription;
                }
            }
            catch (Exception)
            {
                jobDisplayDescription = jobDescription;
            }

            var jobDescr = personDispCredentials.Length > 0
                                                ? string.Format("{0}, {1}", jobDisplayDescription, personDispCredentials)
                                                : jobDisplayDescription;

            var       db = new RSMDataModelDataContext();
            XmlOutput xo;

            try
            {
                xo = new XmlOutput()
                     .XmlDeclaration()
                     .Node("NETBOX-API").Attribute("sessionid", SessionID).Within()
                     .Node("COMMAND").Attribute("name", "AddPerson").Attribute("num", "1").Within()
                     .Node("PARAMS").Within()
                     .Node("PERSONID").InnerText(person.PersonID.ToString())
                     .Node("LASTNAME").InnerText(person.LastName)
                     .Node("FIRSTNAME").InnerText(person.NickFirst)
                     .Node("MIDDLENAME").InnerText(person.MiddleName)
                     .Node("CONTACTLOCATION").InnerText(person.Facility)
                     .Node("UDF1").InnerText(person.JobCode)
                     .Node("UDF2").InnerText(jobDescr)
                     .Node("UDF3").InnerText(person.DeptID)
                     .Node("UDF4").InnerText(person.DeptDescr)
                     .Node("UDF5").InnerText(person.Facility)
                     .Node("UDF6").InnerText(person.BadgeNumber)
                     .Node("UDF7").InnerText(person.JobDescr)
                     .Node("UDF8").InnerText(personDispCredentials)
                     .Node("UDF9").InnerText(person.EmployeeID)
                     .Node("ACCESSLEVELS").Within();
            }
            catch (Exception)
            {
                throw (new Exception(string.Format("Exception building API XML for {0}, {1}", person.LastName, person.FirstName)));
            }

            try
            {
                // TODO Deal with no access levels
                var levels = db.LevelsAssignedToPerson(person.PersonID);
                var lcount = 0;

                foreach (var l in levels)
                {
                    lcount++;
                    if (lcount < MAX_LEVELS_S2_SUPPORTS)
                    {
                        xo.Node("ACCESSLEVEL").InnerText(l.AccessLevelName);
                    }
                }
            }
            catch (Exception)
            {
                throw (new Exception(string.Format("Exception adding levels for {0}, {1}", person.LastName, person.FirstName)));
            }

            XmlDocument doc;

            try
            {
                doc = HttpPost(xo);

                if (CallWasSuccessful(doc))
                {
                    db.Syslog(ExportSystem,
                              Severity.Informational,
                              string.Format("Exported associate \"{0}, {1} {2}\" to S2.", person.LastName, person.FirstName,
                                            person.MiddleName),
                              "");

                    XmlNode details = doc["NETBOX"]["RESPONSE"]["DETAILS"];
                    return(true);
                }
            }
            catch (Exception)
            {
                throw (new Exception(string.Format("Exception checking success for {0}, {1}", person.LastName, person.FirstName)));
            }

            try
            {
                db.Syslog(ExportSystem,
                          Severity.Error,
                          string.Format("FAILED exporting associate \"{0}, {1} {2}\" to S2.", person.LastName, person.FirstName,
                                        person.MiddleName),
                          doc["NETBOX"]["RESPONSE"]["DETAILS"]["ERRMSG"].InnerText);
            }
            catch (Exception)
            {
                throw (new Exception(string.Format("Exception logging error for {0}, {1}\n'{2}'", person.LastName, person.FirstName,
                                                   doc.InnerXml)));
            }
            return(false);
        }
예제 #20
0
파일: ecma2wiki.cs 프로젝트: raj581/Marvin
 private void ProcessAsIs(XmlElement elem)
 {
     Output.Flush();
     Output.WriteNodeTo(elem);
     XmlOutput.Flush();
 }
예제 #21
0
        public void ShouldCreateShopRootElement()
        {
            var formatter = new ShopFormatter(new ShopBuilder(new Uri("http://localhost")).Build());
            var xml = new XmlOutput(formatter.CreateXml());

            Assert.AreEqual(1, xml.GetNodeCount("r:shop"));
        }
예제 #22
0
 /// <summary>
 /// Actual transformation and error handling.
 /// </summary>
 private void TransformImpl(XmlReader srcReader, MvpXslTransform xslt, XmlResolver resolver, XmlOutput results)
 {
     xslt.MultiOutput = options.MultiOutput;
     try
     {
         xslt.Transform(new XmlInput(srcReader, resolver), options.XslArgList, results);
     }
     catch (XmlException xe)
     {
         string uri = options.LoadSourceFromStdin ? NXsltStrings.FromStdin : xe.SourceUri;
         throw new NXsltException(NXsltStrings.ErrorParsingDoc, uri, Reporter.GetFullMessage(xe));
     }
     catch (XmlSchemaValidationException ve)
     {
         string uri = options.LoadSourceFromStdin ? NXsltStrings.FromStdin : srcReader.BaseURI;
         throw new NXsltException(NXsltStrings.ErrorParsingDoc, uri, Reporter.GetFullMessage(ve));
     }
     catch (Exception e)
     {
         throw new NXsltException(NXsltStrings.ErrorTransform, Reporter.GetFullMessage(e));
     }
 }
예제 #23
0
        public void ShouldCreateLinksAsChildrenOfShopElement()
        {
            var shop = new ShopBuilder(new Uri("http://localhost/"))
                .AddLink(new Link(new Uri("/quotes", UriKind.Relative), RestbucksMediaType.Value, LinkRelations.Rfq, LinkRelations.Prefetch))
                .AddLink(new Link(new Uri("/order-forms/1234", UriKind.Relative), "application/xml", LinkRelations.OrderForm))
                .Build();

            var xml = new XmlOutput(new ShopFormatter(shop).CreateXml());

            Assert.AreEqual(2, xml.GetNodeCount("r:shop/r:link"));

            Assert.AreEqual("rb:rfq prefetch", xml.GetNodeValue("r:shop/r:link[1]/@rel"));
            Assert.AreEqual("/quotes", xml.GetNodeValue("r:shop/r:link[1]/@href"));
            Assert.AreEqual(RestbucksMediaType.Value, xml.GetNodeValue("r:shop/r:link[1]/@type"));

            Assert.AreEqual("rb:order-form", xml.GetNodeValue("r:shop/r:link[2]/@rel"));
            Assert.AreEqual("application/xml", xml.GetNodeValue("r:shop/r:link[2]/@type"));
            Assert.AreEqual("/order-forms/1234", xml.GetNodeValue("r:shop/r:link[2]/@href"));
        }
예제 #24
0
        public void ShouldAddXmlBaseAttributeToRootElement()
        {
            var formatter = new ShopFormatter(new ShopBuilder(new Uri("http://restbucks.com:8080/shop")).Build());
            var xml = new XmlOutput(formatter.CreateXml());

            Assert.AreEqual("http://restbucks.com:8080/shop", xml.GetNodeValue("r:shop/@xml:base"));
        }
예제 #25
0
        /// <summary>
        /// Command line exit Code Summary:
        /// 0 – Application completed its task with no errors
        /// 1 – Configuration.xml error
        /// 2 – Missing plugin dll
        /// 3 - Missing refmapper xml
        /// 4 - Datasource directory error
        /// 5 - XML output directory error
        /// 6 - Data Transfer failed
        /// 7 - Log directory error
        /// 8 - Failed to move sent file to the "completed" subdirectory
        /// 9 - No data to send. There was no valid data to send, double check source files.
        /// </summary>

        public static void Main(string[] args)
        {
            // path of where app is running from
            _path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

            // init _conf and check files
            if (CheckFiles(_path))
            {
                // log to catch errors
                Log log = new Log(_conf.LogDirectory);

                // load plugin
                _plugin = PluginLoader.LoadExtractor("plugins\\" + _conf.Plugin);

                // DataTable to store all the extracted data from files
                DataTable results = new DataTable();

                string[] files = System.IO.Directory.GetFiles(_conf.DataSourceDirectory);
                // scans folder for file
                foreach (string file in files)
                {
                    // extract data
                    DataTable dt = _plugin.GetData(_conf, file);

                    // valid datatable of all valid rows
                    DataTable validDt = dt.Clone();

                    // validate the data
                    foreach (DataRow dr in dt.Rows)
                    {
                        Validator validator = new Validator();
                        bool      valid     = true;

                        if (!validator.ValidateDataRow(dr))
                        {
                            valid = false;
                        }

                        if (!_plugin.Validate(dr, _path + "\\plugins\\" + _conf.RefMapper))
                        {
                            valid = false;
                        }

                        // if valid import to validDt
                        if (valid)
                        {
                            validDt.ImportRow(dr);
                        }
                        else
                        {
                            log.write("Error validating row in " + file + ": ");
                            // print datarow contents to log file
                            foreach (DataColumn dc in dr.Table.Columns)
                            {
                                log.write(dc.ColumnName + " : " + dr[dc].ToString());
                            }
                        }
                    }

                    // merged data to Result
                    results.Merge(validDt);
                }

                // timestamp for use in the xml
                DateTime date      = DateTime.Now;
                string   timestamp = String.Format("{0:yyyyMMddHHmmss}", date);

                // if results table is empty then don't generate an empty xml
                if (results.Rows.Count != 0)
                {
                    // generate xml
                    XmlOutput output      = new XmlOutput(null);
                    string    xmlFileName = timestamp + ".xml";
                    // need to parse an emtpy genelist
                    IList <SiteConf.Gene.Object> geneList = new List <SiteConf.Gene.Object>();
                    output.Generate("", _conf.XmlOutputDirectory + "\\" + xmlFileName, results, null, null, _conf.OrgHashCode, geneList);

                    // call VariantExporterCmdLn to send data
                    if (SendData())
                    {
                        // check if completed directory exist
                        if (!System.IO.Directory.Exists(_conf.DataSourceDirectory + "\\completed"))
                        {
                            // create "completed" sub directory inside the xmlOutputDirectory
                            System.IO.Directory.CreateDirectory(_conf.DataSourceDirectory + "\\completed");
                        }

                        // if send successful move files to completed sub directory
                        foreach (string file in files)
                        {
                            // rename file by appending  the date to the end of file
                            // from this "file.tsv" to this "file_20140716143423.tsv"
                            string renamedFile = System.IO.Path.GetFileNameWithoutExtension(file) + "(" +
                                                 DateTime.Now.ToString("yyyyMMddHHmmss") + ")" + System.IO.Path.GetExtension(file);

                            try
                            {
                                System.IO.File.Move(file, _conf.DataSourceDirectory + "\\completed\\" + renamedFile);
                                log.write("Data from file: " + file + " sent.");
                            }
                            catch
                            {
                                log.write("Data from file: " + file + " was sent, but due to an error the file could not be moved to the completed sub directory.");
                            }
                        }
                    }
                }
                else
                {
                    log.write("No valid data to send. Check source that all mandatory fields are provided and correct.");
                    System.Environment.ExitCode = 9;
                }
            }
        }
예제 #26
0
 public void ShouldNotAddItemsElementIfThereAreNoItemsInShop()
 {
     var shop = new ShopBuilder(new Uri("http://localhost")).Build();
     var xml = new XmlOutput(new ShopFormatter(shop).CreateXml());
     Assert.IsNull(xml.GetNode("r:shop/r:items"));
 }
예제 #27
0
        public void ShouldNotAddXmlBaseAttributeToRootElementIfBaseUriIsNull()
        {
            var formatter = new ShopFormatter(new ShopBuilder(null).Build());
            var xml = new XmlOutput(formatter.CreateXml());

            Assert.IsNull(xml.GetNode("r:shop/@xml:base"));
        }