示例#1
0
        public RemoteBranchData(string name, Hash sha1)
        {
            Verify.Argument.IsNeitherNullNorWhitespace(name, "name");

            _name = name;
            _sha1 = sha1;
        }
        public void Given_a_sequence_validation_transcoder_When_writen_to_the_transcoding_stream_Then_the_inner_stream_contains_the_previous_identifier_followed_by_the_data_written()
        {
            byte[] hashBytes = { 1, 2, 3, 4 };
            const string TestText = "Test";

            var hash = new Hash(hashBytes);
            var previousEventHashReader = new PreviousEventHashReader(hash);
            var sequenceValidationTranscodingStreamFactory = new SequenceValidationTranscodingStreamFactory(previousEventHashReader);

            using (var innerStream = new MemoryStream())
            using (var sequenceValidationTranscodingStream = sequenceValidationTranscodingStreamFactory.CreateTrancodingStream(innerStream))
            {
                var writer = new StreamWriter(sequenceValidationTranscodingStream);
                writer.Write(TestText);
                writer.Flush();
                sequenceValidationTranscodingStream.Flush();

                innerStream.Seek(0, SeekOrigin.Begin);

                var hashBuffer = new byte[4];
                innerStream.Read(hashBuffer, 0, 4);
                var reader = new StreamReader(innerStream);
                var actualText = reader.ReadToEnd();

                CollectionAssert.AreEqual(hashBytes, hashBuffer);
                Assert.AreEqual(TestText, actualText);
            }
        }
示例#3
0
 public NetworkPacket(Hash publicKey_Src, PacketType type, byte[] Data)
 {
     PublicKeySource = publicKey_Src;
     Type = type;
     this.Data = Data;
     Token = new Hash();
 }
示例#4
0
 public TxOutId(Byte[] b)
 {
     this.txid = null;
     this.index = 0;
     using (MemoryStream ms = new MemoryStream(b))
         Read(ms);
 }
示例#5
0
        public async Task<Package> GetAsync(long id, SemanticVersion version, Hash hash)
        {
            var key = prefix + id.ToString() + "/" + version.ToString();

            var ms = new MemoryStream();

            using (var blob = await bucket.GetAsync(key))
            {
                using (var data = blob.Open())
                {
                    await data.CopyToAsync(ms).ConfigureAwait(false);
                }
            }

            ms.Position = 0;
            
            var secret = SecretKey.Derive(password, hash.Data);

            var protector = new AesProtector(secret); // dispose?

            var stream = protector.DecryptStream(ms);

            #region Verify the hash

            var computedHash = Hash.ComputeSHA256(stream, true);

            if (computedHash != hash)
            {
                throw new IntegrityException(hash.Data, computedHash.Data);
            }

            #endregion

            return ZipPackage.FromStream(stream, false);
        }
示例#6
0
        public bool Compile(string path, string compileToFilePath = null)
        {
            using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read))
            {

                foreach (var kv in _config.CodeTemplates)
                {
                    var templateStr = kv.Key;
                    var exportPath = kv.Value;

                    // 生成代码
                    var template = Template.Parse(templateStr);
                    var topHash = new Hash();
                    topHash["NameSpace"] = _config.NameSpace;
                    var files = new List<Hash>();
                    topHash["Files"] = files;

                    var hash = DoCompiler(path, stream, compileToFilePath);
                    files.Add(hash);

                    if (!string.IsNullOrEmpty(exportPath))
                        File.WriteAllText(exportPath, template.Render(topHash));
                }

            }

            return true;
        }
示例#7
0
        public static Hash/*!*/ Initialize([NotNull]BlockParam/*!*/ defaultProc, Hash/*!*/ self) {
            Assert.NotNull(self, defaultProc);

            self.DefaultProc = defaultProc.Proc;
            self.DefaultValue = null;
            return self;
        }
 public UnspentTxOutHeader(Byte[] b)
 {
     this.txid = null;
     this.index = 0;
     using (MemoryStream ms = new MemoryStream(b))
         Read(ms);
 }
示例#9
0
        public RemoteReferenceData(string name, Hash hash)
        {
            Verify.Argument.IsNeitherNullNorWhitespace(name, "name");

            _name = name;
            _hash = hash;
        }
