public async override Task ExecuteCommand()
        {
            CalculateEffectivePackageSaveMode();
            string installPath = ResolveInstallPath();

            var packageSourceProvider = new NuGet.Configuration.PackageSourceProvider(Settings);
            var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, ResourceProviders);

            IEnumerable<SourceRepository> primarySources;
            IEnumerable<SourceRepository> secondarySources;
            GetEffectiveSources(sourceRepositoryProvider, out primarySources, out secondarySources);

            if(Arguments.Count == 0)
            {
                throw new InvalidOperationException(NuGetResources.InstallCommandPackageIdMustBeProvided);
            }
            string packageId = Arguments[0];
            NuGetPackageManager packageManager = new NuGetPackageManager(sourceRepositoryProvider, installPath);
            ResolutionContext resolutionContext = new ResolutionContext(dependencyBehavior: DependencyBehavior, includePrelease: Prerelease);
            FolderNuGetProject nugetProject = new FolderNuGetProject(installPath);
            nugetProject.PackageSaveMode = EffectivePackageSaveMode;

            if (Version == null)
            {
                await packageManager.InstallPackageAsync(nugetProject, packageId, resolutionContext, new Common.Console(),
                    primarySources, secondarySources, CancellationToken.None);
            }
            else
            {
                await packageManager.InstallPackageAsync(nugetProject, new PackageIdentity(packageId, new NuGetVersion(Version)), resolutionContext,
                    new Common.Console(), primarySources, secondarySources, CancellationToken.None);
            }           
        }
Example #2
0
        public object Map(ResolutionContext context, IMappingEngineRunner mapper)
        {
            if (IsDataReader(context))
            {
                var dataReader = (IDataReader)context.SourceValue;

                var destinationElementType = TypeHelper.GetElementType(context.DestinationType);
                var buildFrom = CreateBuilder(destinationElementType, dataReader);

                var results = ObjectCreator.CreateList(destinationElementType);
                while (dataReader.Read())
                {
                    results.Add(buildFrom(dataReader));
                }

                return results;
            }

            if (IsDataRecord(context))
            {
                var dataRecord = context.SourceValue as IDataRecord;
                var buildFrom = CreateBuilder(context.DestinationType, dataRecord);

                var result = buildFrom(dataRecord);
                MapPropertyValues(context, mapper, result);

                return result;
            }

            return null;
        }
Example #3
0
        public static AbstractType Demangle(string mangledString, ResolutionContext ctxt, out ITypeDeclaration qualifier, out bool isCFunction)
        {
            if(string.IsNullOrEmpty(mangledString))
                throw new ArgumentException("input string must not be null or empty!");

            if (!mangledString.StartsWith("_D"))
            {
                isCFunction = true;

                if (mangledString.StartsWith ("__D"))
                    mangledString = mangledString.Substring (1);
                // C Functions
                else if (mangledString.StartsWith ("_")) {
                    qualifier = new IdentifierDeclaration (mangledString.Substring (1));
                    return null;
                }
            }

            //TODO: What about C functions that start with 'D'?
            isCFunction = false;

            var dmng = new Demangler(mangledString) { ctxt = ctxt };

            return dmng.MangledName(out qualifier);
        }
        public static Dictionary<int, Dictionary<ISyntaxRegion, byte>> Scan(DModule ast, ResolutionContext ctxt)
        {
            if (ast == null)
                return new Dictionary<int, Dictionary<ISyntaxRegion,byte>>();

            var typeRefFinder = new TypeReferenceFinder(ctxt);

            ContextFrame backupFrame = null;

            if(ctxt.ScopedBlock == ast)
                backupFrame = ctxt.Pop ();
            /*
            if (ctxt.CurrentContext == null)
            {
                ctxt.Push(backupFrame);
                backupFrame = null;
            }*/

            //typeRefFinder.ast = ast;
            // Enum all identifiers
            ast.Accept (typeRefFinder);

            if (backupFrame != null)
                ctxt.Push (backupFrame);

            // Crawl through all remaining expressions by evaluating their types and check if they're actual type references.
            /*typeRefFinder.queueCount = typeRefFinder.q.Count;
            typeRefFinder.ResolveAllIdentifiers();
            */
            return typeRefFinder.Matches;
        }
        public static void EnumChildren(ICompletionDataGenerator cdgen,ResolutionContext ctxt, IBlockNode block, bool isVarInstance,
			MemberFilter vis = MemberFilter.Methods | MemberFilter.Types | MemberFilter.Variables | MemberFilter.Enums, bool publicImports = false)
        {
            var scan = new MemberCompletionEnumeration(ctxt, cdgen) { isVarInst = isVarInstance };

            scan.ScanBlock(block, CodeLocation.Empty, vis, publicImports);
        }
        public static void EnumChildren(ICompletionDataGenerator cdgen,ResolutionContext ctxt, UserDefinedType udt, bool isVarInstance, 
			MemberFilter vis = MemberFilter.Methods | MemberFilter.Types | MemberFilter.Variables | MemberFilter.Enums)
        {
            var scan = new MemberCompletionEnumeration(ctxt, cdgen) { isVarInst = isVarInstance };

            scan.DeepScanClass(udt, vis);
        }
 private ResolutionResult(object value, ResolutionContext context)
 {
     Value = value;
     Context = context;
     Type = ResolveType(value, typeof (object));
     MemberType = Type;
 }
 public bool IsMatch(ResolutionContext context)
 {
     return context.DestinationType.IsAssignableFrom(context.SourceType)
            && context.DestinationType.IsArray
            && context.SourceType.IsArray
            && !ElementsExplicitlyMapped(context);
 }
