Change image after each 10seconds in WPF image box - wpf-controls

There is a requirement of updating image in image boxes of WPF. I am thinking of creating a list with all the paths and then using a timer control checking the 10 seconds. After the 10 seconds has elapsed the next id from list is taken and bound to the image box. I am new to WPF. Can any one help me with a working example.

Use a DispatcherTimer to invoke a method at regular intervalls. In this method change the bound image, remember to raise the INotifyPropertyChanged event to let WPF know it should query the bound property again.

Hi i have made thig running with the below code .
private void timer_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
{
Action action1 = () => this.BeginStoryboard((Storyboard)this.FindResource("BlinkStoryboardFed"));
Dispatcher.BeginInvoke(action1);
Action action = () => BindToImages(lststr);
Dispatcher.BeginInvoke(action);
//BindToImages(lststr);
_timer.Start();
}
public void BindToImages(List<string> lststrpath)
{
lock (_locker)
{
for (int i = 0; i < lststrpath.Count; i++)
{
if (count == 0)
{
startindex = i;
this.BindToImgIndx = startindex;
AppState.Index = i;
BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(lststrpath[startindex].ToString(), UriKind.Relative);
img.CacheOption = BitmapCacheOption.OnLoad;
img.EndInit();
image1.Source = img;
count++;
}
else
{
int k = AppState.Index;
k = ++k;
this.BindToImgIndx = startindex;
if (k < lststrpath.Count)
{
BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(lststrpath[k].ToString(), UriKind.Relative);
img.CacheOption = BitmapCacheOption.OnLoad;
img.EndInit();
image1.Source = img;
}
AppState.Index = k;
}
this.BeginStoryboard((Storyboard)this.FindResource("BlinkStoryboardUnFed"));
break;
}
}
}

Related

How to make parent child relationship in C1flexgrid

I am using C1Flexgrid and I need to make parent child relation in this grid. But child details need to show in same grid (no other grid ) and when I clicked on + expand should happen and vice versa.
I have written below code where I am having one column in datatable related to parent and child . If it is parent then I am making it 1 else 0.
When I tried with this code. R2 row is coming as child node of r which should not be a case as it is parent node.
Please help me on this .
private void Form3_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable("customers");
dt.Columns.Add("abc");
dt.Columns.Add("ddd");
dt.Columns.Add("eee");
dt.Columns.Add("parent");
var r = dt.NewRow();
r["abc"] = "11";
r["ddd"] = "12";
r["eee"] = "13";
r["parent"] = "1";
var r1 = dt.NewRow();
r1["ddd"] = "12";
r1["eee"] = "14";
r1["parent"] = "0";
var r2 = dt.NewRow();
r2["abc"] = "11";
r2["ddd"] = "1222";
r2["eee"] = "14";
r2["parent"] = "1";
var rr32 = dt.NewRow();
rr32["abc"] = "11";
rr32["ddd"] = "1222";
rr32["eee"] = "14";
rr32["parent"] = "0";
dt.Rows.Add(r);
dt.Rows.Add(r1);
dt.Rows.Add(r2);
dt.Rows.Add(rr32);
grid1.DataSource = dt;
GroupBy("parent", 1);
// show outline tree
grid1.Tree.Column = 2;
// autosize to accommodate tree
grid1.AutoSizeCol(grid1.Tree.Column);
grid1.Tree.Show(1);
}
void GroupBy(string columnName, int level)
{
object current = null;
for (int r = grid1.Rows.Fixed; r < grid1.Rows.Count; r++)
{
if (!grid1.Rows[r].IsNode)
{
var value = grid1[r, columnName];
string value2 = grid1[r, "parent"].ToString();
if (!object.Equals(value, current))
{
// value changed: insert node, apply style
if (value2.Equals("0"))
{
grid1.Rows.InsertNode(r, level);
grid1.Rows[r].Style = _nodeStyle[Math.Min(level, _nodeStyle.Length - 1)];
r++;
}
// show group name in first scrollable column
//grid1[r, grid1.Cols.Fixed+1] = value;
// update current value
current = value;
}
}
}
}
}
Your code was almost there, i have manipulated GroupBy method to fit your need. It solves your current requirement but you have to handle sorting and other functionalists of grid yourself.
Hope this helps!
void GroupBy(string columnName, int level)
{
object current = null;
for (int r = grid1.Rows.Fixed; r < grid1.Rows.Count; r++)
{
if (!grid1.Rows[r].IsNode)
{
var value = grid1[r, columnName];
if (!object.Equals(value, current))
{
// value changed: insert node, apply style
grid1.Rows.InsertNode(r, level);
grid1.Rows[r].Style = _nodeStyle[Math.Min(level, _nodeStyle.Length - 1)];
// show group name in first scrollable column
Row row = grid1.Rows[r + 1];
for (int i = 0; i < grid1.Cols.Count; i++)
{
grid1[r, i] = row[i];
}
grid1.Rows[r + 1].Visible = false;
r++;
// update current value
current = value;
}
}
}
}

