string.Concat(string, string, string)

Here are the examples of the csharp api string.Concat(string, string, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

589 Examples 7

19 View Source File : SerializationMaster.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

private static StageElement ReflectOut(string elementName, object item)
        {
            var itemType = item.GetType();
            var nameSplit = itemType.replacedemblyQualifiedName.Split(',');
            var element = new StageElement(elementName, new StageAttribute("type", string.Concat(nameSplit[0], ",", nameSplit[1]), true));

            var properties = from p in itemType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                             let attrib = p.GetAttribute<ApexSerializationAttribute>(true)
                             where attrib != null && p.CanRead && p.CanWrite && (attrib.excludeMask & _excludeMask) == 0
                             select new AIPropInfo
                             {
                                 prop = p,
                                 defaultValue = attrib.defaultValue
                             };

            foreach (var p in properties)
            {
                var val = p.prop.GetValue(item, null);
                if (val != null && !val.Equals(p.defaultValue))
                {
                    StageItem propElement;
                    if (TryStage(p.prop.Name, val, out propElement))
                    {
                        element.Add(propElement);
                    }
                }
            }

            var fields = from f in itemType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                         let attrib = f.GetAttribute<ApexSerializationAttribute>(false)
                         where attrib != null && (attrib.excludeMask & _excludeMask) == 0
                         select new AIFieldInfo
                         {
                             field = f,
                             defaultValue = attrib.defaultValue
                         };

            foreach (var f in fields)
            {
                var val = f.field.GetValue(item);
                if (val != null && !val.Equals(f.defaultValue))
                {
                    StageItem propElement;
                    if (TryStage(f.field.Name, val, out propElement))
                    {
                        element.Add(propElement);
                    }
                }
            }

            return element;
        }

19 View Source File : DebugLogEntry.cs
License : MIT License
Project Creator : ArcturusZhang

public override string ToString()
		{
			if( completeLog == null )
				completeLog = string.Concat( logString, "\n", stackTrace );

			return completeLog;
		}

19 View Source File : I360Render.cs
License : Apache License 2.0
Project Creator : allenai

private static byte[] DoTheHardWork_JPEG( byte[] fileBytes, int imageWidth, int imageHeight )
	{
		int xmpIndex = 0, xmpContentSize = 0;
		while( !SearchChunkForXMP_JPEG( fileBytes, ref xmpIndex, ref xmpContentSize ) )
		{
			if( xmpIndex == -1 )
				break;
		}

		int copyBytesUntil, copyBytesFrom;
		if( xmpIndex == -1 )
		{
			copyBytesUntil = copyBytesFrom = FindIndexToInsertXMPCode_JPEG( fileBytes );
		}
		else
		{
			copyBytesUntil = xmpIndex;
			copyBytesFrom = xmpIndex + 2 + xmpContentSize;
		}

		string xmpContent = string.Concat( XMP_NAMESPACE_JPEG, "\0", string.Format( XMP_CONTENT_TO_FORMAT_JPEG, 75f.ToString( "F1" ), imageWidth, imageHeight ) );
		int xmpLength = xmpContent.Length + 2;
		xmpContent = string.Concat( (char) 0xFF, (char) 0xE1, (char) ( xmpLength / 256 ), (char) ( xmpLength % 256 ), xmpContent );

		byte[] result = new byte[copyBytesUntil + xmpContent.Length + ( fileBytes.Length - copyBytesFrom )];

		Array.Copy( fileBytes, 0, result, 0, copyBytesUntil );

		for( int i = 0; i < xmpContent.Length; i++ )
		{
			result[copyBytesUntil + i] = (byte) xmpContent[i];
		}

		Array.Copy( fileBytes, copyBytesFrom, result, copyBytesUntil + xmpContent.Length, fileBytes.Length - copyBytesFrom );

		return result;
	}

19 View Source File : EpubAsArchive.cs
License : MIT License
Project Creator : AntonyCorbett

private string GetRootFilePath()
        {
            string result = null;

            var entryPath = string.Concat(MetaInfFolderName, "/", ContainerFileName);

            var x = GetXmlFile(entryPath, canCache: true);
            var attr = x?.Root?.Attribute("xmlns");
            if (attr != null)
            {
                XNamespace ns = attr.Value;

                var elements = (from item in x.Descendants(ns + "rootfile") select item).ToArray();
                if (elements.Length == 1)
                {
                    var path = elements[0].Attribute("full-path");
                    if (path != null)
                    {
                        // we replacedume that the content.opf file is in the same folder as the rest of the content
                        result = Path.GetDirectoryName(path.Value);
                    }
                }
            }

            return result;
        }

19 View Source File : SingleInstance.cs
License : GNU General Public License v3.0
Project Creator : Amebis

public static bool InitializeAsFirstInstance(string uniqueName)
        {
            commandLineArgs = GetCommandLineArgs(uniqueName);

            // Build unique application Id and the IPC channel name.
            string applicationIdentifier = uniqueName + Environment.UserName;

            string channelName = string.Concat(applicationIdentifier, Delimiter, ChannelNameSuffix);

            // Create mutex based on unique application Id to check if this is the first instance of the application. 
            singleInstanceMutex = new Mutex(true, applicationIdentifier, out bool firstInstance);
            if (firstInstance)
            {
                CreateRemoteService(channelName);
            }
            else
            {
                SignalFirstInstance(channelName, commandLineArgs);
            }

            return firstInstance;
        }

19 View Source File : DefaultSnapshotEventAdapter.cs
License : Apache License 2.0
Project Creator : AkkaNetContrib

protected virtual byte[] ToBytes(object @event, JObject metadata, out string type, out bool isJson)
        {
            var eventType = @event.GetType();
            isJson = true;
            type = eventType.Name.ToEventCase();
            var clrEventType = string.Concat(eventType.FullName, ", ", eventType.GetTypeInfo().replacedembly.GetName().Name);
            metadata[Constants.EventMetadata.ClrEventType] = clrEventType;

            return _serializer.ToBinary(@event);
        }

19 View Source File : Utility.cs
License : MIT License
Project Creator : aprilyush

private static object GetRenderInstance(string renderInstance)
        {
            if (string.IsNullOrEmpty(renderInstance)) return null;

            string[] k = renderInstance.Split(new char[] { ',' }, 2);
            if (k.Length != 2) return null;

            string replacedemblyKey = k[1].Trim();
            string typeKey = k[0].Trim();
            string cacheKey = string.Concat(typeKey, ",", replacedemblyKey);

            //从缓存读取
            object render;
            bool flag = false;
            lock (RenderInstanceCache)
            {
                flag = RenderInstanceCache.TryGetValue(cacheKey, out render);
            }
            if (!flag || render == null)
            {
                //重新生成实例
                render = null;
                //生成实例
                replacedembly replacedembly;
                if (replacedemblyKey.IndexOf(":") != -1)
                {
                    replacedembly = replacedembly.LoadFrom(replacedemblyKey);
                }
                else
                {
                    replacedembly = replacedembly.Load(replacedemblyKey);
                }
                if (replacedembly != null)
                {
                    render = replacedembly.CreateInstance(typeKey, false);
                }
                if (render != null)
                {
                    //缓存
                    lock (RenderInstanceCache)
                    {
                        if (RenderInstanceCache.ContainsKey(cacheKey))
                        {
                            RenderInstanceCache[cacheKey] = render;
                        }
                        else
                        {
                            RenderInstanceCache.Add(cacheKey, render);
                        }
                    }
                }
            }
            return render;
        }

19 View Source File : ThrottleAttribute.cs
License : MIT License
Project Creator : Adoxio

public override void OnActionExecuting(ActionExecutingContext executingContext)
        {
            var key = string.Concat(Name, "-", GetIpAddress());
            var countLock = new CountLock();
            var castLocked = HttpRuntime.Cache[key] as CountLock;

            if (castLocked != null && castLocked.IsLocked)
            {
                executingContext.Controller.ViewBag.Locked = true;
                executingContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
            }

            else
            {
                var cacheExperation = TimeLimit;
                countLock.Count = 1;
                countLock.IsLocked = false;

                if (castLocked != null)
                {
                    countLock.Count = castLocked.Count + 1;
                    if (countLock.Count > Attempts)
                    {
                        cacheExperation = TimeWait;
                        countLock.IsLocked = true;

                        executingContext.Controller.ViewBag.Locked = true;
                        executingContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
                    }
                }
                
                HttpRuntime.Cache.Insert(key,
                        countLock,
                        null,
                        DateTime.Now.AddMinutes(cacheExperation),
                        Cache.NoSlidingExpiration,
                        CacheItemPriority.Low, null);
            }
        }

19 View Source File : ChunkingCookieManager.cs
License : Apache License 2.0
Project Creator : aspnet

public void AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
            bool pathHasValue = !string.IsNullOrEmpty(options.Path);
            bool expiresHasValue = options.Expires.HasValue;
            bool sameSiteHasValue = options.SameSite.HasValue;

            string escapedKey = Uri.EscapeDataString(key);
            string prefix = escapedKey + "=";

            string suffix = string.Concat(
                !domainHasValue ? null : "; domain=",
                !domainHasValue ? null : options.Domain,
                !pathHasValue ? null : "; path=",
                !pathHasValue ? null : options.Path,
                !expiresHasValue ? null : "; expires=",
                !expiresHasValue ? null : options.Expires.Value.ToString("ddd, dd-MMM-yyyy HH:mm:ss \\G\\M\\T", CultureInfo.InvariantCulture),
                !options.Secure ? null : "; secure",
                !options.HttpOnly ? null : "; HttpOnly",
                !sameSiteHasValue ? null : "; SameSite=",
                !sameSiteHasValue ? null : GetStringRepresentationOfSameSite(options.SameSite.Value));

            value = value ?? string.Empty;
            bool quoted = false;
            if (IsQuoted(value))
            {
                quoted = true;
                value = RemoveQuotes(value);
            }
            string escapedValue = Uri.EscapeDataString(value);

            // Normal cookie
            IHeaderDictionary responseHeaders = context.Response.Headers;
            if (!ChunkSize.HasValue || ChunkSize.Value > prefix.Length + escapedValue.Length + suffix.Length + (quoted ? 2 : 0))
            {
                string setCookieValue = string.Concat(
                    prefix,
                    quoted ? Quote(escapedValue) : escapedValue,
                    suffix);
                responseHeaders.AppendValues(Constants.Headers.SetCookie, setCookieValue);
            }
            else if (ChunkSize.Value < prefix.Length + suffix.Length + (quoted ? 2 : 0) + 10)
            {
                // 10 is the minimum data we want to put in an individual cookie, including the cookie chunk identifier "CXX".
                // No room for data, we can't chunk the options and name
                throw new InvalidOperationException(Resources.Exception_CookieLimitTooSmall);
            }
            else
            {
                // Break the cookie down into multiple cookies.
                // Key = CookieName, value = "Segment1Segment2Segment2"
                // Set-Cookie: CookieName=chunks:3; path=/
                // Set-Cookie: CookieNameC1="Segment1"; path=/
                // Set-Cookie: CookieNameC2="Segment2"; path=/
                // Set-Cookie: CookieNameC3="Segment3"; path=/
                int dataSizePerCookie = ChunkSize.Value - prefix.Length - suffix.Length - (quoted ? 2 : 0) - 3; // Budget 3 chars for the chunkid.
                int cookieChunkCount = (int)Math.Ceiling(escapedValue.Length * 1.0 / dataSizePerCookie);

                responseHeaders.AppendValues(Constants.Headers.SetCookie, prefix + "chunks:" + cookieChunkCount.ToString(CultureInfo.InvariantCulture) + suffix);
                
                string[] chunks = new string[cookieChunkCount];
                int offset = 0;
                for (int chunkId = 1; chunkId <= cookieChunkCount; chunkId++)
                {
                    int remainingLength = escapedValue.Length - offset;
                    int length = Math.Min(dataSizePerCookie, remainingLength);
                    string segment = escapedValue.Substring(offset, length);
                    offset += length;

                    chunks[chunkId - 1] = string.Concat(
                                            escapedKey,
                                            "C",
                                            chunkId.ToString(CultureInfo.InvariantCulture),
                                            "=",
                                            quoted ? "\"" : string.Empty,
                                            segment,
                                            quoted ? "\"" : string.Empty,
                                            suffix);
                }
                responseHeaders.AppendValues(Constants.Headers.SetCookie, chunks);
            }
        }

