示例#1
0
            public static StringConversions__ElementType[] ConvertStringToElementTypeArray(string e)
            {
                if (string.IsNullOrEmpty(e))
                {
                    return(null);
                }

                var xml = StringConversions.ConvertStringToXElement(e);

                //<array c="2">
                //  <i0>2</i0>
                //  <i1>0</i1>
                //</array>

                //Console.WriteLine(new { xml });

                var Length = int.Parse(xml.Attribute("c").Value);

                //Console.WriteLine(new { Length });


                var y = new StringConversions__ElementType[Length];

                for (int i = 0; i < Length; i++)
                {
                    //Console.WriteLine(new { i });

                    y[i] = FromString(xml.Element("i" + i).Value);
                }

                return(y);
            }
示例#2
0
            public static List <StringConversions__ElementType> ConvertStringToListOfElementType(string e)
            {
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201405/20140517
                // X:\jsc.svn\examples\javascript\UIAutomationEvents\UIAutomationEvents\Application.cs
                // X:\jsc.svn\examples\javascript\test\TestWebMethodTaskOfIEnumerable\TestWebMethodTaskOfIEnumerable\ApplicationWebService.cs
                //return ConvertStringToElementTypeArray(e).AsEnumerable();

                #region return inline ConvertStringToElementTypeArray
                var xml = StringConversions.ConvertStringToXElement(e);

                //&lt;array c=&quot;2&quot;&gt;
                //  &lt;i0&gt;2&lt;/i0&gt;
                //  &lt;i1&gt;0&lt;/i1&gt;
                //&lt;/array&gt;

                //Console.WriteLine(new { xml });

                var Length = int.Parse(xml.Attribute("c").Value);

                //Console.WriteLine(new { Length });


                var y = new StringConversions__ElementType[Length];

                for (int i = 0; i < Length; i++)
                {
                    //Console.WriteLine(new { i });

                    y[i] = FromString(xml.Element("i" + i).Value);
                }

                return(y.ToList());

                #endregion
            }
示例#3
0
        private static Boolean TryParsePublicKeyFullOrToken(CILAssemblyName assemblyName, String fullAssemblyName, ref Int32 nameIdx)
        {
            var aux     = NextSeparatorIdx(fullAssemblyName, ASSEMBLY_NAME_ELEMENTS_SEPARATOR, nameIdx);
            var success = aux > 0;

            if (success && !String.Equals("null", fullAssemblyName.Substring(nameIdx, aux), StringComparison.OrdinalIgnoreCase))
            {
                assemblyName._publicKey = StringConversions.HexStr2ByteArray(fullAssemblyName, nameIdx, 0, 0);
            }
            nameIdx += aux;
            return(success);
        }
示例#4
0
        /// <summary>
        /// Creates default base64 lookup character array, and reorders it using <see cref="DigestBasedRandomGenerator"/> with given parameters.
        /// </summary>
        /// <param name="seed">The seed material to <see cref="DigestBasedRandomGenerator"/>, as <see cref="Byte"/> array.</param>
        /// <param name="algorithm">The <see cref="DigestAlgorithm"/> to use. If <c>null</c>, then <see cref="SHA512"/> will be used.</param>
        /// <param name="seedCycleCount">How often the seed will be re-digested.</param>
        /// <param name="isURLSafe">Whether to use url-safe base64 characters.</param>
        /// <returns>A base64 lookup character array, shuffled using the given <paramref name="seed"/>.</returns>
        /// <seealso cref="StringConversions.EncodeBinary(global::System.Byte[], global::System.Char[])"/>
        public static Char[] ShuffleBase64CharactersFromSeed(
            Byte[] seed,
            DigestAlgorithm algorithm = null,
            Int32 seedCycleCount      = 10,
            Boolean isURLSafe         = true
            )
        {
            var chars = StringConversions.CreateBase64EncodeLookupTable(isURLSafe);

            ShuffleBinaryEncodingCharactersFromSeed(chars, seed, algorithm: algorithm, seedCycleCount: seedCycleCount);
            return(chars);
        }
示例#5
0
        /// <summary>gets a stringified representation</summary>
        public override string ToString()
        {
            // encode the IOR to a CDR-stream, afterwards write it to the iorStream
            using (MemoryStream content = new MemoryStream()) {
                byte            flags  = 0;
                CdrOutputStream stream = new CdrOutputStreamImpl(content, flags);
                stream.WriteOctet(flags); // writing the flags before the IOR
                // write content to the IORStream
                WriteToStream(stream);

                return(StringConversions.Stringify("IOR:", content.GetBuffer(), (int)content.Length));
            }
        }
