private void Initialize(Binding binding)
        {
            AddAttribute("Protocol", binding.Protocol);
            AddAttribute("Port", binding.EndPoint.Port.ToString());

            if (binding.Host != "")
            {
                AddAttribute("HostName", binding.Host);
            }

            string address = binding.EndPoint.Address.ToString();

            if (address == "0.0.0.0")
            {
                address = "*";
            }

            AddAttribute("IPAddress", address);

            if (CodeGenHelpers.AreEqualCI(binding.Protocol, "https"))
            {
                AddAttribute("CertificateStoreName", binding.CertificateStoreName);
                AddAttribute("CertificateThumbprint", "the thumbprint of the cert you want to use");
            }
        }
Exemplo n.º 2
0
        public void Prettify_CapitalizesLettersFollowingUnderscores()
        {
            var s = "prettify_this_string";

            var indexes         = new HashSet <int>();
            var underscoreCount = 0;

            for (int i = 0; i < s.Length - 1; i++)
            {
                if (s[i] == '_')
                {
                    if (Char.IsLower(s[i + 1]))
                    {
                        indexes.Add(i - underscoreCount);
                    }

                    ++underscoreCount;
                }
            }

            var prettifiedString = CodeGenHelpers.Prettify(s);

            var actual   = prettifiedString.Skip(1).Where((c) => Char.IsUpper(c));
            var expected = indexes.Select((index) => prettifiedString[index]);

            Assert.Equal(expected, actual);
        }
    private static void DeserializeFormat0(ref MessagePackReader reader, MessagePackSerializerOptions options, ref string message, ref int number)
    {
        int length = reader.ReadMapHeader();
        int i      = 0;
        IFormatterResolver resolver = options.Resolver;

        while (i < length)
        {
            ReadOnlySpan <byte> stringKey = CodeGenHelpers.ReadStringSpan(ref reader);
            int   length2 = stringKey.Length;
            ulong key     = 0uL;
            if (length2 <= 8)
            {
                key = AutomataKeyGen.GetKey(ref stringKey);
            }

            if (length2 == 7 && key == 28542640894207341L)
            {
                message = reader.ReadString();
            }
            else if (length2 == 6 && key == 125779768604014L)
            {
                number = reader.ReadInt32();
            }
            else
            {
                reader.Skip();
            }

            i++;
        }
    }
Exemplo n.º 4
0
        public static McgField[] StructChildArrayToFieldArray(IMcgStructChild[] structChildren)
        {
            ArrayList alFields = new ArrayList();

            foreach (IMcgStructChild child in structChildren)
            {
                if (child is McgUnion)
                {
                    CodeGenHelpers.ThrowValidationException("Cannot flatten unions.");
                }

                McgField field = child as McgField;
                McgBlockCommentedFields block = child as McgBlockCommentedFields;

                if (field != null)
                {
                    alFields.Add(field);
                }
                else if (block != null)
                {
                    //CodeGenHelpers.ValidationAssert(block != null, "Unexpected child type.");

                    alFields.AddRange(StructChildArrayToFieldArray(block.Children));
                }
            }

            return((McgField[])alFields.ToArray(typeof(McgField)));
        }
Exemplo n.º 5
0
        public string GenerateCode(IisPoolAndSitesOptions options)
        {
            IISObjectFactory objectFactory = new IISObjectFactory();
            StringBuilder    sb            = new StringBuilder();

            List <SiteDesiredState> sites = objectFactory.BuildSites(options);
            List <PoolDesiredState> pools = objectFactory.BuildPools(options);

            string baseIndent = CodeGenHelpers.GetIndentString(2);
            string code;

            sb.AppendLine(baseIndent + "# Note this code does not detect server level IIS overrides (it assumes the IIS level settings");
            sb.AppendLine(baseIndent + "# have not been overriden).  See the wiki for information about detecting server level changes.\n");

            if (options.IisPoolAndSitesGenerationMode == IisPoolAndSitesGenerationMode.ConfigFileOrder)
            {
                code = GeneratePools(pools);
                sb.AppendLine(code);

                code = GenerateSites(sites);
                sb.AppendLine(code);
            }
            else
            {
                code = GenerateSitesAndPools(sites, pools);
                sb.AppendLine(code);
            }

            return(sb.ToString());
        }
