コード例 #1
0
        /// <summary>
        /// <para>eng - Mark a label in code (like ":Label"). Create a new label if don't exist.</para>
        /// <para>pt-Br - Gera um label no código (":meuLabel"). Cria um novo label se não existe.</para>
        /// </summary>
        /// <param name="name">
        /// <para>eng - Label name.</para>
        /// <para>pt-Br - Nome do label.</para>
        /// </param>
        /// <returns></returns>
        public ILHelper MarkLabel(string name)
        {
            if (m_Labels.IsNull() || !m_Labels.ContainsKey(name))
            {
                CreateLabel(name);
            }

            Label label = m_Labels[name];

            this.m_il.MarkLabel(label);
            return(this);
        }
コード例 #2
0
 private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     //遍历连接池,发送心跳信息
     if (!AllConnectionKey.IsNull() && AllConnectionKey.Count() > 0)
     {
         foreach (var item in AllConnectionKey)
         {
             if (!item.Value.IsNull())
             {
                 SendHeartbeat(item);
             }
         }
     }
 }
コード例 #3
0
        public bool AddToConnectionList(SqlConnection connection)
        {
            if (connection.IsNull())
            {
                return(false);
            }

            if (connectionList.IsNull())
            {
                return(false);
            }

            connectionList.Add($"{Guid.NewGuid()}", connection);
            return(true);
        }
コード例 #4
0
        public int Update()
        {
            if (mWorkers.IsNull())
            {
                return(0);
            }
            if (mWorkers.Count < 1)
            {
                return(0);
            }
            var time         = Time.time;
            var delta        = time - mLastUpdated;
            var isOverUpdate = delta < 0.001;

            if (isOverUpdate && time > 1)
            {
                Debug.LogWarning("同一フレームで過剰な更新が行われています");
            }
            for (int i = 0; i < mWorkers.Count; i++)
            {
                mWorkers [i].Execute();
            }
            mLastUpdated = time;
            return(mWorkers.Count - mRestingWorker.Count);
        }
コード例 #5
0
        public static Dictionary <K, V> AddRange <K, V>(this Dictionary <K, V> self,
                                                        Dictionary <K, V> sourceDic,
                                                        bool isOverride = false)
        {
            if (self.IsNull())
            {
                Log.W(typeof(List), "Dictionary is null");
            }
            else
            {
                if (sourceDic.IsEmptyOrNull())
                {
                    Log.W(typeof(List), "Dictionary is null");
                    return(self);
                }

                foreach (KeyValuePair <K, V> item in sourceDic)
                {
                    if (self.ContainsKey(item.Key))
                    {
                        if (isOverride)
                        {
                            self[item.Key] = item.Value;
                        }
                    }
                    else
                    {
                        self.Add(item.Key, item.Value);
                    }
                }
            }

            return(self);
        }
コード例 #6
0
        public void SaveActivityLogToCache(ActivityLog activityLog)
        {
            string cacheKey = string.Format("UserSessionActivity.{0}.{1}", WebHelper.GetUserName(), HttpContext.Current.Session.SessionID);

            Dictionary <string, object> cachedObject = this.cacheManager.Get(cacheKey) as Dictionary <string, object>;

            if (cachedObject.IsNull())
            {
                this.logger.Error("The session summary data could not be found from cache");

                return;
            }

            List <ActivityLog> activityLogs = new List <ActivityLog>();

            if (cachedObject.ContainsKey("ActivityLogs"))
            {
                activityLogs = cachedObject["ActivityLogs"] as List <ActivityLog>;

                if (activityLogs.IsNull())
                {
                    this.logger.Error("The activity logs could not be found from cached session summary");

                    return;
                }

                activityLog.ActivityLogType = this.FindActivityTypeById(activityLog.ActivityLogTypeId);
                activityLogs.Add(activityLog);
            }
        }
