Ejemplo n.º 1
0
 public SimpleAsyncHandlerResult(IContext context, HandlerInfo handlerInfo, AsyncCallback callback, object asyncState)
 {
     _context = context;
     _handlerInfo = handlerInfo;
     _callback = callback;
     AsyncState = asyncState;
     _helper = new ErrorHelper(context);
 }
        void ProcessAttributeProvider(ICustomAttributeProvider provider, MethodDefinition conditionA, MethodDefinition conditionB = null)
#endif
        {
            if (provider?.HasCustomAttributes != true)
            {
                return;
            }

            foreach (var ca in provider.CustomAttributes)
            {
                var tr = ca.Constructor.DeclaringType;

                if (!tr.Is("ObjCRuntime", "BindAsAttribute"))
                {
                    continue;
                }

                if (ca.ConstructorArguments.Count != 1)
                {
                    ErrorHelper.Show(ErrorHelper.CreateWarning(LinkContext.Target.App, 4124, provider, Errors.MT4124_E, provider.AsString(), ca.ConstructorArguments.Count));
                    continue;
                }

                var managedType     = ca.ConstructorArguments [0].Value as TypeReference;
                var managedEnumType = managedType?.GetElementType().Resolve();
                if (managedEnumType == null)
                {
                    ErrorHelper.Show(ErrorHelper.CreateWarning(LinkContext.Target.App, 4124, provider, Errors.MT4124_H, provider.AsString(), managedType?.FullName));
                    continue;
                }

                // We only care about enums, BindAs attributes can be used for other types too.
                if (!managedEnumType.IsEnum)
                {
                    continue;
                }

                Tuple <MethodDefinition, MethodDefinition> pair;
                if (cache != null && cache.TryGetValue(managedEnumType, out pair))
                {
#if NET
                    // The pair was already marked if it was cached.
#else
                    Preserve(pair, conditionA, conditionB);
#endif
                    continue;
                }

                // Find the Extension type
                TypeDefinition extensionType = null;
                var            extensionName = managedEnumType.Name + "Extensions";
                foreach (var type in managedEnumType.Module.Types)
                {
                    if (type.Namespace != managedEnumType.Namespace)
                    {
                        continue;
                    }
                    if (type.Name != extensionName)
                    {
                        continue;
                    }
                    extensionType = type;
                    break;
                }
                if (extensionType == null)
                {
                    Driver.Log(1, $"Could not find a smart extension type for the enum {managedEnumType.FullName} (due to BindAs attribute on {provider.AsString ()}): most likely this is because the enum isn't a smart enum.");
                    continue;
                }

                // Find the GetConstant/GetValue methods
                MethodDefinition getConstant = null;
                MethodDefinition getValue    = null;

                foreach (var method in extensionType.Methods)
                {
                    if (!method.IsStatic)
                    {
                        continue;
                    }
                    if (!method.HasParameters || method.Parameters.Count != 1)
                    {
                        continue;
                    }
                    if (method.Name == "GetConstant")
                    {
                        if (!method.ReturnType.Is("Foundation", "NSString"))
                        {
                            continue;
                        }
                        if (method.Parameters [0].ParameterType != managedEnumType)
                        {
                            continue;
                        }
                        getConstant = method;
                    }
                    else if (method.Name == "GetValue")
                    {
                        if (!method.Parameters [0].ParameterType.Is("Foundation", "NSString"))
                        {
                            continue;
                        }
                        if (method.ReturnType != managedEnumType)
                        {
                            continue;
                        }
                        getValue = method;
                    }
                }

                if (getConstant == null)
                {
                    Driver.Log(1, $"Could not find the GetConstant method on the supposedly smart extension type {extensionType.FullName} for the enum {managedEnumType.FullName} (due to BindAs attribute on {provider.AsString ()}): most likely this is because the enum isn't a smart enum.");
                    continue;
                }

                if (getValue == null)
                {
                    Driver.Log(1, $"Could not find the GetValue method on the supposedly smart extension type {extensionType.FullName} for the enum {managedEnumType.FullName} (due to BindAs attribute on {provider.AsString ()}): most likely this is because the enum isn't a smart enum.");
                    continue;
                }

                pair = new Tuple <MethodDefinition, MethodDefinition> (getConstant, getValue);
                if (cache == null)
                {
                    cache = new Dictionary <TypeDefinition, Tuple <MethodDefinition, MethodDefinition> > ();
                }
                cache.Add(managedEnumType, pair);
#if NET
                Mark(pair);
#else
                Preserve(pair, conditionA, conditionB);
#endif
            }
        }
        public List <ICodeElement> MarshalFromLambdaReceiverToCSProp(CSProperty prop, CSType thisType, string csProxyName, CSParameterList delegateParams,
                                                                     FunctionDeclaration funcDecl, CSType methodType, bool isObjC, bool hasAssociatedTypes)
        {
            bool forProtocol     = csProxyName != null;
            bool needsReturn     = funcDecl.IsGetter;
            bool returnIsGeneric = funcDecl.IsTypeSpecGeneric(funcDecl.ReturnTypeSpec);

            var entity = !returnIsGeneric?typeMapper.GetEntityForTypeSpec(funcDecl.ReturnTypeSpec) : null;

            var entityType = !returnIsGeneric?typeMapper.GetEntityTypeForTypeSpec(funcDecl.ReturnTypeSpec) : EntityType.None;

            bool returnIsStructOrEnum = needsReturn && entity != null && entity.IsStructOrEnum;
            bool returnIsClass        = needsReturn && entity != null && entity.EntityType == EntityType.Class;
            bool returnIsProtocol     = needsReturn && entity != null && entity.EntityType == EntityType.Protocol;
            bool returnIsProtocolList = needsReturn && entityType == EntityType.ProtocolList;
            bool returnIsTuple        = needsReturn && entityType == EntityType.Tuple;
            bool returnIsClosure      = needsReturn && entityType == EntityType.Closure;

            string returnCsProxyName = returnIsProtocol ?
                                       NewClassCompiler.CSProxyNameForProtocol(entity.Type.ToFullyQualifiedName(true), typeMapper) : null;

            if (returnIsProtocol && returnCsProxyName == null)
            {
                throw ErrorHelper.CreateError(ReflectorError.kCompilerReferenceBase + 22, $"Unable to find C# interface for protocol {entity.Type.ToFullyQualifiedName ()}");
            }


            var body = new List <ICodeElement> ();

            if (isObjC)
            {
                use.AddIfNotPresent("ObjCRuntime");
            }
            else
            {
                use.AddIfNotPresent(typeof(SwiftObjectRegistry));
            }


            CSIdentifier csharpCall   = null;
            var          thisTypeName = hasAssociatedTypes ? csProxyName : thisType.ToString();

            if (forProtocol && !hasAssociatedTypes)
            {
                csharpCall = new CSIdentifier($"SwiftObjectRegistry.Registry.InterfaceForExistentialContainer<{thisTypeName}> (self).{prop.Name.Name}");
            }
            else
            {
                var call = isObjC ?
                           $"ObjCRuntime.Runtime.GetNSObject<{thisTypeName}> (self).{prop.Name.Name}" :
                           $"SwiftObjectRegistry.Registry.CSObjectForSwiftObject<{thisTypeName}> (self).{prop.Name.Name}";

                csharpCall = new CSIdentifier(call);
            }

            if (funcDecl.IsGetter)
            {
                if (returnIsClass)
                {
                    if (isObjC)
                    {
                        body.Add(CSReturn.ReturnLine(csharpCall.Dot(new CSIdentifier("Handle"))));
                    }
                    else
                    {
                        body.Add(CSReturn.ReturnLine(csharpCall.Dot(NewClassCompiler.kSwiftObjectGetter)));
                    }
                }
                else if (returnIsStructOrEnum || returnIsTuple || returnIsGeneric)
                {
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                    var    retvalId   = new CSIdentifier(retvalName);
                    body.Add(CSFieldDeclaration.VarLine(methodType, retvalId, csharpCall));
                    if (returnIsGeneric)
                    {
                        body.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.ToSwift", false,
                                                                 methodType.Typeof(), retvalId, delegateParams [0].Name));
                    }
                    else
                    {
                        body.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.ToSwift", false,
                                                                 retvalId, delegateParams [0].Name));
                    }
                }
                else if (returnIsProtocol)
                {
                    string retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                    identifiersUsed.Add(retvalName);
                    var retvalId = new CSIdentifier(retvalName);
                    body.Add(CSFieldDeclaration.VarLine(methodType, retvalId, csharpCall));
                    var protocolMaker = new CSFunctionCall("SwiftExistentialContainer1", true,
                                                           new CSFunctionCall("SwiftObjectRegistry.Registry.ExistentialContainerForProtocols", false, retvalId, methodType.Typeof()));
                    body.Add(CSReturn.ReturnLine(protocolMaker));
                }
                else if (returnIsProtocolList)
                {
                    var protoTypeOf    = new List <CSBaseExpression> ();
                    var swiftProtoList = funcDecl.ReturnTypeSpec as ProtocolListTypeSpec;
                    foreach (var swiftProto in swiftProtoList.Protocols.Keys)
                    {
                        protoTypeOf.Add(typeMapper.MapType(funcDecl, swiftProto, false).ToCSType(use).Typeof());
                    }
                    var callExprs = new List <CSBaseExpression> ();
                    callExprs.Add(csharpCall);
                    callExprs.AddRange(protoTypeOf);
                    var retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                    identifiersUsed.Add(retvalName);
                    var retvalId = new CSIdentifier(retvalName);
                    body.Add(CSVariableDeclaration.VarLine(methodType, retvalId, new CSFunctionCall("StructMarshal.ThrowIfNotImplementsAll", false, callExprs.ToArray())));
                    var containerExprs = new List <CSBaseExpression> ();
                    containerExprs.Add(retvalId);
                    containerExprs.AddRange(protoTypeOf);

                    var returnContainerName = MarshalEngine.Uniqueify("returnContainer", identifiersUsed);
                    identifiersUsed.Add(returnContainerName);
                    var returnContainerId = new CSIdentifier(returnContainerName);
                    body.Add(CSVariableDeclaration.VarLine(CSSimpleType.Var, returnContainerId, new CSFunctionCall("SwiftObjectRegistry.Registry.ExistentialContainerForProtocols", false, containerExprs.ToArray())));
                    body.Add(CSFunctionCall.FunctionCallLine($"{returnContainerName}.CopyTo", false, new CSUnaryExpression(CSUnaryOperator.Ref, delegateParams [0].Name)));
                }
                else
                {
                    if (returnIsClosure)
                    {
                        body.Add(CSReturn.ReturnLine(MarshalEngine.BuildBlindClosureCall(csharpCall, methodType as CSSimpleType, use)));
                    }
                    else
                    {
                        body.Add(CSReturn.ReturnLine(csharpCall));
                    }
                }
            }
            else
            {
                CSBaseExpression valueExpr      = null;
                bool             valueIsGeneric = funcDecl.IsTypeSpecGeneric(funcDecl.ParameterLists [1] [0].TypeSpec);
                entity = !valueIsGeneric?typeMapper.GetEntityForTypeSpec(funcDecl.ParameterLists [1] [0].TypeSpec) : null;

                entityType = !valueIsGeneric?typeMapper.GetEntityTypeForTypeSpec(funcDecl.ParameterLists [1] [0].TypeSpec) : EntityType.None;

                var isUnusualNewValue = IsUnusualParameter(entity, delegateParams [1]);

                if (entityType == EntityType.Class || (entity != null && entity.IsObjCProtocol))
                {
                    var csParmType = delegateParams [1].CSType as CSSimpleType;
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 42, "Inconceivable! The class type for a method was a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(SwiftObjectRegistry));
                    var fullClassName = entity.Type.ToFullyQualifiedName(true);
                    var retrievecall  = NewClassCompiler.SafeMarshalClassFromIntPtr(delegateParams [1].Name, csParmType, use, fullClassName, typeMapper, entity.IsObjCProtocol);
                    valueExpr = retrievecall;
                }
                else if (entityType == EntityType.Protocol)
                {
                    use.AddIfNotPresent(typeof(SwiftObjectRegistry));
                    var retrievecall = new CSFunctionCall($"SwiftObjectRegistry.Registry.InterfaceForExistentialContainer<{thisType.ToString ()}> (self).{prop.Name.Name}", false);
                    valueExpr = retrievecall;
                }
                else if (entityType == EntityType.Tuple || (entity != null && entity.IsStructOrEnum && !isUnusualNewValue))
                {
                    var ntb     = typeMapper.MapType(funcDecl, funcDecl.ParameterLists [1] [0].TypeSpec, false);
                    var valType = ntb.ToCSType(use);
                    if (entityType == EntityType.TrivialEnum)
                    {
                        valueExpr = new CSCastExpression(valType, new CSCastExpression(CSSimpleType.Long, delegateParams [1].Name));
                    }
                    else
                    {
                        var marshalCall = new CSFunctionCall("StructMarshal.Marshaler.ToNet", false, delegateParams [1].Name, valType.Typeof());
                        valueExpr = new CSCastExpression(valType, marshalCall);
                    }
                }
                else if (valueIsGeneric)
                {
                    // T someVal = (T)StructMarshal.Marshaler.ToNet(parm, typeof(T));
                    // someVal gets passed in
                    var depthIndex = funcDecl.GetGenericDepthAndIndex(funcDecl.ParameterLists [1] [0].TypeSpec);
                    var genRef     = new CSGenericReferenceType(depthIndex.Item1, depthIndex.Item2);
                    genRef.ReferenceNamer = GenericRenamer;
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify(delegateParams [1].Name + "Temp", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    var valDecl = CSVariableDeclaration.VarLine(genRef, valMarshalId,
                                                                new CSCastExpression(genRef, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false,
                                                                                                                delegateParams [1].Name,
                                                                                                                genRef.Typeof())));
                    body.Add(valDecl);
                    valueExpr = valMarshalId;
                }
                else
                {
                    if (entityType == EntityType.Closure)
                    {
                        valueExpr = MarshalEngine.BuildWrappedClosureCall(delegateParams [1].Name, methodType as CSSimpleType);
                    }
                    else
                    {
                        valueExpr = delegateParams [1].Name;
                    }
                }
                body.Add(CSAssignment.Assign(csharpCall, valueExpr));
            }
            return(body);
        }
