public override void Map(string inputLine, MapperContext context)
        {
            try
            {
                var doc = XDocument.Parse(inputLine);

                var sensors =
                    doc.Descendants("sensor")
                       .Select(
                           element => new
                                          {
                                              name = (string)element.Attribute("name"),
                                              value = element.Value
                                          });

                foreach (var sensor in sensors)
                {
                    context.EmitKeyValue(sensor.name, sensor.value);
                }
            }
            catch (Exception x)
            {
                context.EmitLine(x.ToString());
            }
        }
        // Gets the total number of purchases made by users in North America & in Europe.
        // The input is the output from the AggregatePurchaseMapper job (which map reduced the 'clickstearm' data file).
        // In format........'Country \t Number of Purchases \t % of the purchases made by New users'
        // E.g. 'France	5	20'
        public override void Map(string inputLine, MapperContext context)
        {
            var dataRow = inputLine.Split('\t');
            if (dataRow.Count() == 3)
            {
                var country = dataRow[0];
                int numPurchases;
                int percentNew;
                if (int.TryParse(dataRow[1], out numPurchases) && int.TryParse(dataRow[2], out percentNew))
                {
                    var continent = string.Empty;

                    if (_europeanCountries.Contains(country))
                    {
                        continent = "Europe";
                    }
                    else if (_northAmericanCountries.Contains(country))
                    {
                        continent = "North America";
                    }

                    if (!string.IsNullOrEmpty(continent))
                    {
                        var numNewUserPurchases = numPurchases * percentNew / 100;
                        context.EmitKeyValue(continent, numNewUserPurchases.ToString(CultureInfo.InvariantCulture));
                    }

                }
            }
        }
Example #3
0
        public override void Map(string inputLine, MapperContext context)
        {
            var matches = commaSplit.Matches(inputLine);

            //Hadoop is semi-structured, meaning that we do not need every row to match
            //our expected structure.  This is a simplistic check, but given a more polyglot
            //data set, we could filter out unexpected rows or perform more complex filtering.
            if (matches == null || matches.Count != 6)
            {
                //If this were a production data set, I would think about logging bad rows
                //but because this is a demo, I just want to return without passing anything
                //to be reduced.
                return;
            }

            //Trim off any leading comma or surrounding quotation marks.
            string key = matches[1].Value.TrimStart(',').Trim('\"');

            //We don't want to return the header row.
            if (key == "LCR DESC")
            {
                return;
            }

            //The Map function returns a set of key-value pairs.
            //The key in this case is the specific crime, and our value
            //is "1" (which we will use to get a count).
            context.EmitKeyValue(key, value);
        }
        public override void Map(string inputLine, MapperContext context)
        {
            //Step to Identify the Practice or Prescription data set
            //Using the SDK, tried to use the MapperContext.InputFileName property: it is always empty
            //So decided to use items count of each datasets
            //Items count 8 for practice and Items count 9 for prescription

            char[] delimiterChars = { ',' };

            //split up the passed in line
            string[] individualItems = inputLine.Trim().Split(delimiterChars);

            if (individualItems.Count() == 9)
            {
                Prescription prescription = reader.ExtractPrescriptionsFromCsvLineFormat(inputLine);

                if (String.IsNullOrWhiteSpace(prescription.PracticeId)) { return; }  //Ignore, practise name cannot be null

                //Filter by peppermint oil

                if (prescription.BNFName.ToLower() != "peppermint oil") { return; }  //Ignore, if filtor not matched

                context.EmitKeyValue(prescription.BNFName, prescription.ActualCost.ToString("0.00"));
            } 
        }
        public override void Map(string inputLine, MapperContext context)
        {
            var delivery = new Delivery();
            double result = 0.0;

            context.Log("MAPPER:::START");
            context.Log(inputLine);
            context.Log("UTF-8: " + Encoding.UTF8.GetBytes(inputLine).Length);
            context.Log("ASCII: " + Encoding.ASCII.GetBytes(inputLine).Length);

            // Read the incoming string as a Thrift Binary serialized object
            var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(inputLine));
            using (var transport = new TStreamTransport(inputStream, null))
            {
                delivery.Read(new TBinaryProtocol(transport));
                context.Log("MAPPER:::AFTER_READ");

                // Get the driven kilometers from the vehicle's odometer sensor
                var sensorData = delivery.Vehicle.SensorHistory;
                var minOdo = sensorData.Min(d => d.OdoMeter);
                var maxOdo = sensorData.Max(d => d.OdoMeter);
                result = maxOdo - minOdo;

                context.Log("MAPPER:::BEFORE_STREAM_CLOSE");
            }
            context.Log("MAPPER:::AFTER_STREAM_CLOSE");

            // Emit the vehicle id, and the driven kilometers.
            if (result > 0.1)
            {
                context.EmitKeyValue(delivery.Vehicle.VehicleId, result.ToString(CultureInfo.InvariantCulture));
            }

            context.Log("MAPPER:::END");
        }