Example #9
0
 private static bool EnumToEnumMapping(ResolutionContext context)
 {
     // Enum to enum mapping
     var sourceEnumType = TypeHelper.GetEnumerationType(context.SourceType);
     var destEnumType = TypeHelper.GetEnumerationType(context.DestinationType);
     return sourceEnumType != null && destEnumType != null;
 }
 private ResolutionResult(object value, ResolutionContext context, Type memberType)
 {
     Value = value;
     Context = context;
     Type = ResolveType(value, memberType);
     MemberType = memberType;
 }
 public bool IsMatch(ResolutionContext context)
 {
     return IsPrimitiveArrayType(context.DestinationType) &&
            IsPrimitiveArrayType(context.SourceType) &&
            (TypeHelper.GetElementType(context.DestinationType)
                .Equals(TypeHelper.GetElementType(context.SourceType)));
 }
            public object Convert(Type enumSourceType, Type enumDestinationType, ResolutionContext context)
            {
                Type underlyingSourceType = Enum.GetUnderlyingType(enumSourceType);
                var underlyingSourceValue = System.Convert.ChangeType(context.SourceValue, underlyingSourceType);

                return Enum.ToObject(context.DestinationType, underlyingSourceValue);
            }
Example #13
0
        public ContextFrame(ResolutionContext ctxt, IBlockNode b, IStatement stmt = null)
        {
            this.ctxt = ctxt;
            declarationCondititons = new ConditionalCompilation.ConditionSet(ctxt.CompilationEnvironment);

            Set(b,stmt);
        }
Example #14
0
 UFCSResolver(ResolutionContext ctxt, ISemantic firstArg, int nameHash = 0, ISyntaxRegion sr = null)
     : base(ctxt)
 {
     this.firstArgument = firstArg;
     this.nameFilterHash = nameHash;
     this.sr = sr;
 }
        public bool IsMatch(ResolutionContext context)
        {
            if (context == null) throw new ArgumentNullException("context");

            TypeConverter typeConverter = GetTypeConverter(context);
            return typeConverter.CanConvertTo(context.DestinationType);
        }
Example #16
0
        /// <summary>
        /// </summary>
        /// <param name="ast">The syntax tree to scan</param>
        /// <param name="symbol">Might not be a child symbol of ast</param>
        /// <param name="ctxt">The context required to search for symbols</param>
        /// <returns></returns>
        public static IEnumerable<ISyntaxRegion> Scan(DModule ast, INode symbol, ResolutionContext ctxt, bool includeDefinition = true)
        {
            if (ast == null || symbol == null || ctxt == null)
                return null;

            var f = new ReferencesFinder(symbol, ast, ctxt);

            using(ctxt.Push(ast))
                ast.Accept (f);

            var nodeRoot = symbol.NodeRoot as DModule;
            if (includeDefinition && nodeRoot != null && nodeRoot.FileName == ast.FileName)
            {
                var dc = symbol.Parent as DClassLike;
                if (dc != null && dc.ClassType == D_Parser.Parser.DTokens.Template &&
                    dc.NameHash == symbol.NameHash)
                {
                    f.l.Insert(0, new IdentifierDeclaration(dc.NameHash)
                        {
                            Location = dc.NameLocation,
                            EndLocation = new CodeLocation(dc.NameLocation.Column + dc.Name.Length, dc.NameLocation.Line)
                        });
                }

                f.l.Insert(0, new IdentifierDeclaration(symbol.NameHash)
                    {
                        Location = symbol.NameLocation,
                        EndLocation = new CodeLocation(symbol.NameLocation.Column + symbol.Name.Length,	symbol.NameLocation.Line)
                    });
            }

            return f.l;
        }