示例#10
0
        /* This function (for internal use only) locates an element in an
        ** hash table that matches the given key.  The hash for this key has
        ** already been computed and is passed as the 4th parameter.
        */
        static HashElem findElementGivenHash(
            Hash pH,       /* The pH to be searched */
            string pKey,   /* The key we are searching for */
            int nKey,      /* Bytes in key (not counting zero terminator) */
            u32 h         /* The hash for this key. */
            )
        {
            HashElem elem;                /* Used to loop thru the element list */
              int count;                    /* Number of elements left to test */

              if ( pH.ht != null && pH.ht[h] != null )
              {
            _ht pEntry = pH.ht[h];
            elem = pEntry.chain;
            count = (int)pEntry.count;
              }
              else
              {
            elem = pH.first;
            count = (int)pH.count;
              }
              while ( count-- > 0 && ALWAYS( elem ) )
              {
            if ( elem.nKey == nKey && elem.pKey.Equals( pKey, StringComparison.InvariantCultureIgnoreCase ) )
            {
              return elem;
            }
            elem = elem.next;
              }
              return null;
        }
示例#11
0
        public HeaderHash(Hash hash = null)
        {
            _names = new Dictionary<string, string>();

            hash = hash ?? new Hash();
            hash.Each(pair => this[pair.Key] = pair.Value);
        }
示例#12
0
 public LeafDataType this[Hash hash]
 {
     get
     {
         return Values[hash];
     }
 }
示例#13
0
		public bool Exists(Hash hash)
		{
			if (files.ContainsKey(hash)) return true;

			if (CheckAndAddOneFile(hash)) return true;
			return false;
		}
示例#14
0
 public static Hash FromDynamic(dynamic source)
 {
     var result = new Hash();
     if (source != null)
     {
         if (source is ExpandoObject)
         {
             return Hash.FromDictionary((IDictionary<string, object>)source);
         }
         var type = (Type)source.GetType();
         if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type))
         {
             throw new NotImplementedException("I don't feel like coding this up right now; use a static type?");
         }
         PropertyInfo[] properties;
         if (CachedStatics.ContainsKey(type))
         {
             properties = CachedStatics[type];
         }
         else
         {
             properties = type.GetProperties();
             CachedStatics.Add(type, properties);
         }
         foreach (var property in properties)
         {
             result[property.Name] = property.GetValue(source, null);
         }
     }
     return result;
 }
示例#15
0
 private static Hash CreateDefaultTagMapping(RubyContext/*!*/ context) {
     Hash taggedClasses = new Hash(context.EqualityComparer);
     taggedClasses.Add(MutableString.Create("tag:ruby.yaml.org,2002:array"), context.GetClass(typeof(RubyArray)));
     taggedClasses.Add(MutableString.Create("tag:ruby.yaml.org,2002:exception"), context.GetClass(typeof(Exception)));
     taggedClasses.Add(MutableString.Create("tag:ruby.yaml.org,2002:hash"), context.GetClass(typeof(Hash)));
     taggedClasses.Add(MutableString.Create("tag:ruby.yaml.org,2002:object"), context.GetClass(typeof(object)));
     taggedClasses.Add(MutableString.Create("tag:ruby.yaml.org,2002:range"), context.GetClass(typeof(Range)));
     taggedClasses.Add(MutableString.Create("tag:ruby.yaml.org,2002:regexp"), context.GetClass(typeof(RubyRegex)));
     taggedClasses.Add(MutableString.Create("tag:ruby.yaml.org,2002:string"), context.GetClass(typeof(MutableString)));
     taggedClasses.Add(MutableString.Create("tag:ruby.yaml.org,2002:struct"), context.GetClass(typeof(RubyStruct)));
     taggedClasses.Add(MutableString.Create("tag:ruby.yaml.org,2002:sym"), context.GetClass(typeof(SymbolId)));
     taggedClasses.Add(MutableString.Create("tag:ruby.yaml.org,2002:symbol"), context.GetClass(typeof(SymbolId)));
     taggedClasses.Add(MutableString.Create("tag:ruby.yaml.org,2002:time"), context.GetClass(typeof(DateTime)));
     taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:binary"), context.GetClass(typeof(MutableString)));
     taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:bool#no"), context.FalseClass);
     taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:bool#yes"), context.TrueClass);
     taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:float"), context.GetClass(typeof(Double)));
     taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:int"), context.GetClass(typeof(Integer)));
     taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:map"), context.GetClass(typeof(Hash)));
     taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:null"), context.NilClass);            
     taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:seq"), context.GetClass(typeof(RubyArray)));            
     taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:str"), context.GetClass(typeof(MutableString)));
     taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:timestamp"), context.GetClass(typeof(DateTime)));
     //Currently not supported
     //taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:omap"), ec.GetClass(typeof()));
     //taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:pairs"),//    ec.GetClass(typeof()));
     //taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:set"),//    ec.GetClass(typeof()));
     //taggedClasses.Add(MutableString.Create("tag:yaml.org,2002:timestamp#ymd'"), );
     return taggedClasses;
 }