Example #6
0
 public override void Map(string inputLine, MapperContext context)
 {
     //interpret the incoming line as an integer value
     var value = int.Parse(inputLine);
     //determine whether value is even or odd
     string key = value%2 == 0 ? "even" : "odd";
     //output key assignment with value
     context.EmitKeyValue(key, value.ToString());
 }
        public override void Map(string inputLine, MapperContext context)
        {
            // The odometer is on index 2
            var parts = inputLine.Split('\t');
            var id = parts[0];
            var kilometers = parts[2];

            context.EmitKeyValue(id, kilometers);
        }
Example #8
0
        public override void Map(string inputLine, MapperContext context)
        {
            string[] terms = inputLine.Split('\t');
            // add a sanity check in case we have a data quality issue
            if (terms.Length != 6) return;

            // get the country part out
            string country = terms[3];
            context.EmitKeyValue(country, "1");
        }
 public override void Map(string inputLine, MapperContext context)
 {
     string[] inputValues = inputLine.Split(',');
     //Pulls all responses that link to the id of this question
     if (inputValues[1].Trim() == "10001")
     {
         string ip = inputValues[0].Trim();
         string country = IpAddressResolver.Resolve(ip);
         context.EmitKeyValue(country, inputValues[2]);
     }
 }
        public override void Map(string inputLine, MapperContext context)
        {
            var dataRow = inputLine.Split('\t');
            if (dataRow.Count() == 4)
            {
                var userId = dataRow[1];
                var rating = dataRow[2];
                var movieId = dataRow[3];

                context.EmitKeyValue(userId, StringUtility.GetAsTabbedString(new[]{ movieId, rating}));
            }
        }
Example #11
0
        public override void Map(string inputLine, MapperContext context)
        {
            string[] fields = inputLine.Split(',');
            string horse = fields[0];
            string jockey = fields[1];
            string course = fields[2];

            string stats = GetStatsForHorseJockeyCourse(
                horse,
                jockey,
                course);

            context.EmitKeyValue(horse, stats);
        }
        public override void Map(string inputLine, MapperContext context)
        {
            //example input: Hello, Andy
            if (!inputLine.StartsWith("Hello, "))
            {
                context.Log(string.Format("The inputLine {0} is not in the correct format", inputLine));
                context.IncrementCounter("RecoverableError", "InputFormatIncorrect", 1);
                return;
            }

            var key = inputLine.Substring(7);
            if (key.EndsWith(".")) key = key.Trim('.');

            context.EmitKeyValue(key, "1");//we are going to count instances, the value is irrelevant
        }
        public void should_inherit_base_beforemap()
        {
            // arrange
            var source = new Class {Prop = "test"};
            var context = new MapperContext();
            context.CreateMap<BaseClass, BaseDto>()
                .BeforeMap((s, d) => d.DifferentProp = s.Prop)
                .Include<Class, Dto>();

            context.CreateMap<Class, Dto>();

            // act
            var dest = context.Engine.Map<Class, Dto>(source);

            // assert
            "test".ShouldEqual(dest.DifferentProp);
        }
        // Gets the total number of purchases in each country across the 4 days & the % of these purchases made by new users.
        // Each data row in 'clickstearm' data file is in the format...
        // 'DateTime of Hit \t ProductId \t VisitorType \t Country of Request \t Referrer \t Action'
        // E.g. 01/03/2013 18:51:31	159822	Regular	USA	Adword	Purchase
        public override void Map(string inputLine, MapperContext context)
        {
            var dataRow = inputLine.Split('\t');
            if (dataRow.Count() == 6)
            {
                var visitorType = dataRow[2];
                var country = dataRow[3];
                var action = dataRow[5];

                if (action == "Purchase")
                {
                    context.IncrementCounter("HitMissProgress", "PurchaseFound", 1);
                    context.EmitKeyValue(country, visitorType);
                }
                context.IncrementCounter("HitMissProgress", "PurchaseNotFound", 1);
            }
        }
        public override void Map(string inputLine, MapperContext context)
        {
            var matches = commaSplit.Matches(inputLine);

            //Hadoop is semi-structured, meaning that we do not need every row to match
            //our expected structure.  This is a simplistic check, but given a more polyglot
            //data set, we could filter out unexpected rows or perform more complex filtering.
            if (matches == null || matches.Count != 6)
            {
                //If this were a production data set, I would think about logging bad rows
                //but because this is a demo, I just want to return without passing anything
                //to be reduced.
                return;
            }

            //Trim off any leading comma or surrounding quotation marks.
            string key = matches[5].Value.TrimStart(',').Trim('\"').Trim('(').Trim(')');

            //We don't want to return the header row.
            if (key == "LOCATION")
            {
                return;
            }

            //At this point, we have coordinates which look like
            //35.776238687249744, -78.6246378053371
            //We want to solve to 3 places after the decimal point to
            //get a better idea of "neighborhood"/area-level crime.
            var keyvals = key.Split(',');
            if (keyvals.Length != 2)
            {
                return;
            }

            key = keyvals[0].Trim(' ').Substring(0, keyvals[0].IndexOf('.') + 4)
                  + ", " + keyvals[1].Trim(' ').Substring(0, keyvals[1].IndexOf('.') + 3);

            //The Map function returns a set of key-value pairs.
            //The key in this case is the specific crime, and our value
            //is "1" (which we will use to get a count).
            context.EmitKeyValue(key, value);
        }
        public override void Map(string inputLine, MapperContext context)
        {
            var ofertas = ServiceHelper.Deserialize<OffertResult>(inputLine);

            foreach (var oferta in ofertas.offers.Where(x => x.category != null && !String.IsNullOrEmpty(x.category.value)))
            {
                if (oferta.province != null && !String.IsNullOrEmpty(oferta.province.value))
                {
                    var fecha = String.Format("{0}:00:00", Convert.ToDateTime(oferta.published).Hour);
                    var provincia = Province.DepurarProvincia(oferta.province.value);

                    var linea = String.Format("{0};{1};{2}" + Environment.NewLine,
                       oferta.category.value,
                       provincia,
                       fecha);

                    context.EmitKeyValue(linea, "1");
                }
            }
        }
        public override void Map(string inputLine, MapperContext context)
        {
            if (inputLine.Contains(";"))
            {
                var array = inputLine.Split(';');

                if (array.Length >= 3)
                {
                    var provincia = Province.DepurarProvincia(array[2]);
                    var fecha = String.Format("{0}:00:00",
                        Convert.ToDateTime(array[1], new CultureInfo("es-es")).Hour);

                    var linea = String.Format("{0};{1};{2}" + Environment.NewLine,
                               array[0],
                               provincia,
                               fecha);

                    context.EmitKeyValue(linea, "1");
                }
            }
        }
        public override void Map(string inputLine, MapperContext context)
        {
            //Step to Identify the Practice or Prescription data set
            //Using the SDK, tried to use the MapperContext.InputFileName property: it is always empty
            //So decided to use items count of each datasets
            //Items count 8 for practice and Items count 9 for prescription

            char[] delimiterChars = { ',' };

            //split up the passed in line
            string[] individualItems = inputLine.Trim().Split(delimiterChars);

            if (individualItems.Count() == 8)
            {
                Practices practice = reader.ExtractPracticesFromCsvLineFormat(inputLine);

                if (String.IsNullOrWhiteSpace(practice.ReferenceId)) { return; }  //Ignore, practise name cannot be null
                if (String.IsNullOrWhiteSpace(practice.Name)) { return; }  //Ignore, practise name cannot be null

                context.EmitKeyValue("UK", Convert.ToString(practice.ReferenceId));
            }
           
        }