Ejemplo n.º 4
0
        void EnvDTE.IDTWizard.Execute(object Application, int hwndOwner, ref object[] ContextParams, ref object[] CustomParams, ref EnvDTE.wizardResult retval)
        {
            IVsTemplate vsTemplate = null;

            try
            {
                DTE dte = new DTETemplate((DTE)Application);
                CustomParams[0] = Environment.ExpandEnvironmentVariables((string)CustomParams[0]);

                if (!Path.IsPathRooted((string)CustomParams[0]) && CustomParams.Length >= 2)
                {
                    var guidancePackageName = (string)CustomParams[1];

                    var guidancePackageConfigurationFile = RecipeManager.GetConfigurationFile(RecipeManagerPackage.Singleton, guidancePackageName);

                    if (!string.IsNullOrEmpty(guidancePackageConfigurationFile))
                    {
                        var template = Path.Combine(Path.GetDirectoryName(guidancePackageConfigurationFile), (string)CustomParams[0]);

                        if (File.Exists(template))
                        {
                            CustomParams[0] = template;
                        }
                    }
                }
                string templateFileName             = (string)CustomParams[0];
                IVsTemplatesService templateService = (IVsTemplatesService)
                                                      ServiceHelper.GetService(
                    (IRecipeManagerService)
                    new VsServiceProvider(Application).GetService(typeof(IRecipeManagerService)),
                    typeof(IVsTemplatesService), this);
                vsTemplate = templateService.GetTemplate(templateFileName);
                string wizardKind = ((string)ContextParams[0]).ToUpper(CultureInfo.InvariantCulture);
                if (wizardKind == Constants.vsWizardNewProject)
                {
                    string destDir = (string)ContextParams[2];
                    //Web projects can pass in an empty directory, if so don't create the dest directory.
                    if ((new System.Uri(destDir)).IsFile)
                    {
                        Directory.CreateDirectory(destDir);
                    }

                    //If adding the project as exclusive, close the current solution then check to see if a
                    //  solution name is specified. If so, then create Ona solution with that name.
                    if (((bool)ContextParams[4]) == true)
                    {
                        vsPromptResult promptResult = dte.ItemOperations.PromptToSave;
                        if (promptResult == vsPromptResult.vsPromptResultCancelled)
                        {
                            retval = wizardResult.wizardResultCancel;
                            return;
                        }
                        dte.Solution.Close(false);
                        if (string.IsNullOrEmpty(((string)ContextParams[5])) == false)
                        {
                            dte.Solution.Create(destDir, ((string)ContextParams[5]));
                        }
                        ContextParams[4] = false;
                    }
                    // Create a new Solution Folder for the multiproject template
                    else if (vsTemplate.VSKind == WizardRunKind.AsMultiProject)
                    {
                        string folderName = (string)ContextParams[1];
                        if (dte.SelectedItems.Count == 1)
                        {
                            object item = DteHelper.GetTarget(dte);
                            if (item is Solution2)
                            {
                                ((Solution2)item).AddSolutionFolder(folderName);
                            }
                            else if (item is Project)
                            {
                                SolutionFolder slnFolder = (SolutionFolder)(((Project)item).Object);
                                slnFolder.AddSolutionFolder(folderName);
                            }
                        }
                    }
                }

                // Pre-fill state with context parameters.
                context = new System.Collections.Specialized.HybridDictionary();
                // See http://msdn.microsoft.com/library/en-us/vsintro7/html/vxlrfcontextparamsenum.asp
                string kind = ((string)ContextParams[0]).ToUpper();
                if (kind == Constants.vsWizardNewProject.ToUpper())
                {
                    FillNewProject(ContextParams, context);
                }
                else if (kind == Constants.vsWizardAddSubProject.ToUpper())
                {
                    FillAddSubProject(ContextParams, context);
                }
                else if (kind == Constants.vsWizardAddItem.ToUpper())
                {
                    FillAddItem(ContextParams, context);
                }

                IDTWizard wizard = new Microsoft.VisualStudio.TemplateWizard.Wizard();
                wizard.Execute(dte, hwndOwner, ref ContextParams, ref CustomParams, ref retval);
            }
            catch (Exception ex)
            {
                retval = wizardResult.wizardResultCancel;
                if (!(ex is COMException) || ((COMException)ex).ErrorCode != VSConstants.E_ABORT)
                {
                    ErrorHelper.Show(this.Site, ex);
                }
            }
            finally
            {
                Debug.Assert(UnfoldTemplate.UnfoldingTemplates.Count == 0);
                UnfoldTemplate.UnfoldingTemplates.Clear();
            }
        }
Ejemplo n.º 5
0
        // failure overrides, with defaults

        protected virtual Exception Fail(AssemblyDefinition assembly, Exception e)
        {
            var message = $"{Name} failed processing `{assembly?.FullName}`.";

            return(ErrorHelper.CreateError(ErrorCode, e, message));
        }
Ejemplo n.º 6
0
        protected virtual Exception Fail(PropertyDefinition property, Exception e)
        {
            var message = $"{Name} failed processing {property?.FullName}.";

            return(ErrorHelper.CreateError(ErrorCode | 4, e, message));
        }
Ejemplo n.º 7
0
        protected virtual Exception Fail(FieldDefinition field, Exception e)
        {
            var message = $"{Name} failed processing `{field?.FullName}`.";

            return(ErrorHelper.CreateError(ErrorCode | 2, e, message));
        }
Ejemplo n.º 8
0
 private void solutionTree_AfterSelect(object sender, TreeViewEventArgs e)
 {
     if (e.Node.Tag == null)
     {
         // May be a node that holds other elements.
         this.validSelection = false;
         if (SelectionChanged != null)
         {
             SelectionChanged(this, new SelectionChangedEventArgs(this.validSelection, e.Node.Tag));
         }
         return;
     }
     try
     {
         if (reference == null)
         {
             // UNDONE: the generic code at the end of the if statements
             // doesn't work for COM objects. Find an alternative generic way of
             // determining type compatibility in the future.
             if (this.valueType == typeof(EnvDTE.Solution))
             {
                 this.validSelection = e.Node.Tag is EnvDTE.Solution;
             }
             else if (this.valueType == typeof(EnvDTE.Project))
             {
                 this.validSelection = e.Node.Tag is EnvDTE.Project;
             }
             else if (this.valueType == typeof(EnvDTE.ProjectItem))
             {
                 this.validSelection = e.Node.Tag is EnvDTE.ProjectItem;
             }
             else if (this.valueType == typeof(EnvDTE80.SolutionFolder))
             {
                 this.validSelection = e.Node.Tag is EnvDTE80.SolutionFolder;
             }
             else if (this.valueType == typeof(VSLangProj.Reference))
             {
                 this.validSelection = e.Node.Tag is VSLangProj.Reference;
             }
             else
             {
                 this.validSelection = (this.valueType == e.Node.Tag.GetType() ||
                                        this.valueType.IsAssignableFrom(e.Node.Tag.GetType()));
             }
         }
         else
         {
             try
             {
                 this.validSelection = reference.IsEnabledFor(e.Node.Tag);
             }
             catch (Exception ex)
             {
                 throw new RecipeFrameworkException(
                           Properties.Resources.Reference_FailEnabledFor, ex);
             }
         }
     }
     catch (Exception ex)
     {
         this.validSelection = false;
         ErrorHelper.Show(this.Site, ex);
     }
     finally
     {
         try
         {
             if (this.validSelection && GetService(typeof(IWindowsFormsEditorService)) != null)
             {
                 ((IWindowsFormsEditorService)GetService(typeof(IWindowsFormsEditorService))).CloseDropDown();
             }
             if (SelectionChanged != null)
             {
                 SelectionChanged(this, new SelectionChangedEventArgs(this.validSelection, e.Node.Tag));
             }
         }
         catch (Exception ex)
         {
             ErrorHelper.Show(this.Site, ex);
         }
     }
 }
Ejemplo n.º 9
0
 private void NpmController_ExceptionLogged(object sender, NpmExceptionEventArgs e)
 {
     WriteNpmLogToOutputWindow(ErrorHelper.GetExceptionDetailsText(e.Exception));
 }
