Exemplo n.º 1
0
        /// <summary>
        /// Upload file to server (file system or blob if azure)
        /// and return the name of the file created
        /// </summary>
        /// <param name="stream">stream to upload</param>
        /// <returns>the file name</returns>
        public static string UploadFile(this Controller controller, string url, MiscHelpers.ImageSize imageSize, string folder = null)
        {
            if (string.IsNullOrEmpty(url))
                return string.Empty;

            var ext = ".jpg";
            var contentType = "image/jpeg";
            var fileName = String.Format("{0:yyyy-MM-dd_hh-mm-ss-ffff}", DateTime.UtcNow) + ext;

            //Create a WebRequest to get the file
            HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);

            //Create a response for this request
            HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

            if (fileReq.ContentLength > 0)
                fileResp.ContentLength = fileReq.ContentLength;

            using (var fs = CopyAndClose(fileResp.GetResponseStream()))
            {
                SaveFile(controller, fs, fileName, ext, contentType, folder, imageSize.Width, imageSize.Height);
                fs.Position = 0;
                SaveFile(controller, fs, fileName, ext, contentType, folder, imageSize.TWidth, imageSize.THeight, true);
            }
            return fileName;
        }
Exemplo n.º 2
0
 public override string ToString()
 {
     return(MiscHelpers.FormatInvariant("ref {0}", Type.GetFriendlyName()));
 }
Exemplo n.º 3
0
 /// <summary>
 /// Initializes a new VBScript engine instance with the specified programmatic
 /// identifier, name, and options.
 /// </summary>
 /// <param name="progID">The programmatic identifier (ProgID) of the VBScript engine class.</param>
 /// <param name="name">A name to associate with the instance. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
 /// <param name="flags">A value that selects options for the operation.</param>
 /// <remarks>
 /// The <paramref name="progID"/> argument can be a class identifier (CLSID) in standard
 /// GUID format with braces (e.g., "{F414C260-6AC0-11CF-B6D1-00AA00BBBB58}").
 /// </remarks>
 protected VBScriptEngine(string progID, string name, WindowsScriptEngineFlags flags)
     : base(progID, name, flags)
 {
     Execute(
         MiscHelpers.FormatInvariant("{0} [internal]", GetType().Name),
         @"
             class EngineInternalImpl
                 public function getCommandResult(value)
                     if IsObject(value) then
                         if value is nothing then
                             getCommandResult = ""[nothing]""
                         else
                             dim valueTypeName
                             valueTypeName = TypeName(value)
                             if (valueTypeName = ""Object"" or valueTypeName = ""Unknown"") then
                                 set getCommandResult = value
                             else
                                 getCommandResult = ""[ScriptObject:"" & valueTypeName & ""]""
                             end if
                         end if
                     elseif IsArray(value) then
                         getCommandResult = ""[array]""
                     elseif IsNull(value) then
                         getCommandResult = ""[null]""
                     elseif IsEmpty(value) then
                         getCommandResult = ""[empty]""
                     else
                         getCommandResult = CStr(value)
                     end if
                 end function
                 public function invokeConstructor(constructor, args)
                     Err.Raise 445
                 end function
                 public function invokeMethod(target, method, args)
                     if IsObject(target) then
                         if target is nothing then
                         else
                             Err.Raise 445
                         end if
                     elseif IsNull(target) then
                     elseif IsEmpty(target) then
                     else
                         Err.Raise 445
                     end if
                     dim count
                     if IsArray(args) then
                         count = UBound(args) + 1
                         if count < 1 then
                             invokeMethod = method()
                         elseif count = 1 then
                             invokeMethod = method(args(0))
                         elseif count = 2 then
                             invokeMethod = method(args(0), args(1))
                         elseif count = 3 then
                             invokeMethod = method(args(0), args(1), args(2))
                         elseif count = 4 then
                             invokeMethod = method(args(0), args(1), args(2), args(3))
                         elseif count = 5 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4))
                         elseif count = 6 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5))
                         elseif count = 7 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6))
                         elseif count = 8 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7))
                         elseif count = 9 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8))
                         elseif count = 10 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9))
                         elseif count = 11 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10))
                         elseif count = 12 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10), args(11))
                         elseif count = 13 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10), args(11), args(12))
                         elseif count = 14 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10), args(11), args(12), args(13))
                         elseif count = 15 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10), args(11), args(12), args(13), args(14))
                         elseif count = 16 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10), args(11), args(12), args(13), args(14), args(15))
                         else
                             Err.Raise 450
                         end if
                     else
                         count = args.Length
                         if count < 1 then
                             invokeMethod = method()
                         elseif count = 1 then
                             invokeMethod = method(args.GetValue(0))
                         elseif count = 2 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1))
                         elseif count = 3 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2))
                         elseif count = 4 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3))
                         elseif count = 5 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4))
                         elseif count = 6 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5))
                         elseif count = 7 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6))
                         elseif count = 8 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7))
                         elseif count = 9 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8))
                         elseif count = 10 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9))
                         elseif count = 11 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9), args.GetValue(10))
                         elseif count = 12 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9), args.GetValue(10), args.GetValue(11))
                         elseif count = 13 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9), args.GetValue(10), args.GetValue(11), args.GetValue(12))
                         elseif count = 14 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9), args.GetValue(10), args.GetValue(11), args.GetValue(12), args.GetValue(13))
                         elseif count = 15 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9), args.GetValue(10), args.GetValue(11), args.GetValue(12), args.GetValue(13), args.GetValue(14))
                         elseif count = 16 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9), args.GetValue(10), args.GetValue(11), args.GetValue(12), args.GetValue(13), args.GetValue(14), args.GetValue(15))
                         else
                             Err.Raise 450
                         end if
                     end if
                 end function
             end class
             set EngineInternal = new EngineInternalImpl
         "
         );
 }