コード例 #7
0
        public void CreateDictionaryForThirdParty(ref Dictionary <string, object> dicThirdParty, ThirdPartySchedule objThirdPartySchedule)
        {
            if (objThirdPartySchedule.IsNull())
            {
                throw new ArgumentNullException();
            }

            if (dicThirdParty.IsNull())
            {
                dicThirdParty = new Dictionary <string, object>();
            }

            dicThirdParty.Add("IdEntidad", !objThirdPartySchedule.EntityId_RemitTo.IsNull() ?
                              objThirdPartySchedule.EntityId_RemitTo.Value : -1);
            dicThirdParty.Add("NumeroCasoOrden", objThirdPartySchedule.TerminationOrderNumber);
            dicThirdParty.Add("NumeroParticipante", objThirdPartySchedule.OrderIdentifier);
            dicThirdParty.Add("TerminationFlag", objThirdPartySchedule.TerminationFlag.HasValue ?
                              objThirdPartySchedule.TerminationFlag.Value: false);
            dicThirdParty.Add("SinglePayment", objThirdPartySchedule.SinglePaymentAmount.Value);
            dicThirdParty.Add("FirstInstallmentAmount", !objThirdPartySchedule.FirstInstallmentAmount.IsNull() ?
                              objThirdPartySchedule.FirstInstallmentAmount.Value : 0);
            dicThirdParty.Add("SecondInstallmentAmount", !objThirdPartySchedule.SecondInstallmentAmount.IsNull() ?
                              objThirdPartySchedule.SecondInstallmentAmount.Value : 0);
            dicThirdParty.Add("FechaTerminacion", objThirdPartySchedule.TerminationDate.HasValue ?
                              objThirdPartySchedule.TerminationDate.Value.ToLongDateString() : string.Empty);
        }
コード例 #8
0
        public string RenderAnswerIgnoreDuplicates(Dictionary <string, string> renderedQuestionFields, out Dictionary <string, string> fieldDict)
        {
            fieldDict = new Dictionary <string, string>();

            if (this.Card.IsNull() || renderedQuestionFields.IsNull())
            {
                LogTo.Warning("Failed to Render because card was null");
                return(null);
            }

            var renderer = BuildIgnoreDuplicatesAnswerRenderer(renderedQuestionFields);

            if (renderer.IsNull())
            {
                LogTo.Error("Failed to Render because the attempt to BuildRenderer returned null");
                return(null);
            }

            fieldDict = RenderedFields;
            string output = renderer.Render(Card.Template.AnswerFormat, Card.Note.Fields);

            return(output
                   .FixMediaPaths(MediaPath)
                   .AddCss(Card.Note.NoteType.CSS)
                   .ReplaceWhitespace());
        }
コード例 #9
0
        /// <summary>
        /// Создать комманду для БД и при необходимости запустить
        /// </summary>
        /// <param name="connector">коннектор для БД</param>
        /// <param name="procedureFolder">Папка с файлом процедуры</param>
        /// <param name="procedureName">Имя процедуры (SQL файл)</param>
        /// <param name="doExecuteReader">Если True возвращает ридер из команды</param>
        /// <param name="parameters">Параметры в виде (ключ, объект) если null не добавляются</param>
        /// <returns>OleDbCommand команда или OleDbDataReader</returns>
        private object CreateCommand(AccessConnector connector,
                                     string procedureFolder,
                                     string procedureName,
                                     Dictionary <string, object> parameters = null,
                                     bool doExecuteReader = true)
        {
            OleDbCommand cmd = connector.GetCommand();

            cmd.CommandText = connector.GetStoreProcedure(procedureFolder, procedureName);

            if (!parameters.IsNull())
            {
                foreach (string key in parameters.Keys)
                {
                    cmd.Parameters.AddWithValue(key, parameters[key]);
                }
            }

            if (doExecuteReader)
            {
                return(cmd.ExecuteReader());
            }
            else
            {
                return(cmd);
            }
        }
コード例 #10
0
 /// <summary>
 /// Pass 'null' if your implementation does not have dynamic properties.
 /// Create a static method that returns a Dictionary with the names and types of dynamic properties you need.
 /// </summary>
 protected DynamicConfigurableObjectBase(Dictionary <string, Type> propertyNames)
 {
     if (propertyNames.IsNull())
     {
         PropertyNames = new Dictionary <string, Type>();
     }
     PropertyNames = propertyNames;
 }
コード例 #11
0
 private void NullCheck()
 {
     if (_m_dict.IsNull() || _m_keys.IsNull())
     {
         _m_dict = new Dictionary <TKey, TValue>();
         _m_keys = new List <TKey>();
     }
 }
コード例 #12
0
        public void CreateLog(Dictionary <string, string> caseToBeProcess, Payment paymentsToBeProcess)
        {
            if (caseToBeProcess.IsNull())
            {
                throw new ArgumentNullException();
            }

            XmlHelper.SerializeKeyValuePairs("VENDOR", caseToBeProcess);
        }
コード例 #13
0
        public static DbType GetDbType(Type appType)
        {
            if (typeMap.IsNull())
            {
                InitializeDbType();
            }
            DbType type = typeMap[appType];

            return(type.IsNull() ? DbType.AnsiString : type);
        }