Example #19
0
        private IEnumerable <DataTypeConfigurationFieldDisplay> MapPreValues(IDataEditor source, MapperContext context)
        {
            // this is a new data type, initialize default configuration
            // get the configuration editor,
            // get the configuration fields and map to UI,
            // get the configuration default values and map to UI

            var configurationEditor = source.GetConfigurationEditor();

            var fields = context.MapEnumerable <ConfigurationField, DataTypeConfigurationFieldDisplay>(configurationEditor.Fields);

            var defaultConfiguration = configurationEditor.DefaultConfiguration;

            if (defaultConfiguration != null)
            {
                MapConfigurationFields(null, fields, defaultConfiguration);
            }

            return(fields);
        }
Example #20
0
        private IEnumerable <PropertyEditorBasic> MapAvailableEditors(IDataType source, MapperContext context)
        {
            var properties = _propertyEditors
                             .Where(x => !x.IsDeprecated || _contentSettings.ShowDeprecatedPropertyEditors || source.EditorAlias == x.Alias)
                             .OrderBy(x => x.Name);

            return(context.MapEnumerable <IDataEditor, PropertyEditorBasic>(properties));
        }
Example #21
0
 internal MappingConfigStartingPoint(MapperContext mapperContext)
 {
     _configInfo = new MappingConfigInfo(mapperContext);
 }
Example #22
0
        public UserProfile GetCreator(IContent source, MapperContext context)
        {
            var profile = source.GetWriterProfile(_userService);

            return(profile == null ? null : context.Map <IProfile, UserProfile>(profile));
        }
Example #23
0
        private static PropertyGroup MapSaveGroup <TPropertyType>(PropertyGroupBasic <TPropertyType> sourceGroup,
                                                                  IEnumerable <PropertyGroup> destOrigGroups, MapperContext context)
            where TPropertyType : PropertyTypeBasic
        {
            PropertyGroup destGroup;

            if (sourceGroup.Id > 0)
            {
                // update an existing group
                // ensure it is still there, then map/update
                destGroup = destOrigGroups.FirstOrDefault(x => x.Id == sourceGroup.Id);
                if (destGroup != null)
                {
                    context.Map(sourceGroup, destGroup);
                    return(destGroup);
                }

                // force-clear the ID as it does not match anything
                sourceGroup.Id = 0;
            }

            // insert a new group, or update an existing group that has
            // been deleted in the meantime and we need to re-create
            // map/create
            destGroup = context.Map <PropertyGroup>(sourceGroup);
            return(destGroup);
        }