Example #17
0
        public object ResolveValue(ResolutionContext context, IMappingEngineRunner mappingEngine)
        {
            var ctorArgs = new List<object>();

            foreach (var map in CtorParams)
            {
                var result = map.ResolveValue(context);

                var sourceType = result.Type;
                var destinationType = map.Parameter.ParameterType;

                var typeMap = mappingEngine.ConfigurationProvider.ResolveTypeMap(result, destinationType);

                Type targetSourceType = typeMap != null ? typeMap.SourceType : sourceType;

                var newContext = context.CreateTypeContext(typeMap, result.Value, null, targetSourceType,
                    destinationType);

                if (typeMap == null && map.Parameter.IsOptional)
                {
                    object value = map.Parameter.DefaultValue;
                    ctorArgs.Add(value);
                }
                else
                {
                    var value = mappingEngine.Map(newContext);
                    ctorArgs.Add(value);
                }
            }

            return _runtimeCtor.Value(ctorArgs.ToArray());
        }
		/// <summary>
		/// http://dlang.org/operatoroverloading.html#Dispatch
		/// Check for the existence of an opDispatch overload.
		/// Important: Because static opDispatches are allowed as well, do check whether we can access non-static overloads from non-instance expressions or such
		/// </summary>
		public static IEnumerable<AbstractType> TryResolveFurtherIdViaOpDispatch (ResolutionContext ctxt, int nextIdentifierHash, UserDefinedType b, ISyntaxRegion typeBase = null)
		{
			// The usual SO prevention
			if (nextIdentifierHash == opDispatchId || b == null)
				yield break;

			AbstractType[] overloads;

			var opt = ctxt.CurrentContext.ContextDependentOptions;
			// Look for opDispatch-Members inside b's Definition
			using (ctxt.Push(b))
			{
				ctxt.CurrentContext.ContextDependentOptions = opt; // Mainly required for not resolving opDispatch's return type, as this will be performed later on in higher levels
				overloads = TypeDeclarationResolver.ResolveFurtherTypeIdentifier(opDispatchId, b, ctxt, typeBase, false);
			}

			if (overloads == null || overloads.Length < 0)
				yield break;

			var av = new ArrayValue (Evaluation.GetStringType(ctxt), Strings.TryGet(nextIdentifierHash));

			foreach (DSymbol o in overloads) {
				var dn = o.Definition;
				if (dn.TemplateParameters != null && dn.TemplateParameters.Length > 0 && 
					dn.TemplateParameters[0] is TemplateValueParameter)
				{
					//TODO: Test parameter types for being a string value
					o.SetDeducedTypes(new[]{ new TemplateParameterSymbol(dn.TemplateParameters[0], av) });
					yield return o;
				}
			}
		}
        /// <summary>
        /// Activates an instance with given arguments.
        /// </summary>
        /// <param name="resolutionContext">The container.</param>
        /// <returns>The activated instance.</returns>
        public object ActivateInstance(ResolutionContext resolutionContext)
        {
            var runtimeArguments = resolutionContext.RuntimeArguments;

            if (this._container == null)
            {
                this._container = resolutionContext.Container;
            }

            int countOfRuntimeArguments = runtimeArguments.CountOfAllArguments;

            if (this._cachedConstructor == null || countOfRuntimeArguments > 0)
            {
                var constructors = _implementationType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                _cachedConstructor = this._constructorSelector.SelectConstructor(constructors, resolutionContext);
            }

            if (this._cachedArguments == null || countOfRuntimeArguments > 0 || GetAnyDependencyParameter(resolutionContext))
            {
                this._cachedArguments = this._argumentCollector.CollectArguments(
                        this._container.Resolve,
                        this._cachedConstructor.GetParameters(),
                        resolutionContext);
            }

            if (this._cachedArguments.Length != this._cachedConstructor.GetParameters().Length)
            {
                throw new ResolutionFailedException(
                    Resources.NoSuitableConstructorFoundFormat.FormatWith(_implementationType));
            }

            return this._cachedConstructor.Invoke(this._cachedArguments);
        }
        /// <summary>
        /// Activates an instance with given arguments.
        /// </summary>
        /// <param name="resolutionContext">The container.</param>
        /// <returns>The activated instance.</returns>
        public object ActivateInstance(ResolutionContext resolutionContext)
        {
            if (this._container == null)
            {
                this._container = resolutionContext.Container;
            }

            var constructors = _implementationType.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
            var finalConstructor = this._constructorSelector.SelectConstructor(constructors, resolutionContext);

            object[] finalArguments = this._argumentCollector.CollectArguments(
                this._container.Resolve,
                finalConstructor.GetParameters(),
                resolutionContext);

            if (finalArguments != null && finalArguments.Length != finalConstructor.GetParameters().Length)
            {
                throw new ResolutionFailedException
                    (Resources.NoSuitableConstructorFoundFormat.FormatWith(_implementationType),
                     this._implementationType);

            }

            return finalConstructor.Invoke(finalArguments);
        }
 public bool IsMatch(ResolutionContext context)
 {
     return typeof (LambdaExpression).IsAssignableFrom(context.SourceType)
            && context.SourceType != typeof (LambdaExpression)
            && typeof (LambdaExpression).IsAssignableFrom(context.DestinationType)
            && context.DestinationType != typeof (LambdaExpression);
 }
        public object Map(ResolutionContext context, IMappingEngineRunner mapper)
        {
            var sourceDelegateType = context.SourceType.GetGenericArguments()[0];
            var destDelegateType = context.DestinationType.GetGenericArguments()[0];
            var expression = (LambdaExpression) context.SourceValue;

            if (sourceDelegateType.GetGenericTypeDefinition() != destDelegateType.GetGenericTypeDefinition())
                throw new AutoMapperMappingException("Source and destination expressions must be of the same type.");

            var parameters = expression.Parameters.ToArray();
            var body = expression.Body;

            for (int i = 0; i < expression.Parameters.Count; i++)
            {
                var sourceParamType = sourceDelegateType.GetGenericArguments()[i];
                var destParamType = destDelegateType.GetGenericArguments()[i];

                if (sourceParamType == destParamType)
                    continue;

                var typeMap = mapper.ConfigurationProvider.ResolveTypeMap(destParamType, sourceParamType);

                if (typeMap == null)
                    throw new AutoMapperMappingException(
                        $"Could not find type map from destination type {destParamType} to source type {sourceParamType}. Use CreateMap to create a map from the source to destination types.");

                var oldParam = expression.Parameters[i];
                var newParam = Expression.Parameter(typeMap.SourceType, oldParam.Name);
                parameters[i] = newParam;
                var visitor = new MappingVisitor(typeMap, oldParam, newParam);
                body = visitor.Visit(body);
            }
            return Expression.Lambda(body, parameters);
        }
		public static ArrayType GetStringType(ResolutionContext ctxt, LiteralSubformat fmt = LiteralSubformat.Utf8)
		{
			ArrayType _t = null;

			if (ctxt != null && ctxt.ScopedBlock != null)
			{
				var obj = ctxt.ParseCache.LookupModuleName(ctxt.ScopedBlock.NodeRoot as DModule, "object").FirstOrDefault();

				if (obj != null)
				{
					string strType = fmt == LiteralSubformat.Utf32 ? "dstring" :
						fmt == LiteralSubformat.Utf16 ? "wstring" :
						"string";

					var strNode = obj[strType];

					if (strNode != null)
						foreach (var n in strNode) {
							_t = TypeDeclarationResolver.HandleNodeMatch(n, ctxt) as ArrayType;
							if (_t != null)
								break;
						}
				}
			}

			if (_t == null)
			{
				var ch = fmt == LiteralSubformat.Utf32 ? DTokens.Dchar :
					fmt == LiteralSubformat.Utf16 ? DTokens.Wchar : DTokens.Char;

				_t = new ArrayType(new PrimitiveType(ch, DTokens.Immutable));
			}

			return _t;
		}
        static void GetDoneVersionDebugSpecs(ConditionSet cs, MutableConditionFlagSet l, DBlockNode m, ResolutionContext ctxt)
        {
            if (m.StaticStatements == null || m.StaticStatements.Count == 0)
                return;

            foreach(var ss in m.StaticStatements)
            {
                if(ss is VersionSpecification)
                {
                    var vs = (VersionSpecification)ss;

                    if(!_checkForMatchinSpecConditions(m,cs,ss,ctxt))
                        continue;

                    if(vs.SpecifiedId==null)
             						l.AddVersionCondition(vs.SpecifiedNumber);
                    else
                        l.AddVersionCondition(vs.SpecifiedId);
                }
                else if(ss is DebugSpecification)
                {
                    var ds = (DebugSpecification)ss;

                    if(!_checkForMatchinSpecConditions(m,cs,ss, ctxt))
                        continue;

                    if (ds.SpecifiedId == null)
                        l.AddDebugCondition(ds.SpecifiedDebugLevel);
                    else
                        l.AddDebugCondition(ds.SpecifiedId);
                }
            }
        }