19 View Source File : MessagePayloadSerializerFactory.cs
License : MIT License
Project Creator : Adyen

private string CreateMessagePayloadFullName(string messageCategory, string messageType)
        {
            var nameSpaceSeparator = ".";

            var messagePayloadName = messageCategory.ToString() + messageType;
            var nexoDomainNameSpace = typeof(PaymentRequest).Namespace;

            return string.Concat(nexoDomainNameSpace, nameSpaceSeparator, messagePayloadName);
        }

19 View Source File : AuthenticationClient.cs
License : MIT License
Project Creator : anthonyreilly

public async Task UsernamePreplacedwordAsync(string clientId, string clientSecret, string username, string preplacedword, string tokenRequestEndpointUrl)
        {
#if DEBUG
            Stopwatch sw = new Stopwatch();
            sw.Start();
#endif
            if (string.IsNullOrEmpty(clientId)) throw new ArgumentNullException("clientId", "Client ID is null or empty");
            if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException("clientSecret", "Client Secret is null or empty");
            if (string.IsNullOrEmpty(username)) throw new ArgumentNullException("username", "Username is null or empty");
            if (string.IsNullOrEmpty(preplacedword)) throw new ArgumentNullException("preplacedword", "Preplacedword is null or empty");
            if (string.IsNullOrEmpty(tokenRequestEndpointUrl)) throw new ArgumentNullException("tokenRequestEndpointUrl", "Token Request Endpoint is null or empty");
            if (!Uri.IsWellFormedUriString(tokenRequestEndpointUrl, UriKind.Absolute)) throw new FormatException("Invalid tokenRequestEndpointUrl");

            var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("grant_type", "preplacedword"),
                    new KeyValuePair<string, string>("client_id", clientId),
                    new KeyValuePair<string, string>("client_secret", clientSecret),
                    new KeyValuePair<string, string>("username", username),
                    new KeyValuePair<string, string>("preplacedword", preplacedword)
                });

            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(tokenRequestEndpointUrl),
                Content = content
            };

            request.Headers.UserAgent.ParseAdd(string.Concat(UserAgent, "/", ApiVersion));

            var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);
            var response = await responseMessage.Content.ReadreplacedtringAsync().ConfigureAwait(false);

            if (responseMessage.IsSuccessStatusCode)
            {
                this.AccessInfo = JsonConvert.DeserializeObject<AccessTokenResponse>(response);
            }
            else if (responseMessage.StatusCode == HttpStatusCode.NotFound)
            {
                // Unable to reach the auth/token url
                throw new ForceAuthException(Error.Unknown.ToString(), "Error reaching Login URL", responseMessage.StatusCode);
            }
            else
            {
                var errorResponse = JsonConvert.DeserializeObject<AuthErrorResponse>(response);
                throw new ForceAuthException(errorResponse.Error, errorResponse.ErrorDescription, responseMessage.StatusCode);
            }
#if DEBUG
            sw.Stop();
            Debug.WriteLine(string.Format("Login completed in {0}ms", sw.ElapsedMilliseconds.ToString()));
#endif
            return;
        }

19 View Source File : BaseEngine.cs
License : MIT License
Project Creator : angelsix

