public override Android.Views.View OnCreateView(Android.Views.LayoutInflater inflater, Android.Views.ViewGroup container, Bundle savedInstanceState) { var ignored = base.OnCreateView(inflater, container, savedInstanceState); var view = this.BindingInflate(Resource.Layout.fragment_friends, null); // Create your application here this.m_ViewPager = view.FindViewById<ViewPager>(Resource.Id.viewPager); this.m_ViewPager.OffscreenPageLimit = 4; this.m_PageIndicator = view.FindViewById<TabPageIndicator>(Resource.Id.viewPagerIndicator); var fragments = new List<MvxViewPagerFragmentAdapter.FragmentInfo> { new MvxViewPagerFragmentAdapter.FragmentInfo { FragmentType = typeof(FriendsAllView), Title = "All", ViewModel = this.ViewModel.FriendsAllViewModel }, new MvxViewPagerFragmentAdapter.FragmentInfo { FragmentType = typeof(FriendsRecentView), Title = "Recent", ViewModel = this.ViewModel.FriendsRecentViewModel } }; this.m_Adapter = new MvxViewPagerFragmentAdapter(this.Activity, this.ChildFragmentManager, fragments); this.m_ViewPager.Adapter = this.m_Adapter; this.m_PageIndicator.SetViewPager(this.m_ViewPager); this.m_PageIndicator.CurrentItem = 0; return view; }
void Android.Gms.Location.ILocationListener.OnLocationChanged(Android.Locations.Location location) { //Location Updated System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}: {2},{3}",CrossGeofence.Id,"Location Update",location.Latitude,location.Longitude)); ((GeofenceImplementation)CrossGeofence.Current).SetLastKnownLocation(location); }
public void OnServiceConnected(ComponentName name, Android.OS.IBinder service) { Service = IInAppBillingServiceStub.AsInterface (service); string packageName = _activity.PackageName; try { int response = Service.IsBillingSupported (Xamarin.InAppBilling.Billing.APIVersion, packageName, "inapp"); if (response != BillingResult.OK) { Connected = false; } // check for v3 subscriptions support response = Service.IsBillingSupported (Billing.APIVersion, packageName, ItemType.Subscription); if (response == BillingResult.OK) { Connected = true; RaiseOnConnected (Connected); return; } else { Connected = false; } } catch (Exception ex) { Connected = false; } }
public override Android.Views.View OnCreateView (Android.Views.LayoutInflater inflater, Android.Views.ViewGroup container, Android.OS.Bundle savedInstanceState) { var view = inflater.Inflate (Resource.Layout.fragment_cart_detail, container, false); var itemInfo = Constants.ITEMS_FOR_SALE[mItemId]; var itemName = view.FindViewById<TextView> (Resource.Id.text_item_name); itemName.Text = itemInfo.Name; var itemImage = Resources.GetDrawable (itemInfo.ImageResourceId); int imageSize = Resources.GetDimensionPixelSize (Resource.Dimension.image_thumbnail_size); int actualWidth = itemImage.IntrinsicWidth; int actualHeight = itemImage.IntrinsicHeight; int scaledHeight = imageSize; int scaledWidth = (int) (((float) actualWidth / actualHeight) * scaledHeight); itemImage.SetBounds (0, 0, scaledWidth, scaledHeight); itemName.SetCompoundDrawables (itemImage, null, null, null); var itemPrice = view.FindViewById<TextView> (Resource.Id.text_item_price); itemPrice.Text = Util.FormatPrice (Activity, itemInfo.PriceMicros); var shippingCost = view.FindViewById<TextView> (Resource.Id.text_shipping_price); var tax = view.FindViewById<TextView> (Resource.Id.text_tax_price); var total = view.FindViewById<TextView> (Resource.Id.text_total_price); if ((mItemId == Constants.PROMOTION_ITEM) && ((BikestoreApplication)this.Activity.Application).IsAddressValidForPromo) { shippingCost.Text = Util.FormatPrice (Activity, 0L); } else { shippingCost.Text = Util.FormatPrice (Activity, itemInfo.ShippingPriceMicros); } tax.Text = Util.FormatPrice (Activity, itemInfo.TaxMicros); total.Text = Util.FormatPrice (Activity, itemInfo.TotalPrice); return view; }
public static DataApi Obtain (Android.Content.Context ctx) { var db = ctx.OpenOrCreateDatabase ("trips.db", Android.Content.FileCreationMode.WorldReadable, null); var path = db.Path; db.Close (); return new DataApi (path); }
public void OnLocationChanged(Android.Locations.Location location) { curLatitudeValue = location.Latitude; curLatitude.Text = curLatitudeValue.ToString(); curLongitudeValue = location.Longitude; curLongitude.Text = curLongitudeValue.ToString(); //check the proximity to the offender location if (testLongitudeValue != 0.0 && testLatitudeValue != 0.0) { Location offenderLocation = new Location(Provider); offenderLocation.Longitude = testLongitudeValue; offenderLocation.Latitude = testLatitudeValue; float meters = location.DistanceTo(offenderLocation); if (!insideRadius && (meters < 100)) { insideRadius = true; SendNotification (); } else if (insideRadius && (meters > 100)) { insideRadius = false; } //Toast.MakeText(this, "Distance = " + meters.ToString() + " meters", ToastLength.Short).Show (); } }
public override void OnStart (Android.Content.Intent intent, int startId) { base.OnStart (intent, startId); serviceStarted = true; Log.Debug ("InvitePollService", "SimpleService started"); DoStuff (); }
public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig) { base.OnConfigurationChanged(newConfig); ResultView.SetBounds( new System.Drawing.RectangleF( 0, 0, NavbarFragment.GetCurrentContainerDisplayWidth( ), this.Resources.DisplayMetrics.HeightPixels ) ); BlockerView.SetBounds( new System.Drawing.RectangleF( 0, 0, NavbarFragment.GetCurrentContainerDisplayWidth( ), this.Resources.DisplayMetrics.HeightPixels ) ); }
/// <summary> /// Initialize android user dialogs /// </summary> public static void Init(Android.App.Activity activity, bool useAppCompat = false) { ActivityLifecycleCallbacks.Register(activity); if (useAppCompat) Instance = new AppCompatUserDialogsImpl(null); else Instance = new UserDialogsImpl(null); }
public void OnAutoFocus(bool focused, Android.Hardware.Camera camera) { if (focused) { Toast.MakeText(context, Application.Context.Resources.GetString(Resource.String.commonFocused), ToastLength.Short).Show(); } }
public override RecyclerView.ViewHolder OnCreateViewHolder(Android.Views.ViewGroup parent, int viewType) { TextView tv = (TextView)LayoutInflater.From(parent.Context). Inflate(Android.Resource.Layout.SimpleListItem1, parent, false); return new ViewHolder(tv); }
public SimpleStringRecyclerViewAdapter (Android.App.Activity context, List<String> items) { parent = context; context.Theme.ResolveAttribute (Resource.Attribute.selectableItemBackground, typedValue, true); background = typedValue.ResourceId; values = items; }
protected override void OnCreate(Android.OS.Bundle savedInstanceState) { //RequestWindowFeature(Android.Views.WindowFeatures.ActionBar); base.OnCreate(savedInstanceState); CrimePagerActivity.context = this; mViewPager = new ViewPager(this); mViewPager.Id = (Resource.Id.viewPager); SetContentView(mViewPager); mCrimes = CrimeLab.GetInstance(CrimePagerActivity.context).Crimes; Title = mCrimes[0].Title; CrimePagerAdapter adapter = new CrimePagerAdapter(SupportFragmentManager); mViewPager.Adapter = adapter; mViewPager.PageSelected += (object sender, ViewPager.PageSelectedEventArgs e) => { var crime = mCrimes[e.Position]; if (crime.Title != null) Title = crime.Title; }; // mViewPager.SetOnPageChangeListener(this); string crimeId = Intent.GetStringExtra(CrimeFragment.EXTRA_CRIME_ID); for (int i = 0; i < mCrimes.Count; i++) { if (mCrimes[i].Id == crimeId) { mViewPager.SetCurrentItem(i, false); break; } } }
public bool OnKeyDown (Android.Views.Keycode keyCode, KeyEvent e) { if (keyCode == Keycode.Menu) return true; return false; }
/// <summary> /// Transforms the page. /// </summary> /// <param name="page">The page.</param> /// <param name="position">The position.</param> public void TransformPage(Android.Views.View page, float position) { int pageWidth = page.Width; if(position < -1) { page.Alpha = 0; } else if(position <= 0) { page.Alpha = (1); page.TranslationX = 0; page.ScaleX = 1; page.ScaleY = 1; } else if(position <= 1) { page.Alpha = 1 - position; page.TranslationX = (pageWidth * -position); float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.Abs(position)); page.ScaleX = (scaleFactor); page.ScaleY = (scaleFactor); } else { page.Alpha = 0; } }
public Application (IntPtr handle, Android.Runtime.JniHandleOwnership ownerShip) : base (handle, ownerShip) { return; }
public override Android.Content.Intent Execute(Android.Content.Context context) { CategorySeries category = new CategorySeries("Weight indic"); category.Add("Current", 75); category.Add("Minimum", 65); category.Add("Maximum", 90); DialRenderer renderer = new DialRenderer(); renderer.ChartTitleTextSize = 20; renderer.LabelsTextSize = 15; renderer.LegendTextSize = 15; renderer.SetMargins(new int[] { 20, 30, 15, 0 }); SimpleSeriesRenderer r = new SimpleSeriesRenderer(); r.Color = Color.Blue; renderer.AddSeriesRenderer(r); r = new SimpleSeriesRenderer(); r.Color = Color.Rgb(0, 150, 0); renderer.AddSeriesRenderer(r); r = new SimpleSeriesRenderer(); r.Color = Color.Green; renderer.AddSeriesRenderer(r); renderer.LabelsTextSize = 10; renderer.LabelsColor = Color.White; renderer.ShowLabels = true; renderer.SetVisualTypes(new DialRenderer.Type[] { DialRenderer.Type.Arrow, DialRenderer.Type.Needle, DialRenderer.Type.Needle }); renderer.MinValue = 0; renderer.MaxValue = 150; return ChartFactory.GetDialChartIntent(context, category, renderer, "Weight indicator"); }
public static bool CreateOptionsMenu(this Context context, IParentMenu parentMenu, Android.Views.IMenu menu) { if (parentMenu == null) { return false; } #warning TODO - make this OO - let the _parentMenu render itself... foreach (var child in parentMenu.Children) { var childCast = child as CaptionAndIconMenu; if (childCast != null) { var item = menu.Add(1, childCast.UniqueId, 0, childCast.Caption); if (!string.IsNullOrEmpty(childCast.Icon)) { #warning TODO - cannot use Resourcein library code! Should we use reflection here? Or some other mechaniasm? var resourceId = context.Resources.GetIdentifier(childCast.Icon, "drawable", context.PackageName); if (resourceId > 0) { item.SetIcon(resourceId); } } } } return true; }
public bool OnError(MediaPlayer mp, Android.Media.MediaError e, int s) { #if DEBUG Console.WriteLine("{0}", e.ToString()); #endif return true; }
public override void OnClick(Android.App.Fragment source, int buttonId, object context = null) { // only handle input if the springboard is closed if ( NavbarFragment.ShouldTaskAllowInput( ) ) { // if the main page is the source if ( source == MainPage ) { // and it's button id 0, goto the create page if ( buttonId == 0 ) { PresentFragment( CreatePage, true ); } } else if ( source == CreatePage ) { if ( buttonId == 0 ) { PostPage.PrayerRequest = (Rock.Client.PrayerRequest)context; PresentFragment( PostPage, true ); } } else if ( source == PostPage ) { // this is our first / only "circular" navigation, as we're returning to the main page after // having posted a prayer. In which case, clear the back stack. NavbarFragment.FragmentManager.PopBackStack( null, PopBackStackFlags.Inclusive ); PresentFragment( MainPage, false ); } } }
protected override void OnDraw(Android.Graphics.Canvas canvas) { base.OnDraw (canvas); TextPaint textPaint = Paint; textPaint.Color = new Android.Graphics.Color(CurrentTextColor); textPaint.DrawableState = GetDrawableState (); canvas.Save(); if ( TopDown ) { canvas.Translate( Width, 0 ); canvas.Rotate( 90 ); } else { canvas.Translate( 0, Height ); canvas.Rotate( -90 ); } canvas.Translate (CompoundPaddingLeft, ExtendedPaddingTop); Layout.Draw (canvas); // getLayout().draw( canvas ); canvas.Restore (); // canvas.restore(); }
public void OnAnimationEnd(Android.Views.Animations.Animation animation) { if (m_isLast && OnAnimationEndEvent != null) { OnAnimationEndEvent(); } }
public bool OnSurfaceTextureDestroyed (Android.Graphics.SurfaceTexture surface) { _camera.StopPreview (); _camera.Release (); return true; }
public override void OnCreate (Android.OS.Bundle savedInstanceState) { base.OnCreate (savedInstanceState); if (savedInstanceState != null) { mRetryCounter = savedInstanceState.GetInt (KEY_RETRY_COUNTER); mRetryLoadFullWalletCount = savedInstanceState.GetInt (KEY_RETRY_FULL_WALLET_COUNTER); mHandleFullWalletWhenReady = savedInstanceState.GetBoolean (KEY_HANDLE_FULL_WALLET_WHEN_READY); } mActivityLaunchIntent = Activity.Intent; mItemId = mActivityLaunchIntent.GetIntExtra (Constants.EXTRA_ITEM_ID, 0); mMaskedWallet = mActivityLaunchIntent.GetParcelableExtra (Constants.EXTRA_MASKED_WALLET).JavaCast<MaskedWallet> (); var accountName = ((BikestoreApplication) Activity.Application).AccountName; // Set up an API client; mGoogleApiClient = new GoogleApiClient.Builder (Activity) .AddConnectionCallbacks (this) .AddOnConnectionFailedListener (this) .SetAccountName (accountName) .AddApi (WalletClass.API, new WalletClass.WalletOptions.Builder () .SetEnvironment (Constants.WALLET_ENVIRONMENT) .SetTheme (WalletConstants.ThemeLight) .Build ()) .Build (); mRetryHandler = new RetryHandler (this); }
// Menu aanmaken met de drie schermen voor navigatie binnen de applicatie public override bool OnCreateOptionsMenu(Android.Views.IMenu menu) { base.OnCreateOptionsMenu(menu); int groupId = 0; int menuItemId = Android.Views.Menu.First; int menuItemOrder = Android.Views.Menu.None; // Text to be displayed for this menu item. int menuItemText = Resource.String.menuitem1; // Create the menu item and keep a reference to it. //Het eerste menu item wordt hier toegevoegd IMenuItem menuItem1 = menu.Add(groupId, menuItemId, menuItemOrder, menuItemText); menuItem1.SetShortcut('1', 'a'); Int32 MenuGroup = 10; //Het tweede menu item wordt hier toegevoegd IMenuItem menuItem2 = menu.Add(MenuGroup, menuItemId + 1, menuItemOrder + 1, new Java.Lang.String("Toevoegen")); menuItem2.SetShortcut('2', 'b'); //Het derde menu item wordt hier toegevoegd IMenuItem menuItem3 = menu.Add(MenuGroup, menuItemId + 2, menuItemOrder + 2, new Java.Lang.String("Overzicht")); menuItem3.SetShortcut('3', 'c'); return true; }
private void Init(Android.Content.Context context, IAttributeSet attrs, int p) { TypedArray a = context.ObtainStyledAttributes(attrs, Resource.Styleable.CircleProgressBar, p, 0); float density = context.Resources.DisplayMetrics.Density; mBackGroundColor = a.GetColor(Resource.Styleable.CircleProgressBar_mlpb_background_color, DEFAULT_CIRCLE_BG_LIGHT); mProgressColor = a.GetColor(Resource.Styleable.CircleProgressBar_mlpb_progress_color, DEFAULT_CIRCLE_BG_LIGHT); mInnerRadius = a.GetDimensionPixelOffset(Resource.Styleable.CircleProgressBar_mlpb_inner_radius, -1); mProgressStokeWidth = a.GetDimensionPixelOffset(Resource.Styleable.CircleProgressBar_mlpb_progress_stoke_width, (int)(STROKE_WIDTH_LARGE * density)); mArrowWidth = a.GetDimensionPixelOffset(Resource.Styleable.CircleProgressBar_mlpb_arrow_width, -1); mArrowHeight = a.GetDimensionPixelOffset(Resource.Styleable.CircleProgressBar_mlpb_arrow_height, -1); mTextSize = a.GetDimensionPixelOffset(Resource.Styleable.CircleProgressBar_mlpb_progress_text_size, (int)(DEFAULT_TEXT_SIZE * density)); mTextColor = a.GetColor(Resource.Styleable.CircleProgressBar_mlpb_progress_text_color, Color.Black); mShowArrow = a.GetBoolean(Resource.Styleable.CircleProgressBar_mlpb_show_arrow, false); mCircleBackgroundEnabled = a.GetBoolean(Resource.Styleable.CircleProgressBar_mlpb_enable_circle_background, true); mProgress = a.GetInt(Resource.Styleable.CircleProgressBar_mlpb_progress, 0); mMax = a.GetInt(Resource.Styleable.CircleProgressBar_mlpb_max, 100); int textVisible = a.GetInt(Resource.Styleable.CircleProgressBar_mlpb_progress_text_visibility, 1); if (textVisible != 1) { mIfDrawText = true; } mTextPaint = new Paint(); mTextPaint.SetStyle(Paint.Style.Fill); mTextPaint.Color = mTextColor; mTextPaint.TextSize = mTextSize; mTextPaint.AntiAlias = true; a.Recycle(); mProgressDrawable = new MaterialProgressDrawale(Context, this); base.SetImageDrawable(mProgressDrawable); }
public void OnServiceConnected(ComponentName name, Android.OS.IBinder service) { Logger.Debug ("Billing service connected."); Service = IInAppBillingServiceStub.AsInterface (service); string packageName = _activity.PackageName; try { Logger.Debug ("Checking for in-app billing V3 support"); int response = Service.IsBillingSupported (Billing.APIVersion, packageName, ItemType.InApp); if (response != BillingResult.OK) { Connected = false; } Logger.Debug ("In-app billing version 3 supported for {0}", packageName); // check for v3 subscriptions support response = Service.IsBillingSupported (Billing.APIVersion, packageName, ItemType.Subscription); if (response == BillingResult.OK) { Logger.Debug ("Subscriptions AVAILABLE."); Connected = true; RaiseOnConnected (Connected); return; } else { Logger.Debug ("Subscriptions NOT AVAILABLE. Response: {0}", response); Connected = false; } } catch (Exception ex) { Logger.Debug (ex.ToString ()); Connected = false; } }
public override Android.Views.View GetView(int position, Android.Views.View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = inflater.Inflate(Resource.Layout.PostItem, parent, false); holder = new ViewHolder(); holder.avatar = (ImageView)convertView .FindViewById(Resource.Id.user_photo); holder.userNick = (TextView)convertView .FindViewById(Resource.Id.user_nick); holder.postDate = (TextView)convertView .FindViewById(Resource.Id.post_date); holder.postContent = (TextView)convertView .FindViewById(Resource.Id.post_content); convertView.SetTag(Resource.String.view_holder_tag, holder); } else { holder = (ViewHolder)convertView.GetTag(Resource.String.view_holder_tag); } Post postAtPosition = posts[position]; holder.postContent.Text = postAtPosition.content; holder.userNick.Text = postAtPosition.userName; holder.postDate.Text = HttpUtils.postDateToShowFormat(postAtPosition.updatedAt); Color backgroundColor = postAtPosition.marked ? context.Resources.GetColor(Resource.Color.post_selected) : context.Resources.GetColor(Resource.Color.post_idle); convertView.SetBackgroundColor(backgroundColor); return convertView; }
private void Setup(Android.Content.Context context) { AndroidContext = context; TextureLoader._context = context; RequestFocus(); FocusableInTouchMode = true; }
public override Android.Content.Intent Execute(Android.Content.Context context) { String[] titles = new String[] { "Series 1", "Series 2", "Series 3", "Series 4", "Series 5" }; IList<double[]> x = new List<double[]>(); IList<double[]> values = new List<double[]>(); int count = 20; int length = titles.Length; Random r = new Random(); for (int i = 0; i < length; i++) { double[] xValues = new double[count]; double[] yValues = new double[count]; for (int k = 0; k < count; k++) { xValues[k] = k + r.Next() % 10; yValues[k] = k * 2 + r.Next() % 10; } x.Add(xValues); values.Add(yValues); } int[] colors = new int[] { Color.Blue, Color.Cyan, Color.Magenta, Color.LightGray, Color.Green }; PointStyle[] styles = new PointStyle[] { PointStyle.X, PointStyle.Diamond, PointStyle.Triangle, PointStyle.Square, PointStyle.Circle }; XYMultipleSeriesRenderer renderer = BuildRenderer(colors, styles); SetChartSettings(renderer, "Scatter chart", "X", "Y", -10, 30, -10, 51, Color.Gray, Color.LightGray); renderer.XLabels = 10; renderer.YLabels = 10; length = renderer.SeriesRendererCount; for (int i = 0; i < length; i++) { ((XYSeriesRenderer)renderer.GetSeriesRendererAt(i)).FillPoints = true; } return ChartFactory.GetScatterChartIntent(context, BuildDataset(titles, x, values), renderer); }
public void TestAct() { Helpers.TestBlockerKillInteraction(Game.Agents[nameof(Marshal)], Agent, Game, true, true); Game.Reset(); Agent = (Android)Game.Agents[nameof(Android)]; Helpers.TestBlockerKillInteraction(Game.Agents[nameof(Swallow)], Agent, Game, true, true); Game.Reset(); Agent = (Android)Game.Agents[nameof(Android)]; Helpers.TestBlockerKillInteraction(Game.Agents[nameof(Marshal)], Agent, Game, true, false); Game.Reset(); Agent = (Android)Game.Agents[nameof(Android)]; Helpers.TestBlockerKillInteraction(Game.Agents[nameof(Swallow)], Agent, Game, true, false); Game.Reset(); Agent = (Android)Game.Agents[nameof(Android)]; }
public static void SetMachineType(string _m) { _m = "psp"; // Allways PSP switch (_m.ToLower()) { case "nokia": case "symbian": case "qt": MachineType = new Symbian(); break; case "droid": case "android": MachineType = new Android(); break; case "ipad": case "iphone": case "ipod": case "ios": MachineType = new IOS(); break; case "psp": MachineType = new PSP(); break; case "windows": case "win": MachineType = new Windows(); break; case "html5": MachineType = new HTML5(); break; } if (MachineType != null) { TextureType[0] = MachineType.OpaqueTextureType; TextureType[1] = MachineType.AlphaTextureType; TexturePageWidth = MachineType.TPageWidth; TexturePageHeight = MachineType.TPageHeight; } }
private static void PerformAdapterPattern() { Android android = new Android(); Iphone iPhone = new Iphone(); AdapterService.RechargeMicroUsbPhone(android); Console.WriteLine("Recharging android with MicroUsb ..."); AdapterService.RechargeLightningPhone(iPhone); Console.WriteLine("Recharging iPhone with Lightning ..."); LightningToMircroUsbAdapter lightingPhoneAdaptee = new LightningToMircroUsbAdapter(iPhone); AdapterService.RechargeMicroUsbPhone(lightingPhoneAdaptee); Console.WriteLine("Recharging iPhone with MicroUsb"); Console.ReadKey(); }
/// <inheritdoc/> internal protected override Message CopyAndValidate() { // copy var copy = new Message() { Data = Data, Notification = Notification?.CopyAndValidate(), Android = Android?.CopyAndValidate(), Apns = Apns?.CopyAndValidate(), Webpush = Webpush?.CopyAndValidate(), Token = Token?.ToList(), Topic = Topic, Condition = Condition, }; // validate var tokenList = Token != null ? new List <string>(Token) : new List <string>(); var nonnullTokens = tokenList.FindAll((target) => !string.IsNullOrEmpty(target)); var fieldList = new List <string>() { copy.Topic, copy.Condition, }; var nonnullFields = fieldList.FindAll((target) => !string.IsNullOrEmpty(target)); if (nonnullFields.Count > 1) { throw new ArgumentException("Exactly one of Token, Topic or Condition is required."); } if (nonnullFields.Count == 1 && nonnullTokens.Count > 0) { throw new ArgumentException("Exactly one of Token, Topic or Condition is required."); } if (nonnullFields.Count == 0 && nonnullTokens.Count == 0) { throw new ArgumentException("Exactly one of Token, Topic or Condition is required."); } return(copy); }
public override async Task OnMessage(SocketMessage arg, Android android, bool editedMessage) { var message = arg.Content; var rules = await Utils.ReadAllRules(); string response = ""; foreach (Match match in ruleRegex.Matches(message)) { string digitMessage = new string(match.Value.Where(c => char.IsDigit(c)).ToArray()).Trim(); bool parseSuccess = int.TryParse(digitMessage, out int ruleNr); bool validRange = rules.Length >= ruleNr && ruleNr > 0; if (parseSuccess && validRange) { response += $"rule {rules[ruleNr - 1].ToLower()}\n"; } } await arg.Channel.SendMessageAsync(response); }
static void InterfaceExample() { Clown bozo = new Clown(); Android mrBot = new Android(); // can mrBot drive? (does the Android class implement IDrive?) if (mrBot is IDrive) { string license = mrBot.DriversLicense; } R2d2 r2 = new R2d2(); Car myCar = new Car(); //R2 does not implement IDRive, therefore, it cannot drive myCar. Only Bozo or mrBot can. // myCar.Drive(r2) // will give an error myCar.Drive(bozo); }
public void CaptureFrame(MegacoolFrameCaptureConfig config) { AndroidJavaObject jConfig = new AndroidJavaObject("co.megacool.megacool.RecordingConfig"); // We have to use the generic version of Call here since the Java methods are not void, even // though we discard the return value jConfig.Call <AndroidJavaObject>("id", config.RecordingId); jConfig.Call <AndroidJavaObject>("maxFrames", config.MaxFrames); jConfig.Call <AndroidJavaObject>("peakLocation", config.PeakLocation); jConfig.Call <AndroidJavaObject>("frameRate", config.FrameRate); jConfig.Call <AndroidJavaObject>("playbackFrameRate", config.PlaybackFrameRate); jConfig.Call <AndroidJavaObject>("lastFrameDelay", config.LastFrameDelay); jConfig.Call <AndroidJavaObject>("overflowStrategy", config.OverflowStrategy.ToString()); // AndroidJavaObject jCrop = new AndroidJavaObject("android.graphics.Rect", // (int)config.Crop.xMin, (int)config.Crop.yMin, (int)config.Crop.xMax, (int)config.Crop.yMax); // jConfig.Call<AndroidJavaObject>("cropRect", jCrop); Android.Call("captureFrame", jConfig); }
public void TestAttack() { Agent agent = new Hacker(); Agent attacker = new Android(); Agent protector = new Medic(); agent.Protect(protector); agent.Attack(attacker); Assert.IsTrue(agent.WasAttacked); Assert.IsTrue(agent.IsActive); Assert.IsNull(agent.Killer); agent.Reset(); agent.Attack(attacker); Assert.IsTrue(agent.WasAttacked); Assert.IsFalse(agent.IsActive); Assert.IsNotNull(agent.Killer); Assert.AreSame(attacker, agent.Killer); }
protected string GetObbPath(string prefix, string suffix) { if (prefix == null) { throw new ArgumentNullException("prefix"); } if (suffix == null) { throw new ArgumentNullException("suffix"); } string location = Path.Combine(Android.GetStorage(), prefix); if (!Directory.Exists(location)) { return(""); } var file = Directory.GetFiles(location).ToList().Find(x => x.EndsWith(suffix)); return(file ?? ""); }
private static void Main(string[] args) { if (args == null || args.Length < 2) { return; } var fn = args[0]; if (fn == "repull") { var remote = args[1]; if (Common.SafeIndex(args, 2, out var bvu)) { var bu = bvu.Last().ToString(); var bv = long.Parse(bvu.SubstringBefore(bu)); CopyConvert.BlockValue = bv; CopyConvert.BlockUnit = bu; } Common.SafeIndex(args, 3, out var dest); CopyConvert.Repull(remote, dest); } else if (fn == "setup") { Android.Setup(); } else if (fn == "reset") { Android.Reset(); } else { Console.WriteLine("Command/verb not recognized or implemented: {0}", fn); } }
public static void OpenHttpUri(string r_Uri) { if (string.IsNullOrEmpty(r_Uri)) { DeBug.LogRed("注意:输入网址为空"); } else { if (IsAndroid) { Android.ToDevelopUtils(new AlertDialogJson() { type = (int)AlertDialogType.GPS, message = r_Uri, extend = r_Uri, }); } else { } } }
static void Main(string[] args) { // FACTORY METHOD PATTERN //PizzaStore nyStore = new NYPizzaStore(); //PizzaStore chicagoStore = new ChicagoPizzaStore(); //Pizza pizza = nyStore.OrderPizza("Cheese"); //Console.WriteLine("Customar ordered: " + pizza.Name + "\n"); //pizza = chicagoStore.OrderPizza("Veggie"); //Console.WriteLine("Customer ordered: " + pizza.Name); // ABSTRACT FACTORY PATTERN var android = new Android(new LightTheme()); new NavigationBar(android); var apple = new Apple(new DarkTheme()); new DropdownMenu(apple); }
private void OnGUI() { GUI.Label(new Rect(210, 10, 100, 80), text, statu); if (GUI.Button(new Rect(60, 10, 140, 40), "像素密度")) { int density = NativeBridge.sington.NGetDensity(); m_info.text = "PPI:" + density; } if (GUI.Button(new Rect(60, 70, 140, 40), "运营商")) { string str = NativeBridge.sington.NCheckSIM(); m_info.text = "运营商:" + str; } if (GUI.Button(new Rect(60, 130, 140, 40), "加载gif")) { StartCoroutine(GifHander()); } #if UNITY_ANDROID if (GUI.Button(new Rect(60, 190, 140, 40), "NDK")) { Debug.Log(Android.GetMemory()); NDKRead("test.txt"); } if (GUI.Button(new Rect(60, 250, 140, 40), "Streaming")) { string file = "test.txt"; int code = Android.CopyStreamingAsset(file); Debug.Log("code: " + code); string txt = Android.LoadSteamString(file); Debug.Log(txt); } if (GUI.Button(new Rect(60, 310, 140, 40), "UnZip")) { Android.UnZip("lua.zip"); } #endif GUIWebview(); }
private async Task Execute(string content, SocketMessage message, Android android) { foreach (var remoteResponse in remoteResponseTable) { if (remoteResponse.Key.ToLower() != content.ToLower()) { continue; } await message.Channel.SendMessageAsync(remoteResponse.Value); } foreach (CommandReference commandReference in commands) { foreach (string alias in commandReference.Aliases) { if (!content.StartsWith(alias)) { continue; } content = content.Remove(0, alias.Length).Trim(); string[] parts = content.Split(' ').Where(e => !string.IsNullOrWhiteSpace(e)).ToArray(); string[] arguments = parts.ToArray(); CommandParameters parameters = new CommandParameters(message, android, arguments); if (!commandReference.IsAuthorised(message.Channel.Id, message.Author.Id, parameters.Android.MainGuild.GetUser(message.Author.Id).Roles)) { continue; } await(commandReference.Delegate(parameters) as Task); break; } } await Task.CompletedTask; }
public override async Task Initialise(Android android) { android.Client.ReactionAdded += OnReactionAdd; android.Client.ReactionRemoved += OnReactionRemoved; adverbs = new HashSet <string>(await File.ReadAllLinesAsync("all-adverbs.txt")); timer.Interval = TimeSpan.FromMinutes(60).TotalMilliseconds; timer.Elapsed += async(o, ee) => { var now = DateTime.UtcNow; if (now.DayOfWeek == DayOfWeek.Tuesday && now.TimeOfDay.Hours == 15) { try { if (!canReset) { return; } canReset = false; await ResetPeriodicBoard(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } else { canReset = true; } }; timer.Start(); await Load(); await Task.CompletedTask; }
/// <summary> /// Runs unit tests for the Dealer class. /// </summary> static void TestDealer() { Hand h1 = new Hand(); Hand h2 = new Hand(); Deck d = new Deck(); Console.WriteLine("Tests for the Dealer Class"); List <Player> guests = new List <Player>(); Human George = new Human("George", h1); Android r2d2 = new Android("r2d2", h2); guests.Add(George); Dealer dealer = new Dealer(guests, r2d2, d); Console.WriteLine("Test number of Rounds: " + dealer.numberOfRounds() + "\n(Should display 0)"); Console.WriteLine("Test number of wins: " + dealer.numberOfWins() + "\n(Should display 0)"); Console.WriteLine("Test game status: " + dealer.gameStatus() + "\n(Should display status)"); Console.WriteLine("This concludes all of the unit test that don't require use of the forms."); Console.WriteLine("If this point has been reached, then all tests have been completed sucsessfully."); Console.WriteLine("Please press enter when you are ready to quit."); }
/// <summary> /// Deploys a new android in the field. /// </summary> /// <param name="teamId">The unique identifier of the registered team that is sending this request.</param> /// <param name="androidId">The unique identifier of the deployed android this reuest is meant for.</param> /// <param name="request">The actual request.</param> /// <returns>The android the request is for.</returns> public async Task <AndroidDto> SendRequest(Guid teamId, Guid androidId, AndroidRequestDto request) { Team teamToCheck = await _dbContext.Teams.SingleOrDefaultAsync(x => x.Id == teamId); if (teamToCheck == null) { throw new HtfValidationException("The specified team is unknown!"); } if (!Crypt.EnhancedVerify(request.Password, teamToCheck.Password)) { throw new HtfValidationException("The specified password is not correct!"); } Android androidToRequest = await _dbContext.Androids.SingleOrDefaultAsync(x => x.Id == androidId); if (androidToRequest == null) { throw new HtfValidationException("The specified android is unknown!"); } if (androidToRequest.Compromised) { throw new HtfValidationException("The specified android is compromised!"); } if (androidToRequest.AutoPilot == AutoPilot.Level1) { throw new HtfValidationException("The specified level-1 android does not support manual requests!"); } SensoryDataRequest requestToCreate = _requestMapper.Map(request); requestToCreate.AndroidId = androidId; requestToCreate.TimeStamp = DateTime.UtcNow; await _dbContext.SensoryDataRequests.AddAsync(requestToCreate); await _dbContext.SaveChangesAsync(); return(_androidMapper.Map(androidToRequest)); }
public async Task GlobalRefresh(Android android, int maxMessages = 1000) { Suggestions.Clear(); var channel = android.MainGuild.GetTextChannel(Server.Channels.Suggestions); var allMessages = await channel.GetMessagesAsync(maxMessages).FlattenAsync(); Console.WriteLine(allMessages.Count() + " messages total"); foreach (IMessage message in allMessages) { try { var n = (IUserMessage)message; AddSuggestion(n); } catch (Exception) { Console.WriteLine("Can't cast message to IUserMessage: " + message.Content); } } Save(); }
public bool Violates(SocketMessage message, Android android) { return(message.MentionedUsers.Count > MentionThreshold); }
/// <summary> /// Deploys a new android in the field. /// </summary> /// <param name="teamId">The unique identifier of the registered team to deploy an android for.</param> /// <param name="android">The android settings to use for deployment.</param> /// <returns>The deployed android.</returns> public async Task <AndroidDto> DeployAndroid(Guid teamId, DeployAndroidDto android) { Team teamToCheck = await _dbContext.Teams.SingleOrDefaultAsync(x => x.Id == teamId); if (teamToCheck == null) { throw new HtfValidationException("The specified team is unknown!"); } if (!Crypt.EnhancedVerify(android.Password, teamToCheck.Password)) { throw new HtfValidationException("The specified password is not correct!"); } Android androidToDeploy = _deploymentMapper.Map(android); if (!Enum.IsDefined(typeof(AutoPilot), androidToDeploy.AutoPilot)) { throw new HtfValidationException("The specified value for 'AutoPilot' is not within the expected range!"); } if (!Enum.IsDefined(typeof(SensorAccuracy), androidToDeploy.LocationSensorAccuracy)) { throw new HtfValidationException("The specified value for 'CrowdSensorAccuracy' is not within the expected range!"); } if (!Enum.IsDefined(typeof(SensorAccuracy), androidToDeploy.CrowdSensorAccuracy)) { throw new HtfValidationException("The specified value for 'LocationSensorAccuracy' is not within the expected range!"); } if (!Enum.IsDefined(typeof(SensorAccuracy), androidToDeploy.MoodSensorAccuracy)) { throw new HtfValidationException("The specified value for 'MoodSensorAccuracy' is not within the expected range!"); } if (!Enum.IsDefined(typeof(SensorAccuracy), androidToDeploy.RelationshipSensorAccuracy)) { throw new HtfValidationException("The specified value for 'RelationshipSensorAccuracy' is not within the expected range!"); } Int32 existingAndroids = await _dbContext.Androids.CountAsync( x => x.TeamId == teamId && !x.Compromised && x.AutoPilot == androidToDeploy.AutoPilot); switch (androidToDeploy.AutoPilot) { case AutoPilot.Level1: if (existingAndroids >= 500) { throw new HtfValidationException("This many level-1 androids in the field is getting suspicious!"); } break; case AutoPilot.Level2: if (existingAndroids >= 50) { throw new HtfValidationException("This many level-2 androids in the field is getting suspicious!"); } break; case AutoPilot.Level3: if (existingAndroids >= 5) { throw new HtfValidationException("This many level-3 androids in the field is getting suspicious!"); } break; } androidToDeploy.TeamId = teamId; if (androidToDeploy.AutoPilot == AutoPilot.Level1) { androidToDeploy.LocationSensorAccuracy = SensorAccuracy.LowAccuracySensor; androidToDeploy.CrowdSensorAccuracy = SensorAccuracy.LowAccuracySensor; androidToDeploy.MoodSensorAccuracy = SensorAccuracy.LowAccuracySensor; androidToDeploy.RelationshipSensorAccuracy = SensorAccuracy.LowAccuracySensor; } if (androidToDeploy.AutoPilot == AutoPilot.Level2) { androidToDeploy.LocationSensorAccuracy = SensorAccuracy.MediumAccuracySensor; androidToDeploy.CrowdSensorAccuracy = SensorAccuracy.MediumAccuracySensor; androidToDeploy.MoodSensorAccuracy = SensorAccuracy.MediumAccuracySensor; androidToDeploy.RelationshipSensorAccuracy = SensorAccuracy.MediumAccuracySensor; } switch (androidToDeploy.AutoPilot) { case AutoPilot.Level1: teamToCheck.Score += 10; break; case AutoPilot.Level2: teamToCheck.Score += 100; break; case AutoPilot.Level3: teamToCheck.Score += 1000; break; } await _dbContext.Androids.AddAsync(androidToDeploy); await _dbContext.SaveChangesAsync(); return(_androidMapper.Map(androidToDeploy)); }
//create group post public ActionResult CreateGroupPost(string content, String sportSelect, IEnumerable <HttpPostedFileBase> uploadImages, int groupId) { var result = new AjaxOperationResult <PostGeneralViewModel>(); var _postService = this.Service <IPostService>(); var _notiService = this.Service <INotificationService>(); var _memberService = this.Service <IGroupMemberService>(); var _userService = this.Service <IAspNetUserService>(); var _groupService = this.Service <IGroupService>(); var post = new Post(); int ImageNumber = 0; bool hasText = false; post.Active = true; post.CreateDate = DateTime.Now; post.LatestInteractionTime = post.CreateDate; post.UserId = User.Identity.GetUserId(); post.GroupId = groupId; if (uploadImages != null) { if (uploadImages.ToList()[0] != null && uploadImages.ToList().Count > 0) { if (uploadImages.ToList().Count == 1) { ImageNumber = 1; } else { ImageNumber = 2; } } } if (!String.IsNullOrEmpty(content)) { hasText = true; } post.PostContent = content; if (ImageNumber == 0 && hasText) { post.ContentType = (int)ContentPostType.TextOnly; } else if (ImageNumber == 1 && hasText) { post.ContentType = (int)ContentPostType.TextAndImage; } else if (ImageNumber == 2 && hasText) { post.ContentType = (int)ContentPostType.TextAndMultiImages; } else if (ImageNumber == 1 && !hasText) { post.ContentType = (int)ContentPostType.ImageOnly; } else if (ImageNumber == 2 && !hasText) { post.ContentType = (int)ContentPostType.MultiImages; } _postService.Create(post); _postService.Save(); if (post.GroupId != null) { List <GroupMember> memberList = _memberService.GetActive(x => x.GroupId == post.GroupId).ToList(); AspNetUser postedUser = _userService.FirstOrDefaultActive(x => x.Id.Equals(post.UserId)); foreach (var member in memberList) { if (!(member.UserId.Equals(post.UserId))) { Group g = _groupService.FindGroupById(groupId); Notification noti = _notiService.CreateNoti(member.UserId, post.UserId, Utils.GetEnumDescription(NotificationType.GroupPost), postedUser.FullName + " đã đăng một bài viết trong nhóm " + g.Name, (int)NotificationType.GroupPost, post.Id, null, null, groupId); List <string> registrationIds = GetToken(member.UserId); NotificationModel notiModel = Mapper.Map <NotificationModel>(PrepareNotificationCustomViewModel(noti)); if (registrationIds != null && registrationIds.Count != 0) { Android.Notify(registrationIds, null, notiModel); } //signalR noti NotificationFullInfoViewModel notiModelR = _notiService.PrepareNoti(Mapper.Map <NotificationFullInfoViewModel>(noti)); // Get the context for the Pusher hub IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext <RealTimeHub>(); // Notify clients in the group hubContext.Clients.User(notiModel.UserId).send(notiModelR); } } } if (uploadImages != null) { if (uploadImages.ToList()[0] != null && uploadImages.ToList().Count > 0) { var _postImageService = this.Service <IPostImageService>(); _postImageService.saveImage(post.Id, uploadImages); } } if (!String.IsNullOrEmpty(sportSelect)) { string[] sportId = sportSelect.Split(','); if (sportId != null) { var _postSport = this.Service <IPostSportService>(); var postSport = new PostSport(); foreach (var item in sportId) { if (!item.Equals("")) { postSport.PostId = post.Id; postSport.SportId = Int32.Parse(item); _postSport.Create(postSport); } } } } result.AdditionalData = Mapper.Map <PostGeneralViewModel>(post); return(Json(result)); }
private static async Task HandlePendingRequests() { using (HtfDbContext dbContext = new HtfDbContext()) { Console.WriteLine("[ HTF2017 - Getting pending sensory data requests... ]"); List <SensoryDataRequest> dataRequests = await dbContext.SensoryDataRequests .Where(x => !x.Fulfilled).OrderBy(x => x.TimeStamp).ToListAsync(); Console.WriteLine($"[ HTF2017 - {(dataRequests.Count > 0 ? $"{dataRequests.Count}" : "no")} pending sensory data requests found. ]"); foreach (SensoryDataRequest dataRequest in dataRequests) { Android android = await dbContext.Androids.Include(x => x.Team).SingleOrDefaultAsync(x => x.Id == dataRequest.AndroidId); if (android != null) { Location location = await dbContext.Locations.SingleOrDefaultAsync(x => x.Id == android.Team.LocationId); Console.WriteLine($"[ HTF2017 - Processing datarequest for '{android.Team.Name}'. ]"); SensoryData previousCrowdSensoryData = await dbContext.SensoryData .Where(x => x.AndroidId == dataRequest.AndroidId && x.Crowd.HasValue) .OrderByDescending(o => o.TimeStamp).FirstOrDefaultAsync(); SensoryData previousMoodSensoryData = await dbContext.SensoryData .Where(x => x.AndroidId == dataRequest.AndroidId && x.Mood.HasValue) .OrderByDescending(o => o.TimeStamp).FirstOrDefaultAsync(); SensoryData previousRelationshipSensoryData = await dbContext.SensoryData .Where(x => x.AndroidId == dataRequest.AndroidId && x.Relationship.HasValue) .OrderByDescending(o => o.TimeStamp).FirstOrDefaultAsync(); SensoryData data = new SensoryData { AndroidId = dataRequest.AndroidId, // https://www.movable-type.co.uk/scripts/latlong.html Longitude = dataRequest.Location ? location.Longitude : (Double?)null, Lattitude = dataRequest.Location ? location.Lattitude : (Double?)null, Crowd = dataRequest.Crowd ? GetCrowd(android, previousCrowdSensoryData) : null, Mood = dataRequest.Mood ? GetMood(android, previousMoodSensoryData) : null, Relationship = dataRequest.Relationship ? GetRelationship(android, previousRelationshipSensoryData) : null, TimeStamp = DateTime.UtcNow, AutonomousRequested = dataRequest.AutonomousRequest }; await dbContext.SensoryData.AddAsync(data); dataRequest.Fulfilled = true; Boolean isCompromised = IsAndroidCompromised(android.AutoPilot, android.LocationSensorAccuracy, android.CrowdSensorAccuracy, android.MoodSensorAccuracy, android.RelationshipSensorAccuracy); if (isCompromised) { android.Compromised = true; switch (android.AutoPilot) { case AutoPilot.Level1: android.Team.Score -= 10; break; case AutoPilot.Level2: android.Team.Score -= 100; break; case AutoPilot.Level3: android.Team.Score -= 1000; break; } } await dbContext.SaveChangesAsync(); Console.WriteLine($"[ HTF2017 - datarequest for '{android.Team.Name}' processed and fulfilled. ]"); } else { Console.WriteLine($"[ HTF2017 - PANIC - No team found for android '{dataRequest.AndroidId}'! ]"); } } } }
private static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .ReadFrom.AppSettings() .CreateLogger(); var options = new CommandLineOptions(); // allow app to be debugged in visual studio. if (Debugger.IsAttached) { // args = "--help ".Split(' '); args = "--platform=essentials".Split(' '); // args = new[] // { // "--platform=none", // @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\Xamarin.iOS\v1.0\Xamarin.iOS.dll" // }; } // Parse in 'strict mode'; i.e. success or quit if (Parser.Default.ParseArgumentsStrict(args, options)) { try { if (!string.IsNullOrWhiteSpace(options.Template)) { _mustacheTemplate = options.Template; Log.Debug("Using {template} instead of the default template.", _mustacheTemplate); } if (!string.IsNullOrWhiteSpace(options.ReferenceAssemblies)) { _referenceAssembliesLocation = options.ReferenceAssemblies; Log.Debug($"Using {_referenceAssembliesLocation} instead of the default reference assemblies location."); } IPlatform platform = null; switch (options.Platform) { case AutoPlatform.None: if (!options.Assemblies.Any()) { throw new Exception("Assemblies to be used for manual generation were not specified."); } platform = new Bespoke(); platform.Assemblies = options.Assemblies; if (PlatformHelper.IsRunningOnMono()) { platform.CecilSearchDirectories = platform.Assemblies.Select(Path.GetDirectoryName).Distinct().ToList(); } else { platform.CecilSearchDirectories.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5"); } break; case AutoPlatform.Android: platform = new Android(_referenceAssembliesLocation); break; case AutoPlatform.iOS: platform = new iOS(_referenceAssembliesLocation); break; case AutoPlatform.Mac: platform = new Mac(_referenceAssembliesLocation); break; case AutoPlatform.TVOS: platform = new TVOS(_referenceAssembliesLocation); break; case AutoPlatform.WPF: platform = new WPF(); break; case AutoPlatform.XamForms: platform = new XamForms(); break; case AutoPlatform.Tizen: platform = new Tizen(); break; case AutoPlatform.UWP: platform = new UWP(); break; case AutoPlatform.Winforms: platform = new Winforms(); break; case AutoPlatform.Essentials: platform = new Essentials(); _mustacheTemplate = "XamarinEssentialsTemplate.mustache"; break; default: throw new ArgumentOutOfRangeException(); } ExtractEventsFromAssemblies(platform); Environment.Exit((int)ExitCode.Success); } catch (Exception ex) { Log.Fatal(ex.ToString()); if (Debugger.IsAttached) { Debugger.Break(); } } } Environment.Exit((int)ExitCode.Error); }
public string FindAuthorName(Android android) { return(android.MainGuild.GetUser(AuthorId)?.Username ?? "a user that left the server or deleted their account"); }
public User() { time = null; android = null; ios = null; }
public override string ObbPath() { return(Android.GetStorage() + "/Android/obb/com.fantasyflightgames.mom/main.598.com.fantasyflightgames.mom.obb"); }
public AndroidDto Map(Android team) { return(_mapper.Map <AndroidDto>(team)); }
// Use for assign android to job without influence on Reliability public void AssignAndroidToJob(Job job, Android android) { android.CurrentJob = job; _dataSource.SaveChanges(); }
public ActionResult Comment(int postId, String userId, String content, HttpPostedFileBase image) { var service = this.Service <IPostCommentService>(); var notiService = this.Service <INotificationService>(); var postService = this.Service <IPostService>(); var aspNetUserService = this.Service <IAspNetUserService>(); var likeService = this.Service <ILikeService>(); ResponseModel <PostCommentDetailViewModel> response = null; try { String commentImage = null; if (image != null) { FileUploader uploader = new FileUploader(); commentImage = uploader.UploadImage(image, userImagePath); } PostComment comment = service.Comment(postId, userId, content, commentImage); AspNetUser commentedUser = aspNetUserService.FindUser(comment.UserId); Post post = postService.GetPostById(comment.PostId); AspNetUser user = postService.GetUserNameOfPost(post.Id); List <string> AllRelativeUserIdOfPost = new List <string>(); List <PostComment> listPostCmt = service.GetAllRelativeCmtDistinct(postId).ToList(); List <Like> listPostLike = likeService.GetAllRelativeLikeDistinct(postId).ToList(); foreach (var item in listPostCmt) { AllRelativeUserIdOfPost.Add(item.UserId); } foreach (var item in listPostLike) { AllRelativeUserIdOfPost.Add(item.UserId); } AllRelativeUserIdOfPost = AllRelativeUserIdOfPost.Distinct().ToList(); //Noti to post creator if (!(post.UserId.Equals(commentedUser.Id))) { string u = post.UserId; string u1 = commentedUser.Id; Notification notiForPostCreator = notiService.SaveNoti(u, u1, "Comment", commentedUser.FullName + " đã bình luận về bài viết của bạn", int.Parse(NotificationType.Post.ToString("d")), post.Id, null, null); //Fire base noti List <string> registrationIds = GetToken(user.Id); //registrationIds.Add("dgizAK4sGBs:APA91bGtyQTwOiAgNHE_mIYCZhP0pIqLCUvDzuf29otcT214jdtN2e9D6iUPg3cbYvljKbbRJj5z7uaTLEn1WeUam3cnFqzU1E74AAZ7V82JUlvUbS77mM42xHZJ5DifojXEv3JPNEXQ"); NotificationModel model = Mapper.Map <NotificationModel>(PrepareNotificationCustomViewModel(notiForPostCreator)); if (registrationIds != null && registrationIds.Count != 0) { Android.Notify(registrationIds, null, model); } //SignalR Noti NotificationFullInfoViewModel notiModelR = notiService.PrepareNoti(Mapper.Map <NotificationFullInfoViewModel>(notiForPostCreator)); // Get the context for the Pusher hub IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext <RealTimeHub>(); // Notify clients in the group hubContext.Clients.User(notiModelR.UserId).send(notiModelR); } //noti to all user that relavtive in this post foreach (var item in AllRelativeUserIdOfPost) { if (!(item.Equals(commentedUser.Id)) && !(item.Equals(post.UserId))) { string i = item; string i1 = commentedUser.Id; Notification not = notiService.SaveNoti(item, commentedUser.Id, "Comment", commentedUser.FullName + " đã bình luận về bài viết mà bạn theo dõi", int.Parse(NotificationType.Post.ToString("d")), post.Id, null, null); Notification noti = notiService.FirstOrDefaultActive(n => n.Id == not.Id); //Fire base noti List <string> registrationIds = GetToken(item); //registrationIds.Add("dgizAK4sGBs:APA91bGtyQTwOiAgNHE_mIYCZhP0pIqLCUvDzuf29otcT214jdtN2e9D6iUPg3cbYvljKbbRJj5z7uaTLEn1WeUam3cnFqzU1E74AAZ7V82JUlvUbS77mM42xHZJ5DifojXEv3JPNEXQ"); NotificationModel model = Mapper.Map <NotificationModel>(PrepareNotificationCustomViewModel(noti)); if (registrationIds != null && registrationIds.Count != 0) { Android.Notify(registrationIds, null, model); } //SignalR Noti NotificationFullInfoViewModel notiModelR = notiService.PrepareNoti(Mapper.Map <NotificationFullInfoViewModel>(noti)); // Get the context for the Pusher hub IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext <RealTimeHub>(); // Notify clients in the group hubContext.Clients.User(notiModelR.UserId).send(notiModelR); } } PostCommentDetailViewModel result = PreparePostCommentDetailViewModel(comment); response = new ResponseModel <PostCommentDetailViewModel>(true, "Bình luận thành công", null, result); post.LatestInteractionTime = DateTime.Now; postService.Update(post); postService.Save(); } catch (Exception) { response = ResponseModel <PostCommentDetailViewModel> .CreateErrorResponse("Bình luận thất bại", systemError); } return(Json(response)); }
public static async Task Main(string[] args) { Log.Logger = new LoggerConfiguration() .ReadFrom.AppSettings() .CreateLogger(); // allow app to be debugged in visual studio. if (Debugger.IsAttached) { args = "--platform=essentials --output-path=test.txt".Split(' '); } await new Parser(parserSettings => parserSettings.CaseInsensitiveEnumValues = true).ParseArguments <CommandLineOptions>(args).MapResult( async options => { try { if (!string.IsNullOrWhiteSpace(options.Template)) { _mustacheTemplate = options.Template; Log.Debug("Using {template} instead of the default template.", _mustacheTemplate); } if (!string.IsNullOrWhiteSpace(options.ReferenceAssemblies)) { _referenceAssembliesLocation = options.ReferenceAssemblies; Log.Debug($"Using {_referenceAssembliesLocation} instead of the default reference assemblies location."); } IPlatform platform = null; switch (options.Platform) { case AutoPlatform.None: if (options.Assemblies.Any() == false) { throw new Exception("Assemblies to be used for manual generation were not specified."); } platform = new Bespoke(); platform.Assemblies.AddRange(options.Assemblies); if (PlatformHelper.IsRunningOnMono()) { platform.CecilSearchDirectories.AddRange(platform.Assemblies.Select(Path.GetDirectoryName).Distinct().ToList()); } else { platform.CecilSearchDirectories.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5"); } break; case AutoPlatform.Android: platform = new Android(_referenceAssembliesLocation); break; case AutoPlatform.iOS: platform = new iOS(_referenceAssembliesLocation); break; case AutoPlatform.Mac: platform = new Mac(_referenceAssembliesLocation); break; case AutoPlatform.TVOS: platform = new TVOS(_referenceAssembliesLocation); break; case AutoPlatform.WPF: platform = new WPF(); break; case AutoPlatform.XamForms: platform = new XamForms(); break; case AutoPlatform.Tizen4: platform = new Tizen(); break; case AutoPlatform.UWP: platform = new UWP(); break; case AutoPlatform.Winforms: platform = new Winforms(); break; case AutoPlatform.Essentials: platform = new Essentials(); _mustacheTemplate = "XamarinEssentialsTemplate.mustache"; break; default: throw new ArgumentException($"Platform not {options.Platform} supported"); } await ExtractEventsFromAssemblies(options.OutputPath, platform).ConfigureAwait(false); Environment.Exit((int)ExitCode.Success); } catch (Exception ex) { Log.Fatal(ex.ToString()); if (Debugger.IsAttached) { Debugger.Break(); } } Environment.Exit((int)ExitCode.Error); }, _ => Task.CompletedTask).ConfigureAwait(false); }