public void Execute(ClientContext ctx, string listTitle, XElement schema, Action<Field> setAdditionalProperties = null)
        {
            var displayName = schema.Attribute("DisplayName").Value;
            Logger.Verbose($"Started executing {nameof(CreateColumnOnList)} for column '{displayName}' on list '{listTitle}'");

            var list = ctx.Web.Lists.GetByTitle(listTitle);
            var fields = list.Fields;
            ctx.Load(fields);
            ctx.ExecuteQuery();

            // if using internal names in code, remember to encode those before querying, e.g., 
            // space character becomes "_x0020_" as described here:
            // http://www.n8d.at/blog/encode-and-decode-field-names-from-display-name-to-internal-name/
            // We don't use the internal name here because it's limited to 32 chacters. This means
            // "Secondary site abcde" is the longest possible internal name when taken into account
            // the "_x0020_" character. Using a longer name will truncate the internal name to 32
            // characters. Thus querying on the complete, not truncated name, will always return no
            // results which causes the field get created repetedly.
            var field = fields.SingleOrDefault(f => f.Title == displayName);
            if (field != null)
            {
                Logger.Warning($"Column '{displayName}' already on list {listTitle}");
                return;
            }

            var newField = list.Fields.AddFieldAsXml(schema.ToString(), true, AddFieldOptions.DefaultValue);
            ctx.Load(newField);
            ctx.ExecuteQuery();

            if (setAdditionalProperties != null)
            {
                setAdditionalProperties(newField);
                newField.Update();
            }
        }
        protected override XElement Validate(XElement item)
        {
            // Validate with XSD
            XElement xsdErrors = this.ValidateXSD(item, HttpContext.Current.Server.MapPath(@"~\Xslt\Senior\Senior.xsd"));
            if (xsdErrors != null && xsdErrors.Elements("Error").Count() > 0)
            {
                return xsdErrors;
            }

            // Validate with Stored Proc
            string result = string.Empty;
            using (Persistence oDB = new Persistence())
            {
                Persistence.ParameterCollection parameters = new Persistence.ParameterCollection();
                parameters.Add("InputXml");
                parameters[0].Value = item.ToString();
                oDB.Execute("Masters_ConnectionString", "ValidateSeniorData", parameters, out result);
            }

            if (!string.IsNullOrEmpty(result))
            {
                XElement spErrors = XElement.Parse(result);
                spErrors.Elements("Error").Where(e => string.IsNullOrEmpty(e.Value)).Remove();

                if (spErrors.Elements("Error").Count() > 0)
                {
                    return spErrors;
                }
            }

            // SUCCESS!
            return null;

        }