protected void ReplaceTag(ref string fileContents, Match match, string newContent, bool removeNewline = true)
        {
            // If we want to remove a suffixed newline...
            if (removeNewline)
            {
                // Remove carriage return
                if ((fileContents.Length > match.Index + match.Length) &&
                    fileContents[match.Index + match.Length] == '\r')
                    fileContents = string.Concat(fileContents.Substring(0, match.Index + match.Length), fileContents.Substring(match.Index + match.Length + 1));

                // Return newline
                if ((fileContents.Length > match.Index + match.Length) &&
                    fileContents[match.Index + match.Length] == '\n')
                    fileContents = string.Concat(fileContents.Substring(0, match.Index + match.Length), fileContents.Substring(match.Index + match.Length + 1));
            }

            // If the match is at the start, replace it
            if (match.Index == 0)
                fileContents = newContent + fileContents.Substring(match.Length);
            // Otherwise do an inner replace
            else
                fileContents = string.Concat(fileContents.Substring(0, match.Index), newContent, fileContents.Substring(match.Index + match.Length));
        }

19 View Source File : GrpcCrossChainClientProviderTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public void CreateCrossChainClient_Test()
        {
            var remoteChainId = ChainOptions.ChainId;
            var localChainId = ChainHelper.GetChainId(1);

            var host = "127.0.0.1";
            var port = 5000;
            var crossChainClientDto = new CrossChainClientCreationContext
            {
                LocalChainId = localChainId,
                RemoteChainId = remoteChainId,
                IsClientToParentChain = false,
                RemoteServerHost = host,
                RemoteServerPort = port
            };
            
            var client = _grpcCrossChainClientProvider.CreateChainInitializationDataClient(crossChainClientDto);
            var isClientCached = _grpcCrossChainClientProvider.TryGetClient(remoteChainId, out _);
            replacedert.False(isClientCached);
            
            replacedert.True(client.RemoteChainId == remoteChainId);
            replacedert.False(client.IsConnected);
            replacedert.Equal(remoteChainId, client.RemoteChainId);
            
            var expectedUriStr = string.Concat(host, ":", "5000");
            replacedert.Equal(expectedUriStr, client.TargetUriString);
        }

19 View Source File : EditorUtilitiesInternal.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

internal static void CreateOrUpdatereplacedet<T>(T obj, string replacedetName = "", string defaultreplacedetSubPath = "") where T : UnityEngine.Object
        {
            string path = replacedetDatabase.GetreplacedetPath(obj);
            if (replacedetDatabase.Contains(obj))
            {
                EditorUtility.SetDirty(obj);
            }
            else
            {
                //Have to do this rather replacedbersome path construction due to the workings of the replacedetDatabase methods
                path = "replacedets";

                var subPath = GetSubPath(defaultreplacedetSubPath);
                if (!string.IsNullOrEmpty(subPath))
                {
                    path = string.Concat(path, "/", subPath);
                }

                var folderId = replacedetDatabase.replacedetPathToGUID(path);
                if (string.IsNullOrEmpty(folderId))
                {
                    folderId = replacedetDatabase.CreateFolder("replacedets", subPath);
                    path = replacedetDatabase.GUIDToreplacedetPath(folderId);
                }

                if (string.IsNullOrEmpty(replacedetName))
                {
                    replacedetName = typeof(T).Name;
                }

                path = string.Concat(path, "/", replacedetName, ".replacedet");
                path = replacedetDatabase.GenerateUniquereplacedetPath(path);

                replacedetDatabase.Createreplacedet(obj, path);

                EditorGUIUtility.PingObject(obj);
            }

            replacedetDatabase.Savereplacedets();
        }

19 View Source File : EmailService.cs
License : MIT License
Project Creator : ADefWebserver

private async Task<string> SendMailAsync(bool SendAsync, string MailFrom, string MailTo, string MailToDisplayName, string Cc, string Bcc, string ReplyTo, System.Net.Mail.MailPriority Priority,
            string Subject, Encoding BodyEncoding, string Body, string[] Attachment, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPreplacedword, bool SMTPEnableSSL)
        {
            string strSendMail = "";
            GeneralSettings GeneralSettings = await _generalSettingsService.GetGeneralSettingsAsync();

            // SMTP server configuration
            if (SMTPServer == "")
            {
                SMTPServer = GeneralSettings.SMTPServer;

                if (SMTPServer.Trim().Length == 0)
                {
                    return "Error: Cannot send email - SMTPServer not set";
                }
            }

            if (SMTPAuthentication == "")
            {
                SMTPAuthentication = GeneralSettings.SMTPAuthendication;
            }

            if (SMTPUsername == "")
            {
                SMTPUsername = GeneralSettings.SMTPUserName;
            }

            if (SMTPPreplacedword == "")
            {
                SMTPPreplacedword = GeneralSettings.SMTPPreplacedword;
            }

            MailTo = MailTo.Replace(";", ",");
            Cc = Cc.Replace(";", ",");
            Bcc = Bcc.Replace(";", ",");

            System.Net.Mail.MailMessage objMail = null;
            try
            {
                System.Net.Mail.MailAddress SenderMailAddress = new System.Net.Mail.MailAddress(MailFrom, MailFrom);
                System.Net.Mail.MailAddress RecipientMailAddress = new System.Net.Mail.MailAddress(MailTo, MailToDisplayName);

                objMail = new System.Net.Mail.MailMessage(SenderMailAddress, RecipientMailAddress);

                if (Cc != "")
                {
                    objMail.CC.Add(Cc);
                }
                if (Bcc != "")
                {
                    objMail.Bcc.Add(Bcc);
                }

                if (ReplyTo != string.Empty)
                {
                    objMail.ReplyToList.Add(new System.Net.Mail.MailAddress(ReplyTo));
                }

                objMail.Priority = (System.Net.Mail.MailPriority)Priority;
                objMail.IsBodyHtml = IsHTMLMail(Body);

                foreach (string myAtt in Attachment)
                {
                    if (myAtt != "") objMail.Attachments.Add(new System.Net.Mail.Attachment(myAtt));
                }

                // message
                objMail.SubjectEncoding = BodyEncoding;
                objMail.Subject = Subject.Trim();
                objMail.BodyEncoding = BodyEncoding;

                System.Net.Mail.AlternateView PlainView =
                    System.Net.Mail.AlternateView.CreateAlternateViewFromString(Utility.ConvertToText(Body),
                    null, "text/plain");

                objMail.AlternateViews.Add(PlainView);

                //if body contains html, add html part
                if (IsHTMLMail(Body))
                {
                    System.Net.Mail.AlternateView HTMLView =
                        System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, "text/html");

                    objMail.AlternateViews.Add(HTMLView);
                }
            }
            catch (Exception objException)
            {
                // Problem creating Mail Object
                strSendMail = MailTo + ": " + objException.Message;

                // Log Error 
                BlazorBlogs.Data.Models.Logs objLog = new Data.Models.Logs();
                objLog.LogDate = DateTime.Now;
                objLog.LogAction = $"{Constants.EmailError} - Error: {strSendMail}";
                objLog.LogUserName = MailTo;
                objLog.LogIpaddress = "127.0.0.1";
            }

            if (objMail != null)
            {
                // external SMTP server alternate port
                int? SmtpPort = null;
                int portPos = SMTPServer.IndexOf(":");
                if (portPos > -1)
                {
                    SmtpPort = Int32.Parse(SMTPServer.Substring(portPos + 1, SMTPServer.Length - portPos - 1));
                    SMTPServer = SMTPServer.Substring(0, portPos);
                }

                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();

                if (SMTPServer != "")
                {
                    smtpClient.Host = SMTPServer;
                    smtpClient.Port = (SmtpPort == null) ? (int)25 : (Convert.ToInt32(SmtpPort));

                    switch (SMTPAuthentication)
                    {
                        case "":
                        case "0":
                            // anonymous
                            break;
                        case "1":
                            // basic
                            if (SMTPUsername != "" & SMTPPreplacedword != "")
                            {
                                smtpClient.UseDefaultCredentials = false;
                                smtpClient.Credentials = new System.Net.NetworkCredential(SMTPUsername, SMTPPreplacedword);
                            }

                            break;
                        case "2":
                            // NTLM
                            smtpClient.UseDefaultCredentials = true;
                            break;
                    }
                }
                smtpClient.EnableSsl = SMTPEnableSSL;

                try
                {
                    if (SendAsync) // Send Email using SendAsync
                    {
                        // Set the method that is called back when the send operation ends.
                        smtpClient.SendCompleted += SmtpClient_SendCompleted;

                        // Send the email
                        MailMessage objMailMessage = new MailMessage();
                        objMailMessage = objMail;

                        smtpClient.SendAsync(objMail, objMailMessage);
                        strSendMail = "";
                    }
                    else // Send email and wait for response
                    {
                        smtpClient.Send(objMail);
                        strSendMail = "";

                        // Log the Email
                        LogEmail(objMail);

                        objMail.Dispose();
                        smtpClient.Dispose();
                    }
                }
                catch (Exception objException)
                {
                    // mail configuration problem
                    if (!(objException.InnerException == null))
                    {
                        strSendMail = string.Concat(objException.Message, Environment.NewLine, objException.InnerException.Message);
                    }
                    else
                    {
                        strSendMail = objException.Message;
                    }

                    // Log Error 
                    BlazorBlogs.Data.Models.Logs objLog = new Data.Models.Logs();
                    objLog.LogDate = DateTime.Now;
                    objLog.LogAction = $"{Constants.EmailError} - Error: {strSendMail}";
                    objLog.LogUserName = null;
                    objLog.LogIpaddress = "127.0.0.1";

                    _context.Logs.Add(objLog);
                    _context.SaveChanges();
                }
            }

            return strSendMail;
        }