Exemplo n.º 4
0
 public ProcessDebugManagerWrapper64()
 {
     processDebugManager = (IProcessDebugManager64)MiscHelpers.CreateCOMObject("ProcessDebugManager");
 }
Exemplo n.º 5
0
        public void DrawBorders(SKCanvas dc, SKRect rect_Card)
        {
            SKPaint thisPaint = MiscHelpers.GetStrokePaint(SKColors.Black, 3); //i think 3 is enough.

            MainGraphics !.DrawDefaultRectangles(dc, rect_Card, thisPaint);
        }
Exemplo n.º 6
0
 public ExtensionMethodSummary()
 {
     Types       = MiscHelpers.GetEmptyArray <Type>();
     Methods     = MiscHelpers.GetEmptyArray <MethodInfo>();
     MethodNames = MiscHelpers.GetEmptyArray <string>();
 }
Exemplo n.º 7
0
 public override void MenuCallback(object sender, EventArgs e)
 {
     MiscHelpers.LaunchLink(@"http://" + Resources.HelpWebsite);
 }
Exemplo n.º 8
0
 /// <summary>
 /// Initializes a new host type collection with selected types from one or more assemblies.
 /// The assemblies are specified by name.
 /// </summary>
 /// <param name="filter">A filter for selecting the types to add.</param>
 /// <param name="assemblyNames">The names of the assemblies that contain the types with which to initialize the collection.</param>
 public HostTypeCollection(Predicate <Type> filter, params string[] assemblyNames)
 {
     MiscHelpers.VerifyNonNullArgument(assemblyNames, "assemblyNames");
     Array.ForEach(assemblyNames, assemblyName => AddAssembly(assemblyName, filter));
 }
Exemplo n.º 9
0
 /// <summary>
 /// Adds types from an assembly to a host type collection. The assembly is specified by name.
 /// </summary>
 /// <param name="assemblyName">The name of the assembly that contains the types to add.</param>
 public void AddAssembly(string assemblyName)
 {
     MiscHelpers.VerifyNonBlankArgument(assemblyName, "assemblyName", "Invalid assembly name");
     AddAssembly(Assembly.Load(AssemblyTable.GetFullAssemblyName(assemblyName)));
 }
Exemplo n.º 10
0
 /// <summary>
 /// Adds a type to a host type collection.
 /// </summary>
 /// <param name="type">The type to add.</param>
 public void AddType(Type type)
 {
     MiscHelpers.VerifyNonNullArgument(type, "type");
     AddType(HostType.Wrap(type));
 }
Exemplo n.º 11
0
 /// <summary>
 /// Initializes a new host type collection with types from one or more assemblies. The
 /// assemblies are specified by name.
 /// </summary>
 /// <param name="assemblyNames">The names of the assemblies that contain the types with which to initialize the collection.</param>
 public HostTypeCollection(params string[] assemblyNames)
     : base(true)
 {
     MiscHelpers.VerifyNonNullArgument(assemblyNames, "assemblyNames");
     Array.ForEach(assemblyNames, AddAssembly);
 }