示例#16
0
 public void Initialize()
 {
     CoolHashFunctionByMe coolHash = new CoolHashFunctionByMe();
     tableString = new Hash<string>(coolHash);
     BoringStandartHashFunction boringHash = new BoringStandartHashFunction();
     tableInt = new Hash<int>(boringHash);
 }
示例#17
0
 public NetworkPacket(Hash publicKey_Src, PacketType type, byte[] Data, Hash token)
 {
     PublicKeySource = publicKey_Src;
     Type = type;
     this.Data = Data;
     Token = token;
 }
示例#18
0
文件: User.cs 项目: ruhex/ais
        /// <summary>
        /// Метод реализующий авторизацию пользователя. Принимает 2 параметра: логин и пароль. Задаёт метод щифрования и устанавливает соединение с БД, передавая принятые параметры.
        /// Возрашает Boolean соединения.
        /// </summary>
        /// <param name="user">Логин</param>
        /// <param name="pass">Пароль</param>
        /// <returns>Успех или крах авторизации</returns>
        public static bool Authorization(string user, string pass)
        {
            //Задаём алгоритм хэширования пасса
            HashType = Hash.SHA1;

            MySqlDataReader dataReaderTemp = MySQL.UserAut(user, pass);
            while (dataReaderTemp.Read())
            {
                Id = dataReaderTemp.GetInt32("id_user");
                Login = dataReaderTemp.GetString("login_user");
                Role = dataReaderTemp.GetString("role");
            }

            if (!dataReaderTemp.HasRows)
            {
                MySQL.connection.Close();
                return false;
            }
            bool toReturn = false;
            switch (HashType)
            {
                case Hash.SHA1:
                    if (sha1(pass) == dataReaderTemp.GetString("pass_user"))
                        toReturn = true;
                    break;
                case Hash.MD5:
                    if (md5(pass) == dataReaderTemp.GetString("pass_user"))
                        toReturn = true;
                    break;
            }
            MySQL.connection.Close();
            MemoryManagement.FlushMemory();
            return toReturn;
        }
示例#19
0
 public NetworkPacket()
 {
     PublicKeySource = new Hash();
     Type = PacketType.TPT_NOTHING;
     Data = new byte[0];
     Token = new Hash();
 }
示例#20
0
 public static Hash Decode(IByteReader stream)
 {
     Hash decodedHash = new Hash();
       int Hashsize = 32;
       decodedHash.InnerValue = XdrEncoding.ReadFixOpaque(stream, (uint)Hashsize);
     return decodedHash;
 }
 public NodeSocketData(Hash PublicKey, int ListenPort, string IP, string Name)
 {
     this.PublicKey = PublicKey;
     this.ListenPort = ListenPort;
     this.IP = IP;
     this.Name = Name;
 }
 public void Init()
 {
     SignerPublicKey = new Hash();
     BallotHash = new Hash();
     Signature = new Hash();
     LedgerCloseSequence = 0;
 }