Example #25
0
		Evaluation(AbstractSymbolValueProvider vp) { 
			this.ValueProvider = vp; 
			if(vp!=null)
				vp.ev = this;
			this.eval = true;
			this.ctxt = vp.ResolutionContext;
		}
Example #26
0
		private ResolutionResult(object value, ResolutionContext context, Type memberType)
		{
			_value = value;
			_context = context;
			_type = ResolveType(value, memberType);
			_memberType = memberType;
		}
Example #27
0
		private ResolutionResult(object value, ResolutionContext context)
		{
            _value = value;
			_context = context;
			_type = ResolveType(value, typeof(object));
            _memberType = _type;
        }
Example #28
0
        public bool IsMatch(ResolutionContext context)
        {
            if (context == null) throw new ArgumentNullException("context");

            bool toEnum = false;
            return EnumToStringMapping(context, ref toEnum) || EnumToEnumMapping(context) || EnumToUnderlyingTypeMapping(context, ref toEnum);
        }
        /// <summary>
        /// Install package by Identity
        /// </summary>
        /// <param name="project"></param>
        /// <param name="identity"></param>
        /// <param name="resolutionContext"></param>
        /// <param name="projectContext"></param>
        /// <param name="isPreview"></param>
        /// <param name="isForce"></param>
        /// <param name="uninstallContext"></param>
        /// <returns></returns>
        protected async Task InstallPackageByIdentityAsync(NuGetProject project, PackageIdentity identity, ResolutionContext resolutionContext, INuGetProjectContext projectContext, bool isPreview, bool isForce = false, UninstallationContext uninstallContext = null)
        {
            List<NuGetProjectAction> actions = new List<NuGetProjectAction>();
            // For Install-Package -Force
            if (isForce)
            {
                PackageReference installedReference = project.GetInstalledPackagesAsync(CancellationToken.None).Result.Where(p =>
                    StringComparer.OrdinalIgnoreCase.Equals(identity.Id, p.PackageIdentity.Id)).FirstOrDefault();
                if (installedReference != null)
                {
                    actions.AddRange(await PackageManager.PreviewUninstallPackageAsync(project, installedReference.PackageIdentity, uninstallContext, projectContext, CancellationToken.None));
                }
                NuGetProjectAction installAction = NuGetProjectAction.CreateInstallProjectAction(identity, ActiveSourceRepository);
                actions.Add(installAction);
            }
            else
            {
                actions.AddRange(await PackageManager.PreviewInstallPackageAsync(project, identity, resolutionContext, projectContext, ActiveSourceRepository, null, CancellationToken.None));
            }

            if (isPreview)
            {
                PreviewNuGetPackageActions(actions);
            }
            else
            {
                await PackageManager.ExecuteNuGetProjectActionsAsync(project, actions, this, CancellationToken.None);
            }
        }
		public static IEnumerable<TemplateIntermediateType> SearchForClassDerivatives(TemplateIntermediateType t, ResolutionContext ctxt)
		{
			if (!(t is ClassType || t is InterfaceType))
				throw new ArgumentException ("t is expected to be a class or an interface, not " + (t != null ? t.ToString () : "null"));

			var f = new ClassInterfaceDerivativeFinder (ctxt);

			f.typeNodeToFind = t.Definition;
			var bt = t;
			while (bt != null) {
				f.alreadyResolvedClasses.Add (bt.Definition);
				bt = DResolver.StripMemberSymbols (bt.Base) as TemplateIntermediateType;
			}

			var filter = MemberFilter.Classes;
			if (t is InterfaceType) // -> Only interfaces can inherit interfaces. Interfaces cannot be subclasses of classes.
			{
				filter |= MemberFilter.Interfaces;
				f.isInterface = true;
			}

			f.IterateThroughScopeLayers (t.Definition.Location, filter);

			return f.results; // return them.
		}
Example #31
0
 public bool Convert(string sourceMember, ResolutionContext context)
 {
     return(sourceMember == null);
 }