Example #24
0
        public override void Map(string inputLine, MapperContext context)
        {

            var data = inputLine.Split('\t');
            //countrycode --- name,value,originalValue
            context.EmitKeyValue(data[0], data[1] + '\t' + data[2] + '\t' + data[3] + '\t' + data[4]);
        }
Example #25
0
 // Umbraco.Code.MapAll -Alias
 private void Map(IContent source, ContentItemBasic <ContentPropertyBasic> target, MapperContext context)
 {
     target.ContentTypeId    = source.ContentType.Id;
     target.ContentTypeAlias = source.ContentType.Alias;
     target.CreateDate       = source.CreateDate;
     target.Edited           = source.Edited;
     target.Icon             = source.ContentType.Icon;
     target.Id              = source.Id;
     target.Key             = source.Key;
     target.Name            = GetName(source, context);
     target.Owner           = _commonMapper.GetOwner(source, context);
     target.ParentId        = source.ParentId;
     target.Path            = source.Path;
     target.Properties      = context.MapEnumerable <Property, ContentPropertyBasic>(source.Properties);
     target.SortOrder       = source.SortOrder;
     target.State           = _basicStateMapper.Map(source, context);
     target.Trashed         = source.Trashed;
     target.Udi             = Udi.Create(source.Blueprint ? Constants.UdiEntityType.DocumentBlueprint : Constants.UdiEntityType.Document, source.Key);
     target.UpdateDate      = GetUpdateDate(source, context);
     target.Updater         = _commonMapper.GetCreator(source, context);
     target.VariesByCulture = source.ContentType.VariesByCulture();
 }
 public override void Initialize(MapperContext context)
 {
     reader = new PracticeLineReader();
     base.Initialize(context);
 }
        public override void Map(string inputLine, MapperContext context)
        {
            var delivery = SerializationHelper.Deserialize<Delivery>(inputLine);

            //TODO
        }
 public override void Initialize(MapperContext context)
 {
     practiceLinereader = new PracticeLineReader();
     prescriptionLinereader = new PrescriptionLineReader();
     base.Initialize(context);
 }
Example #29
0
 public override void Map(string inputLine, MapperContext context)
 {
     var data = inputLine.Split('\t');
     context.EmitKeyValue((-Double.Parse(data[1])).ToString(), inputLine);//order by value descending
 }
Example #30
0
 // Umbraco.Code.MapAll -Value
 private static void Map(ConfigurationField source, DataTypeConfigurationFieldDisplay target, MapperContext context)
 {
     target.Config      = source.Config;
     target.Description = source.Description;
     target.HideLabel   = source.HideLabel;
     target.Key         = source.Key;
     target.Name        = source.Name;
     target.View        = source.View;
 }
Example #31
0
 // Umbraco.Code.MapAll
 private static void Map(Section source, ManifestSection target, MapperContext context)
 {
     target.Alias = source.Alias;
     target.Name  = source.Name;
 }
Example #32
0
 internal PlanTargetSelector(MapperContext mapperContext)
 {
     _mapperContext = mapperContext;
 }
 public void TestMerge()
 {
     var context1 = new MapperContext();
     var context2 = new MapperContext();
 }
Example #34
0
 // Umbraco.Code.MapAll
 private static void Map(IContent source, ContentPropertyCollectionDto target, MapperContext context)
 {
     target.Properties = context.MapEnumerable <Property, ContentPropertyDto>(source.Properties);
 }
Example #35
0
 // no MapAll - uses the IContentTypeBase map method, which has MapAll
 private static void Map(IContentTypeComposition source, ContentTypeBasic target, MapperContext context)
 {
     Map(source, target, Constants.UdiEntityType.MemberType);
 }
Example #36
0
        // no MapAll - relies on the non-generic method
        private void MapTypeToDisplayBase <TSource, TSourcePropertyType, TTarget, TTargetPropertyType>(TSource source,
                                                                                                       TTarget target, MapperContext context)
            where TSource : ContentTypeSave <TSourcePropertyType>
            where TSourcePropertyType : PropertyTypeBasic
            where TTarget : ContentTypeCompositionDisplay <TTargetPropertyType>
            where TTargetPropertyType : PropertyTypeDisplay
        {
            MapTypeToDisplayBase(source, target);

            target.Groups =
                context
                .MapEnumerable <PropertyGroupBasic <TSourcePropertyType>, PropertyGroupDisplay <TTargetPropertyType> >(
                    source.Groups);
        }
        public override void Map(string inputLine, MapperContext context)
        {
            //split line on tabs
            try
            {
                var s = JsonConvert.DeserializeObject<Roo>(inputLine);


                //get year observed
                if (string.IsNullOrEmpty(s.prepTime))
                {
                    s.prepTime = "Un";
                }

                //get ufo type
                if (string.IsNullOrEmpty(s.name))
                {
                    s.name = "nul";
                }

                context.EmitKeyValue(s.prepTime, s.name);


                //send output

            }
            catch (InvalidCastException ex)
            {
                context.EmitKeyValue("error", "roor");
            }

        }