コード例 #14
0
 private void ClearFontCache()
 {
     if (!_fontCache.IsNull())
     {
         foreach (string key in _fontCache.Keys)
         {
             _fontCache[key].Dispose();
         }
         _fontCache.Clear();
     }
 }
コード例 #15
0
        public static string CreateBrowserPreviewFields(Dictionary <string, string> fieldDict)
        {
            if (fieldDict.IsNull() || !fieldDict.Any())
            {
                return(string.Empty);
            }

            return(String.Join("\n", fieldDict
                               .Where(x => !x.Value.IsNullOrEmpty())
                               .Select(x => x.Key + ": " + x.Value)));
        }
コード例 #16
0
ファイル: Examples.cs プロジェクト: yojimbo87/dictator
        public static void NullTypeCheckOperations()
        {
            var document = new Dictionary <string, object>()
                           .Object("foo", null)
                           .Int("bar", 12345);

            // true
            var isNull = document.IsNull("foo");
            // true
            var isNotNull = document.IsNotNull("bar");
            // false
            var isNull2 = document.IsNull("nonExistingField");
            // false
            var isNotNull2 = document.IsNotNull("nonExistingField");

            Console.WriteLine(isNull);
            Console.WriteLine(isNotNull);
            Console.WriteLine(isNull2);
            Console.WriteLine(isNotNull2);
        }
コード例 #17
0
        public static IQueryable <T> ApplySoft <T>(this IQueryable <T> source, string orderBy,
                                                   Dictionary <string, PropertyMappingValue> mappingDictionary)
        {
            if (source.IsNull())
            {
                throw new ArgumentException("Source");
            }

            if (mappingDictionary.IsNull())
            {
                throw new ArgumentException("MappingDcitionary");
            }

            if (orderBy.IsEmpty())
            {
                return(source);
            }

            var orderByAfterSplit = orderBy.Split(",");

            foreach (var orderByClause in orderByAfterSplit.Reverse())
            {
                var trimmedOrderByClause = orderBy.Trim();

                var orderDescending = trimmedOrderByClause.EndsWith(" desc", StringComparison.Ordinal);

                var indexOffFirstSpace = trimmedOrderByClause.IndexOf(" ", StringComparison.Ordinal);
                var propertyName       = indexOffFirstSpace == -1 ? trimmedOrderByClause : trimmedOrderByClause.Remove(indexOffFirstSpace);

                if (!mappingDictionary.ContainsKey(propertyName))
                {
                    throw new ArgumentException($"Key mapping for {propertyName} is missing");
                }

                var propertyMappingValue = mappingDictionary[propertyName];

                if (propertyMappingValue.IsNull())
                {
                    throw new ArgumentException("PropertyMappingValue");
                }

                foreach (var destinationProperty in propertyMappingValue.DestinationProperties.Reverse())
                {
                    if (propertyMappingValue.Revert)
                    {
                        orderDescending = !orderDescending;
                    }
                    source = source.OrderBy(destinationProperty + (orderDescending ? " descending" : " ascending"));
                }
            }

            return(source);
        }
コード例 #18
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="url"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        internal async Task <string> PostAsync(string url, Dictionary <string, string> model = null)
        {
            if (model.IsNull())
            {
                model = new Dictionary <string, string>();
            }

            model.Add("APIKey", SendloopInfo.ApiKey);
            var res = await url.PostAsync(new FormUrlEncodedContent( model ));

            return(await res.Content.ReadAsStringAsync());
        }
コード例 #19
0
 internal static IInterceptor GetInstance(Type reletedType)
 {
     if (_instances.IsNull())
     {
         _instances = new Dictionary <Type, IInterceptor>();
     }
     if (!_instances.ContainsKey(reletedType))
     {
         Type generic = typeof(CollectionInterceptor <>).MakeGenericType(reletedType);
         _instances.Add(reletedType, Activator.CreateInstance(generic) as IInterceptor);
     }
     return(_instances[reletedType] as IInterceptor);
 }
コード例 #20
0
 protected virtual void PrepareCommandParameter(
     IDbCommand command,
     string cmdText,
     Dictionary <string, object> parameters)
 {
     if (parameters.IsNull() || parameters.Count.IsZero())
     {
         return;
     }
     IDbDataParameter[] commandParameters = command.CommandType != CommandType.StoredProcedure ? GetSpParameterSet(command, cmdText, parameters) : GetSpParameterSet(ConnectionString, cmdText);
     AssignParameterValues(commandParameters, parameters);
     AttachParameters(command, commandParameters);
 }