Ejemplo n.º 10
0
        public ActionResult Callback()
        {
            var oauthClient = new FacebookOAuthClient(FacebookApplication.Current)
            {
                RedirectUri = GetFacebookRedirectUri()
            };
            FacebookOAuthResult oAuthResult;

            if (oauthClient.TryParseResult(Request.Url, out oAuthResult))
            {
                if (oAuthResult.IsSuccess)
                {
                    if (!string.IsNullOrWhiteSpace(oAuthResult.Code))
                    {
                        string returnUrl  = "";
                        string domainName = null;
                        string planName   = null;
                        string affiliate  = null;
                        var    state      = new CallbackState();
                        try
                        {
                            if (!string.IsNullOrWhiteSpace(oAuthResult.State))
                            {
                                state = (CallbackState)JsonSerializer.Current.DeserializeObject(Encoding.UTF8.GetString(OAuthFacebook.Base64UrlDecode(oAuthResult.State)), typeof(CallbackState));
                                // TODO: at the moment only check if there is token. Hack Bug
                                // we do this because for logins we are saving token in a separate domain
                                if (!string.IsNullOrEmpty(state.csrf_token) && !ValidateFacebookCsrfToken(state.csrf_token))
                                {
                                    // someone tried to hack the site.
                                    return(RedirectToAction("Index", "Error"));
                                }

                                if (!string.IsNullOrEmpty(state.return_url))
                                {
                                    returnUrl = state.return_url;
                                }

                                if (!string.IsNullOrEmpty(state.domain_name))
                                {
                                    domainName = state.domain_name;
                                }

                                if (!string.IsNullOrEmpty(state.plan_name))
                                {
                                    planName = state.plan_name;
                                }

                                if (!string.IsNullOrEmpty(state.affiliate))
                                {
                                    affiliate = state.affiliate;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Syslog.Write(ex);
                            // catch incase user puts his own state,
                            // Base64UrlDecode might throw exception if the value is not properly encoded.
                            return(RedirectToAction("Index", "Error"));
                        }

                        try
                        {
                            var token         = (IDictionary <string, object>)oauthClient.ExchangeCodeForAccessToken(oAuthResult.Code);
                            var token_key     = (string)token["access_token"];
                            var token_expires = token.ContainsKey("expires") ? token["expires"].ToString() : "";
                            if (state.isRegistration && !string.IsNullOrEmpty(domainName))
                            {
                                var errorMessage = ProcessSuccesfulFacebookRegistrationCallback(token, domainName, planName, affiliate);

                                if (!string.IsNullOrEmpty(errorMessage))
                                {
                                    return(Redirect(ErrorHelper.CreateErrorPage(errorMessage, "/register/" + planName)));
                                }
                            }

                            if (state.isLogin || state.isLink)
                            {
                                var returnUri       = new Uri(returnUrl);
                                var queryParameters = HttpUtility.ParseQueryString(returnUri.Query);
                                queryParameters.Add("token", token_key);
                                queryParameters.Add("expires", token_expires);
                                returnUrl = string.Format("{0}://{1}{2}{3}", returnUri.Scheme, returnUri.Host, returnUri.LocalPath, queryParameters.ToQueryString(true));
                            }

                            if (state.requestPageTokens && !string.IsNullOrEmpty(state.domain_name))
                            {
                                // obtain any other account tokens
                                var facebook = new FacebookService(token_key);
                                var accounts = facebook.Account.GetAccountTokens("me");
                                if (accounts != null && accounts.data != null)
                                {
                                    var domain =
                                        repository.GetSubDomains().SingleOrDefault(x => x.name == state.domain_name);
                                    if (domain != null)
                                    {
                                        foreach (var entry in accounts.data)
                                        {
                                            if (entry.name != null)
                                            {
                                                var ftoken = new facebook_token
                                                {
                                                    pageid      = entry.id,
                                                    subdomainid = domain.id,
                                                    accesstoken = entry.access_token,
                                                    name        = entry.name,
                                                    category    = entry.category,
                                                    flags       = (int)FacebookTokenSettings.NONE
                                                };
                                                repository.AddUpdateFacebookToken(ftoken);
                                            }
                                        }
                                    }
                                }
                            }

                            // save any changes
                            repository.Save();

                            // prevent open redirection attacks. make sure the returnUrl is trusted before redirecting to it
                            if (!string.IsNullOrWhiteSpace(returnUrl) && returnUrl.Contains(GeneralConstants.SUBDOMAIN_HOST))
                            {
                                return(Redirect(returnUrl));
                            }
                        }
                        catch (FacebookApiException ex)
                        {
                            // catch incase the user entered dummy code or the code expired.
                            Syslog.Write(ex);
                        }
                    }
                }
                else
                {
                    switch (oAuthResult.ErrorReason)
                    {
                    // permission request denied
                    case "user_denied":
                        return(RedirectToAction("NoAuth", "Error"));

                    default:
                        Syslog.Write(string.Format("Unhandled Facebook OAUTH {0} - {1}", oAuthResult.ErrorReason, oAuthResult.ErrorDescription));
                        break;
                    }
                }
            }
            return(RedirectToAction("Index", "Error"));
        }
Ejemplo n.º 11
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            var  request          = actionContext.ActionArguments[RequestArgumentName];
            bool enableValidation = false;

            if (Utils.Configuration.HasSetting(Constants.ValidateWSDLocation))
            {
                enableValidation = Utils.Configuration[Constants.ValidateWSDLocation].ToBool();
            }

            if (request == null || !enableValidation)
            {
                return;
            }

            HttpRequestMessage httpRequest  = (HttpRequestMessage)request;
            Request            requestparam = new Request();

            this.PawsAuditor.UserId        = this.PawsLogger.UserId;
            this.PawsAuditor.TransactionId = this.PawsLogger.TransactionId;
            this.PawsAuditor.RegionCode    = Utils.Configuration.CurrentRegionId;

            try
            {
                requestparam = JsonSerialization.DeserializeString <Request>(httpRequest.Content.ReadAsStringAsync().Result);
                GeoLocation   geolocation  = requestparam.Params.Location;
                GeoLocation[] geolocations = requestparam.Params.Locations;

                List <RegionPolygonsCache> subregions = (List <RegionPolygonsCache>)DatabaseCache.ServiceCacheHelper.GetServiceCacheObjects(ServiceCacheObjectType.RegionPolygons, null);

                bool isValidRequest = false;
                bool isBatchRequest = false;

                if (geolocation != null)
                {
                    isValidRequest = ValidateRequestedLocation(geolocation, subregions);
                }
                else if (geolocations != null && geolocations.Length > 0)
                {
                    isBatchRequest = true;
                    isValidRequest = ValidateBatchRequestLocations(geolocations, subregions);
                }

                stopWatch.Stop();

                if (!isValidRequest)
                {
                    PawsResponse errorResponse = null;

                    if (isBatchRequest)
                    {
                        errorResponse = ErrorHelper.CreateErrorResponse(requestparam.Method, geolocations, Constants.ErrorMessageOutsideCoverage);
                    }
                    else
                    {
                        errorResponse = ErrorHelper.CreateErrorResponse(requestparam.Method, geolocation, Constants.ErrorMessageOutsideCoverage);
                    }

                    this.PawsLogger.Log(TraceEventType.Error, LoggingMessageId.PAWSGenericMessage, errorResponse.Error.Message);

                    string  auditMethod;
                    AuditId auditId = PawsUtil.GetAuditId(requestparam.Method, out auditMethod);

                    this.PawsAuditor.Audit(auditId, AuditStatus.Failure, stopWatch.ElapsedMilliseconds, auditMethod + " failed");

                    actionContext.Response = actionContext.Request.CreateResponse <PawsResponse>(errorResponse);
                }
            }
            catch (Exception ex)
            {
                stopWatch.Stop();

                this.PawsLogger.Log(TraceEventType.Error, LoggingMessageId.PAWSGenericMessage, ex.ToString());

                string  auditMethod;
                AuditId auditId = PawsUtil.GetAuditId(requestparam.Method, out auditMethod);

                this.PawsAuditor.Audit(auditId, AuditStatus.Failure, stopWatch.ElapsedMilliseconds, auditMethod + " failed");

                PawsResponse errorResponse = ErrorHelper.CreateExceptionResponse(requestparam.Method, ex.Message);

                actionContext.Response = actionContext.Request.CreateResponse <PawsResponse>(errorResponse);
            }
        }
Ejemplo n.º 12
0
 public BindingException(int code, bool error, Exception innerException, string message, params object[] args) :
     base(String.Format(message, args), innerException)
 {
     Code  = code;
     Error = error || ErrorHelper.GetWarningLevel(code) == ErrorHelper.WarningLevel.Error;
 }
Ejemplo n.º 13
0
 public string GetErrorMessage(ErrorCode errorCode)
 {
     return(ErrorHelper.GetErrorMessage(errorCode));
 }
Ejemplo n.º 14
0
        /// <summary>
        /// 执行检查
        /// </summary>
        /// <returns></returns>
        public bool Check()
        {
            //初始化
            Init();

            if (m_NormalRuleList == null && m_TopoRuleList == null)
            {
                SendMessage(enumMessageType.RuleError, "没有可检查的规则,检查结束");
                return(false);
            }

            // 验证
            Verify();

            ReOpenTopo();

            // 预处理
            Pretreat();


            if (m_NormalRuleList.Count == 0 && m_TopoRuleList.Count == 0)
            {
                SendMessage(enumMessageType.RuleError, "没有可检查的规则,检查结束");
                return(false);
            }


            bool        isSucceed = true;
            ErrorHelper errHelper = ErrorHelper.Instance;

            errHelper.ResultConnection = this.m_ResultConnection;
            CheckHelper checkHelper = new CheckHelper(this.m_ResultConnection);

            // 自动检查
            for (int i = 0; i < m_NormalRuleList.Count; i++)
            {
                SendCheckingEvent(m_NormalRuleList[i]);
                SendMessage(enumMessageType.RuleError, string.Format("规则“{0}”开始检查", m_NormalRuleList[i].InstanceName));

                List <Error> errList  = new List <Error>();
                int          errCount = 0;
                try
                {
                    bool ruleSucceed = m_NormalRuleList[i].Check(ref errList);
                    if (ruleSucceed)
                    {
                        this.m_SucceedCount++;
                        if (errList != null)
                        {
                            errCount = errList.Count;
                        }

                        this.m_ErrorCount += 0;
                        SendMessage(enumMessageType.RuleError, string.Format("规则“{0}”检查成功,错误数:{1}\r\n", m_NormalRuleList[i].InstanceName, errCount));


                        checkHelper.UpdateRuleState(m_DictRuleAndInfo[m_NormalRuleList[i]].arrayRuleParas[0].strInstID, errCount, enumRuleState.ExecuteSucceed);
                    }
                    else
                    {
                        // 添加时默认了为失败,不用更新
                        //checkHelper.UpdateRuleState(m_DictRuleAndInfo[m_NormalRuleList[i]].arrayRuleParas[0].strInstID, 0, enumRuleState.ExecuteFailed);

                        SendMessage(enumMessageType.RuleError, string.Format("规则“{0}”检查失败\r\n", m_NormalRuleList[i].InstanceName));
                        isSucceed = false;
                        continue;
                    }
                }
                catch (Exception ex)
                {
                    // 添加时默认了为失败,不用更新
                    //checkHelper.UpdateRuleState(m_DictRuleAndInfo[m_NormalRuleList[i]].arrayRuleParas[0].strInstID, 0, enumRuleState.ExecuteFailed);

                    SendMessage(enumMessageType.Exception, string.Format("规则“{0}”检查失败,信息:{1}\r\n", m_NormalRuleList[i].InstanceName, ex.Message));
                    continue;
                }
                finally
                {
                    // 无论如何,检查完成了
                    SendRuleCheckedEvent(m_NormalRuleList[i], errCount);
                }

                errHelper.AddErrorList(errList);
            }

            // Topo检查
            // 由本类在Init方法中创建拓扑
            // 在Topo规则的预处理中进行拓扑规则添加
            // 在这里统一进行拓扑验证
            // 规则的Hy.Check方法只负责错误结果的读取
            if (m_TopoRuleList.Count > 0)
            {
                if (this.TopoRuleCheckBegin != null)
                {
                    this.TopoRuleCheckBegin.Invoke(this);
                }

                if (this.m_Topology != null)
                {
                    this.m_Topology.ValidateTopology((this.m_Topology.FeatureDataset as IGeoDataset).Extent);
                }

                for (int i = 0; i < m_TopoRuleList.Count; i++)
                {
                    SendCheckingEvent(m_TopoRuleList[i]);
                    SendMessage(enumMessageType.RuleError, string.Format("规则“{0}”开始获取(拓扑)结果", m_TopoRuleList[i].InstanceName));

                    List <Error> errList  = new List <Error>();
                    int          errCount = 0;
                    try
                    {
                        bool ruleSucceed = m_TopoRuleList[i].Check(ref errList);
                        if (ruleSucceed)
                        {
                            this.m_SucceedCount++;
                            if (errList != null)
                            {
                                errCount = errList.Count;
                            }

                            this.m_ErrorCount += errCount;
                            SendMessage(enumMessageType.RuleError, string.Format("规则“{0}”获取(拓扑)结果成功,错误数:{1}\r\n", m_TopoRuleList[i].InstanceName, errCount));

                            checkHelper.UpdateRuleState(m_DictRuleAndInfo[m_TopoRuleList[i]].arrayRuleParas[0].strInstID, errCount, enumRuleState.ExecuteSucceed, m_TopoRuleList[i].InstanceName);
                        }
                        else
                        {
                            // 添加时默认了为失败,不用更新
                            //checkHelper.UpdateRuleState(m_DictRuleAndInfo[m_TopoRuleList[i]].arrayRuleParas[0].strInstID, 0, enumRuleState.ExecuteFailed,m_TopoRuleList[i].InstanceName);

                            SendMessage(enumMessageType.RuleError, string.Format("规则“{0}”获取(拓扑)结果失败\r\n", m_TopoRuleList[i].InstanceName));
                            isSucceed = false;
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        // 添加时默认了为失败,不用更新
                        //checkHelper.UpdateRuleState(m_DictRuleAndInfo[m_TopoRuleList[i]].arrayRuleParas[0].strInstID, 0, enumRuleState.ExecuteFailed,m_TopoRuleList[i].InstanceName);

                        SendMessage(enumMessageType.Exception, string.Format("规则“{0}”获取(拓扑)结果失败,信息:{1}\r\n", m_TopoRuleList[i].InstanceName, ex.Message));
                        continue;
                    }
                    finally
                    {
                        // 无论如何,检查完成了
                        SendRuleCheckedEvent(m_TopoRuleList[i], errCount);
                    }

                    errHelper.AddErrorList(errList);
                }
            }

            errHelper.Flush();
            this.Release();

            if (this.CheckComplete != null)
            {
                this.CheckComplete.Invoke(this);
            }

            return(isSucceed);
        }
Ejemplo n.º 15
0
        public static void ReadLaunchArgs()
        {
            try
            {
                string key          = _settings.key;
                string queueName    = ExchangeNames.Launch + "_" + key;
                string exchangeName = ExchangeNames.Launch;

                IModel channel = GetChanel();
                ExchangeDeclareIfNotExist(exchangeName, "direct", true);

                channel.QueueBind(queueName,
                                  exchangeName,
                                  key);

                EventingBasicConsumer consumer = new EventingBasicConsumer(channel);

                consumer.Received += (model, ea) =>
                {
                    LogManager.GetCurrentClassLogger().Info("vw.launch received message!");
                    var    body    = ea.Body;
                    string message = Encoding.UTF8.GetString(body);

#if UNITY_EDITOR
                    SaveCache(message);
#endif
                    LaunchArguments launchArguments = message.JsonDeserialize <LaunchArguments>();

                    if (launchArguments.extraArgs != null)
                    {
                        Debug.Log("!!@@##"
                                  + launchArguments
                                  .extraArgs);     //not sure where to instantiate local logger with LogManager.GetCurrentClassLogger()
                        ArgumentStorage.ClearStorage();
                        ArgumentStorage.AddJsonArgsArray(launchArguments.extraArgs);
                    }

                    ProjectDataListener.Instance.LaunchArguments = launchArguments;
                };

                channel.BasicConsume(queueName,
                                     true,
                                     consumer);
            }
            catch (Exception e)
            {
                CloseConnectionAndChanel();

#if UNITY_EDITOR
                LaunchArguments launchArguments = LoadFromCache();

                if (launchArguments != null)
                {
                    LogManager.GetCurrentClassLogger().Info("Loading previous vw.launch...");
                    ProjectDataListener.Instance.LaunchArguments = launchArguments;
                }
                else
                {
                    LauncherErrorManager.Instance.ShowFatalErrorKey(
                        ErrorHelper.GetErrorKeyByCode(Varwin.Errors.ErrorCode.RabbitNoArgsError),
                        e.StackTrace);
                }
#else
                LogManager.GetCurrentClassLogger().Fatal("vw.launch not found! StackTrace = " + e.StackTrace);
                LauncherErrorManager.Instance.ShowFatalErrorKey(ErrorHelper.GetErrorKeyByCode(Varwin.Errors.ErrorCode.RabbitNoArgsError), e.StackTrace);
#endif
            }
        }
Ejemplo n.º 16
0
        public override bool UpdateData(int userId, int id, ref object dtoItem, out Notification notification)
        {
            notification      = new Notification();
            notification.Type = NotificationType.Success;
            FrameMaterialDto dtoFrameMaterial = ((Newtonsoft.Json.Linq.JObject)dtoItem).ToObject <FrameMaterialDto>();

            int    number;
            string indexName;

            try
            {
                using (var context = CreateContext())
                {
                    FrameMaterial frameMaterial = null;

                    if (id == 0)
                    {
                        frameMaterial = new FrameMaterial();

                        context.FrameMaterial.Add(frameMaterial);
                        frameMaterial.UpdatedBy   = userId;
                        frameMaterial.UpdatedDate = DateTime.Now;
                    }
                    else
                    {
                        var item = context.FrameMaterialMng_FrameMaterialCheck_View.Where(o => o.FrameMaterialID == id).FirstOrDefault();
                        //CheckPermission
                        if (item.isUsed.Value == true)
                        {
                            throw new Exception("You can't update because it used in item other!");
                        }
                        frameMaterial             = context.FrameMaterial.FirstOrDefault(o => o.FrameMaterialID == id);
                        frameMaterial.UpdatedBy   = userId;
                        frameMaterial.UpdatedDate = DateTime.Now;
                    }

                    if (frameMaterial == null)
                    {
                        notification.Message = "Frame Material not found!";

                        return(false);
                    }
                    else
                    {
                        converter.DTO2BD(dtoFrameMaterial, ref frameMaterial);

                        if (id <= 0)
                        {
                            // Generate code.
                            using (var trans = context.Database.BeginTransaction())
                            {
                                context.Database.ExecuteSqlCommand("SELECT * FROM FrameMaterial WITH (TABLOCKX, HOLDLOCK)");

                                try
                                {
                                    var newCode = context.FrameMaterialMng_function_GenerateCode().FirstOrDefault();

                                    if (!"**".Equals(newCode))
                                    {
                                        frameMaterial.FrameMaterialUD = newCode;

                                        context.SaveChanges();
                                    }
                                    else
                                    {
                                        notification.Type    = NotificationType.Error;
                                        notification.Message = "Auto generated code exceed maximum option: [ZZ]";
                                    }
                                }
                                catch (Exception ex)
                                {
                                    trans.Rollback();
                                    throw ex;
                                }
                                finally
                                {
                                    trans.Commit();
                                }
                            }
                        }
                        else
                        {
                            context.SaveChanges();
                        }

                        dtoItem = GetData(frameMaterial.FrameMaterialID, out notification).Data;

                        return(true);
                    }
                }
            }
            catch (DataException exData)
            {
                notification.Type = NotificationType.Error;
                ErrorHelper.DataExceptionParser(exData, out number, out indexName);

                if (number == 2601 && !string.IsNullOrEmpty(indexName))
                {
                    if ("FrameMaterialUDUnique".Equals(indexName))
                    {
                        notification.Message = "The Frame Material Code is already exists.";
                    }
                }
                else
                {
                    notification.Message = exData.Message;
                }

                return(false);
            }
            catch (Exception ex)
            {
                notification.Type    = NotificationType.Error;
                notification.Message = ex.Message;

                return(false);
            }
        }
 void Warn(AssemblyDefinition assembly, MemberReference mr)
 {
     ErrorHelper.Warning(WarnCode, Errors.MM2107, assembly.Name.Name, mr.DeclaringType.FullName, mr.Name, string.Join(", ", ((MethodReference)mr).Parameters.Select((v) => v.ParameterType.FullName)));
 }
Ejemplo n.º 18
0
        protected virtual Exception Fail(TypeDefinition type, Exception e)
        {
            var message = $"{Name} failed processing {type?.FullName}.";

            return(ErrorHelper.CreateError(ErrorCode | 1, e, message));
        }
Ejemplo n.º 19
0
        bool RegisterMethod(ObjCMethod method)
        {
            IntPtr reg_handle;
            IntPtr tramp;

            reg_handle = (method.IsStatic && !method.IsCategoryInstance) ? Class.object_getClass(method.DeclaringType.Handle) : method.DeclaringType.Handle;

            switch (method.Trampoline)
            {
            case Trampoline.Constructor:
                tramp = Method.ConstructorTrampoline;
                break;

            case Trampoline.Double:
                tramp = Method.DoubleTrampoline;
                break;

            case Trampoline.Long:
                tramp = Method.LongTrampoline;
                break;

            case Trampoline.Normal:
                tramp = Method.Trampoline;
                break;

            case Trampoline.Release:
                tramp = Method.ReleaseTrampoline;
                break;

            case Trampoline.Retain:
                tramp = Method.RetainTrampoline;
                break;

            case Trampoline.Single:
                tramp = Method.SingleTrampoline;
                break;

            case Trampoline.Static:
                tramp = Method.StaticTrampoline;
                break;

            case Trampoline.StaticDouble:
                tramp = Method.StaticDoubleTrampoline;
                break;

            case Trampoline.StaticLong:
                tramp = Method.StaticLongTrampoline;
                break;

            case Trampoline.StaticSingle:
                tramp = Method.StaticSingleTrampoline;
                break;

            case Trampoline.StaticStret:
                tramp = Method.StaticStretTrampoline;
                break;

            case Trampoline.Stret:
                tramp = Method.StretTrampoline;
                break;

            case Trampoline.X86_DoubleABI_StaticStretTrampoline:
                tramp = Method.X86_DoubleABI_StaticStretTrampoline;
                break;

            case Trampoline.X86_DoubleABI_StretTrampoline:
                tramp = Method.X86_DoubleABI_StretTrampoline;
                break;

#if MONOMAC
            case Trampoline.CopyWithZone1:
                tramp = Method.CopyWithZone1;
                break;

            case Trampoline.CopyWithZone2:
                tramp = Method.CopyWithZone2;
                break;
#endif
            case Trampoline.GetGCHandle:
                tramp = Method.GetGCHandleTrampoline;
                break;

            case Trampoline.SetGCHandle:
                tramp = Method.SetGCHandleTrampoline;
                break;

            default:
                throw ErrorHelper.CreateError(4144, "Cannot register the method '{0}.{1}' since it does not have an associated trampoline. Please file a bug report at http://bugzilla.xamarin.com", method.DeclaringType.Type.FullName, method.Name);
            }

            return(Class.class_addMethod(reg_handle, Selector.GetHandle(method.Selector), tramp, method.Signature));
        }
Ejemplo n.º 20
0
        protected virtual Exception Fail(MethodDefinition method, Exception e)
        {
            var message = $"{Name} failed processing `{method?.FullName}`.";

            return(ErrorHelper.CreateError(ErrorCode | 3, e, message));
        }
Ejemplo n.º 21
0
 protected override Exception CreateException(int code, Exception innerException, Type type, string message, params object [] args)
 {
     // There doesn't seem to be a way to find the source code location
     // for the method using System.Reflection.
     return(ErrorHelper.CreateError(code, innerException, message, args));
 }
Ejemplo n.º 22
0
        protected virtual Exception Fail(EventDefinition @event, Exception e)
        {
            var message = $"{Name} failed processing {@event?.FullName}.";

            return(ErrorHelper.CreateError(ErrorCode | 5, e, message));
        }
Ejemplo n.º 23
0
        protected override void OnRegisterProtocol(ObjCType type)
        {
            var protocol = Protocol.objc_getProtocol(type.ProtocolName);

            if (protocol != IntPtr.Zero)
            {
                type.Handle = protocol;
                if (!type_map.ContainsKey(protocol))
                {
                    type_map [protocol] = type;
                }
                return;
            }

            protocol = Protocol.objc_allocateProtocol(type.ProtocolName);

            if (type.Protocols != null)
            {
                foreach (var proto in type.Protocols)
                {
                    if (proto.ProtocolName == "JSExport")
                    {
#if MONOMAC
                        const string msg = "Detected a protocol ({0}) inheriting from the JSExport protocol while using the dynamic registrar. It is not possible to export protocols to JavaScriptCore dynamically; the static registrar must be used (add '--registrar:static' to the additional mmp arguments in the project's Mac Build options to select the static registrar).";
#else
                        const string msg = "Detected a protocol ({0}) inheriting from the JSExport protocol while using the dynamic registrar. It is not possible to export protocols to JavaScriptCore dynamically; the static registrar must be used (add '--registrar:static' to the additional mtouch arguments in the project's iOS Build options to select the static registrar).";
#endif
                        ErrorHelper.Warning(4147, msg, GetTypeFullName(type.Type));
                    }
                    Protocol.protocol_addProtocol(protocol, proto.Handle);
                }
            }

            if (type.Properties != null)
            {
                foreach (var property in type.Properties)
                {
                    int count;
                    var props = GetPropertyAttributes(property, out count, true);
                    // Only required instance properties are added (the rest of the logic is commented out in the public source at least,
                    // see file objc4-647/runtime/objc-runtime-old.mm in Apple's open source code). Still add all properties in case Apple
                    // implements their missing bits.
                    Protocol.protocol_addProperty(protocol, property.Selector, props, count, !property.IsOptional, !property.IsStatic);
                    // The properties need to be added as methods as well.
                    var propertyType = ToSignature(property.PropertyType, property, false);
                    Protocol.protocol_addMethodDescription(protocol, Selector.GetHandle(property.GetterSelector), propertyType + "@:", !property.IsOptional, !property.IsStatic);
                    if (!property.IsReadOnly)
                    {
                        Protocol.protocol_addMethodDescription(protocol, Selector.GetHandle(property.SetterSelector), "v@:" + propertyType, !property.IsOptional, !property.IsStatic);
                    }
                }
            }

            if (type.Methods != null)
            {
                foreach (var method in type.Methods)
                {
                    Protocol.protocol_addMethodDescription(protocol, Selector.GetHandle(method.Selector), method.Signature, !method.IsOptional, !method.IsStatic);
                }
            }

            Protocol.objc_registerProtocol(protocol);
            type_map [protocol] = type;

            Trace("   [DYNAMIC PROTOCOL] Registered the protocol {0} for {1}", type.ProtocolName, type.Type.FullName);
        }
Ejemplo n.º 24
0
        protected override void TryEndProcess()
        {
            var app = Configuration.Application;

            app.SelectRegistrar();

            switch (app.Registrar)
            {
            case RegistrarMode.Dynamic:
                // Nothing to do here
                break;

            case RegistrarMode.PartialStatic:
                string method = null;
                switch (app.Platform)
                {
                case ApplePlatform.iOS:
                    method = "xamarin_create_classes_Xamarin_iOS";
                    break;

                case ApplePlatform.WatchOS:
                    method = "xamarin_create_classes_Xamarin_WatchOS";
                    break;

                case ApplePlatform.TVOS:
                    method = "xamarin_create_classes_Xamarin_TVOS";
                    break;

                case ApplePlatform.MacOSX:
                    method = "xamarin_create_classes_Xamarin_Mac";
                    break;

                case ApplePlatform.MacCatalyst:
                    method = "xamarin_create_classes_Xamarin_MacCatalyst";
                    break;

                default:
                    Report(ErrorHelper.CreateError(71, Errors.MX0071, app.Platform, app.ProductName));
                    break;
                }
                Configuration.RegistrationMethods.Add(method);
                Configuration.CompilerFlags.AddLinkWith(Configuration.PartialStaticRegistrarLibrary);
                break;

            case RegistrarMode.Static:
                var dir    = Configuration.CacheDirectory;
                var header = Path.Combine(dir, "registrar.h");
                var code   = Path.Combine(dir, "registrar.mm");
                Configuration.Target.StaticRegistrar.Generate(Configuration.Assemblies, header, code);

                var items = new List <MSBuildItem> ();
                foreach (var abi in Configuration.Abis)
                {
                    items.Add(new MSBuildItem {
                        Include  = code,
                        Metadata =
                        {
                            { "Arch",      abi.AsArchString() },
                            { "Arguments", "-std=c++14"       },
                        },
                    });
                }

                Configuration.WriteOutputForMSBuild("_RegistrarFile", items);
                Configuration.RegistrationMethods.Add("xamarin_create_classes");
                break;

            case RegistrarMode.Default:             // We should have resolved 'Default' to an actual mode by now.
            default:
                Report(ErrorHelper.CreateError(99, Errors.MX0099, $"Invalid registrar mode: {app.Registrar}"));
                break;
            }
        }
Ejemplo n.º 25
0
        protected override void OnRegisterType(ObjCType type)
        {
            type.Handle = Class.GetHandle(type.ExportedName);

            if (type.Handle != IntPtr.Zero)
            {
                if (!type_map.ContainsKey(type.Handle))
                {
                    type_map [type.Handle] = type;
                }
                return;
            }

            /*FIXME try to guess the name of the missing library - quite trivial for monotouch.dll*/
            // types decorated with [Model] attribute are not registered (see registrar.cs and regression from #769)
            if (type.IsWrapper && !type.IsModel)
            {
                if (!IsSimulatorOrDesktop)
                {
                    // This can happen when Apple introduces new types and puts them as base types for already
                    // existing types. We can't throw any exceptions in that case, since the derived class
                    // can still be used in older iOS versions.

                    // Hardcode these types to ignore any loading errors.
                    // We could also look at the AvailabilityAttribute, but it would require us
                    // to not link it away anymore like we currently do.

#if !COREBUILD && !MONOMAC && !WATCH
                    var major = -1;
                    switch (type.Name)
                    {
                    case "PKObject":
                    case "CBAttribute":
                    case "CBPeer":
                        major = 8;
                        break;

                    case "GKGameCenterViewController":
                        major = 6;
                        break;

                    case "CBManager":
                    case "GKBasePlayer":
                        major = 10;
                        break;
                    }
                    if ((major > 0) && !UIDevice.CurrentDevice.CheckSystemVersion(major, 0))
                    {
                        return;
                    }
#endif

                    // a missing [Model] attribute will cause this error on devices (e.g. bug #4864)
                    throw ErrorHelper.CreateError(8005, "Wrapper type '{0}' is missing its native ObjectiveC class '{1}'.", type.Type.FullName, type.Name);
                }
                else
                {
                    /*On simulator this is a common issue since we eagerly register all types. This is an issue with unlinked
                     * monotouch.dll since we don't link all frameworks most of the time. */
                    return;
                }
            }

            if (type.IsFakeProtocol)
            {
                return;
            }

            var super = type.SuperType;

            type.Handle = Class.objc_allocateClassPair(super.Handle, type.ExportedName, IntPtr.Zero);

            if (type.Properties != null)
            {
                foreach (var property in type.Properties)
                {
                    int count;
                    var props = GetPropertyAttributes(property, out count, false);
                    Class.class_addProperty(type.Handle, property.Selector, props, count);
                }
            }

            if (type.Fields != null)
            {
                foreach (var field in type.Fields.Values)
                {
                    Class.class_addIvar(type.Handle, field.Name, new IntPtr(field.Size), field.Alignment, field.FieldType);
                }
            }

            if (type.Methods != null)
            {
                foreach (var method in type.Methods)
                {
                    RegisterMethod(method);
                }
            }

            if (type.Protocols != null)
            {
                foreach (var protocol in type.Protocols)
                {
                    Class.class_addProtocol(type.Handle, protocol.Handle);
                }
            }

            Class.objc_registerClassPair(type.Handle);
            type_map [type.Handle] = type;
            AddCustomType(type.Type);

            Trace("   [DYNAMIC CLASS] Registered the class {0} for {1}", type.ExportedName, type.Type.FullName);
        }
        public List <ICodeElement> MarshalFromLambdaReceiverToCSFunc(CSType thisType, string csProxyName, CSParameterList delegateParams,
                                                                     FunctionDeclaration funcDecl, CSType methodType, CSParameterList methodParams, string methodName, bool isObjC, bool hasAssociatedTypes)
        {
            bool thisIsInterface = csProxyName != null;
            bool isIndexer       = funcDecl.IsSubscript;
            bool needsReturn     = methodType != null && methodType != CSSimpleType.Void;
            bool isSetter        = funcDecl.IsSubscriptSetter;
            bool returnIsGeneric = funcDecl.IsTypeSpecGeneric(funcDecl.ReturnTypeSpec);

            var entity = !returnIsGeneric?typeMapper.GetEntityForTypeSpec(funcDecl.ReturnTypeSpec) : null;

            var returnEntity = entity;
            var entityType   = !returnIsGeneric?typeMapper.GetEntityTypeForTypeSpec(funcDecl.ReturnTypeSpec) : EntityType.None;

            bool returnIsStruct   = needsReturn && entity != null && entity.IsStructOrEnum;
            bool returnIsClass    = needsReturn && entity != null && entity.EntityType == EntityType.Class;
            bool returnIsProtocol = needsReturn && ((entity != null && entity.EntityType == EntityType.Protocol) || entityType == EntityType.ProtocolList);
            bool returnIsTuple    = needsReturn && entityType == EntityType.Tuple;
            bool returnIsClosure  = needsReturn && entityType == EntityType.Closure;

            var callParams                    = new List <CSBaseExpression> ();
            var preMarshalCode                = new List <CSLine> ();
            var postMarshalCode               = new List <CSLine> ();
            CSBaseExpression valueExpr        = null;
            bool             marshalingThrows = false;


            if (isSetter)
            {
                var valueID = delegateParams [1].Name;
                valueExpr = valueID;
                var  swiftNewValue     = funcDecl.ParameterLists [1] [0];
                bool newValueIsGeneric = funcDecl.IsTypeSpecGeneric(funcDecl.PropertyType);
                entity = !newValueIsGeneric?typeMapper.GetEntityForTypeSpec(swiftNewValue.TypeSpec) : null;

                entityType = !newValueIsGeneric?typeMapper.GetEntityTypeForTypeSpec(swiftNewValue.TypeSpec) : EntityType.None;

                var isUnusualNewValue = IsUnusualParameter(entity, delegateParams [1]);

                if (entityType == EntityType.Class || entity != null && entity.IsObjCProtocol)
                {
                    var csParmType = new CSSimpleType(entity.SharpNamespace + "." + entity.SharpTypeName);
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 26, "Inconceivable! The class type for a subscript was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(SwiftObjectRegistry));

                    var fullClassName = entity.Type.ToFullyQualifiedName(true);
                    valueExpr = NewClassCompiler.SafeMarshalClassFromIntPtr(valueID, csParmType, use, fullClassName, typeMapper, entity.IsObjCProtocol);
                }
                else if (entityType == EntityType.Protocol)
                {
                    var csParmType = new CSSimpleType(entity.SharpNamespace + "." + entity.SharpTypeName);
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 27, "Inconceivable! The protocol type for a subscript was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    use.AddIfNotPresent(typeof(SwiftObjectRegistry));
                    valueExpr = new CSFunctionCall($"SwiftObjectRegistry.Registry.InterfaceForExistentialContainer<{csParmType.ToString ()}>", false, valueID);
                }
                else if ((entityType == EntityType.Struct || entityType == EntityType.Enum) && !isUnusualNewValue)
                {
                    var csParmType = new CSSimpleType(entity.SharpNamespace + "." + entity.SharpTypeName);
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 28, $"Inconceivable! The {entityType} type for a subscript was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify("val", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    CSLine valDecl = CSVariableDeclaration.VarLine(csParmType, valMarshalId,
                                                                   new CSCastExpression(csParmType, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false, valueID,
                                                                                                                       csParmType.Typeof())));
                    preMarshalCode.Add(valDecl);
                    valueExpr = valMarshalId;
                }
                else if (entityType == EntityType.Tuple)
                {
                    var csParmType = new CSSimpleType(entity.SharpNamespace + "." + entity.SharpTypeName);
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 29, "Inconceivable! The tuple type for a subscript was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify("val", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    var valDecl = CSVariableDeclaration.VarLine(csParmType, valMarshalId,
                                                                new CSCastExpression(csParmType, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false, valueID,
                                                                                                                    csParmType.Typeof())));
                    preMarshalCode.Add(valDecl);
                    valueExpr = valMarshalId;
                }
                else if (newValueIsGeneric)
                {
                    var depthIndex = funcDecl.GetGenericDepthAndIndex(swiftNewValue.TypeSpec);
                    var genRef     = new CSGenericReferenceType(depthIndex.Item1, depthIndex.Item2);
                    genRef.ReferenceNamer = GenericRenamer;
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify("valTemp", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    var valDecl = CSVariableDeclaration.VarLine(genRef, valMarshalId,
                                                                new CSCastExpression(genRef, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false,
                                                                                                                valueID, genRef.Typeof())));
                    preMarshalCode.Add(valDecl);
                    valueExpr = valMarshalId;
                }
            }

            int j = 0;
            int k = isSetter ? 1 : 0;

            for (int i = (funcDecl.HasThrows || returnIsStruct || returnIsProtocol || isSetter || returnIsGeneric) ? 2 : 1; i < delegateParams.Count; i++, j++, k++)
            {
                var  swiftParm     = funcDecl.ParameterLists [1] [k];
                bool parmIsGeneric = funcDecl.IsTypeSpecGeneric(swiftParm);
                entity = !parmIsGeneric?typeMapper.GetEntityForTypeSpec(swiftParm.TypeSpec) : null;

                entityType = !parmIsGeneric?typeMapper.GetEntityTypeForTypeSpec(swiftParm.TypeSpec) : EntityType.None;

                var isUnusualParameter = IsUnusualParameter(entity, delegateParams [i]);
                var csParm             = methodParams [j];

                if (entityType == EntityType.Class || (entity != null && entity.IsObjCProtocol))
                {
                    var csParmType = csParm.CSType as CSSimpleType;
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 31, "Inconceivable! The class type for a method was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(SwiftObjectRegistry));

                    var fullClassName = entity.Type.ToFullyQualifiedName(true);
                    var retrievecall  = NewClassCompiler.SafeMarshalClassFromIntPtr(delegateParams [0].Name, csParmType, use, fullClassName, typeMapper, entity.IsObjCProtocol);
                    if (csParm.ParameterKind == CSParameterKind.Out || csParm.ParameterKind == CSParameterKind.Ref)
                    {
                        string id = MarshalEngine.Uniqueify(delegateParams [i].Name.Name, identifiersUsed);
                        identifiersUsed.Add(id);
                        preMarshalCode.Add(CSFieldDeclaration.FieldLine(csParmType, id, retrievecall));
                        callParams.Add(new CSIdentifier(String.Format("{0} {1}",
                                                                      csParm.ParameterKind == CSParameterKind.Out ? "out" : "ref", id)));
                        postMarshalCode.Add(CSAssignment.Assign(delegateParams [i].Name,
                                                                NewClassCompiler.SafeBackingFieldAccessor(new CSIdentifier(id), use, entity.Type.ToFullyQualifiedName(true), typeMapper)));
                    }
                    else
                    {
                        callParams.Add(retrievecall);
                    }
                }
                else if (entityType == EntityType.Protocol)
                {
                    var thePtr     = new CSIdentifier(MarshalEngine.Uniqueify("p", identifiersUsed));
                    var csParmType = csParm.CSType as CSSimpleType;
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 32, "Inconceivable! The protocol type for a method was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(SwiftObjectRegistry));
                    string csParmProxyType = NewClassCompiler.CSProxyNameForProtocol(entity.Type.ToFullyQualifiedName(true), typeMapper);
                    if (csParmProxyType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 33, $"Unable to find C# interface type for protocol {entity.Type.ToFullyQualifiedName ()}");
                    }

                    var retrievecall = new CSFunctionCall($"SwiftObjectRegistry.Registry.InterfaceForExistentialContainer<{csParmType.Name}>", false, delegateParams [i].Name);
                    if (csParm.ParameterKind == CSParameterKind.Out || csParm.ParameterKind == CSParameterKind.Ref)
                    {
                        CSIdentifier id = new CSIdentifier(MarshalEngine.Uniqueify(delegateParams [i].Name.Name, identifiersUsed));
                        identifiersUsed.Add(id.Name);
                        preMarshalCode.Add(CSFieldDeclaration.FieldLine(csParmType, id.Name, retrievecall));
                        callParams.Add(new CSIdentifier(String.Format("{0} {1}",
                                                                      csParm.ParameterKind == CSParameterKind.Out ? "out" : "ref", id)));
                        postMarshalCode.Add(CSAssignment.Assign(delegateParams [i].Name,
                                                                new CSFunctionCall("SwiftExistentialContainer1", true,
                                                                                   new CSFunctionCall("SwiftObjectRegistry.Registry.ExistentialContainerForProtocol", false, id, csParmType.Typeof()))));
                    }
                    else
                    {
                        callParams.Add(retrievecall);
                    }
                }
                else if ((entityType == EntityType.Struct || entityType == EntityType.Enum) && !isUnusualParameter)
                {
                    var csParmType = csParm.CSType as CSSimpleType;
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 34, $"Inconceivable! The {entityType} type for a method was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify(delegateParams [i].Name + "Temp", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    var valDecl = CSVariableDeclaration.VarLine(csParmType, valMarshalId,
                                                                new CSCastExpression(csParmType, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false, delegateParams [i].Name,
                                                                                                                    csParmType.Typeof())));
                    preMarshalCode.Add(valDecl);
                    callParams.Add(valMarshalId);
                }
                else if (entityType == EntityType.Tuple)
                {
                    var csParmType = csParm.CSType as CSSimpleType;
                    if (csParmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 35, "Inconceivable! The tuple type for a parameter in a method was NOT a CSSimpleType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify(delegateParams [i].Name + "Temp", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    var valDecl = CSVariableDeclaration.VarLine(csParmType, valMarshalId,
                                                                new CSCastExpression(csParmType, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false, delegateParams [i].Name,
                                                                                                                    csParmType.Typeof())));
                    preMarshalCode.Add(valDecl);
                    callParams.Add(valMarshalId);
                }
                else if (entityType == EntityType.Closure)
                {
                    // parm is a SwiftClosureRepresentation
                    // (FuncType)StructMarshal.Marshaler.MakeDelegateFromBlindClosure (arg, argTypes, returnType);
                    var argTypesId = new CSIdentifier(MarshalEngine.Uniqueify("argTypes" + delegateParams [i], identifiersUsed));
                    identifiersUsed.Add(argTypesId.Name);
                    var parmType = csParm.CSType as CSSimpleType;
                    if (parmType == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 44, "Inconceivable! The type for a closure should be a CSSimpleType");
                    }
                    var hasReturn      = parmType.GenericTypeName == "Func";
                    var returnType     = hasReturn ? (CSBaseExpression)parmType.GenericTypes [parmType.GenericTypes.Length - 1].Typeof() : CSConstant.Null;
                    var argTypesLength = hasReturn ? parmType.GenericTypes.Length - 1 : parmType.GenericTypes.Length;
                    var argTypes       = new CSBaseExpression [argTypesLength];
                    for (int idx = 0; idx < argTypesLength; idx++)
                    {
                        argTypes [idx] = parmType.GenericTypes [idx].Typeof();
                    }
                    var typeArr = new CSArray1DInitialized(CSSimpleType.Type, argTypes);

                    var closureExpr = new CSFunctionCall("StructMarshal.Marshaler.MakeDelegateFromBlindClosure", false, delegateParams [i].Name,
                                                         typeArr, returnType);
                    var castTo = new CSCastExpression(csParm.CSType, closureExpr);
                    callParams.Add(castTo);
                }
                else if (entityType == EntityType.ProtocolList)
                {
                    preMarshalCode.Add(CSFunctionCall.FunctionCallLine("throw new NotImplementedException", false, CSConstant.Val($"Argument {csParm.Name} is a protocol list type and can't be marshaled from a virtual method.")));
                    callParams.Add(CSConstant.Null);
                    marshalingThrows = true;
                }
                else if (parmIsGeneric)
                {
                    // parm is an IntPtr to some T
                    // to get T, we ask funcDecl for the depthIndex of T
                    // T someVal = (T)StructMarshal.Marshaler.ToNet(parm, typeof(T));
                    // someVal gets passed in
                    var genRef = csParm.CSType as CSGenericReferenceType;
                    if (genRef == null)
                    {
                        throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 36, "Inconceivable! The generic type for a parameter in a method was NOT a CSGenericReferenceType!");
                    }
                    use.AddIfNotPresent(typeof(StructMarshal));
                    string valMarshalName = MarshalEngine.Uniqueify(delegateParams [i].Name + "Temp", identifiersUsed);
                    var    valMarshalId   = new CSIdentifier(valMarshalName);

                    var valDecl = CSVariableDeclaration.VarLine(genRef, valMarshalId,
                                                                new CSCastExpression(genRef, new CSFunctionCall("StructMarshal.Marshaler.ToNet", false,
                                                                                                                delegateParams [i].Name,
                                                                                                                genRef.Typeof())));
                    preMarshalCode.Add(valDecl);
                    callParams.Add(valMarshalId);
                }
                else
                {
                    if (csParm.ParameterKind == CSParameterKind.Out || csParm.ParameterKind == CSParameterKind.Ref)
                    {
                        callParams.Add(new CSIdentifier(String.Format("{0} {1}",
                                                                      csParm.ParameterKind == CSParameterKind.Out ? "out" : "ref", delegateParams [i].Name.Name)));
                    }
                    else
                    {
                        callParams.Add(delegateParams [i].Name);
                    }
                }
            }

            var body = new CSCodeBlock();

            if (isObjC)
            {
                use.AddIfNotPresent("ObjCRuntime");
            }
            else
            {
                use.AddIfNotPresent(typeof(SwiftObjectRegistry));
            }


            var    thisTypeName = hasAssociatedTypes ? csProxyName : thisType.ToString();
            string registryCall;

            if (thisIsInterface && !hasAssociatedTypes)
            {
                registryCall = $"SwiftObjectRegistry.Registry.InterfaceForExistentialContainer<{thisTypeName}> (self)";
            }
            else
            {
                registryCall = isObjC ? $"Runtime.GetNSObject<{thisTypeName}> (self)" : $"SwiftObjectRegistry.Registry.CSObjectForSwiftObject <{thisTypeName}> (self)";
            }


            var invoker = isIndexer ? (CSBaseExpression) new CSIndexExpression(registryCall, false, callParams.ToArray()) :
                          new CSFunctionCall($"{registryCall}.{methodName}", false, callParams.ToArray());

            var    tryBlock   = funcDecl.HasThrows ? new CSCodeBlock() : null;
            var    catchBlock = funcDecl.HasThrows ? new CSCodeBlock() : null;
            var    altBody    = tryBlock ?? body;
            string catchName  = MarshalEngine.Uniqueify("e", identifiersUsed);
            var    catchID    = new CSIdentifier(catchName);


            altBody.AddRange(preMarshalCode);
            if (marshalingThrows)
            {
                return(altBody);
            }

            if (funcDecl.HasThrows || needsReturn)               // function that returns or getter
            {
                if (funcDecl.HasThrows)
                {
                    use.AddIfNotPresent(typeof(SwiftError));
                    use.AddIfNotPresent(typeof(Tuple));
                    use.AddIfNotPresent(typeof(StructMarshal));
                    CSType returnTuple = null;
                    if (needsReturn)
                    {
                        returnTuple = new CSSimpleType("Tuple", false,
                                                       methodType,
                                                       new CSSimpleType(typeof(SwiftError)),
                                                       CSSimpleType.Bool);
                    }
                    else
                    {
                        returnTuple = new CSSimpleType("Tuple", false,
                                                       new CSSimpleType(typeof(SwiftError)),
                                                       CSSimpleType.Bool);
                    }


                    if (needsReturn)
                    {
                        string retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                        var    retvalId   = new CSIdentifier(retvalName);
                        altBody.Add(CSFieldDeclaration.VarLine(methodType, retvalId, invoker));
                        postMarshalCode.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.ToSwift", false,
                                                                            methodType.Typeof(),
                                                                            retvalId,
                                                                            delegateParams [0].Name));
                        altBody.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.SetErrorNotThrown", false,
                                                                    delegateParams [0].Name, returnTuple.Typeof()));
                    }
                    else
                    {
                        if (isSetter)
                        {
                            altBody.Add(CSAssignment.Assign(invoker, CSAssignmentOperator.Assign, valueExpr));
                        }
                        else
                        {
                            altBody.Add(new CSLine(invoker));
                        }
                        altBody.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.SetErrorNotThrown", false,
                                                                    delegateParams [0].Name, returnTuple.Typeof()));
                    }
                    string swiftError           = MarshalEngine.Uniqueify("err", identifiersUsed);
                    var    swiftErrorIdentifier = new CSIdentifier(swiftError);
                    catchBlock.Add(CSFieldDeclaration.VarLine(new CSSimpleType(typeof(SwiftError)), swiftErrorIdentifier,
                                                              new CSFunctionCall("SwiftError.FromException", false, catchID)));
                    catchBlock.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.SetErrorThrown", false,
                                                                   delegateParams [0].Name,
                                                                   swiftErrorIdentifier,
                                                                   returnTuple.Typeof()));
                }
                else
                {
                    if (returnIsClass)
                    {
                        string       retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                        CSIdentifier retvalId   = new CSIdentifier(retvalName);
                        altBody.Add(CSFieldDeclaration.VarLine(methodType, retvalId, invoker));
                        postMarshalCode.Add(CSReturn.ReturnLine(
                                                NewClassCompiler.SafeBackingFieldAccessor(retvalId, use, returnEntity.Type.ToFullyQualifiedName(), typeMapper)));
                    }
                    else if (returnIsProtocol)
                    {
                        string retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                        identifiersUsed.Add(retvalName);
                        var retvalId = new CSIdentifier(retvalName);
                        altBody.Add(CSFieldDeclaration.VarLine(methodType, retvalId, invoker));
                        var returnContainer = MarshalEngine.Uniqueify("returnContainer", identifiersUsed);
                        identifiersUsed.Add(returnContainer);
                        var returnContainerId = new CSIdentifier(returnContainer);
                        var protoGetter       = new CSFunctionCall($"SwiftObjectRegistry.Registry.ExistentialContainerForProtocols", false, retvalId, methodType.Typeof());
                        var protoDecl         = CSVariableDeclaration.VarLine(CSSimpleType.Var, returnContainerId, protoGetter);
                        var marshalBack       = CSFunctionCall.FunctionCallLine($"{returnContainer}.CopyTo", delegateParams [0].Name);
                        postMarshalCode.Add(protoDecl);
                        postMarshalCode.Add(marshalBack);
                    }
                    else if (returnIsStruct)
                    {
                        // non-blitable means that the parameter is an IntPtr and we can call the
                        // marshaler to copy into it
                        use.AddIfNotPresent(typeof(StructMarshal));
                        var marshalCall = CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.ToSwift", false,
                                                                          invoker, delegateParams [0].Name);
                        altBody.Add(marshalCall);
                    }
                    else if (returnIsTuple)
                    {
                        // non-blitable means that the parameter is an IntPtr and we can call the
                        // marshaler to copy into it
                        use.AddIfNotPresent(typeof(StructMarshal));
                        var marshalCall = CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.ToSwift", false,
                                                                          invoker, delegateParams [0].Name);
                        altBody.Add(marshalCall);
                    }
                    else if (returnIsGeneric)
                    {
                        // T retval = invoker();
                        // if (retval is ISwiftObject) {
                        //     Marshal.WriteIntPtr(delegateParams [0].Name, ((ISwiftObject)retval).SwiftObject);
                        // }
                        // else {
                        //    StructMarshal.Marshaler.ToSwift(typeof(T), retval, delegateParams[0].Name);
                        // }
                        string retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                        var    retvalId   = new CSIdentifier(retvalName);
                        altBody.Add(CSFieldDeclaration.VarLine(methodType, retvalId, invoker));
                        var ifClause = new CSCodeBlock();
                        ifClause.Add(CSFunctionCall.FunctionCallLine("Marshal.WriteIntPtr", false,
                                                                     delegateParams [0].Name,
                                                                     new CSParenthesisExpression(new CSCastExpression("ISwiftObject", retvalId)).Dot(NewClassCompiler.kSwiftObjectGetter)));
                        var elseClause = new CSCodeBlock();
                        elseClause.Add(CSFunctionCall.FunctionCallLine("StructMarshal.Marshaler.ToSwift", false,
                                                                       methodType.Typeof(),
                                                                       retvalId,
                                                                       delegateParams [0].Name));
                        CSBaseExpression ifExpr = new CSSimpleType("ISwiftObject").Typeof().Dot(new CSFunctionCall("IsAssignableFrom", false,
                                                                                                                   methodType.Typeof()));

                        var retTest = new CSIfElse(ifExpr, ifClause, elseClause);
                        altBody.Add(retTest);
                    }
                    else
                    {
                        if (returnIsClosure)
                        {
                            invoker = MarshalEngine.BuildBlindClosureCall(invoker, methodType as CSSimpleType, use);
                        }
                        if (postMarshalCode.Count > 0)
                        {
                            string       retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                            CSIdentifier retvalId   = new CSIdentifier(retvalName);
                            altBody.Add(CSFieldDeclaration.VarLine(methodType, retvalId, invoker));
                            postMarshalCode.Add(CSReturn.ReturnLine(retvalId));
                        }
                        else
                        {
                            altBody.Add(CSReturn.ReturnLine(invoker));
                        }
                    }
                }
            }
            else                 // no return or setter
            {
                if (isSetter)
                {
                    altBody.Add(CSAssignment.Assign(invoker, CSAssignmentOperator.Assign, valueExpr));
                }
                else
                {
                    altBody.Add(new CSLine(invoker));
                }
            }
            altBody.AddRange(postMarshalCode);

            if (funcDecl.HasThrows)
            {
                body.Add(new CSTryCatch(tryBlock, new CSCatch(typeof(Exception), catchName, catchBlock)));
            }
            return(body);
        }