Exemplo n.º 12
0
        private static object BindMethodRaw(BindingFlags bindFlags, InvokeMemberBinder binder, HostTarget target, object[] bindArgs)
        {
            var expr = DynamicHelpers.Bind(binder, target, bindArgs).Expression;

            if (expr == null)
            {
                return(new Func <Exception>(() => new MissingMemberException(MiscHelpers.FormatInvariant("Object has no method named '{0}'", binder.Name))));
            }

            if (expr.NodeType == ExpressionType.Dynamic)
            {
                // The binding result is a dynamic call, which is indicative of COM interop. This
                // sort of binding is not very useful here; it can't be resolved to a MethodInfo
                // instance, and caching it is problematic because it includes argument bindings.
                // Falling back to reflection should work in most cases because COM interfaces
                // support neither generic nor overloaded methods.

                try
                {
                    var method = target.Type.GetMethod(binder.Name, bindFlags);
                    return((object)method ?? new Func <Exception>(() => new MissingMemberException(MiscHelpers.FormatInvariant("Object has no method named '{0}'", binder.Name))));
                }
                catch (AmbiguousMatchException exception)
                {
                    return(new Func <Exception>(() => new AmbiguousMatchException(exception.Message)));
                }
            }

            return((new MethodBindingVisitor(target.InvokeTarget, binder.Name, expr)).Result);
        }
Exemplo n.º 13
0
            public override async Task <Document> LoadDocumentAsync(DocumentSettings settings, DocumentInfo?sourceInfo, string specifier, DocumentCategory category, DocumentContextCallback contextCallback)
            {
                MiscHelpers.VerifyNonNullArgument(settings, "settings");
                MiscHelpers.VerifyNonBlankArgument(specifier, "specifier", "Invalid document specifier");

                if ((settings.AccessFlags & DocumentAccessFlags.EnableAllLoading) == DocumentAccessFlags.None)
                {
                    throw new UnauthorizedAccessException("The script engine is not configured for loading documents");
                }

                if (category == null)
                {
                    category = sourceInfo.HasValue ? sourceInfo.Value.Category : DocumentCategory.Script;
                }

                List <Uri> candidateUris;

                Uri uri;

                if (Uri.TryCreate(specifier, UriKind.RelativeOrAbsolute, out uri) && uri.IsAbsoluteUri)
                {
                    candidateUris = await GetCandidateUrisAsync(settings, sourceInfo, uri).ConfigureAwait(false);
                }
                else
                {
                    candidateUris = await GetCandidateUrisAsync(settings, sourceInfo, specifier).ConfigureAwait(false);
                }

                if (candidateUris.Count < 1)
                {
                    throw new FileNotFoundException(null, specifier);
                }

                if (candidateUris.Count == 1)
                {
                    return(await LoadDocumentAsync(settings, candidateUris[0], category, contextCallback).ConfigureAwait(false));
                }

                var exceptions = new List <Exception>(candidateUris.Count);

                foreach (var candidateUri in candidateUris)
                {
                    var task = LoadDocumentAsync(settings, candidateUri, category, contextCallback);
                    try
                    {
                        return(await task.ConfigureAwait(false));
                    }
                    catch (Exception exception)
                    {
                        if ((task.Exception != null) && task.Exception.InnerExceptions.Count == 1)
                        {
                            Debug.Assert(ReferenceEquals(task.Exception.InnerExceptions[0], exception));
                            exceptions.Add(exception);
                        }
                        else
                        {
                            exceptions.Add(task.Exception);
                        }
                    }
                }

                if (exceptions.Count < 1)
                {
                    MiscHelpers.AssertUnreachable();
                    throw new FileNotFoundException(null, specifier);
                }

                if (exceptions.Count == 1)
                {
                    MiscHelpers.AssertUnreachable();
                    throw new FileLoadException(exceptions[0].Message, specifier, exceptions[0]);
                }

                throw new AggregateException(exceptions).Flatten();
            }
Exemplo n.º 14
0
        public async Task SayHello()
        {
            var embed = MiscHelpers.CreateEmbed(Context, "Hello!", "My name is Wsashi, a bot created by Phytal! (And possibly your Waifu..)").WithImageUrl(Global.Client.CurrentUser.GetAvatarUrl());

            await MiscHelpers.SendMessage(Context, embed);
        }
