How to Set auto sliders in pageviewers in xamarin.android - xamarin

I am trying to put auto sliders in my code for page viewers in xamarin.android and tried may ways to do that but it is not working correctly can you please help me to set up the auto slider to the page viewer i am posting my last tried code which is auto sliding one page and jumping off right away to last page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V4.View;
using Android.Support.V4.App;
using MyApplication.Droid.Library;
using System.Timers;
namespace MyApplication.Droid.Circles
{
[Activity(Label = "SampleCirclesSnap")]
public class SampleCirclesSnap : FragmentActivity
{
public TestFragmentAdapter mAdapter;
public ViewPager mPager;
public PageIndicator mIndicator;
public Timer time;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.simple_circles);
mAdapter = new TestFragmentAdapter(SupportFragmentManager);
mPager = FindViewById<ViewPager>(Resource.Id.pager);
mPager.Adapter = mAdapter;
var indicator = FindViewById<CirclePageIndicator>(Resource.Id.indicator);
mIndicator = indicator;
indicator.SetViewPager(mPager);
indicator.SetSnap(true);
time = new System.Timers.Timer();
time.Elapsed += (sender, args) => viewPager.SetCurrentItem(CurrentItem++, true);
time.Interval = 1000;
time.Enabled = true;
}
}
}
My fragments related code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V4.App;
using Fragment = Android.Support.V4.App.Fragment;
using FragmentManager = Android.Support.V4.App.FragmentManager;
namespace MyApplication.Droid
{
public class TestFragmentAdapter : FragmentPagerAdapter
{
// public static string[] CONTENT = new string[] { "This", "Is", "A", "Test", };
public static int[] CONTENT = new int[] { Resource.Drawable.Visa, Resource.Drawable.home_s, Resource.Drawable.Set_s, Resource.Drawable.Icon, Resource.Drawable.home_s };
int mCount;
public TestFragmentAdapter(FragmentManager fm) : base(fm)
{
mCount = CONTENT.Count();
}
public override Fragment GetItem(int position)
{
return new TestFragment(CONTENT[position % CONTENT.Count()]);
}
public override int Count
{
get
{
return mCount;
}
}
public void SetCount(int count)
{
Console.WriteLine("Setting count to " + count);
if (count > 0 && count <= 10)
{
mCount = count;
NotifyDataSetChanged();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Fragment = Android.Support.V4.App.Fragment;
namespace MyApplication.Droid
{
class TestFragment : Fragment
{
private const string KEY_CONTENT = "TestFragment:Content";
string mContent = "???";
private int v;
public TestFragment()
{
}
public TestFragment(int v)
{
this.v = v;
}
//public TestFragment(string content)
//{
// var builder = new StringBuilder();
// for (int i = 0; i < 20; i++)
// {
// if (i != 19)
// builder.Append(content).Append(" ");
// else
// builder.Append(content);
// }
// mContent = builder.ToString();
//}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//if ((savedInstanceState != null) && savedInstanceState.ContainsKey(KEY_CONTENT))
//{
// mContent = savedInstanceState.GetString(KEY_CONTENT);
//}
ImageView image = new ImageView(Activity);
image.SetImageResource(v);
//TextView text = new TextView(Activity);
//text.Gravity = GravityFlags.Center;
//text.Text = mContent;
//text.TextSize = (20 * Resources.DisplayMetrics.Density);
//text.SetPadding(20, 20, 20, 20);
LinearLayout layout = new LinearLayout(Activity);
layout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.FillParent);
layout.SetGravity(GravityFlags.Center);
layout.AddView(image);
return layout;
}
public override void OnSaveInstanceState(Bundle outState)
{
base.OnSaveInstanceState(outState);
outState.PutString(KEY_CONTENT, mContent);
}
}
}
anyone Please help me with the code to auto slide pageviewers on set time in xamarin android

I think you will need to invoke your method of changing current item to the RunOnUiThread method to ensure this it will be executed in UI thread, for example:
var timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Enabled = true;
int page = 0;
timer.Elapsed += (sender, args) =>
{
RunOnUiThread(() =>
{
if (page <= viewPager.Adapter.Count)
{
page++;
}
else
{
page = 0;
}
viewPager.SetCurrentItem(page, true);
Log.WriteLine(LogPriority.Debug, "CurrentItem:", viewPager.CurrentItem.ToString());
});
};
Tested on Android 6.0 emulator:

Related

Loading Image while service gets data using Xamarin Forms

In my application in login page i want loading image with message "Loading" in xamarin forms before the service gets data.
For that i used Activity indicator like this:
ActivityIndicator indicator = new ActivityIndicator { Color = Color.Blue, };
indicator.IsRunning = false;
indicator.IsVisible = false;
indicator.HorizontalOptions = LayoutOptions.CenterAndExpand;
indicator.VerticalOptions = LayoutOptions.CenterAndExpand;
and after click on Login button,I added code like this
indicator.IsRunning = true;
indicator.IsVisible = true;
now i am getting loading image only and in the same screen.But i want like the above image.can anyone suggest me to solve this.
Thanks in advance
You can use following library for the Dialogs
It supports Xamarin.Forms aswell
https://www.nuget.org/packages/Acr.UserDialogs/
EDIT 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
**using Acr.UserDialogs;**
using Xamarin.Forms;
using Splat;
namespace ProjectScreen
{
public partial class MainPage : ContentPage
{
public ObservableCollection<MainPageViewModel> projects { get; set; }
public SQLite.Net.SQLiteConnection _connection;
public bool IsLoading;
public MainPage()
{
projects = new ObservableCollection<MainPageViewModel>();
InitializeComponent();
this.getConnection();
foreach (Project Pname in this.GetProjects())
{
projects.Add(new MainPageViewModel { Name = Pname.name });
lstView.ItemsSource = projects;
}
AddNewItem.Clicked += (o, s) =>
{
this.PromptCommand();
};
lstView.ItemSelected += LstView_ItemSelected;
}
private void LstView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
**UserDialogs.Instance.ShowLoading("Loading data");**
Task.Run(() => { waitForMinute(); });
}
private async void waitForMinute()
{
await Task.Delay(10000);
**UserDialogs.Instance.Loading().Hide();**
Device.BeginInvokeOnMainThread(() =>
{
Navigation.PushAsync(new NavigationPage(new ProjectDetails()));
});
}
}
}
}
Lines indicated with ** are for AcrDialog You can use them in any file as per your requirement
make Sure you run them on main thread