Ejemplo n.º 27
0
        //private void ChangeLinksForAllMediaDetails(string oldAbsoluteUrl, string newAbsoluteUrl)
        //{
        //    if (string.IsNullOrEmpty(oldAbsoluteUrl) || oldAbsoluteUrl == newAbsoluteUrl)
        //        return;

        //    var oldTemplateVarUrl = ParserHelper.ParseData(oldAbsoluteUrl, this.TemplateVars, true);
        //    var newTemplateVarUrl = ParserHelper.ParseData(newAbsoluteUrl, this.TemplateVars, true);

        //    var foundItems = MediaDetailsMapper.GetDataModel().MediaDetails.Where(i => i.MainContent.Contains(oldTemplateVarUrl) || i.ShortDescription.Contains(oldTemplateVarUrl));

        //    if (foundItems.Any())
        //    {
        //        foreach (var item in foundItems)
        //        {
        //            item.ShortDescription = item.ShortDescription.Replace(oldTemplateVarUrl, newTemplateVarUrl);
        //            item.MainContent = item.MainContent.Replace(oldTemplateVarUrl, newTemplateVarUrl);
        //        }

        //        var numberOfItemsEffected = MediaDetailsMapper.GetDataModel().SaveChanges();
        //    }
        //}

        protected void Save_OnClick(object sender, EventArgs e)
        {
            if (CanAccessItem != null && CanAccessItem.IsError)
            {
                DisplayErrorMessage("Error saving item", CanAccessItem.Error);
                return;
            }

            if (!CurrentUser.HasPermission(PermissionsEnum.Publish))
            {
                DisplayErrorMessage("Error saving item", ErrorHelper.CreateError(new Exception("You do not have the appropriate permissions to save items")));
                return;
            }

            string commandArgument = ((LinkButton)sender).CommandArgument;

            bool isDraft = false;

            if (commandArgument == "CreateDraft")
            {
                isDraft = true;
            }

            IMediaDetail history = CreateHistory(isDraft);

            Return returnObj = BaseMapper.GenerateReturn();

            if ((history != null) && (history.IsDraft))
            {
                history.CopyFrom(selectedItem);
                UpdateObjectFromFields(history);
                history.IsDraft = isDraft;

                returnObj = SaveHistory(history);

                if (returnObj.IsError)
                {
                    DisplayErrorMessage("Error Saving Item", returnObj.Error);
                }
                else
                {
                    DisplaySuccessMessage("Successfully Saved Item as Draft");

                    UpdateFieldsFromObject();
                }

                RedirectToAdminUrl(selectedItem, history.HistoryVersionNumber);

                return;
            }

            var tmpSelectedItem = BaseMapper.GetObjectFromContext((MediaDetail)selectedItem);

            if (tmpSelectedItem != null)
            {
                selectedItem = tmpSelectedItem;
            }

            if (parentMediaItem != null)
            {
                parentMediaItem = BaseMapper.GetObjectFromContext(parentMediaItem);
            }
            else
            {
                parentMediaItem = selectedItem?.Media?.ParentMedia;
            }

            if (selectedItem == null)
            {
                selectedItem = MediaDetailsMapper.CreateObject(mediaTypeId, selectedMediaItem, parentMediaItem);
            }

            var oldLinkTitle       = selectedItem.LinkTitle;
            var oldVirtualPath     = selectedItem.VirtualPath;
            var canRender          = selectedItem.CanRender;
            var oldAbsoluteUrl     = selectedItem.AbsoluteUrl;
            var oldPostPublishDate = selectedItem.PublishDate;

            UpdateObjectFromFields(selectedItem);

            var validate = selectedItem.Validate();

            if (validate.IsError)
            {
                DisplayErrorMessage("Error saving item", validate.Error);
                return;
            }

            if ((oldPostPublishDate != selectedItem.PublishDate) && !CurrentUser.HasPermission(PermissionsEnum.Publish))
            {
                DisplayErrorMessage("Error saving item", ErrorHelper.CreateError(new Exception("You do not have the appropriate permissions to publish items")));
                return;
            }

            if (selectedItem.ID == 0)
            {
                selectedItem.CreatedByUserID = CurrentUser.ID;

                if ((parentMediaItem != null) && (selectedItem.Media.ID == 0))
                {
                    selectedItem.Media.OrderIndex = parentMediaItem.ChildMedias.Count(i => i.ID != 0);
                }


                returnObj = MediaDetailsMapper.Insert(selectedItem);

                if (!returnObj.IsError)
                {
                    ContextHelper.Clear(ContextType.Cache);
                    FileCacheHelper.ClearAllCache();
                }
                else
                {
                    DisplayErrorMessage("Error", returnObj.Error);
                }
            }
            else
            {
                if (!isDraft)
                {
                    if (history != null)
                    {
                        returnObj = SaveHistory(history);
                    }

                    //selectedItem.Media.ReorderChildren();

                    if (!returnObj.IsError)
                    {
                        returnObj = MediaDetailsMapper.Update(selectedItem);
                    }
                }
            }

            if (returnObj.IsError)
            {
                DisplayErrorMessage("Error Saving Item", returnObj.Error);
            }
            else
            {
                if (history != null)
                {
                    selectedItem.History.Add((MediaDetail)history);
                    Return historyReturnObj = MediaDetailsMapper.Update(selectedItem);
                }

                selectedItem.RemoveFromCache();
                FileCacheHelper.DeleteGenerateNavCache();

                if (oldVirtualPath != selectedItem.VirtualPath || canRender != selectedItem.CanRender || oldLinkTitle != selectedItem.LinkTitle)
                {
                    ContextHelper.Clear(ContextType.Cache);
                    //FileCacheHelper.ClearCacheDir("generatenav");

                    //FileCacheHelper.ClearAllCache();

                    selectedItem.ClearAutoCalculatedVirtualPathCache();

                    if (commandArgument == "SaveAndPublish")
                    {
                        PublishNow_OnClick(sender, e);
                        //RedirectToMediaDetail(mediaTypeEnum, selectedItem.MediaID, selectedItem.Media.ParentMediaID);
                    }
                    else
                    {
                        RedirectToAdminUrl(selectedItem.MediaTypeID, selectedItem.MediaID, selectedItem.Media.ParentMediaID);
                    }

                    //ChangeLinksForAllMediaDetails(oldAbsoluteUrl, selectedItem.AbsoluteUrl);
                }

                DisplaySuccessMessage("Successfully Saved Item");

                ExecuteRawJS("ReloadPreviewPanel()");

                if (!selectedItem.IsHistory)
                {
                    SelectedMediaDetail = selectedItem;
                    SelectedMedia       = MediasMapper.GetByID(selectedItem.MediaID);
                }

                if (((Request["selectedMediaId"] == null) || (Request["selectedMediaId"].ToString() == "0")) && (commandArgument != "SaveAndPublish"))
                {
                    RedirectToAdminUrl(selectedItem.MediaTypeID, selectedItem.MediaID, selectedItem.Media.ParentMediaID);
                }
                else
                {
                    if (commandArgument == "SaveAndPublish")
                    {
                        PublishNow_OnClick(sender, e);
                        //RedirectToMediaDetail(mediaTypeEnum, selectedItem.MediaID, selectedItem.Media.ParentMediaID);
                    }

                    UpdateFieldsFromObject();

                    /*else
                     *  Response.Redirect(Request.Url.AbsoluteUri);*/

                    //UpdateFieldsFromObject();
                    //RedirectToMediaDetail(mediaTypeEnum, selectedItem.MediaID, selectedItem.Media.ParentMediaID);
                }
            }
        }
        TypeSpec Parse()
        {
            TypeSpecToken            token = tokenizer.Peek();
            TypeSpec                 type  = null;
            List <TypeSpecAttribute> attrs = null;
            var    inout     = false;
            string typeLabel = null;

            // Prefix

            // parse any attributes
            if (token.Kind == TypeTokenKind.At)
            {
                attrs = ParseAttributes();
                token = tokenizer.Peek();
            }

            // looks like it's inout
            if (token.Kind == TypeTokenKind.TypeName && token.Value == "inout")
            {
                inout = true;
                tokenizer.Next();
                token = tokenizer.Peek();
            }

            if (token.Kind == TypeTokenKind.TypeLabel)
            {
                typeLabel = token.Value;
                tokenizer.Next();
                token = tokenizer.Peek();
            }


            // meat


            if (token.Kind == TypeTokenKind.LeftParenthesis)               // tuple
            {
                tokenizer.Next();
                TupleTypeSpec tuple = ParseTuple();
                type      = tuple.Elements.Count == 1 ? tuple.Elements [0] : tuple;
                typeLabel = type.TypeLabel;
            }
            else if (token.Kind == TypeTokenKind.TypeName)                 // name
            {
                tokenizer.Next();
                var tokenValue = token.Value.StartsWith("ObjectiveC.", StringComparison.Ordinal) ?
                                 "Foundation" + token.Value.Substring("ObjectiveC".Length) : token.Value;
                type = new NamedTypeSpec(tokenValue);
            }
            else if (token.Kind == TypeTokenKind.LeftBracket)                 // array
            {
                tokenizer.Next();
                type = ParseArray();
            }
            else                 // illegal
            {
                throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 0, $"Unexpected token {token.Value}.");
            }

            // look-ahead for closure
            if (tokenizer.Peek().Kind == TypeTokenKind.TypeName && tokenizer.Peek().Value == "throws")
            {
                tokenizer.Next();
                if (tokenizer.Peek().Kind != TypeTokenKind.Arrow)
                {
                    throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 1, $"Unexpected token {tokenizer.Peek ().Value} after a 'throws' in a closure.");
                }
                tokenizer.Next();
                type = ParseClosure(type, true);
            }

            if (tokenizer.Peek().Kind == TypeTokenKind.Arrow)
            {
                tokenizer.Next();
                type = ParseClosure(type, false);
            }
            else if (tokenizer.Peek().Kind == TypeTokenKind.LeftAngle)
            {
                tokenizer.Next();
                type = Genericize(type);
            }

            if (tokenizer.Peek().Kind == TypeTokenKind.Period)
            {
                tokenizer.Next();
                var currType = type as NamedTypeSpec;
                if (currType == null)
                {
                    throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 2, $"In parsing an inner type (type.type), first element is a {type.Kind} instead of a NamedTypeSpec.");
                }
                var nextType = Parse() as NamedTypeSpec;
                if (nextType == null)
                {
                    throw ErrorHelper.CreateError(ReflectorError.kTypeParseBase + 3, $"In parsing an inner type (type.type), the second element is a {nextType.Kind} instead of a NamedTypeSpec");
                }
                currType.InnerType = nextType;
            }

            // Postfix

            if (tokenizer.Peek().Kind == TypeTokenKind.Ampersand)
            {
                type = ParseProtocolList(type as NamedTypeSpec);
            }

            while (tokenizer.Peek().Kind == TypeTokenKind.QuestionMark)
            {
                tokenizer.Next();
                type = WrapAsBoundGeneric(type, "Swift.Optional");
            }

            if (tokenizer.Peek().Kind == TypeTokenKind.ExclamationPoint)
            {
                tokenizer.Next();
                type = WrapAsBoundGeneric(type, "Swift.ImplicitlyUnwrappedOptional");
            }

            type.IsInOut   = inout;
            type.TypeLabel = typeLabel;

            if (type != null && attrs != null)
            {
                type.Attributes.AddRange(attrs);
            }

            return(type);
        }