Example #38
0
        private static IPropertyType MapSaveProperty(PropertyTypeBasic sourceProperty,
                                                     IEnumerable <IPropertyType> destOrigProperties, MapperContext context)
        {
            IPropertyType destProperty;

            if (sourceProperty.Id > 0)
            {
                // updating an existing property
                // ensure it is still there, then map/update
                destProperty = destOrigProperties.FirstOrDefault(x => x.Id == sourceProperty.Id);
                if (destProperty != null)
                {
                    context.Map(sourceProperty, destProperty);
                    return(destProperty);
                }

                // force-clear the ID as it does not match anything
                sourceProperty.Id = 0;
            }

            // insert a new property, or update an existing property that has
            // been deleted in the meantime and we need to re-create
            // map/create
            destProperty = context.Map <IPropertyType>(sourceProperty);
            return(destProperty);
        }
Example #39
0
 // no MapAll - take care
 private void Map(MediaTypeSave source, MediaTypeDisplay target, MapperContext context)
 {
     MapTypeToDisplayBase <MediaTypeSave, PropertyTypeBasic, MediaTypeDisplay, PropertyTypeDisplay>(source, target, context);
 }
Example #40
0
        public override void Map(string inputLine, MapperContext context)
        {
            int         i      = 0;
            SingleTweet Tweets = JsonConvert.DeserializeObject <SingleTweet>(StripHTML(inputLine));;


            var MaxSource = from k in Tweets.statuses group k by k.source into r select r.Max(n => n.source);

            var SourceNotNullCount  = (from k in Tweets.statuses where k.source != null select k.source).Count();
            var CountryNotNullCount = (from k in Tweets.statuses where k.place != null select k.place).Count();

            //"Fri Apr 22 16:26:21 +0000 2016"
            var CreatedAt = (from k in Tweets.statuses group k by k.created_at into r select r.Key);
            Dictionary <long, int> LDates = new Dictionary <long, int>();

            foreach (var item in CreatedAt)
            {
                var      ds  = item.Split(' ');
                var      dsT = ds[3].Split(':');
                DateTime d   = new DateTime(int.Parse(ds[5]), 4, int.Parse(ds[2]), int.Parse(dsT[0]), int.Parse(dsT[1]), int.Parse(dsT[2]));
                var      cd  = (from k in Tweets.statuses where k.created_at == item select k.created_at).Count();
                try
                {
                    LDates.Add(d.Ticks, cd);
                }
                catch (Exception)
                {
                }
            }


            var MaxUser    = (from k in Tweets.statuses group k by k.user.name into r select r.Max(n => n.user.name)).Take(10);
            var MaxCountry = (from k in Tweets.statuses where k.place != null group k by k.place into r select r.Max(n => n.place));



            var RetweetSum   = (from k in Tweets.statuses select k.retweet_count).Sum();
            var FavouriteSum = (from k in Tweets.statuses select k.favorite_count).Sum();
            var tweetsCount  = (from k in Tweets.statuses select k).Count();

            dynamic a  = MaxCountry.ToList();
            dynamic ac = MaxSource.ToList();


            List <string> Countries = new List <string>();
            List <string> Sources   = new List <string>();

            foreach (var item in a)
            {
                string[] Sp = Regex.Split(item.ToString(), "\"country\":");
                string   r  = Sp[1].Replace("\"", "");
                r = r.Remove(Sp[1].IndexOf(",")).ToString().Trim();
                Countries.Add(r.Trim(',', ' ').Trim());
            }

            foreach (var item in ac)
            {
                Sources.Add(item.Trim());
            }
            Dictionary <string, double> CountryCounter = new Dictionary <string, double>();
            Dictionary <string, double> SourceCounter  = new Dictionary <string, double>();

            foreach (var c in Countries)
            {
                var CountCountry = (from k in Countries where k == c select k).Count();

                double y = ((double)CountCountry / (double)CountryNotNullCount) * 100;
                try
                {
                    CountryCounter.Add(c, Math.Round(y, 2));
                }
                catch (Exception)
                {
                }
            }

            foreach (var c in Sources)
            {
                var    CountCountry = (from k in Sources where k == c select k).Count();
                double y            = ((double)CountCountry / (double)SourceNotNullCount) * 100;
                try
                {
                    SourceCounter.Add(c, Math.Round(y, 2));
                }
                catch (Exception)
                {
                }
            }

            var uCountry = CountryCounter;
            var uSources = SourceCounter.Distinct().Take(10);

            List <string> Finish = new List <string>();

            Finish.Add(JsonConvert.SerializeObject(MaxUser));
            Finish.Add(JsonConvert.SerializeObject(uCountry));
            Finish.Add(JsonConvert.SerializeObject(uSources));
            Finish.Add(JsonConvert.SerializeObject(LDates.Take(100)));

            Finish.Add(JsonConvert.SerializeObject(RetweetSum));
            Finish.Add(JsonConvert.SerializeObject(FavouriteSum));
            Finish.Add(JsonConvert.SerializeObject(tweetsCount));

            var json = JsonConvert.SerializeObject(Finish);

            context.EmitKeyValue(json, i.ToString());
        }