Exemplo n.º 6
0
        public void WriteRaw()
        {
            // x86
            for (int i = 1; i <= MessagePackRange.MaxFixStringLength; i++)
            {
                var src       = Enumerable.Range(0, i).Select(x => (byte)x).ToArray();
                var dst       = new Sequence <byte>();
                var dstWriter = new MessagePackWriter(dst);
                (typeof(UnsafeMemory32).GetMethod("WriteRaw" + i).CreateDelegate(typeof(WriteDelegate)) as WriteDelegate).Invoke(ref dstWriter, src);
                dstWriter.Flush();
                dst.Length.Is(i);
                src.AsSpan().SequenceEqual(CodeGenHelpers.GetSpanFromSequence(dst.AsReadOnlySequence)).IsTrue();
            }

            // x64
            for (int i = 1; i <= MessagePackRange.MaxFixStringLength; i++)
            {
                var src       = Enumerable.Range(0, i).Select(x => (byte)x).ToArray();
                var dst       = new Sequence <byte>();
                var dstWriter = new MessagePackWriter(dst);
                (typeof(UnsafeMemory64).GetMethod("WriteRaw" + i).CreateDelegate(typeof(WriteDelegate)) as WriteDelegate).Invoke(ref dstWriter, src);
                dstWriter.Flush();
                dst.Length.Is(i);
                src.AsSpan().SequenceEqual(CodeGenHelpers.GetSpanFromSequence(dst.AsReadOnlySequence)).IsTrue();
            }
        }
Exemplo n.º 7
0
        public void Prettify_PreservesCapitalizationOfAlreadyCapitalizedLetters()
        {
            var s = "pReTtIfY";

            var expected = s.Where((c) => Char.IsUpper(c));
            var actual   = CodeGenHelpers.Prettify(s).Skip(1).Where((c) => Char.IsUpper(c));

            Assert.Equal(expected, actual);
        }
Exemplo n.º 8
0
        public WindowsFeature(string variableName, string featureName, string ensureState
                              , string description = "")
        {
            this.Key = CodeGenHelpers.FormatKey(variableName, "Feature");
            this.ObjectDescription = description;

            this.AddAttribute("Name", featureName);
            this.AddAttribute("Ensure", ensureState);
        }
Exemplo n.º 9
0
        public override string GetChildCode(int baseIndentDepth)
        {
            string baseIndent = CodeGenHelpers.GetIndentString(baseIndentDepth);

            var code = "";

            code += GetChildListCode("BindingInfo", this.Bindings.ToList <DesiredStateBase>(), baseIndentDepth, baseIndent);

            code += GetChildListCode("WebConfigProp", this.AuthDesiredStateList.ToList <DesiredStateBase>(), baseIndentDepth, baseIndent);

            return(code);
        }
Exemplo n.º 10
0
        public override string GetChildCode(int baseIndentDepth)
        {
            string baseIndent = CodeGenHelpers.GetIndentString(baseIndentDepth);

            string code = "";

            if (AuthenticationInfo != null)
            {
                code += baseIndent + "AuthenticationInfo = \n" + this.AuthenticationInfo.GetCode(baseIndentDepth + 2, CodeGenType.SingleChild);
            }

            return(code);
        }