Ejemplo n.º 29
0
    protected void cmdOK_Click(object sender, EventArgs e)
    {
        ClearErrors();
        try
        {
            if (!ValidateUIRequirements())
            {
                return;
            }
            MoveArguments arguments = new MoveArguments
            {
                SourceContact        = Contact,
                SourceAccount        = Contact.Account,
                TargetAccount        = (IAccount)lueTargetAccount.LookupResultValue,
                UseSourceContactInfo = chkUseSourceAddressPhn.Checked
            };
            //Add the move/reassign options for each of the items
            //Activity Options
            MoveItemOption moveOption = rdbMoveActivity.Checked
                                            ? new MoveItemOption {
                Entity = "Activity", MoveToAccount = true, ReassignTo = arguments.TargetAccount.Id
            }
                                            : new MoveItemOption {
                Entity = "Activity", ReassignTo = (lueReassignActivity.LookupResultValue as IContact).Id, MoveToAccount = false
            };
            arguments.Items.Add(moveOption);

            //History/Notes Options
            moveOption = rdbMoveHistory.Checked
                             ? new MoveItemOption {
                Entity = "History", MoveToAccount = true, ReassignTo = arguments.TargetAccount.Id
            }
                             : new MoveItemOption {
                Entity = "History", ReassignTo = (lueReassignNotesHistory.LookupResultValue as IContact).Id, MoveToAccount = false
            };
            arguments.Items.Add(moveOption);

            object openItemsReassignContact        = lueReassignOpenItems.LookupResultValue != null ? (lueReassignOpenItems.LookupResultValue as IContact).Id : null;
            object closedItemsReassignContact      = lueReassignClosedItems.LookupResultValue != null ? (lueReassignClosedItems.LookupResultValue as IContact).Id : null;
            object openSupportItemsReassignContact = lueReassignSupportItems.LookupResultValue != null
                                                         ? (lueReassignSupportItems.LookupResultValue as IContact).Id
                                                         : null;
            //Attachment Options
            moveOption = new MoveItemOption
            {
                Entity        = "Attachment",
                ReassignTo    = openItemsReassignContact,
                MoveToAccount = false
            };
            arguments.Items.Add(moveOption);

            //Literature Requests Options
            moveOption = new MoveItemOption
            {
                Entity           = "LitRequest",
                OpenItemsOnly    = true,
                ClosedItemsOnly  = true,
                ReassignTo       = openItemsReassignContact,
                ReassignToClosed = closedItemsReassignContact,
                MoveToAccount    = false
            };
            arguments.Items.Add(moveOption);

            //Opportunity Options
            moveOption = new MoveItemOption
            {
                Entity           = "OpportunityContact",
                OpenItemsOnly    = true,
                ClosedItemsOnly  = true,
                ReassignTo       = openItemsReassignContact,
                ReassignToClosed = closedItemsReassignContact,
                MoveToAccount    = false
            };
            arguments.Items.Add(moveOption);

            //Sales Order Options
            moveOption = new MoveItemOption
            {
                Entity        = "SalesOrder",
                OpenItemsOnly = true,
                ReassignTo    = openItemsReassignContact,
                MoveToAccount = false
            };
            arguments.Items.Add(moveOption);

            //Ticket Options
            moveOption = new MoveItemOption
            {
                Entity        = "Ticket",
                ReassignTo    = openSupportItemsReassignContact,
                OpenItemsOnly = true,
                MoveToAccount = false
            };
            arguments.Items.Add(moveOption);
            //Return Options
            moveOption = new MoveItemOption
            {
                Entity        = "Return",
                ReassignTo    = openSupportItemsReassignContact,
                OpenItemsOnly = true,
                MoveToAccount = false
            };
            arguments.Items.Add(moveOption);
            //Contract Options
            moveOption = new MoveItemOption
            {
                Entity        = "Contract",
                ReassignTo    = openSupportItemsReassignContact,
                OpenItemsOnly = true,
                MoveToAccount = false
            };
            arguments.Items.Add(moveOption);

            Contact.MoveContact(arguments);

            // redirect back to page so new info can be displayed
            if (Contact.Id != null)
            {
                Response.Redirect(string.Format("Contact.aspx?entityId={0}", (Contact.Id)), false);
            }
        }
        catch (Exception ex)
        {
            string sSlxErrorId = null;
            var    sMsg        = ErrorHelper.GetClientErrorHtmlMessage(ex, ref sSlxErrorId);
            if (!string.IsNullOrEmpty(sSlxErrorId))
            {
                log.Error(ErrorHelper.AppendSlxErrorId("The call to SmartParts_Contact_MoveContact.cmdOK_Click failed", sSlxErrorId),
                          ex);
            }
            DialogService.ShowHtmlMessage(sMsg, ErrorHelper.IsDevelopmentContext() ? 600 : -1,
                                          ErrorHelper.IsDevelopmentContext() ? 800 : -1);
        }
    }