コード例 #21
0
        private void MapVendor(ref Dictionary <string, string> dicVendor, CaseDetail caseTobeProcess)
        {
            if (dicVendor.IsNull())
            {
                dicVendor = new Dictionary <string, string>();
            }

            if (caseTobeProcess.IsNull())
            {
                throw new ArgumentNullException();
            }

            dicVendor.Add("FUNCTION", "ZFI_VENDOR_CREATION");
            dicVendor.Add("IM_INTERFACE_CODE", "ITF_VENDOR");
            dicVendor.Add("IM_FLAT_FILE_FLAG", "N");
            dicVendor.Add("TABLE", "TBL_SOURCE_DATA");
            dicVendor.Add("LIFNR", String.Format("{0}{1}", caseTobeProcess.CaseNumber, caseTobeProcess.CaseKey));
            dicVendor.Add("BUKRS", "1000");
            dicVendor.Add("KTOKK", caseTobeProcess.Entity.ParticipantType.ParticipantType1.ToUpper().Equals("ABOGADO", StringComparison.InvariantCultureIgnoreCase) ? "ZABO" : "ZCOM");
            dicVendor.Add("NAME1", caseTobeProcess.Entity.FirstName);
            dicVendor.Add("NAME2", caseTobeProcess.Entity.MiddleName);
            dicVendor.Add("LNAME1", caseTobeProcess.Entity.LastName);
            dicVendor.Add("LNAME2", caseTobeProcess.Entity.SecondLastName);
            dicVendor.Add("SORT1", caseTobeProcess.Entity.ParticipantType.ParticipantType1.ToUpper().Equals("ABOGADO", StringComparison.InvariantCultureIgnoreCase) ? "HONORARIOS" : "COMPENSACIONES");

            var currentAddress = caseTobeProcess.Entity.Addresses.Where(a => a.AddressType.AddressType1.ToUpper().Equals("POSTAL", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

            dicVendor.Add("STREET", currentAddress.IsNull() ? string.Empty : currentAddress.Line1);
            dicVendor.Add("STR_SUPPL1", currentAddress.IsNull() ? string.Empty : currentAddress.Line2);
            dicVendor.Add("CITY", currentAddress.IsNull() ? string.Empty : (currentAddress.City.IsNull() ? string.Empty : currentAddress.City.City1));
            dicVendor.Add("ZIP_CODE", currentAddress.IsNull() ? string.Empty : currentAddress.ZipCode);
            dicVendor.Add("COUNTRY", currentAddress.IsNull() ? string.Empty : (currentAddress.Country.IsNull() ? string.Empty : currentAddress.Country.Country1));
            dicVendor.Add("REGION", currentAddress.IsNull() ? string.Empty : (currentAddress.State.IsNull() ? string.Empty : currentAddress.State.State1));
            dicVendor.Add("LANGU", "E");
            dicVendor.Add("AKONT", caseTobeProcess.Entity.ParticipantType.ParticipantType1.ToUpper().Equals("ABOGADO", StringComparison.InvariantCultureIgnoreCase) ? "2030050090" : "2010010010");
            dicVendor.Add("ZTERM", "0001");
            dicVendor.Add("ZWELS", "0001");

            var currentPhone = caseTobeProcess.Entity.Phones.Where(p => !p.PhoneNumber.IsNullOrEmpty()).FirstOrDefault();

            dicVendor.Add("TEL_NUMBER", currentPhone.IsNull() ? string.Empty : currentPhone.PhoneNumber);
            dicVendor.Add("STCD1", "580000001");
            dicVendor.Add("WAERS", "USD");
            dicVendor.Add("WITHT", caseTobeProcess.Entity.ParticipantType.ParticipantType1.ToUpper().Equals("ABOGADO", StringComparison.InvariantCultureIgnoreCase) ? "A7" : string.Empty);
            dicVendor.Add("WT_WITHCD", caseTobeProcess.Entity.ParticipantType.ParticipantType1.ToUpper().Equals("ABOGADO", StringComparison.InvariantCultureIgnoreCase) ? "07" : string.Empty);
            dicVendor.Add("QLAND", caseTobeProcess.Entity.ParticipantType.ParticipantType1.ToUpper().Equals("ABOGADO", StringComparison.InvariantCultureIgnoreCase) ? "PR" : string.Empty);
            dicVendor.Add("WT_SUBJCT", caseTobeProcess.Entity.ParticipantType.ParticipantType1.ToUpper().Equals("ABOGADO", StringComparison.InvariantCultureIgnoreCase) ? "X" : string.Empty);
            dicVendor.Add("Birthdate", caseTobeProcess.Entity.BirthDate.HasValue ? caseTobeProcess.Entity.BirthDate.Value.ToString("YYYYMMDD") : string.Empty);
            dicVendor.Add("DeadDate", caseTobeProcess.Entity.DeceaseDate.HasValue ? caseTobeProcess.Entity.DeceaseDate.Value.ToString("YYYYMMDD") : string.Empty);
            dicVendor.Add("Gender", caseTobeProcess.Entity.Gender.IsNull() ? "U" : caseTobeProcess.Entity.Gender.GenderCode);
        }
コード例 #22
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="url"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        internal async Task <TResult> PostAsync <TResult>(string url, Dictionary <string, string> model = null)
        {
            if (model.IsNull())
            {
                model = new Dictionary <string, string>();
            }

            model.Add("APIKey", SendloopInfo.ApiKey);
            var res = await url.PostAsync(new FormUrlEncodedContent( model ));

            var content = await res.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <TResult>(content));
        }
コード例 #23
0
        public static bool HandleFieldArgumentsAreValid(Dictionary <string, string> input, string key)
        {
            if (input.IsNull())
            {
                return(false);
            }

            if (key.IsNullOrEmpty())
            {
                return(false);
            }

            return(true);
        }
コード例 #24
0
        /// <summary>
        /// Gets an SQL query or statement by the token for the SQL agent specified.
        /// </summary>
        /// <param name="token">a token (key, name) of the requested query or statement</param>
        /// <param name="sqlAgent">an SQL agent for which the SQL query or statement is meant for</param>
        /// <exception cref="ArgumentNullException">Parameters token or sqlAgent are not specified.</exception>
        /// <exception cref="FileNotFoundException">No repository files found or they contain no data
        /// for the SQL agent type specified.</exception>
        /// <exception cref="InvalidDataException">Failed to load SQL repository file due to bad format or duplicate query tokens.</exception>
        /// <exception cref="InvalidOperationException">SQL query token is unknown or SQL query dictionary is not available for the SQL implementation.</exception>
        public string GetSqlQuery(string token, ISqlAgent sqlAgent)
        {
            if (token.IsNullOrWhiteSpace())
            {
                throw new ArgumentNullException(nameof(token));
            }
            if (sqlAgent.IsNull())
            {
                throw new ArgumentNullException(nameof(sqlAgent));
            }

            if (_tokenDictionary.IsNull())
            {
                lock (_dictLock)
                {
                    if (_tokenDictionary.IsNull())
                    {
                        Initialize();
                    }
                }
            }

            if (!_tokenDictionary.ContainsKey(sqlAgent.SqlImplementationId))
            {
                throw new InvalidOperationException(string.Format(Properties.Resources.SqlDictionaryNotAvailableException,
                                                                  sqlAgent.Name));
            }

            var dictionaryForSqlAgent = _tokenDictionary[sqlAgent.SqlImplementationId];

            if (!dictionaryForSqlAgent.ContainsKey(token.Trim()))
            {
                throw new InvalidOperationException(string.Format(Properties.Resources.SqlDictionary_UnknownSqlQueryToken, token));
            }

            return(dictionaryForSqlAgent[token.Trim()]);
        }
コード例 #25
0
        public static Dictionary <K, V> ForEach <K, V>(this Dictionary <K, V> self, Action <K, V> action)
        {
            if (self.IsNull())
            {
                Log.W(typeof(List), "Dictionary is null");
            }
            else
            {
                foreach (KeyValuePair <K, V> item in self)
                {
                    action(item.Key, item.Value);
                }
            }

            return(self);
        }
コード例 #26
0
        /// <summary>
        /// Returns a string that represents the current HtmlChunk.
        /// </summary>
        public override string ToString()
        {
            switch (Type)
            {
            case HtmlChunkType.Text:
                return("Text (length = {0})".FormatWith(this.Text.Length));

            case HtmlChunkType.Tag:
                return("Tag ({0}, name = '{1}', parameters: {2})".FormatWith(
                           TagType,
                           TagName,
                           parameters.IsNull() ? 0 : parameters.Count));

            default:
                return(Type.ToString());
            }
        }
コード例 #27
0
        private SapTransaction GenerateSapTransactionLog(Dictionary <string, string> caseToBeProcess, Dictionary <string, string> paymentToBeProcess, Dictionary <string, string> paymentDocToBeProcess)
        {
            if (caseToBeProcess.IsNull())
            {
                throw new ArgumentNullException();
            }

            string log = XmlHelper.SerializeKeyValuePairs("VENDOR", caseToBeProcess);

            return(new SapTransaction {
                TransactionDetail = log,
                CreatedBy = "SAP Interface",
                CreatedDateTime = DateTime.UtcNow,
                ModifiedBy = "SAP Interface",
                ModifiedDateTime = DateTime.UtcNow
            });
        }
コード例 #28
0
        public HtmlChunk(string tagName, HtmlTagType tagType, Dictionary <string, string> parameters = null)
            : this()
        {
            this.Type = HtmlChunkType.Tag;

            this.TagName    = tagName;
            this.TagType    = tagType;
            this.parameters = parameters;

            this.Html =
                '<' +
                (tagType == HtmlTagType.Close ? "/" : "") +
                tagName +
                (parameters.IsNull() ? "" : ' ' + parameters.Aggregate(kvp => "{0}=\"{1}\"".FormatWith(kvp.Key, kvp.Value), " ")) +
                (tagType == HtmlTagType.SelfClose ? "/" : "") +
                '>';
        }
コード例 #29
0
        /// <summary>
        /// 易宝异步返回
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public YBResponsePara YBCallBack(HttpContext context)
        {
            YBResponsePara result = new YBResponsePara()
            {
                isPaySuccess = false,
                orderNumber  = "",
                paymentMoney = 0,
                resultMsg    = ""
            };

            try
            {
                if (context.Request["data"].IsNull() ||
                    context.Request["encryptkey"].IsNull())
                {
                    result.resultMsg = "回调参数不正确";
                    return(result);
                }
                //回调中的参数data
                string data = context.Request["data"].ToString();
                //回调中的参数encryptkey
                string encryptkey = context.Request["encryptkey"].ToString();
                //解密易宝支付回调结果
                string callback_result = YJPayUtil.checkYbCallbackResult(data, encryptkey);
                if (callback_result != "验签未通过")
                {
                    //string descstring = AES.Decrypt(data, APIURLConfig.merchantAesKey);
                    Dictionary <string, object> responsePara = callback_result.JsonToDocument <Dictionary <string, object> >();

                    if (!responsePara.IsNull())
                    {
                        result.isPaySuccess = true;
                        result.paymentMoney = AlipayConfig.MoneyFormatDco(responsePara["amount"].ToString());
                        result.orderNumber  = responsePara["orderid"].ToString();
                        result.resultMsg    = "返回成功";
                    }
                }
            }
            catch (Exception err)
            {
                result.resultMsg = err.Message;
            }

            return(result);
        }
コード例 #30
0
        /// <summary>
        /// Basically strips everything between the start marker and the end marker
        /// The start marker is the Key in the Dictionary<string, string>, the end marker is the Value
        /// </summary>
        /// <param name="rules">
        /// </param>
        /// <param name="content">
        /// </param>
        /// <returns>
        /// </returns>
        private static string StripByRules(Dictionary <string, string> rules, string content)
        {
            if (rules.IsNull() || content.IsNullOrEmpty())
            {
                return(content);
            }

            foreach (var k in rules)
            {
                var key     = Regex.Escape(k.Key);
                var value   = Regex.Escape(k.Value);
                var pattern = "({0})(.*?)({1})".FormatWith(key, value);
                const RegexOptions options = RegexOptions.IgnoreCase |
                                             RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled;
                content = Regex.Replace(content, pattern, string.Empty, options);
            }

            return(content);
        }
コード例 #31
0
ファイル: LuaHelper.cs プロジェクト: Schumix/Schumix2
        /// <summary>
        /// Registers Lua functions found in the specified target.
        /// </summary>
        /// <param name="luaFunctions">Global lua function table.</param>
        /// <param name="target">Object (class,struct) to search in.</param>
        /// <param name="vm">The Lua virtual machine.</param>
        public static void RegisterLuaFunctions(Lua vm, ref Dictionary<string, LuaFunctionDescriptor> luaFunctions, object target)
        {
            if(vm.IsNull() || luaFunctions.IsNull())
                return;

            var type = target.GetType();

            foreach(var method in type.GetMethods())
            {
                foreach(var attribute in Attribute.GetCustomAttributes(method))
                {
                    var attr = attribute as LuaFunctionAttribute;

                    if(attr.IsNull())
                        continue;

                    var parameters = new List<string>();
                    var paramInfo = method.GetParameters();

                    if(!attr.FunctionParameters.IsNull() && paramInfo.Length != attr.FunctionParameters.Length)
                    {
                        Log.Error("LuaHelper", sLConsole.GetString("Function {0} (exported as {1}): argument number mismatch. Declared {2}, but requires {3}!"), method.Name, attr.FunctionName,
                            attr.FunctionParameters.Length, paramInfo.Length);
                        break;
                    }

                    // build parameter doc hashtable.
                    if(!attr.FunctionParameters.IsNull())
                        parameters.AddRange(paramInfo.Select((t, i) => string.Format("{0} - {1}", t.Name, attr.FunctionParameters[i])));

                    var descriptor = new LuaFunctionDescriptor(attr.FunctionName, attr.FunctionDocumentation, parameters);
                    luaFunctions.Add(attr.FunctionName, descriptor);
                    vm.RegisterFunction(attr.FunctionName, target, method);
                }
            }
        }
コード例 #32
0
        public void SetLinkTag(Dictionary<string, string> attributes)
        {
            if (attributes.IsNull())
            {
                throw new ArgumentNullException();
            }

            var linkElement = Document.CreateElement(TagNames.LinkTagName);
            foreach (KeyValuePair<string, string> attribute in attributes)
            {
                linkElement.SetAttribute(attribute.Key, attribute.Value);
            }

            var bodyElement = GetElementsByTagName(TagNames.BodyTagName)[0];
            bodyElement.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeBegin, linkElement);
        }