Example #41
0
 // Umbraco.Code.MapAll -CreateDate -UpdateDate -DeleteDate -Key -PropertyTypes
 private static void Map(PropertyGroupBasic <MemberPropertyTypeBasic> source, PropertyGroup target, MapperContext context)
 {
     if (source.Id > 0)
     {
         target.Id = source.Id;
     }
     target.Key       = source.Key;
     target.Type      = source.Type;
     target.Name      = source.Name;
     target.Alias     = source.Alias;
     target.SortOrder = source.SortOrder;
 }
Example #42
0
 // Umbraco.Code.MapAll -Edited -Updater -Alias
 private void Map(IMedia source, ContentItemBasic <ContentPropertyBasic> target, MapperContext context)
 {
     target.ContentTypeId    = source.ContentType.Id;
     target.ContentTypeAlias = source.ContentType.Alias;
     target.CreateDate       = source.CreateDate;
     target.Icon             = source.ContentType.Icon;
     target.Id              = source.Id;
     target.Key             = source.Key;
     target.Name            = source.Name;
     target.Owner           = _commonMapper.GetOwner(source, context);
     target.ParentId        = source.ParentId;
     target.Path            = source.Path;
     target.Properties      = context.MapEnumerable <Property, ContentPropertyBasic>(source.Properties);
     target.SortOrder       = source.SortOrder;
     target.State           = null;
     target.Trashed         = source.Trashed;
     target.Udi             = Udi.Create(Constants.UdiEntityType.Media, source.Key);
     target.UpdateDate      = source.UpdateDate;
     target.VariesByCulture = source.ContentType.VariesByCulture();
 }
Example #43
0
 // no MapAll - take care
 private void Map(MediaTypeSave source, IMediaType target, MapperContext context)
 {
     MapSaveToTypeBase <MediaTypeSave, PropertyTypeBasic>(source, target, context);
     MapComposition(source, target, alias => _mediaTypeService.Get(alias));
 }
Example #44
0
        private IEnumerable <DataTypeConfigurationFieldDisplay> MapPreValues(IDataType dataType, MapperContext context)
        {
            // in v7 it was apparently fine to have an empty .EditorAlias here, in which case we would map onto
            // an empty fields list, which made no sense since there would be nothing to map to - and besides,
            // a datatype without an editor alias is a serious issue - v8 wants an editor here

            if (string.IsNullOrWhiteSpace(dataType.EditorAlias) || !_propertyEditors.TryGet(dataType.EditorAlias, out var editor))
            {
                throw new InvalidOperationException($"Could not find a property editor with alias \"{dataType.EditorAlias}\".");
            }

            var configurationEditor = editor.GetConfigurationEditor();
            var fields = context.MapEnumerable <ConfigurationField, DataTypeConfigurationFieldDisplay>(configurationEditor.Fields);
            var configurationDictionary = configurationEditor.ToConfigurationEditor(dataType.Configuration);

            MapConfigurationFields(dataType, fields, configurationDictionary);

            return(fields);
        }
Example #45
0
 // no MapAll - uses the IContentTypeBase map method, which has MapAll
 private void Map(IMemberType source, ContentTypeBasic target, MapperContext context) =>
 Map(source, target, Constants.UdiEntityType.MemberType);
Example #46
0
 // Umbraco.Code.MapAll
 private static void Map(IDataEditor source, PropertyEditorBasic target, MapperContext context)
 {
     target.Alias = source.Alias;
     target.Icon  = source.Icon;
     target.Name  = source.Name;
 }
Example #47
0
 // no MapAll - take care
 private void Map(MemberTypeSave source, MemberTypeDisplay target, MapperContext context) =>
 MapTypeToDisplayBase <MemberTypeSave, MemberPropertyTypeBasic, MemberTypeDisplay, MemberPropertyTypeDisplay>(
     source, target, context);
Example #48
0
 public PlanTargetSelector(MapperContext mapperContext, IQueryable <TSource> exampleQueryable)
     : this(mapperContext)
 {
     _exampleQueryable = exampleQueryable;
 }