Ejemplo n.º 30
0
        // Called from CoreHttpMessageHandler
        internal static TypeDefinition GetHttpMessageHandler(RuntimeOptions options, ModuleDefinition httpModule, ModuleDefinition platformModule = null)
        {
            string handler;

            if (options != null)
            {
                handler = options.http_message_handler;
            }
            else if (Driver.App.Platform == Utils.ApplePlatform.WatchOS)
            {
                handler = NSUrlSessionHandlerValue;
            }
            else
            {
                handler = HttpClientHandlerValue;
            }
            TypeDefinition type;

            switch (handler)
            {
#if MONOMAC
            case HttpClientHandlerValue:
                type = httpModule.GetType("System.Net.Http", "HttpClientHandler");
                break;

            case CFNetworkHandlerValue:
                type = platformModule.GetType("System.Net.Http", "CFNetworkHandler");
                break;

            case NSUrlSessionHandlerValue:
                type = platformModule.GetType("Foundation", "NSUrlSessionHandler");
                break;
#else
            case HttpClientHandlerValue:
                if (Driver.App.Platform == Utils.ApplePlatform.WatchOS)
                {
                    ErrorHelper.Warning(2015, "Invalid HttpMessageHandler `{0}` for watchOS. The only valid value is NSUrlSessionHandler.", handler);
                    type = httpModule.GetType("System.Net.Http", "NSUrlSessionHandler");
                }
                else
                {
                    type = httpModule.GetType("System.Net.Http", "HttpClientHandler");
                }
                break;

            case CFNetworkHandlerValue:
                if (Driver.App.Platform == Utils.ApplePlatform.WatchOS)
                {
                    ErrorHelper.Warning(2015, "Invalid HttpMessageHandler `{0}` for watchOS. The only valid value is NSUrlSessionHandler.", handler);
                    type = httpModule.GetType("System.Net.Http", "NSUrlSessionHandler");
                }
                else
                {
                    type = httpModule.GetType("System.Net.Http", "CFNetworkHandler");
                }
                break;

            case NSUrlSessionHandlerValue:
                type = httpModule.GetType("System.Net.Http", "NSUrlSessionHandler");
                break;
#endif
            default:
                throw new InvalidOperationException(string.Format("Unknown HttpMessageHandler `{0}`.", handler));
            }
            if (type == null)
            {
                throw new InvalidOperationException(string.Format("Cannot load HttpMessageHandler `{0}`.", handler));
            }
            return(type);
        }
Ejemplo n.º 31
0
 private void WriteNpmException(object sender, NpmExceptionEventArgs e)
 {
     this.outputPane.WriteLine(ErrorHelper.GetExceptionDetailsText(e.Exception));
 }