Ejemplo n.º 3
0
        public void GetJohnDeerePartInfoAndSubmit(XElement SKUParts)
        {
            string info = "";
            bool IsFailed = false;
            try
            {
                info = GetJohnDeerePartInfo(SKUParts);
                //var fileBytes = Encoding.Default.GetBytes(info);
                //string acsNamespace = HartvilleToolConfigManager.GetSetting("JohnDeere.Biztalk.acsNamespace");
                //string issuerName = HartvilleToolConfigManager.GetSetting("JohnDeere.Biztalk.issuerName");
                //string issuerKey = HartvilleToolConfigManager.GetSetting("JohnDeere.Biztalk.issuerKey");
                //string runtimeAddress = HartvilleToolConfigManager.GetSetting("JohnDeere.Biztalk.runtimeAddress");
                //string contentType = "application/xml";
                //// Trace.TraceInformation("Prepare for sending to Biztalk");
                //MessageSender.SendMessage(acsNamespace,
                //    issuerName, issuerKey, runtimeAddress,
                //    fileBytes, contentType);
                InsertResultIntoSQL(info);

            }
            catch(Exception ex) {
                IsFailed = true;
                HartvilleToolConfigManager.NotifyEmailError("Error  GetJohnDeerePartInfo raw-WCF" + ex.Message, SKUParts.ToString() + Environment.NewLine +  info);
            }

            LogRequestIntoDatabase("GetJohnDeerePartInfo", SKUParts.ToString(), info, IsFailed);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// RSS version 1.0
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private RssSchema ParseRDFItem(XElement item)
        {
            var rssItem = ParseItem(item);

            rssItem.PublishDate = item.GetSafeElementDate("date", NsRdfElementsNamespaceUri);

            string image = item.GetSafeElementString("image");
            if (string.IsNullOrEmpty(image))
            {
                image = item.GetImage();
            }
            if (string.IsNullOrEmpty(image) && item.ToString().Contains("media:thumbnail"))
            {
                XNamespace ns = "http://search.yahoo.com/mrss/";
                var element = item.Elements(ns + "thumbnail").Last();
                image = element.Attribute("url").Value;
            }
            if (string.IsNullOrEmpty(image) && item.ToString().Contains("thumbnail"))
            {
                image = item.GetSafeElementString("thumbnail");
            }

            rssItem.ImageUrl = image;

            return rssItem;
        }
		private static void PrintXml(XElement xml){
			Console.WriteLine(xml.ToString());
			Console.WriteLine();
			Console.WriteLine("---------------------------");
			Console.WriteLine();
			Console.WriteLine(xml.ToString().Replace("\"", "\"\""));
		}
 public Scientrace.Vector formulaVector(Scientrace.Vector aVector, XElement xformula)
 {
     string f_x = "x";
     string f_y = "y";
     string f_z = "z";
     if (xformula.Attribute("xyz") != null) {
     try {
         string xyz = xformula.Attribute("xyz").Value;
         char[] delimiterChars = { ';', '\t' };
         string[] elements = xyz.Split(delimiterChars);
         if (elements.Length !=3) {
             throw new XMLException("Element "+xformula.ToString()+" has \""+elements.Length+ "\" != 3 valid vector elements. ");
             }
         f_x=elements[0];
         f_y=elements[1];
         f_z=elements[2];
         } catch { throw new XMLException("Formula "+xformula.ToString()+" does not have proper parameters for {xyz} attribute (can't parse {"+xformula.Attribute("xyz").Value.ToString()+"}. Perhaps incorrect use of PreProcess variables or decimal separators?)."); }
     } // attribute "xyz"
     f_x = this.getXStringByName(xformula, "x", f_x);
     f_y = this.getXStringByName(xformula, "y", f_y);
     f_z = this.getXStringByName(xformula, "z", f_z);
     Dictionary<string, object> replace_vectors = new Dictionary<string, object>(){{"x", (decimal)aVector.x}, {"y", (decimal)aVector.y}, {"z", (decimal)aVector.z} };
     return new Scientrace.Vector(
     Scientrace.MathStrings.solveString(f_x, replace_vectors),
     Scientrace.MathStrings.solveString(f_y, replace_vectors),
     Scientrace.MathStrings.solveString(f_z, replace_vectors)
     );
 }
Ejemplo n.º 7
0
        public void ConstructorShould_Load_Project_File_Content_Into_Member()
        {
            XElement fileContentAsXml = new XElement("project", new XElement("project_name", PROJECT_NAME));

            File.WriteAllText(projectFilePath, fileContentAsXml.ToString());

            ProjectFileReader pfr = new ProjectFileReader(projectFilePath);

            Assert.AreEqual(fileContentAsXml.ToString(), pfr.ProjectFileContent);
        }
 private void Trans(XElement serializedExpression)
 {
     serializedExpression.Save("beforeTransit.xml");
     Console.WriteLine("beforeTransit:");
     Console.WriteLine(serializedExpression.ToString());
     Transit(serializedExpression);
     Console.WriteLine("afterTransit:");
     Console.WriteLine(serializedExpression.ToString());
     serializedExpression.Save("afterTransit.xml");
 }
Ejemplo n.º 9
0
        public long UpdatePaymentRequest(XElement xml)
        {
            if (logger.IsDebugEnabled)
            {
                logger.Debug(string.Format("UpdatePaymentRequest {0}", xml));
            }

            long batchControlLogId = 0;

            using (SqlConnection conn = new SqlConnection(this.GeniusXConnectionString))
            {
                conn.Open();

                // insert record in BatchControllog (Status = In Progress)
                batchControlLogId = this.AddBatchEntry(BatchControlConstant.BatchType.Custom, "Description", xml.ToString(), conn);

                try
                {
                    // update Paymenet request
                    using (SqlCommand cmd = new SqlCommand("UpdatePaymentRequestAXA", conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@PaymentRequests", SqlDbType.Xml).Value = xml.ToString();                        
                        cmd.ExecuteScalar();
                    }

                    // update BatchControlLog (Status = completed, CompletionStatus = Clear)
                    this.UpdateBatchStatus(batchControlLogId, BatchControlConstant.BatchStatus.Completed, BatchControlConstant.CompletionStatus.Clear, conn);
                }
                catch (Exception ex)
                {
                    // insert record into BatchErrorLogHeader                    
                    // add error detail into BatchErrorLogDetail
                    this.AddErrorLog(batchControlLogId, BatchControlConstant.MessageLevel.Error, ex.Message, string.Empty, conn);

                    // update BatchControlLog (Status = completed, CompletionStatus= Errors)
                    this.UpdateBatchStatus(batchControlLogId, BatchControlConstant.BatchStatus.Completed, BatchControlConstant.CompletionStatus.Errors, conn);                    

                    logger.Error(string.Format("UpdatePaymentRequest - {0}", ex.Message));

                    return batchControlLogId;
                }
            }

            if (logger.IsDebugEnabled)
            {
                logger.Debug(string.Format("UpdatePaymentRequest {0} => returns: {1}", xml,batchControlLogId));
            }

            return 0;
        }
Ejemplo n.º 10
0
        public void TestAssignValue()
        {
            var address = new XElement("address",
                                       new XElement("street", "1st street"),
                                       new XElement("city", "2nd city"));
            var street = address.Element("street");
            street.Value = "88";

            Assert.AreEqual("<address><street>88</street><city>2nd city</city></address>", address.ToString(SaveOptions.DisableFormatting));

            // -------------- set value on parent will replace all its children elements
            address.Value = "replaced";
            Assert.AreEqual("<address>replaced</address>", address.ToString(SaveOptions.DisableFormatting));
        }
Ejemplo n.º 11
0
        public static string GetFileIdsAsXml(List <string> ids)
        {
            try
            {
                var output = new StringBuilder();

                foreach (string id in ids)
                {
                    var element = new System.Xml.Linq.XElement("Id", id);

                    if (output.Length > 0)
                    {
                        output.Append("  ");
                    }

                    output.AppendLine(element.ToString());
                }

                return(output.ToString());
            }
            catch (Exception exception)
            {
                Log.Error(exception);

                return(null);
            }
        }
Ejemplo n.º 12
0
        public void ProcessRequest(HttpContext context)
        {
            if (!string.IsNullOrEmpty(context.Request["index"]) && !string.IsNullOrEmpty(context.Request["sceneid"]))
            {
                int page = Convert.ToInt32(context.Request["index"]);
                var query = from w in DbCenter.QueryDb.GameUserextendwishes
                            select w;
                query = query.Where(wh => wh.SceneId == context.Request["sceneid"].ToString());
                IList<GameUserextendwishes> list = query.OrderByDescending(c=>c.Indexs).Skip(page - 1).Take(1).ToList();
                XElement item;
                foreach (GameUserextendwishes w in list)
                {
                    SysUsers user = DbCenter.QueryDb.SysUsers.Single(u => u.ID == w.ExtendUserId);
                    item = new XElement("item", new XAttribute("id", w.Id.ToString()),
                        new XAttribute("index", w.Indexs.ToString()),
                         new XAttribute("userId", w.ExtendUserId.ToString()),
                          new XAttribute("content", w.Content.ToString()),
                           new XAttribute("nickName", user.PetName),
                            new XAttribute("wishType", w.Wishtype.ToString()),
                              new XAttribute("time", w.Date.ToShortDateString()),
                               new XAttribute("stone", w.SceneId.ToString()),
                                new XAttribute("viewNums", w.ViewNum.ToString()),
                                 new XAttribute("isAnonymity", w.IsNim.ToString())

                        );
                    context.Response.ContentType = "text/plain";
                    context.Response.Write(item.ToString());

                }

            }
        }
        private void PerformCustomAction(XFormData data, string subject, string to, string from)
        {
            var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"));
            XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

            // This part uses the xform data to create a custom email with the data as an attachment
            var import = new XElement("Import", new XAttribute(XNamespace.Xmlns + "xsi", xsi));
            import.Add(new XElement("ElementInForm", data.GetValue("elementInForm")));
            doc.Add(import);

            var mailMessage = new MailMessage
            {
                BodyEncoding = Encoding.UTF8,
                SubjectEncoding = Encoding.UTF8,
                IsBodyHtml = false,
                Body = import.ToString(),
                Subject = subject,
            };

            mailMessage.From = new MailAddress(from);
            mailMessage.To.Add(to);

            var customXml = new MemoryStream();
            doc.Save(customXml);
            customXml.Position = 0;

            Attachment xml = new Attachment(customXml, "example.xml", MediaTypeNames.Text.Xml);
            mailMessage.Attachments.Add(xml);
            new SmtpClient().Send(mailMessage);
        }
Ejemplo n.º 14
0
		public override void PopulateTree (Tree tree)
		{
			var storage = tree.HelpSource.Storage;
			var nsSummaries = new Dictionary<string, XElement> ();
			int resID = 0;

			foreach (var asm in directories) {
				var indexFilePath = Path.Combine (asm, "index.xml");
				if (!File.Exists (indexFilePath)) {
					Console.Error.WriteLine ("Warning: couldn't process directory `{0}' as it has no index.xml file", asm);
					continue;
				}

				EcmaDoc.PopulateTreeFromIndexFile (indexFilePath, EcmaHelpSource.EcmaPrefix, tree, storage, nsSummaries, _ => resID++.ToString ());
			}

			foreach (var summary in nsSummaries)
				storage.Store ("xml.summary." + summary.Key, summary.Value.ToString ());

			var masterSummary = new XElement ("elements",
			                                  directories
			                                  .SelectMany (d => Directory.EnumerateFiles (d, "ns-*.xml"))
			                                  .Select (ExtractNamespaceSummary));
			storage.Store ("mastersummary.xml", masterSummary.ToString ());
		}
Ejemplo n.º 15
0
        public void Compare(XElement expected, XElement actual)
        {
            this.UpdateSchemasForUseStrongSpatialTypes(expected);
            this.UpdateSchemasForUseStrongSpatialTypes(actual);

            this.UpdateSchemaAliasToSchemaNamepsace(expected);
            this.UpdateSchemaAliasToSchemaNamepsace(actual);

            this.UpdatePrimitiveTypeNameForEdmFullName(expected);
            this.UpdatePrimitiveTypeNameForEdmFullName(actual);

            this.CompensateDefaultFacets(expected);
            this.CompensateDefaultFacets(actual);

            this.CompensateSpatialTypeSrid(expected);
            this.CompensateSpatialTypeSrid(actual);

            XElement sortedExpected = this.csdlSorter.SortCsdl(expected);
            XElement sortedActual = this.csdlSorter.SortCsdl(actual);

            Console.WriteLine("Sorted Expected: " + expected.ToString());
            Console.WriteLine("Sorted Actual: " + sortedActual.ToString());

            Assert.AreEqual(sortedExpected.ToString(), sortedActual.ToString(), "Csdl not equal!");
        }
 public void GetObjectData_EmptyXElement_ReturnsSameAsToStringCalledWithDisableFormatting()
 {
     XElement element = new XElement("name");
     String data = GetDataValueFromGetObjectData(element);
     String toStringResult = element.ToString(SaveOptions.DisableFormatting);
     Assert.AreEqual(toStringResult, data);
 }
        public void GenerateXml_WithIntroducedInterfaces()
        {
            var interfaceIdentifierGenerator = new IdentifierGenerator<Type>();
              var mixinConfiguration = MixinConfiguration.BuildNew()
              .ForClass<TargetClass2>().AddMixin<Mixin3>()
              .BuildConfiguration();

              var type1 = new InvolvedType (typeof (TargetClass2));
              type1.ClassContext = new ReflectedObject (mixinConfiguration.ClassContexts.First());

              // TargetClass2 does not implement any interface
              // Mixin3 introduces interface IDisposable
              var interfaceIntroductions = GetInterfaceIntroductions (type1, typeof (Mixin3), mixinConfiguration);
              var reportGenerator = new InterfaceIntroductionReportGenerator (interfaceIntroductions, interfaceIdentifierGenerator);

              var output = reportGenerator.GenerateXml();

              var expectedOutput = new XElement (
              "InterfaceIntroductions",
              new XElement (
              "IntroducedInterface",
              new XAttribute ("ref", "0")
              ));

              Assert.That (output.ToString(), Is.EqualTo (expectedOutput.ToString()));
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            // 呼叫新增畫面
            Forms.AddABCardSubjectNameForm asnf = new AddABCardSubjectNameForm(_ABCardTemplateTransfer.GetAllSubjectNameList());

            if (asnf.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
            {
                string SubjectName = asnf.GetAddSubjectName();
                if (!string.IsNullOrEmpty(SubjectName))
                {
                    XElement elm = new XElement("Subject");
                    elm.SetAttributeValue("label", SubjectName);
                    DAO.UDT_ABCardTemplateDefinitionDef abtdf = new DAO.UDT_ABCardTemplateDefinitionDef();
                    abtdf.SubjectName = SubjectName;
                    abtdf.Content = elm.ToString();

                    // 呼叫UDT 新增資料
                    List<DAO.UDT_ABCardTemplateDefinitionDef> addList = new List<DAO.UDT_ABCardTemplateDefinitionDef>();
                    addList.Add(abtdf);
                    DAO.UDTTransfer.InsertABCardTemplate(addList);

                    // 畫面重新載入
                    _BGRun();
                }
            }
        }
Ejemplo n.º 19
0
 internal static void LogError(Guid errorId, Exception ex, Dictionary <string, string> dataObject)
 {
     try
     {
         using (Models.ApplicationDbContext ctx = new ApplicationDbContext())
         {
             ErrorLog errorLogInfo = new ErrorLog();
             errorLogInfo.ErrorId = errorId;
             errorLogInfo.Message = ex.ToString();
             XElement objectData = new System.Xml.Linq.XElement("ObjectData");
             foreach (var singleItem in dataObject)
             {
                 XElement propertyInfoElement = new XElement("PropertyInfo");
                 propertyInfoElement.SetAttributeValue("Name", singleItem.Key);
                 propertyInfoElement.SetAttributeValue("Value", singleItem.Value);
                 objectData.Add(propertyInfoElement);
             }
             errorLogInfo.Data = objectData.ToString();
             ctx.ErrorLogs.Add(errorLogInfo);
             ctx.SaveChanges();
         }
     }
     catch (Exception)
     {
         //do nothing
     }
 }
Ejemplo n.º 20
0
        private XE BuildSoapXml(XE /* request */ in0)
        {
            // Canonicalize XML by removing redundant whitespace and newlines.
            // Canonicalizing by way of XElement.ToString() has the effect of
            // removing trailing "<?xml version="1.0" encoding="UTF-8"?>. We
            // could add it back in, but it doesn't make a different to the
            // Oracle backend.
            var in0Canonicalized = in0.ToString(SaveOptions.DisableFormatting);

            // Because we're storing the request XML element inside the Soap XML
            // element, we must encode the request XML. .NET supports using HTML
            // encoding only when XML encoding, but because XML and HTML differs
            // slightly (HTML doesn't encode newlines whereas in XML they must
            // be encoded as ';&#xD;'), we disabled formatting during request
            // XML canonicalization, causing the XML to not include newlines.
            // Otherwise, when the Oracle backend calculates CRC32 of the
            // request XML, it'll not match and respond with
            //
            //   <ResponseCode>D</ResponseCode> <DisplayMessage>Request failed
            //   integrity check</DisplayMessage>
            var in0Encoded = WebUtility.HtmlEncode(in0Canonicalized);
            var in3        = Crc32.ToPaddedCrc32String(Crc32.Compute(Encoding.UTF8.GetBytes(in0Canonicalized)));

            return(XE.Parse(
                       string.Format(
                           SoapRequestBodyTemplate,
                           in0Encoded,
                           /* in1 */ _options.LogonName,
                           /* in2 */ _options.Password,
                           /* CRC32 of in0 */ in3)));
        }
Ejemplo n.º 21
0
        public void ProcessRequest(HttpContext context)
        {                                                                                                                                                                                                                                                                                                          
            string user = context.Request.QueryString["user"];
            string pass = context.Request.QueryString["pass"];

            SysUsers player = DbCenter.QueryDb.SysUsers.SingleOrDefault(c => c.UserName == user && c.PassWord == pass);
            if (player != null)
            {
                var list = from g in DbCenter.QueryDb.GameUsersGoods
                           join m in DbCenter.QueryDb.GameSysgoodsmodels on g.GoodsModelId equals m.ID
                           where g.UserId == player.ID && g.State == 0
                           select new Goods { Good = g, Model = m };

                XElement node = new XElement("list");
                foreach (var t in list)
                {
                    node.Add(FlashUtils.CreateGoods(t));
                }

                context.Response.ContentType = "text/plain";
                context.Response.Write(node.ToString(false));
            }
            else
            {
                context.Response.Write(string.Format("用户不存在:{0}",user));
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Get the employees from Xero API
        /// </summary>
        /// <param name="orgId">organization id for Initalization</param>
        public void SyncEmployees(string costomerKey, int orgId)
        {
            Initialize(costomerKey, orgId);
            var employees = repository.Employees.ToList();

            if (employees.Count > 0)
            {
                XElement xmlEmployees = new XElement("EmployeeList",
                   employees.Select(i => new XElement("Items", new XAttribute("EmployeeID", i.EmployeeID), new XAttribute("FirstName", i.FirstName), new XAttribute("LastName", i.LastName), new XAttribute("Status", i.Status), new XAttribute("UpdatedDateUTC", i.UpdatedDateUTC), new XAttribute("ExternalLink", i.ExternalLink))));
                try
                {
                    string connectionString = null;
                    connectionString = System.Configuration.ConfigurationSettings.AppSettings["DbConn"];
                    using (SqlConnection con = new SqlConnection(connectionString))
                    {
                        using (SqlCommand cmd = new SqlCommand("SyncEmployees", con))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Add("@X", SqlDbType.Xml).Value = xmlEmployees.ToString();
                            cmd.Parameters.Add("@OrgId", SqlDbType.Int).Value = orgId;
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                        }
                    }
                }
                catch (Exception ex) { throw ex; }
            }
        }
Ejemplo n.º 23
0
        public override void Execute()
        {
            List<XElement> xList = new List<XElement>();

            for(int i=0; i < QueueState.Count();i++)
            {
                IBuilding b = QueueState.ElementAt(i).Key;
                IBuildingFunction f = BuildingState.Where( x => x.Value == b).FirstOrDefault().Key;
                ITimer t = QueueState.ElementAt(i).Value;

                XElement xEl = new XElement("Queue",
                    new XElement("Building",
                        new XElement("Id", b.Id),
                        new XElement("Time", t.Get()),
                        new XElement("Function",f.Name),
                        new XElement("X",b.Tile.X),
                        new XElement("Z",b.Tile.Z)
                        ));
                xList.Add(xEl);
            }

            XElement New = new XElement("QueueSystem",
               xList.AsEnumerable()
                   );
            Debug.Log(New.ToString());
            GameData.SaveQueueState(New);
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Get the contacts from Xero API
 /// </summary>
 /// <param name="orgId">organization id for Initalization</param>
 public void SyncContacts(string costomerKey, int orgId)
 {
     Initialize(costomerKey,orgId);
     var contacts = repository.Contacts.ToList();
     XElement xmlcontacts = new XElement("ContactList",
         contacts.Select(i => new XElement("Items", new XAttribute("Name", i.Name))));
     try
     {
         string connectionString = null;
         connectionString = System.Configuration.ConfigurationSettings.AppSettings["DbConn"];
         using (SqlConnection con = new SqlConnection(connectionString))
         {
             using (SqlCommand cmd = new SqlCommand("SyncCompany", con))
             {
                 cmd.CommandType = CommandType.StoredProcedure;
                 cmd.Parameters.Add("@X", SqlDbType.Xml).Value = xmlcontacts.ToString();
                 cmd.Parameters.Add("@Org_Id", SqlDbType.Int).Value = orgId;
                 con.Open();
                 cmd.ExecuteNonQuery();
                 con.Close();
             }
         }
     }
     catch (Exception ex) { throw ex; }
 }
        public override string GetSerializedValue()
        {
            var xml = new XElement("preValues");

            //mode
            xml.Add(new XElement("preValue", new XAttribute("name", "Mode"),
                            new XCData(Mode.ToString())));

            //items
            var itemsxml = new XElement("preValue",
                new XAttribute("name", "ListItems"),
                new XAttribute("dataSource", DataSource ?? ""));

            foreach (var i in Items)
            {
                itemsxml.Add(new XElement("item", 
                                new XAttribute("id", i.Id),
                                new XCData(i.Value)));
            }

            xml.Add(itemsxml);

            xml.Add(new XElement("preValue", new XAttribute("name", "IsRequired"),
                        new XCData(IsRequired.ToString())));

            return xml.ToString();
        }
Ejemplo n.º 26
0
        public belEncerramentoMDFe(PesquisaManifestosModel objPesquisa, string cUF, string cMun)
        {
            this.objPesquisa = objPesquisa;
            XNamespace pf = "http://www.portalfiscal.inf.br/mdfe";
            XContainer envCTe = new XElement(pf + "evEncMDFe",
                 new XElement(pf + "descEvento", "Encerramento"),
                 new XElement(pf + "nProt", objPesquisa.protocolo),
                 new XElement(pf + "dtEnc", daoUtil.GetDateServidor().ToString("yyyy-MM-dd")),
                 new XElement(pf + "cUF", cUF),
                 new XElement(pf + "cMun", cMun.Trim()));
            XmlDocument xmlCanc = new XmlDocument();
            xmlCanc.LoadXml(envCTe.ToString());
            string sPath = Pastas.PROTOCOLOS + objPesquisa.protocolo + "evEnc.xml";
            if (File.Exists(sPath))
                File.Delete(sPath);
            xmlCanc.Save(sPath);
            try
            {
                belValidaXml.ValidarXml("http://www.portalfiscal.inf.br/mdfe", Pastas.SCHEMA_MDFe + "\\evEncMDFe_v1.00.xsd", sPath);
            }
            catch (Exception ex)
            {                
                throw ex;
            }

            objEvento = new belEventoMDFe(xmlCanc.DocumentElement, objPesquisa, "110112");

          //  Encerramento();
        }
        public void Submit(Order order, XDocument document)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }

            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            var ordersElement = document.Element("Orders");
            if (ordersElement == null)
            {
                ordersElement = new XElement("Orders");
                document.Add(ordersElement);
            }

            var orderElement = new XElement("Order",
                new XAttribute("OrderType", order.OrderType),
                new XAttribute("Shares", order.Shares),
                new XAttribute("StopLimitPrice", order.StopLimitPrice),
                new XAttribute("TickerSymbol", order.TickerSymbol),
                new XAttribute("TimeInForce", order.TimeInForce),
                new XAttribute("TransactionType", order.TransactionType),
                new XAttribute("Date", DateTime.Now.ToString(CultureInfo.InvariantCulture))
                );
            ordersElement.Add(orderElement);

            string message = String.Format(CultureInfo.CurrentCulture, Resources.LogOrderSubmitted,
                                           orderElement.ToString());
            logger.Log(message, Category.Debug, Priority.Low);
        }
Ejemplo n.º 28
0
        public void ProcessRequest(HttpContext context)
        {
            bool value = false;
            string message = "Fail!";

            XElement result = new XElement("Result");
            try
            {
                int userid = int.Parse(context.Request.Params["ID"]);
                
                using (PlayerBussiness db = new PlayerBussiness())
                {
                    ItemInfo[] items = db.GetUserItem(userid);

                    foreach (ItemInfo item in items)
                    {
                        result.Add(Road.Flash.FlashUtils.CreateGoodsInfo(item));
                    }

                }
                value = true;
                message = "Success!";
            }
            catch (Exception ex)
            {
                log.Error("LoadUserItems", ex);
            }

            result.Add(new XAttribute("value", value));
            result.Add(new XAttribute("message", message));

            context.Response.ContentType = "text/plain";
            context.Response.Write(result.ToString(false));
        }
Ejemplo n.º 29
0
        public void SaveTree(String TreeXml)
        {
            if (String.IsNullOrEmpty(TreeXml))
            {
                //创建一棵空树
                XElement root = new XElement("root");
                TreeXml = root.ToString();
            }

            using (InfocenterEntities context = new InfocenterEntities(EFConnectionString))
            {
               Tree treeObj = context.Trees.FirstOrDefault();
               if (treeObj != null)
               {
                   //更新树
                   treeObj.maintree = Encoding.UTF8.GetBytes(TreeXml);
                   context.SaveChanges();
               }
               else
               {
                   //正常情况下应该不会走到这个分支,但仍然写在这里,逻辑就完整了。
                   treeObj = new Tree();
                   treeObj.maintree = Encoding.UTF8.GetBytes(TreeXml);
                   context.Trees.Add(treeObj);
                   context.SaveChanges();
               }

            }
        }
Ejemplo n.º 30
0
        public static Transaction FromXml(XElement tran)
        {
            if (tran == null)
            {
                return null;
            }
            var ret = new Transaction(
                tran.ToString(),
                tran.GetStringChild("amount"),
                tran.GetStringChild("on_test_gateway"),
                tran.GetStringChild("succeeded"),
                tran.GetStringChild("token"),
                tran.Element("payment_method").GetStringChild("number"),
                tran.Element("response").GetStringChild("avs_code"),
                new TransactionErrors(tran)
                );

            ret.GatewayTransactionId = tran.GetStringChild("gateway_transaction_id");
            ret.CreatedAt = DateTime.Parse(tran.GetStringChild("created_at"));
            ret.PaymentMethodToken = tran.Element("payment_method").GetStringChild("token");

            if (ret.Succeeded == false && ret.Errors.Count == 0)
            {
                if (string.Equals(tran.GetStringChild("state"), "gateway_processing_failed",
                                  StringComparison.InvariantCultureIgnoreCase))
                {

                    ret.Errors = new TransactionErrors("",TransactionErrorType.Unknown);
                }
            }
            return ret;
        }
Ejemplo n.º 31
0
		void Write (XElement element)
		{
			try {
				Writer.WriteLine (element.ToString ());
			} catch {
			}
		}
Ejemplo n.º 32
0
        public void ProcessRequest(HttpContext context)
        {
            string user = context.Request.Params["user"];
            string pass = context.Request.Params["pass"];
            XElement result = new XElement("result");
            if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(pass))
            {
                SysUsers p = DbCenter.QueryDb.SysUsers.First(c => c.UserName == user && c.PassWord == pass);
                if (user != null)
                {
                    context.Response.Cookies.Add(new HttpCookie("id", p.ID.ToString()));
                    result.Add(new XAttribute("value", true));
                }
                else
                {
                    result.Add(new XAttribute("value", false));
                    result.Add(new XAttribute("message", "用户名或者密码错误!"));
                }
            }
            else
            {
                result.Add(new XAttribute("value", false));
                result.Add(new XAttribute("message", "参数个数不正确!"));
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(result.ToString());
        }
Ejemplo n.º 33
0
        public static PaymentMethod FromXml(XElement element)
        {
            if (element == null)
            {
                return null;
            }

            var ret = new PaymentMethod(element.ToString());
            ret.Token = element.GetStringChild("token");
            ret.Number = element.GetStringChild("number");
            ret.StorageState = element.GetStringChild("storage_state");
            ret.FirstName = element.GetStringChild("first_name");
            ret.LastName = element.GetStringChild("last_name");
            ret.CreatedAt = DateTime.Parse(element.GetStringChild("created_at"));

            ret.ExpirationMonth = int.Parse(element.GetStringChild("month"));
            ret.ExpirationYear = int.Parse(element.GetStringChild("year"));
            ret.CardType = element.GetStringChild("card_type");
            ret.Address1 = element.GetStringChild("address1");
            ret.Address2 = element.GetStringChild("address2");
            ret.City = element.GetStringChild("city");
            ret.State = element.GetStringChild("state");
            ret.Zip = element.GetStringChild("zip");
            ret.Country = element.GetStringChild("country");

            return ret;
        }
Ejemplo n.º 34
0
        public void XElementTypeConverterTests()
        {
            PrimitiveTypeConverter converter = new XElementTypeConverter();

            System.Xml.Linq.XElement xel = (System.Xml.Linq.XElement)converter.Parse("<feed></feed>");
            Assert.AreEqual("<feed></feed>", xel.ToString());
            Assert.AreEqual("<feed></feed>", converter.ToString(xel));
        }
Ejemplo n.º 35
0
        public void Then得到字串中介資料(string pi_sExpected)
        {
            string sActual = ScenarioContext.Current.Get <string>("Result");

            System.Xml.Linq.XElement objExpected = System.Xml.Linq.XElement.Parse(pi_sExpected);

            Assert.AreEqual(objExpected.ToString(), sActual);
        }
Ejemplo n.º 36
0
        public async Task <XE> ExecuteAsync(XE in0, CancellationToken cancellationToken)
        {
            _logger.LogInformation(in0.ToString());

            var soapRequestBody = BuildSoapXml(in0);
            var soapResponse    = await SendSoapMessageAsync(soapRequestBody, cancellationToken);

            var returnElement = DeconstructSoapResponse(soapResponse);

            _logger.LogInformation(returnElement.ToString());
            return(returnElement);
        }
Ejemplo n.º 37
0
    protected void BtnTodos_Click(object sender, EventArgs e)
    {
        try
        {
            System.Xml.Linq.XElement _documento = (System.Xml.Linq.XElement)Session["Documento"];

            //asigno al control de despliegue el documento completo
            XmlListar.DocumentContent = _documento.ToString();
        }
        catch (Exception ex)
        {
            LblError.Text = ex.Message;
        }
    }
Ejemplo n.º 38
0
        private async Task <XE> SendSoapMessageAsync(XE soapRequestBody, CancellationToken cancellationToken)
        {
            var content  = new StringContent(soapRequestBody.ToString(), Encoding.UTF8, "text/xml");
            var response = await _httpClient.PostAsync(_options.StoredValueServiceUrl, content, cancellationToken);

            var responseBodyString = await response.Content.ReadAsStringAsync();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new OracleHospitalityClientException($"Unable to POST to {_options.StoredValueServiceUrl}. Expected {(int)HttpStatusCode.OK} {HttpStatusCode.OK}. Got {(int)response.StatusCode} {response.StatusCode} with body '{responseBodyString}'");
            }

            return(XE.Parse(responseBodyString));
        }
Ejemplo n.º 39
0
    //Implemented based on interface, not part of algorithm
    internal static string RemoveAllNamespaces(string xmlDocument)
    {
        System.Xml.Linq.XElement xmlDocumentWithoutNs = null;

        try { xmlDocumentWithoutNs = RemoveAllNamespaces(System.Xml.Linq.XElement.Parse(xmlDocument)); }
        catch (Exception ex1)
        {
            System.Text.StringBuilder sbXMLDocument = new System.Text.StringBuilder();
            sbXMLDocument.AppendFormat("<root>{0}</root>", xmlDocument);

            try { xmlDocument = Convert.ToString(sbXMLDocument); xmlDocumentWithoutNs = RemoveAllNamespaces(System.Xml.Linq.XElement.Parse(xmlDocument)); }
            catch (Exception ex2) { }
        }

        return(xmlDocumentWithoutNs.ToString());
    }
Ejemplo n.º 40
0
        public static string EnsureXmlAttribute(this string xml, string name, object value)
        {
            System.Xml.Linq.XElement ele = XElement.Parse(xml);
            if (ele == null)
            {
                return(xml);
            }
            var att = ele.Attribute(name);

            if (att == null)
            {
                att = new XAttribute(name, value);
                ele.Add(att);
            }
            else
            {
                ele.SetAttributeValue(name, value);
            }
            return(ele.ToString());
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Gets information from Dynamics entity based on FetchXML query
        /// </summary>
        /// <param name="FetchXML">Quer</param>
        /// <param name="top">True for top 50 or all rows</param>
        /// <returns></returns>
        public DataTable GetData(String FetchXML, Boolean top)
        {
            if (string.IsNullOrEmpty(FetchXML))
            {
                throw new Exception("FetchXML query is empty");
            }


            try
            {
                if (service == null)
                {
                    throw new Exception("No Organization Service Available");
                }

                DataTable        dTable = new DataTable();
                EntityCollection result = new EntityCollection();
                bool             AddCol = true;
                int page = 1;

                AttributeMetadata mdta;

                System.Xml.Linq.XElement xe = XElement.Parse(FetchXML.Trim());


                if (xe.Attribute("mapping") == null)
                {
                    xe.SetAttributeValue("mapping", "logical");
                }

                do
                {
                    if (top)
                    {
                        if (xe.Attribute("distinct") == null)
                        {
                            xe.SetAttributeValue("distinct", "false");
                        }

                        if (xe.Attribute("count") == null)
                        {
                            xe.SetAttributeValue("count", "50");
                        }
                        else
                        {
                            xe.Attribute("count").SetValue("50");
                        }

                        result = service.RetrieveMultiple(new FetchExpression(xe.ToString()));

                        result.MoreRecords = false;
                    }
                    else
                    {
                        if (xe.Attribute("paging-cookie") == null)
                        {
                            xe.SetAttributeValue("paging-cookie", result.PagingCookie);
                        }
                        else
                        {
                            xe.Attribute("paging-cookie").SetValue(result.PagingCookie);
                        }

                        if (xe.Attribute("count") == null)
                        {
                            xe.SetAttributeValue("count", "5000");
                        }


                        if (xe.Attribute("page") == null)
                        {
                            xe.SetAttributeValue("page", System.Convert.ToString(page));
                        }
                        else
                        {
                            xe.Attribute("page").SetValue(System.Convert.ToString(page));
                        }

                        page++;



                        result = service.RetrieveMultiple(new FetchExpression(xe.ToString()));
                    }



                    RetrieveEntityRequest mdRequest = new RetrieveEntityRequest()
                    {
                        EntityFilters         = EntityFilters.Attributes,
                        LogicalName           = result.EntityName,
                        RetrieveAsIfPublished = false
                    };

                    RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)service.Execute(mdRequest);

                    entMetadata = entityResponse.EntityMetadata;


                    if (AddCol)
                    {
                        foreach (Entity entity in result.Entities)
                        {
                            for (int iElement = 0; iElement <= entity.Attributes.Count - 1; iElement++)
                            {
                                string columnName = entity.Attributes.Keys.ElementAt(iElement);

                                if (!dTable.Columns.Contains(columnName))
                                {
                                    mdta = entMetadata.Attributes.FirstOrDefault(m => m.LogicalName == columnName);


                                    if (SupportedTypes.isValidAttribute(mdta))
                                    {
                                        switch (mdta.AttributeType.Value)
                                        {
                                        //    break;
                                        case AttributeTypeCode.BigInt:
                                            dTable.Columns.Add(columnName, typeof(Int64));

                                            break;

                                        case AttributeTypeCode.Boolean:
                                            dTable.Columns.Add(columnName, typeof(bool));
                                            break;

                                        case AttributeTypeCode.DateTime:
                                            dTable.Columns.Add(columnName, typeof(DateTime));

                                            break;

                                        case AttributeTypeCode.Decimal:
                                            dTable.Columns.Add(columnName, typeof(decimal));

                                            break;

                                        case AttributeTypeCode.Double:
                                        case AttributeTypeCode.Money:

                                            dTable.Columns.Add(columnName, typeof(float));
                                            break;

                                        case AttributeTypeCode.Integer:
                                        case AttributeTypeCode.Picklist:
                                        case AttributeTypeCode.State:
                                        case AttributeTypeCode.Status:
                                            dTable.Columns.Add(columnName, typeof(Int32));
                                            break;

                                        case AttributeTypeCode.Uniqueidentifier:
                                        case AttributeTypeCode.Customer:
                                        case AttributeTypeCode.Lookup:
                                        case AttributeTypeCode.PartyList:
                                        case AttributeTypeCode.Owner:
                                            dTable.Columns.Add(columnName, typeof(Guid));
                                            break;

                                        default:


                                            dTable.Columns.Add(columnName, typeof(string));
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        AddCol = false;
                    }



                    foreach (Entity entity in result.Entities)
                    {
                        DataRow dRow = dTable.NewRow();
                        for (int i = 0; i <= entity.Attributes.Count - 1; i++)
                        {
                            string colName = entity.Attributes.Keys.ElementAt(i);



                            mdta = entMetadata.Attributes.FirstOrDefault(m => m.LogicalName == colName);
                            if (mdta != null)
                            {
                                switch (mdta.AttributeType.Value)
                                {
                                //case AttributeTypeCode.Boolean:
                                //    dRow[colName] = entity.Attributes.Values.ElementAt(i).ToString() == "1" || entity.Attributes.Values.ElementAt(i).ToString().Trim().ToLower() == "true";
                                //    break;

                                case AttributeTypeCode.Picklist:
                                case AttributeTypeCode.State:
                                case AttributeTypeCode.Status:
                                    dRow[colName] = ((Microsoft.Xrm.Sdk.OptionSetValue)entity.Attributes.Values.ElementAt(i)).Value;
                                    break;

                                case AttributeTypeCode.Customer:
                                case AttributeTypeCode.Lookup:
                                case AttributeTypeCode.PartyList:
                                case AttributeTypeCode.Owner:


                                    dRow[colName] = (Guid)((Microsoft.Xrm.Sdk.EntityReference)entity.Attributes.Values.ElementAt(i)).Id;
                                    break;

                                case AttributeTypeCode.BigInt:
                                    dRow[colName] = (Int64?)entity.Attributes.Values.ElementAt(i);
                                    break;

                                case AttributeTypeCode.Decimal:

                                    dRow[colName] = (decimal?)entity.Attributes.Values.ElementAt(i);
                                    break;

                                case AttributeTypeCode.Double:
                                    dRow[colName] = (double?)entity.Attributes.Values.ElementAt(i);
                                    break;

                                case AttributeTypeCode.Integer:
                                    dRow[colName] = (int?)entity.Attributes.Values.ElementAt(i);
                                    break;

                                case AttributeTypeCode.Money:
                                    dRow[colName] = ((Microsoft.Xrm.Sdk.Money)entity.Attributes.Values.ElementAt(i)).Value;
                                    break;

                                case AttributeTypeCode.DateTime:
                                    dRow[colName] = (DateTime?)entity.Attributes.Values.ElementAt(i);
                                    break;

                                case AttributeTypeCode.Uniqueidentifier:
                                    dRow[colName] = (Guid?)entity.Attributes.Values.ElementAt(i);
                                    break;

                                case AttributeTypeCode.Boolean:
                                    dRow[colName] = (bool?)entity.Attributes.Values.ElementAt(i);
                                    break;

                                default:
                                    dRow[colName] = (string)entity.Attributes.Values.ElementAt(i);

                                    break;
                                }
                            }
                        }
                        dTable.Rows.Add(dRow);
                    }
                }while (result.MoreRecords);

                return(dTable);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 42
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        #region initialiseVariables
        int    intProcessSerialId = 0;
        string strProcessId       = Guid.NewGuid().ToString().ToUpper();
        string strPageName        = "FundTransfer";

        string strResultCode    = string.Empty;
        string strResultDetail  = string.Empty;
        string strErrorCode     = string.Empty;
        string strErrorDetail   = string.Empty;
        string strProcessRemark = string.Empty;
        bool   isProcessAbort   = false;
        bool   isSystemError    = false;

        System.Xml.Linq.XElement xeResponse = null;

        string strStatusCode = string.Empty;
        string strStatusText = string.Empty;

        string strOperatorId   = string.Empty;
        string strMemberCode   = string.Empty;
        string strSiteCode     = string.Empty;
        string strCurrencyCode = string.Empty;
        string strSessionToken = string.Empty;

        string strTransferFrom   = string.Empty;
        string strTransferTo     = string.Empty;
        string strTransferAmount = string.Empty;
        string strPromoCode      = string.Empty;

        string strTransferId     = string.Empty;
        string strTransferStatus = string.Empty;

        bool includeStatus = false;
        #endregion

        #region populateVariables
        strTransferFrom   = drpTransferFrom.SelectedValue;
        strTransferTo     = drpTransferTo.SelectedValue;
        strTransferAmount = txtTransferAmount.Text;
        strPromoCode      = txtPromoCode.Text;

        strOperatorId   = commonVariables.OperatorId;
        strSiteCode     = commonVariables.SiteUrl.ToLower();
        strMemberCode   = base.userInfo.MemberCode;
        strCurrencyCode = commonCookie.CookieCurrency;
        strSessionToken = base.userInfo.CurrentSessionId;
        #endregion

        #region parametersValidation
        if (string.Compare(strTransferFrom, "-1", true) == 0)
        {
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/FundTransfer/SelectTransferFrom", xeErrors);
            isProcessAbort  = true;
        }
        else if (string.Compare(strTransferTo, "-1", true) == 0)
        {
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/FundTransfer/SelectTransferFrom", xeErrors);
            isProcessAbort  = true;
        }
        else if (string.Compare(strTransferFrom, strTransferTo, true) == 0)
        {
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/FundTransfer/InvalidFundTransfer", xeErrors);
            isProcessAbort  = true;
        }
        else if (string.IsNullOrEmpty(strMemberCode))
        {
            strAlertCode    = "-1";
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/SessionExpired", xeErrors);
            isProcessAbort  = true;
        }
        else if (string.IsNullOrEmpty(strCurrencyCode))
        {
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/FundTransfer/SessionExpired", xeErrors);
            isProcessAbort  = true;
        }
        else if (string.IsNullOrEmpty(strSessionToken))
        {
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/FundTransfer/SessionExpired", xeErrors);
            isProcessAbort  = true;
        }
        else if (string.IsNullOrEmpty(strTransferAmount))
        {
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/FundTransfer/InputTransferAmount", xeErrors);
            isProcessAbort  = true;
        }
        else if (commonValidation.isInjection(strTransferAmount))
        {
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/FundTransfer/TransferAmountDisallowed", xeErrors);
            isProcessAbort  = true;
        }
        else if (!commonValidation.isNumeric(strTransferAmount))
        {
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/FundTransfer/TransferAmountDisallowed", xeErrors);
            isProcessAbort  = true;
        }
        else if (commonValidation.isInjection(strPromoCode))
        {
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Promotion/InvalidPromo", xeErrors);
            isProcessAbort  = true;
        }

        strProcessRemark = string.Format("TransferFrom: {0} | TransferTo: {1} | TransferAmount: {2} | PromoCode: {3} | MemberCode: {4} | CurrencyCode: {5} | SessionToken: {6}", strTransferFrom, strTransferTo, strTransferAmount, strPromoCode, strMemberCode, strCurrencyCode, strSessionToken);

        intProcessSerialId += 1;
        commonAuditTrail.appendLog("system", strPageName, "ParameterValidation", "DataBaseManager.DLL", strResultCode, strResultDetail, strErrorCode, strErrorDetail, strProcessRemark, Convert.ToString(intProcessSerialId), strProcessId, isSystemError);
        #endregion

        #region initiateFundTransfer
        if (!isProcessAbort)
        {
            try
            {
                using (svcFundTransfer.FundTransferClient svcInstance = new svcFundTransfer.FundTransferClient())
                {
                    xeResponse = svcInstance.initiateTransfer(strTransferFrom, strTransferTo, strOperatorId, strSiteCode, strMemberCode, strCurrencyCode, strSessionToken, Math.Abs(Convert.ToDecimal(strTransferAmount)), strPromoCode, svcFundTransfer.transferOrigin.Mobile, out strStatusCode, out strStatusText);
                }
            }
            catch (Exception ex)
            {
                strResultCode   = Convert.ToString(ex.HResult);
                strResultDetail = ex.Message;
            }

            strAlertCode = strStatusCode;

            switch (strStatusCode)
            {
            case "-60":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/TransferFailed", xeErrors);
                break;

            case "00":

                strTransferId     = commonCulture.ElementValues.getResourceString("transferId", xeResponse);
                strTransferStatus = commonCulture.ElementValues.getResourceString("transferStatus", xeResponse);

                string strPokerAddOn = string.Empty;
                if (string.Compare(strTransferFrom, "6", true) == 0 && string.Compare(strTransferTo, "16", true) != 0)
                {
                    strPokerAddOn = "[break]" + commonVariables.GetSessionVariable("CurrencyCode") + " " + commonCulture.ElementValues.getResourceString("transferAmount", xeResponse) + commonCulture.ElementValues.getResourceXPathString("FundTransfer/USDDeposited", xeErrors);
                }
                else if (string.Compare(strTransferTo, "6", true) == 0)
                {
                    strPokerAddOn = "[break]USD " + commonValidation.roundDown(commonCulture.ElementValues.getResourceString("transferAmount", xeResponse), 2) + commonCulture.ElementValues.getResourceXPathString("FundTransfer/USDDeposited", xeErrors);
                }

                string strFishingAddOn = string.Empty;
                if (string.Compare(strTransferFrom, "16", true) == 0 && string.Compare(strTransferTo, "6", true) != 0)
                {
                    strFishingAddOn = "[break]" + commonVariables.GetSessionVariable("CurrencyCode") + " " + commonCulture.ElementValues.getResourceString("transferAmount", xeResponse) + commonCulture.ElementValues.getResourceXPathString("FundTransfer/USDDeposited", xeErrors);
                }
                else if (string.Compare(strTransferTo, "16", true) == 0)
                {
                    strFishingAddOn = "[break]RMB " + commonValidation.roundDown(commonCulture.ElementValues.getResourceString("transferAmount", xeResponse), 2) + commonCulture.ElementValues.getResourceXPathString("FundTransfer/USDDeposited", xeErrors);
                }

                string err46 = string.Empty;
                if (commonCulture.ElementValues.getResourceString("customCode", xeResponse).Equals("1"))
                {
                    err46 = "[break]" + commonCulture.ElementValues.getResourceXPathString("FundTransfer/ERR46", xeErrors);
                }

                strAlertMessage = string.Format("{0}{1}{2}{3}{4}", commonCulture.ElementValues.getResourceXPathString("FundTransfer/TransferSuccess", xeErrors),
                                                commonCulture.ElementValues.getResourceXPathString("FundTransfer/BalanceBeforeAfter", xeErrors)
                                                .Replace("{walletFrom}", string.Format("{0} => {1}", Convert.ToDecimal(commonCulture.ElementValues.getResourceString("transferFromBalanceBefore", xeResponse)).ToString(commonVariables.DecimalFormat), Convert.ToDecimal(commonCulture.ElementValues.getResourceString("transferFromBalanceAfter", xeResponse)).ToString(commonVariables.DecimalFormat)))
                                                .Replace("{walletTo}", string.Format("{0} => {1}", Convert.ToDecimal(commonCulture.ElementValues.getResourceString("transferToBalanceBefore", xeResponse)).ToString(commonVariables.DecimalFormat), Convert.ToDecimal(commonCulture.ElementValues.getResourceString("transferToBalanceAfter", xeResponse)).ToString(commonVariables.DecimalFormat))),
                                                strPokerAddOn, strFishingAddOn, err46);

                drpTransferFrom.SelectedIndex = 0;
                drpTransferTo.SelectedIndex   = 0;

                txtTransferAmount.Text = string.Empty;
                txtPromoCode.Text      = string.Empty;
                break;

            case "12":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/InvalidFundTransfer", xeErrors);
                break;

            case "13":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/TransferAmountDisallowed", xeErrors);
                break;

            case "36":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("SessionExpired", xeErrors);
                break;

            case "51":     // "Transfer Declined - Reference ID already in used";
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/TransferFailed", xeErrors);
                break;

            case "53":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/TransferDeclined", xeErrors) + "[break]" + commonCulture.ElementValues.getResourceXPathString("FundTransfer/InsufficientFunds", xeErrors);
                break;

            case "54":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/UnderMaintenance", xeErrors);
                break;

            case "55":     // "Transfer Declined - Funds refunded"
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("ServerError", xeErrors);
                break;

            case "62":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/FundOutLimit", xeErrors);
                break;

            case "63":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/FundInLimit", xeErrors);
                break;

            case "64":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/FundOutLimitReq", xeErrors);
                break;

            case "65":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/FundInLimitReq", xeErrors);
                break;

            case "70":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/TransferFailed", xeErrors) + "[break]" + commonCulture.ElementValues.getResourceXPathString("ServerError", xeErrors);
                break;

            case "100":
            case "101":
            case "107":
            case "108":
            case "71":     // merchant accoutn frozen
            case "52":     //new error code - no messages yet
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("Promotion/InvalidPromo", xeErrors);
                break;

            case "102":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/MinTransferNotMet", xeErrors);
                break;

            case "105":
            case "106":
            case "109":
                string  strTransferAmountAllowed = commonCulture.ElementValues.getResourceString("transferAmountAllowed", xeResponse);
                string  strTotalStakeAmount      = commonCulture.ElementValues.getResourceString("totalStakeAmount", xeResponse);
                string  strRolloverAmount        = commonCulture.ElementValues.getResourceString("rolloverAmount", xeResponse);
                decimal decRolloverAmountNeeded  = Convert.ToDecimal(strRolloverAmount) - Convert.ToDecimal(strTotalStakeAmount);

                strAlertMessage = string.Format("{0} ({1}) [break]{2} [break]{3}", commonCulture.ElementValues.getResourceXPathString("FundTransfer/RolloverNotMet", xeErrors), strStatusCode, commonCulture.ElementValues.getResourceXPathString("FundTransfer/RolloverAmountNeeded", xeErrors) + commonValidation.roundDown(decRolloverAmountNeeded, 2), commonCulture.ElementValues.getResourceXPathString("FundTransfer/TransferAmountAllowed", xeErrors) + commonValidation.roundDown(strTransferAmountAllowed, 2));
                includeStatus   = false;
                break;

            case "103":
            case "104":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("Promotion/PromoAlreadyClaimed", xeErrors);
                break;

            case "ERR01":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/ERR01", xeErrors);
                break;

            case "917":
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/CloseGame", xeErrors);
                break;

            default:
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("FundTransfer/TransferFailed", xeErrors);
                break;
            }
            if (includeStatus)
            {
                strAlertMessage = string.Format("{0} {1}", strAlertMessage, strStatusCode);
            }

            strErrorCode     = strStatusCode;
            strErrorDetail   = strAlertMessage;
            strProcessRemark = string.Format("TransferFrom: {0} | TransferTo: {1} | TransferAmount: {2} | PromoCode: {3} | MemberCode: {4} | CurrencyCode: {5} | SessionToken: {6} | TransferId: {7} | TransferStatus: {8} | Response: {9}",
                                             strTransferFrom, strTransferTo, strTransferAmount, strPromoCode, strMemberCode, strCurrencyCode, strSessionToken, strTransferId, strTransferStatus, xeResponse == null ? string.Empty : xeResponse.ToString());

            intProcessSerialId += 1;
            commonAuditTrail.appendLog("system", strPageName, "InitiateFundTransfer", "DataBaseManager.DLL", strResultCode, strResultDetail, strErrorCode, strErrorDetail, strProcessRemark, Convert.ToString(intProcessSerialId), strProcessId, isSystemError);
        }

        #endregion
    }
        public void Execute(ClientContext ctx, string libraryName, string filePath, E webPart, int row, int column)
        {
            XNamespace v2    = "http://schemas.microsoft.com/WebPart/v2";
            XNamespace v3    = "http://schemas.microsoft.com/WebPart/v3";
            string     title = null;

            var v3Prope = webPart.Elements().ToList().SingleOrDefault(e => e.Name.LocalName == "webPart");

            if (webPart.Name.Namespace == v2)
            {
                title = webPart.Element(v2 + "Title").Value;
            }
            else if (v3Prope != null && v3Prope.Name.Namespace == v3)
            {
                var properties = v3Prope.Element(v3 + "data").Element(v3 + "properties").Elements(v3 + "property");
                title = properties.Single(e => e.Attribute("name").Value == "Title").Value;
            }
            else
            {
                throw new ArgumentException("Unable to extract title for webpart definition");
            }
            Logger.Verbose($"Started executing {nameof(AddWebPartToWikiPage)} with title '{title}' to page '{filePath}'");

            var web     = ctx.Web;
            var library = web.Lists.GetByTitle(libraryName);

            ctx.Load(library, l => l.RootFolder);
            ctx.ExecuteQuery();

            var page = web.GetFileByServerRelativeUrl(library.RootFolder.ServerRelativeUrl + "/" + filePath);

            ctx.Load(library, l => l.RootFolder);
            ctx.Load(page, p => p.Exists);
            ctx.ExecuteQuery();

            if (!page.Exists)
            {
                throw new ArgumentException($"File path '{filePath}' not found in library '{libraryName}'");
            }

            var fields = page.ListItemAllFields;

            ctx.Load(page, p => p.ListItemAllFields);
            ctx.ExecuteQuery();

            var wikiField = E.Parse((string)fields["WikiField"]);
            var rows      = wikiField.Element("table").Element("tbody").Elements("tr");

            if (row >= rows.Count())
            {
                throw new ArgumentException($"Cannot insert into row {row}. Page only contains {rows.Count()} rows");
            }

            var columns = rows.ElementAt(row).Elements("td");

            if (column >= columns.Count())
            {
                throw new ArgumentException($"Cannot intert into column {column}. Page only contains {columns.Count()} columns");
            }

            var manager = page.GetLimitedWebPartManager(PersonalizationScope.Shared);

            ctx.Load(manager, m => m.WebParts.Include(m2 => m2.WebPart.Title));
            ctx.ExecuteQuery();

            var candidate = manager.WebParts.SingleOrDefault(wpd => wpd.WebPart.Title == title);

            if (candidate != null)
            {
                Logger.Warning($"Web part with title '{title}' already on page");
                return;
            }

            var definition = manager.ImportWebPart(webPart.ToString());
            var newWebPart = manager.AddWebPart(definition.WebPart, "wpz", 0);

            ctx.Load(newWebPart);
            ctx.ExecuteQuery();

            var id = newWebPart.Id;
            var layoutsZoneInner = columns.ElementAt(column);

            layoutsZoneInner
            .Element("div")
            .Element("div")
            .Add(new E("p", ""),
                 new E("div", new A("class", "ms-rtestate-read ms-rte-wpbox"),
                       new E("div", new A("class", "ms-rtestate-notify ms-rtestate-read " + id), new A("id", "div_" + id), new A("unselectable", "on"), ""),
                       new E("div", new A("id", "vid_" + id), new A("unselectable", "on"), new A("style", "display:none;"), "")));

            fields["WikiField"] = wikiField.ToString();
            fields.Update();
            ctx.ExecuteQuery();
        }
Ejemplo n.º 44
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        #region initialiseVariables
        int    intProcessSerialId = 0;
        string strProcessId       = Guid.NewGuid().ToString().ToUpper();
        string strPageName        = "Deposit.FastDeposit";

        string strResultCode    = string.Empty;
        string strResultDetail  = string.Empty;
        string strErrorCode     = string.Empty;
        string strErrorDetail   = string.Empty;
        string strProcessRemark = string.Empty;
        bool   isProcessAbort   = false;
        bool   isSystemError    = false;

        long   lngOperatorId    = long.MinValue;
        string strDepositAmount = string.Empty;
        string strReferenceId   = string.Empty;
        string strSystemAccount = string.Empty;
        string strDepositDate   = string.Empty;
        //string strDepositDay = string.Empty;
        //string strDepositMonth = string.Empty;
        //string strDepositYear = string.Empty;
        string strDepositHour    = string.Empty;
        string strDepositMinute  = string.Empty;
        string strDepositChannel = string.Empty;
        string strBankCode       = string.Empty;
        string strBankName       = string.Empty;
        string strBankNameInput  = string.Empty;
        string strAccountName    = string.Empty;
        string strAccountNumber  = string.Empty;

        decimal decMinLimit     = decimal.Zero;
        decimal decMaxLimit     = decimal.Zero;
        decimal decTotalAllowed = decimal.Zero;
        decimal decDailyLimit   = decimal.Zero;

        System.DateTime          dtDepositDateTime = System.DateTime.MinValue;
        System.Xml.Linq.XElement xeResponse        = null;

        bool   isDepositSuccessful = false;
        string strTransferId       = string.Empty;
        bool   sessionExpired      = false;

        #endregion

        #region populateVariables
        lngOperatorId   = long.Parse(commonVariables.OperatorId);
        strMemberCode   = commonVariables.GetSessionVariable("MemberCode");
        strCurrencyCode = commonVariables.GetSessionVariable("CurrencyCode");

        strDepositAmount = txtAmount.Value;
        strReferenceId   = txtReferenceId.Value;
        strSystemAccount = drpSystemAccount.Value;
        strDepositDate   = drpDepositDate.Value;
        //strDepositDay = drpDay.SelectedValue;
        //strDepositMonth = drpMonth.SelectedValue;
        //strDepositYear = drpYear.SelectedValue;
        strDepositHour    = drpHour.Value;
        strDepositMinute  = drpMinute.Value;
        strDepositChannel = drpDepositChannel.Value;
        strBankCode       = drpBank.Value;
        strBankName       = drpBank.Items.FindByValue(strBankCode).Text;
        strBankNameInput  = txtBankName.Value;
        strAccountName    = txtAccountName.Value;
        strAccountNumber  = txtAccountNumber.Value;

        if (string.Compare(strCurrencyCode, "krw", true) == 0)
        {
            dtDepositDateTime = System.DateTime.Now;
        }
        //else { dtDepositDateTime = System.DateTime.Parse(drpDepositDate.SelectedValue)}//new System.DateTime(Convert.ToInt32(strDepositYear), Convert.ToInt32(strDepositMonth), Convert.ToInt32(strDepositDay), Convert.ToInt32(strDepositHour), Convert.ToInt32(strDepositMinute), 0); }
        #endregion

        #region parametersValidation
        if (string.IsNullOrEmpty(strDepositAmount))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/MissingDepositAmount", xeErrors); return;
        }
        else if (string.IsNullOrEmpty(strAccountName))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/MissingAccountName", xeErrors); return;
        }
        else if (string.IsNullOrEmpty(strAccountNumber))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/MissingAccountNumber", xeErrors); return;
        }
        else if (string.Compare(drpBank.Value, "OTHER", true) == 0 && string.IsNullOrEmpty(strBankNameInput))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/MissingBankName", xeErrors); return;
        }
        else if (Convert.ToString(drpSystemAccount.Value) == "-1")
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/SelectSystemAccount", xeErrors); return;
        }
        else if (Convert.ToString(drpDepositChannel.Value) == "-1")
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/SelectDepositChannel", xeErrors); return;
        }
        else if (Convert.ToString(drpBank.Value) == "-1")
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/SelectBank", xeErrors); return;
        }
        else if (!commonValidation.isDecimal(strDepositAmount))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/InvalidDepositAmount", xeErrors); return;
        }
        else if (Convert.ToDecimal(strDepositAmount) <= 0)
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/InvalidDepositAmount", xeErrors); return;
        }
        else if (commonValidation.isInjection(strDepositAmount))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/InvalidDepositAmount", xeErrors); return;
        }
        else if (commonValidation.isInjection(strReferenceId))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/InvalidReferenceId", xeErrors); return;
        }
        else if (commonValidation.isInjection(strBankNameInput))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/InvalidBankName", xeErrors); return;
        }
        else if (commonValidation.isInjection(strAccountName))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/InvalidAccountName", xeErrors); return;
        }
        else if (commonValidation.isInjection(strAccountNumber))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/InvalidAccountNumber", xeErrors); return;
        }
        else if (string.Compare(strCurrencyCode, "krw", true) != 0)
        {
            if (!string.IsNullOrEmpty(strDepositDate))
            {
                dtDepositDateTime = System.DateTime.Parse(strDepositDate);
                if ((dtDepositDateTime - System.DateTime.Now).TotalHours > 72 || (dtDepositDateTime - System.DateTime.Now).TotalHours < -72)
                {
                    strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/InvalidDateTime", xeErrors); return;
                }
            }
            else if (string.IsNullOrEmpty(strDepositDate))
            {
                strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/InvalidDateTime", xeErrors); return;
            }
        }
        else if (string.IsNullOrEmpty(strMemberCode))
        {
            strAlertCode    = "-1";
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/SessionExpired", xeErrors);
            isProcessAbort  = true;
            sessionExpired  = true;
        }
        else if (string.IsNullOrEmpty(strCurrencyCode))
        {
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/FundTransfer/SessionExpired", xeErrors);
            isProcessAbort  = true;
            sessionExpired  = true;
        }

        #endregion

        #region initialiseDeposit
        if (!isProcessAbort)
        {
            try
            {
                string strProcessCode = string.Empty;
                string strProcessText = string.Empty;

                System.Data.DataTable dtPaymentMethodLimits = null;

                using (svcPayMember.MemberClient svcInstance = new svcPayMember.MemberClient())
                {
                    dtPaymentMethodLimits = svcInstance.getMethodLimits(strOperatorId, strMemberCode, Convert.ToString(Convert.ToInt32(commonVariables.DepositMethod.FastDeposit)), Convert.ToString(Convert.ToInt32(commonVariables.PaymentTransactionType.Deposit)), false, out strProcessCode, out strProcessText);

                    if (dtPaymentMethodLimits.Rows.Count > 0)
                    {
                        decMinLimit     = Convert.ToDecimal(dtPaymentMethodLimits.Rows[0]["minDeposit"]);
                        decMaxLimit     = Convert.ToDecimal(dtPaymentMethodLimits.Rows[0]["maxDeposit"]);
                        decTotalAllowed = Convert.ToDecimal(dtPaymentMethodLimits.Rows[0]["totalAllowed"]);
                        decDailyLimit   = Convert.ToDecimal(dtPaymentMethodLimits.Rows[0]["limitDaily"]);

                        if (Convert.ToDecimal(strDepositAmount) < decMinLimit)
                        {
                            strAlertCode    = "-1";
                            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/AmountMinLimit", xeErrors);
                            isProcessAbort  = true;
                        }
                        else if (Convert.ToDecimal(strDepositAmount) > decMaxLimit)
                        {
                            strAlertCode    = "-1";
                            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/AmountMaxLimit", xeErrors);
                            isProcessAbort  = true;
                        }
                        else if (Convert.ToDecimal(strDepositAmount) > decTotalAllowed)
                        {
                            strAlertCode    = "-1";
                            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/TotalAllowedExceeded", xeErrors);
                            isProcessAbort  = true;
                        }
                    }
                }

                if (!isProcessAbort)
                {
                    using (svcPayDeposit.DepositClient svcInstance = new svcPayDeposit.DepositClient())
                    {
                        xeResponse = svcInstance.createFastDepositTransactionV1(lngOperatorId, strMemberCode, strDepositChannel, Convert.ToInt64(commonVariables.DepositMethod.FastDeposit),
                                                                                strCurrencyCode, Convert.ToDecimal(strDepositAmount), Convert.ToInt64(strSystemAccount), strAccountName, strAccountNumber, dtDepositDateTime,
                                                                                strReferenceId, strBankCode, strBankName, strBankNameInput, Convert.ToString(commonVariables.TransactionSource.Wap));

                        if (xeResponse == null)
                        {
                            strAlertCode    = "-1";
                            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/TransferFail", xeErrors);
                        }
                        else
                        {
                            isDepositSuccessful = Convert.ToBoolean(commonCulture.ElementValues.getResourceString("result", xeResponse));
                            strTransferId       = commonCulture.ElementValues.getResourceString("invId", xeResponse);

                            if (isDepositSuccessful)
                            {
                                strAlertCode      = "0";
                                strAlertMessage   = string.Format("{0}\\n{1}: {2}", commonCulture.ElementValues.getResourceXPathString("/Deposit/TransferSuccess", xeErrors), commonCulture.ElementValues.getResourceString("lblTransactionId", xeResources), strTransferId);
                                btnSubmit.Visible = false;
                                btnBack.Value     = commonCulture.ElementValues.getResourceString("home", commonVariables.LeftMenuXML);
                            }
                            else
                            {
                                strAlertCode    = "-1";
                                strAlertMessage = string.Format("{0}\\n{1}", commonCulture.ElementValues.getResourceXPathString("/Deposit/TransferFail", xeErrors), commonCulture.ElementValues.getResourceXPathString("/Deposit/error" + strTransferId, xeErrors));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                strAlertCode    = "-1";
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Deposit/Exception", xeErrors);

                strErrorDetail = ex.Message;
            }

            strProcessRemark = string.Format("OperatorId: {0} | MemberCode: {1} | CurrencyCode: {2} | DepositAmount: {3} | DepositChannel: {4} | AccountName: {6} | AccountNumber: {6} | SystemAccount: {7} | BankCode: {8} | BankName: {9} | BankNameInput: {10} | ReferenceID: {11} | DepositDateTime: {12} | MinLimit: {13} | MaxLimit: {14} | TotalAllowed: {15} | DailyLimit: {16} | Response: {17}",
                                             lngOperatorId, strMemberCode, strCurrencyCode, strDepositAmount, strDepositChannel, strAccountName, strAccountNumber, strSystemAccount, strBankCode, strBankName, strBankNameInput, strReferenceId, dtDepositDateTime.ToString("yyyy-MM-dd HH:mm:ss"), decMinLimit, decMaxLimit, decTotalAllowed, decDailyLimit, xeResponse == null ? string.Empty : xeResponse.ToString());

            intProcessSerialId += 1;
            commonAuditTrail.appendLog("system", strPageName, "InitiateDeposit", "DataBaseManager.DLL", strResultCode, strResultDetail, strErrorCode, strErrorDetail, strProcessRemark, Convert.ToString(intProcessSerialId), strProcessId, isSystemError);
        }

        #region Response
        txtMessage.InnerHtml = strAlertMessage.Replace("\\n", "<br />");
        #endregion

        #endregion

        if (sessionExpired)
        {
            Response.Redirect("/Expire");
        }
    }
Ejemplo n.º 45
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        #region initialiseVariables
        int    intProcessSerialId = 0;
        string strProcessId       = Guid.NewGuid().ToString().ToUpper();
        string strPageName        = "Withdrawal.BankTransfer";

        string strResultCode    = string.Empty;
        string strResultDetail  = string.Empty;
        string strErrorCode     = string.Empty;
        string strErrorDetail   = string.Empty;
        string strProcessRemark = string.Empty;
        bool   isProcessAbort   = false;
        bool   isSystemError    = false;

        long   lngOperatorId     = long.MinValue;
        string strWithdrawAmount = string.Empty;
        string strBankCode       = string.Empty;
        string strBankName       = string.Empty;
        string strBankNameInput  = string.Empty;
        string strBankBranch     = string.Empty;
        string strBankAddress    = string.Empty;
        string strAccountName    = string.Empty;
        string strAccountNumber  = string.Empty;
        string strMyKad          = string.Empty;
        string strMobileNumber   = string.Empty;
        bool   MobileNotify      = false;

        decimal decMinLimit     = decimal.Zero;
        decimal decMaxLimit     = decimal.Zero;
        decimal decTotalAllowed = decimal.Zero;
        decimal decDailyLimit   = decimal.Zero;

        System.Xml.Linq.XElement xeResponse = null;

        bool   isWithdrawSuccessful = false;
        string strTransferId        = string.Empty;

        bool sessionExpired = false;
        #endregion

        #region populateVariables
        lngOperatorId   = long.Parse(commonVariables.OperatorId);
        strMemberCode   = commonVariables.GetSessionVariable("MemberCode");
        strCurrencyCode = commonVariables.GetSessionVariable("CurrencyCode");

        strWithdrawAmount = txtAmount.Value;
        strBankCode       = drpBank.Value;
        strBankName       = drpBank.Items.FindByValue(strBankCode).Text;
        strBankNameInput  = txtBankName.Value;
        strBankAddress    = txtAddress.Value;
        strBankBranch     = txtBankBranch.Value;
        strAccountName    = txtAccountName.Value;
        strAccountNumber  = txtAccountNumber.Value;
        strMyKad          = txtMyKad.Value;

        System.Text.RegularExpressions.Regex regxATM = new System.Text.RegularExpressions.Regex("([0-9]{16})$");

        #endregion

        #region parametersValidation
        if (string.IsNullOrEmpty(strWithdrawAmount))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/MissingWithdrawalAmount", xeErrors); return;
        }
        else if (string.IsNullOrEmpty(strAccountName))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/MissingAccountName", xeErrors); return;
        }
        else if (string.IsNullOrEmpty(strAccountNumber))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/MissingAccountNumber", xeErrors); return;
        }
        else if (string.Compare(drpBank.Value, "OTHER", true) == 0 && string.IsNullOrEmpty(strBankNameInput))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/MissingBankName", xeErrors); return;
        }
        //else if (string.Compare(drpBank.SelectedValue, "VIETIN", true) == 0 && (!commonValidation.isNumeric(strAccountNumber) || !regxATM.IsMatch(strAccountNumber))) { strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/InvalidAccountNumber", xeErrors); return; }
        else if (string.IsNullOrEmpty(strBankBranch) && string.Compare(strCurrencyCode, "krw", true) != 0)
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/MissingBankBranch", xeErrors); return;
        }
        else if (string.IsNullOrEmpty(strBankAddress) && string.Compare(strCurrencyCode, "krw", true) != 0)
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/MissingBankAddress", xeErrors); return;
        }
        else if (string.Compare(strCurrencyCode, "myr", true) == 0)
        {
            if (string.IsNullOrEmpty(strMyKad))
            {
                strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/MissingAccountNumber", xeErrors); return;
            }
        }
        else if (Convert.ToString(drpBank.Value) == "-1")
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/SelectBank", xeErrors); return;
        }
        else if (!commonValidation.isDecimal(strWithdrawAmount))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/InvalidWithdrawAmount", xeErrors); return;
        }
        else if (Convert.ToDecimal(strWithdrawAmount) <= 0)
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/InvalidWithdrawAmount", xeErrors); return;
        }
        else if (commonValidation.isInjection(strWithdrawAmount))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/InvalidWithdrawAmount", xeErrors); return;
        }
        else if (commonValidation.isInjection(strBankNameInput))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/InvalidBankName", xeErrors); return;
        }
        else if (commonValidation.isInjection(strAccountName))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/InvalidAccountName", xeErrors); return;
        }
        else if (commonValidation.isInjection(strAccountNumber))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/InvalidAccountNumber", xeErrors); return;
        }
        else if (commonValidation.isInjection(strBankBranch))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/InvalidBankBranch", xeErrors); return;
        }
        else if (commonValidation.isInjection(strBankAddress))
        {
            strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/InvalidBankAddress", xeErrors); return;
        }
        else if (string.Compare(strCurrencyCode, "myr", true) == 0)
        {
            if (commonValidation.isInjection(strMyKad))
            {
                strAlertCode = "-1"; strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/MissingMyKad", xeErrors); return;
            }
        }
        else if (string.IsNullOrEmpty(strMemberCode))
        {
            strAlertCode    = "-1";
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/SessionExpired", xeErrors);
            isProcessAbort  = true;
            sessionExpired  = true;
        }
        else if (string.IsNullOrEmpty(strCurrencyCode))
        {
            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/FundTransfer/SessionExpired", xeErrors);
            isProcessAbort  = true;
            sessionExpired  = true;
        }
        #endregion

        #region initialiseWithdrawal
        if (!isProcessAbort)
        {
            try
            {
                string strProcessCode = string.Empty;
                string strProcessText = string.Empty;

                System.Data.DataTable dtPaymentMethodLimits = null;

                using (svcPayMember.MemberClient svcInstance = new svcPayMember.MemberClient())
                {
                    dtPaymentMethodLimits = svcInstance.getMethodLimits(strOperatorId, strMemberCode, Convert.ToString(Convert.ToInt32(commonVariables.WithdrawalMethod.BankTransfer)), Convert.ToString(Convert.ToInt32(commonVariables.PaymentTransactionType.Withdrawal)), false, out strProcessCode, out strProcessText);

                    if (dtPaymentMethodLimits.Rows.Count > 0)
                    {
                        decMinLimit     = Convert.ToDecimal(dtPaymentMethodLimits.Rows[0]["minWithdrawal"]);
                        decMaxLimit     = Convert.ToDecimal(dtPaymentMethodLimits.Rows[0]["maxWithdrawal"]);
                        decTotalAllowed = Convert.ToDecimal(dtPaymentMethodLimits.Rows[0]["totalAllowed"]);
                        decDailyLimit   = Convert.ToDecimal(dtPaymentMethodLimits.Rows[0]["limitDaily"]);

                        if (Convert.ToDecimal(strWithdrawAmount) < decMinLimit)
                        {
                            strAlertCode    = "-1";
                            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/AmountMinLimit", xeErrors);
                            isProcessAbort  = true;
                        }
                        else if (Convert.ToDecimal(strWithdrawAmount) > decMaxLimit)
                        {
                            strAlertCode    = "-1";
                            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/AmountMaxLimit", xeErrors);
                            isProcessAbort  = true;
                        }
                        else if (Convert.ToDecimal(strWithdrawAmount) > decTotalAllowed)
                        {
                            strAlertCode    = "-1";
                            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/TotalAllowedExceeded", xeErrors);
                            isProcessAbort  = true;
                        }
                    }
                }

                if (!isProcessAbort)
                {
                    using (svcPayWithdrawal.WithdrawalClient svcInstance = new svcPayWithdrawal.WithdrawalClient())
                    {
                        xeResponse = svcInstance.createBankTransferTransactionV1(lngOperatorId, strMemberCode, Convert.ToInt64(commonVariables.WithdrawalMethod.BankTransfer),
                                                                                 strCurrencyCode, Convert.ToDecimal(strWithdrawAmount), strAccountName, strAccountNumber, strBankAddress, strBankBranch, strBankCode, strBankName, strBankNameInput,
                                                                                 strMyKad, strMobileNumber, MobileNotify, Convert.ToString(commonVariables.TransactionSource.Wap));

                        if (xeResponse == null)
                        {
                            strAlertCode    = "-1";
                            strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/TransferFail", xeErrors);
                        }
                        else
                        {
                            isWithdrawSuccessful = Convert.ToBoolean(commonCulture.ElementValues.getResourceString("result", xeResponse));
                            strTransferId        = commonCulture.ElementValues.getResourceString("invId", xeResponse);

                            if (isWithdrawSuccessful)
                            {
                                strAlertCode      = "0";
                                strAlertMessage   = string.Format("{0}\\n{1}: {2}", commonCulture.ElementValues.getResourceXPathString("/Withdrawal/TransferSuccess", xeErrors), commonCulture.ElementValues.getResourceString("lblTransactionId", xeResources), strTransferId);
                                btnSubmit.Visible = false;
                                btnBack.Value     = commonCulture.ElementValues.getResourceString("home", commonVariables.LeftMenuXML);
                            }
                            else
                            {
                                strAlertCode    = "-1";
                                strAlertMessage = string.Format("{0}\\n{1}", commonCulture.ElementValues.getResourceXPathString("/Withdrawal/TransferFail", xeErrors), commonCulture.ElementValues.getResourceXPathString("/Withdrawal/error" + strTransferId, xeErrors));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                strAlertCode    = "-1";
                strAlertMessage = commonCulture.ElementValues.getResourceXPathString("/Withdrawal/Exception", xeErrors);

                strErrorDetail = ex.Message;
            }

            strProcessRemark = string.Format("OperatorId: {0} | MemberCode: {1} | CurrencyCode: {2} | WithdrawAmount: {3} | AccountName: {4} | AccountNumber: {5} | BankAddress: {6} | BankBranch: {7} | BankCode: {8} | BankName: {9} | BankNameInput: {10} | MyKad: {11} | Mobile: {12} | MinLimit: {13} | MaxLimit: {14} | TotalAllowed: {15} | DailyLimit: {16} | Response: {17}",
                                             lngOperatorId, strMemberCode, strCurrencyCode, strWithdrawAmount, strAccountName, strAccountNumber, strBankAddress, strBankBranch, strBankCode, strBankName, strBankNameInput, strMyKad, strMobileNumber, decMinLimit, decMaxLimit, decTotalAllowed, decDailyLimit, xeResponse == null ? string.Empty : xeResponse.ToString());

            intProcessSerialId += 1;
            commonAuditTrail.appendLog("system", strPageName, "InitiateWithdrawal", "DataBaseManager.DLL", strResultCode, strResultDetail, strErrorCode, strErrorDetail, strProcessRemark, Convert.ToString(intProcessSerialId), strProcessId, isSystemError);
        }
        #region Response
        txtMessage.InnerHtml = strAlertMessage.Replace("\\n", "<br />");
        #endregion

        #endregion

        if (sessionExpired)
        {
            Response.Redirect("/Expire");
        }
    }
Ejemplo n.º 46
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Get a reference to infrastructural services
                WorkflowServicesManager servicesManager = null;

                try
                {
                    servicesManager = new WorkflowServicesManager(web.Context, web);
                }
                catch (ServerException)
                {
                    // If there is no workflow service present in the farm this method will throw an error.
                    // Swallow the exception
                }

                if (servicesManager != null)
                {
                    var deploymentService   = servicesManager.GetWorkflowDeploymentService();
                    var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

                    // Pre-load useful properties
                    web.EnsureProperty(w => w.Id);

                    // Provision Workflow Definitions
                    foreach (var templateDefinition in template.Workflows.WorkflowDefinitions)
                    {
                        // Load the Workflow Definition XAML
                        Stream xamlStream             = template.Connector.GetFileStream(templateDefinition.XamlPath);
                        System.Xml.Linq.XElement xaml = System.Xml.Linq.XElement.Load(xamlStream);

                        int retryCount    = 5;
                        int retryAttempts = 1;
                        int delay         = 2000;

                        while (retryAttempts <= retryCount)
                        {
                            try
                            {
                                // Create the WorkflowDefinition instance
                                Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition workflowDefinition =
                                    new Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition(web.Context)
                                {
                                    AssociationUrl          = templateDefinition.AssociationUrl,
                                    Description             = templateDefinition.Description,
                                    DisplayName             = templateDefinition.DisplayName,
                                    FormField               = templateDefinition.FormField,
                                    DraftVersion            = templateDefinition.DraftVersion,
                                    Id                      = templateDefinition.Id,
                                    InitiationUrl           = templateDefinition.InitiationUrl,
                                    RequiresAssociationForm = templateDefinition.RequiresAssociationForm,
                                    RequiresInitiationForm  = templateDefinition.RequiresInitiationForm,
                                    RestrictToScope         = parser.ParseString(templateDefinition.RestrictToScope),
                                    RestrictToType          = templateDefinition.RestrictToType != "Universal" ? templateDefinition.RestrictToType : null,
                                    Xaml                    = parser.ParseString(xaml.ToString()),
                                };

                                //foreach (var p in definition.Properties)
                                //{
                                //    workflowDefinition.SetProperty(p.Key, parser.ParseString(p.Value));
                                //}

                                // Save the Workflow Definition
                                var newDefinition = deploymentService.SaveDefinition(workflowDefinition);
                                //web.Context.Load(workflowDefinition); //not needed
                                web.Context.ExecuteQueryRetry();

                                // Let's publish the Workflow Definition, if needed
                                if (templateDefinition.Published)
                                {
                                    deploymentService.PublishDefinition(newDefinition.Value);
                                    web.Context.ExecuteQueryRetry();
                                }

                                break; // no errors so exit loop
                            }
                            catch (Exception ex)
                            {
                                // check exception is due to connection closed issue
                                if (ex is ServerException && ((ServerException)ex).ServerErrorCode == -2130575223 &&
                                    ((ServerException)ex).ServerErrorTypeName.Equals("Microsoft.SharePoint.SPException", StringComparison.InvariantCultureIgnoreCase) &&
                                    ((ServerException)ex).Message.Contains("A connection that was expected to be kept alive was closed by the server.")
                                    )
                                {
                                    WriteWarning(String.Format("Connection closed whilst adding Workflow Definition, trying again in {0}ms", delay), ProvisioningMessageType.Warning);

                                    Thread.Sleep(delay);

                                    retryAttempts++;
                                    delay = delay * 2; // double delay for next retry
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                    }


                    // get existing subscriptions
                    var existingWorkflowSubscriptions = web.GetWorkflowSubscriptions();

                    foreach (var subscription in template.Workflows.WorkflowSubscriptions)
                    {
                        Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription = null;

                        // Check if the subscription already exists before adding it, and
                        // if already exists a subscription with the same name and with the same DefinitionId,
                        // it is a duplicate and we just need to update it
                        string subscriptionName;
                        if (subscription.PropertyDefinitions.TryGetValue("SharePointWorkflowContext.Subscription.Name", out subscriptionName) &&
                            existingWorkflowSubscriptions.Any(s => s.PropertyDefinitions["SharePointWorkflowContext.Subscription.Name"] == subscriptionName && s.DefinitionId == subscription.DefinitionId))
                        {
                            // Thus, delete it before adding it again!
                            WriteWarning(string.Format("Workflow Subscription '{0}' already exists. It will be updated.", subscription.Name), ProvisioningMessageType.Warning);
                            workflowSubscription = existingWorkflowSubscriptions.FirstOrDefault((s => s.PropertyDefinitions["SharePointWorkflowContext.Subscription.Name"] == subscriptionName && s.DefinitionId == subscription.DefinitionId));

                            if (workflowSubscription != null)
                            {
                                subscriptionService.DeleteSubscription(workflowSubscription.Id);
                                web.Context.ExecuteQueryRetry();
                            }
                        }

#if ONPREMISES
                        // Create the WorkflowDefinition instance
                        workflowSubscription =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                        {
                            DefinitionId  = subscription.DefinitionId,
                            Enabled       = subscription.Enabled,
                            EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                            EventTypes    = subscription.EventTypes,
                            ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
                            Name            = subscription.Name,
                            StatusFieldName = subscription.StatusFieldName,
                        };
#else
                        // Create the WorkflowDefinition instance
                        workflowSubscription =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                        {
                            DefinitionId  = subscription.DefinitionId,
                            Enabled       = subscription.Enabled,
                            EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                            EventTypes    = subscription.EventTypes,
                            ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
                            Name = subscription.Name,
                            ParentContentTypeId = subscription.ParentContentTypeId,
                            StatusFieldName     = subscription.StatusFieldName,
                        };
#endif

                        if (workflowSubscription != null)
                        {
                            foreach (var propertyDefinition in subscription.PropertyDefinitions
                                     .Where(d => d.Key == "TaskListId" ||
                                            d.Key == "HistoryListId" ||
                                            d.Key == "SharePointWorkflowContext.Subscription.Id" ||
                                            d.Key == "SharePointWorkflowContext.Subscription.Name" ||
                                            d.Key == "CreatedBySPD"))
                            {
                                workflowSubscription.SetProperty(propertyDefinition.Key, parser.ParseString(propertyDefinition.Value));
                            }
                            if (!String.IsNullOrEmpty(subscription.ListId))
                            {
                                // It is a List Workflow
                                Guid targetListId = Guid.Parse(parser.ParseString(subscription.ListId));
                                subscriptionService.PublishSubscriptionForList(workflowSubscription, targetListId);
                            }
                            else
                            {
                                // It is a Site Workflow
                                subscriptionService.PublishSubscription(workflowSubscription);
                            }
                            web.Context.ExecuteQueryRetry();
                        }
                    }
                }
            }

            return(parser);
        }