Xamarin Android: When I open my application by notification splash-screen doesn't work

If I open the application by clicking on the notification (got from Google Cloud Messaging), I doesn't get splash-screen
GcmListenerService.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Gms.Gcm;
using Android.Util;
using System;
using Android.Database.Sqlite;
namespace Dharma.Droid
{
[Service (Exported = false), IntentFilter (new [] { "com.google.android.c2dm.intent.RECEIVE" })]
public class MyGcmListenerService : GcmListenerService
{
public override void OnMessageReceived (string from, Bundle data)
{
var message = data.GetString ("message");
Log.Debug ("MyGcmListenerService", "From: " + from);
Log.Debug ("MyGcmListenerService", "Message: " + message);
DataAccess.InsertDowload (message);
SendNotification (message);
}
void SendNotification (string message)
{
var intent = new Intent (this, typeof(MainActivity));
intent.AddFlags (ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity (this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new Notification.Builder (this)
.SetSmallIcon (Resource.Drawable.mhu2)
.SetContentTitle ("Mobile Health Unit")
.SetContentText ("U heeft een nieuwe vragenlijst.")
.SetAutoCancel (true)
.SetContentIntent (pendingIntent);
var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
notificationManager.Notify (0, notificationBuilder.Build());
}
}
}
InstanceIdListenerService.cs
using Android.App;
using Android.Content;
using Android.Gms.Gcm.Iid;
namespace Dharma.Droid
{
[Service(Exported = false), IntentFilter(new[] { "com.google.android.gms.iid.InstanceID" })]
class MyInstanceIDListenerService : InstanceIDListenerService
{
public override void OnTokenRefresh()
{
var intent = new Intent (this, typeof (RegistrationIntentService));
StartService (intent);
}
}
}
RegistrationIntentService.cs
using System;
using Android.App;
using Android.Content;
using Android.Util;
using Android.Gms.Gcm;
using Android.Gms.Gcm.Iid;
namespace Dharma.Droid
{
[Service(Exported = false)]
class RegistrationIntentService : IntentService
{
static object locker = new object();
public RegistrationIntentService() : base("RegistrationIntentService") { }
protected override void OnHandleIntent (Intent intent)
{
try
{
Log.Info ("RegistrationIntentService", "Calling InstanceID.GetToken");
lock (locker)
{
var instanceID = InstanceID.GetInstance (this);
var token = instanceID.GetToken (
"***************", GoogleCloudMessaging.InstanceIdScope, null);
Log.Info ("RegistrationIntentService", "GCM Registration Token: " + token);
SendRegistrationToAppServer (token);
Subscribe (token);
}
}
catch (Exception e)
{
Log.Debug("RegistrationIntentService", "Failed to get a registration token");
return;
}
}
void SendRegistrationToAppServer (string token)
{
}
void Subscribe (string token)
{
var pubSub = GcmPubSub.GetInstance(this);
pubSub.Subscribe(token, "/topics/global", null);
}
}
}
SplashActivity.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V7.App;
using Android.Util;
using System.Threading.Tasks;
using Android.Gms.Common;
namespace Dharma.Droid
{
[Activity(Theme = "#style/MyTheme.Splash", MainLauncher = true, NoHistory = true)]
public class SplashActivity : AppCompatActivity
{
static readonly string TAG = "X:" + typeof (SplashActivity).Name;
public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
}
protected override void OnResume()
{
base.OnResume();
Task startupWork = new Task(() =>
{
Task.Delay(5000); // Simulate a bit of startup work.
});
startupWork.ContinueWith(t =>
{
NetworkDiscovery network = new NetworkDiscovery();
CredentialsService cs = new CredentialsService();
if (GetToken() && network.IsOnline())
{
StartActivity(typeof (MainActivity));
}
else
{
StartActivity(typeof (NoInternetActivity));
}
}, TaskScheduler.FromCurrentSynchronizationContext());
startupWork.Start();
}
public bool GetToken()
{
if (IsPlayServicesAvailable ())
{
var intent = new Intent (this, typeof (RegistrationIntentService));
StartService (intent);
return true;
}
else
{
return false;
}
}
public bool IsPlayServicesAvailable ()
{
int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable (this);
if (resultCode != ConnectionResult.Success)
{
return false;
}
else
{
return true;
}
}
}
}
The issue is with these lines:
var intent = new Intent (this, typeof(MainActivity));
intent.AddFlags (ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity (this, 0, intent, PendingIntentFlags.OneShot);
Specifically var intent = new Intent (this, typeof(MainActivity)); where you are telling the notification to open your MainActivity when it is clicked. If you want to show the splash screen, you should tell it to open the splash screen instead by replacing that line with:
var intent = new Intent (this, typeof(SplashActivity));
The only issue with this is if the application is already open, you might not want to show the splash screen again. To fix this, I would recommend doing something like this where they have a boolean on IsRunning that gets set in the MainActivity lifecycle events. You could check that boolean like this possibly:
Activity intent;
if(MainActivity.IsRunning) {
intent = new Intent (this, typeof(MainActivity));
intent.AddFlags (ActivityFlags.ClearTop);
} else {
intent = new Intent (this, typeof(SplashActivity));
intent.AddFlags (ActivityFlags.ClearTop);
}
var pendingIntent = PendingIntent.GetActivity (this, 0, intent, PendingIntentFlags.OneShot);
Warning, I did not test the code above.

how to combine query results of several times function call with entity framework5?

i want to use a function to query db with linq and combine their results,i write the code as follows but cannot work , any one can help me? thanks!
the error:(The operation cannot be completed because the DbContext has been disposed)
the part code:
public static IEnumerable<UserLocation> loadedUserList;
public static IEnumerable<UserLocation> combinedUserList;
public static void loadDataInStaticClass()
{
using (var context = new SptialTestEntities())
{
var loadedUserList = from newRcords in context.UserLocations
where newRcords.ID > lastLoadedID
select newRcords;
if (loadedUserList.Any())
{
foreach (var user in loadedUserList)
{
Console.WriteLine(user.UserName);
}
if (combinedUserList != null)
{
combinedUserList = loadedUserList.Union(combinedUserList);
foreach (var cc in combinedUserList)
{
Console.WriteLine("\n after combined:" + cc.UserName);
}
}
else
{
combinedUserList = loadedUserList;
Console.WriteLine("\nfirst run :" + combinedUserList.Count());
foreach (var cc in combinedUserList)
{
Console.WriteLine("\n user:" + cc.UserName);
}
}
}
}
}
the problem is: the first call is ok, but the second report error: The operation cannot be completed because the DbContext has been disposed ,and how?
thanks!
i paste the whole code and some one can run and check the mistake and thank u:
userLocation a table contain userid,username,userlocation(geography type) ,and
i user database first mode in visual studio 2012 and map the userLocation to a entity of SptialTestEntities.
Program.cs
static void Main(string[] args)
{
for (int i = 1; i < 3; i++)
{
Console.WriteLine("\nrun{0}times, i);
Test.LoadUsersFromDB();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Data.Spatial;
using System.Data.Entity;
using System.Xml.Linq;
using System.IO;
using System.Configuration;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections;
using System.Globalization;
namespace SptialMatch
{
class Test
{
public static int lastedLoadedRecordID = 14;
public static IEnumerable<UserLocation> loadedUserList;
public static IEnumerable<UserLocation> combinedUserList;
public static void LoadUsersFromDB()
{
try
{
Console.WriteLine("\n------------------------load data begin----------------------------------------------------------");
//var context = new SptialTestEntities();
using (var context = new SptialTestEntities())
{
System.Diagnostics.Stopwatch loadStopwatch = new System.Diagnostics.Stopwatch();
loadStopwatch.Start();
loadedUserList = from newRcords in context.UserLocations
where newRcords.ID > lastedLoadedRecordID
select newRcords;
if (loadedUserList.Any())
{
foreach (var loadUser in loadedUserList)
{
Console.WriteLine("\n loaded element:" + loadUser.UserName);
}
if (combinedUserList != null)
{
Console.WriteLine("\nnot first run:" );
foreach (var cc in combinedUserList)
{
Console.WriteLine("\n before union:" + cc.UserName);
}
IEnumerable<UserLocation> tmp = loadedUserList.AsEnumerable();
combinedUserList = tmp.Union<UserLocation>(combinedUserList.AsEnumerable(), new UserComparer2()).ToList();
Console.WriteLine("\nnot first run after union:" );
foreach (var cc in combinedUserList)
{
Console.WriteLine("\n after union the user name is:" + cc.UserName);
}
}
else
{
combinedUserList = loadedUserList;
Console.WriteLine("\nfirst run the count is:" + combinedUserList.Count());
foreach (var cc in combinedUserList)
{
Console.WriteLine("\n the combined list:" + cc.UserName);
}
}
var maxID = loadedUserList.Max(myMaxID => myMaxID.ID);
lastedLoadedRecordID = lastedLoadedRecordID + 1;
}
else
{
Console.WriteLine("\n no new data!");
Console.WriteLine("\n-----------------load end,no new data yet------------------------------------------------");
Thread.Sleep(3000);
}
loadStopwatch.Stop();
Console.WriteLine("\nload time cost{0} seconds。", loadStopwatch.Elapsed);
Console.WriteLine("\n---------------------load end ----------------------------------------------------------");
}
}
catch (Exception ex)
{
Console.WriteLine("\n exception message:" + ex.Message);
}
}
}
class UserComparer2 : IEqualityComparer<UserLocation>
{
public bool Equals(UserLocation x, UserLocation y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.ID == y.ID && x.UserName == y.UserName;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(UserLocation user)
{
//Check whether the object is null
if (Object.ReferenceEquals(user, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashUserName = user.UserName == null ? 0 : user.UserName.GetHashCode();
//Get hash code for the Code field.
int hashUserCode = user.ID.GetHashCode();
//Calculate the hash code for the product.
return hashUserName ^ hashUserCode;
}
}
}

Create a simple GUI from scratch

On a platform that has no real libraries available, and bare-minimum graphics other than a "display object of dimension(x,y,xx,yy) at coordinates (x,y), I'm trying to create a simple gui.
Can someone point me to a reference where I can understand the logistical principles involved in displaying a set of objects on the screen, and highlighting the selected object, allowing users to navigate between objects and move highlighting to each object. It seems like it should be simple to do, but I would like to understand how people think about this.
How would one create an object with a method like obj.highlight() where obj.highlight would turn off highlighting in all other objects? Would one simply do a for next loop through an array of objects, skipping the current object, turning off highlighting and then set the current object to true? Highlighting would be accomplished by drawing another object on top of the selected object with a transparent center.
This is a single threaded system, (but allows a small amount of async processing).
I'm looking more for conceptual ideas but code in VB that doesn't make use of proprietary graphics calls might be useful.
I've coded a small sample app that does its own control framework by painting over a form using .Net C#. Just something simple with this result:
I've done the IsSelected by recursively disabling all controls and toggling the clicked one.
See the part with window.MouseUp += (sender, arg) =>.
Selection can go through mouse or the Tab key.
The code approach should be portable to other languages, and online-translatable to VB.Net.
Relevant snippet of code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
namespace CustomGUI
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form window = new Form1();
window.BackColor = Color.Gray;
Graphics api = window.CreateGraphics();
GUIControl form = new GUIControl();
form.Location = new Point(30,30);
form.Size = new Size(200, 300);
GUIControl control1 = new GUIControl();
control1.Location = new Point(0, 0);
control1.Size = new Size(200, 130);
control1.Background = Color.Blue;
GUIControl control11 = new GUIControl();
control11.Location = new Point(140, 30);
control11.Size = new Size(30, 30);
control11.Background = Color.Red;
GUIControl control12 = new GUIControl();
control12.Location = new Point(30, 30);
control12.Size = new Size(30, 30);
control12.Background = Color.Red;
control12.BorderColor = Color.Green;
control12.BorderWidth = 5;
GuiLabel control2 = new GuiLabel();
control2.Location = new Point(10, 200);
control2.Size = new Size(180, 30);
control2.Background = Color.Green;
control2.Text = "Hello World!";
control1.AddChild(control11);
control1.AddChild(control12);
form.AddChild(control1);
form.AddChild(control2);
window.MouseUp += (sender, arg) =>
{
// hit test the control where the mouse has landed
IGUIContainer control = form.HitTest(arg.Location);
if (control != null)
{
// recursive on all controls
foreach (var ct in (new IGUIContainer[] { form }).Traverse(c => c.Controls))
{
//deselecting all others
if (ct != control) ct.IsSelected = false;
}
control.IsSelected = !control.IsSelected;
}
window.Invalidate(); // force paint
};
window.KeyUp += (sender, key) =>
{
if (key.KeyCode == Keys.Tab && key.Modifiers == Keys.None)
{
var selected = (new IGUIContainer[] { form }).Traverse(c => c.Controls).FirstOrDefault(c => c.IsSelected);
IGUIContainer parent;
if (selected == null)
{
parent = form;
}
else
{
parent = selected;
}
IGUIContainer control;
if (parent.Controls.Count > 0)
{
control = parent.Controls[0];
}
else
{
control = GUIControl.Next(parent);
}
if (control == null) control = form;
foreach (var ct in (new IGUIContainer[] { form }).Traverse(c => c.Controls))
{
if (ct != control) ct.IsSelected = false;
}
control.IsSelected = true;
window.Invalidate();
}
};
window.Paint += (sender, args) =>
{
form.Draw(api, new Point(0,0));
};
Application.Run(window);
}
}
}
All the needed classes and interfaces:
IDrawable:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace CustomGUI
{
public interface IDrawable
{
Point Location { get; set; }
Size Size { get; set; }
Rectangle GetRealRect(Point origin);
void Draw(Graphics gfxApi, Point origin);
}
}
IGUIContainer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace CustomGUI
{
delegate void SelectionChangedHandler(object sender, bool newIsSelected);
interface IGUIContainer : IUIElement
{
IGUIContainer Parent { get; set; }
List<IGUIContainer> Controls { get; }
void AddChild(IGUIContainer child);
bool IsSelected { get; set; }
event SelectionChangedHandler SelectionChanged;
IGUIContainer HitTest(Point mouseCoord);
}
}
UIElement:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Diagnostics;
namespace CustomGUI
{
abstract class UIElement : IUIElement
{
private Point _location;
private Size _size;
private Color _background;
private Color _foreground;
private Color _borderColor;
private int _borderWidth;
public UIElement()
{
_foreground = Color.Black;
_background = Color.White;
_borderColor = Color.Transparent;
}
public Point Location
{
get
{
return _location;
}
set
{
_location = value;
}
}
public Size Size
{
get
{
return _size;
}
set
{
_size = value;
}
}
public virtual void Draw(Graphics drawingApi, Point origin)
{
Rectangle inside = GetRealRect(origin);
Pen borderPen = new Pen(new SolidBrush(_borderColor), _borderWidth);
drawingApi.FillRectangle(new SolidBrush(_background), inside);
drawingApi.DrawRectangle(borderPen, inside);
}
public Rectangle ClientRect
{
get
{
return new Rectangle(_location, _size);
}
}
public Color Background
{
get
{
return _background;
}
set
{
_background = value;
}
}
public Color Foreground
{
get
{
return _foreground;
}
set
{
_foreground = value;
}
}
public Rectangle GetRealRect(Point origin)
{
int left = ClientRect.Left + origin.X;
int top = ClientRect.Top + origin.Y;
int width = ClientRect.Width;
int height = ClientRect.Height;
Debug.WriteLine("GetRealRect " + left + ", " + top + ", " + width + ", " + height);
return new Rectangle(left, top, width, height);
}
public int BorderWidth
{
get
{
return _borderWidth;
}
set
{
_borderWidth = value;
}
}
public Color BorderColor
{
get
{
return _borderColor;
}
set
{
_borderColor = value;
}
}
}
}
GUIControl:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace CustomGUI
{
class GUIControl : UIElement, IGUIContainer
{
private IGUIContainer _parent;
private List<IGUIContainer> _controls = new List<IGUIContainer>();
private bool _isSelected;
public List<IGUIContainer> Controls
{
get
{
return _controls;
}
}
public override void Draw(Graphics api, Point origin)
{
Point original = origin;
base.Draw(api, origin);
origin.Offset(this.Location);
foreach (var ctrl in Controls)
{
ctrl.Draw(api, origin);
}
if (IsSelected)
{
Pen selection = new Pen(Color.Yellow, 3);
selection.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
api.DrawRectangle(selection, GetRealRect(original));
}
}
public IGUIContainer HitTest(Point coord)
{
Point newOrigin = coord;
newOrigin.Offset(-this.Location.X, -this.Location.Y);
foreach (var ctrl in Controls)
{
IGUIContainer hit = ctrl.HitTest(newOrigin);
if (hit != null)
{
return hit;
}
}
return ClientRect.Contains(coord) ? this : null;
}
public bool IsSelected
{
get
{
return _isSelected;
}
set
{
_isSelected = value;
if (SelectionChanged != null)
{
SelectionChanged(this, _isSelected);
}
}
}
public event SelectionChangedHandler SelectionChanged;
public void AddChild(IGUIContainer child)
{
// if you need to implement event propagation this is the place to attach them to children
child.Parent = this;
Controls.Add(child);
}
public IGUIContainer Parent
{
get
{
return _parent;
}
set
{
_parent = value;
}
}
public static IGUIContainer Next(IGUIContainer self)
{
if (self.Parent != null &&
self.Parent.Controls.Count - 1 > self.Parent.Controls.IndexOf(self))
{
return self.Parent.Controls[self.Parent.Controls.IndexOf(self) + 1];
}
else if (self.Parent != null)
{
return Next(self.Parent);
}
else
{
return null;
}
}
}
}
GUILabel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace CustomGUI
{
class GuiLabel : GUIControl
{
public string Text { get; set; }
public Font Font { get; set; }
public GuiLabel()
{
Font = new Font(new FontFamily("Tahoma"), 12, FontStyle.Regular);
}
public override void Draw(System.Drawing.Graphics api, System.Drawing.Point origin)
{
base.Draw(api, origin);
Rectangle controlRect = GetRealRect(origin);
SizeF size = api.MeasureString(Text, Font);
Point textPosition = new Point(controlRect.Location.X + (int)(controlRect.Width - size.Width) / 2,
controlRect.Location.Y + (int)(controlRect.Height - size.Height) / 2);
api.DrawString(Text, Font, new SolidBrush(Foreground), textPosition);
}
}
}
Extension (for Traverse method to flatten recursion):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CustomGUI
{
static class Extensions
{
public static IEnumerable<T> Traverse<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> fnRecurse)
{
foreach (T item in source)
{
yield return item;
IEnumerable<T> seqRecurse = fnRecurse(item);
if (seqRecurse != null)
{
foreach (T itemRecurse in Traverse(seqRecurse, fnRecurse))
{
yield return itemRecurse;
}
}
}
}
}
}
Well that is one question that can be answered in a million ways... :)
But as long as you can draw pixels (or anything remotely like it), you can draw a GUI. If you have an object oriented language at hand, I would not choose to highlight and unhighlight the current object. I would give if focus and remove focus from it, and let the object itself decide whether it should be redrawn and how that should be done.
You can automatically unfocus the previous object if all object are placed in some sort of container. When you press a navigational key (like Tab) or press a mouse button, that container can process that message and focus the next object and unfocus the last object.
It requires some programming, but the concept is quite easy. It becomes harder when you want it to perform well, look slick, have all kinds of anumations and transitions... But as I said, the concept is simple and you won't even need OO to do it, although it will probably give you a much cleaner result. I think I can program an ASCII based GUI in DOS Batch on a rainy afternoon if I needed to.

Resolve typeload exception in C#

In my application for windows mobile 6.5 i am trying to create a thumbnail using a method.But on call of that method i am receiving typtload exception.
Could anyone please let me know how can i resolve this.Below pasted is my code.
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;
using System.Reflection;
using System.IO;
using System.Net;
using Microsoft.WindowsMobile.Forms;
using System.Diagnostics;
using DirectShowLib;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace MyAppl
{
public partial class HomeForm : Form
{
public HomeForm()
{
InitializeComponent();
}
public class GetCamera
{
public static String videoFilePath;
public static Bitmap myBitmap;
CameraCaptureDialog ccd = new CameraCaptureDialog();
public void getCameraDialogue()
{
ccd.Mode = CameraCaptureMode.VideoWithAudio;
ccd.StillQuality = CameraCaptureStillQuality.Low;
ccd.Title = "sweet";
ccd.VideoTimeLimit = TimeSpan.FromMinutes(60);
DialogResult dlgResult = ccd.ShowDialog();
if (dlgResult == DialogResult.OK)
{
videoFilePath = ccd.FileName;
}
}
public void MyThumb(String path)
{
IGraphBuilder graphbuilder = (IGraphBuilder)new FilterGraph();
ISampleGrabber samplegrabber = (ISampleGrabber)new SampleGrabber();
graphbuilder.AddFilter((IBaseFilter)samplegrabber, "samplegrabber");
AMMediaType mt = new AMMediaType();
mt.majorType = MediaType.Video;
mt.subType = MediaSubType.RGB24;
mt.formatType = FormatType.VideoInfo;
samplegrabber.SetMediaType(mt);
int hr = graphbuilder.RenderFile(path, null);
IMediaEventEx mediaEvt = (IMediaEventEx)graphbuilder;
IMediaSeeking mediaSeek = (IMediaSeeking)graphbuilder;
IMediaControl mediaCtrl = (IMediaControl)graphbuilder;
IBasicAudio basicAudio = (IBasicAudio)graphbuilder;
IVideoWindow videoWin = (IVideoWindow)graphbuilder;
basicAudio.put_Volume(-10000);
videoWin.put_AutoShow(OABool.False);
samplegrabber.SetOneShot(true);
samplegrabber.SetBufferSamples(true);
long d = 0;
mediaSeek.GetDuration(out d);
long numSecs = d / 10000000;
long secondstocapture = (long)(numSecs * 0.10f);
DsLong rtStart, rtStop;
rtStart = new DsLong(secondstocapture * 10000000);
rtStop = rtStart;
mediaSeek.SetPositions(rtStart, AMSeekingSeekingFlags.AbsolutePositioning, rtStop, AMSeekingSeekingFlags.AbsolutePositioning);
mediaCtrl.Run();
EventCode evcode;
mediaEvt.WaitForCompletion(-1, out evcode);
VideoInfoHeader videoheader = new VideoInfoHeader();
AMMediaType grab = new AMMediaType();
samplegrabber.GetConnectedMediaType(grab);
videoheader = (VideoInfoHeader)Marshal.PtrToStructure(grab.formatPtr,
typeof(VideoInfoHeader));
int width = videoheader.SrcRect.right;
int height = videoheader.SrcRect.bottom;
Bitmap b = new Bitmap(width, height, PixelFormat.Format24bppRgb);
uint bytesPerPixel = (uint)(24 >> 3);
uint extraBytes = ((uint)width * bytesPerPixel) % 4;
uint adjustedLineSize = bytesPerPixel * ((uint)width + extraBytes);
uint sizeOfImageData = (uint)(height) * adjustedLineSize;
System.Drawing.Imaging.BitmapData bd1 = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int bufsize = (int)sizeOfImageData;
int n = samplegrabber.GetCurrentBuffer(ref bufsize, bd1.Scan0);
b.UnlockBits(bd1);
// b.RotateFlip(RotateFlipType.RotateNoneFlipY);
// b.Save("C:\\aaa\\out.bmp");
Marshal.ReleaseComObject(graphbuilder);
Marshal.ReleaseComObject(samplegrabber);
// return b;
}
}
private void pbRecord_Click(object sender, EventArgs e)
{
GetCamera camera = new GetCamera();
camera.getCameraDialogue();
if (GetCamera.videoFilePath != null)
{
camera.MyThumb(GetCamera.videoFilePath);
}
}
}
}
Receiving Typeloadexception in the line camera.MyThumb(GetCamera.videoFilePath);
Please forward your valuable suggestions.
Thanks in advance :)
it may be the static vars not getting initialized on time
include this line in your code:
static GetCamera() {}

Resources