private async Task AddressMessageAsync(Message message, PlacementTarget target, PlacementStrategy strategy, ActivationAddress targetAddress) { var placementResult = await placementDirectorsManager.SelectOrAddActivation( message.SendingAddress, target, this.catalog, strategy); SetMessageTargetPlacement(message, placementResult, targetAddress); }
public Task <SiloAddress> OnAddActivation(PlacementStrategy strategy, PlacementTarget target, IPlacementContext context) { var silos = context.GetCompatibleSilos(target).OrderBy(x => x).ToArray(); if (Constants.DefaultNumGrainsInOneLayer == 0) { Constants.DefaultNumGrainsInOneLayer = 2 * (silos.Length - 1); } var targetSilo = RequestContext.Get("targetSilo"); if (targetSilo != null) { foreach (SiloAddress silo in silos) { if (silo.Endpoint.Address.ToString().Equals(targetSilo)) { return(Task.FromResult(silo)); } } } var excludeSilo = RequestContext.Get("excludeSilo"); if (excludeSilo != null) { silos = silos.Where(x => !x.Endpoint.Address.ToString().Equals(excludeSilo)).ToArray(); } object index = RequestContext.Get("grainIndex"); if (index == null) { index = new Random().Next(0, silos.Count()); } return(Task.FromResult(silos[(int)index % silos.Count()])); }
private CustomPopupPlacement[] ComboBoxCustomPopupPlacementCallback( Size popupSize, Size targetSize, Point offset) { var visualAncestry = PlacementTarget.GetVisualAncestry().ToList(); SetupBackground(visualAncestry); SetupVisiblePlacementWidth(visualAncestry); var data = GetPositioningData(visualAncestry, popupSize, targetSize, offset); var preferUpIfSafe = data.LocationY + data.PopupSize.Height > data.ScreenHeight; if (ClassicMode || data.LocationX + data.PopupSize.Width - data.RealOffsetX > data.ScreenWidth || data.LocationX - data.RealOffsetX < 0 || !preferUpIfSafe && data.LocationY - Math.Abs(data.NewDownY) < 0) { SetCurrentValue(PopupPlacementProperty, ComboBoxPopupPlacement.Classic); return(new[] { GetClassicPopupPlacement(this, data) }); } if (preferUpIfSafe) { SetCurrentValue(PopupPlacementProperty, ComboBoxPopupPlacement.Up); return(new[] { GetUpPopupPlacement(data) }); } SetCurrentValue(PopupPlacementProperty, ComboBoxPopupPlacement.Down); return(new[] { GetDownPopupPlacement(data) }); }
public Task <SiloAddress> OnAddActivation(PlacementStrategy strategy, PlacementTarget target, IPlacementContext context) { if (unusedSilos.Count == 0 && usedSilos.Count == 0) { var silos = context.GetCompatibleSilos(target).OrderBy(x => x).ToArray(); foreach (var siloAddress in silos) { unusedSilos.Enqueue(siloAddress); } } if (unusedSilos.Count == 0 && usedSilos.Count > 0) { //check if all usedSilos are compatible //var additionalSilos = context.GetCompatibleSilos(target).OrderBy(x => x).ToArray(); unusedSilos = new ConcurrentQueue <SiloAddress>(usedSilos); usedSilos = new ConcurrentQueue <SiloAddress>(); } //TODO: check if siloAddres is still compatible SiloAddress nextSiloAddress = null; unusedSilos.TryDequeue(out nextSiloAddress); if (nextSiloAddress == null) { throw new ArgumentNullException("Couldn't find a compatible silo for grain"); } usedSilos.Enqueue(nextSiloAddress); return(Task.FromResult(nextSiloAddress)); }
/// <summary> /// Resolve target address for a message /// - use transaction info /// - check ordering info in message and sending activation /// - use sender's placement strategy /// </summary> /// <param name="message"></param> /// <returns>Resolve when message is addressed (modifies message fields)</returns> private Task AddressMessage(Message message) { var targetAddress = message.TargetAddress; if (targetAddress is null) { throw new InvalidOperationException("Cannot address a message with a null TargetAddress"); } if (targetAddress.IsComplete) { return(Task.CompletedTask); } var target = new PlacementTarget( message.TargetGrain, message.RequestContextData, message.InterfaceType, message.InterfaceVersion); var placementTask = placementService.GetOrPlaceActivation(target, this.catalog); if (placementTask.IsCompletedSuccessfully) { SetMessageTargetPlacement(message, placementTask.Result, targetAddress); return(Task.CompletedTask); } return(AddressMessageAsync(placementTask)); async Task AddressMessageAsync(ValueTask <PlacementResult> addressTask) { SetMessageTargetPlacement(message, await addressTask, targetAddress); } }
private void LoadPlacements(DeliveryFile file, string[] headers, FileCompression compression = FileCompression.Gzip) { if (file == null) { throw new ArgumentException("Placement delivery file does not exist"); } _placementsCache.Clear(); using (var placementsReader = new CsvDynamicReader(file.OpenContents(compression: compression), headers)) { Mappings.OnFieldRequired = fieldName => placementsReader.Current[fieldName]; placementsReader.MatchExactColumns = false; while (placementsReader.Read()) { if (placementsReader.Current[AdWordsConst.PlacementIdFieldName] == AdWordsConst.EOF) { break; } var placementPrimaryKey = new KeywordPrimaryKey { KeywordId = Convert.ToInt64(placementsReader.Current[AdWordsConst.PlacementIdFieldName]), AdgroupId = Convert.ToInt64(placementsReader.Current[AdWordsConst.AdGroupIdFieldName]), CampaignId = Convert.ToInt64(placementsReader.Current[AdWordsConst.CampaignIdFieldName]) }; var placement = new PlacementTarget(); PlacementMappings.Apply(placement); _placementsCache.Add(placementPrimaryKey.ToString(), placement); } } }
/// <summary> /// Resolve target address for a message /// - use transaction info /// - check ordering info in message and sending activation /// - use sender's placement strategy /// </summary> /// <param name="message"></param> /// <returns>Resolve when message is addressed (modifies message fields)</returns> private Task AddressMessage(Message message) { var targetAddress = message.TargetAddress; if (targetAddress.IsComplete) { return(Task.CompletedTask); } var request = message.IsUsingInterfaceVersions ? message.BodyObject as InvokeMethodRequest : null; var target = new PlacementTarget( message.TargetGrain, message.RequestContextData, request?.InterfaceId ?? 0, request?.InterfaceVersion ?? 0); var placementTask = placementService.GetOrPlaceActivation(target, this.catalog); if (placementTask.IsCompletedSuccessfully) { SetMessageTargetPlacement(message, placementTask.Result, targetAddress); return(Task.CompletedTask); } return(AddressMessageAsync(placementTask)); async Task AddressMessageAsync(ValueTask <PlacementResult> addressTask) { SetMessageTargetPlacement(message, await addressTask, targetAddress); } }
/// <summary> /// Resolve target address for a message /// - use transaction info /// - check ordering info in message and sending activation /// - use sender's placement strategy /// </summary> /// <param name="message"></param> /// <returns>Resolve when message is addressed (modifies message fields)</returns> private Task AddressMessage(Message message) { var targetAddress = message.TargetAddress; if (targetAddress.IsComplete) { return(Task.CompletedTask); } // placement strategy is determined by searching for a specification. first, we check for a strategy associated with the grain reference, // second, we check for a strategy associated with the target's interface. third, we check for a strategy associated with the activation sending the // message. var strategy = targetAddress.Grain.IsGrain ? catalog.GetGrainPlacementStrategy(targetAddress.Grain) : null; var request = message.IsUsingInterfaceVersions ? message.BodyObject as InvokeMethodRequest : null; var target = new PlacementTarget( message.TargetGrain, message.RequestContextData, request?.InterfaceId ?? 0, request?.InterfaceVersion ?? 0); PlacementResult placementResult; if (placementDirectorsManager.TrySelectActivationSynchronously( message.SendingAddress, target, this.catalog, strategy, out placementResult) && placementResult != null) { SetMessageTargetPlacement(message, placementResult, targetAddress); return(Task.CompletedTask); } return(AddressMessageAsync(message, target, strategy, targetAddress)); }
private CustomPopupPlacement[] ComboBoxCustomPopupPlacementCallback( Size popupSize, Size targetSize, Point offset) { var visualAncestry = PlacementTarget.GetVisualAncestry().ToList(); SetupBackground(visualAncestry); SetupVisiblePlacementWidth(visualAncestry); var data = GetPositioningData(visualAncestry, popupSize, targetSize, offset); if (ClassicMode || (data.LocationX + data.PopupSize.Width - data.RealOffsetX > data.ScreenWidth || data.LocationX - data.RealOffsetX < 0)) { PopupPlacement = ComboBoxPopupPlacement.Classic; return(new[] { GetClassicPopupPlacement(this, data) }); } else if (data.LocationY + data.PopupSize.Height > data.ScreenHeight) { PopupPlacement = ComboBoxPopupPlacement.Up; return(new[] { GetUpPopupPlacement(this, data) }); } else { PopupPlacement = ComboBoxPopupPlacement.Down; return(new[] { GetDownPopupPlacement(this, data) }); } }
public Task <SiloAddress> OnAddActivation(PlacementStrategy strategy, PlacementTarget target, IPlacementContext context) { SiloAddress[] silos; if (target.InterfaceVersion == 0) { silos = context.GetCompatibleSilos(target); } else { var silosByVersion = context.GetCompatibleSilosWithVersions(target); var maxSiloCount = 0; ushort version = 0; foreach (var kvp in silosByVersion) { if (kvp.Value.Length > maxSiloCount) { version = kvp.Key; maxSiloCount = kvp.Value.Length; } } silos = silosByVersion[version]; } return(Task.FromResult(silos[random.Next(silos.Length)])); }
void Liste_SelectionChanged(Object sender, SelectionChangedEventArgs e) { Liste.SelectionChanged -= Liste_SelectionChanged; OnSelecting(); PlacementTarget.Focus(); _tb.Focus(); }
/// <summary> /// 处理方向定置 /// </summary> private void DealDirectionPosion() { var popPoint = PointToScreen(new Point(0, 0)); //弹出面板屏幕坐标位置 var targetPoint = PlacementTarget.PointToScreen(new Point(0, 0)); //目标控件屏幕坐标位置 if (Placement == PlacementMode.Top || Placement == PlacementMode.Bottom) { this.HorizontalOffset = 0 - (this.RenderSize.Width - this.PlacementTarget.RenderSize.Width) / 2; //水平居中 if (this.Placement == PlacementMode.Top) { if (popPoint.Y < targetPoint.Y) { this.Direction = Dock.Bottom; } else { this.Direction = Dock.Top; } } else if (this.Placement == PlacementMode.Bottom) { if (popPoint.Y > targetPoint.Y) { this.Direction = Dock.Top; } else { this.Direction = Dock.Bottom; } } } else if (Placement == PlacementMode.Left || Placement == PlacementMode.Right) { this.VerticalOffset = 0 - (this.RenderSize.Height - this.PlacementTarget.RenderSize.Height) / 2; //垂直居中 if (this.Placement == PlacementMode.Left) { if (popPoint.X > targetPoint.X) { this.Direction = Dock.Left; } else { this.Direction = Dock.Right; } } if (this.Placement == PlacementMode.Right) { if (popPoint.X < targetPoint.X) { this.Direction = Dock.Right; } else { this.Direction = Dock.Left; } } } }
public static ActorPlacementRequest From(PlacementTarget target) { var @interface = ActorType.Of(target.GrainIdentity.TypeCode).Interface; var id = target.GrainIdentity.PrimaryKeyString; var path = new ActorPath(@interface.Name, id); return(new ActorPlacementRequest(path, @interface.Mapping)); }
/// <summary> /// Opens the popup. /// </summary> public void Open() { if (_popupRoot == null) { _popupRoot = new PopupRoot(DependencyResolver) { [~ContentControl.ContentProperty] = this[~ChildProperty], [~WidthProperty] = this[~WidthProperty], [~HeightProperty] = this[~HeightProperty], [~MinWidthProperty] = this[~MinWidthProperty], [~MaxWidthProperty] = this[~MaxWidthProperty], [~MinHeightProperty] = this[~MinHeightProperty], [~MaxHeightProperty] = this[~MaxHeightProperty], }; ((ISetLogicalParent)_popupRoot).SetParent(this); } _popupRoot.Position = GetPosition(); if (_topLevel == null && PlacementTarget != null) { _topLevel = PlacementTarget.GetSelfAndLogicalAncestors().First(x => x is TopLevel) as TopLevel; } if (_topLevel != null) { var window = _topLevel as Window; if (window != null) { window.Deactivated += WindowDeactivated; } else { var parentPopuproot = _topLevel as PopupRoot; if (parentPopuproot != null && parentPopuproot.Parent != null) { ((Popup)(parentPopuproot.Parent)).Closed += ParentClosed; } } _topLevel.AddHandler(PointerPressedEvent, PointerPressedOutside, RoutingStrategies.Tunnel); _nonClientListener = InputManager.Instance.Process.Subscribe(ListenForNonClientClick); } PopupRootCreated?.Invoke(this, EventArgs.Empty); _popupRoot.Show(); _ignoreIsOpenChanged = true; IsOpen = true; _ignoreIsOpenChanged = false; Opened?.Invoke(this, EventArgs.Empty); }
private CustomPopupPlacement[] ComboBoxCustomPopupPlacementCallback(Size popupSize, Size targetSize, Point offset) { var locationFromScreen = this.PlacementTarget.PointToScreen(new Point(0, 0)); var mainVisual = PlacementTarget.GetVisualAncestry().OfType <System.Windows.Media.Visual>().LastOrDefault(); if (mainVisual == null) { return(new CustomPopupPlacement[0]); } var screenWidth = (int)DpiHelper.TransformToDeviceX(mainVisual, SystemParameters.PrimaryScreenWidth); var screenHeight = (int)DpiHelper.TransformToDeviceY(mainVisual, SystemParameters.PrimaryScreenHeight); var locationX = (int)locationFromScreen.X % screenWidth; var locationY = (int)locationFromScreen.Y % screenHeight; var realOffsetX = (popupSize.Width - targetSize.Width) / 2.0; var offsetX = DpiHelper.TransformToDeviceX(mainVisual, offset.X); var defaultVerticalOffsetIndepent = DpiHelper.TransformToDeviceY(mainVisual, DefaultVerticalOffset); var upVerticalOffsetIndepent = DpiHelper.TransformToDeviceY(mainVisual, UpVerticalOffset); var downVerticalOffsetIndepent = DpiHelper.TransformToDeviceY(mainVisual, DownVerticalOffset); if (locationX + popupSize.Width - realOffsetX > screenWidth || locationX + realOffsetX < 0) { SetChildTemplateIfNeed(DefaultContentTemplate); var newY = locationY + popupSize.Height > screenHeight ? -(defaultVerticalOffsetIndepent + popupSize.Height) : defaultVerticalOffsetIndepent + targetSize.Height; return(new[] { new CustomPopupPlacement(new Point(offsetX, newY), PopupPrimaryAxis.Horizontal) }); } if (locationY + popupSize.Height > screenHeight) { SetChildTemplateIfNeed(UpContentTemplate); var newY = upVerticalOffsetIndepent - popupSize.Height + targetSize.Height; return(new[] { new CustomPopupPlacement(new Point(offsetX, newY), PopupPrimaryAxis.None) }); } else { SetChildTemplateIfNeed(DownContentTemplate); var newY = downVerticalOffsetIndepent; return(new[] { new CustomPopupPlacement(new Point(offsetX, newY), PopupPrimaryAxis.None) }); } }
/// <summary> /// Translates the location. /// </summary> private void TranslateLocation() { var rootWindow = Application.Current.MainWindow; var placementTransform = PlacementTarget.TransformToAncestor(rootWindow); var popupTransform = this.TransformToAncestor(rootWindow); var placementPoint = placementTransform.Transform(new Point(0, 0)); var popupPoint = placementTransform.Transform(new Point(0, 0)); var translateTransform = new TranslateTransform(placementPoint.X - popupPoint.X, placementPoint.Y - popupPoint.Y); RenderTransform = translateTransform; }
public Task <SiloAddress> OnAddActivation(PlacementStrategy strategy, PlacementTarget target, IPlacementContext context) { var silos = context.GetCompatibleSilos(target).OrderBy(s => s).ToArray(); //尽量把每一个隔开 long grainid = target.GrainIdentity.PrimaryKeyLong; if (silos.Length > grainid) { return(Task.FromResult(silos[grainid])); } else { return(Task.FromResult(silos[random.Next(silos.Length)])); } }
public Task <SiloAddress> OnAddActivation(PlacementStrategy strategy, PlacementTarget target, IPlacementContext context) { var silos = context.GetCompatibleSilos(target).OrderBy(s => s).ToArray(); var oddTick = DateTime.UtcNow.Ticks % 2 == 1; switch (((TestCustomPlacementStrategy)strategy).Scenario) { case CustomPlacementScenario.FixedSilo: return(Task.FromResult(silos[silos.Length - 2])); // second from last silos. case CustomPlacementScenario.ExcludeOne: return(Task.FromResult(oddTick ? silos[0] : silos[silos.Length - 1])); // randomly return first or last silos default: throw new InvalidOperationException(); // should never get here, only to make compiler happy } }
private void AddMeta() { var item = new MenuItem { Header = "Set Metadata" }; item.Click += delegate { var prefabTile = PlacementTarget as PrefabTile; if (prefabTile == null) { return; } var tileData = prefabTile.DataContext as PrefabTileData; if (tileData == null) { return; } tileData.Metadata = SetMetadata.GetString(tileData.Metadata); }; AddChild(item); item = new MenuItem { Header = "Pull Value" }; item.Click += delegate { var prefabTile = PlacementTarget as PrefabTile; if (prefabTile == null) { return; } var room = PlacementTarget.GetParent <PrefabRoom>(); ((PrefabTileData)room.PaintTile.DataContext).Reassign(prefabTile.DataContext as PrefabTileData); if (room.HasFile()) { room.Save(); } }; AddChild(item); }
private void SetPosition() { GeneralTransform objGeneralTransform = PlacementTarget.TransformToVisual(Application.Current.RootVisual); Point point = objGeneralTransform.Transform(new Point(0, 0)); Rect rcElement = new Rect(point, PlacementTarget.RenderSize); _popup.HorizontalOffset = rcElement.Left; switch (Placement) { case PlacementMode.Bottom: _popup.VerticalOffset = rcElement.Top + rcElement.Height; break; case PlacementMode.Top: _popup.Child.UpdateLayout(); _popup.VerticalOffset = rcElement.Top - _popup.Child.RenderSize.Height; break; } }
private PositioningData GetPositioningData(IEnumerable <DependencyObject> visualAncestry, Size popupSize, Size targetSize, Point offset) { var locationFromScreen = PlacementTarget.PointToScreen(new Point(0, 0)); var mainVisual = visualAncestry.OfType <Visual>().LastOrDefault(); if (mainVisual == null) { throw new ArgumentException($"{nameof(visualAncestry)} must contains unless one {nameof(Visual)} control inside."); } var screen = Screen.FromPoint(locationFromScreen); var screenWidth = (int)DpiHelper.TransformToDeviceX(mainVisual, (int)screen.Bounds.Width); var screenHeight = (int)DpiHelper.TransformToDeviceY(mainVisual, (int)screen.Bounds.Height); //Adjust the location to be in terms of the current screen var locationX = (int)(locationFromScreen.X - screen.Bounds.X) % screenWidth; var locationY = (int)(locationFromScreen.Y - screen.Bounds.Y) % screenHeight; var upVerticalOffsetIndepent = DpiHelper.TransformToDeviceY(mainVisual, UpVerticalOffset); var newUpY = upVerticalOffsetIndepent - popupSize.Height + targetSize.Height; var newDownY = DpiHelper.TransformToDeviceY(mainVisual, DownVerticalOffset); double offsetX; const int rtlHorizontalOffset = 20; if (FlowDirection == FlowDirection.LeftToRight) { offsetX = DpiHelper.TransformToDeviceX(mainVisual, offset.X); } else { offsetX = DpiHelper.TransformToDeviceX(mainVisual, offset.X - targetSize.Width - rtlHorizontalOffset); } return(new PositioningData( mainVisual, offsetX, newUpY, newDownY, popupSize, targetSize, locationX, locationY, screenHeight, screenWidth)); }
//TODO: get rid of dead activations. Somehow. public virtual Task <SiloAddress> OnAddActivation( PlacementStrategy strategy, PlacementTarget target, IPlacementContext context) { var allSilos = context.GetCompatibleSilos(target); var incompatibleSilos = new List <SiloAddress>(); SiloAddress leastLoadedSilo = GetLeastLoadedCompatibleSilo(allSilos, incompatibleSilos); //Remove incompatible silos int value = 0; foreach (var silo in incompatibleSilos) { siloCache.TryRemove(silo, out value); } UpdateCache(leastLoadedSilo); return(Task.FromResult(leastLoadedSilo)); }
void _Close(bool ok, RoutedEventArgs e) { e.Handled = true; IsOpen = false; //SHOULDDO: bad in InfoWindow, with or without this, even if Focusable false and no Focus(). // Also Esc does not work there. // ContextMenu works, except keys (Esc, Arrows, etc). // Classic menu perfect. PlacementTarget?.Focus(); if (ok) { var v = _lb.SelectedItem; if (v != null) { OK?.Invoke(v); } } }
public async Task <SiloAddress> OnAddActivation(PlacementStrategy strategy, PlacementTarget target, IPlacementContext context) { Task <SiloAddress> fromHolder = grainFactory.GetGrain <IPlacementHolder>(target.GrainIdentity.PrimaryKey).GetSiloAddress( target.GrainIdentity.TypeCode); var compatibleSilos = context.GetCompatibleSilos(target); Random random = new Random(); SiloAddress randomSilo = compatibleSilos[random.Next(compatibleSilos.Count)]; SiloAddress holderSilo = await fromHolder; if (holderSilo == null) { return(randomSilo); } else { return(holderSilo); } }
/// <summary> /// Opens the popup. /// </summary> public void Open() { if (_popupRoot == null) { _popupRoot = new PopupRoot(DependencyResolver) { [~ContentControl.ContentProperty] = this[~ChildProperty], [~WidthProperty] = this[~WidthProperty], [~HeightProperty] = this[~HeightProperty], [~MinWidthProperty] = this[~MinWidthProperty], [~MaxWidthProperty] = this[~MaxWidthProperty], [~MinHeightProperty] = this[~MinHeightProperty], [~MaxHeightProperty] = this[~MaxHeightProperty], }; ((ISetLogicalParent)_popupRoot).SetParent(this); } _popupRoot.Position = GetPosition(); if (_topLevel == null && PlacementTarget != null) { _topLevel = PlacementTarget.GetSelfAndLogicalAncestors().First(x => x is TopLevel) as TopLevel; } if (_topLevel != null) { _topLevel.Deactivated += TopLevelDeactivated; _topLevel.AddHandler(PointerPressedEvent, PointerPressedOutside, RoutingStrategies.Tunnel); } PopupRootCreated?.Invoke(this, EventArgs.Empty); _popupRoot.Show(); IsOpen = true; Opened?.Invoke(this, EventArgs.Empty); }
private PositioningData GetPositioningData(IEnumerable <DependencyObject> visualAncestry, Size popupSize, Size targetSize, Point offset) { var locationFromScreen = PlacementTarget.PointToScreen(new Point(0, 0)); var mainVisual = visualAncestry.OfType <Visual>().LastOrDefault(); if (mainVisual == null) { throw new ArgumentException($"{nameof(visualAncestry)} must contains unless one {nameof(Visual)} control inside."); } var screenWidth = (int)DpiHelper.TransformToDeviceX(mainVisual, SystemParameters.PrimaryScreenWidth); var screenHeight = (int)DpiHelper.TransformToDeviceY(mainVisual, SystemParameters.PrimaryScreenHeight); var locationX = (int)locationFromScreen.X % screenWidth; var locationY = (int)locationFromScreen.Y % screenHeight; double offsetX; const int rtlHorizontalOffset = 20; if (FlowDirection == FlowDirection.LeftToRight) { offsetX = DpiHelper.TransformToDeviceX(mainVisual, offset.X); } else { offsetX = DpiHelper.TransformToDeviceX(mainVisual, offset.X - targetSize.Width - rtlHorizontalOffset); } return(new PositioningData( mainVisual, offsetX, popupSize, targetSize, locationX, locationY, screenHeight, screenWidth)); }
/// <summary> /// Resolve target address for a message /// - use transaction info /// - check ordering info in message and sending activation /// - use sender's placement strategy /// </summary> /// <param name="message"></param> /// <returns>Resolve when message is addressed (modifies message fields)</returns> private async Task AddressMessage(Message message) { var targetAddress = message.TargetAddress; if (targetAddress.IsComplete) { return; } // placement strategy is determined by searching for a specification. first, we check for a strategy associated with the grain reference, // second, we check for a strategy associated with the target's interface. third, we check for a strategy associated with the activation sending the // message. var strategy = targetAddress.Grain.IsGrain ? catalog.GetGrainPlacementStrategy(targetAddress.Grain) : null; var request = message.IsUsingInterfaceVersions ? message.GetDeserializedBody(this.serializationManager) as InvokeMethodRequest : null; var target = new PlacementTarget(message.TargetGrain, request?.InterfaceId ?? 0, request?.InterfaceVersion ?? 0); var placementResult = await this.placementDirectorsManager.SelectOrAddActivation( message.SendingAddress, target, this.catalog, strategy); if (placementResult.IsNewPlacement && targetAddress.Grain.IsClient) { logger.Error(ErrorCode.Dispatcher_AddressMsg_UnregisteredClient, String.Format("AddressMessage could not find target for client pseudo-grain {0}", message)); throw new KeyNotFoundException(String.Format("Attempting to send a message {0} to an unregistered client pseudo-grain {1}", message, targetAddress.Grain)); } message.SetTargetPlacement(placementResult); if (placementResult.IsNewPlacement) { CounterStatistic.FindOrCreate(StatisticNames.DISPATCHER_NEW_PLACEMENT).Increment(); } if (logger.IsVerbose2) { logger.Verbose2(ErrorCode.Dispatcher_AddressMsg_SelectTarget, "AddressMessage Placement SelectTarget {0}", message); } }
private void SetPosition() { if (PopupLayer != null && IsOpen) { popupContainer.Measure(PopupLayer.VisualSize); Size popupSize = popupContainer.DesiredSize; Rect placementTargetRect = PlacementTarget != null ? new Rect(PopupLayer.PointFromRoot(PlacementTarget.PointToRoot(Point.Zero)), PlacementTarget.VisualSize) : Rect.Zero; Point position = System.Windows.Controls.Primitives.Placement.GetPosition(Placement, placementTargetRect, PlacementRectangle, GetMouseBounds(), new Point(HorizontalOffset, VerticalOffset), popupSize, new Rect(PopupLayer.VisualSize)); popupContainer.Position = position; PopupLayer.UpdateLayout(); } }
private CustomPopupPlacement[] ComboBoxCustomPopupPlacementCallback( Size popupSize, Size targetSize, Point offset) { var visualAncestry = PlacementTarget.GetVisualAncestry().ToList(); SetupBackground(visualAncestry); SetupVisiblePlacementWidth(visualAncestry); var locationFromScreen = PlacementTarget.PointToScreen(new Point(0, 0)); var mainVisual = visualAncestry.OfType <Visual>().LastOrDefault(); if (mainVisual == null) { return(new CustomPopupPlacement[0]); } var screenWidth = (int)DpiHelper.TransformToDeviceX(mainVisual, SystemParameters.PrimaryScreenWidth); var screenHeight = (int)DpiHelper.TransformToDeviceY(mainVisual, SystemParameters.PrimaryScreenHeight); var locationX = (int)locationFromScreen.X % screenWidth; var locationY = (int)locationFromScreen.Y % screenHeight; var realOffsetX = (popupSize.Width - targetSize.Width) / 2.0; double offsetX; const int rtlHorizontalOffset = 20; if (FlowDirection == FlowDirection.LeftToRight) { offsetX = DpiHelper.TransformToDeviceX(mainVisual, offset.X); } else { offsetX = DpiHelper.TransformToDeviceX(mainVisual, offset.X - targetSize.Width - rtlHorizontalOffset); } if (locationX + popupSize.Width - realOffsetX > screenWidth || locationX - realOffsetX < 0) { SetChildTemplateIfNeed(DefaultContentTemplate); var defaultVerticalOffsetIndepent = DpiHelper.TransformToDeviceY(mainVisual, DefaultVerticalOffset); var newY = locationY + popupSize.Height > screenHeight ? -(defaultVerticalOffsetIndepent + popupSize.Height) : defaultVerticalOffsetIndepent + targetSize.Height; return(new[] { new CustomPopupPlacement(new Point(offsetX, newY), PopupPrimaryAxis.Horizontal) }); } if (locationY + popupSize.Height > screenHeight) { SetChildTemplateIfNeed(UpContentTemplate); var upVerticalOffsetIndepent = DpiHelper.TransformToDeviceY(mainVisual, UpVerticalOffset); var newY = upVerticalOffsetIndepent - popupSize.Height + targetSize.Height; return(new[] { new CustomPopupPlacement(new Point(offsetX, newY), PopupPrimaryAxis.None) }); } else { SetChildTemplateIfNeed(DownContentTemplate); var downVerticalOffsetIndepent = DpiHelper.TransformToDeviceY(mainVisual, DownVerticalOffset); var newY = downVerticalOffsetIndepent; return(new[] { new CustomPopupPlacement(new Point(offsetX, newY), PopupPrimaryAxis.None) }); } }
protected override Core.Services.ServiceOutcome DoPipelineWork() { bool includeConversionTypes = Boolean.Parse(this.Delivery.Parameters["includeConversionTypes"].ToString()); bool includeDisplaytData = Boolean.Parse(this.Delivery.Parameters["includeDisplaytData"].ToString()); bool ConvertToUSD = Boolean.Parse(this.Delivery.Parameters["ConvertToUSD"].ToString()); //double ConstCurrencyRate = this.Delivery.Parameters.ContainsKey("ConstCurrencyRate") ? Convert.ToDouble(this.Delivery.Parameters["ConstCurrencyRate"]) : 1; //Status Members Dictionary <string, ObjectStatus> kwd_Status_Data = new Dictionary <string, ObjectStatus>(); Dictionary <string, ObjectStatus> placement_kwd_Status_Data = new Dictionary <string, ObjectStatus>(); Dictionary <Int64, ObjectStatus> adGroup_Status_Data = new Dictionary <Int64, ObjectStatus>(); Dictionary <Int64, ObjectStatus> ad_Status_Data = new Dictionary <Int64, ObjectStatus>(); Dictionary <Int64, ObjectStatus> campaign_Status_Data = new Dictionary <Int64, ObjectStatus>(); using (this.ImportManager = new AdMetricsImportManager(this.Instance.InstanceID, new MetricsImportManagerOptions() { MeasureOptions = MeasureOptions.IsTarget | MeasureOptions.IsCalculated | MeasureOptions.IsBackOffice, MeasureOptionsOperator = OptionsOperator.Not, SegmentOptions = Data.Objects.SegmentOptions.All, SegmentOptionsOperator = OptionsOperator.And })) { string[] requiredHeaders = new string[1]; requiredHeaders[0] = Const.AdPreRequiredHeader; #region Getting Keywords Data Dictionary <string, double> _totals = new Dictionary <string, double>(); DeliveryFile _keyWordsFile = this.Delivery.Files[GoogleStaticReportsNamesUtill._reportNames[GA.ReportDefinitionReportType.KEYWORDS_PERFORMANCE_REPORT]]; requiredHeaders[0] = Const.AdPreRequiredHeader; var _keywordsReader = new CsvDynamicReader(_keyWordsFile.OpenContents(compression: FileCompression.Gzip), requiredHeaders); _keywordsReader.MatchExactColumns = false; Dictionary <string, KeywordTarget> _keywordsData = new Dictionary <string, KeywordTarget>(); this.ImportManager.BeginImport(this.Delivery); using (_keywordsReader) { while (_keywordsReader.Read()) { this.Mappings.OnFieldRequired = field => _keywordsReader.Current[field]; if (_keywordsReader.Current[Const.KeywordIdFieldName] == Const.EOF) { break; } KeywordPrimaryKey keywordPrimaryKey = new KeywordPrimaryKey() { KeywordId = Convert.ToInt64(_keywordsReader.Current[Const.KeywordIdFieldName]), AdgroupId = Convert.ToInt64(_keywordsReader.Current[Const.AdGroupIdFieldName]), CampaignId = Convert.ToInt64(_keywordsReader.Current[Const.CampaignIdFieldName]) }; KeywordTarget keyword = new KeywordTarget() { OriginalID = _keywordsReader.Current[Const.KeywordIdFieldName], Keyword = _keywordsReader.Current[Const.KeywordFieldName], //Status = kwd_Status_Data[keywordPrimaryKey.ToString()] }; keyword.QualityScore = Convert.ToString(_keywordsReader.Current[Const.QualityScoreFieldName]); string matchType = _keywordsReader.Current[Const.MatchTypeFieldName]; keyword.MatchType = (KeywordMatchType)Enum.Parse(typeof(KeywordMatchType), matchType, true); //Setting Tracker for Keyword if (!String.IsNullOrWhiteSpace(Convert.ToString(_keywordsReader.Current[Const.DestUrlFieldName]))) { keyword.DestinationUrl = Convert.ToString(_keywordsReader.Current[Const.DestUrlFieldName]); //setting kwd tracker //if (((String)(_keywordsReader.Current[Const.DestUrlFieldName])).IndexOf(Const.CreativeIDTrackingValue, StringComparison.OrdinalIgnoreCase) >= 0) if (Convert.ToBoolean(this.Delivery.Parameters["UseKwdTrackerAsAdTracker"])) { if (this.Mappings != null && this.Mappings.Objects.ContainsKey(typeof(KeywordTarget))) { this.Mappings.Objects[typeof(KeywordTarget)].Apply(keyword); } } } _keywordsData.Add(keywordPrimaryKey.ToString(), keyword); } } #endregion Dictionary <string, PlacementTarget> _placementsData = new Dictionary <string, PlacementTarget>(); #region Getting Placements Data string[] _placementsFileRequiredHeaders = new string[1]; _placementsFileRequiredHeaders[0] = Const.PlacementCriteriaID; DeliveryFile _PlacementsFile = this.Delivery.Files[GoogleStaticReportsNamesUtill._reportNames[GA.ReportDefinitionReportType.PLACEMENT_PERFORMANCE_REPORT]]; var _PlacementsReader = new CsvDynamicReader(_PlacementsFile.OpenContents(compression: FileCompression.Gzip), _placementsFileRequiredHeaders); using (_PlacementsReader) { while (_PlacementsReader.Read()) { if (_PlacementsReader.Current[Const.PlacementCriteriaID] == Const.EOF) { break; } //Read data only if managed GDN, otherwise it is an automatic GDN so skip if (!((String)(_PlacementsReader.Current[Const.PlacementCriteriaID])).Trim().Equals("--")) { KeywordPrimaryKey placementPrimaryKey = new KeywordPrimaryKey() { KeywordId = Convert.ToInt64(_PlacementsReader.Current[Const.PlacementCriteriaID]), AdgroupId = Convert.ToInt64(_PlacementsReader.Current[Const.AdGroupIdFieldName]), CampaignId = Convert.ToInt64(_PlacementsReader.Current[Const.CampaignIdFieldName]) }; PlacementTarget placement = new PlacementTarget() { OriginalID = _PlacementsReader.Current[Const.PlacementCriteriaID], Placement = _PlacementsReader.Current[Const.PlacementFieldName], PlacementType = PlacementType.Managed, // Status = placement_kwd_Status_Data[placementPrimaryKey.ToString()] }; //Setting Tracker for placment if (!String.IsNullOrWhiteSpace(Convert.ToString(_PlacementsReader.Current[Const.DestUrlFieldName]))) { placement.DestinationUrl = Convert.ToString(_PlacementsReader.Current[Const.DestUrlFieldName]); } _placementsData.Add(placementPrimaryKey.ToString(), placement); } } } #endregion #region Getting Conversions Data //Get Ads Conversion ( for ex. signup , purchase ) DeliveryFile _conversionFile = this.Delivery.Files[GoogleStaticReportsNamesUtill._reportNames[GA.ReportDefinitionReportType.AD_PERFORMANCE_REPORT] + "_Conv"]; var _conversionsReader = new CsvDynamicReader(_conversionFile.OpenContents(compression: FileCompression.Gzip), requiredHeaders); Dictionary <string, Dictionary <string, long> > importedAdsWithConv = new Dictionary <string, Dictionary <string, long> >(); using (_conversionsReader) { while (_conversionsReader.Read()) { if (_conversionsReader.Current[Const.AdIDFieldName] == Const.EOF) // if end of report { break; } string conversionKey = String.Format("{0}#{1}", _conversionsReader.Current[Const.AdIDFieldName], _conversionsReader.Current[Const.KeywordIdFieldName]); Dictionary <string, long> conversionDic = new Dictionary <string, long>(); if (!importedAdsWithConv.TryGetValue(conversionKey, out conversionDic)) { //ADD conversionKey to importedAdsWithConv //than add conversion field to importedAdsWithConv : <conversion name , conversion value> Dictionary <string, long> conversion = new Dictionary <string, long>(); conversion.Add(Convert.ToString(_conversionsReader.Current[Const.ConversionTrackingPurposeFieldName]), Convert.ToInt64(_conversionsReader.Current[Const.ConversionManyPerClickFieldName])); importedAdsWithConv.Add(conversionKey, conversion); } else // if Key exists { // if current add already has current conversion type than add value to the current type if (!conversionDic.ContainsKey(Convert.ToString(_conversionsReader.Current[Const.ConversionTrackingPurposeFieldName]))) { conversionDic.Add(Convert.ToString(_conversionsReader.Current[Const.ConversionTrackingPurposeFieldName]), Convert.ToInt64(_conversionsReader.Current[Const.ConversionManyPerClickFieldName])); } // else create new conversion type and add the value else { conversionDic[Convert.ToString(_conversionsReader.Current[Const.ConversionTrackingPurposeFieldName])] += Convert.ToInt64(_conversionsReader.Current[Const.ConversionManyPerClickFieldName]); } } } } #endregion #region Getting Ads Data DeliveryFile _adPerformanceFile = this.Delivery.Files[GoogleStaticReportsNamesUtill._reportNames[GA.ReportDefinitionReportType.AD_PERFORMANCE_REPORT]]; var _adsReader = new CsvDynamicReader(_adPerformanceFile.OpenContents(compression: FileCompression.Gzip), requiredHeaders); Dictionary <string, Ad> importedAds = new Dictionary <string, Ad>(); //session.Begin(false); //this.ImportManager.BeginImport(this.Delivery); DeliveryOutput currentOutput = Delivery.Outputs.First(); foreach (KeyValuePair <string, Measure> measure in this.ImportManager.Measures) { if (measure.Value.Options.HasFlag(MeasureOptions.ValidationRequired)) { _totals.Add(measure.Key, 0); } } using (_adsReader) { this.Mappings.OnFieldRequired = field => _adsReader.Current[field]; while (_adsReader.Read()) { string currencyCode = ((string)(_adsReader.Current.Currency)).ToUpper(); // Adding totals line for validation (checksum) if (_adsReader.Current[Const.AdIDFieldName] == Const.EOF) { foreach (KeyValuePair <string, Measure> measure in this.ImportManager.Measures) { if (!measure.Value.Options.HasFlag(MeasureOptions.ValidationRequired)) { continue; } switch (measure.Key) { case Measure.Common.Clicks: _totals[Measure.Common.Clicks] = Convert.ToInt64(_adsReader.Current.Clicks); break; case Measure.Common.Cost: _totals[Measure.Common.Cost] = ConvertToUSD ? this.ConvertToUSD(this.Delivery.Parameters["CurrencyCode"].ToString().ToUpper(), (Convert.ToDouble(_adsReader.Current.Cost)) / 1000000) : (Convert.ToDouble(_adsReader.Current.Cost)) / 1000000; break; case Measure.Common.Impressions: _totals[Measure.Common.Impressions] = Convert.ToInt64(_adsReader.Current.Impressions); break; } } break; } AdMetricsUnit adMetricsUnit = new AdMetricsUnit(); adMetricsUnit.Output = currentOutput; Ad ad; #region Try Get SearchKWD /***********************************************************************************/ //Creating kwd primary key KeywordPrimaryKey kwdKey = new KeywordPrimaryKey() { AdgroupId = Convert.ToInt64(_adsReader.Current[Const.AdGroupIdFieldName]), KeywordId = Convert.ToInt64(_adsReader.Current[Const.KeywordIdFieldName]), CampaignId = Convert.ToInt64(_adsReader.Current[Const.CampaignIdFieldName]) }; //Check if keyword file contains this kwdkey and not a GDN Keyword String[] GdnKwdIds = this.Delivery.Parameters["KeywordContentId"].ToString().Split(','); bool IsSearchKwd = false; KeywordTarget kwd = null; PlacementTarget placement = null; if (!GdnKwdIds.Contains(kwdKey.KeywordId.ToString()) && _keywordsData.ContainsKey(kwdKey.ToString())) { kwd = new KeywordTarget(); try { kwd = _keywordsData[kwdKey.ToString()]; } catch (Exception) { //Creating KWD with OriginalID , since the KWD doesnt exists in KWD report. kwd = new KeywordTarget { OriginalID = Convert.ToString(_adsReader.Current[Const.KeywordIdFieldName]) }; } IsSearchKwd = true; } else { placement = new PlacementTarget(); try { placement = _placementsData[kwdKey.ToString()]; } catch (Exception) { placement.OriginalID = Convert.ToString(_adsReader.Current[Const.KeywordIdFieldName]); placement.PlacementType = PlacementType.Automatic; placement.Placement = Const.AutoDisplayNetworkName; } } /***********************************************************************************/ #endregion string adId = _adsReader.Current[Const.AdIDFieldName]; if (!importedAds.ContainsKey(adId)) { ad = new Ad(); ad.OriginalID = adId; ad.Channel = new Channel() { ID = 1 }; ad.Account = new Account { ID = this.Delivery.Account.ID, OriginalID = (String)_adPerformanceFile.Parameters["AdwordsClientID"] }; // ad.Status = ad_Status_Data[Convert.ToInt64(adId)]; #region Ad Type /****************************************************************/ string adTypeColumnValue = Convert.ToString(_adsReader.Current[Const.AdTypeFieldName]); string devicePreferenceColumnValue = Convert.ToString(_adsReader.Current[Const.AdDevicePreferenceFieldName]); if (!GoogleAdTypeDic.ContainsKey(adTypeColumnValue)) { continue; } string adTypeEdgeValue = GoogleAdTypeDic[adTypeColumnValue].ToString(); //EdgeAdType atv = (EdgeAdType)Enum.Parse(typeof(EdgeAdType), adTypeEdgeValue, true); //is mobile ad ? if (devicePreferenceColumnValue.Equals(Const.AdDevicePreferenceMobileFieldValue)) { string mobileValue = string.Format("Mobile {0}", Convert.ToString(_adsReader.Current[Const.AdTypeFieldName])); //Check if this mobile value exists on dictionary if (GoogleAdTypeDic.ContainsKey(mobileValue)) { adTypeEdgeValue = GoogleAdTypeDic[mobileValue].ToString(); } else { adTypeEdgeValue = GoogleAdTypeDic[Const.AdTypeValues.Mobile_ad].ToString(); } } ad.ExtraFields[AdType] = (int)(EdgeAdType)Enum.Parse(typeof(EdgeAdType), adTypeEdgeValue, true);; /****************************************************************/ #endregion //Creative ad.Creatives.Add(new TextCreative { TextType = TextCreativeType.DisplayUrl, Text = _adsReader.Current[Const.DisplayURLFieldName] }); #region Ad Tracker segment /******************************************************/ ////Setting Tracker for Ad if (!String.IsNullOrWhiteSpace(_adsReader.Current[Const.DestUrlFieldName])) { ad.DestinationUrl = _adsReader.Current[Const.DestUrlFieldName]; if (this.Mappings != null && this.Mappings.Objects.ContainsKey(typeof(Ad))) { this.Mappings.Objects[typeof(Ad)].Apply(ad); } } //if Ad doesnt contains tracker than check for kwd tracker if (Convert.ToBoolean(this.Delivery.Parameters["UseKwdTrackerAsAdTracker"])) { if (kwd != null && kwd.Segments != null && kwd.Segments.ContainsKey(this.ImportManager.SegmentTypes[Segment.Common.Tracker])) { if (kwd.Segments[this.ImportManager.SegmentTypes[Segment.Common.Tracker]] != null && kwd.Segments[this.ImportManager.SegmentTypes[Segment.Common.Tracker]].Value != null) { SegmentObject tracker = kwd.Segments[this.ImportManager.SegmentTypes[Segment.Common.Tracker]]; //if value contains ADID than replace ADID with AD original id tracker.Value = tracker.Value.Replace("ADID", ad.OriginalID); ad.Segments[this.ImportManager.SegmentTypes[Segment.Common.Tracker]] = tracker; } } } /******************************************************/ #endregion #region Campaign /****************************************************************/ ad.Segments[this.ImportManager.SegmentTypes[Segment.Common.Campaign]] = new Campaign() { OriginalID = _adsReader.Current[Const.CampaignIdFieldName], Name = _adsReader.Current[Const.CampaignFieldName], //Status = campaign_Status_Data[Convert.ToInt64(_adsReader.Current[Const.CampaignIdFieldName])] }; /****************************************************************/ #endregion #region Image /****************************************************************/ //Image Type > Create Image if (String.Equals(Convert.ToString(_adsReader.Current[Const.AdTypeFieldName]), "Image ad")) { string adNameField = _adsReader.Current[Const.AdFieldName]; string[] imageParams = adNameField.Trim().Split(new Char[] { ':', ';' }); // Ad name: 468_60_Test7options_Romanian.swf; 468 x 60 ad.Name = imageParams[1].Trim(); ad.Creatives.Add(new ImageCreative() { ImageUrl = imageParams[1].Trim(), ImageSize = imageParams[2].Trim() }); } /****************************************************************/ #endregion #region Text od Display /****************************************************************/ else //Text ad or Display ad { ad.Name = _adsReader.Current[Const.AdFieldName]; ad.Creatives.Add(new TextCreative { TextType = TextCreativeType.Title, Text = _adsReader.Current.Ad, }); ad.Creatives.Add(new TextCreative { TextType = TextCreativeType.Body, Text = _adsReader.Current["Description line 1"], Text2 = _adsReader.Current["Description line 2"] }); } /****************************************************************/ #endregion #region Adgroup /****************************************************************/ //Insert Adgroup ad.Segments[this.ImportManager.SegmentTypes[Segment.Common.AdGroup]] = new AdGroup() { Campaign = (Campaign)ad.Segments[this.ImportManager.SegmentTypes[Segment.Common.Campaign]], Value = _adsReader.Current[Const.AdGroupFieldName], OriginalID = _adsReader.Current[Const.AdGroupIdFieldName], // Status = adGroup_Status_Data[Convert.ToInt64(_adsReader.Current[Const.AdGroupIdFieldName])] }; /****************************************************************/ #endregion #region Network /****************************************************************/ //Insert Network Type Display Network / Search Network //string networkType = Convert.ToString(_adsReader.Current[Const.NetworkFieldName]); //if (networkType.Equals(Const.GoogleSearchNetwork)) // networkType = Const.SystemSearchNetwork; //else if (networkType.Equals(Const.GoogleDisplayNetwork)) // networkType = Const.SystemDisplayNetwork; //ad.ExtraFields[NetworkType] = networkType; /****************************************************************/ #endregion importedAds.Add(adId, ad); this.ImportManager.ImportAd(ad); } else { ad = importedAds[adId]; } adMetricsUnit.Ad = ad; //INSERTING SEARCH KEYWORD INTO METRICS if (IsSearchKwd & kwd != null) { adMetricsUnit.TargetDimensions = new List <Target>(); adMetricsUnit.TargetDimensions.Add(kwd); } //INSERTING GDN KEYWORD INTO METRICS else if (placement != null) { //INSERTING KEYWORD INTO METRICS adMetricsUnit.TargetDimensions = new List <Target>(); adMetricsUnit.TargetDimensions.Add(placement); } //INSERTING METRICS DATA adMetricsUnit.MeasureValues = new Dictionary <Measure, double>(); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.Clicks], Convert.ToInt64(_adsReader.Current.Clicks)); //Currencies Conversion Support adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.Cost], ConvertToUSD ? this.ConvertToUSD(currencyCode.ToUpper(), (Convert.ToDouble(_adsReader.Current.Cost)) / 1000000) : (Convert.ToDouble(_adsReader.Current.Cost)) / 1000000); if (ConvertToUSD) { adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.CostBeforeConversion], (Convert.ToDouble(_adsReader.Current.Cost)) / 1000000); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.USDConversionRate], Convert.ToDouble(this.ImportManager.CurrencyRates[currencyCode].RateValue)); } adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.Impressions], Convert.ToInt64(_adsReader.Current.Impressions)); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.AveragePosition], Convert.ToDouble(_adsReader.Current[Const.AvgPositionFieldName])); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[GoogleMeasuresDic[Const.ConversionOnePerClickFieldName]], Convert.ToDouble(_adsReader.Current[Const.ConversionOnePerClickFieldName])); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[GoogleMeasuresDic[Const.ConversionManyPerClickFieldName]], Convert.ToDouble(_adsReader.Current[Const.ConversionManyPerClickFieldName])); //Inserting conversion values string conversionKey = String.Format("{0}#{1}", ad.OriginalID, _adsReader.Current[Const.KeywordIdFieldName]); Dictionary <string, long> conversionDic = new Dictionary <string, long>(); if (importedAdsWithConv.TryGetValue(conversionKey, out conversionDic)) { foreach (var pair in conversionDic) { if (GoogleMeasuresDic.ContainsKey(pair.Key)) { adMetricsUnit.MeasureValues[this.ImportManager.Measures[GoogleMeasuresDic[pair.Key]]] = pair.Value; } } } adMetricsUnit.Currency = new Currency { Code = Convert.ToString(_adsReader.Current.Currency) }; this.ImportManager.ImportMetrics(adMetricsUnit); } #endregion } #region Getting Sitelinks Data without metrics if (this.Delivery.Parameters.ContainsKey("AppendSitelinks") && Boolean.Parse(this.Delivery.Parameters["AppendSitelinks"].ToString())) { string[] sitelinksRequiredHeaders = new string[1]; sitelinksRequiredHeaders[0] = Const.PlaceholderFeedItemID; DeliveryFile _sitelinkPerformanceFile = this.Delivery.Files[GoogleStaticReportsNamesUtill._reportNames[GA.ReportDefinitionReportType.PLACEHOLDER_FEED_ITEM_REPORT]]; var _sitelinkReader = new CsvDynamicReader(_sitelinkPerformanceFile.OpenContents(compression: FileCompression.Gzip), sitelinksRequiredHeaders); AdMetricsUnit siteLinkMetricsUnit = new AdMetricsUnit(); siteLinkMetricsUnit.Output = currentOutput; Ad sitelinkAd; using (_sitelinkReader) { this.Mappings.OnFieldRequired = field => _sitelinkReader.Current[field]; //to do : get site link tracker string[] sitelinkAttr; while (_sitelinkReader.Read()) { if (((String)_sitelinkReader.Current[Const.SiteLinkAttributeValuesHeader]).Equals(Const.Sitelink_EOF)) { break; } string sitelinkId = string.Format("{0}{1}{2}", _sitelinkReader.Current[Const.PlaceholderFeedItemID], _sitelinkReader.Current[Const.CampaignIdFieldName], _sitelinkReader.Current[Const.AdGroupIdFieldName]); sitelinkAd = new Ad(); sitelinkAd.OriginalID = sitelinkId; sitelinkAd.Channel = new Channel() { ID = 1 }; sitelinkAd.Account = new Account { ID = this.Delivery.Account.ID, OriginalID = (String)_adPerformanceFile.Parameters["AdwordsClientID"] }; //Creative sitelinkAttr = ((String)_sitelinkReader.Current[Const.SiteLinkAttributeValuesHeader]).Split(';'); bool legacy = sitelinkAttr.Count() != 4 ? true : false; string destUrl = string.Empty; bool destUrlParsingError = false; //Checking desturl errors ( we would like to insert only sitelinks that contains desturl ). try { destUrl = sitelinkAttr[1]; } catch (Exception e) { Log.Write("Error while trying to pars destination url from attribute field on sitelink report", e); destUrlParsingError = true; } if (!destUrlParsingError) { ////Setting Tracker for Ad if (!String.IsNullOrWhiteSpace(sitelinkAttr[1])) { sitelinkAd.DestinationUrl = sitelinkAttr[1]; if (this.Mappings != null && this.Mappings.Objects.ContainsKey(typeof(Ad))) { this.Mappings.Objects[typeof(Ad)].Apply(sitelinkAd); } } sitelinkAd.Segments[this.ImportManager.SegmentTypes[Segment.Common.Campaign]] = new Campaign() { OriginalID = _sitelinkReader.Current[Const.CampaignIdFieldName], Name = _sitelinkReader.Current[Const.CampaignFieldName], }; //Insert Adgroup sitelinkAd.Segments[this.ImportManager.SegmentTypes[Segment.Common.AdGroup]] = new AdGroup() { Campaign = (Campaign)sitelinkAd.Segments[this.ImportManager.SegmentTypes[Segment.Common.Campaign]], Value = _sitelinkReader.Current[Const.AdGroupFieldName], OriginalID = _sitelinkReader.Current[Const.AdGroupIdFieldName], // Status = adGroup_Status_Data[Convert.ToInt64(_adsReader.Current[Const.AdGroupIdFieldName])] }; sitelinkAd.Creatives.Add(new TextCreative { TextType = TextCreativeType.DisplayUrl, Text = sitelinkAttr[1] }); if (!legacy) // only in case it doesnt contains legacy siteink { sitelinkAd.Creatives.Add(new TextCreative { TextType = TextCreativeType.Body, Text = sitelinkAttr[2], Text2 = sitelinkAttr[3] }); } sitelinkAd.Name = "[Sitelink] " + sitelinkAttr[0]; sitelinkAd.Creatives.Add(new TextCreative { TextType = TextCreativeType.Title, Text = "[Sitelink] " + sitelinkAttr[0] }); //Ad Type //Note: changed to "sitelink" following Amir request sitelinkAd.ExtraFields[AdType] = (int)(EdgeAdType.Sitelink); siteLinkMetricsUnit.Ad = sitelinkAd; //Setting Default Currency as USD following Amir's request from March 2014 siteLinkMetricsUnit.Currency = new Currency { Code = "USD" }; //INSERTING METRICS DATA siteLinkMetricsUnit.MeasureValues = new Dictionary <Measure, double>(); siteLinkMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.Clicks], 0); siteLinkMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.Cost], 0); siteLinkMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.Impressions], 0); siteLinkMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.AveragePosition], 0); siteLinkMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[GoogleMeasuresDic[Const.ConversionOnePerClickFieldName]], 0); siteLinkMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[GoogleMeasuresDic[Const.ConversionManyPerClickFieldName]], 0); ImportManager.ImportMetrics(siteLinkMetricsUnit); ImportManager.ImportAd(sitelinkAd); } } } }// end if #endregion currentOutput.Checksum = _totals; this.ImportManager.EndImport(); } return(Core.Services.ServiceOutcome.Success); }