19 View Source File : AIEditorMenus.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

private static void AddSharedItems(GenericMenu menu, AIUI ui, bool allowDelete, Vector2 mousePos)
        {
            if (menu.GereplacedemCount() > 0)
            {
                menu.AddSeparator(string.Empty);
            }

            if (ui.undoRedo.canUndo)
            {
                menu.AddItem(new GUIContent(string.Concat("Undo (", ctrlOrCmd, " + Shift + Z)")), false, () => ui.undoRedo.Undo());
            }
            else
            {
                menu.AddDisabledItem(new GUIContent(string.Concat("Undo (", ctrlOrCmd, " + Shift + Z)")));
            }

            if (ui.undoRedo.canRedo)
            {
                menu.AddItem(new GUIContent(string.Concat("Redo (", ctrlOrCmd, " + Shift + Y)")), false, () => ui.undoRedo.Redo());
            }
            else
            {
                menu.AddDisabledItem(new GUIContent(string.Concat("Redo (", ctrlOrCmd, " + Shift + Y)")));
            }

            menu.AddSeparator(string.Empty);
            var hreplacedelection = ui.selectedViews.Count > 0 || ui.currentAction != null || ui.currentQualifier != null || ui.currentSelector != null;
            if (hreplacedelection)
            {
                menu.AddItem(new GUIContent(string.Concat("Cut (", ctrlOrCmd, " + X)")), false, () => ClipboardService.CutToClipboard(ui));
                menu.AddItem(new GUIContent(string.Concat("Copy (", ctrlOrCmd, " + C)")), false, () => ClipboardService.CopyToClipboard(ui));
                menu.AddItem(new GUIContent(string.Concat("Duplicate (", ctrlOrCmd, " + D)")), false, () => ClipboardService.Duplicate(ui, mousePos));
            }
            else
            {
                menu.AddDisabledItem(new GUIContent(string.Concat("Cut (", ctrlOrCmd, " + X)")));
                menu.AddDisabledItem(new GUIContent(string.Concat("Copy (", ctrlOrCmd, " + C)")));
                menu.AddDisabledItem(new GUIContent(string.Concat("Duplicate (", ctrlOrCmd, " + D)")));
            }

            if (!string.IsNullOrEmpty(EditorGUIUtility.systemCopyBuffer))
            {
                menu.AddItem(new GUIContent(string.Concat("Paste (", ctrlOrCmd, " + V)")), false, () => ClipboardService.PasteFromClipboard(ui, mousePos));
            }
            else
            {
                menu.AddDisabledItem(new GUIContent(string.Concat("Paste (", ctrlOrCmd, " + V)")));
            }

            menu.AddSeparator(string.Empty);
            menu.AddItem(new GUIContent(string.Concat("Select All (", ctrlOrCmd, " + A)")), false, () => ui.MultiSelectViews(ui.canvas.views));

            if (allowDelete)
            {
                menu.AddSeparator(string.Empty);
                if (hreplacedelection)
                {
                    menu.AddItem(new GUIContent("Delete (Del)"), false, () => ui.RemoveSelected());
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Delete (Del)"));
                }
            }

            menu.ShowAsContext();
        }

19 View Source File : DefaultEventAdapter.cs
License : Apache License 2.0
Project Creator : AkkaNetContrib

protected virtual byte[] ToBytes(object payload, JObject metadata, out string type, out bool isJson)
        {
            if (payload is Tagged tagged)
            {
                payload = tagged.Payload;
            }
            var eventType = payload.GetType();
            isJson = true;
            type = eventType.Name.ToEventCase();
            var clrEventType = string.Concat(eventType.FullName, ", ", eventType.GetTypeInfo().replacedembly.GetName().Name);
            metadata[Constants.EventMetadata.ClrEventType] = clrEventType;

            return _serializer.ToBinary(payload);
        }

19 View Source File : CommandOutput.cs
License : MIT License
Project Creator : aquilahkj