示例#6
0
        /// <summary>parses an iiop-addr string</summary>
        private void ParseIiopAddr(string iiopAddr, int protocolPrefixLength)
        {
            // version part
            int hostIndex;
            int atIndex = iiopAddr.IndexOf('@', protocolPrefixLength);

            if (atIndex >= 0)
            {
                // version spec
                string   versionPart  = iiopAddr.Substring(protocolPrefixLength, atIndex - protocolPrefixLength);
                string[] versionParts = versionPart.Split(new char[] { '.' }, 2);
                try {
                    byte major = System.Byte.Parse(versionParts[0]);
                    if (versionParts.Length != 2)
                    {
                        throw new BAD_PARAM(9, CompletionStatus.Completed_No);
                    }
                    byte minor = System.Byte.Parse(versionParts[1]);
                    m_version = new GiopVersion(major, minor);
                } catch (Exception) {
                    throw new BAD_PARAM(9, CompletionStatus.Completed_No);
                }
                hostIndex = atIndex + 1;
            }
            else
            {
                m_version = new GiopVersion(1, 0); // default
                hostIndex = protocolPrefixLength;
            }

            // host, port part
            int commaIndex = iiopAddr.IndexOf(':', hostIndex);

            if (commaIndex >= 0)
            {
                m_host = iiopAddr.Substring(hostIndex, commaIndex - hostIndex);
                try {
                    m_port = System.Int32.Parse(iiopAddr.Substring(commaIndex + 1));
                } catch (Exception) {
                    throw new BAD_PARAM(9, CompletionStatus.Completed_No);
                }
            }
            else
            {
                m_host = iiopAddr.Substring(hostIndex);
            }
            if (StringConversions.IsBlank(m_host))
            {
                m_host = "localhost";
            }
        }
示例#7
0
            public static string ConvertListOfElementTypeToString(List <StringConversions__ElementType> ee)
            {
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201405/20140517
                // X:\jsc.svn\examples\javascript\test\TestWebMethodTaskOfIEnumerable\TestWebMethodTaskOfIEnumerable\ApplicationWebService.cs
                //return ConvertElementTypeArrayToString(e.ToArray());


                //Unable to cast object of type 'System.Int32[]' to type 'System.Object[]'.

                //Console.WriteLine("enter ConvertElementTypeArrayToString");

                #region return inline ConvertElementTypeArrayToString
                if (ee == null)
                {
                    return(null);
                }

                //var o = (object[])e;

                var e = ee.ToArray();

                var xml = new XElement("enumerable");

                var Length = e.Length;

                xml.Add(new XAttribute("c", "" + Length));

                for (int i = 0; i < Length; i++)
                {
                    // ldelem.ref ?
                    var item = e[i];

                    //                 [MethodAccessException: Attempt by method &#39;mscorlib.&lt;020000f3Array\+ConvertToString&gt;.ConvertToString(Int32[])&#39; to access method &#39;&lt;&gt;f__AnonymousType4d`2&lt;System.Int32,System.__Canon&gt;..ctor(Int32, System.__Canon)&#39; failed.]
                    //mscorlib.&lt;020000f3Array\+ConvertToString&gt;.ConvertToString(Int32[] ) +305


                    //Console.WriteLine("i: " + i + ", item: " + item);

                    xml.Add(new XElement("i" + i, ToString((StringConversions__ElementType)item)));
                }

                var value = StringConversions.ConvertXElementToString(xml);

                //Console.WriteLine("value: " + value);

                return(value);

                #endregion
            }
示例#8
0
            public static IEnumerable <StringConversions__ElementType> ConvertStringToElementTypeEnumerable(string e)
            {
                //Additional information: Attempt by method 'mscorlib.<02000005IEnumerable\+ConvertToString>.ConvertToString(System.Collections.Generic.IEnumerable`1<TestIEnumerableForService.foo>)' to access method '<>f__AnonymousType6`1<System.__Canon>..ctor(System.__Canon)' failed.


                // X:\jsc.svn\examples\javascript\Test\TestIEnumerableForService\TestIEnumerableForService\ApplicationWebService.cs
                //Console.WriteLine("enter ConvertStringToElementTypeEnumerable " + new { e });
                //Console.WriteLine("enter ConvertStringToElementTypeEnumerable e:" + e);

                // X:\jsc.svn\examples\javascript\test\TestWebMethodTaskOfIEnumerable\TestWebMethodTaskOfIEnumerable\ApplicationWebService.cs
                //return ConvertStringToElementTypeArray(e).AsEnumerable();

                #region return inline ConvertStringToElementTypeArray
                var xml = StringConversions.ConvertStringToXElement(e);

                // X:\jsc.svn\examples\javascript\Test\TestIEnumerableForService\TestIEnumerableForService\ApplicationWebService.cs
                if (xml == null)
                {
                    return(null);
                }


                //&lt;array c=&quot;2&quot;&gt;
                //  &lt;i0&gt;2&lt;/i0&gt;
                //  &lt;i1&gt;0&lt;/i1&gt;
                //&lt;/array&gt;

                //Console.WriteLine(new { xml });

                var Length = int.Parse(xml.Attribute("c").Value);

                //Console.WriteLine(new { Length });


                var y = new StringConversions__ElementType[Length];

                for (int i = 0; i < Length; i++)
                {
                    //Console.WriteLine(new { i });

                    y[i] = FromString(xml.Element("i" + i).Value);
                }

                return(y.AsEnumerable());

                #endregion
            }