示例#23
0
    /*
    ** 2001 September 22
    **
    ** The author disclaims copyright to this source code.  In place of
    ** a legal notice, here is a blessing:
    **
    **    May you do good and not evil.
    **    May you find forgiveness for yourself and forgive others.
    **    May you share freely, never taking more than you give.
    **
    *************************************************************************
    ** This is the implementation of generic hash-tables
    ** used in SQLite.
    *************************************************************************
    **  Included in SQLite3 port to C#-SQLite;  2008 Noah B Hart
    **  C#-SQLite is an independent reimplementation of the SQLite software library
    **
    **  SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
    **
    *************************************************************************
    */
    //#include "sqliteInt.h"
    //#include <assert.h>

    /* Turn bulk memory into a hash table object by initializing the
    ** fields of the Hash structure.
    **
    ** "pNew" is a pointer to the hash table that is to be initialized.
    */
    static void sqlite3HashInit( Hash pNew )
    {
      Debug.Assert( pNew != null );
      pNew.first = null;
      pNew.count = 0;
      pNew.htsize = 0;
      pNew.ht = null;
    }
        async Task SendInitialize(Hash publicKey)
        {
            await Task.Delay(Common.random.Next(500, 1000)); // Wait a random delay before connecting.
            NetworkPacketQueueEntry npqe = new NetworkPacketQueueEntry(publicKey,
                new NetworkPacket(nodeConfig.PublicKey, PacketType.TPT_HELLO, new byte[0]));

            network.AddToQueue(npqe);
        }
 public void BuildUrlByRouteName()
 {
     var urlBuilder = TestFactory.CreateUrlBuilder(
         routes => routes.Map("PatientsShow", "Patients/{id}",
                       new { action = "Show", controller = "Patients" }, new { }));
     var parameters = new Hash { { "id", "123" } };
     Assert.AreEqual("/Patients/123", urlBuilder.BuildUrlByName("PatientsShow", parameters));
 }
示例#26
0
 public void When_Creating_element_With_Dictionary_Sticks()
 {
     var hash = new Hash {{"Key1", "Val1"}, {"Key2", "Val2"}, {"Key3", "Val3"}};
     var element = new CheckBoxField(hash);
     Assert.That(element.Tag, Is.EqualTo("input"));
     Assert.That(element.Attributes.Count == 4);
     Assert.That(element["Key1"] == "Val1");
 }
示例#27
0
 public RubyArray Call(IDictionary<object, object> env) {
     var envHash = new Hash(RubyEngine.Context);
     foreach (var pair in env) {
         var value = pair.Value.GetType() == "".GetType() ? MutableString.Create((string)pair.Value) : pair.Value;
         envHash[MutableString.Create((string)pair.Key)] = value;
     }
     return RubyEngine.ExecuteMethod<RubyArray>(_app, "call", envHash);
 }
示例#28
0
 public LeafDataType this[Hash hash]
 {
     get
     {
         if (Values.ContainsKey(hash)) return Values[hash];
         else throw new Exception("Key does not exist..."); // Think of better ways to do this...
     }
 }
示例#29
0
		public void SetUp()
		{
			_assigns = Hash.FromAnonymousObject(new
			{
				best_cars = "bmw",
				car = Hash.FromAnonymousObject(new { bmw = "good", gm = "bad" })
			});
		}
 /// <summary>
 /// Check whether the given PK is already connected.
 /// </summary>
 /// <param name="PublicKey"></param>
 /// <returns></returns>
 public bool IsConnected(Hash PublicKey)
 {
     if (IncomingConnections.ContainsKey(PublicKey))
     {
         return true;
     }
     else return false;
 }
示例#31
0
 public override int GetHashCode()
 => Hash.Combine(this.ClassificationType, this.TextSpan.GetHashCode());
示例#32
0
 public override int GetHashCode()
 {
     return(_errorInfo == null
         ? _name.GetHashCode()
         : Hash.Combine(_name, _errorInfo.Code));
 }
示例#33
0
        /// <summary>
        /// Создает HashKey для пользвателя
        /// </summary>
        /// <param name="hashKeySeed">Зерно для генерации ключа</param>
        /// <param name="l">Длина ключа</param>
        /// <returns>HashKey</returns>
        private string GethashKey(string hashKeySeed, int l)
        {
            string[] result          = new string[l / 3];
            string[] hashKeySeedData = new string[(int)Math.Ceiling(hashKeySeed.Length / 4.0)];
            for (int i = 0, j = 0; i < hashKeySeed.Length; i += 4, j++)
            {
                hashKeySeedData[j] = Hash.Sha512(new string(hashKeySeed.Skip(i).Take(4).ToArray())) + Hash.Sha512(new string(hashKeySeed.Skip(i).Take(4).ToArray().Reverse().ToArray()));
            }

            for (int i = 0, j = 0, k = 0; i < result.Length; i++, j++)
            {
                if (j > hashKeySeedData.Length - 1)
                {
                    j  = 0;
                    k += 2;

                    if (k > hashKeySeed.Length)
                    {
                        k = 0;
                    }
                }
                string current = new string(hashKeySeed.Skip(k).Take(2).ToArray());
                int    index   = Convert.ToInt32(current, 16);
                result[i] = new string(hashKeySeedData[j].Skip(index).Take(3).ToArray());
                if (result[i].Length < 3)
                {
                    for (int c = result[i].Length; c < 3; c++)
                    {
                        result[i] = "0" + result[i];
                    }
                }
            }

            return(string.Join("", result));
        }
 public List <Urun> HashAra(string Aciklama)
 {
     return(Hash.Ara(Aciklama));
 }