How to save the trained data in openimaj?

I'm working on a project which is about taking attendance of a class through the class video. I'm training the data when the program is running and it is taking a lot of time to train the data. Is there any way by which I can save the trained data and use directly in the program. Below is my code:
public static void main(String[] args) throws MalformedURLException, IOException, VideoCaptureException
{
FKEFaceDetector faceDetector = new FKEFaceDetector(new HaarCascadeDetector(40));
EigenFaceRecogniser<KEDetectedFace, Person> faceRecogniser = EigenFaceRecogniser.create(20, new RotateScaleAligner(), 1, DoubleFVComparison.CORRELATION, 0.9f);
final FaceRecognitionEngine<KEDetectedFace, Person> faceEngine = FaceRecognitionEngine.create(faceDetector, faceRecogniser);
Video<MBFImage> video;
//video = new VideoCapture(320, 100);
video = new XuggleVideo(new URL("file:///home/kamal/Videos/Samplevideo1.mp4"));
Person[] dataset = new Person[12];
dataset[0] = new Person("a");
dataset[1] = new Person("b");
dataset[2] = new Person("c");
dataset[3] = new Person("d");
dataset[4] = new Person("e");
dataset[5] = new Person("f");
dataset[6] = new Person("g");
dataset[7] = new Person("h");
dataset[8] = new Person("i");
dataset[9] = new Person("j");
dataset[10] = new Person("k");
dataset[11] = new Person("l");
int dcount;
for(int i = 0; i < 12; i++)
{
dcount = 0;
for(int j = 1; j <= 20 && dcount == 0; j++)
{
MBFImage mbfImage = ImageUtilities.readMBF(new URL("file:///home/kamal/Pictures/"+i+"/"+j+".png"));
FImage fimg = mbfImage.flatten();
List<KEDetectedFace> faces = faceEngine.getDetector().detectFaces(fimg);
if(faces.size() > 0)
{
faceEngine.train(faces.get(0), dataset[i]);
dcount++;
}
}
}
VideoDisplay<MBFImage> vd = VideoDisplay.createVideoDisplay(video);
vd.addVideoListener(new VideoDisplayListener<MBFImage>() {
public void afterUpdate(VideoDisplay<MBFImage> display) {
}
public void beforeUpdate(MBFImage frame)
{
FImage image = frame.flatten();
List<KEDetectedFace> faces = faceEngine.getDetector().detectFaces(image);
for(DetectedFace face : faces) {
frame.drawShape(face.getBounds(), RGBColour.RED);
try {
List<IndependentPair<KEDetectedFace, ScoredAnnotation<Person>>> rfaces = faceEngine.recogniseBest(face.getFacePatch());
ScoredAnnotation<Person> score = rfaces.get(0).getSecondObject();
if (score != null)
{
System.out.println("Mr. "+score.annotation+" is Present.");
}
else
{
System.out.println("Recognizing");
}
} catch (Exception e) {
}
}
}
});
}
Yes, just use the static methods in the org.openimaj.io.IOUtils class to write the faceEngine to disk once it's trained and read it back in again.