Exemplo n.º 11
0
        public void GetEncodedStringBytes(char c, int count)
        {
            var s          = new string(c, count);
            var bin1       = CodeGenHelpers.GetEncodedStringBytes(s);
            var bin2       = MessagePackSerializer.Serialize(s);
            var bin3       = new Sequence <byte>();
            var bin3Writer = new MessagePackWriter(bin3);

            bin3Writer.WriteRaw(bin1);
            bin3Writer.Flush();

            new ReadOnlySpan <byte>(bin1).SequenceEqual(bin2).IsTrue();
            new ReadOnlySpan <byte>(bin1).SequenceEqual(CodeGenHelpers.GetSpanFromSequence(bin3)).IsTrue();
        }
        public void GetEncodedStringBytes(char c, int count)
        {
            var s          = new string(c, count);
            var bin1       = CodeGenHelpers.GetEncodedStringBytes(s);
            var bin2       = MessagePackSerializer.Serialize(s);
            var bin3       = new Sequence <byte>();
            var bin3Writer = new MessagePackWriter(bin3);

            bin3Writer.WriteRaw(bin1);
            bin3Writer.Flush();

            MessagePack.Internal.ByteArrayComparer.Equals(bin1, bin2).IsTrue();
            MessagePack.Internal.ByteArrayComparer.Equals(bin1, CodeGenHelpers.GetSpanFromSequence(bin3)).IsTrue();
        }
Exemplo n.º 13
0
        public override string GetChildCode(int baseIndentDepth)
        {
            string baseIndent = CodeGenHelpers.GetIndentString(baseIndentDepth);

            string code = "";

            code += CodeGenHelpers.GenerateChildListCode("BindingInfo", this.Bindings.ToList <DesiredStateBase>(), baseIndentDepth, baseIndent);

            if (AuthenticationInfo != null)
            {
                code += baseIndent + "AuthenticationInfo = \n" + this.AuthenticationInfo.GetCode(baseIndentDepth + 2, CodeGenType.SingleChild);
            }

            return(code);
        }
Exemplo n.º 14
0
        internal McgUnion(
            IMcgStructChild[] children
            )
        {
            foreach (IMcgStructChild child in children)
            {
                if (child is McgUnion)
                {
                    CodeGenHelpers.ThrowValidationException(
                        String.Format("Nested unions are not allowed"));
                }
            }

            Children = children;
        }
Exemplo n.º 15
0
        private void FixEnums()
        {
            foreach (var e in EnumCache)
            {
                foreach (var v in e.Values)
                {
                    if (String.IsNullOrEmpty(v.Name))
                    {
                        v.Name = CodeGenHelpers.Prettify(v.JsonName);
                    }
                }

                CodeGenHelpers.NonNullableTypes.Add(e.Name);
            }
        }
Exemplo n.º 16
0
        public string GenerateIisSiteImports()
        {
            string        code = "";
            StringBuilder sb   = new StringBuilder();

            string indent = CodeGenHelpers.GetIndentString(1);

            sb.AppendLine(indent + "# Information about where to get needed modules and required version information can ");
            sb.AppendLine(indent + "# be found here: https://github.com/kevinsea/dsc-generator/wiki/Powershell-Modules");
            sb.AppendLine(indent + "# ---------------------------------------------------------------------------------");
            sb.AppendLine("");
            sb.AppendLine(indent + "Import-DscResource -ModuleName xWebAdministration");

            return(sb.ToString());
        }
        public WebConfigPropertyDesiredState(string filter, string propertyName, string value, string siteLocation)
        {
            SiteName = siteLocation.Split('/')[0];

            var elements          = filter.Split('/');
            var parentElementName = elements[elements.Length - 1];

            this.Key = CodeGenHelpers.FormatKey(siteLocation + "_" + parentElementName.Replace("Authentication", "Auth") + "_" + propertyName);

            this.SiteLocation = siteLocation;
            this.AddAttribute("Location", siteLocation);
            this.AddAttribute("Filter", filter);
            this.AddAttribute("Name", propertyName);
            this.AddAttribute("Value", value);
            this.AddAttribute("PSPath", "MACHINE/WEBROOT/APPHOST");
        }