Exemplo n.º 15
0
        private string GetStackTraceInternal()
        {
            Debug.Assert(engineFlags.HasFlag(WindowsScriptEngineFlags.EnableDebugging));
            var stackTrace = string.Empty;

            IEnumDebugStackFrames enumFrames;

            activeScript.EnumStackFrames(out enumFrames);

            while (true)
            {
                DebugStackFrameDescriptor descriptor;
                uint countFetched;
                enumFrames.Next(1, out descriptor, out countFetched);
                if (countFetched < 1)
                {
                    break;
                }

                try
                {
                    string description;
                    descriptor.Frame.GetDescriptionString(true, out description);

                    IDebugCodeContext codeContext;
                    descriptor.Frame.GetCodeContext(out codeContext);

                    IDebugDocumentContext documentContext;
                    codeContext.GetDocumentContext(out documentContext);
                    if (documentContext == null)
                    {
                        stackTrace += MiscHelpers.FormatInvariant("    at {0}\n", description);
                    }
                    else
                    {
                        IDebugDocument document;
                        documentContext.GetDocument(out document);
                        var documentText = (IDebugDocumentText)document;

                        string documentName;
                        document.GetName(DocumentNameType.Title, out documentName);

                        uint position;
                        uint length;
                        documentText.GetPositionOfContext(documentContext, out position, out length);

                        var pBuffer = Marshal.AllocCoTaskMem((int)(sizeof(char) * length));
                        try
                        {
                            uint lengthReturned = 0;
                            documentText.GetText(position, pBuffer, IntPtr.Zero, ref lengthReturned, length);
                            var codeLine = Marshal.PtrToStringUni(pBuffer, (int)lengthReturned);

                            uint lineNumber;
                            uint offsetInLine;
                            documentText.GetLineOfPosition(position, out lineNumber, out offsetInLine);

                            stackTrace += MiscHelpers.FormatInvariant("    at {0} ({1}:{2}:{3}) -> {4}\n", description, documentName, lineNumber, offsetInLine, codeLine);
                        }
                        finally
                        {
                            Marshal.FreeCoTaskMem(pBuffer);
                        }
                    }
                }
                finally
                {
                    if (descriptor.FinalObject != null)
                    {
                        Marshal.ReleaseComObject(descriptor.FinalObject);
                    }
                }
            }

            return(stackTrace.TrimEnd('\n'));
        }
Exemplo n.º 16
0
 /// <summary>
 /// Initializes a new <see cref="ScriptInterruptedException"/> with the specified error message and nested exception.
 /// </summary>
 /// <param name="message">The error message.</param>
 /// <param name="innerException">The exception that caused the current exception to be thrown.</param>
 public ScriptInterruptedException(string message, Exception innerException)
     : base(MiscHelpers.EnsureNonBlank(message, defaultMessage), innerException)
 {
     // ReSharper disable once RedundantBaseQualifier
     errorDetails = base.Message;
 }
Exemplo n.º 17
0
 public override string ToString()
 {
     return(MiscHelpers.FormatInvariant("HostIndexedProperty:{0}", name));
 }
Exemplo n.º 18
0
        protected void VerifyParameterMapping(MethodBase methodBase)
        {
            var parameters = methodBase.GetParameters();

            if (parameters.Length == 0)
            {
                return;
            }

            var map = TypeConfig.ParameterMap ?? (TypeConfig.ParameterMap = new Dictionary <ParameterInfo, MemberInfo>());

            var memberConfigs = TypeConfig.Members.Where(mc => mc.ComputeFinalInclusionFast()).ToArray();

            foreach (var parameterInfo in parameters)
            {
                // Originally here was a lot of clever code here that tried to match by type, eliminate results, ...
                // but it turns out it's much better to simply let the user do stuff and throw errors as soon as there's just a hint of ambiguity!

                // Are we still missing a mapping for this member?
                if (!map.TryGetValue(parameterInfo, out MemberInfo sourceMember))
                {
                    var caseInsensitiveMatches = memberConfigs.Where(mc => parameterInfo.Name.Equals(mc.Member.Name, StringComparison.OrdinalIgnoreCase)).ToArray();
                    if (SetMatchOrThrow(parameterInfo, caseInsensitiveMatches))
                    {
                        continue;
                    }

                    var tolerantMatches = memberConfigs.Where(mc => parameterInfo.Name.Equals(MiscHelpers.CleanMemberName(mc.Member.Name), StringComparison.OrdinalIgnoreCase)).ToArray();
                    if (SetMatchOrThrow(parameterInfo, tolerantMatches))
                    {
                        continue;
                    }

                    throw new CerasException($"Cannot find any automatic mapping from any member to the parameter '{parameterInfo.ParameterType.Name} {parameterInfo.Name}'");
                }
                else
                {
                    // We already have a user-provided match, but is it part of the serialization?
                    var sourceMemberConfig = TypeConfig.Members.First(mc => mc.Member == sourceMember);
                    if (!sourceMemberConfig.ComputeFinalInclusionFast())
                    {
                        throw new CerasException($"The type construction mode for the type '{TypeConfig.Type.FullName}' is invalid because the parameter '{parameterInfo.ParameterType.Name} {parameterInfo.Name}' is supposed to be initialized from the member '{sourceMember.FieldOrPropType().Name} {sourceMember.Name}', but that member is not part of the serialization, so it will not be available at deserialization-time.");
                    }
                }
            }

            bool SetMatchOrThrow(ParameterInfo p, MemberConfig[] configs)
            {
                if (configs.Length > 1)
                {
                    throw new AmbiguousMatchException($"There are multiple members that match the parameter '{p.ParameterType.Name} {p.Name}': {string.Join(", ", configs.Select(c => c.Member.Name))}");
                }

                if (configs.Length == 0)
                {
                    return(false);
                }

                map.Add(p, configs[0].Member);
                return(true);
            }
        }