void ICommandOutput.Output(CommandOutputInfo info)
        {
            if (info == null)
                throw new ArgumentNullException(nameof(info));
            if (Enable && (OnCommandOutput != null || UseConsoleOutput)) {
                var sb = new StringBuilder();
                sb.AppendLine("action\t:" + info.Action);
                sb.AppendLine("type\t:" + info.CommandType);
                sb.AppendLine("level\t:" + info.Level);
                sb.AppendLine("region\t:" + info.Start + "," + info.Size);
                sb.AppendLine("time\t:" + info.StartTime.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                sb.AppendLine("span\t:" + (info.EndTime - info.StartTime).TotalMilliseconds);
                sb.AppendLine("trans\t:" + (info.IsTransaction ? "true" : "false"));
                sb.AppendLine("success\t:" + (info.Success ? "true" : "false"));
                if (info.Success) {
                    sb.AppendLine("result\t:" + (info.Result != null ? info.Result.ToString() : "null"));
                }
                else {
                    sb.AppendLine("error\t:" + info.ExceptionMessage);
                }
                var datas = info.Datas;
                var command = info.Command;
                if (datas != null && datas.Length > 0) {
                    sb.AppendLine("params\t:");
                    foreach (var data in datas) {
                        sb.AppendLine(string.Format("  {2},{3},{0}={1}", data.ParameterName, data.Value, data.Direction, data.DbType));
                    }
                }
                sb.AppendLine("command\t:");
                sb.Append("  ");
                sb.AppendLine(command);
                var commandInfo = sb.ToString();
                string runnableCommand = null;
                if (OutputFullCommand) {
                    if (datas != null && datas.Length > 0) {
                        var temp = command;
                        var dict = new Dictionary<string, string>();
                        var patterns = new List<string>();
                        foreach (var data in datas) {
                            string value;
                            if (data.Value == null) {
                                value = "null";
                            }
                            else if (data.Value == DBNull.Value) {
                                value = "null";
                            }
                            else {
                                var code = Type.GetTypeCode(data.Value.GetType());
                                var type = data.Value.GetType();
                                if (code == TypeCode.Empty) {
                                    value = "null";
                                }
                                else if (type.GetTypeInfo().IsEnum) {
                                    value = Convert.ToInt64(data.Value).ToString();
                                }
                                else if (code == TypeCode.String || code == TypeCode.Char) {
                                    var content = data.Value.ToString();
                                    content = content.Replace("'", "''");
                                    value = string.Concat("'", content, "'");
                                }
                                else if (code == TypeCode.DateTime) {
                                    var dt = (DateTime)data.Value;
                                    value = string.Concat("'", dt.ToString("yyyy-MM-dd HH:mm:ss"), "'");
                                }
                                else if(data.Value is byte[]) {
                                    value = "[bytes]";
                                }
                                else {
                                    value = data.Value.ToString();
                                }
                            }
                            dict[data.ParameterName] = value;
                            var name = data.ParameterName.Replace("?", "\\?");
                            patterns.Add(name + "\\b");
                        }
                        var regex = new Regex(string.Join("|", patterns), RegexOptions.Compiled);
                        temp = regex.Replace(temp, x =>
                        {
                            if (dict.TryGetValue(x.Value, out var data)) {
                                return data;
                            }

                            return x.Value;
                        });
                        runnableCommand = temp;
                    }
                    else {
                        runnableCommand = command;
                    }
                }

                if (OnCommandOutput != null) {
                    var args = new CommandOutputEventArgs
                    {
                        CommandInfo = commandInfo, 
                        RunnableCommand = runnableCommand
                    };
                    OnCommandOutput(this, args);
                }
                if (UseConsoleOutput) {
                    if (runnableCommand != null) {
                        sb.AppendLine("--------------------");
                        sb.Append("  ");
                        sb.AppendLine(runnableCommand);
                    }
                    Console.WriteLine(sb);
                }
            }
        }

19 View Source File : VssHttpRequestSettings.cs
License : MIT License
Project Creator : actions

protected internal virtual Boolean ApplyTo(HttpRequestMessage request)
        {
            // Make sure we only apply the settings to the request once
            if (request.Properties.ContainsKey(PropertyName))
            {
                return false;
            }

            request.Properties.Add(PropertyName, this);

            if (this.AcceptLanguages != null && this.AcceptLanguages.Count > 0)
            {
                // An empty or null CultureInfo name will cause an ArgumentNullException in the
                // StringWithQualityHeaderValue constructor. CultureInfo.InvariantCulture is an example of
                // a CultureInfo that has an empty name.
                foreach (CultureInfo culture in this.AcceptLanguages.Where(a => !String.IsNullOrEmpty(a.Name)))
                {
                    request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue(culture.Name));
                }
            }

            if (this.UserAgent != null)
            {
                foreach (var headerVal in this.UserAgent)
                {
                    if (!request.Headers.UserAgent.Contains(headerVal))
                    {
                        request.Headers.UserAgent.Add(headerVal);
                    }
                }
            }

            if (this.SuppressFedAuthRedirects)
            {
                request.Headers.Add(Internal.HttpHeaders.TfsFedAuthRedirect, "Suppress");
            }

            // Record the command, if we have it.  Otherwise, just record the session ID.
            if (!request.Headers.Contains(Internal.HttpHeaders.TfsSessionHeader))
            {
                if (!String.IsNullOrEmpty(this.OperationName))
                {
                    request.Headers.Add(Internal.HttpHeaders.TfsSessionHeader, String.Concat(this.SessionId.ToString("D"), ", ", this.OperationName));
                }
                else
                {
                    request.Headers.Add(Internal.HttpHeaders.TfsSessionHeader, this.SessionId.ToString("D"));
                }
            }

            if (!String.IsNullOrEmpty(this.AgentId))
            {
                request.Headers.Add(Internal.HttpHeaders.VssAgentHeader, this.AgentId);
            }

            // Content is being sent as chunked by default in dotnet5.4, which differs than the .net 4.5 behaviour.
            if (request.Content != null && !request.Content.Headers.ContentLength.HasValue && !request.Headers.TransferEncodingChunked.HasValue)
            {
                request.Content.Headers.ContentLength = request.Content.ReadAsByteArrayAsync().Result.Length;
            }

            return true;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : arvindshmicrosoft

public override void ExplicitVisit(NamedTableReference table)
        {
            var schemaName = table.SchemaObject.SchemaIdentifier != null ? table.SchemaObject.SchemaIdentifier.Value : "dbo";
            Console.WriteLine(string.Concat(schemaName, ".", table.SchemaObject.BaseIdentifier.Value));

            base.ExplicitVisit(table);
        }

19 View Source File : GuidObjectFolder.cs
License : MIT License
Project Creator : Alprog

public string GetFullPath(string separator = "/")
            {
                if (Parent == null)
                {
                    return Name;
                }

                var parentPath = Parent.GetFullPath(separator);
                return String.Concat(parentPath, separator, Name);
            }

19 View Source File : GuidObjectFolder.cs
License : MIT License
Project Creator : Alprog

public string GetScopePath(string separator = "/")
            {
                if (Parent == null)
                {
                    return Name;
                }

                var parentPath = Parent.GetScopePath(separator);
                if (SkipCodegen)
                {
                    return parentPath;
                }

                return String.Concat(parentPath, separator, Name);
            }

19 View Source File : ExpressionValue.cs
License : MIT License
Project Creator : actions

public override String ToString()
        {
            if (!String.IsNullOrEmpty(m_expression))
            {
                return String.Concat("$[ ", m_expression, " ]");
            }
            else
            {
                return m_literalValue?.ToString();
            }
        }

19 View Source File : CsvOutputFormatter.cs
License : GNU General Public License v3.0
Project Creator : andysal

private void writeStream(Type type, object value, Stream stream)
        {
            Type itemType = type.GetGenericArguments()[0];

            StringWriter _stringWriter = new StringWriter();

            _stringWriter.WriteLine(
                string.Join<string>(
                    ";", itemType.GetProperties().Select(x => x.Name)
                )
            );

            foreach (var obj in (IEnumerable<object>)value)
            {

                var vals = obj.GetType().GetProperties().Select(
                    pi => new {
                        Value = pi.GetValue(obj, null)
                    }
                );

                string _valueLine = string.Empty;

                foreach (var val in vals)
                {

                    if (val.Value != null)
                    {

                        var _val = val.Value.ToString();

                        //Check if the value contans a comma and place it in quotes if so
                        if (_val.Contains(","))
                            _val = string.Concat("\"", _val, "\"");

                        //Replace any \r or \n special characters from a new line with a space
                        if (_val.Contains("\r"))
                            _val = _val.Replace("\r", " ");
                        if (_val.Contains("\n"))
                            _val = _val.Replace("\n", " ");

                        _valueLine = string.Concat(_valueLine, _val, ";");

                    }
                    else
                    {

                        _valueLine = string.Concat(string.Empty, ";");
                    }
                }

                _stringWriter.WriteLine(_valueLine.TrimEnd(';'));
            }

            var streamWriter = new StreamWriter(stream);
            streamWriter.Write(_stringWriter.ToString());
            streamWriter.Flush();
        }

19 View Source File : AElfString.cs
License : MIT License
Project Creator : AElfProject

public static string Concat(string str0, string str1, string str2)
        {
            return ValidatedString(string.Concat(str0, str1, str2));
        }

19 View Source File : AuthenticationClient.cs
License : MIT License
Project Creator : anthonyreilly

public async Task WebServerAsync(string clientId, string clientSecret, string redirectUri, string code, string tokenRequestEndpointUrl = TokenRequestEndpointUrl)
        {
            if (string.IsNullOrEmpty(clientId)) throw new ArgumentNullException("clientId");
            if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException("clientSecret");
            if (string.IsNullOrEmpty(redirectUri)) throw new ArgumentNullException("redirectUri");
            if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute)) throw new FormatException("redirectUri");
            if (string.IsNullOrEmpty(code)) throw new ArgumentNullException("code");
            if (string.IsNullOrEmpty(tokenRequestEndpointUrl)) throw new ArgumentNullException("tokenRequestEndpointUrl");
            if (!Uri.IsWellFormedUriString(tokenRequestEndpointUrl, UriKind.Absolute)) throw new FormatException("tokenRequestEndpointUrl");

            var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("grant_type", "authorization_code"),
                    new KeyValuePair<string, string>("client_id", clientId),
                    new KeyValuePair<string, string>("client_secret", clientSecret),
                    new KeyValuePair<string, string>("redirect_uri", redirectUri),
                    new KeyValuePair<string, string>("code", code)
                });

            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(tokenRequestEndpointUrl),
                Content = content
            };

            request.Headers.UserAgent.ParseAdd(string.Concat(UserAgent, "/", ApiVersion));

            var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);
            var response = await responseMessage.Content.ReadreplacedtringAsync().ConfigureAwait(false);

            if (responseMessage.IsSuccessStatusCode)
            {
                this.AccessInfo = JsonConvert.DeserializeObject<AccessTokenResponse>(response);
            }
            else
            {
                try
                {
                    var errorResponse = JsonConvert.DeserializeObject<AuthErrorResponse>(response);
                    throw new ForceAuthException(errorResponse.Error, errorResponse.ErrorDescription, responseMessage.StatusCode);
                }
                catch (Exception ex)
                {
                    throw new ForceAuthException("Unknown", ex.Message, responseMessage.StatusCode);
                }

            }
        }

