初始化

This commit is contained in:
2025-12-11 11:39:02 +08:00
commit 156d6ccb06
1708 changed files with 1162911 additions and 0 deletions

View File

@@ -0,0 +1,224 @@
using System;
using System.Diagnostics;
using System.Threading;
namespace Aliyun.Api.LOG.Common
{
/// <summary>
/// The implementation of <see cref="IAsyncResult"/>
/// that represents the status of an async operation.
/// </summary>
internal abstract class AsyncResult : IAsyncResult, IDisposable
{
#region Fields
private object _asyncState;
private bool _completedSynchronously;
private bool _isCompleted;
private AsyncCallback _userCallback;
private ManualResetEvent _asyncWaitEvent;
private Exception _exception;
#endregion
#region IAsyncResult Members
/// <summary>
/// Gets a user-defined object that qualifies or contains information about an asynchronous operation.
/// </summary>
[DebuggerNonUserCode]
public object AsyncState
{
get
{
return _asyncState;
}
}
/// <summary>
/// Gets a <see cref="WaitHandle"/> that is used to wait for an asynchronous operation to complete.
/// </summary>
[DebuggerNonUserCode]
public WaitHandle AsyncWaitHandle
{
get
{
if (_asyncWaitEvent != null)
{
return _asyncWaitEvent;
}
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
if (Interlocked.CompareExchange<ManualResetEvent>(ref _asyncWaitEvent, manualResetEvent, null) != null)
{
manualResetEvent.Close();
}
if (this.IsCompleted)
{
_asyncWaitEvent.Set();
}
return _asyncWaitEvent;
}
}
/// <summary>
/// Gets a value that indicates whether the asynchronous operation completed synchronously.
/// </summary>
[DebuggerNonUserCode]
public bool CompletedSynchronously
{
get
{
return _completedSynchronously;
}
protected set
{
_completedSynchronously = value;
}
}
/// <summary>
/// Gets a value that indicates whether the asynchronous operation has completed.
/// </summary>
[DebuggerNonUserCode]
public bool IsCompleted
{
get
{
return _isCompleted;
}
}
#endregion
/// <summary>
/// Initializes an instance of <see cref="AsyncResult"/>.
/// </summary>
/// <param name="callback">The callback method when the async operation completes.</param>
/// <param name="state">A user-defined object that qualifies or contains information about an asynchronous operation.</param>
protected AsyncResult(AsyncCallback callback, object state)
{
_userCallback = callback;
_asyncState = state;
}
/// <summary>
/// Completes the async operation with an exception.
/// </summary>
/// <param name="ex">Exception from the async operation.</param>
public void Complete(Exception ex)
{
// Complete should not throw if disposed.
Debug.Assert(ex != null);
_exception = ex;
this.NotifyCompletion();
}
/// <summary>
/// When called in the dervied classes, wait for completion.
/// It throws exception if the async operation ends with an exception.
/// </summary>
protected void WaitForCompletion()
{
if (!this.IsCompleted)
{
_asyncWaitEvent.WaitOne();
}
if (this._exception != null)
{
throw this._exception;
}
}
/// <summary>
/// When called in the derived classes, notify operation completion
/// by setting <see cref="P:AsyncWaitHandle"/> and calling the user callback.
/// </summary>
[DebuggerNonUserCode]
protected void NotifyCompletion()
{
_isCompleted = true;
if (_asyncWaitEvent != null)
{
_asyncWaitEvent.Set();
}
if (_userCallback != null)
{
_userCallback(this);
}
}
#region IDisposable Members
/// <summary>
/// Disposes the object and release resource.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// When overrided in the derived classes, release resources.
/// </summary>
/// <param name="disposing">Whether the method is called <see cref="M:Dispose"/></param>
protected virtual void Dispose(bool disposing)
{
if (disposing && _asyncWaitEvent != null)
{
_asyncWaitEvent.Close();
_asyncWaitEvent = null;
}
}
#endregion
}
/// <summary>
/// Represents the status of an async operation.
/// It also holds the result of the operation.
/// </summary>
/// <typeparam name="T">Type of the operation result.</typeparam>
internal class AsyncResult<T> : AsyncResult
{
/// <summary>
/// The result of the async operation.
/// </summary>
private T _result;
/// <summary>
/// Initializes an instance of <see cref="AsyncResult&lt;T&gt;"/>.
/// </summary>
/// <param name="callback">The callback method when the async operation completes.</param>
/// <param name="state">A user-defined object that qualifies or contains information about an asynchronous operation.</param>
public AsyncResult(AsyncCallback callback, object state)
: base(callback, state)
{
}
/// <summary>
/// Gets result and release resources.
/// </summary>
/// <returns>The instance of result.</returns>
public T GetResult()
{
base.WaitForCompletion();
return _result;
}
/// <summary>
/// Sets result and notify completion.
/// </summary>
/// <param name="result">The instance of result.</param>
public void Complete(T result)
{
// Complete should not throw if disposed.
this._result = result;
base.NotifyCompletion();
}
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (C) Alibaba Cloud Computing
* All rights reserved.
*
* 版权所有 C阿里云计算有限公司
*/
using System;
using System.Diagnostics;
using System.Globalization;
namespace Aliyun.Api.LOG.Common.Utilities
{
/// <summary>
/// Description of DateUtils.
/// </summary>
public static class DateUtils
{
private static DateTime _1970StartDateTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
private const string _rfc822DateFormat = "ddd, dd MMM yyyy HH:mm:ss \\G\\M\\T";
private const string _iso8601DateFormat = "yyyy-MM-dd'T'HH:mm:ss.fff'Z'";
/// <summary>
/// Formats an instance of <see cref="DateTime" /> to a GMT string.
/// </summary>
/// <param name="dt">The date time to format.</param>
/// <returns></returns>
public static string FormatRfc822Date(DateTime dt)
{
return dt.ToUniversalTime().ToString(_rfc822DateFormat,
CultureInfo.InvariantCulture);
}
/// <summary>
/// Formats a GMT date string to an object of <see cref="DateTime" />.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static DateTime ParseRfc822Date(String dt)
{
Debug.Assert(!string.IsNullOrEmpty(dt));
return DateTime.SpecifyKind(
DateTime.ParseExact(dt,
_rfc822DateFormat,
CultureInfo.InvariantCulture),
DateTimeKind.Utc);
}
/// <summary>
/// Formats a date to a string in the format of ISO 8601 spec.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string FormatIso8601Date(DateTime dt)
{
return dt.ToUniversalTime().ToString(_iso8601DateFormat,
CultureInfo.CreateSpecificCulture("en-US"));
}
/// <summary>
/// convert time stamp to DateTime.
/// </summary>
/// <param name="timeStamp">seconds</param>
/// <returns></returns>
public static DateTime GetDateTime(uint timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = ((long)timeStamp * System.TimeSpan.TicksPerSecond);
System.TimeSpan toNow = new System.TimeSpan(lTime);
DateTime targetDt = dtStart.Add(toNow);
return targetDt;
}
public static uint TimeSpan() {
return (uint)Math.Round((DateTime.Now - _1970StartDateTime).TotalSeconds, MidpointRounding.AwayFromZero);
}
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (C) Alibaba Cloud Computing
* All rights reserved.
*
* 版权所有 C阿里云计算有限公司
*/
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Aliyun.Api.LOG.Common.Utilities
{
/// <summary>
/// Description of EnumUtils.
/// </summary>
internal static class EnumUtils
{
private static IDictionary<Enum, StringValueAttribute> _stringValues =
new Dictionary<Enum, StringValueAttribute>();
public static string GetStringValue(this Enum value)
{
string output = null;
Type type = value.GetType();
if (_stringValues.ContainsKey(value))
{
output = (_stringValues[value] as StringValueAttribute).Value;
}
else
{
FieldInfo fi = type.GetField(value.ToString());
StringValueAttribute[] attrs =
fi.GetCustomAttributes(typeof (StringValueAttribute),
false) as StringValueAttribute[];
if (attrs.Length > 0)
{
output = attrs[0].Value;
// Put it in the cache.
lock(_stringValues)
{
// Double check
if (!_stringValues.ContainsKey(value))
{
_stringValues.Add(value, attrs[0]);
}
}
}
else
{
return value.ToString();
}
}
return output;
}
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright (C) Alibaba Cloud Computing
* All rights reserved.
*
* 版权所有 C阿里云计算有限公司
*/
using System;
namespace Aliyun.Api.LOG.Common.Utilities
{
/// <summary>
/// Description of HttpHeaders.
/// </summary>
internal static class HttpHeaders
{
public const string Authorization = "Authorization";
public const string CacheControl = "Cache-Control";
public const string ContentDisposition = "Content-Disposition";
public const string ContentEncoding = "Content-Encoding";
public const string ContentLength = "Content-Length";
public const string ContentMd5 = "Content-MD5";
public const string ContentType = "Content-Type";
public const string Date = "Date";
public const string Expires = "Expires";
public const string ETag = "ETag";
public const string LastModified = "Last-Modified";
public const string Range = "Range";
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright (C) Alibaba Cloud Computing
* All rights reserved.
*
* 版权所有 C阿里云计算有限公司
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace Aliyun.Api.LOG.Common.Utilities
{
/// <summary>
/// Description of HttpUtils.
/// </summary>
internal static class HttpUtils
{
public const string UTF8Charset = "utf-8";
public const string Iso88591Charset = "iso-8859-1";
/// <summary>
/// Builds the URI parameter string from the request parameters.
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
public static string GetRequestParameterString(IEnumerable<KeyValuePair<string, string>> parameters)
{
StringBuilder stringBuilder = new StringBuilder();
bool isFirst = true;
foreach (var p in parameters)
{
Debug.Assert(!string.IsNullOrEmpty(p.Key), "Null Or empty key is not allowed.");
if (!isFirst)
{
stringBuilder.Append("&");
}
isFirst = false;
stringBuilder.Append(p.Key);
if (p.Value != null)
{
stringBuilder.Append("=").Append(UrlEncode(p.Value, UTF8Charset));
}
}
return stringBuilder.ToString();
}
/// <summary>
/// Encodes the URL.
/// </summary>
/// <param name="data"></param>
/// <param name="charset"></param>
/// <returns></returns>
public static string UrlEncode(string data, string charset = UTF8Charset)
{
Debug.Assert(data != null && !string.IsNullOrEmpty(charset));
StringBuilder stringBuilder = new StringBuilder(data.Length * 2);
string text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
byte[] bytes = Encoding.GetEncoding(charset).GetBytes(data);
foreach (char c in bytes)
{
if (text.IndexOf(c) != -1)
{
stringBuilder.Append(c);
}
else
{
stringBuilder.Append("%").Append(
string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)c));
}
}
return stringBuilder.ToString();
}
// Convert a text from one charset to another.
public static string ReEncode(string text, string fromCharset, string toCharset)
{
Debug.Assert(text != null);
var buffer = Encoding.GetEncoding(fromCharset).GetBytes(text);
return Encoding.GetEncoding(toCharset).GetString(buffer);
}
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright (C) Alibaba Cloud Computing
* All rights reserved.
*
* 版权所有 C阿里云计算有限公司
*/
using System;
using System.Diagnostics;
using System.IO;
namespace Aliyun.Api.LOG.Common.Utilities
{
/// <summary>
/// Description of IOUtils.
/// </summary>
internal static class IOUtils
{
private const int _bufferSize = 1024 * 4;
public static void WriteTo(this Stream src, Stream dest){
if (dest == null)
throw new ArgumentNullException("dest");
byte[] buffer = new byte[_bufferSize];
int bytesRead = 0;
while((bytesRead = src.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, bytesRead);
}
dest.Flush();
}
/// <summary>
/// Write a stream to another
/// </summary>
/// <param name="orignStream">The stream you want to write from</param>
/// <param name="destStream">The stream written to</param>
/// <param name="maxLength">The max length of the stream to write</param>
/// <returns>The actual length written to destStream</returns>
public static long WriteTo(this Stream orignStream, Stream destStream, long maxLength)
{
const int buffSize = 1024;
byte[] buff = new byte[buffSize];
long alreadyRead = 0;
int readCount = 0;
while (alreadyRead < maxLength)
{
readCount = orignStream.Read(buff, 0, buffSize);
if (readCount <= 0) { break; }
if (alreadyRead + readCount > maxLength)
{
readCount = (int) (maxLength - alreadyRead);
}
alreadyRead += readCount;
destStream.Write(buff, 0, readCount);
}
destStream.Flush();
return alreadyRead;
}
}
}

View File

@@ -0,0 +1,24 @@
/*
* Copyright (C) Alibaba Cloud Computing
* All rights reserved.
*
* 版权所有 C阿里云计算有限公司
*/
using System;
namespace Aliyun.Api.LOG.Common.Utilities
{
/// <summary>
/// The Attribute to mark a field that corresponds a string.
/// </summary>
internal sealed class StringValueAttribute : System.Attribute
{
public string Value { get; private set; }
public StringValueAttribute(string value)
{
this.Value = value;
}
}
}