コード例 #33
0
ファイル: ContentCrawlerRules.cs プロジェクト: fzhenmei/study
        /// <summary>
        /// Basically strips everything between the start marker and the end marker
        /// The start marker is the Key in the Dictionary<string, string>, the end marker is the Value
        /// </summary>
        /// <param name="rules">
        /// </param>
        /// <param name="content">
        /// </param>
        /// <returns>
        /// </returns>
        private static string StripByRules(Dictionary<string, string> rules, string content)
        {
            if (rules.IsNull() || content.IsNullOrEmpty())
            {
                return content;
            }

            foreach (KeyValuePair<string, string> k in rules)
            {
                string key = Regex.Escape(k.Key);
                string value = Regex.Escape(k.Value);
                string pattern = "({0})(.*?)({1})".FormatWith(key, value);
                const RegexOptions options = RegexOptions.IgnoreCase |
                    RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled;
                content = Regex.Replace(content, pattern, string.Empty, options);
            }

            return content;
        }
コード例 #34
0
        public void SetBaseTag(Dictionary<string, string> attributes)
        {
            if (attributes.IsNull())
            {
                throw new ArgumentNullException();
            }

            var baseElement = Document.CreateElement(TagNames.BaseTagName);
            foreach (KeyValuePair<string, string> attribute in attributes)
            {
                baseElement.SetAttribute(attribute.Key, attribute.Value);
            }

            var headElement = GetElementsByTagName(TagNames.HeadTagName)[0];
            headElement.AppendChild(baseElement);
        }