19 View Source File : WordListReducer.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

private bool CheckInDictionary(string currentSurface, string currentBaseform, string reading, string pronun)
        {
            AppendWordPart(currentSurface, reading, pronun, currentBaseform);
            surface.Append("*");

            string searchWord = String.Concat(surface.ToString(), " OR ", baseform.ToString());
            bool isHave = JmdictEnreplacedy.HasreplacedWord(searchWord, dictionary);            

            if (!isHave)
            {
                surface.Remove(surface.Length - 1, 1);
                RemoveLastWordPath();
                return false;
            }
            else
            {
                surface.Remove(surface.Length - 1, 1);
                return true;
            }
        }

19 View Source File : GrpcCrossChainClientProviderTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public void AddOrUpdateClient_Test()
        {
            var remoteChainId = ChainOptions.ChainId;
            var localChainId = ChainHelper.GetChainId(1);

            var host = "127.0.0.1";
            var port = 5000;
            var crossChainClientDto = new CrossChainClientCreationContext
            {
                LocalChainId = localChainId,
                RemoteChainId = remoteChainId,
                IsClientToParentChain = false,
                RemoteServerHost = host,
                RemoteServerPort = port
            };
            
            var client = _grpcCrossChainClientProvider.AddOrUpdateClient(crossChainClientDto);

            replacedert.True(client.RemoteChainId == remoteChainId);
            replacedert.False(client.IsConnected);
            replacedert.Equal(remoteChainId, client.RemoteChainId);

            var expectedUriStr = string.Concat(host, ":", "5000");
            replacedert.Equal(expectedUriStr, client.TargetUriString);
            
            var sameClient = _grpcCrossChainClientProvider.AddOrUpdateClient(crossChainClientDto);
            sameClient.ShouldBe(client);
        }

19 View Source File : AuthenticationClient.cs
License : MIT License
Project Creator : anthonyreilly

public async Task TokenRefreshAsync(string refreshToken, string clientId, string clientSecret = "", string tokenRequestEndpointUrl = TokenRequestEndpointUrl)
        {
            var uri = UriFormatter.RefreshTokenUrl(
                tokenRequestEndpointUrl,
                refreshToken,
                clientId,
                clientSecret);

            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = uri
            };

            request.Headers.UserAgent.ParseAdd(string.Concat(UserAgent, "/", ApiVersion));

            var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);
            var response = await responseMessage.Content.ReadreplacedtringAsync().ConfigureAwait(false);

            if (responseMessage.IsSuccessStatusCode)
            {
                this.AccessInfo = JsonConvert.DeserializeObject<AccessTokenResponse>(response);
                this.AccessInfo.RefreshToken = refreshToken; //not included in reponse
            }
            else
            {
                var errorResponse = JsonConvert.DeserializeObject<AuthErrorResponse>(response);
                throw new ForceAuthException(errorResponse.Error, errorResponse.ErrorDescription, responseMessage.StatusCode);
            }
        }

19 View Source File : LocationCacheManager.cs
License : MIT License
Project Creator : actions

private static String BuildCacheMissString(String serviceType, Guid serviceIdentifier)
        {
            return String.Concat(serviceType, "_", serviceIdentifier.ToString());
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : anupavanm

public void Type(string words)
  {
    mContent = String.Concat(mContent," ", words);
  }

19 View Source File : ExecutionObserverInjectorTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public void ConstructCounterProxyTest()
        {
            var module = GetContractModule(typeof(TestContract));
            var ns = "AElf.CSharp.CodeOps";
            var typeDefinition = ExecutionObserverInjector.ConstructCounterProxy(module, ns);
            typeDefinition.Methods.Count.ShouldBe(3);
            typeDefinition.Methods.Select(method => method.DeclaringType.FullName)
                .ShouldAllBe(name => name == string.Concat(ns, ".", nameof(ExecutionObserverProxy)));
            new[]
            {
                nameof(ExecutionObserverProxy.SetObserver), nameof(ExecutionObserverProxy.BranchCount),
                nameof(ExecutionObserverProxy.CallCount)
            }.ShouldAllBe(name => typeDefinition.Methods.Select(method => method.Name).Contains(name));
        }

19 View Source File : PathingEngineBase.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

private void FailRequest(IPathRequest request, Exception e)
        {
            _segments.Clear();
            _segmentRequest.Clear();
            _currentResult = null;

            var result = new PathResult(PathingStatus.Failed, null, 0, request)
            {
                errorInfo = string.Concat(e.Message, Environment.NewLine, e.StackTrace)
            };

            request.Complete(result);
        }

19 View Source File : XmlFoldingStrategy.cs
License : MIT License
Project Creator : Abdesol

XmlFoldStart CreateElementFoldStart(TextDoreplacedent doreplacedent, XmlReader reader)
		{
			// Take off 1 from the offset returned
			// from the xml since it points to the start
			// of the element name and not the beginning
			// tag.
			//XmlFoldStart newFoldStart = new XmlFoldStart(reader.Prefix, reader.LocalName, reader.LineNumber - 1, reader.LinePosition - 2);
			XmlFoldStart newFoldStart = new XmlFoldStart();

			IXmlLineInfo lineInfo = (IXmlLineInfo)reader;
			newFoldStart.StartLine = lineInfo.LineNumber;
			newFoldStart.StartOffset = doreplacedent.GetOffset(newFoldStart.StartLine, lineInfo.LinePosition - 1);

			if (this.ShowAttributesWhenFolded && reader.HasAttributes) {
				newFoldStart.Name = String.Concat("<", reader.Name, " ", GetAttributeFoldText(reader), ">");
			} else {
				newFoldStart.Name = String.Concat("<", reader.Name, ">");
			}

			return newFoldStart;
		}

19 View Source File : AssetPath.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

public static string Combine(string partOne, string partTwo)
        {
            return string.Concat(
                NormalizePath(partOne),
                "/",
                NormalizePath(partTwo));
        }

19 View Source File : LegacyEventAdapter.cs
License : Apache License 2.0
Project Creator : AkkaNetContrib

protected virtual byte[] ToBytes(object @event, JObject metadata, out string type, out bool isJson)
        {
            var eventType = @event.GetType();
            isJson = true;
            type = eventType.Name.ToEventCase();
            var clrEventType = string.Concat(eventType.FullName, ", ", eventType.GetTypeInfo().replacedembly.GetName().Name);
            metadata[Constants.EventMetadata.ClrEventType] = clrEventType;

            var dataString = JsonConvert.SerializeObject(@event);
            return Encoding.UTF8.GetBytes(dataString);
        }

19 View Source File : StoredAIs.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

internal static string EnsureValidName(string name, AIStorage target)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = "New AI";
            }
            else
            {
                var invalidChars = System.IO.Path.GetInvalidFileNameChars();
                var transformer = new StringBuilder(name.Length);
                for (int i = 0; i < name.Length; i++)
                {
                    var allowChar = true;
                    for (int j = 0; j < invalidChars.Length; j++)
                    {
                        var invalidChar = invalidChars[j];
                        if (invalidChar.Equals(name[i]))
                        {
                            allowChar = false;
                            break;
                        }
                    }

                    if (allowChar)
                    {
                        transformer.Append(name[i]);
                    }
                }

                name = transformer.ToString();
            }

            var nameBase = name;
            int idx = 0;
            var stored = AIs.FirstOrDefault(a => a.name.Equals(name, StringComparison.OrdinalIgnoreCase));
            while (stored != null && !object.ReferenceEquals(stored, target))
            {
                idx++;
                name = string.Concat(nameBase, " ", idx.ToString("##"));
                stored = AIs.FirstOrDefault(a => a.name.Equals(name, StringComparison.OrdinalIgnoreCase));
            }

            return name;
        }