示例#35
0
 public override int GetHashCode()
 {
     return(Hash.Combine(_path, 0));
 }
示例#36
0
 public static IObservable <WWW> GetWWW(string url, Hash headers = null, IProgress <float> progress = null)
 {
     return(Observable.FromCoroutine <WWW>((observer, cancellation) => Fetch(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation)));
 }
示例#37
0
 public static IObservable <WWW> PostWWW(string url, byte[] postData, Hash headers, IProgress <float> progress = null)
 {
     return(Observable.FromCoroutine <WWW>((observer, cancellation) => Fetch(new WWW(url, postData, headers), observer, progress, cancellation)));
 }
示例#38
0
        public static IObservable <WWW> PostWWW(string url, WWWForm content, Hash headers, IProgress <float> progress = null)
        {
            var contentHeaders = content.headers;

            return(Observable.FromCoroutine <WWW>((observer, cancellation) => Fetch(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation)));
        }
示例#39
0
 public static Node node(Hash t, int i)
 {
     return(t.node.get(i));
 }
 public List <Urun> HashListele()
 {
     return(Hash.Listele());
 }
 public override int GetHashCode()
 {
     return(Hash.Combine(_originalDiagnostic.GetHashCode(),
                         Hash.Combine(_suppressionId.GetHashCode(), _suppressionJustification.GetHashCode())));
 }
 public sealed override int GetHashCode()
 {
     return(Hash.Combine(ContainingSymbol, _underlyingParameter.Ordinal));
 }
示例#43
0
 public override sealed int GetHashCode()
 {
     return(Hash.Combine(ContainingType.GetHashCode(), _tupleElementIndex.GetHashCode()));
 }
 /// <summary>Gets the localized text for the given code and language.</summary>
 /// <param name="code">The code to identify the text.</param>
 /// <param name="additionalData">The additional placeholder data to use in the text.</param>
 /// <param name="language">The language.</param>
 /// <returns>The localized text.</returns>
 public static string GetLocalizedText(string code, IDictionary <string, object> additionalData, string language)
 {
     return(GetLocalizedText(code, language, Hash.FromDictionary(additionalData)));
 }
示例#45
0
 public ChainSwap(string sourcePlatform, string sourceChain, Hash sourceHash, string destinationPlatform, string destinationChain, Hash destinationHash)
 {
     this.sourcePlatform      = sourcePlatform;
     this.sourceChain         = sourceChain;
     this.sourceHash          = sourceHash;
     this.destinationPlatform = destinationPlatform;
     this.destinationChain    = destinationChain;
     this.destinationHash     = destinationHash;
 }
 public Urun HashtenSil(string Aciklama)
 {
     return(Hash.Sil(Aciklama));
 }
示例#47
0
 public override int GetHashCode()
 {
     return(Hash.Combine(Mantissa.GetHashCode(), Exponent));
 }
        /// <summary>Gets the localized error message for the given exception.</summary>
        /// <param name="exception">The exception.</param>
        /// <param name="language">The language.</param>
        /// <returns>The localized error message.</returns>
        public static string GetLocalizedErrorCode(PictureparkException exception, string language)
        {
            var errorAsString = exception.GetType().Name;

            return(GetLocalizedText(errorAsString, language, Hash.FromAnonymousObject(exception)));
        }
示例#49
0
        private static bool ConfirmTransaction(JSONRPC_Client rpc, Logger logger, string host, Hash hash, int maxTries = 99999)
        {
            var hashStr = hash.ToString();

            int tryCount = 0;

            int delay = 250;

            do
            {
                var response = rpc.SendRequest(logger, host, "getConfirmations", hashStr);
                if (response == null)
                {
                    logger.Error("Transfer request failed");
                    return(false);
                }

                var confirmations = response.GetInt32("confirmations");
                if (confirmations > 0)
                {
                    logger.Success("Confirmations: " + confirmations);
                    return(true);
                }

                tryCount--;
                if (tryCount >= maxTries)
                {
                    return(false);
                }

                Thread.Sleep(delay);
                delay *= 2;
            } while (true);
        }
 public int GetHashCode(Diagnostic obj)
 {
     return(Hash.Combine(obj.Id.GetHashCode(), obj.Location.GetHashCode()));
 }