Example #49
0
        // Umbraco.Code.MapAll -ContentTypeId -ParentTabContentTypes -ParentTabContentTypeNames
        private static void Map(PropertyGroupBasic <MemberPropertyTypeBasic> source,
                                PropertyGroupDisplay <MemberPropertyTypeDisplay> target, MapperContext context)
        {
            target.Inherited = source.Inherited;
            if (source.Id > 0)
            {
                target.Id = source.Id;
            }

            target.Key        = source.Key;
            target.Type       = source.Type;
            target.Name       = source.Name;
            target.Alias      = source.Alias;
            target.SortOrder  = source.SortOrder;
            target.Properties =
                context.MapEnumerable <MemberPropertyTypeBasic, MemberPropertyTypeDisplay>(source.Properties);
        }
        public override void Map(IProperty originalProp, ContentPropertyDisplay dest, MapperContext context)
        {
            base.Map(originalProp, dest, context);

            var config = DataTypeService.GetDataType(originalProp.PropertyType.DataTypeId).Configuration;

            // TODO: IDataValueEditor configuration - general issue
            // GetValueEditor() returns a non-configured IDataValueEditor
            // - for richtext and nested, configuration determines HideLabel, so we need to configure the value editor
            // - could configuration also determines ValueType, everywhere?
            // - does it make any sense to use a IDataValueEditor without configuring it?

            // configure the editor for display with configuration
            var valEditor = dest.PropertyEditor.GetValueEditor(config);

            //set the display properties after mapping
            dest.Alias       = originalProp.Alias;
            dest.Description = originalProp.PropertyType.Description;
            dest.Label       = originalProp.PropertyType.Name;
            dest.HideLabel   = valEditor.HideLabel;
            dest.LabelOnTop  = originalProp.PropertyType.LabelOnTop;

            //add the validation information
            dest.Validation.Mandatory        = originalProp.PropertyType.Mandatory;
            dest.Validation.MandatoryMessage = originalProp.PropertyType.MandatoryMessage;
            dest.Validation.Pattern          = originalProp.PropertyType.ValidationRegExp;
            dest.Validation.PatternMessage   = originalProp.PropertyType.ValidationRegExpMessage;

            if (dest.PropertyEditor == null)
            {
                //display.Config = PreValueCollection.AsDictionary(preVals);
                //if there is no property editor it means that it is a legacy data type
                // we cannot support editing with that so we'll just render the readonly value view.
                dest.View = "views/propertyeditors/readonlyvalue/readonlyvalue.html";
            }
            else
            {
                //let the property editor format the pre-values
                dest.Config = dest.PropertyEditor.GetConfigurationEditor().ToValueEditor(config);
                dest.View   = valEditor.View;
            }

            //Translate
            dest.Label       = _textService.UmbracoDictionaryTranslate(_cultureDictionary, dest.Label);
            dest.Description = _textService.UmbracoDictionaryTranslate(_cultureDictionary, dest.Description);
        }
Example #51
0
 // Umbraco.Code.MapAll -Editor -View -Config -ContentTypeId -ContentTypeName -Locked -DataTypeIcon -DataTypeName
 private static void Map(MemberPropertyTypeBasic source, MemberPropertyTypeDisplay target, MapperContext context)
 {
     target.Alias = source.Alias;
     target.AllowCultureVariant = source.AllowCultureVariant;
     target.AllowSegmentVariant = source.AllowSegmentVariant;
     target.DataTypeId          = source.DataTypeId;
     target.DataTypeKey         = source.DataTypeKey;
     target.Description         = source.Description;
     target.GroupId             = source.GroupId;
     target.Id                    = source.Id;
     target.Inherited             = source.Inherited;
     target.IsSensitiveData       = source.IsSensitiveData;
     target.Label                 = source.Label;
     target.MemberCanEditProperty = source.MemberCanEditProperty;
     target.MemberCanViewProperty = source.MemberCanViewProperty;
     target.SortOrder             = source.SortOrder;
     target.Validation            = source.Validation;
     target.LabelOnTop            = source.LabelOnTop;
 }
Example #52
0
        private DateTime?GetScheduledDate(IContent source, ContentScheduleAction action, MapperContext context)
        {
            var culture  = context.GetCulture() ?? string.Empty;
            var schedule = source.ContentSchedule.GetSchedule(culture, action);

            return(schedule.FirstOrDefault()?.Date); // take the first, it's ordered by date
        }