Example #32
0
        public ManagementEvent Convert(ContentfulEvent source, ManagementEvent destination, ResolutionContext context)
        {
            destination.Alerts = new Dictionary <string, List <ManagementAlert> > {
                { "en-GB", source.Alerts.Select(o => context.Mapper.Map <ContentfulAlert, ManagementAlert>(o)).ToList() }
            };
            destination.BookingInformation = new Dictionary <string, string> {
                { "en-GB", source.BookingInformation }
            };
            destination.Categories = new Dictionary <string, List <string> > {
                { "en-GB", source.Categories }
            };
            destination.Description = new Dictionary <string, string> {
                { "en-GB", source.Description }
            };
            destination.Documents = new Dictionary <string, List <LinkReference> > {
                { "en-GB", source.Documents.Select(o => context.Mapper.Map <Asset, LinkReference>(o)).ToList() }
            };
            destination.EndTime = new Dictionary <string, string> {
                { "en-GB", source.EndTime }
            };
            destination.EventCategories = new Dictionary <string, List <ManagementEventCategory> >()
            {
                {
                    "en-GB",
                    source.EventCategories.Select(o => context.Mapper.Map <ContentfulEventCategory, ManagementEventCategory>(o)).ToList()
                }
            };
            destination.EventDate = new Dictionary <string, DateTime> {
                { "en-GB", source.EventDate }
            };
            destination.Featured = new Dictionary <string, bool> {
                { "en-GB", source.Featured }
            };
            destination.Fee = new Dictionary <string, string> {
                { "en-GB", source.Fee }
            };
            destination.Free = new Dictionary <string, bool?> {
                { "en-GB", source.Free }
            };
            if (source.Frequency != EventFrequency.None)
            {
                destination.Frequency = new Dictionary <string, EventFrequency> {
                    { "en-GB", source.Frequency }
                };
                destination.Occurences = new Dictionary <string, int> {
                    { "en-GB", source.Occurences }
                };
            }
            destination.Group = new Dictionary <string, ManagementReference> {
                { "en-GB", new ManagementReference {
                      Sys = context.Mapper.Map <SystemProperties, ManagementSystemProperties>(source.Group.Sys)
                  } }
            };
            destination.Image = string.IsNullOrWhiteSpace(source.Image.SystemProperties.Id) ? null : new Dictionary <string, LinkReference> {
                { "en-GB", new LinkReference()
                  {
                      Sys = new ManagementAsset()
                      {
                          Id = source.Image.SystemProperties.Id
                      }
                  } }
            };
            destination.Location = new Dictionary <string, string> {
                { "en-GB", source.Location }
            };
            destination.MapPosition = new Dictionary <string, MapPosition> {
                { "en-GB", source.MapPosition }
            };
            destination.Paid = new Dictionary <string, bool?> {
                { "en-GB", source.Paid }
            };
            destination.Slug = new Dictionary <string, string>()
            {
                { "en-GB", source.Slug }
            };
            destination.StartTime = new Dictionary <string, string> {
                { "en-GB", source.StartTime }
            };
            destination.SubmittedBy = new Dictionary <string, string> {
                { "en-GB", source.SubmittedBy }
            };
            destination.Tags = new Dictionary <string, List <string> > {
                { "en-GB", source.Tags }
            };
            destination.Teaser = new Dictionary <string, string> {
                { "en-GB", source.Teaser }
            };
            destination.Title = new Dictionary <string, string> {
                { "en-GB", source.Title }
            };

            return(destination);
        }
Example #33
0
        public bool Resolve(UserActivity source, AttendeeDto destination, bool destMember, ResolutionContext context)
        {
            var currentUser = _context.Users.SingleOrDefaultAsync(x => x.UserName == _userAccessor.GetCurrentUsername()).Result;

            if (currentUser.Followings.Any(x => x.TargetId == source.AppUserId))
            {
                return(true);
            }

            return(false);
        }
Example #34
0
        public string Resolve(OrderItem source, OrderItemDto destination, string destMember, ResolutionContext context)
        {
            if (!string.IsNullOrEmpty(source.ItemOrdered.PictureUrl))
            {
                return(_config["ApiUrl"] + source.ItemOrdered.PictureUrl);
            }

            return(null);
        }
Example #35
0
        public Dictionary <string, STATE> Convert(List <BindedDocumentVM> sourceMember, ResolutionContext context)
        {
            Dictionary <string, STATE> result = new Dictionary <string, STATE>();

            foreach (BindedDocumentVM p in sourceMember)
            {
                result.Add(p.Type, (STATE)p.State);
            }
            return(result);
        }
Example #36
0
        public List <BindedDocumentVM> Convert(Dictionary <string, STATE> sourceMember, ResolutionContext context)
        {
            List <BindedDocumentVM> result = new List <BindedDocumentVM>();

            foreach (KeyValuePair <string, STATE> p in sourceMember)
            {
                result.Add(new BindedDocumentVM {
                    State = (STATEVM)p.Value, Type = p.Key
                });
            }
            return(result);
        }
 /// <summary>
 ///   Maps the specified source.
 /// </summary>
 /// <param name="source">The source.</param>
 /// <param name="destination">The destination.</param>
 /// <param name="context">The context.</param>
 /// <returns></returns>
 public override string Map(LinkDetails source, string destination, ResolutionContext context)
 {
     return(source?.Url ?? source?.Script);
 }