示例#51
0
        private ABIExitCode CompileTemplates(MetadataFile metadataFile)
        {
            _logger.Info("Templates process starting");

            #region Template path

            string templatePath = Path.Combine(_options.TemplatePath, metadataFile.Phase, metadataFile.Source);
            if (!Directory.Exists(templatePath))
            {
                return(ABIExitCode.ErrorTemplatePathSourceDirectoryNotExisting);
            }

            string templatePathVersionSpecific = Path.Combine(templatePath, metadataFile.TargetSQLPlatformVersion);
            if (Directory.Exists(templatePathVersionSpecific))
            {
                templatePath = templatePathVersionSpecific;
            }
            else
            {
                _logger.Debug("Template path for TargetSQLPlatformVersion '{0}' not found. Falling back to catch-all folder.", templatePathVersionSpecific);
            }

            _logger.Info("Using template path '{0}'", templatePath);

            #endregion

            #region Template search pattern

            string templateSearchPattern = metadataFile.Pattern;
            if (!string.IsNullOrEmpty(metadataFile.Source))
            {
                templateSearchPattern += "-" + metadataFile.Source;
            }
            if (!string.IsNullOrEmpty(metadataFile.Implementation))
            {
                templateSearchPattern += "-" + metadataFile.Implementation;
            }

            // BASE     -> phase\pattern-source-implementation.version.*
            // EXTENDED -> phase\pattern-source-implementation[-extensions].version.*
            string baseTemplateSearchPattern     = templateSearchPattern + "." + metadataFile.Version + ".*";
            string extendedTemplateSearchPattern = templateSearchPattern + "-*." + metadataFile.Version + ".*";

            _logger.Info("Template search patterns '{0}' '{1}'", baseTemplateSearchPattern, extendedTemplateSearchPattern);

            #endregion

            var templateFiles = Directory.EnumerateFiles(templatePath, baseTemplateSearchPattern)
                                .Union(Directory.EnumerateFiles(templatePath, extendedTemplateSearchPattern))
                                .OrderBy((path) => path)
                                .ToList();

            _logger.Info("Template files found '{0}'", templateFiles.Count);
            _logger.Debug("Listing template files found");
            foreach (string templateFile in templateFiles)
            {
                _logger.Debug("\t'{0}'", templateFile.Replace(templatePath, string.Empty));
            }

            foreach (string templateFile in templateFiles)
            {
                #region Process template

                _logger.Info("Processing template file '{0}'", Path.GetFileName(templateFile));
                _logger.Debug("Template file full path '{0}'", templateFile);

                _logger.Info("Creating context");
                var renderMetadata = (Dictionary <string, object>)JsonHelper.Deserialize(metadataFile.Json.ToString());

                _logger.Info("Parsing template file");
                var template = Template.Parse(File.ReadAllText(templateFile));

                _logger.Info("Rendering");
                string outputFileContent = string.Empty;
                try
                {
                    outputFileContent = template.Render(parameters: new RenderParameters
                    {
                        LocalVariables = Hash.FromDictionary(renderMetadata),
                        RethrowErrors  = true
                    });

                    metadataFile.Result.Warnings += template.Errors.Count();

                    foreach (var error in template.Errors)
                    {
                        _logger.Warn(error.Message);
                    }
                }
                catch (DotLiquid.Exceptions.LiquidException le)
                {
                    _logger.Error(le, "Exception occurred during template rendering");
                    return(ABIExitCode.ErrorTemplatePatternMissingInMetadata);
                }

                string outputPath = Path.Combine(_options.OutputPath, metadataFile.Phase);
                if (metadataFile.Phase.ToLower() == "load")
                {
                    outputPath = Path.Combine(outputPath, metadataFile.Pattern);
                }
                outputPath = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(metadataFile.FullName));
                _logger.Info("Using output path '{0}'", outputPath);

                string outputFile = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(metadataFile.FullName) + Path.GetExtension(Path.GetFileNameWithoutExtension(templateFile)));
                _logger.Info("Writing output file '{0}'", outputFile.Replace(_options.OutputPath, string.Empty));
                _logger.Debug("Output file full path '{0}'", outputFile);

                Directory.CreateDirectory(outputPath);
                File.WriteAllText(outputFile, outputFileContent);

                metadataFile.Result.Artifacts += 1;
                #endregion
            }

            _logger.Info("Templates process completed");

            if (metadataFile.Result.Warnings > 0)
            {
                return(ABIExitCode.CompileCompletedWithWarnings);
            }

            return(ABIExitCode.CompileCompleted);
        }