Example #53
0
        // Umbraco.Code.MapAll -CreatorId -Level -SortOrder -Variations
        // Umbraco.Code.MapAll -CreateDate -UpdateDate -DeleteDate
        // Umbraco.Code.MapAll -ContentTypeComposition (done by AfterMapSaveToType)
        private static void MapSaveToTypeBase <TSource, TSourcePropertyType>(TSource source,
                                                                             IContentTypeComposition target, MapperContext context)
            where TSource : ContentTypeSave <TSourcePropertyType>
            where TSourcePropertyType : PropertyTypeBasic
        {
            // TODO: not so clean really
            var isPublishing = target is IContentType;

            var id = Convert.ToInt32(source.Id);

            if (id > 0)
            {
                target.Id = id;
            }

            target.Alias       = source.Alias;
            target.Description = source.Description;
            target.Icon        = source.Icon;
            target.IsContainer = source.IsContainer;
            target.IsElement   = source.IsElement;
            target.Key         = source.Key;
            target.Name        = source.Name;
            target.ParentId    = source.ParentId;
            target.Path        = source.Path;
            target.Thumbnail   = source.Thumbnail;

            target.AllowedAsRoot       = source.AllowAsRoot;
            target.AllowedContentTypes = source.AllowedContentTypes.Select((t, i) => new ContentTypeSort(t, i));

            if (!(target is IMemberType))
            {
                target.SetVariesBy(ContentVariation.Culture, source.AllowCultureVariant);
                target.SetVariesBy(ContentVariation.Segment, source.AllowSegmentVariant);
            }

            // handle property groups and property types
            // note that ContentTypeSave has
            // - all groups, inherited and local; only *one* occurrence per group *name*
            // - potentially including the generic properties group
            // - all properties, inherited and local
            //
            // also, see PropertyTypeGroupResolver.ResolveCore:
            // - if a group is local *and* inherited, then Inherited is true
            //   and the identifier is the identifier of the *local* group
            //
            // IContentTypeComposition AddPropertyGroup, AddPropertyType methods do some
            // unique-alias-checking, etc that is *not* compatible with re-mapping everything
            // the way we do it here, so we should exclusively do it by
            // - managing a property group's PropertyTypes collection
            // - managing the content type's PropertyTypes collection (for generic properties)

            // handle actual groups (non-generic-properties)
            PropertyGroup[] destOrigGroups     = target.PropertyGroups.ToArray(); // local groups
            IPropertyType[] destOrigProperties = target.PropertyTypes.ToArray();  // all properties, in groups or not
            var             destGroups         = new List <PropertyGroup>();

            PropertyGroupBasic <TSourcePropertyType>[] sourceGroups =
                source.Groups.Where(x => x.IsGenericProperties == false).ToArray();
            var sourceGroupParentAliases = sourceGroups.Select(x => x.GetParentAlias()).Distinct().ToArray();

            foreach (PropertyGroupBasic <TSourcePropertyType> sourceGroup in sourceGroups)
            {
                // get the dest group
                PropertyGroup destGroup = MapSaveGroup(sourceGroup, destOrigGroups, context);

                // handle local properties
                IPropertyType[] destProperties = sourceGroup.Properties
                                                 .Where(x => x.Inherited == false)
                                                 .Select(x => MapSaveProperty(x, destOrigProperties, context))
                                                 .ToArray();

                // if the group has no local properties and is not used as parent, skip it, ie sort-of garbage-collect
                // local groups which would not have local properties anymore
                if (destProperties.Length == 0 && !sourceGroupParentAliases.Contains(sourceGroup.Alias))
                {
                    continue;
                }

                // ensure no duplicate alias, then assign the group properties collection
                EnsureUniqueAliases(destProperties);
                destGroup.PropertyTypes = new PropertyTypeCollection(isPublishing, destProperties);
                destGroups.Add(destGroup);
            }

            // ensure no duplicate name, then assign the groups collection
            EnsureUniqueAliases(destGroups);
            target.PropertyGroups = new PropertyGroupCollection(destGroups);

            // because the property groups collection was rebuilt, there is no need to remove
            // the old groups - they are just gone and will be cleared by the repository

            // handle non-grouped (ie generic) properties
            PropertyGroupBasic <TSourcePropertyType> genericPropertiesGroup =
                source.Groups.FirstOrDefault(x => x.IsGenericProperties);

            if (genericPropertiesGroup != null)
            {
                // handle local properties
                IPropertyType[] destProperties = genericPropertiesGroup.Properties
                                                 .Where(x => x.Inherited == false)
                                                 .Select(x => MapSaveProperty(x, destOrigProperties, context))
                                                 .ToArray();

                // ensure no duplicate alias, then assign the generic properties collection
                EnsureUniqueAliases(destProperties);
                target.NoGroupPropertyTypes = new PropertyTypeCollection(isPublishing, destProperties);
            }

            // because all property collections were rebuilt, there is no need to remove
            // some old properties, they are just gone and will be cleared by the repository
        }
Example #54
0
 // no MapAll - uses the IContentTypeBase map method, which has MapAll
 private static void Map(IMediaType source, ContentTypeBasic target, MapperContext context)
 {
     Map(source, target, Constants.UdiEntityType.MediaType);
 }
Example #55
0
        public override void Map(string inputLine, MapperContext context)
        {
            var PROCESSED_YEAR = 2007;

            var data = ExtractValueFromLine(inputLine);
            if (data.CountryName == "Country Name")
            {
                return;
            }
            if (data.YearValues.ContainsKey(PROCESSED_YEAR))
            {
                var trend = ComputeTrend(data.YearValues, PROCESSED_YEAR);

                context.EmitKeyValue(data.IndicatorCode, data.CountryCode + '\t' + data.CountryName + '\t' + trend + '\t' + data.YearValues[PROCESSED_YEAR]);

            }

        }