19 View Source File : CrmEntitySecurityCacheInfo.cs
License : MIT License
Project Creator : Adoxio

private string BuildKey(Enreplacedy enreplacedy, CrmEnreplacedyRight right, string securityContextKey)
		{
			var baseKey = string.Concat(securityContextKey, ":", enreplacedy.Id, ":", right);

            IIdenreplacedy idenreplacedy;

			return TryGetCurrentIdenreplacedy(out idenreplacedy)
				? string.Concat(baseKey, ":Idenreplacedy=", idenreplacedy.Name)
                : string.Concat(baseKey, ":Anonymous");
        }

19 View Source File : Utility.cs
License : MIT License
Project Creator : aprilyush

public static Type CreateType(string typeName, string replacedembly)
        {
            if (string.IsNullOrEmpty(typeName)) return null;

            Type type = null;
            bool flag = false;
            string cacheKey = string.Concat(typeName, ",", replacedembly);

            lock (TypeCache)
            {
                flag = TypeCache.TryGetValue(cacheKey, out type);
            }
            if (!flag)
            {
                if (string.IsNullOrEmpty(replacedembly))
                {
                    //从当前程序域里建立类型
                    type = Type.GetType(typeName, false, true);
                    if (type == null)
                    {
                        //搜索当前程序域里的所有程序集
                        replacedembly[] replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
                        foreach (replacedembly asm in replacedemblies)
                        {
                            type = asm.GetType(typeName, false, true);
                            if (type != null) break;
                        }
                    }
                }
                else
                {
                    //从某个程序集里建立类型
                    replacedembly asm;
                    if (replacedembly.IndexOf(":") != -1)
                    {
                        asm = replacedembly.LoadFrom(replacedembly);
                    }
                    else
                    {
                        asm = replacedembly.Load(replacedembly);
                    }
                    if (asm != null)
                    {
                        type = asm.GetType(typeName, false, true);
                    }
                }
                //缓存
                lock (TypeCache)
                {
                    if (!TypeCache.ContainsKey(cacheKey))
                    {
                        TypeCache.Add(cacheKey, type);
                    }
                }
            }
            return type;
        }

19 View Source File : Common.cs
License : MIT License
Project Creator : AlbertMN

static string ResourceNameToPath(string lib)
    {
        var bittyness = IntPtr.Size == 8 ? "64" : "32";

        var name = lib;

        if (lib.StartsWith(String.Concat("costura", bittyness, ".")))
        {
            name = Path.Combine(bittyness, lib.Substring(10));
        }
        else if (lib.StartsWith("costura."))
        {
            name = lib.Substring(8);
        }

        if (name.EndsWith(".compressed"))
        {
            name = name.Substring(0, name.Length - 11);
        }

        return name;
    }

19 View Source File : TextFormatter.cs
License : MIT License
Project Creator : aquilahkj

private static Section[] LoadSections(string pattern, bool supportExtend)
        {
            var prev = 0;

            var chars = pattern.ToCharArray();
            var realLen = chars.Length;
            var safeLen = realLen - 1;

            var endFlag = false;
            var list = new List<Section>();
            for (var i = 0; i < safeLen; i++)
            {
                var c = chars[i];
                if (c == '{')
                {
                    if (chars[i + 1] == '{')
                    {
                        i++;
                    }
                    else
                    {
                        if (i > 0)
                        {
                            var normalSection = new Section
                            {
                                Type = SectionType.NormalText,
                                Value = string.Format(new string(chars, prev, i - prev))
                            };
                            list.Add(normalSection);
                        }

                        bool nullable;
                        if (chars[i + 1] == '+')
                        {
                            nullable = false;
                            i++;
                        }
                        else
                        {
                            nullable = true;
                        }

                        if (chars[i + 1] == '.')
                        {
                            throw new FormatException(
                                $"Input param name was not a valid word, index is {i + 1}, char is '{'.'}'");
                        }

                        var start = i + 1;
                        var end = -1;
                        var split = -1;
                        for (var j = start; j < realLen; j++)
                        {
                            var e = chars[j];
                            if (e == '}')
                            {
                                if (j == start)
                                {
                                    throw new FormatException(
                                        $"Input string was not in a correct format, index is {j}, char is '{e}'");
                                }

                                if (j < safeLen && chars[j + 1] == '}')
                                {
                                    if (split == -1)
                                    {
                                        throw new FormatException(
                                            $"Input string was not in a correct format, index is {j}, char is '{e}'");
                                    }

                                    j++;
                                    continue;
                                }

                                if (chars[j - 1] == '.')
                                {
                                    throw new FormatException(
                                        $"Input param name was not a valid word, index is {j - 1}, char is '{'.'}'");
                                }

                                end = j;
                                break;
                            }

                            if (e == '{')
                            {
                                if (split > -1 && j < safeLen && chars[j + 1] == '{')
                                {
                                    j++;
                                }
                                else
                                {
                                    throw new FormatException(
                                        $"Input string was not in a correct format, index is {j}, char is '{e}'");
                                }
                            }
                            else if (split == -1)
                            {
                                if (e == ':' || e == ',')
                                {
                                    if (supportExtend)
                                    {
                                        if (j == start)
                                        {
                                            throw new FormatException(
                                                $"Input string was not a correct format, index is {j}, char is '{e}'");
                                        }

                                        if (chars[j - 1] == '.')
                                        {
                                            throw new FormatException(
                                                $"Input param name was not a valid word, index is {j - 1}, char is '{'.'}'");
                                        }

                                        split = j;
                                    }
                                    else
                                    {
                                        throw new FormatException(
                                            $"Input string was not support extend format, index is {j}, char is '{e}'");
                                    }
                                }
                                else if ((e >= 48 && e <= 57) || (e >= 65 && e <= 90) || (e >= 97 && e <= 122) ||
                                         e == '_')
                                {
                                }
                                else if (e == '.')
                                {
                                    if (chars[j + 1] == '.')
                                    {
                                        throw new FormatException(
                                            $"Input param name was not a valid word, index is {j + 1}, char is '{'.'}'");
                                    }
                                }
                                else
                                {
                                    throw new FormatException(
                                        $"Input param name was not a valid word, index is {j}, char is '{e}'");
                                }
                            }
                        }

                        if (end == -1)
                        {
                            throw new FormatException(
                                $"Input string was not in a correct format, index is {i}, '{c}' not valid close char");
                        }

                        endFlag |= end == safeLen;
                        string name;
                        string value;
                        bool extendFormat;
                        if (split > -1)
                        {
                            name = new string(chars, start, split - start);
                            var format = new string(chars, split, end - split);
                            value = string.Concat("{0", format, "}");
                            extendFormat = true;
                        }
                        else
                        {
                            name = new string(chars, start, end - start);
                            value = "{0}";
                            extendFormat = false;
                        }

                        var formatSection = new Section
                        {
                            Type = SectionType.FormatText,
                            Name = name,
                            Value = value,
                            Nullable = nullable,
                            ExtendFormat = extendFormat
                        };
                        list.Add(formatSection);
                        prev = end + 1;
                        i = end;
                    }
                }
                else if (c == '}')
                {
                    if (chars[i + 1] == '}')
                    {
                        i++;
                    }
                    else
                    {
                        throw new FormatException(
                            $"Input string was not in a correct format, index is {i}, char is '{c}'");
                    }
                }
            }

            if (!endFlag)
            {
                var c = chars[safeLen];
                if (c == '{' || c == '}')
                {
                    throw new FormatException(
                        $"Input string was not in a correct format, Index is {safeLen}, char is '{c}'");
                }

                var normalSection = new Section
                {
                    Type = SectionType.NormalText,
                    Value = string.Format(new string(chars, prev, realLen - prev))
                };
                list.Add(normalSection);
            }

            return list.ToArray();
        }