Extracting a portion of Image in C#

I have made a C# Windows application with two Picture-Boxes one as MainPictureBox and other as ThumbnailBox, I want to Extract a portion of Image upon moving mouse over Main Image and load it into ThumbnailPictureBox.
Here is a way to get a thumbnail from the image.
public static Bitmap Thumb(this Image inputStream, int width, int height)
{
using (var bitMap = new Bitmap(inputStream))
{
int originalWidth = bitMap.Width;
int originalHeight = bitMap.Height;
int startPositionHeight = 0;
int startPosionWidth = 0;
int widthHeight = 0;
if (originalWidth > originalHeight)
{
startPosionWidth = (originalWidth - originalHeight) / 2;
widthHeight = originalHeight;
}
else if (originalHeight > originalWidth)
{
startPositionHeight = (originalHeight - originalWidth) / 2;
widthHeight = originalWidth;
}
else if (originalWidth == originalHeight)
{
widthHeight = originalHeight;
}
var rect = new Rectangle(startPosionWidth, startPositionHeight, widthHeight, widthHeight);
using (Bitmap cropped = bitMap.Clone(rect, bitMap.PixelFormat))
{
using (var newbitmap = new Bitmap(cropped, width, height))
{
var stream = new MemoryStream();
newbitmap.Save(stream, ImageFormat.Tiff);
stream.Position = 0;
return new Bitmap(stream);
}
}
}
}

How can I correct the error "Cross-thread operation not valid"?

This following code gives me the error below . I think I need "InvokeRequired" . But I don't understand how can I use?
error:Cross-thread operation not valid: Control 'statusBar1' accessed from a thread other than the thread it was created on.
the code :
public void CalculateGeneration(int nPopulation, int nGeneration)
{
int _previousFitness = 0;
Population TestPopulation = new Population();
for (int i = 0; i < nGeneration; i++)
{
if (_threadFlag)
break;
TestPopulation.NextGeneration();
Genome g = TestPopulation.GetHighestScoreGenome();
if (i % 100 == 0)
{
Console.WriteLine("Generation #{0}", i);
if ( ToPercent(g.CurrentFitness) != _previousFitness)
{
Console.WriteLine(g.ToString());
_gene = g;
statusBar1.Text = String.Format("Current Fitness = {0}", g.CurrentFitness.ToString("0.00"));
this.Text = String.Format("Sudoko Grid - Generation {0}", i);
Invalidate();
_previousFitness = ToPercent(g.CurrentFitness);
}
if (g.CurrentFitness > .9999)
{
Console.WriteLine("Final Solution at Generation {0}", i);
statusBar1.Text = "Finished";
Console.WriteLine(g.ToString());
break;
}
}
}
}
Easiest for reusability is to add a helper function like:
void setstatus(string txt)
{
Action set = () => statusBar1.Text = txt;
statusBar1.Invoke(set);
}
Or with the invokerequired check first:
delegate void settextdelegate(string txt);
void setstatus(string txt)
{
if (statusBar1.InvokeRequired)
statusBar1.Invoke(new settextdelegate(setstatus), txt);
else
statusBar1.Text = txt;
}
Either way the status can then be set like
setstatus("Finished");
For completeness I should add that even better would be to keep your calculating logic separated from your form and raise a status from within your calculating functionality that can be hanled by the form, but that could be completely out of scope here.

Sharepoint 2010 custom webpart paging