示例#9
0
 /// <summary>
 /// maps a CLS namespace to a module hirarchy
 /// </summary>
 // used for generator
 public static string[] MapNamespaceNameToIdlModules(string clsNamespace)
 {
     string[] modules;
     if ((clsNamespace != null) && !StringConversions.IsBlank(clsNamespace))
     {
         modules = clsNamespace.Split('.');
     }
     else
     {
         modules = new string[0];
     }
     for (int i = 0; i < modules.Length; i++)
     {
         modules[i] = MapClsNameToIdlName(modules[i]);
     }
     return(modules);
 }
示例#10
0
 /// <summary>
 /// creates an IOR from the IOR stringified form
 /// </summary>
 public Ior(string iorAsString)
 {
     // iorAsString contains only characters 0-9, A-F and IOR --> all of this are short characters
     if (iorAsString.StartsWith("IOR:"))
     {
         MemoryStream       memStream = new MemoryStream(StringConversions.Destringify(iorAsString, 4));
         CdrInputStreamImpl cdrStream = new CdrInputStreamImpl(memStream);
         byte flags = cdrStream.ReadOctet();
         cdrStream.ConfigStream(flags, new GiopVersion(1, 2)); // giop dep operation are not used for IORs
         List <IorProfile> profiles = new List <IorProfile>();
         ParseIOR(cdrStream, out m_typId, profiles);
         m_profiles = profiles.ToArray();
     }
     else
     {
         throw new INV_OBJREF(9420, CompletionStatus.Completed_No);
     }
 }
示例#11
0
        private void VerifyNativeVsFluentCryptography(
            TNativeAlgorithmFactory nativeFactory,
            TUtilPackAlgorithmFactory utilPackFactory,
            Byte[] key,
            Int32 minLength,
            Int32 maxLength
            )
        {
            var r     = new Random();
            var count = minLength + (Math.Abs(r.NextInt32()) % (maxLength - minLength));
            var bytez = r.NextBytes(count);

            Byte[] nativeHash;
            using (var native = nativeFactory(key.CreateArrayCopy()))
            {
                nativeHash = native.ComputeHash(bytez);
            }

            Byte[] camHash;
            using (var cam = utilPackFactory(key.CreateArrayCopy()))
            {
                camHash = cam.ComputeDigest(bytez, 0, bytez.Length);

                Assert.IsTrue(
                    ArrayEqualityComparer <Byte> .ArrayEquality(nativeHash, camHash),
                    "The hash differed:\nNative hash: {0}\nUtilPack hash: {1}\ninput: {2}",
                    StringConversions.CreateHexString(nativeHash),
                    StringConversions.CreateHexString(camHash),
                    StringConversions.CreateHexString(bytez)
                    );

                // Test that resetting works by computing same digest again
                camHash = cam.ComputeDigest(bytez, 0, bytez.Length);
                Assert.IsTrue(
                    ArrayEqualityComparer <Byte> .ArrayEquality(nativeHash, camHash),
                    "The hash differed:\nNative hash: {0}\nUtilPack hash: {1}\ninput: {2}",
                    StringConversions.CreateHexString(nativeHash),
                    StringConversions.CreateHexString(camHash),
                    StringConversions.CreateHexString(bytez)
                    );
            }
        }
示例#12
0
            public static string ConvertElementTypeArrayToString(StringConversions__ElementType[] e)
            {
                //Unable to cast object of type 'System.Int32[]' to type 'System.Object[]'.

                //Console.WriteLine("enter ConvertElementTypeArrayToString");

                if (e == null)
                {
                    return(null);
                }

                //var o = (object[])e;


                var xml = new XElement("array");

                var Length = e.Length;

                xml.Add(new XAttribute("c", "" + Length));

                for (int i = 0; i < Length; i++)
                {
                    // ldelem.ref ?
                    var item = e[i];

                    //                 [MethodAccessException: Attempt by method &#39;mscorlib.&lt;020000f3Array\+ConvertToString&gt;.ConvertToString(Int32[])&#39; to access method &#39;&lt;&gt;f__AnonymousType4d`2&lt;System.Int32,System.__Canon&gt;..ctor(Int32, System.__Canon)&#39; failed.]
                    //mscorlib.&lt;020000f3Array\+ConvertToString&gt;.ConvertToString(Int32[] ) +305


                    //Console.WriteLine("i: " + i + ", item: " + item);

                    xml.Add(new XElement("i" + i, ToString((StringConversions__ElementType)item)));
                }

                var value = StringConversions.ConvertXElementToString(xml);

                //Console.WriteLine("value: " + value);

                return(value);
            }
        private static Assembly DoLoadGeneratedAssembly(Assembly assembly, ApplicationModel <Qi4CS.Core.SPI.Instance.ApplicationSPI> model, EventHandler <AssemblyLoadingArgs> loadingEvt)
        {
            var args = new AssemblyLoadingArgs(assembly.FullName, Qi4CSGeneratedAssemblyAttribute.GetGeneratedAssemblyName(assembly));

            loadingEvt.InvokeEventIfNotNull(evt => evt(model, args));

            var an = args.Qi4CSGeneratedAssemblyName;

            if (args.Version != null)
            {
                an += ", Version=" + args.Version;
            }

            if (!String.IsNullOrEmpty(args.Culture))
            {
                an += ", Culture=" + args.Culture;
            }

            if (!args.PublicKey.IsNullOrEmpty())
            {
                an += ", PublicKey=" + StringConversions.ByteArray2HexStr(args.PublicKey);
            }
            else if (!args.PublicKeyToken.IsNullOrEmpty())
            {
                an += ", PublicKeyToken=" + StringConversions.ByteArray2HexStr(args.PublicKeyToken);
            }

            return(Assembly.Load(
#if WINDOWS_PHONE_APP
                       new AssemblyName(
#endif
                       an
#if WINDOWS_PHONE_APP
                       )
#endif
                       ));
        }
