I am android c# developer beginner and need to work in back ground showing my listview but my code have a load action such as fetching database and convert from byte array to image so I used async task but it hangs and give me this error Unhandled Exception:
Android.Util.AndroidRuntimeException: occurred
//this my async class :
public class UpdatePB : AsyncTask<string, string, string>
{
private Activity context;
private ProgressDialog progressDialog;
public List<Advertise_TableItem> GroupLst;
Dictionary<Advertise_TableItem, List<Replies_TableItem>> ChildLst;
// Advertise_HomeScreenAdapter adb;
public ExpandableListViewAdapter Adapter;
AbdoService.abdo_service AbdoService;
//string user_id;
Context myContext;
ExpandableListView listview;
DataTable table;
public UpdatePB(Activity context, ExpandableListView listview, Context myContext)
{
this.context = context;
this.listview = listview;
this.myContext = myContext;
}
protected override string RunInBackground(string[] #params)
{
//System.Threading.Thread.Sleep(3000);
//adb = new Advertise_HomeScreenAdapter(this, tableItems);
//listview.Adapter = adb;
//progressDialog = new ProgressDialog(context);
//progressDialog.Show();
AbdoService = new AbdoService.abdo_service();
GroupLst = new List<Advertise_TableItem>();
ChildLst = new Dictionary<Advertise_TableItem, List<Replies_TableItem>>();
if (CrossConnectivity.Current.IsConnected)
{
table = AbdoService.selectAllAdvertises().table;
int I = 0;
foreach (DataRow item in table.Rows)
{
// bitmap = BitmapFactory.DecodeByteArray(AbdoService.GetByteImage(item[1].ToString()).ByteImage, 0, AbdoService.GetByteImage(item[1].ToString()).ByteImage.Length);
GroupLst.Add(new Advertise_TableItem(item[1].ToString(), item[2].ToString(), item[3].ToString(), item[0].ToString()));
List<Replies_TableItem> child = new List<Replies_TableItem>();
//child.Add(new Replies_TableItem("mohammed", "comment 1 "));
//child.Add(new Replies_TableItem("ahmed", "comment 2 "));
var childTable = AbdoService.selectReply(item[0].ToString());
foreach (DataRow childItem in childTable.table.Rows)
{
child.Add(new Replies_TableItem(childItem[1].ToString(), childItem[2].ToString()));
}
ChildLst.Add(GroupLst[I], child);
I++;
}
}
else
{
if_connected();
}
Adapter = new ExpandableListViewAdapter(myContext, GroupLst, ChildLst);
////System.Threading.Thread.Sleep(3000);
listview.SetAdapter(Adapter);
for (int i = 0; i < Adapter.GroupCount; i++)
{
listview.ExpandGroup(i);
}
//listview.GroupClick += Listview_GroupClick;
//startServices();
////RunOnUiThread(() => progressBar.Visibility = ViewStates.Invisible);
return context.Title;
}
public void if_connected()
{
var callDialog = new Android.App.AlertDialog.Builder(context);
callDialog.SetTitle("Notify");
callDialog.SetMessage("connect internet");
callDialog.SetNeutralButton("ok", delegate
{
context.Finish();
context.StartActivity(typeof(AllAdvertises));
});
callDialog.Show();
}
protected override void OnPreExecute()
{
progressDialog = new ProgressDialog(context);
progressDialog.Show();
}
//protected override void OnProgressUpdate(params string[] values)
//{
// //mtv.Text = Convert.ToString(values[0]);
// //Android.Util.Log.Error("lv==", values[0] + "");
// listview.SetAdapter(Adapter);
// for (int i = 0; i < Adapter.GroupCount; i++)
// {
// listview.ExpandGroup(i);
// }
//}
protected override void OnPostExecute(string result)
{
result = context.Title;
progressDialog.Dismiss();
}
}
//this is my Activity function oncreate()
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetTheme(Resource.Style.AppTheme);
SetContentView(Resource.Layout.AllAdvertises);
//progressDialog = new ProgressDialog(this);
//progressDialog.SetMessage("hiiiiiiiiiiiii");
//progressDialog.Show();
// System.Threading.Thread.Sleep(1000);
//ProgressBar progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);
//RunOnUiThread(() => progressBar.Visibility=ViewStates.Visible);
//DoSomeWork1(arguments);
prefs = PreferenceManager.GetDefaultSharedPreferences(this);
TextView UserName = FindViewById<TextView>(Resource.Id.txtUserName);
string user_id = prefs.GetString("UserId", "0");
if (user_id != "0")
{
UserName.Text = " Hello " + prefs.GetString("UserName", "0");
}
//AbdoService = new AbdoService.abdo_service();
////table= b.GetResult();
//// //AbdoService.selectAllAdvertisesCompleted += AbdoService_selectAllAdvertisesCompleted;
//// //AbdoService.selectAllAdvertisesAsync();
listview = FindViewById<ExpandableListView>(Resource.Id.EdListView);
//GroupLst = new List<Advertise_TableItem>();
//ChildLst = new Dictionary<Advertise_TableItem, List<Replies_TableItem>>();
//if (CrossConnectivity.Current.IsConnected)
//{
// //table = AbdoService.selectAllAdvertises().table;
// int I = 0;
// foreach (DataRow item in table.Rows)
// {
// // bitmap = BitmapFactory.DecodeByteArray(AbdoService.GetByteImage(item[1].ToString()).ByteImage, 0, AbdoService.GetByteImage(item[1].ToString()).ByteImage.Length);
// GroupLst.Add(new Advertise_TableItem(item[1].ToString(), item[2].ToString(), item[3].ToString(), item[0].ToString()));
// List<Replies_TableItem> child = new List<Replies_TableItem>();
// //child.Add(new Replies_TableItem("mohammed", "comment 1 "));
// //child.Add(new Replies_TableItem("ahmed", "comment 2 "));
// var childTable = AbdoService.selectReply(item[0].ToString());
// foreach (DataRow childItem in childTable.table.Rows)
// {
// child.Add(new Replies_TableItem(childItem[1].ToString(), childItem[2].ToString()));
// }
// ChildLst.Add(GroupLst[I], child);
// I++;
// }
//}
//else
//{
// if_connected();
//}
////adb = new Advertise_HomeScreenAdapter(this, tableItems);
////listview.Adapter = adb;
//Adapter = new ExpandableListViewAdapter(this, GroupLst, ChildLst);
UpdatePB uptask = new UpdatePB(this, listview, this);
uptask.Execute("paramter");
//uptask.GetResult();
//listview.SetAdapter(Adapter);
//for (int i = 0; i < Adapter.GroupCount; i++)
//{
// listview.ExpandGroup(i);
//}
listview.GroupClick += Listview_GroupClick;
startServices();
//////RunOnUiThread(() => progressBar.Visibility = ViewStates.Invisible);
}
you can not touch the UI from a background thread so you need to move this line:
listview.SetAdapter(Adapter);
for (int i = 0; i < Adapter.GroupCount; i++)
{
listview.ExpandGroup(i);
}
from RunInBackground(string[] #params) to OnPostExecute(string result)
also move if_connected(); from RunInBackground(string[] #params) to OnPostExecute(string result) because if_connected(); shows a dialog it can not be run in background
And add your complete Stack Trace of error to your question because there may be some other errors there in addition to mentioned ones.
Related
Is there a way for me to link my module in all of my form i'm using c# app and this is my code. This is actually a notification bell that will notify users if he/she has/have notifications. I already linked it on homepage how am i able to do that in all other pages
private void systemNotificationREXS(HomePage module)
{
TextBox Username = (TextBox)module.FindControl("Hide_user");
Label Fullname = (Label)module.FindControl("userfullname");
Label notifLabel = (Label)module.FindControl("notifLabel");
using (con = new SqlConnection(EXCUSESLPCON))
{
using (cmd = new SqlCommand("SYSTEMNOTIFICATIONEXSLIP", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userfullname", Fullname.Text);
con.Open();
using(adp = new SqlDataAdapter(cmd))
{
using(dt = new DataTable())
{
adp.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++ )
{
int notifcount = int.Parse(dt.Rows[i]["notifcount"].ToString());
string modulename = dt.Rows[i]["modulename"].ToString();
string modulebody = modulename + "Body";
string moduleLabel = modulename + "Label";
Label namebox = (Label)module.FindControl(modulename);
if (notifcount > 0)
{
namebox.Visible = true;
namebox.Text = notifcount.ToString();
module.FindControl(modulebody).Visible = true;
try
{
module.FindControl(moduleLabel).Visible = true;
}
catch
{
notifLabel.Visible = false;
}
}
else
{
namebox.Visible = false;
module.FindControl(modulebody).Visible = false;
try
{
module.FindControl(moduleLabel).Visible = false;
}
catch
{
notifLabel.Visible = false;
}
}
}
}
}
con.Close();
}
}
}
internal void notificationSystemREXS(string fullname, string hide_user, HomePage modulename)
{
systemNotificationREXS(modulename);
}
Code to linked on homepage:
private void systemNotificationREXS()
{
Notification moduleacc = new Notification();
moduleacc.notificationSystemREXS(userfullname.Text, Hide_user.Text, this);
}
Your method does very simple job, but you have made it complicated and over dependent on the module and other stuff.
The method should return only the notification data for the user and let the caller of the method to decide what to do with the data.
Consider doing following.
public class NotificationData
{
public int NotificationCount {get;set;}
public int ModuleName {get;set;}
}
public class NotificationService
{
public static List<NotificationData> GetNotificationData(string username)
{
var notificationList = new List<NotificationData>();
using (con = new SqlConnection(EXCUSESLPCON))
{
using (cmd = new SqlCommand("SYSTEMNOTIFICATIONEXSLIP", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userfullname", Fullname.Text);
con.Open();
using(adp = new SqlDataAdapter(cmd))
{
using(dt = new DataTable())
{
for (int i = 0; i < dt.Rows.Count; i++ )
{
var notification = new NotificationData();
notification.NotificationCount = int.Parse(dt.Rows[i]["notifcount"].ToString());
notification.ModuleName = dt.Rows[i]["modulename"].ToString();
}
}
}
}
}
return notificationList
}
}
Now you should use this method from whichever page you want as following.
Let say you want to use it from HomePage. So you may write following code in Page_Load event of HomePage. (I am assuming here that HomePage is a web page and it has all the controls loaded before this code gets executed).
Label userNameLabel = (Label)this.FindControl("userfullname");
var userName = userNameLabelText;
var notificationList = NotificationService.GetNotificationData(userName);
foreach(var notification in notificationList)
{
var modulename = notification.ModuleName;
var notifcount = notification.Count;
string modulebody = modulename + "Body";
string moduleLabel = modulename + "Label";
Label namebox = (Label)this.FindControl(modulename);
if (notifcount > 0)
{
namebox.Visible = true;
namebox.Text = notifcount.ToString();
this.FindControl(modulebody).Visible = true;
try
{
this.FindControl(moduleLabel).Visible = true;
}
catch
{
notifLabel.Visible = false;
}
}
else
{
namebox.Visible = false;
this.FindControl(modulebody).Visible = false;
try
{
this.FindControl(moduleLabel).Visible = false;
}
catch
{
notifLabel.Visible = false;
}
}
}
I hope this should help you resolve your issue.
i want to draw route line using mkMap in xamarin ios. my code is working correctly but it does not show route line between points. my code is given below
my first picture shows the starting annotation point and second picture shows ending annotation point
MapView Code:
private MKMapView _map;
private MapDelegate _mapDelegate;
public QiblaCompassVC (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
_map = new MKMapView(mapsView.Bounds)
{
MapType = MKMapType.Standard,
ShowsUserLocation = true,
ZoomEnabled = true,
ScrollEnabled = true
};
//_map = new MKMapView(mapsView.Bounds);
// _map.ShowsUserLocation = true;
_mapDelegate = new MapDelegate();
_map.Delegate = _mapDelegate;
//mapsView.Add(_map);
View = _map;
var target = new CLLocationCoordinate2D(30.3753, 69.3451);
var viewPoint = new CLLocationCoordinate2D(21.3891, 39.8579);
var annotation = new mapAnnotation(new CLLocationCoordinate2D(30.3753, 69.3451), "Pakistan", "Countery of love");
_map.AddAnnotation(annotation);
var annotation1 = new mapAnnotation(new CLLocationCoordinate2D(21.3891, 39.8579), "Makka", "Allah home");
_map.AddAnnotation(annotation1);
var camera = MKMapCamera.CameraLookingAtCenterCoordinate(target, viewPoint, 500);
_map.Camera = camera;
createRoute();
//CLLocationCoordinate2D coords = new CLLocationCoordinate2D(30.3753, 69.3451);
//MKCoordinateSpan span = new MKCoordinateSpan(MilesToLatitudeDegrees(20), MilesToLongitudeDegrees(20, coords.Latitude));
//_map.Region = new MKCoordinateRegion(coords, span);
}
public void createRoute()
{
var dict = new NSDictionary();
var orignPlaceMark = new MKPlacemark(new CLLocationCoordinate2D(30.3753, 69.3451), dict);
var sourceItem = new MKMapItem(orignPlaceMark);
//End at Xamarin Cambridge Office
var destPlaceMark = new MKPlacemark(new CLLocationCoordinate2D(21.3891, 39.8579), dict);
var destItem = new MKMapItem(destPlaceMark);
var request = new MKDirectionsRequest
{
Source = sourceItem,
Destination = destItem,
RequestsAlternateRoutes = true,
};
var directions = new MKDirections(request);
directions.CalculateDirections((response, error) =>
{
if (error != null)
{
Console.WriteLine(error.LocalizedDescription);
}
else
{
//Add each Polyline from route to map as overlay
foreach (var route in response.Routes)
{
_map.AddOverlay(route.Polyline);
}
}
});
}
MapDelegate Code:
class MapDelegate : MKMapViewDelegate
{
public override MKOverlayRenderer OverlayRenderer(MKMapView mapView, IMKOverlay overlay)
{
if (overlay is MKPolyline)
{
var route = (MKPolyline)overlay;
var renderer = new MKPolylineRenderer(route) { StrokeColor = UIColor.Blue };
return renderer;
}
return null;
}
public override MKOverlayView GetViewForOverlay(MKMapView mapView, IMKOverlay overlay)
{
if (overlay is MKPolyline)
{
// return a view for the polygon
MKPolyline l_polyline = overlay as MKPolyline;
MKPolylineView l_polylineView = new MKPolylineView(l_polyline);
MKPolylineRenderer l_polylineRenderer = new MKPolylineRenderer(l_polyline);
l_polylineView.FillColor = UIColor.Blue;
l_polylineView.StrokeColor = UIColor.Red;
return l_polylineView;
}
return null;
}
}
The problem is in the GetViewForOverlay method,
The overlay parameter is not not of type MKPolyline, it is a wrapper containing the MKPolyline, this is how to get it :
MKOverlayRenderer GetOverlayRenderer(MKMapView mapView, IMKOverlay overlayWrapper)
{
var overlay = Runtime.GetNSObject(overlayWrapper.Handle) as IMKOverlay;
...
}
Source from xamarin forum
I am trying to filter the pins on a map depending on what you write in the searchbar. So if you write for example: "Unit" then only the pins with the adress "Unit....(ed states)" will show up. I have started with some code but I am not sure how I should carry on. When I type something now every pin loads instead of the ones that match with the inputted text on the searchbar. I guess I have to use the filterfunction before I add the pins.
This is my startPage:
public StartPage ()
{
searchBar.TextChanged += (sender2, e2) => FilterContacts(searchBar.Text);
searchBar.SearchButtonPressed += (sender2, e2) => FilterContacts(searchBar.Text);
}
This is where the filter is happening. I get the data from my DB.
private async void FilterContacts (string filter)
{
map.Pins.Clear ();
if (string.IsNullOrWhiteSpace (filter)) {
} else {
var getItems = await phpApi.getInfo ();
foreach (var currentItem in getItems["results"]) {
theName = currentItem ["Name"].ToString (); //theName = string
theAdress = currentItem ["Adress"].ToString (); //theAdress = String
var theUserPosition = theAdress;
Geocoder gc = new Geocoder ();
Task<IEnumerable<Position>> result =
gc.GetPositionsForAddressAsync (theUserPosition);
if (theAdress != null) {
IEnumerable<Position> data = await result;
foreach (Position p in data) {
var pin = new Pin ();
pin.Position = new Position (p.Latitude, p.Longitude);
pin.Label = theName;
pin.Address = theAdress;
map.Pins.Add (pin);
theAdress.ToLower ().Contains (filter.ToLower ());
}
}
}
}
}
load the data and geocode it ONCE and store it; then only call the filter logic
public StartPage ()
{
searchBar.TextChanged += (sender2, e2) => FilterPins(searchBar.Text);
searchBar.SearchButtonPressed += (sender2, e2) => FilterPins(searchBar.Text);
}
// create a list to store our Pins
List<Pin> myPins = new List<Pin>();
private async override void OnAppearing() {
if (myPins.Count == 0) {
myPins = await LoadData();
filterPins(string.Empty);
}
}
// load the data, geocode, store results
private async List<Pin> LoadData() {
var pins = new List<Pin>();
var getItems = await phpApi.getInfo ();
foreach (var currentItem in getItems["results"]) {
Geocoder gc = new Geocoder ();
var pos = await gc.GetPositionsForAddressAsync (theUserPosition);
foreach (Position p in pos) {
var pin = new Pin ();
pin.Position = new Position (p.Latitude, p.Longitude);
pin.Label = theName;
pin.Address = theAdress;
pins.Add(pin);
}
}
return pins;
}
private async void FilterPins (string filter)
{
map.Pins.Clear ();
foreach(Pin p in myPins) {
if (string.IsNullOrWhiteSpace(filter) || (p.Address.Contains(filter)) {
map.Pins.Add(p);
}
}
}
I am working on Windows Phone 8 project. In my project there are 10 Events with 10 EventHandlers ReverseGeocodeQuery_QueryCompleted (1 to 10). When first EventHandler is completed it turn on second event.
What should I implement to manage those Events without so much code.
code
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(0);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_1;
myReverseGeocodeQuery.QueryAsync();
private void ReverseGeocodeQuery_QueryCompleted_1(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine("Pierwszy");
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
}
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(1);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_2;
myReverseGeocodeQuery.QueryAsync();
}
}
private void ReverseGeocodeQuery_QueryCompleted_2(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine("Drugi");
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(2);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_3;
myReverseGeocodeQuery.QueryAsync();
}
}
}
Example Solution 1
public class DataContainer
{
public string Description { get; set; }
public GeoCoordinate Coordinate { get; set; }
//public List<GeoCoordinate> mySimulationCoordinates { get; set; }
public String EnterSimulation() {
StringBuilder strRet = new StringBuilder();
List<GeoCoordinate> mySimulationCoordinates = new List<GeoCoordinate>();
mySimulationCoordinates.Add(new GeoCoordinate(51.760752, 19.458216));
mySimulationCoordinates.Add(new GeoCoordinate(51.760757, 19.458356));
mySimulationCoordinates.Add(new GeoCoordinate(51.760738, 19.458442));
mySimulationCoordinates.Add(new GeoCoordinate(51.7607, 19.458501));
mySimulationCoordinates.Add(new GeoCoordinate(51.760662, 19.458533));
var descriptions = new[] { "Pierwszy", "Drugi", "Trzeci", "Czwarty", "PiÄ…ty" }; //etc
var zipped = mySimulationCoordinates.Zip(descriptions, (coord, desc) => new DataContainer { Description = desc, Coordinate = coord });
int k = zipped.Count();
foreach (var item in zipped)
{
var currentItem = item;
using (var waitHandle = new AutoResetEvent(false))
{
var geocodeQuery = new ReverseGeocodeQuery();
geocodeQuery.GeoCoordinate = item.Coordinate;
geocodeQuery.QueryCompleted += (sender, args) =>
{
if (args.Error == null)
{
if (args.Result.Count > 0)
{
MapAddress address = args.Result[0].Information.Address;
//label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine(currentItem.Description);
str.AppendLine("House Number" + address.HouseNumber);
str.AppendLine("Street " + address.Street);
strRet.AppendLine("->");
strRet.Append(str);
waitHandle.Set();
}
}
};
geocodeQuery.QueryAsync();
waitHandle.WaitOne();
}
}
return strRet.ToString();
}
It stuck on 1st item. Is inside and wait ... wait ... can't pass to next element.
Umm... Let's see, shouldn't that be easier?
Warning: untested
public class DataContainer
{
public string Description {get;set;}
public GeoCoordinate Coordinate {get;set;}
}
var descriptions = new[] {"Pierwszy" , "Drugi" , "Trzeci" }; //etc
var zipped = mySimulationCoordinates.Zip(descriptions, (coord, desc) => new DataContainer { Description = desc, Coordinate = coord });
foreach(var item in zipped)
{
var currentItem = item;
using(var waitHandle = new AutoResetEvent(false))
{
var geocodeQuery = new ReverseGeocodeQuery();
geocodeQuery.GeoCoordinate = currentItem.Coordinates;
geocodeQuery.QueryCompleted += (sender, args) => {
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = args.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine(currentItem.Description);
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
waitHandle.Set();
}
}
};
geoCodeQuery.QueryAsync();
waitHandle.WaitOne();
}
}
That should guarantee you that one event is handled after another in order.
I am sharing a static array between a number of System.Threading.Timer simultaneously. This array is accessed only by the first timer thread & second timer will not accessed this array. An exception is displayed: "error can not evaluate expression a native frame is on top of the call stack in c#"
please reply
project code:
public partial class OPC_server : DevExpress.XtraEditors.XtraForm
{
private System.Threading.Timer timer1;
private System.Threading.Timer timer2;
parameter param = new parameter();//another class
private static readonly object myLockHolder = new object();
private static readonly object myLockHolder1 = new object();
public static OpcServer[] _opcServer;
private void OPC_server_Load(object sender, EventArgs e)
{
getconnectedOPC();
}
public void getconnectedOPC()
{
ds = opcconn.GetOPCServerInfo();
int i=0;
DataTable dtOPC=new DataTable();
if (ds.Tables[0].Rows.Count != 0 || ds.Tables[0] != null)
{
dtOPC = ds.Tables[0].Copy();
_opcServer = new OpcServer[dtOPC.Rows.Count];
TimeSpan delayTime = new TimeSpan(0, 0, 1);
TimeSpan intervalTime = new TimeSpan(0, 0, 0, 0, 450);
foreach (DataRow row in dtOPC.Rows)
{
if (i <= dtOPC.Rows.Count)
{
//connetion(row);
getconnect(i, row, dtOPC.Rows.Count);
i++;
}
}
connetion(dtOPC.Rows.Count);
}
}
//connecting the server
public void getconnect(int conn, DataRow r,int rows)
{
DataSet ds2=new DataSet();
DataTable dt2 = new DataTable();
try
{
string machinename = Convert.ToString(r["OPCIPAddress"]);
string servername = Convert.ToString(r["OPCName"]);
_opcServer[conn] = new OpcServer();
int i = _opcServer[conn].Connect(machinename, servername);
if (i == 0)
{
opcconn.update("true", servername);
writelog(servername, "connected");
}
else
{
opcconn.update("false", servername);
writelog(servername, "disconnected");
}
}
catch (OPCException e)
{
servername = Convert.ToString(r["OPCName"]);
opcconn.update("false", servername);
writelog(servername, e.Message.ToString());
}
catch (ApplicationException e)
{
servername = Convert.ToString(r["OPCName"]);
opcconn.update("false", servername);
writelog(servername, "No instance server");
}
}
public void connetion(object state)
{
int k ,i,q=0;
k = (System.Int32)state;
DataSet dsgroup=new DataSet();
while(j < k)
{
try
{
bool val;
HRESULTS re;
SrvStatus status;
DateTime dt;
i = _opcServer[j].GetStatus(out status);
if (HRESULTS.Failed(i))
{
try
{
opcconn.update("false", _opcServer[j].ServerName.ToString());
string IP = opcconn.search(_opcServer[j].ServerName.ToString());
_opcServer[j].Connect(IP, _opcServer[j].ServerName.ToString());
opcconn.update("true", _opcServer[j].ServerName.ToString());
j++;
}
catch
{
opcconn.update("false", _opcServer[j].ServerName.ToString());
j++;
}
}
else
{
val = HRESULTS.Succeeded(i);
dsgroup = grpclass.getgroupinfo(j + 1);
if (dsgroup.Tables[0].Rows.Count != 0)
{
grpdt = new DataTable();
grpdt = dsgroup.Tables[0].Copy();
foreach (DataRow Row in grpdt.Rows)
{
if (groupcnt <= 128)
{
if (cntgroup < grpdt.Rows.Count)
{
grp = _opcServer[j].AddGroup((Convert.ToString(Row["GroupName"])), (Convert.ToBoolean(Row["setactive"])), (Convert.ToInt32(Row["refreshRate"])), 1);
ds1 = param.getparameter1(Convert.ToInt32(Row["groupID"]));
if (ds1.Tables[0].Rows.Count != 0)
{
dt1 = ds1.Tables[0].Copy();
int tq = 0;
item1 = new OPCItemDef[dt1.Rows.Count];
int clienthandle = 1;
foreach (DataRow r in dt1.Rows)
{
if (tq < item1.Length)
{
item1[tq] = new OPCItemDef(Convert.ToString(r["param_ID"]), Convert.ToBoolean(r["active"]), clienthandle, VarEnum.VT_EMPTY);
++clienthandle;
tq++;
}
}
int y = grp.AddItems(item1, out addRslt);
// thread started like each group assign one thread
OPCthread(Row, groupcnt);
groupcnt++;
cntgroup++;
}
}
}
}
}
cntgroup = 0;
j++;
}
}
catch (OPCException)
{
string servername = opcconn.getserver(j + 1);
string IPadd = opcconn.search(servername);
_opcServer[j].Connect(IPadd, servername);
}
catch (IndexOutOfRangeException)
{
j = 0;
}
catch (InvalidCastException e)
{
try
{
// writelog1(_opcServer[j].ServerName.ToString(), "disconnected");
opcconn.update("false", _opcServer[j].ServerName.ToString());
string IP = opcconn.search(_opcServer[j].ServerName.ToString());
_opcServer[j].Connect(IP, _opcServer[j].ServerName.ToString());
opcconn.update("true", _opcServer[j].ServerName.ToString());
j++;
}
catch
{
// writelog1(_opcServer[j].ServerName.ToString(), "connection failed");
opcconn.update("true", _opcServer[j].ServerName.ToString());
j++;
}
}
catch (ArgumentOutOfRangeException)
{
j = 0;
}
catch (NullReferenceException)
{
try
{
// writelog1("server'" + j + "' ", "no server instance");
OPC1 = opcconn.getserver(j + 1);
string IPA = opcconn.search(OPC1);
_opcServer[j].Connect(IPA, OPC1);
opcconn.update("true", OPC1);
writelog(OPC1, "connected");
j++;
}
catch (OPCException e)
{
opcconn.update("false", OPC1);
writelog(OPC1, e.Message.ToString());
j++;
}
catch (ApplicationException e)
{
opcconn.update("false", OPC1);
writelog(OPC1, "No instance server");
j++;
}
}
}
}
public void OPCthread(DataRow r2,int timerinfo)
{
if (timerinfo == 0)
{
int rer = Convert.ToInt32(r2["refreshRate"]);//at least 1 second
TimeSpan dueTime = new TimeSpan(0, 0,0,0,rer);
TimeSpan interval = new TimeSpan(0, 0, 0 ,0 ,rer);
timer1 = new System.Threading.Timer(register, r2, dueTime,interval);
}
else if (timerinfo == 1)
{
TimeSpan dueTime;
TimeSpan interval;
int rer1 = Convert.ToInt32(r2["refreshRate"]);
dueTime = new TimeSpan(0, 0, 0, 0, rer1);
interval = new TimeSpan(0, 0, 0, 0, rer1);
timer2 = new System.Threading.Timer(register1, r2, dueTime, interval);
}
}
public void register(object row1)
{
try
{
lock (myLockHolder)
{
int cnt = 0, cnt1 = 0;
ItemValue[] rVals;
OPCItemDef[] item;
OpcServer srv = new OpcServer();
string[] array;
//SrvStatus status1;
DataSet paramds = new DataSet();
DataTable paramdt = new DataTable();
DataRow dt = (System.Data.DataRow)row1;
int serverID = Convert.ToInt32(dt["OPCServerID"]);
paramds = param.getparameter(Convert.ToInt32(dt["groupID"]));
if (Convert.ToBoolean(dt["setactive"]) == true)
{
if (paramds != null && paramds.Tables[0].Rows.Count != 0)
{
paramdt = paramds.Tables[0].Copy();
int tq = 0;
item = new OPCItemDef[paramdt.Rows.Count];
int clienthandle = 1;
foreach (DataRow r in paramdt.Rows)
{
if (tq < item.Length)
{
item[tq] = new OPCItemDef(Convert.ToString(r["param_ID"]), Convert.ToBoolean(r["active"]), clienthandle, VarEnum.VT_EMPTY);
++clienthandle;
tq++;
}
}
array = new string[item.Length];
cnt1 = 0;
while (cnt1 < array.Length)
{
array[cnt1] = item[cnt1].ItemID;
cnt1++;
}
rVals = _opcServer[serverID - 1].Read(array, Convert.ToInt32(dt["refreshRate"]));
//this line i got the exception when i checking the value of the _opcserver varible in locals the it will be display as "error can not evaluate expression a native frame is on top of the call stack in c#" & thread will stop the execution.
param.update(rVals, Convert.ToInt32(dt["groupID"]));
}
}
}
}
catch (ThreadAbortException) { }
finally { }
}
public void register1(object row2)
{
try
{
lock (myLockHolder1)
{
int cnt = 0, cnt11 = 0;
ItemValue[] rVals1;
OPCItemDef[] item1;
OpcServer srv1 = new OpcServer();
string[] array1;
DataSet paramds1 = new DataSet();
DataTable paramdt1 = new DataTable();
DataRow dt1 = (System.Data.DataRow)row2;
int serverID1 = Convert.ToInt32(dt1["OPCServerID"]);
// Boolean gstatus = grpclass.getstatus(Convert.ToInt32(dt["groupID"]));
paramds1 = param.getparameter2(Convert.ToInt32(dt1["groupID"]));
if (Convert.ToBoolean(dt1["setactive"]) == true)
{
if (paramds1 != null)
{
paramdt1 = paramds1.Tables[0].Copy();
int tq1 = 0;
item1 = new OPCItemDef[paramdt1.Rows.Count];
int clienthandle1 = 1;
foreach (DataRow r in paramdt1.Rows)
{
if (tq1 < item1.Length)
{
item1[tq1] = new OPCItemDef(Convert.ToString(r["param_ID"]), Convert.ToBoolean(r["active"]), clienthandle1, VarEnum.VT_EMPTY);
clienthandle1++;
tq1++;
}
}
array1 = new string[item1.Length];
cnt11 = 0;
while (cnt11 < array1.Length)
{
array1[cnt11] = item1[cnt11].ItemID;
cnt11++;
}
rvals = _opcServer[serverID1 - 1].Read(array1, Convert.ToInt32(dt1["refreshRate"]));//this line i got the exception when i checking the value of the _opcserver varible in locals the it will be display as "error can not evaluate expression a native frame is on top of the call stack in c#" & thread will stop the execution.
param.update1(rVals1, Convert.ToInt32(dt1["groupID"]));
}
}
}
}
catch { }
finally { }
}
The error you are seeing is not an Exception. The message you see is just letting you know that a native frame is on the top of the stack instead of a managed frame.
It's possible that the error you're seeing has nothing to do with the array - but it's difficult to tell without seeing some of your code.
There are two very common problems involved with multi-threaded programs. If I had to take a guess, you're getting an InvalidOperationException either because the "Object is currently in use" or because "Cross-thread operation not valid".
If the first is the case, you need to use something like:
lock (myObject)
{
// Alter myObject
}
see Locks.
And if the second is the case, you need to use something like:
Invoke(new MethodInvoker(delegate()
{
// Alter stuff in Forms/Controls
}));
see Invoke.
It would really help if you could post the exact Exception you're getting and the code which produces it.
Edit: You have posted a mountain of code to look through. It is very unhelpful.
You say the line causing it is
rvals = _opcServer[serverID1 - 1].Read(array1, Convert.ToInt32(dt1["refreshRate"]));
but nowhere in your code can I see you have declared the variable _opcServer.
As I have already told you, the native frame message isn't an Exception and doesn't mean that there is anything wrong with your program! - it's simply the debugger telling you that it can't give you the values of the managed variables.
Please put this code around the line to identify which type of Exception you are getting, and tell me what the Exception is.
try
{
rvals = _opcServer[serverID1 - 1].Read(array1, Convert.ToInt32(dt1["refreshRate"]));
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show("Exception: " + ex.GetType().ToString() +
"\r\nMessage: " + ex.Message);
}