Example #38
0
        public ManagementGroup Convert(ContentfulGroup source, ManagementGroup destination, ResolutionContext context)
        {
            if (destination == null)
            {
                destination = new ManagementGroup();
            }

            destination.AdditionalInformation = new Dictionary <string, string> {
                { "en-GB", source.AdditionalInformation }
            };
            destination.MapPosition = new Dictionary <string, MapPosition> {
                { "en-GB", source.MapPosition }
            };
            destination.Address = new Dictionary <string, string> {
                { "en-GB", source.Address }
            };
            destination.Description = new Dictionary <string, string> {
                { "en-GB", source.Description }
            };
            destination.Email = new Dictionary <string, string> {
                { "en-GB", source.Email }
            };
            destination.Facebook = new Dictionary <string, string> {
                { "en-GB", source.Facebook }
            };
            destination.GroupAdministrators = new Dictionary <string, GroupAdministrators> {
                { "en-GB", source.GroupAdministrators }
            };
            destination.Image = string.IsNullOrWhiteSpace(source.Image.SystemProperties.Id) ? null : new Dictionary <string, LinkReference> {
                { "en-GB", new LinkReference()
                  {
                      Sys = new ManagementAsset()
                      {
                          Id = source.Image.SystemProperties.Id
                      }
                  } }
            };
            destination.Name = new Dictionary <string, string> {
                { "en-GB", source.Name }
            };
            destination.PhoneNumber = new Dictionary <string, string> {
                { "en-GB", source.PhoneNumber }
            };
            destination.Slug = new Dictionary <string, string> {
                { "en-GB", source.Slug }
            };
            destination.Twitter = new Dictionary <string, string> {
                { "en-GB", source.Twitter }
            };
            destination.Volunteering = new Dictionary <string, bool> {
                { "en-GB", source.Volunteering }
            };
            destination.Donations = new Dictionary <string, bool> {
                { "en-GB", source.Donations }
            };
            destination.Website = new Dictionary <string, string> {
                { "en-GB", source.Website }
            };
            destination.DateHiddenFrom = new Dictionary <string, string> {
                { "en-GB", source.DateHiddenFrom != null?source.DateHiddenFrom.Value.ToString("yyyy-MM-ddTHH:mm:ssK") : DateTime.MaxValue.ToString("yyyy-MM-ddTHH:mm:ssK") }
            };
            destination.DateHiddenTo = new Dictionary <string, string> {
                { "en-GB", source.DateHiddenTo != null?source.DateHiddenTo.Value.ToString("yyyy-MM-ddTHH:mm:ssK") : DateTime.MaxValue.ToString("yyyy-MM-ddTHH:mm:ssK") }
            };
            destination.Cost = new Dictionary <string, List <string> >()
            {
                {
                    "en-GB",
                    source.Cost?.Select(o => o).ToList()
                }
            };
            destination.CostText = new Dictionary <string, string> {
                { "en-GB", source.CostText }
            };
            destination.AbilityLevel = new Dictionary <string, string> {
                { "en-GB", source.AbilityLevel }
            };

            destination.CategoriesReference = new Dictionary <string, List <ManagementGroupCategory> >()
            {
                {
                    "en-GB",
                    source.CategoriesReference.Select(o => context.Mapper.Map <ContentfulGroupCategory, ManagementGroupCategory>(o)).ToList()
                }
            };

            destination.VolunteeringText = new Dictionary <string, string> {
                { "en-GB", source.VolunteeringText }
            };
            if (destination.Organisation != null)
            {
                destination.Organisation = new Dictionary <string, ManagementReference>()
                {
                    { "en-GB", new ManagementReference {
                          Sys = context.Mapper.Map <SystemProperties, ManagementSystemProperties>(source.Organisation.Sys)
                      } }
                };
            }

            destination.SubCategories = new Dictionary <string, List <ManagementReference> >()
            {
                {
                    "en-GB",
                    source.SubCategories.Select(sc => new ManagementReference {
                        Sys = context.Mapper.Map <SystemProperties, ManagementSystemProperties>(sc.Sys)
                    }).ToList()
                }
            };

            destination.AgeRange = new Dictionary <string, List <string> > {
                { "en-GB", source.AgeRange }
            };
            destination.SuitableFor = new Dictionary <string, List <string> > {
                { "en-GB", source.SuitableFor }
            };
            destination.DonationsText = new Dictionary <string, string> {
                { "en-GB", source.DonationsText }
            };
            destination.DonationsUrl = new Dictionary <string, string> {
                { "en-GB", source.DonationsUrl }
            };
            destination.GroupBranding = new Dictionary <string, List <ManagementReference> >
            {
                {
                    "en-GB",
                    source.GroupBranding.Select(sc => new ManagementReference {
                        Sys = context.Mapper.Map <SystemProperties, ManagementSystemProperties>(sc.Sys)
                    }).ToList()
                }
            };
            return(destination);
        }
Example #39
0
        public string Resolve(BlogEntity source, BlogToReturnDto destination, string destMember, ResolutionContext context)
        {
            if (!string.IsNullOrEmpty(source.PictureUrl))
            {
                return(_configuration["ApiUrl"] + source.PictureUrl);
            }

            return(null);
        }
Example #40
0
 public BetDto Convert(Tuple <Player, Bet, string> source, BetDto destination, ResolutionContext context)
 {
     return(new BetDto
     {
         Username = source.Item1.Username,
         UserId = source.Item1.Id,
         Bet = source.Item2?.Amount ?? 0,
         IsDivided = source.Item2?.IsSplitted ?? false,
         IsDouble = source.Item2?.IsDouble ?? false
     });
 }
 public int Resolve(object source, object destination, int destinationMember, ResolutionContext context)
 {
     return(source != null ? (int)source : 0);
 }
 public string Resolve(object source, object destination, string destinationMember, ResolutionContext context)
 {
     return((bool)source ? "CĂł" : "KhĂ´ng");
 }