Exemplo n.º 18
0
        internal McgBlockCommentedFields(
            IMcgStructChild[] children,
            string comment
            )
        {
            foreach (IMcgStructChild child in children)
            {
                if (child is McgBlockCommentedFields)
                {
                    CodeGenHelpers.ThrowValidationException(
                        String.Format("Nested block comments are not allowed: '{0}'", comment));
                }
            }

            Children = children;
            Comment  = comment;
        }
        private static void DeserializeFormat0(ref MessagePackReader reader, MessagePackSerializerOptions options, ref Type type, ref IExposedWrapper wrapper)
        {
            int count    = reader.ReadMapHeader();
            int typeHash = 0;

            for (int i = 0; i < count; i++)
            {
                ReadOnlySpan <byte> stringKey = CodeGenHelpers.ReadStringSpan(ref reader);

                switch (stringKey.Length)
                {
                default:
FAIL:
                    reader.Skip();
                    continue;

                case 4:
                    if (AutomataKeyGen.GetKey(ref stringKey) != 1701869940UL)
                    {
                        goto FAIL;
                    }

                    typeHash = reader.ReadInt32();
                    type     = LevelEditorSerializer.GetType(typeHash);
                    continue;

                case 10:
                    if (!stringKey.SequenceEqual(SpanProperties.Slice(1)))
                    {
                        goto FAIL;
                    }

                    if (type == null)
                    {
                        Debug.LogWarning($"Couldn't find a wrapper for type hash {typeHash}.");
                        reader.Skip();
                        continue;
                    }

                    ((LevelEditorResolver)LevelEditorResolver.instance).DeserializeWrapper(type, ref reader, options, out wrapper);
                    continue;
                }
            }
        }
Exemplo n.º 20
0
        private string GenerateSitesAndPools(IEnumerable <SiteDesiredState> siteList
                                             , IEnumerable <PoolDesiredState> poolList)
        {
            string        code        = "";
            int           poolCounter = 0;
            StringBuilder sb          = new StringBuilder();

            List <PoolDesiredState> poolsLeftToGenerate = new List <PoolDesiredState>(poolList);

            siteList = siteList.OrderBy(s => s.Name);

            foreach (SiteDesiredState site in siteList)
            {
                code = GetSiteHeader(site);
                sb.Append(code);

                foreach (string poolName in site.GetPoolsReferenced())
                {
                    var poolToGenerate = poolsLeftToGenerate.FirstOrDefault(p => p.Name == poolName);

                    if (poolToGenerate != null)
                    {
                        code = GeneratePool(poolToGenerate, poolCounter);
                        poolCounter++;
                        sb.AppendLine(code);

                        poolsLeftToGenerate.Remove(poolToGenerate);
                    }
                    else
                    {
                        code = CodeGenHelpers.GetIndentString(2)
                               + string.Format("# Pool '{0}' was generated with an earlier site\n", poolName);

                        sb.Append(code);
                    }
                }

                sb.AppendLine("");
                sb.Append(GenerateSite(site));
            }

            return(sb.ToString());
        }
Exemplo n.º 21
0
        private static void DeserializeFormat0(ref MessagePackReader reader, MessagePackSerializerOptions options, ref Type type, ref object value)
        {
            int count    = reader.ReadMapHeader();
            int typeHash = 0;

            for (int i = 0; i < count; i++)
            {
                ReadOnlySpan <byte> stringKey = CodeGenHelpers.ReadStringSpan(ref reader);
                switch (stringKey.Length)
                {
                default:
FAIL:
                    reader.Skip();
                    continue;

                case 4:
                    if (AutomataKeyGen.GetKey(ref stringKey) != 1701869940UL)
                    {
                        goto FAIL;
                    }

                    typeHash = reader.ReadInt32();
                    type     = LevelEditorSerializer.GetType(typeHash);
                    continue;

                case 5:
                    if (AutomataKeyGen.GetKey(ref stringKey) != 435761734006UL)
                    {
                        goto FAIL;
                    }

                    if (type == null)
                    {
                        Debug.LogWarning($"Can't deserialize some custom data because there's no type with hash {typeHash}.");
                        reader.Skip();
                        break;
                    }

                    ((LevelEditorResolver)LevelEditorResolver.instance).DeserializeDynamic(type, ref reader, out value, options);
                    continue;
                }
            }
        }