示例#14
0
        private static string UnescapeNonAscii(string uri)
        {
            StringBuilder result = null;
            int           escapeSequenceStartIndex = 0;

            for (int i = 0; i != uri.Length; ++i)
            {
                bool endOfSequence;
                if (IsPotentiallyEscapedCharacterRepresentation1(uri, i,
                                                                 i -
                                                                 escapeSequenceStartIndex,
                                                                 out endOfSequence))
                {
                    // either new escape sequence starting with \ or continue of a sequence
                    if (endOfSequence)
                    {
                        // it's an escape char in form \uQRST
                        if (result == null)
                        {
                            result = new StringBuilder(uri, 0, escapeSequenceStartIndex,
                                                       uri.Length);
                        }
                        int charNr = StringConversions.Parse(uri,
                                                             escapeSequenceStartIndex + 2, 4);
                        result.Append(Convert.ToChar(charNr));
                        escapeSequenceStartIndex = i;
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (IsPotentiallyEscapedCharacterRepresentation2(uri, i,
                                                                      i -
                                                                      escapeSequenceStartIndex,
                                                                      out endOfSequence))
                {
                    if (endOfSequence)
                    {
                        // it's an escape char in form \\u
                        if (result == null)
                        {
                            result = new StringBuilder(uri, 0, escapeSequenceStartIndex,
                                                       uri.Length);
                        }
                        result.Append(@"\u");
                        escapeSequenceStartIndex = i;
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    // no escape sequence, add string directly to result
                    if (result != null)
                    {
                        result.Append(uri, escapeSequenceStartIndex,
                                      i - escapeSequenceStartIndex + 1);
                    }
                    escapeSequenceStartIndex = i;
                }
                ++escapeSequenceStartIndex;
            }
            return(result != null?result.ToString() : uri);
        }
        /// <summary>
        /// Converts a R_VAL to a CLR object of a specific type
        /// </summary>
        internal static object ValueToObjectOfType(RubyState state, R_VAL value, Type desiredType,
                                                   object defaultValue, bool isOptional)
        {
            if (desiredType.IsByRef)
            {
                desiredType = desiredType.GetElementType();
            }

            if (desiredType == typeof(R_VAL))
            {
                return(value);
            }

            if (desiredType == typeof(object))
            {
                return(ValueToObject(state, value));
            }

            StringConversions.StringSubtype stringSubType = StringConversions.GetStringSubtype(desiredType);
            string str = null;

            Type nt           = Nullable.GetUnderlyingType(desiredType);
            Type nullableType = null;

            if (nt != null)
            {
                nullableType = desiredType;
                desiredType  = nt;
            }

            switch (value.tt)
            {
            case DataType.Void:
                if (isOptional)
                {
                    return(defaultValue);
                }
                else if ((!desiredType.IsValueType) || (nullableType != null))
                {
                    return(null);
                }
                break;

            case DataType.Nil:
                if (Framework.Do.IsValueType(desiredType))
                {
                    if (nullableType != null)
                    {
                        return(null);
                    }

                    if (isOptional)
                    {
                        return(defaultValue);
                    }
                }
                else
                {
                    return(null);
                }

                break;

            case DataType.Boolean:
                if (desiredType == typeof(bool))
                {
                    return(value.Boolean);
                }
                if (stringSubType != StringConversions.StringSubtype.None)
                {
                    str = value.Boolean.ToString();
                }
                break;

            case DataType.Number:
                if (Framework.Do.IsEnum(desiredType))
                {
                    // number to enum conv
                    Type underType = Enum.GetUnderlyingType(desiredType);
                    return(NumericConversions.DoubleToType(underType, value.Number));
                }

                if (NumericConversions.NumericTypes.Contains(desiredType))
                {
                    return(NumericConversions.DoubleToType(desiredType, value.Number));
                }
                if (stringSubType != StringConversions.StringSubtype.None)
                {
                    str = value.Number.ToString();
                }
                break;

            case DataType.String:
                if (stringSubType != StringConversions.StringSubtype.None)
                {
                    str = value.String;
                }
                break;

            case DataType.Function:
                if (desiredType == typeof(Closure))
                {
                    return(value.Function);
                }
                else if (desiredType == typeof(ScriptFunctionDelegate))
                {
                    return(value.Function.GetDelegate());
                }
                break;

            case DataType.ClrFunction:
                if (desiredType == typeof(CallbackFunction))
                {
                    return(value.Callback);
                }
                else if (desiredType == typeof(Func <ScriptExecutionContext, CallbackArguments, R_VAL>))
                {
                    return(value.Callback.ClrCallback);
                }
                break;

            case DataType.UserData:
                if (value.UserData.Object != null)
                {
                    var udObj  = value.UserData.Object;
                    var udDesc = value.UserData.Descriptor;

                    if (udDesc.IsTypeCompatible(desiredType, udObj))
                    {
                        return(udObj);
                    }

                    if (stringSubType != StringConversions.StringSubtype.None)
                    {
                        str = udDesc.AsString(udObj);
                    }
                }

                break;

            case DataType.Table:
                if (desiredType == typeof(Table) ||
                    Framework.Do.IsAssignableFrom(desiredType, typeof(Table)))
                {
                    return(value.Table);
                }
                else
                {
                    object o = TableConversions.ConvertTableToType(value.Table, desiredType);
                    if (o != null)
                    {
                        return(o);
                    }
                }

                break;

            case DataType.Tuple:
                break;
            }

            if (stringSubType != StringConversions.StringSubtype.None && str != null)
            {
                return(StringConversions.ConvertString(stringSubType, str, desiredType, value.Type));
            }

            throw ScriptRuntimeException.ConvertObjectFailed(value.Type, desiredType);
        }
示例#16
0
 /// <inheritdoc />
 public override String ToString()
 {
     // mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
     return(Utils.EscapeSomeString(this._name) +
            ASSEMBLY_NAME_ELEMENTS_SEPARATOR + ' ' + VERSION + ASSEMBLY_NAME_ELEMENT_VALUE_SEPARATOR + this._majorVersion + VERSION_SEPARATOR + this._minorVersion + VERSION_SEPARATOR + this._buildNumber + VERSION_SEPARATOR + this._revision +
            ASSEMBLY_NAME_ELEMENTS_SEPARATOR + ' ' + CULTURE + ASSEMBLY_NAME_ELEMENT_VALUE_SEPARATOR + (this._culture == null || this._culture.Trim().Length == 0 ? NEUTRAL_CULTURE : this._culture) +
            (this._publicKey == null ? "" :
             ("" + ASSEMBLY_NAME_ELEMENTS_SEPARATOR + ' ' + (((AssemblyFlags)this._flags).IsFullPublicKey() ? PUBLIC_KEY : PUBLIC_KEY_TOKEN) + ASSEMBLY_NAME_ELEMENT_VALUE_SEPARATOR + StringConversions.ByteArray2HexStr(this._publicKey, 0, this._publicKey.Length, false))
            ));
 }
示例#17
0
            public static string ConvertElementTypeEnumerableToString(IEnumerable <StringConversions__ElementType> ee)
            {
                //0:10325ms WebServiceForJavaScript.WriteMethod { Name = foo }
                //0:10325ms enter ConvertElementTypeArrayToString ee:[object Object]

                //Console.WriteLine("enter ConvertElementTypeArrayToString " + new { ee });
                //Console.WriteLine("enter ConvertElementTypeArrayToString ee:" + ee);

                // X:\jsc.svn\examples\javascript\Test\TestIEnumerableForService\TestIEnumerableForService\ApplicationWebService.cs
                // X:\jsc.svn\examples\javascript\test\TestWebMethodTaskOfIEnumerable\TestWebMethodTaskOfIEnumerable\ApplicationWebService.cs
                //return ConvertElementTypeArrayToString(e.ToArray());


                //Unable to cast object of type 'System.Int32[]' to type 'System.Object[]'.


                #region return inline ConvertElementTypeArrayToString
                if (ee == null)
                {
                    //Console.WriteLine("enter ConvertElementTypeArrayToString ee is null");

                    //                 at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
                    //at mscorlib.< 02000005IEnumerable\.ConvertToString >.ConvertToString(IEnumerable`1)
                    //at TestIEnumerableForService.Global.Invoke(InternalWebMethodInfo)
                    //at ScriptCoreLib.Ultra.WebService.InternalGlobalExtensions.<> c__DisplayClass0.< InternalApplication_BeginRequest > b__12(WebServiceScriptApplication app)
                    //at ScriptCoreLib.Ultra.WebService.InternalGlobalExtensions.InternalApplication_BeginRequest(InternalGlobal g)
                    //at TestIEnumerableForService.Global.Application_BeginRequest(Object, EventArgs)
                    //at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
                    //at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean & completedSynchronously)

                    return(null);
                }

                //var o = (object[])e;

                var e = ee.ToArray();

                var xml = new XElement("enumerable");

                var Length = e.Length;

                //Console.WriteLine("ConvertElementTypeArrayToString " + new { Length });
                //Console.WriteLine("ConvertElementTypeArrayToString Length: " + Length);

                xml.Add(new XAttribute("c", "" + Length));

                for (int i = 0; i < Length; i++)
                {
                    // ldelem.ref ?
                    var item = e[i];

                    //                 [MethodAccessException: Attempt by method &#39;mscorlib.&lt;020000f3Array\+ConvertToString&gt;.ConvertToString(Int32[])&#39; to access method &#39;&lt;&gt;f__AnonymousType4d`2&lt;System.Int32,System.__Canon&gt;..ctor(Int32, System.__Canon)&#39; failed.]
                    //mscorlib.&lt;020000f3Array\+ConvertToString&gt;.ConvertToString(Int32[] ) +305


                    //Console.WriteLine("i: " + i + ", item: " + item);

                    xml.Add(new XElement("i" + i, ToString((StringConversions__ElementType)item)));
                }

                var value = StringConversions.ConvertXElementToString(xml);

                //Console.WriteLine("ConvertElementTypeArrayToString " + new { value });
                //Console.WriteLine("ConvertElementTypeArrayToString value: " + value);

                return(value);

                #endregion
            }
示例#18
0
        /// <summary>
        /// This method reads assembly information from the <c>FrameworkList.xml</c> located in reference assemblies sud-directory <c>RedistList</c>.
        /// </summary>
        /// <param name="defaultTargetFWDir">This will be the default target framework directory if XML file does not define <c>TargetFrameworkDirectory</c> attribute.</param>
        /// <param name="stream">The opened file to <c>FrameworkList.xml</c>.</param>
        /// <param name="assemblyFilenameEnumerator">The callback to enumerate all assembly files in the directory. Will be used only if assembly file list is not present in XML file.</param>
        /// <param name="ctxFactory">The callback to create a new <see cref="CILReflectionContext"/>. Will be used only if assembly file list is not present in XML file.</param>
        /// <param name="streamOpener">The callback to open assemblies in the target framework directory. Will be used only if assembly file list is not present in XML file.</param>
        /// <param name="fileExistsCheck">The callback to check for file existence. Will be used only if assembly file list is present in XML file. The first argument is target framework directory, and second argument is assembly name.</param>
        /// <param name="msCorLibName">The detected name of the assembly which acts as <c>mscorlib</c> assembly of this framework.</param>
        /// <param name="frameworkDisplayName">The detected display name of the framework.</param>
        /// <param name="targetFWDir">The detected value of target framework directory, potentially relative.</param>
        /// <returns>Assembly information persisted in the file.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="assemblyFilenameEnumerator"/> or <paramref name="ctxFactory"/> is <c>null</c>.</exception>
        /// <exception cref="InvalidDataException">If the <c>FrameworkList.xml</c> is in malformed format.</exception>
        /// <exception cref="InvalidOperationException">If the <c>FrameworkList.xml</c> does not define <c>TargetFrameworkDirectory</c> attribute and <paramref name="defaultTargetFWDir"/> is <c>null</c> or empty.</exception>
        public static IDictionary <String, Tuple <Version, Byte[]> > ReadAssemblyInformationFromRedistXMLFile(
            String defaultTargetFWDir,
            Stream stream,
            Func <String, IEnumerable <String> > assemblyFilenameEnumerator,
            Func <CILReflectionContext> ctxFactory,
            Func <String, Stream> streamOpener,
            Func <String, String, Boolean> fileExistsCheck,
            out String msCorLibName,
            out String frameworkDisplayName,
            out String targetFWDir
            )
        {
            var xmlSettings = new System.Xml.XmlReaderSettings();

            xmlSettings.CloseInput = false;

            using (var xml = System.Xml.XmlReader.Create(stream, xmlSettings))
            {
                xml.Read();
                // Move to Root and then to File-listing
                if (!xml.ReadToNextSibling("FileList"))
                {
                    throw new InvalidDataException("FrameworkList.xml seems to be in invalid format (FileList).");
                }

                frameworkDisplayName = xml.GetAttribute("Name");

                var asses = new List <Tuple <String, Version, Byte[]> >();


                targetFWDir = xml.GetAttribute("TargetFrameworkDirectory");
                if (String.IsNullOrEmpty(targetFWDir))
                {
                    // Can't trust <FileList> element children, since they contain facade assemblies as well.
                    targetFWDir = defaultTargetFWDir;
                    if (String.IsNullOrEmpty(targetFWDir))
                    {
                        throw new InvalidOperationException("Failed to resolve target framework moniker directory, as XML redistribution list file did not contain 'TargetFrameworkDirectory' attribute nor default target framework directory was specified.");
                    }
                }

                // If the <FileList> is present, we need to read the file information while checking that the file really exists
                if (xml.ReadToDescendant("File"))
                {
                    ArgumentValidator.ValidateNotNull("File existence checker", fileExistsCheck);

                    do
                    {
                        var simpleAssemblyName = xml.GetAttribute("AssemblyName");
                        if (fileExistsCheck(targetFWDir, simpleAssemblyName))
                        {
                            asses.Add(Tuple.Create(simpleAssemblyName, Version.Parse(xml.GetAttribute("Version")), StringConversions.HexStr2ByteArray(xml.GetAttribute("PublicKeyToken"))));
                        }
                    } while (xml.ReadToNextSibling("File"));
                }
                else
                {
                    // On Mono, .NETFramework assemblies are not enumerated in the FrameworkList.xml, making this process really slow
                    ArgumentValidator.ValidateNotNull("Assembly file name enumerator", assemblyFilenameEnumerator);
                    ArgumentValidator.ValidateNotNull("CIL Reflection Context factory", ctxFactory);
                    ArgumentValidator.ValidateNotNull("Stream opener", streamOpener);

                    using (var ctx = ctxFactory())
                    {
                        foreach (var fn in assemblyFilenameEnumerator(targetFWDir))
                        {
                            var eArgs = EmittingArguments.CreateForLoadingAssembly();
                            using (var curStream = streamOpener(fn))
                            {
                                try
                                {
                                    var ass = ctx.LoadAssembly(curStream, eArgs);
                                    var an  = ass.Name;
                                    asses.Add(Tuple.Create(an.Name, new Version(an.MajorVersion, an.MinorVersion, an.BuildNumber, an.Revision), ass.GetPublicKeyToken()));
                                }
                                catch
                                {
                                    // Ignore - some non-CLI files present sometimes as well here.
                                }
                            }
                        }
                    }
                }

                var result = asses.ToDictionary(t => t.Item1, t => Tuple.Create(t.Item2, t.Item3));
                msCorLibName = result.ContainsKey(Consts.NEW_MSCORLIB_NAME) ? Consts.NEW_MSCORLIB_NAME : Consts.MSCORLIB_NAME;
                return(result);
            }
        }
        /// <summary>
        /// This method will generate the Qi4CS assemblies.
        /// </summary>
        /// <param name="projectDir">The project directory.</param>
        /// <param name="targetFWID">The target framework identifier.</param>
        /// <param name="targetFWVersion">The target framework version.</param>
        /// <param name="targetFWProfile">The target framework profile.</param>
        /// <param name="referenceAssembliesDir">The base directory where target framework assemblies reside. Should be the directory where target framework assemblies are found under subdirectory <c>&lt;framework-id&gt;\&lt;framework-version&gt;</c>, e.g. <c>".NETFramework\v4.0"</c>.</param>
        /// <param name="targetPlatform">The textual name of target platform.</param>
        /// <param name="path">The path where to store assemblies.</param>
        /// <param name="assemblySNInfo">The file containing strongname information about the assemblies to be emitted.</param>
        /// <param name="qi4CSDir">The directory where Qi4CS assemblies actually used by the application reside.</param>
        /// <param name="verify">Whether to run PEVerify on generated Qi4CS assemblies.</param>
        /// <param name="winSDKDir">The directory where the Windows SDK resides, needed to detect PEVerify executable.</param>
        public IDictionary <String, String> GenerateAssemblies(String projectDir, String targetFWID, String targetFWVersion, String targetFWProfile, String referenceAssembliesDir, String targetPlatform, String path, String assemblySNInfo, String qi4CSDir, Boolean verify, String winSDKDir)
        {
            qi4CSDir = Path.GetFullPath(qi4CSDir);
            path     = Path.GetFullPath(path);

            XElement assemblyInfo = null;

            if (!String.IsNullOrEmpty(assemblySNInfo))
            {
                try
                {
                    assemblyInfo = XElement.Load(new StringReader(assemblySNInfo));
                }
                catch (Exception exc)
                {
                    throw new Qi4CSBuildException("Invalid assembly info element " + assemblySNInfo + ".\n" + exc);
                }
            }
            Func <String, Stream> streamOpener = str => File.Open(str, FileMode.Open, FileAccess.Read, FileShare.Read);

            referenceAssembliesDir = Path.Combine(referenceAssembliesDir, targetFWID, targetFWVersion);
            if (!String.IsNullOrEmpty(targetFWProfile))
            {
                referenceAssembliesDir = Path.Combine(referenceAssembliesDir, "Profile", targetFWProfile);
            }

            String msCorLibName; String fwDisplayName; String targetFWDir;
            var    thisFWMoniker = new FrameworkMonikerInfo(targetFWID, targetFWVersion, targetFWProfile, DotNETReflectionContext.ReadAssemblyInformationFromRedistXMLFile(Path.Combine(referenceAssembliesDir, "RedistList", "FrameworkList.xml"), out msCorLibName, out fwDisplayName, out targetFWDir), msCorLibName, fwDisplayName);

            if (!String.IsNullOrEmpty(targetFWDir))
            {
                referenceAssembliesDir = targetFWDir;
            }

            if (!Directory.Exists(referenceAssembliesDir))
            {
                throw new Qi4CSBuildException("The reference assemblies directory " + referenceAssembliesDir + " does not exist.");
            }

            referenceAssembliesDir += Path.DirectorySeparatorChar;

            var isX86         = X86.Equals(targetPlatform, StringComparison.InvariantCultureIgnoreCase);
            var targetMachine = String.IsNullOrEmpty(targetPlatform) || ANYCPU.Equals(targetPlatform, StringComparison.InvariantCultureIgnoreCase) || isX86 ?
                                ImageFileMachine.I386 :
                                ImageFileMachine.AMD64; // TODO more machines
            var mFlags = ModuleFlags.ILOnly;

            if (isX86)
            {
                mFlags |= ModuleFlags.Required32Bit;
            }

            var snDic = new ConcurrentDictionary <String, Tuple <StrongNameKeyPair, AssemblyHashAlgorithm> >();

            if (assemblyInfo != null)
            {
                foreach (var elem in assemblyInfo.XPathSelectElements("assembly"))
                {
                    snDic[elem.Attribute("name").Value] = Tuple.Create(
                        SubElementTextOrFallback(elem, "sn", (XElement snElem, out StrongNameKeyPair sn) =>
                    {
                        var type = snElem.Attribute("type");
                        sn       = "container".Equals(type.Value, StringComparison.InvariantCultureIgnoreCase) ?
                                   new StrongNameKeyPair(snElem.Value) :
                                   new StrongNameKeyPair("inline".Equals(type.Value, StringComparison.InvariantCultureIgnoreCase) ? StringConversions.HexStr2ByteArray(snElem.Value) : ReadAllBytes(projectDir, snElem.Value));
                        return(true);
                    }, null),
                        SubElementAttributeOrFallback(elem, "hashAlgorithm", (String algoStr, out AssemblyHashAlgorithm algo) =>
                    {
                        return(Enum.TryParse <AssemblyHashAlgorithm>(algoStr, out algo));
                    }, AssemblyHashAlgorithm.SHA1));
                }
            }

            var runtimeRootDir = Path.GetDirectoryName(new Uri(typeof(Object).Assembly.CodeBase).LocalPath);


            var actualPath = path;
            var needToMove = verify && !String.Equals(actualPath, qi4CSDir);

            if (needToMove)
            {
                // When verifying strong-named assemblies in different location than application's out dir, the .dll.config file
                // should hold recursively all non-.NET references, which is quite complicated and maybe not even enough.
                // Instead, emit Qi4CS assemblies into out dir and move them after verifying
                actualPath = qi4CSDir;
            }

            IDictionary <System.Reflection.Assembly, String> genAssFilenames;

            try
            {
                genAssFilenames = this._modelFactory.Model.GenerateAndSaveAssemblies(
                    actualPath,
                    this.IsSilverlight,
                    (nAss, gAss) =>
                {
                    Tuple <StrongNameKeyPair, AssemblyHashAlgorithm> snTuple;
                    snDic.TryGetValue(nAss.GetName().Name, out snTuple);
                    var sn    = snTuple == null ? null : snTuple.Item1;
                    var eArgs = EmittingArguments.CreateForEmittingWithMoniker(gAss.ReflectionContext, targetMachine, TargetRuntime.Net_4_0, ModuleKind.Dll, null, runtimeRootDir, referenceAssembliesDir, streamOpener, sn, thisFWMoniker, String.Equals(thisFWMoniker.FrameworkName, PCL_FW_NAME), mFlags);

                    gAss.AddTargetFrameworkAttributeWithMonikerInfo(thisFWMoniker, eArgs.AssemblyMapper);
                    if (snTuple != null)
                    {
                        eArgs.SigningAlgorithm = snTuple.Item2;
                    }
                    return(eArgs);
                });
            }
            catch (InvalidApplicationModelException apme)
            {
                throw new Qi4CSBuildException("The Qi4CS model was not valid:\n" + apme.ValidationResult, apme);
            }

            if (verify)
            {
                try
                {
                    winSDKDir = FindWinSDKBinPath(winSDKDir);
                    foreach (var fn in genAssFilenames)
                    {
                        Verify(winSDKDir, fn.Value, snDic != null && snDic.ContainsKey(fn.Key.GetName().Name));
                    }
                }
                finally
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    foreach (var kvp in genAssFilenames.ToArray())
                    {
                        var fn = kvp.Value;
                        try
                        {
                            var targetFn = Path.Combine(path, Path.GetFileName(fn));
                            if (!String.Equals(fn, targetFn))
                            {
                                if (File.Exists(targetFn))
                                {
                                    try
                                    {
                                        File.Delete(targetFn);
                                    }
                                    catch
                                    {
                                        // Ignore
                                    }
                                }
                                File.Move(fn, targetFn);
                                genAssFilenames.Remove(kvp.Key);
                                genAssFilenames.Add(kvp.Key, targetFn);
                            }
                        }
                        catch
                        {
                            // Ignore
                        }
                    }
                }
            }

            return(genAssFilenames.ToDictionary(
                       kvp => kvp.Key.CodeBase,
                       kvp => kvp.Value
                       ));
        }