19 View Source File : BaseApiClient.cs
License : MIT License
Project Creator : 4egod

protected string GetSignature(string signatureBaseString)
        {
            byte[] key = Encoding.ASCII.GetBytes(string.Concat(Uri.EscapeDataString(ConsumerSecret), "&", Uri.EscapeDataString(AccessTokenSecret)));

            string signature;
            using (HMACSHA1 hasher = new HMACSHA1(key))
            {
                signature = Convert.ToBase64String(hasher.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString)));
            }

            return signature;
        }

19 View Source File : CommonExtensions.cs
License : Apache License 2.0
Project Creator : artemshuba

public static string ConstructQueryString(this Dictionary<string, string> parameters)
        {
            return string.Join("&", parameters.Select(pair => pair.Key).Distinct().Select(name => string.Concat(name, "=", WebUtility.HtmlEncode(parameters[name]))).ToArray());
        }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : AlphaYu

private static string ReplaceGenericParametersInGenericTypeName(this string typeName, Type type)
		{
			var genericArguments = type.GetTypeInfo().GetAllGenericArguments();

			const string regexForGenericArguments = @"`[1-9]\d*";

			var rgx = new Regex(regexForGenericArguments);

			typeName = rgx.Replace(typeName, match =>
			{
				var currentGenericArgumentNumbers = int.Parse(match.Value.Substring(1));
				var currentArguments = string.Join(",", genericArguments.Take(currentGenericArgumentNumbers).Select(ToGenericTypeString));
				genericArguments = genericArguments.Skip(currentGenericArgumentNumbers).ToArray();
				return string.Concat("<", currentArguments, ">");
			});

			return typeName;
		}

19 View Source File : ThrottleAttribute.cs
License : MIT License
Project Creator : Adoxio

public override void OnActionExecuted(ActionExecutedContext executedContext)
        {
            var key = string.Concat(Name, "-", GetIpAddress());
            if (executedContext.Controller.ViewBag.LoginSuccessful)
            {
                HttpRuntime.Cache.Remove(key);
            }
        }

19 View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099

private static string htmlSyntax(string tplcode, int num) {

			while (num-- > 0) {
				string[] arr = _reg_syntax.Split(tplcode);

				if (arr.Length == 1) break;
				for (int a = 1; a < arr.Length; a += 4) {
					string tag = string.Concat('<', arr[a]);
					string end = string.Concat("</", arr[a], '>');
					int fc = 1;
					for (int b = a; fc > 0 && b < arr.Length; b += 4) {
						if (b > a && arr[a].ToLower() == arr[b].ToLower()) fc++;
						int bpos = 0;
						while (true) {
							int fa = arr[b + 3].IndexOf(tag, bpos);
							int fb = arr[b + 3].IndexOf(end, bpos);
							if (b == a) {
								var z = arr[b + 3].IndexOf("/>");
								if ((fb == -1 || z < fb) && z != -1) {
									var y = arr[b + 3].Substring(0, z + 2);
									if (_reg_htmltag.IsMatch(y) == false)
										fb = z - end.Length + 2;
								}
							}
							if (fa == -1 && fb == -1) break;
							if (fa != -1 && (fa < fb || fb == -1)) {
								fc++;
								bpos = fa + tag.Length;
								continue;
							}
							if (fb != -1) fc--;
							if (fc <= 0) {
								var a1 = arr[a + 1];
								var end3 = string.Concat("{/", a1, "}");
								if (a1.ToLower() == "else") {
									if (_reg_blank.Replace(arr[a - 4 + 3], "").EndsWith("{/if}", StringComparison.CurrentCultureIgnoreCase) == true) {
										var idx = arr[a - 4 + 3].IndexOf("{/if}");
										arr[a - 4 + 3] = string.Concat(arr[a - 4 + 3].Substring(0, idx), arr[a - 4 + 3].Substring(idx + 5));
										//如果 @else="有条件内容",则变换成 elseif 条件内容
										if (_reg_blank.Replace(arr[a + 2], "").Length > 0) a1 = "elseif";
										end3 = "{/if}";
									} else {
										arr[a] = string.Concat("指令 @", arr[a + 1], "='", arr[a + 2], "' 没紧接着 if/else 指令之后,无效. <", arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									}
								}
								if (arr[a + 1].Length > 0) {
									if (_reg_blank.Replace(arr[a + 2], "").Length > 0 || a1.ToLower() == "else") {
										arr[b + 3] = string.Concat(arr[b + 3].Substring(0, fb + end.Length), end3, arr[b + 3].Substring(fb + end.Length));
										arr[a] = string.Concat("{", a1, " ", arr[a + 2], "}<", arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									} else {
										arr[a] = string.Concat('<', arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									}
								}
								break;
							}
							bpos = fb + end.Length;
						}
					}
					if (fc > 0) {
						arr[a] = string.Concat("不严谨的html格式,请检查 ", arr[a], " 的结束标签, @", arr[a + 1], "='", arr[a + 2], "' 指令无效. <", arr[a]);
						arr[a + 1] = arr[a + 2] = string.Empty;
					}
				}
				if (arr.Length > 0) tplcode = string.Join(string.Empty, arr);
			}
			return tplcode;
		}

19 View Source File : XmlFoldingStrategy.cs
License : MIT License
Project Creator : Abdesol

static void CreateCommentFold(TextDoreplacedent doreplacedent, List<NewFolding> foldMarkers, XmlReader reader)
		{
			string comment = reader.Value;
			if (comment != null) {
				int firstNewLine = comment.IndexOf('\n');
				if (firstNewLine >= 0) {

					// Take off 4 chars to get the actual comment start (takes
					// into account the <!-- chars.

					int startOffset = GetOffset(doreplacedent, reader) - 4;
					int endOffset = startOffset + comment.Length + 7;

					string foldText = String.Concat("<!--", comment.Substring(0, firstNewLine).TrimEnd('\r'), "-->");
					foldMarkers.Add(new NewFolding(startOffset, endOffset) { Name = foldText });
				}
			}
		}

19 View Source File : AttributeDescriptor.cs
License : MIT License
Project Creator : actions

public override string ToString()
        {
            return string.Concat(ContainerName,";",AttributeName);
        }

19 View Source File : GrpcClientTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public async Task RequestChainInitializationData_ParentClient_Test()
        {
            var chainId = ChainHelper.GetChainId(ChainHelper.ConvertBase58ToChainId("AELF") + 1);
            await Server.StartAsync(5000);

            var grpcClientInitializationContext = new GrpcClientInitializationContext
            {
                LocalChainId = chainId,
                RemoteChainId = ChainHelper.ConvertBase58ToChainId("AELF"),
                DialTimeout = 1000,
                UriStr = string.Concat(Host, ":", "5000")
            };
            var client = new ClientForParentChain(grpcClientInitializationContext);
            var res = await client.RequestChainInitializationDataAsync(chainId);
            replacedert.Equal(1, res.CreationHeightOnParentChain);
            Dispose();
        }

19 View Source File : Dbg.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd

public void Line([CallerLineNumber] int line = 0)
        {
            var timestamp = Stopwatch.GetTimestamp();
            lock (times)
            {
                ref var time = ref times.GetValueOrNullRef(string.Concat(Name, " line ", line.ToString()));
                time.Item1 += timestamp - Start;
                time.Item2++;
            }
        }

See More Examples