コード例 #35
0
        public static void InsertHtml(HtmlEditingTool htmlEditingTool, string tagName, Dictionary<string, string> attributes)
        {
            if (htmlEditingTool.IsNull() ||
                tagName.IsNull() ||
                attributes.IsNull())
            {
                throw new ArgumentNullException();
            }

            if (htmlEditingTool.Mode == Enums.HtmlEditingToolMode.Preview)
            {
                throw new InvalidOperationException();
            }

            // Вставка html кода разрешена только при снятом выделении.
            if (htmlEditingTool.IsSelection)
            {
                return;
            }

            var htmlDocument = htmlEditingTool.GetNativeHtmlDocument();
            IHTMLTxtRange textRange;
            try
            {
                textRange = htmlDocument.selection.createRange() as IHTMLTxtRange;
            }
            catch
            {
                throw new InvalidOperationException();
            }

            if (textRange.IsNull())
            {
                throw new NullReferenceException();
            }

            var attrs = ConcatAttributes(attributes);
            var html = string.Concat("<", tagName, " ", attrs, ">");

            try
            {
                textRange.pasteHTML(html);
                textRange.collapse(false);
                textRange.select();
            }
            catch
            {
                throw new InvalidOperationException();
            }
        }
コード例 #36
0
        public static void DeleteSurroundWithHtml(HtmlEditingTool htmlEditingTool, string tagName, Dictionary<string, string> attributes)
        {
            if (htmlEditingTool.IsNull() ||
                tagName.IsNull() ||
                attributes.IsNull())
            {
                throw new ArgumentNullException();
            }

            if (htmlEditingTool.Mode == Enums.HtmlEditingToolMode.Preview)
            {
                throw new InvalidOperationException();
            }

            // Обрамление html кода разрешено только при наличии выделения.
            if (!htmlEditingTool.IsSelection)
            {
                return;
            }

            var htmlDocument = htmlEditingTool.GetNativeHtmlDocument();
            IHTMLTxtRange textRange;
            try
            {
                textRange = htmlDocument.selection.createRange() as IHTMLTxtRange;
            }
            catch
            {
                throw new InvalidOperationException();
            }

            if (textRange.IsNull())
            {
                throw new NullReferenceException();
            }

            var current = textRange.htmlText;
            var htmlText = textRange.htmlText;
            htmlText = string.Copy(htmlText);
            var htmlPaste = htmlText;
            string searchString1 = "<DIV";
            string searchString2 = "</DIV";
            while (htmlText.Contains(searchString1) && htmlText.Contains(searchString2))
            {
                int first = htmlText.IndexOf(searchString1);
                int second = htmlText.IndexOf(searchString2);
                if (first < second)
                {
                    int i = htmlPaste.IndexOf(searchString1);

                    string temp="";
                    string temp2 = "";
                    while(htmlPaste[i]!='>')
                    {

                        for(int j=0; j<htmlPaste.Length; j++)
                            if (j != i)
                            {
                                temp = string.Concat(temp, htmlPaste[j].ToString());
                                temp2 = string.Concat(temp2, htmlPaste[j].ToString());
                            }
                            else { temp2 = string.Concat(temp2, " "); }

                        htmlPaste = temp;
                        htmlText = temp2;
                        temp = "";
                        temp2 = "";

                    }
                    for (int j = 0; j < htmlPaste.Length; j++)
                        if (j != i) { temp = string.Concat(temp, htmlPaste[j].ToString()); }
                    htmlPaste = temp;

                    i = htmlPaste.IndexOf(searchString2);
                    temp = "";
                    for (int j = 0; j < htmlPaste.Length; j++)
                        if (j < i || j>(i+5)) { temp = string.Concat(temp, htmlPaste[j].ToString()); }
                    htmlPaste = temp;

                    i = htmlText.IndexOf(searchString2);
                    temp2 = "";
                    for (int j = 0; j < htmlText.Length; j++)
                        if (j < i || j > (i + 5)) { temp2 = string.Concat(temp2, htmlText[j].ToString()); }
                    htmlText = temp2;

                }
                else
                {
                    string temp2 = "";
                    for (int j = 0; j < htmlText.Length; j++)
                        if (j < second || j > (second + 5)) { temp2 = string.Concat(temp2, htmlText[j].ToString()); }
                    htmlText = temp2;
                }
            }
            try
            {
                textRange.pasteHTML(htmlPaste);
                textRange.collapse(false);
                textRange.select();
            }
            catch
            {
                throw new InvalidOperationException();
            }
        }