示例#52
0
        static int Main(string[] args)
        {
            var helpWriter = new StringWriter();
            var parser     = new Parser(with => with.HelpWriter = helpWriter);

            parser.ParseArguments <Options> (args)
            .WithParsed(x => _options = x)
            .WithNotParsed(DisplayHelp);

            void DisplayHelp(IEnumerable <Error> errs)
            {
                if (errs.IsVersion() || errs.IsHelp())
                {
                    Console.WriteLine(helpWriter.ToString());
                    Environment.Exit(0);
                }
                else
                {
                    Console.Error.WriteLine(helpWriter.ToString());
                    Environment.Exit(1);
                }
            }

            SystemEvents.SetConsoleEventHandler(ConsoleEventCallback);

            try
            {
                var hash          = Hash.FromAnonymousObject(_options);
                var appConfigText = Template.Parse(ReadResource("ApplicationHostConfig.xml")).Render(hash);
                ValidateRequiredDllDependencies(appConfigText);
                var webConfigText = Template.Parse(ReadResource("WebConfig.xml")).Render(hash);
                var aspNetText    = Template.Parse(ReadResource("AspNetConfig.xml")).Render(hash);

                Directory.CreateDirectory(_options.TempDirectory);
                Directory.CreateDirectory(_options.ConfigDirectory);
                File.WriteAllText(_options.ApplicationHostConfigPath, appConfigText);
                File.WriteAllText(_options.WebConfigPath, webConfigText);
                File.WriteAllText(_options.AspnetConfigPath, aspNetText);



                Console.WriteLine("Activating HWC with following settings:");
                try
                {
                    Console.WriteLine($"ApplicationHost.config: {_options.ApplicationHostConfigPath}");
                    Console.WriteLine($"Web.config: {_options.WebConfigPath}");
                    Console.WriteLine($"App folder: {_options.AppRootPathFull}");
                    HostableWebCore.Activate(_options.ApplicationHostConfigPath, _options.WebConfigPath, _options.ApplicationInstanceId);
                }
                catch (UnauthorizedAccessException)
                {
                    Console.Error.WriteLine("Access denied starting hostable web core. Start the application as administrator");
                    Console.WriteLine("===========================");
                    throw;
                }


                Console.WriteLine($"Server ID {_options.ApplicationInstanceId} started");
                // we gonna read on different thread here because Console.ReadLine is not the only way the program can end
                // we're also listening to the system events where the app is ordered to shutdown. exitWaitHandle is used to
                // hook up both of these events

                new Thread(() =>
                {
                    Console.ReadLine();
                    _exitWaitHandle.Set();
                }).Start();
                _exitWaitHandle.WaitOne();
                return(0);
            }

            catch (ValidationException ve)
            {
                Console.Error.WriteLine(ve.Message);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
            finally
            {
                Shutdown();
            }
            return(1);
        }
示例#53
0
        private void WriteFormatData(TokenEnum format, Data data, bool formatReadable)
        {
            switch (format)
            {
            case TokenEnum.Hex:
                Context.WriteOutputLine(data.ToHexString());
                break;

            case TokenEnum.Bin:
                Context.WriteOutputLine(data.ToBinaryString());
                break;

            case TokenEnum.Base64:
                Context.WriteOutputLine(data.ToBase64String());
                break;

            case TokenEnum.Url:
                Context.WriteOutputLine(Converter.UrlEncode(data));
                break;

            case TokenEnum.Txt:
                Context.WriteOutputLine(data.ToUtf8String());
                break;

            case TokenEnum.Ascii:
                Context.WriteOutputLine(data.ToAsciiString());
                break;

            case TokenEnum.AutoPrint:
                const int TXT_TH    = 80;
                const int LENGTH_TH = 8;
                const int HEX_TH    = TXT_TH / 2;
                const int B64_TH    = TXT_TH / 4 * 3;
                const int HASH_TH   = 8;

                Context.WriteOutputLine("---");

                if (data.Length > LENGTH_TH)
                {
                    Context.WriteOutputLine("LENGTH: " + data.Length.ToString());
                }

                Context.WriteOutputLine("HEX:    " + (data.Length > HEX_TH ? data.Sub(0, HEX_TH).ToHexString() + "..." : data.ToHexString()));

                if (data.Length < TXT_TH)
                {
                    if (data.IsPrintable())
                    {
                        Context.WriteOutputLine("ASCII:  " + data.ToAsciiString());
                    }
                    else
                    {
                        Context.WriteOutputLine("UTF8:   " + data.ToUtf8String());
                    }
                }

                if (data.Length < B64_TH)
                {
                    Context.WriteOutputLine("BASE64: " + data.ToBase64String());
                }

                if (data.Length > HASH_TH)
                {
                    Context.WriteOutputLine("MD5:    " + Hash.MD5(data).ToHexString());
                    Context.WriteOutputLine("SM3:    " + Hash.SM3(data).ToHexString());
                }

                Context.WriteOutputLine("---");
                break;

            default:
                throw new ArgumentException($"Parameter format should be PrintFormat.", nameof(format));
            }
        }
 public void Dispose()
 {
     Hash.Dispose();
 }
示例#55
0
        public ActionResult CheckForUpdate(string customerid = "", string updateshash = "")
        {
            string ClientIP = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

            if ((DateTime.Now - tLoadTime).TotalSeconds >= 60)
            {
                if (lCount > 60)
                {
                    bOverload = true;
                }
                else
                {
                    bOverload = false;
                }

                lCount    = 0;
                tLoadTime = DateTime.Now;
            }
            else
            {
                lCount++;
            }

            if (!Base.ValidateIP(ClientIP))
            {
                if (Environment.GetEnvironmentVariable("EnforceGetURL") == "true")
                {
                    return(Content((new JArray()).ToString()));
                }
            }
            else
            {
            }

            DateTime dStart = DateTime.Now;
            var      oGet   = new StreamReader(Request.Body).ReadToEndAsync();
            JArray   jItems = JArray.Parse(oGet.Result);

            if (jItems.Count > 0)
            {
                if (!string.IsNullOrEmpty(updateshash)) //still in use?
                {
                    if (updateshash != Hash.CalculateMD5HashString(oGet.Result))
                    {
                        return(Content((new JArray()).ToString()));
                    }
                    else
                    {
                        Console.WriteLine("CheckForUpdates Hash Error !");
                    }
                }

                string   sResult   = Base.CheckForUpdates(jItems, customerid).ToString();
                TimeSpan tDuration = DateTime.Now - dStart;
                if (!bOverload)
                {
                    _hubContext.Clients.All.SendAsync("Append", "<li class=\"list-group-item list-group-item-light\">%tt% - CheckForUpdates(items: " + jItems.Count + " , duration: " + Math.Round(tDuration.TotalSeconds).ToString() + "s) </li>");
                }
                Console.WriteLine("V2 UpdateCheck duration: " + tDuration.TotalMilliseconds.ToString() + "ms");
                Base.WriteLog("V2 UpdateCheck duration: " + Math.Round(tDuration.TotalSeconds).ToString() + "s", ClientIP, 1100, customerid);
                return(Content(sResult));
            }
            else
            {
                return(Content((new JArray()).ToString()));
            }
        }
示例#56
0
文件: ILSpan.cs 项目: belav/roslyn
 public override int GetHashCode() =>
 Hash.Combine(StartOffset.GetHashCode(), EndOffsetExclusive.GetHashCode());
示例#57
0
 public static NodeRef nodevector(Hash t)
 {
     return(t.node);
 }
示例#58
0
 private Hash CalculateVirtualHash(Hash organizationHash, Hash creationToken)
 {
     return(creationToken == null
         ? organizationHash
         : HashHelper.ConcatAndCompute(organizationHash, creationToken));
 }
 public void HasheUrunEkle(Urun urun, string Aciklama)
 {
     Hash.Ekle(Aciklama, urun);
 }
示例#60
0
 public static void nodevector(Hash t, NodeRef v)
 {
     t.node = v;
 }