Exemplo n.º 22
0
        public List <SiteDesiredState> BuildSites(IISCodeGenerator.IisPoolAndSitesOptions iisOptions)
        {
            ServerManager           serverManager      = new ServerManager();
            List <SiteDesiredState> siteCodeList       = new List <SiteDesiredState>();
            WebConfigPropertyDesiredStateAssembler gen = new WebConfigPropertyDesiredStateAssembler();

            List <WebConfigPropertyDesiredState> authDesiredStateList = gen.GetAuthenticationDesiredStates();

            foreach (var site in serverManager.Sites)
            {
                var siteName = site.Name;
                var siteAuthDesiredStateList = authDesiredStateList.Where(a => CodeGenHelpers.AreEqualCI(a.SiteName, siteName));
                var siteCode = new SiteDesiredState(site, siteAuthDesiredStateList, iisOptions);

                siteCodeList.Add(siteCode);
            }

            return(siteCodeList);
        }
Exemplo n.º 23
0
        private void FixClasses()
        {
            foreach (var c in ClassCache)
            {
                if (c.Suffix == null)
                {
                    c.Suffix = ": IStackExchangeModel";
                }

                foreach (var p in c.Properties)
                {
                    if (String.IsNullOrWhiteSpace(p.Name))
                    {
                        p.Name = CodeGenHelpers.Prettify(p.JsonName);
                    }

                    p.IsEnum = EnumCache.Any((e) => e.Name == p.Type);
                }
            }
        }
Exemplo n.º 24
0
 private static string GetVirtualDirectoryVariableName(string name1, string name2)
 {
     return(CodeGenHelpers.FormatKey(name1, name2, "Virt"));
 }
Exemplo n.º 25
0
        public List <WindowsFeature> GetFeatures()
        {
            var features = new List <WindowsFeature>();

            var featureLookupSupport = GetFeatureLookupSupport();

            PowerShell ps = PowerShell.Create();

            if (featureLookupSupport == FeatureLookupSupport.GetWindowsFeature) // Windows server >= 2008
            {
                ps.AddCommand("Get-WindowsFeature");                            //ps.AddParameter("-online"); //
                var psResult = ps.Invoke();

                var listToProcess = psResult
                                    .Where(o => o.Properties["Name"].Value.ToString().StartsWith("Web-"))
                                    .OrderBy(o => o.Properties["Name"].Value.ToString());

                foreach (var psFeature in listToProcess)
                {
                    string featureName = (string)psFeature.Properties["Name"].Value;
                    string displayName = (string)psFeature.Properties["DisplayName"].Value;
                    string installed   = (string)psFeature.Properties["Installed"].Value.ToString();

                    var stateStr = (CodeGenHelpers.AreEqualCI(installed, "true")) ? "Present" : "Absent";

                    var feature = new WindowsFeature(featureName, featureName, stateStr, displayName);

                    features.Add(feature);
                }
            }
            else if (featureLookupSupport == FeatureLookupSupport.GetWindowsOptionalFeature)             // Windows 8 version
            {
                var x = ps.AddCommand("Get-WindowsOptionalFeature").AddParameter("online");

                Collection <PSObject> psResult;

                psResult = ps.Invoke();                         //this call throws a first chance exception that is supressed internally

                var listToProcess = psResult
                                    .Where(o => o.Properties["FeatureName"].Value.ToString().StartsWith("IIS-"))
                                    .OrderByDescending(o => o.Properties["State"].Value.ToString())
                                    .ThenBy(o => o.Properties["FeatureName"].Value.ToString());

                foreach (var psFeature in listToProcess)
                {
                    var featureName = (string)psFeature.Properties["FeatureName"].Value;

                    var state = (string)psFeature.Properties["State"].Value.ToString();

                    var stateStr = (state == "Enabled") ? "Present" : "Absent";

                    var feature = new WindowsFeature(featureName, featureName, stateStr);

                    features.Add(feature);
                }
            }

            else
            {
                var feature = new WindowsFeature("IIS", "Web-Server", "Present", "Correct PowerShell command not present, settting IIS Base");
                features.Add(feature);
            }

            return(features);
        }