I am trying to implement simple paging on my sharepoint webpart. I have a single news articles list which has some simple columns. I want to be able to have then five on a page and with some numerical paging at the bottom. I have gone through the net trying to understand splistitemcollectionposition but with no luck. If anyone can help please can you give me a simple code example or some guidanc
Many thanks
Chris
I would suggest using SPDataSource and a SPGridView, together they will implement paging and many other cool features with minimal or no code.
Use this a a guide for some of the classes/methods/properties you might need to use to get paging to work. Be aware that this code does not compile, i have just pulled together various code snippets that i have in my own list results framework, which includes paging, sorting, grouping and caching. It should be enough to get you started though.
public class PagedListResults : System.Web.UI.WebControls.WebParts.WebPart {
protected SPPagedGridView oGrid;
protected override void CreateChildControls() {
this.oGrid = new SPPagedGridView();
oGrid.AllowPaging = true;
oGrid.PageIndexChanging += new GridViewPageEventHandler(oGrid_PageIndexChanging);
oGrid.PagerTemplate = null; // Must be called after Controls.Add(oGrid)
oGrid.PagerSettings.Mode = PagerButtons.NumericFirstLast;
oGrid.PagerSettings.PageButtonCount = 3;
oGrid.PagerSettings.Position = PagerPosition.TopAndBottom;
base.CreateChildControls();
}
public override void DataBind() {
base.DataBind();
SPQuery q = new SPQuery();
q.RowLimit = (uint)info.PageSize;
if (!string.IsNullOrEmpty(info.PagingInfoData)) {
SPListItemCollectionPosition pos = new SPListItemCollectionPosition(info.PagingInfoData);
q.ListItemCollectionPosition = pos;
} else {
//1st page, dont need a position, and using a position breaks things
}
q.Query = info.Caml;
SPListItemCollection items = SPContext.Current.List.GetItems(q);
FilterInfo info = null;
string tmp = "<View></View>";
tmp = tmp.Replace("<View><Query>", string.Empty);
tmp = tmp.Replace("</Query></View>", string.Empty);
info.Caml = tmp;
info.PagingInfoData = string.Empty;
info.CurrentPage = oGrid.CurrentPageIndex;
info.PageSize = oGrid.PageSize;
if (oGrid.PageIndex == 0 || oGrid.CurrentPageIndex == 0) {
//do nothing
} else {
StringBuilder value = new StringBuilder();
value.Append("Paged=TRUE");
value.AppendFormat("&p_ID={0}", ViewState[KEY_PagingPrefix + "ID:" + oGrid.PageIndex]);
info.PagingInfoData = value.ToString();
}
int pagecount = (int)Math.Ceiling(items.Count / (double)oGrid.PageSize);
for (int i = 1; i < pagecount; i++) { //not always ascending index numbers
ResultItem item = items[(i * oGrid.PageSize) - 1];
ViewState[KEY_PagingPrefix + "ID:" + i] = item.ID;
}
oGrid.VirtualCount = items.Count;
DateTime time3 = DateTime.Now;
DataTable table = new DataTable("Data");
DataBindListData(table, items);
this.oGrid.DataSource = table;
this.oGrid.DataBind();
this.oGrid.PageIndex = oGrid.CurrentPageIndex; //need to reset this after DataBind
}
void oGrid_PageIndexChanging(object sender, GridViewPageEventArgs e) {
oGrid.PageIndex = e.NewPageIndex;
oGrid.CurrentPageIndex = oGrid.PageIndex;
}
}
public class FilterInfo {
public string Caml;
public string PagingInfoData;
public int CurrentPage;
public int PageSize;
}
public class SPPagedGridView : SPGridView {
protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource) {
pagedDataSource.AllowCustomPaging = true;
pagedDataSource.VirtualCount = virtualcount;
pagedDataSource.CurrentPageIndex = currentpageindex;
base.InitializePager(row, columnSpan, pagedDataSource);
}
private int virtualcount = 0;
public int VirtualCount {
get { return virtualcount; }
set { virtualcount = value; }
}
private int currentpageindex = 0;
public int CurrentPageIndex {
get { return currentpageindex; }
set { currentpageindex = value; }
}
}
check out my post on how to page using SPListItemCollectionPosition, I did a component to page over lists, maybe it can help -> http://hveiras.wordpress.com/2011/11/07/listpagert-using-splistitemcollectionposition/

Resources