Exemplo n.º 19
0
        public ActiveScriptWrapper64(string progID, WindowsScriptEngineFlags flags)
        {
            // ReSharper disable SuspiciousTypeConversion.Global

            pActiveScript                 = ActivationHelpers.CreateInstance <IActiveScript>(progID);
            pActiveScriptParse            = UnknownHelpers.QueryInterface <IActiveScriptParse64>(pActiveScript);
            pActiveScriptDebug            = UnknownHelpers.QueryInterface <IActiveScriptDebug64>(pActiveScript);
            pActiveScriptGarbageCollector = UnknownHelpers.QueryInterfaceNoThrow <IActiveScriptGarbageCollector>(pActiveScript);
            pDebugStackFrameSniffer       = UnknownHelpers.QueryInterfaceNoThrow <IDebugStackFrameSnifferEx64>(pActiveScript);

            activeScript                 = (IActiveScript)Marshal.GetObjectForIUnknown(pActiveScript);
            activeScriptParse            = (IActiveScriptParse64)activeScript;
            activeScriptDebug            = (IActiveScriptDebug64)activeScript;
            activeScriptGarbageCollector = activeScript as IActiveScriptGarbageCollector;
            debugStackFrameSniffer       = activeScript as IDebugStackFrameSnifferEx64;

            if (flags.HasFlag(WindowsScriptEngineFlags.EnableStandardsMode))
            {
                var activeScriptProperty = activeScript as IActiveScriptProperty;
                if (activeScriptProperty != null)
                {
                    object name;
                    activeScriptProperty.GetProperty(ScriptProp.Name, IntPtr.Zero, out name);
                    if (Equals(name, "JScript"))
                    {
                        object value = ScriptLanguageVersion.Standards;
                        activeScriptProperty.SetProperty(ScriptProp.InvokeVersioning, IntPtr.Zero, ref value);
                    }
                }

                if (!flags.HasFlag(WindowsScriptEngineFlags.DoNotEnableVTablePatching) && MiscHelpers.IsX86InstructionSet())
                {
                    HostItem.EnableVTablePatching = true;
                }
            }

            // ReSharper restore SuspiciousTypeConversion.Global
        }
        private MethodBindResult BindMethod(string name, Type[] typeArgs, object[] args, object[] bindArgs)
        {
            // WARNING: BindSignature holds on to the specified typeArgs; subsequent modification
            // will result in bugs that are difficult to diagnose. Create a copy if necessary.

            var signature = new BindSignature(target, name, typeArgs, bindArgs);
            MethodBindResult result;

            object rawResult;

            if (engine.TryGetCachedBindResult(signature, out rawResult))
            {
                result = MethodBindResult.Create(name, rawResult, target, args);
            }
            else
            {
                result = BindMethodInternal(name, typeArgs, args, bindArgs);
                if (!result.IsPreferredMethod(name))
                {
                    if (result is MethodBindSuccess)
                    {
                        result = new MethodBindFailure(() => new MissingMemberException(MiscHelpers.FormatInvariant("Object has no method named '{0}' that matches the specified arguments", name)));
                    }

                    foreach (var altName in GetAltMethodNames(name))
                    {
                        var altResult = BindMethodInternal(altName, typeArgs, args, bindArgs);
                        if (altResult.IsUnblockedMethod())
                        {
                            result = altResult;
                            break;
                        }
                    }
                }

                engine.CacheBindResult(signature, result.RawResult);
            }

            return(result);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Initializes a new JScript engine instance with the specified programmatic
        /// identifier, name, list of supported file name extensions, and options.
        /// </summary>
        /// <param name="progID">The programmatic identifier (ProgID) of the JScript engine class.</param>
        /// <param name="name">A name to associate with the instance. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
        /// <param name="fileNameExtensions">A semicolon-delimited list of supported file name extensions.</param>
        /// <param name="flags">A value that selects options for the operation.</param>
        /// <remarks>
        /// The <paramref name="progID"/> argument can be a class identifier (CLSID) in standard
        /// GUID format with braces (e.g., "{F414C260-6AC0-11CF-B6D1-00AA00BBBB58}").
        /// </remarks>
        protected JScriptEngine(string progID, string name, string fileNameExtensions, WindowsScriptEngineFlags flags)
            : base(progID, name, fileNameExtensions, flags)
        {
            Execute(
                MiscHelpers.FormatInvariant("{0} [internal]", GetType().Name),
                @"
                    EngineInternal = (function () {

                        function convertArgs(args) {
                            var result = [];
                            if (args.GetValue) {
                                var count = args.Length;
                                for (var i = 0; i < count; i++) {
                                    result.push(args[i]);
                                }
                            }
                            else {
                                args = new VBArray(args);
                                var count = args.ubound(1) + 1;
                                for (var i = 0; i < count; i++) {
                                    result.push(args.getItem(i));
                                }
                            }
                            return result;
                        }

                        function construct(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15) {
                            return new this(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15);
                        }

                        return {

                            getCommandResult: function (value) {
                                if (value != null) {
                                    if ((typeof(value) == 'object') || (typeof(value) == 'function')) {
                                        if (typeof(value.toString) == 'function') {
                                            return value.toString();
                                        }
                                    }
                                }
                                return value;
                            },

                            invokeConstructor: function (constructor, args) {
                                if (typeof(constructor) != 'function') {
                                    throw new Error('Function expected');
                                }
                                return construct.apply(constructor, convertArgs(args));
                            },

                            invokeMethod: function (target, method, args) {
                                if (typeof(method) != 'function') {
                                    throw new Error('Function expected');
                                }
                                return method.apply(target, convertArgs(args));
                            }
                        };
                    })();
                "
                );
        }
            public static MethodBindResult Create(string name, object rawResult, HostTarget hostTarget, object[] args)
            {
                var method = rawResult as MethodInfo;

                if (method != null)
                {
                    if ((method.IsStatic) && !hostTarget.Flags.HasFlag(HostTargetFlags.AllowStaticMembers))
                    {
                        return(new MethodBindFailure(() => new InvalidOperationException(MiscHelpers.FormatInvariant("Cannot access static method '{0}' in non-static context", method.Name))));
                    }

                    return(new MethodBindSuccess(hostTarget, method, args));
                }

                return(new MethodBindFailure((rawResult as Func <Exception>) ?? (() => new NotSupportedException(MiscHelpers.FormatInvariant("Invocation of method '{0}' failed (unrecognized binding)", name)))));
            }
Exemplo n.º 23
0
 private static void RejectClient(TcpClient tcpClient)
 {
     SendStringAsync(tcpClient, "Remote debugging session already active\r\n", succeeded => MiscHelpers.Try(tcpClient.Close));
 }
Exemplo n.º 24
0
        public override object GetProperty(string name)
        {
            VerifyNotDisposed();

            var result = engine.MarshalToHost(engine.ScriptInvoke(() =>
            {
                try
                {
                    return(target.InvokeMember(name, BindingFlags.GetProperty, null, target, MiscHelpers.GetEmptyArray <object>(), null, CultureInfo.InvariantCulture, null));
                }
                catch (Exception)
                {
                    if (target.GetMethod(name, BindingFlags.GetProperty) != null)
                    {
                        // Property retrieval failed, but a method with the given name exists;
                        // create a tear-off method. This currently applies only to VBScript.

                        return(new ScriptMethod(this, name));
                    }

                    return(Nonexistent.Value);
                }
            }), false);

            var resultScriptItem = result as WindowsScriptItem;

            if ((resultScriptItem != null) && (resultScriptItem.engine == engine))
            {
                resultScriptItem.holder = this;
            }

            return(result);
        }
Exemplo n.º 25
0
        public void DrawImage(SKCanvas canvas, SKRect rect_Card)
        {
            var tempRect = MainGraphics !.GetActualRectangle(3, 3, 224, 124);

            canvas.DrawRect(tempRect, _redPaint);
            var firstRect = MainGraphics.GetActualRectangle(4, 4, 50, 50);

            canvas.DrawRect(firstRect, _whitePaint);
            var fontSize  = MainGraphics.GetFontSize(14); // can adjust as needed
            var textPaint = MiscHelpers.GetTextPaint(SKColors.Black, fontSize);

            canvas.DrawCustomText(ThisCombo !.Points.ToString() + " PTS.", TextExtensions.EnumLayoutOptions.Center, TextExtensions.EnumLayoutOptions.Center, textPaint, firstRect, out _);
            var SecondRect = MainGraphics.GetActualRectangle(56, 4, 170, 50);
            var temps      = MainGraphics.GetFontSize(3);

            canvas.DrawRoundRect(SecondRect, temps, temps, _yellowPaint);
            canvas.DrawRoundRect(SecondRect, temps, temps, _thickBorder);
            firstRect = MainGraphics.GetActualRectangle(56, 4, 170, 16);
            fontSize  = MainGraphics.GetFontSize(16);
            textPaint = MiscHelpers.GetTextPaint(SKColors.Black, fontSize);
            textPaint.FakeBoldText = true;
            canvas.DrawCustomText(ThisCombo.FirstDescription, TextExtensions.EnumLayoutOptions.Center, TextExtensions.EnumLayoutOptions.Center, textPaint, firstRect, out _);
            string firstText;
            string secondText;
            var    tempList = ThisCombo.SecondDescription.Split("|").ToCustomBasicList();

            if (tempList.Count != 2)
            {
                throw new Exception("Needs 2 lines of text");
            }
            firstText  = tempList.First();
            secondText = tempList.Last();
            firstRect  = MainGraphics.GetActualRectangle(56, 20, 170, 16);
            textPaint  = MiscHelpers.GetTextPaint(SKColors.Black, fontSize);
            SecondRect = MainGraphics.GetActualRectangle(56, 36, 170, 16);
            canvas.DrawCustomText(firstText, TextExtensions.EnumLayoutOptions.Center, TextExtensions.EnumLayoutOptions.Center, textPaint, firstRect, out _);
            canvas.DrawCustomText(secondText, TextExtensions.EnumLayoutOptions.Center, TextExtensions.EnumLayoutOptions.Center, textPaint, SecondRect, out _);
            float diffs;

            diffs = 44; // i think
            var   finalSize = MainGraphics.GetFontSize(68);
            float lefts;

            lefts = 5;
            var tops      = 58;
            var otherSize = MainGraphics.GetFontSize(42);

            foreach (var thisItem in ThisCombo.SampleList)
            {
                YahtzeeHandsDownGraphicsCP thisCard = new YahtzeeHandsDownGraphicsCP();
                thisCard.MainGraphics = new BaseDeckGraphicsCP(); //think.
                thisCard.MainGraphics.ThisGraphics = thisCard;
                thisCard.MainGraphics.NeedsToClear = false;
                thisCard.Init();//hopefully this too.
                thisCard.MainGraphics.ActualWidth  = otherSize;
                thisCard.MainGraphics.ActualHeight = finalSize;
                thisCard.MainGraphics.Location     = MainGraphics.GetActualPoint(new SKPoint(lefts, tops));
                thisCard.Color       = thisItem.Color;
                thisCard.IsWild      = thisItem.IsWild;
                thisCard.FirstValue  = thisItem.FirstValue;
                thisCard.SecondValue = thisItem.SecondValue;
                thisCard.MainGraphics.DrawImage(canvas);
                lefts += diffs;
            }
        }
        public void VBScriptEngine_Evaluate_Array()
        {
            // ReSharper disable ImplicitlyCapturedClosure

            var lengths      = new[] { 3, 5, 7 };
            var formatParams = string.Join(", ", Enumerable.Range(0, lengths.Length).Select(position => "{" + position + "}"));

            var hosts = Array.CreateInstance(typeof(object), lengths);

            hosts.Iterate(indices => hosts.SetValue(new HostFunctions(), indices));
            engine.AddHostObject("hostArray", hosts);

            engine.Execute(MiscHelpers.FormatInvariant("dim hosts(" + formatParams + ")", lengths.Select(length => (object)(length - 1)).ToArray()));
            hosts.Iterate(indices => engine.Execute(MiscHelpers.FormatInvariant("set hosts(" + formatParams + ") = hostArray.GetValue(" + formatParams + ")", indices.Select(index => (object)index).ToArray())));
            hosts.Iterate(indices => Assert.AreSame(hosts.GetValue(indices), engine.Evaluate(MiscHelpers.FormatInvariant("hosts(" + formatParams + ")", indices.Select(index => (object)index).ToArray()))));

            var result = engine.Evaluate("hosts");

            Assert.IsInstanceOfType(result, typeof(object[, , ]));
            var hostArray = (object[, , ])result;

            hosts.Iterate(indices => Assert.AreSame(hosts.GetValue(indices), hostArray.GetValue(indices)));

            // ReSharper restore ImplicitlyCapturedClosure
        }
Exemplo n.º 27
0
 public override string ToString()
 {
     return(MiscHelpers.FormatInvariant("HostMethod:{0}", name));
 }
Exemplo n.º 28
0
        private string GetStackTraceInternal()
        {
            Debug.Assert(processDebugManager != null);
            var stackTrace = string.Empty;

            IEnumDebugStackFrames enumFrames;

            activeScript.EnumStackFrames(out enumFrames);

            while (true)
            {
                DebugStackFrameDescriptor descriptor;
                uint countFetched;
                enumFrames.Next(1, out descriptor, out countFetched);
                if (countFetched < 1)
                {
                    break;
                }

                try
                {
                    string description;
                    descriptor.Frame.GetDescriptionString(true, out description);

                    IDebugCodeContext codeContext;
                    descriptor.Frame.GetCodeContext(out codeContext);

                    IDebugDocumentContext documentContext;
                    codeContext.GetDocumentContext(out documentContext);
                    if (documentContext == null)
                    {
                        stackTrace += MiscHelpers.FormatInvariant("    at {0}\n", description);
                    }
                    else
                    {
                        IDebugDocument document;
                        documentContext.GetDocument(out document);
                        var documentText = (IDebugDocumentText)document;

                        string documentName;
                        document.GetName(DocumentNameType.UniqueTitle, out documentName);

                        uint position;
                        uint length;
                        documentText.GetPositionOfContext(documentContext, out position, out length);

                        using (var bufferBlock = new CoTaskMemArrayBlock(sizeof(char), (int)length))
                        {
                            uint lengthReturned = 0;
                            documentText.GetText(position, bufferBlock.Addr, IntPtr.Zero, ref lengthReturned, length);
                            var codeLine = Marshal.PtrToStringUni(bufferBlock.Addr, (int)lengthReturned);

                            uint lineNumber;
                            uint offsetInLine;
                            documentText.GetLineOfPosition(position, out lineNumber, out offsetInLine);

                            stackTrace += MiscHelpers.FormatInvariant("    at {0} ({1}:{2}:{3}) -> {4}\n", description, documentName, lineNumber, offsetInLine, codeLine);
                        }
                    }
                }
                finally
                {
                    if (descriptor.pFinalObject != IntPtr.Zero)
                    {
                        Marshal.Release(descriptor.pFinalObject);
                    }
                }
            }

            return(stackTrace.TrimEnd('\n'));
        }
Exemplo n.º 29
0
        public override string ToString()
        {
            var objectName = value.GetFriendlyName(typeof(T));

            return(MiscHelpers.FormatInvariant("HostVariable:{0}", objectName));
        }
Exemplo n.º 30
0
        private object MarshalToHostInternal(object obj, bool preserveHostTarget, HashSet <Array> marshaledArraySet)
        {
            if (obj == null)
            {
                return(Undefined.Value);
            }

            if (obj is DBNull)
            {
                return(null);
            }

            object result;

            if (MiscHelpers.TryMarshalPrimitiveToHost(obj, out result))
            {
                return(result);
            }

            var array = obj as Array;

            if (array != null)
            {
                // COM interop converts VBScript arrays to managed arrays

                bool alreadyMarshaled;
                if (marshaledArraySet != null)
                {
                    alreadyMarshaled = marshaledArraySet.Contains(array);
                }
                else
                {
                    marshaledArraySet = new HashSet <Array>();
                    alreadyMarshaled  = false;
                }

                if (!alreadyMarshaled)
                {
                    marshaledArraySet.Add(array);
                    array.Iterate(indices => array.SetValue(MarshalToHostInternal(array.GetValue(indices), preserveHostTarget, marshaledArraySet), indices));
                }

                return(array);
            }

            var hostTarget = obj as HostTarget;

            if (hostTarget != null)
            {
                return(preserveHostTarget ? hostTarget : hostTarget.Target);
            }

            var hostItem = obj as HostItem;

            if (hostItem != null)
            {
                return(preserveHostTarget ? hostItem.Target : hostItem.Unwrap());
            }

            if (obj is ScriptItem)
            {
                return(obj);
            }

            return(WindowsScriptItem.Wrap(this, obj));
        }
Exemplo n.º 31
0
        /// <summary>
        /// Upload file to server (file system or blob if azure)
        /// and return the name of the file created
        /// </summary>
        /// <param name="postedFile">file to upload</param>
        /// <returns>the file name</returns>
        public static string UploadFile(this Controller controller, HttpPostedFileBase postedFile, MiscHelpers.ImageSize imageSize, string folder = null)
        {
            if (postedFile == null)
                return string.Empty;

            var ext = Path.GetExtension(postedFile.FileName);
            var fileName = String.Format("{0:yyyy-MM-dd_hh-mm-ss-ffff}", DateTime.UtcNow) + ext;
            using (var fs = postedFile.InputStream)
            {
                SaveFile(controller, fs, fileName, ext, postedFile.ContentType, folder, imageSize.Width, imageSize.Height);
                SaveFile(controller, fs, fileName, ext, postedFile.ContentType, folder, imageSize.TWidth, imageSize.THeight, true);
            }
            return fileName;
        }
Exemplo n.º 32
0
 public PawnPiecesCP()
 {
     _borderPaint = MiscHelpers.GetStrokePaint(SKColors.Black, 1);
 }