コード例 #37
0
        //моя функция для стилей
        public static void SurroundWithStyleHtml(HtmlEditingTool htmlEditingTool, string tagName, Dictionary<string, string> attributes)
        {
            if (htmlEditingTool.IsNull() ||
                tagName.IsNull() ||
                attributes.IsNull())
            {
                throw new ArgumentNullException();
            }

            if (htmlEditingTool.Mode == Enums.HtmlEditingToolMode.Preview)
            {
                throw new InvalidOperationException();
            }

            // Обрамление html кода разрешено только при наличии выделения.
            if (!htmlEditingTool.IsSelection)
            {
                return;
            }

            var htmlDocument = htmlEditingTool.GetNativeHtmlDocument();
            IHTMLTxtRange textRange;
            try
            {
                textRange = htmlDocument.selection.createRange() as IHTMLTxtRange;
            }
            catch
            {
                throw new InvalidOperationException();
            }

            if (textRange.IsNull())
            {
                throw new NullReferenceException();
            }

            var selection = textRange.htmlText;
               // var htmlText = textRange.htmlText;
            selection = string.Copy(selection);
               // var htmlPaste = htmlText;

             //   var selection = htmlEditingTool.GetSelection();
              //  selection = string.Copy(selection);

            if (selection.IsNull())
            {
                throw new NullReferenceException();
            }

            if (selection.StartsWith(" "))
            {
                selection = selection.Remove(0, 1);
                selection = string.Concat("&nbsp;", selection);
            }

            var attrs = ConcatAttributes(attributes);
            selection = string.Concat("<", tagName, " ", attrs, ">", selection, "</", tagName, ">");

            try
            {
                textRange.pasteHTML(selection);
                textRange.collapse(false);
                textRange.select();
            }
            catch
            {
                throw new InvalidOperationException();
            }
        }
コード例 #38
0
        private static string ConcatAttributes(Dictionary<string, string> attributes)
        {
            if (attributes.IsNull())
            {
                throw new ArgumentNullException();
            }

            var attrs = string.Empty;
            foreach (var attribute in attributes)
            {
                attrs += string.Concat(attribute.Key, "=\"", attribute.Value, "\" ");
            }

            return attrs;
        }