PostSharp stackoverflow on aspect - stack-overflow

Aspect class looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using PostSharp.Aspects;
namespace GlobalExceptionHandler
{
[Serializable]
class MyDebugger : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
Console.WriteLine("METHOD ENTRY: " + args.Method.Name + "(" + args.Arguments.GetArgument(0) + ")");
}
public override void OnException(MethodExecutionArgs args)
{
Console.WriteLine("Exception at: " + args.Method.Name + "()");
args.FlowBehavior = FlowBehavior.Continue;
}
}
}
I am applying the aspect to mscorlib assembly to system namespace but excluding the console class which i thought was causing the stackoverflow on my aspect as it uses a Console.WriteLine to print the log.
[assembly: GlobalExceptionHandler.MyDebugger(AttributeTargetAssemblies = "mscorlib", AttributeTargetTypes = "System.Console", AttributeExclude = true, AttributePriority = 100000)]
[assembly: GlobalExceptionHandler.MyDebugger(AttributeTargetAssemblies = "mscorlib", AttributeTargetTypes = "System.*")]
And im still getting the stackoverflow exception

The expression in the aspect code where you add several strings using "+" is actually emitted as a call to String.Concat method by C# compiler. So you get this code in the OnEntry:
Console.WriteLine(String.Concat("METHOD ENTRY: ", args.Method.Name, "(", args.Arguments.GetArgument(0), ")"));
To avoid recursion you can exclude System.String class in the same way you did with System.Console. However, in general case it's better to add a thread-static flag to your aspect that will serve to stop recursive calls.
[Serializable]
class MyDebugger : OnMethodBoundaryAspect
{
[ThreadStatic]
private static bool isLogging;
public override void OnEntry( MethodExecutionArgs args )
{
if ( isLogging ) return;
isLogging = true;
Console.WriteLine( "METHOD ENTRY: " + args.Method.Name + "(" + args.Arguments.GetArgument( 0 ) + ")" );
isLogging = false;
}
public override void OnException( MethodExecutionArgs args )
{
if ( isLogging ) return;
isLogging = true;
Console.WriteLine( "Exception at: " + args.Method.Name + "()" );
args.FlowBehavior = FlowBehavior.Continue;
isLogging = false;
}
}

Related

How can I test my C# Console App using XUnit, the App contain Command line arguments

I have a Program, it's C# Console App, The function of the program is to open a file and search for a specific line and edit it.
I can run the program without Parameter and the local file will be edited, or i can run the program with a parameter to Specify the path of the file I want to modify, or i can run the program with a parameter to get help.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
namespace BuildIncrement
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(args.Length);
string filePath = "version.h";
if (args.Length > 0)
{
if (args[0].Contains("path"))
{
var argsArray = args[0].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (argsArray.Length > 1)
{
filePath = argsArray[1];
}
}
else if (args[0].Contains("help"))
{
Console.WriteLine("To run the Program please type --path");
return;
}
}
if (File.Exists(filePath) == false)
{
Console.WriteLine("Fehler: Die Datei existiert nicht!");
return;
}
List<string> lines = File.ReadAllLines(filePath).ToList();
string line = lines.Where(i => i.Contains("BUILD_NUM")).FirstOrDefault();
//foreach (string line in lines)
int buildNr = 0;
if (line != null)
{
string[] lineparts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (lineparts.Length > 2)
{
string Nr = lineparts[2];
if (int.TryParse(Nr, out buildNr))
{
}
buildNr++;
int index = lines.IndexOf(line);
lines.RemoveAt(index);
lines.Insert(index, line.Replace(Nr, buildNr.ToString()));
}
}
File.WriteAllLines(filePath, lines);
Console.WriteLine($"Build-Nr wurde auf {buildNr} aktualisiert!");
}
}
}
Rectify your code and write the logic in different methods. Call these methods in Main. Then You can use Xunit [Fact] to test your code.
It is perfectly possible to call the Main method and supply arguments to it. (You do have to make it a public method).
[Fact]
public void MyTest()
{
string[] args = new string[] { "MyFile.txt" };
Program.Main(args);
// Assertions about the result
}

How to Set auto sliders in pageviewers in xamarin.android

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:

The name does not exist in the current context

I'm trying to upload files to Oracle database Using C# vs2012. Its my first time I do so especially with Oracle. I just followed an example I found online but I got some errors before I even run the codes showing me that some of the type or name spaces don't exist.
The example I followed : Blob Example
Here are the codes that are underlined red in my Resources_to_upload.aspx.cs
objCmd
objConn
My code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
public partial class Resources_to_upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdUpload_Click(object sender, EventArgs e)
{
try
{
if (fileUploadDocument.PostedFile.ContentLength > 0)
{
// Get the File name and Extension
string FileName = Path.GetFileName(fileUploadDocument.PostedFile.FileName);
string FileExtension = Path.GetExtension(fileUploadDocument.PostedFile.FileName);
//
// Extract the content of the Document into a Byte array
int intlength = fileUploadDocument.PostedFile.ContentLength;
Byte[] byteData = new Byte[intlength];
fileUploadDocument.PostedFile.InputStream.Read(byteData, 0, intlength);
//
// Save the file to the DB
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
object Conn = new OracleConnection(strConn);
//
StringBuilder strQueryBuilder = new StringBuilder("INSERT INTO RESOURCES(RESOURCES_ID, FILE_NAME, TYPE, RESOURCE_FILE) VALUES (");
strQueryBuilder.Append("'1', ");
strQueryBuilder.Append("'" + FileName + "', ");
strQueryBuilder.Append("'" + FileExtension + "', ");
strQueryBuilder.Append(" :RESOURCE_FILE)");
String strQuery = strQueryBuilder.ToString();
//
OracleParameter blobParameter = new OracleParameter();
blobParameter.ParameterName = "Resources_FILE";
blobParameter.OracleType = OracleType.Blob;
blobParameter.Direction = ParameterDirection.Input;
blobParameter.Value = byteData;
objCmd = new OracleCommand(strQuery, objConn);
objCmd.Parameters.Add(blobParameter);
//
objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();
//
lblMsg.Text = "Document Uploaded Succesfully";
}
}
catch (Exception ex)
{
lblMsg.Text = " Error uploading Document: " + ex.Message.ToString();
}
}
}
Please help solve this issue. Thank you
StringBuilder is in the System.Text namespace. So you can either reference it explicitly:
System.Text.StringBuilder strQueryBuilder ...
Or add a using directive to the file:
using System.Text
...
StringBuilder strQueryBuilder ...
As for objCmd and objConn, where do you define those? They're not created in the code you posted. You do create a connection object here:
object Conn = new OracleConnection(strConn);
Maybe you mean to use Conn instead of objConn? But you don't create a command object anywhere. You need to declare and instantiate variables before you can use them.

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