Exemplo n.º 26
0
 internal static string GetPoolVariableName(string poolName)
 {
     return(CodeGenHelpers.FormatKey(poolName, "Pool"));
 }
        static void EmitSerializeUnionCase(
            ILGenerator il,
            Type type,
            TypeInfo ti,
            UnionSerializationInfo info,
            FieldBuilder stringByteKeysField,
            ArgumentField argWriter,
            ArgumentField argValue,
            ArgumentField argOptions,
            LocalBuilder localResolver
            )
        {
            if (info.IsIntKey)
            {
                // use Array
                var maxKey    = info.Members.Select(x => x.IntKey).DefaultIfEmpty(-1).Max();
                var intKeyMap = info.Members.ToDictionary(x => x.IntKey);

                var len = maxKey + 1;
                argWriter.EmitLoad();
                il.EmitLdc_I4(len);
                il.EmitCall(MessagePackWriterTypeInfo.WriteArrayHeader);

                var index = 0;
                for (int i = 0; i <= maxKey; i++)
                {
                    UnionSerializationInfo.EmittableMember member;
                    if (intKeyMap.TryGetValue(i, out member))
                    {
                        EmitSerializeValue(il, ti, member, index++, argWriter, argValue, argOptions, localResolver);
                    }
                    else
                    {
                        // Write Nil as Blanc
                        argWriter.EmitLoad();
                        il.EmitCall(MessagePackWriterTypeInfo.WriteNil);
                    }
                }
            }
            else
            {
                // use Map
                var writeCount = info.Members.Count();

                argWriter.EmitLoad();
                il.EmitLdc_I4(writeCount);
                ////if (writeCount <= MessagePackRange.MaxFixMapCount)
                ////{
                ////    il.EmitCall(MessagePackWriterTypeInfo.WriteFixedMapHeaderUnsafe);
                ////}
                ////else
                {
                    il.EmitCall(MessagePackWriterTypeInfo.WriteMapHeader);
                }

                var index = 0;
                foreach (UnionSerializationInfo.EmittableMember item in info.Members)
                {
                    argWriter.EmitLoad();
                    il.EmitLoadThis();
                    il.EmitLdfld(stringByteKeysField);
                    il.EmitLdc_I4(index);
                    il.Emit(OpCodes.Ldelem_Ref);
                    il.Emit(OpCodes.Call, ReadOnlySpanFromByteArray); // convert byte[] to ReadOnlySpan<byte>

                    // Optimize, WriteRaw(Unity, large) or UnsafeMemory32/64.WriteRawX
                    var valueLen = CodeGenHelpers.GetEncodedStringBytes(item.StringKey).Length;
                    if (valueLen <= MessagePackRange.MaxFixStringLength)
                    {
                        if (UnsafeMemory.Is32Bit)
                        {
                            il.EmitCall(typeof(UnsafeMemory32).GetRuntimeMethod("WriteRaw" + valueLen, new[] { typeof(MessagePackWriter).MakeByRefType(), typeof(ReadOnlySpan <byte>) }));
                        }
                        else
                        {
                            il.EmitCall(typeof(UnsafeMemory64).GetRuntimeMethod("WriteRaw" + valueLen, new[] { typeof(MessagePackWriter).MakeByRefType(), typeof(ReadOnlySpan <byte>) }));
                        }
                    }
                    else
                    {
                        il.EmitCall(MessagePackWriterTypeInfo.WriteRaw);
                    }

                    EmitSerializeValue(il, type.GetTypeInfo(), item, index, argWriter, argValue, argOptions, localResolver);
                    index++;
                }
            }
        }
Exemplo n.º 28
0
 internal static string GetSiteKey(string siteName)
 {
     return(CodeGenHelpers.FormatKey(siteName) + "_Site");
 }
Exemplo n.º 29
0
        public void Prettify_CapitalizesFirstLetter()
        {
            var actual = CodeGenHelpers.Prettify("prettify");

            Assert.True(actual[0] == 'P');
        }
Exemplo n.º 30
0
        public void Prettify_RemovesUnderscores()
        {
            var actual = CodeGenHelpers.Prettify("prettify_this_string");

            Assert.True(!actual.Any((c) => c == '_'));
        }