Example #43
0
        public static void HandleOptLinkOutput(AbstractDProject Project, BuildResult br, string linkerOutput)
        {
            var ctxt = ResolutionContext.Create(DResolverWrapper.CreateParseCacheView(Project), null, null);

            ctxt.ContextIndependentOptions =
                ResolutionOptions.IgnoreAllProtectionAttributes |
                ResolutionOptions.DontResolveBaseTypes |
                ResolutionOptions.DontResolveBaseClasses |
                ResolutionOptions.DontResolveAliases;

            foreach (Match match in optlinkRegex.Matches(linkerOutput))
            {
                var error = new BuildError();

                // Get associated D source file
                if (match.Groups["obj"].Success)
                {
                    var obj = Project.GetAbsoluteChildPath(new FilePath(match.Groups["obj"].Value)).ChangeExtension(".d");

                    foreach (var pf in Project.Files)
                    {
                        if (pf.FilePath == obj)
                        {
                            error.FileName = pf.FilePath;
                            break;
                        }
                    }
                }

                var msg = match.Groups["message"].Value;

                var symUndefMatch = symbolUndefRegex.Match(msg);

                if (symUndefMatch.Success && symUndefMatch.Groups["mangle"].Success)
                {
                    var mangledSymbol = symUndefMatch.Groups["mangle"].Value;
                    ITypeDeclaration qualifier;
                    try
                    {
                        var resSym = Demangler.DemangleAndResolve(mangledSymbol, ctxt, out qualifier);
                        if (resSym is DSymbol)
                        {
                            var ds  = resSym as DSymbol;
                            var ast = ds.Definition.NodeRoot as DModule;
                            if (ast != null)
                            {
                                error.FileName = ast.FileName;
                            }
                            error.Line   = ds.Definition.Location.Line;
                            error.Column = ds.Definition.Location.Column;
                            msg          = ds.Definition.ToString(false, true);
                        }
                        else
                        {
                            msg = qualifier.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        msg = "<log analysis error> " + ex.Message;
                    }
                    error.ErrorText = msg + " could not be resolved - library reference missing?";
                }
                else
                {
                    error.ErrorText = "Linker error " + match.Groups["code"].Value + " - " + msg;
                }

                br.Append(error);
            }
        }
 public string Resolve(object source, object destination, string destinationMember, ResolutionContext context)
 {
     return(source != null ? context.Options.Items[destinationValue].ToString() : string.Empty);
 }
Example #45
0
 string IValueResolver <Employee, EmployeeView, string> .Resolve(Employee source, EmployeeView destination, string destMember, ResolutionContext context)
 {
     if (source.User != null)
     {
         var user = Resolve(source).Result;
         return(user);
     }
     return(null);
 }
Example #46
0
        public static TDestination Map <TSource, TSourceKey, TSourceValue, TDestination, TDestinationKey, TDestinationValue>(TSource source, TDestination destination, ResolutionContext context)
            where TSource : IDictionary <TSourceKey, TSourceValue>
            where TDestination : class, IDictionary <TDestinationKey, TDestinationValue>
        {
            if (source == null && context.Mapper.ShouldMapSourceCollectionAsNull(context))
            {
                return(null);
            }

            TDestination list = destination ?? (
                typeof(TDestination).IsInterface()
                    ? new Dictionary <TDestinationKey, TDestinationValue>() as TDestination
                    : (TDestination)(context.ConfigurationProvider.AllowNullDestinationValues
                        ? ObjectCreator.CreateNonNullValue(typeof(TDestination))
                        : ObjectCreator.CreateObject(typeof(TDestination))));

            list.Clear();
            var itemContext = new ResolutionContext(context);

            foreach (var keyPair in (IEnumerable <KeyValuePair <TSourceKey, TSourceValue> >)source ?? Enumerable.Empty <KeyValuePair <TSourceKey, TSourceValue> >())
            {
                list.Add(itemContext.Map(keyPair.Key, default(TDestinationKey)),
                         itemContext.Map(keyPair.Value, default(TDestinationValue)));
            }
            return(list);
        }
Example #47
0
 public bool Resolve(Object source, Object destination, bool flag, ResolutionContext context)
 {
     return(false);
 }
Example #48
0
        public string Resolve(Object source, Object destination, string message, ResolutionContext context)
        {
            var messageNew = "";

            return(messageNew);
        }
Example #49
0
        public string Resolve(Product source, ProductView destination, string destMember, ResolutionContext context)
        {
            if (source.AvailabilityStatus == null)
            {
                return("");
            }
            if (source.AvailabilityStatus == 0)
            {
                return("");
            }
            var item = _productStatusAvBusinessLogic.GetById(source.AvailabilityStatus);

            return(item.Name);
        }
Example #50
0
        public string Resolve(Product source, ProductView destination, string destMember, ResolutionContext context)
        {
            if (source.Gender == null)
            {
                return("");
            }
            if (source.Gender == 0)
            {
                return("");
            }
            var item = _genderBusinessLogic.GetById(source.Gender);

            return(item.Name);
        }
Example #51
0
 public string Resolve(EmployeeView source, Employee destination, string destMember, ResolutionContext context)
 {
     if (source.UserName != null)
     {
         var user = Resolve(source).Result;
         return(user);
     }
     return(null);
 }
Example #52
0
        public string Resolve(Product source, ProductView destination, string destMember, ResolutionContext context)
        {
            if (source.ProductType == null)
            {
                return("");
            }
            if (source.ProductType == 0)
            {
                return("");
            }
            var type = _productTypeBusinessLogic.GetById(source.ProductType);

            return(type.Name);
        }
Example #53
0
 public PatientForGet Resolve(Claim source, ClaimForGet destination, PatientForGet member, ResolutionContext context)
 {
     return(new PatientForGet {
         Name = source.BeneficiaryName, Gender = source.PatientGender, Address = source.PatientAddress
     });
 }
 public UserClaim Resolve(QueryUniqueDto source, QueryUnique destination, UserClaim destMember, ResolutionContext context)
 {
     return(Helper.GetClaimsFromUser(_httpContextAccessor.HttpContext?.User.Identity as ClaimsIdentity));
 }
Example #55
0
        public static async Task <IEnumerable <NuGetProjectAction> > GetInstallProjectActionsAsync(
            this NuGetPackageManager packageManager,
            NuGetFolderProject nuGetProject,
            PackageIdentity packageIdentity,
            ResolutionContext resolutionContext,
            INuGetProjectContext nuGetProjectContext,
            IEnumerable <SourceRepository> primarySourceRepositories,
            IEnumerable <SourceRepository> secondarySourceRepositories,
            CancellationToken token)
        {
            if (nuGetProject == null)
            {
                throw new ArgumentNullException(nameof(nuGetProject));
            }
            if (packageIdentity == null)
            {
                throw new ArgumentNullException(nameof(packageIdentity));
            }
            if (resolutionContext == null)
            {
                throw new ArgumentNullException(nameof(resolutionContext));
            }
            if (nuGetProjectContext == null)
            {
                throw new ArgumentNullException(nameof(nuGetProjectContext));
            }
            if (primarySourceRepositories == null)
            {
                throw new ArgumentNullException(nameof(primarySourceRepositories));
            }
            if (!primarySourceRepositories.Any())
            {
                throw new ArgumentException(nameof(primarySourceRepositories));
            }
            if (secondarySourceRepositories == null)
            {
                throw new ArgumentNullException(nameof(secondarySourceRepositories));
            }
            if (packageIdentity.Version == null)
            {
                throw new ArgumentNullException(nameof(packageIdentity));
            }

            var localSources = new HashSet <SourceRepository>(new SourceRepositoryComparer());

            localSources.Add(packageManager.PackagesFolderSourceRepository);
            localSources.AddRange(packageManager.GlobalPackageFolderRepositories);

            if (resolutionContext.DependencyBehavior == DependencyBehavior.Ignore)
            {
                var logger = new ProjectContextLogger(nuGetProjectContext);

                // First, check only local sources.
                var sourceRepository = await GetSourceRepositoryAsync(packageIdentity, localSources, resolutionContext.SourceCacheContext, logger, token);

                if (sourceRepository == null)
                {
                    // Else, check provided sources. We use only primary sources when we don't care about dependencies.
                    sourceRepository = await GetSourceRepositoryAsync(packageIdentity, primarySourceRepositories, resolutionContext.SourceCacheContext, logger, token);
                }

                // If still not found, we just throw an exception.
                if (sourceRepository == null)
                {
                    throw new InvalidOperationException($"Unable to find version '{packageIdentity.Version}' of package '{packageIdentity.Id}'.");
                }

                return(new[] { NuGetProjectAction.CreateInstallProjectAction(packageIdentity, sourceRepository, nuGetProject) });
            }

            var primarySources = new HashSet <SourceRepository>(new SourceRepositoryComparer());
            var allSources     = new HashSet <SourceRepository>(new SourceRepositoryComparer());

            Tuple <IReadOnlyCollection <PackageIdentity>, IReadOnlyCollection <SourcePackageDependencyInfo> > packageAndDependencies = null;
            var allDependenciesResolved = false;

            // If target package is already installed, there's a slight chance that all packages are already installed.
            if (await PackageExistsInSourceRepository(
                    packageIdentity,
                    packageManager.PackagesFolderSourceRepository,
                    resolutionContext.SourceCacheContext,
                    new ProjectContextLogger(nuGetProjectContext),
                    token))
            {
                primarySources.Add(packageManager.PackagesFolderSourceRepository);
                allSources.Add(packageManager.PackagesFolderSourceRepository);

                try
                {
                    // Try get all dependencies from local sources only.
                    packageAndDependencies = await GetPackageAndDependenciesToInstall(
                        packageManager,
                        nuGetProject,
                        packageIdentity,
                        resolutionContext,
                        nuGetProjectContext,
                        primarySources,
                        allSources,
                        token);

                    allDependenciesResolved = true;
                }
                catch (NuGetResolverConstraintException)
                {
                    // We didn't manage to find all dependencies in the local packages folder.
                    allDependenciesResolved = false;
                }
            }

            // If we didn't manage to resolve all dependencies from the local sources, check in all sources.
            if (!allDependenciesResolved)
            {
                primarySources.AddRange(localSources);
                primarySources.AddRange(primarySourceRepositories);
                allSources.AddRange(primarySources);
                allSources.AddRange(secondarySourceRepositories);

                packageAndDependencies = await GetPackageAndDependenciesToInstall(
                    packageManager,
                    nuGetProject,
                    packageIdentity,
                    resolutionContext,
                    nuGetProjectContext,
                    primarySources,
                    allSources,
                    token);
            }

            // Create the install actions.
            return(GetProjectActions(
                       packageIdentity,
                       packageAndDependencies.Item1,
                       packageAndDependencies.Item2,
                       nuGetProject));
        }
Example #56
0
 public ProductTypeDto Convert(ProductType source, ProductTypeDto destination, ResolutionContext context)
 {
     if (source.Name == "A")
     {
         return(new ProdTypeA());
     }
     if (source.Name == "B")
     {
         return(new ProdTypeB());
     }
     throw new ArgumentException();
 }
Example #57
0
            public IDictionary <string, Right> Convert(rightType[] source, IDictionary <string, Right> destination, ResolutionContext context)
            {
                ICollection <Right>         values = mapper.Map <rightType[], ICollection <Right> >(source);
                IDictionary <string, Right> rights = new Dictionary <string, Right>();

                foreach (Right right in values)
                {
                    rights.Add(right.Type, right);
                }

                return(rights);
            }
Example #58
0
        public List <string> Resolve(ServiceModel source, ServiceDTO destination, List <string> destMember, ResolutionContext context)
        {
            var instances = _cache.Get <List <string> >(KakaduConstants.ACTIONAPI_INSTANCES);

            if (instances == null || !instances.Any())
            {
                return(new List <string>());
            }

            return(instances.Select(instance => ConcatUrl(instance, source.Code)).ToList());
        }
Example #59
0
            public IDictionary <string, ProvisionedZone> Convert(provisionedZoneType[] source, IDictionary <string, ProvisionedZone> destination, ResolutionContext context)
            {
                ICollection <ProvisionedZone>         values           = mapper.Map <provisionedZoneType[], ICollection <ProvisionedZone> >(source);
                IDictionary <string, ProvisionedZone> provisionedZones = new Dictionary <string, ProvisionedZone>();

                foreach (ProvisionedZone provisionedZone in values)
                {
                    provisionedZones.Add(provisionedZone.SifId, provisionedZone);
                }

                return(provisionedZones);
            }
Example #60
0
        public string Resolve(KnownRouteReplyDTO source, KnownRouteReplyModel destination, string destMember, ResolutionContext context)
        {
            if (source == null)
            {
                return(string.Empty);
            }

            // decompress content if needed
            return(string.IsNullOrWhiteSpace(source.ContentEncoding) ? source.ContentBase64 : source.Decompressed());
        }