How to display multiple icons on same points in googlemap in .net? - c#

How to display multiple icons on same points in googlemap in .net using goolemap api 3
Below is my code
public void selectTrainings(string strQuery)
{
try
{
clsTblMembers objtblMember = new clsTblMembers();
objtblMember.StrEmail = strQuery.ToString();
DataTable dt = objtblMember.SelectSearch();
if (dt != null)
{
int i;
for (i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["Latitude"].ToString() != "" && dt.Rows[i]["Longitude"].ToString() != "")
{
string StrLat = dt.Rows[i]["Latitude"].ToString();
string StrLon = dt.Rows[i]["Longitude"].ToString();
double Numlat;
bool isNumlat = double.TryParse(StrLat, out Numlat);
double Numlon;
bool isNumlon = double.TryParse(StrLon, out Numlon);
if ((isNumlat) && (isNumlon))
{
//coordinates datatype =double;
m1 = new MapControl.MapMarker();
m1.Latitude = Convert.ToDouble(dt.Rows[i]["Latitude"].ToString());
m1.Longitude = Convert.ToDouble(dt.Rows[i]["Longitude"].ToString());
getTraining(Convert.ToInt32(dt.Rows[i]["intId"].ToString()), Convert.ToInt32(dt.Rows[i]["intTypeId"].ToString()), dt.Rows[i]["strCode"].ToString(), dt.Rows[i]["strConductedBy"].ToString(), dt.Rows[i]["dtFromDate"].ToString(), dt.Rows[i]["dtToDate"].ToString(), dt.Rows[i]["strName"].ToString(), dt.Rows[i]["strUC"].ToString(), dt.Rows[i]["strVillage"].ToString());
if (dt.Rows[i]["intTypeId"].ToString() == "1")
{
m1.Title ="CMST - "+ dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t1.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "2")
{
m1.Title = "LMST - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t2.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "3")
{
m1.Title = " Govt.Official Training - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t3.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "4")
{
m1.Title = "Gender Based Violence - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/pg.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "5")
{
m1.Title = "Human Rights - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/ph.png";
}
else
{
m1.Title = "Livelihoods Skills Training - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t4.png";
}
m1.ImageSize1 = 32.0;
m1.ImageSize2 = 37.0;
m1.ImagePoint1 = 0;
m1.ImagePoint2 = 0;
m1.ImagePoint3 = 16.0;
m1.ImagePoint4 = 18.0;
m1.Shadow = "mapIcons/shadow.png";
m1.ShadowSize1 = 51.0;
m1.ShadowSize2 = 37.0;
m1.ShadowPoint1 = 0;
m1.ShadowPoint2 = 0;
m1.ShadowPoint3 = 16.0;
m1.ShadowPoint4 = 18.0;
GoogleMap.Markers.Add(m1);
}
}
}
}
}
catch (Exception ex)
{
}
}

Related

C# Loop over all possible values, when not found increase value and continue

I need to send a request for every supplier code to a webservice (i know that sounds crazy but the owner designed it this way).
The supplier code format is:
30X1X1XXXXX1
You can check what i did so far (github link: https://github.com/rareba/SiapWebServices_Library/blob/master/SiapWebServices_Library/SiapWebServicesFornitore.cs)
public static List<StructAnaFornitoreOut> Get_All_Suppliers(WebServicesFornitoreClient client, StructLogin loginCredentials, string showSuspended = "N", string searchType = "R")
{
var supplier_list = new List<StructAnaFornitoreOut>();
var supplier_retrived = new StructAnaFornitoreOut
{
esito = new StructEsito
{
stato = "OK",
}
};
int KO_Count = 0;
int conto = 1;
int sottoconto = 1;
int codice = 0;
string codFornitore = Generate_Supplier_Code_String(codice, sottoconto, conto);
var search = new StructAnaFornitoreIn
{
IAnaFornitore = new StructAnaFornitore
{
codice = codFornitore
},
IAzione = "C",
//vModRicerca = new string[] { "COD_FIS","PAR_IVA","ALT_SIS" }
};
while (KO_Count < 10)
{
while (KO_Count < 10)
{
while (KO_Count < 10)
{
supplier_retrived = client.gestioneAnagraficaFornitore(loginCredentials, search);
if (supplier_retrived.esito.stato == "KO")
{
KO_Count++;
}
else
{
supplier_list.Add(supplier_retrived);
codFornitore = Generate_Supplier_Code_String(codice, sottoconto, conto);
Console.WriteLine(codFornitore);
codice++;
search.IAnaFornitore.codice = codFornitore;
}
}
KO_Count = 0;
sottoconto++;
}
KO_Count = 0;
conto++;
}
return supplier_list;
}
// Returns a supplier code string increased by 1
public static string Generate_Supplier_Code_String(int codice = 0, int sottoconto = 1, int conto = 1, string mastro = "30")
{
codice++;
string string_conto = " ";
string string_sottoconto = " ";
string string_codice = " ";
if (conto > 9)
{
string_conto = "";
}
if (sottoconto > 9)
{
string_sottoconto = "";
}
if (codice > 9)
{
string_codice = " ";
}
else if (codice > 99)
{
string_codice = " ";
}
else if (codice > 999)
{
string_codice = " ";
}
else if (codice > 9999)
{
string_codice = " ";
}
else if (codice > 99999)
{
string_codice = " ";
}
else if (codice >= 999999)
{
string_codice = "";
}
string customercode = mastro + string_conto + conto + string_sottoconto + sottoconto + string_codice + codice;
return customercode;
}
However this doesn't work at all: it stops at supplier 30 1 1 100 and starts increasing sottoconto like there is no tomorrow.
The idea should be to do something like:
- Get the supplier data
- Increase codice by 1
- If for 10 times you get nothing (esito.status = "KO") then increase sottoconto and start again from codice = 1
- If after incresing sottoconto you still get nothing for 10 times then increase conto and start again from codice = 0

C# Simple Passing Parameters Issue

I know I sound like a bad programmer right now - but I'm new and I can't figure out how to use this reference thing and pass parameters, I mean I know how to do it - but at the same time - this isn't working and I don't know why.
static void Main(string[] args) {
DealCard(ref card);
Console.WriteLine();
Console.ReadLine();
}
private static void DealCard(string card) {
string finalNum = "";
string finalSuite = "";
bool diffCard = false;
do {
Random cardPicker = new Random();
int cardSuite = cardPicker.Next(1, 5);
if (cardSuite == 1) {
finalSuite = "Hearts";
} else if (cardSuite == 2) {
finalSuite = "Spades";
} else if (cardSuite == 3) {
finalSuite = "Clubs";
} else if (cardSuite == 4) {
finalSuite = "Diamonds";
}
int cardNum = cardPicker.Next(1, 14);
if (cardNum == 1) {
finalNum = "Ace";
} else if (cardNum == 2) {
finalNum = "Two";
} else if (cardNum == 3) {
finalNum = "Thre";
} else if (cardNum == 4) {
finalNum = "Four";
} else if (cardNum == 5) {
finalNum = "Five";
} else if (cardNum == 6) {
finalNum = "Six";
} else if (cardNum == 7) {
finalNum = "Seven";
} else if (cardNum == 8) {
finalNum = "Eight";
} else if (cardNum == 9) {
finalNum = "Nine";
} else if (cardNum == 10) {
finalNum = "Ten";
} else if (cardNum == 11) {
finalNum = "Jack";
} else if (cardNum == 12) {
finalNum = "Queen";
} else if (cardNum == 13) {
finalNum = "King";
}
string newCard = finalNum + " of " + finalSuite;
if (newCard != card) {
card = finalNum + " of " + finalSuite;
diffCard = true;
} else {
}
card = newCard;
} while (diffCard == false);
}
Yes I know that massive 'if' is an eyesore.
Yes I know I could accomplish this in less than half the lines.
Yes I know it's a simple question.
Yes I know I'm bad, but I'd like to humbly request that anyone helps me to stop losing hair over this.
You have to declare your method like this:
private static void DealCard(ref string card)
Basically the method has to accept a ref parameter.
Here is documentation to support the answer:
Value Type Parameters
Reference Type Parameters
Your code can be like this
public class Program
{
public static void Main(string[] args) {
string card = "";
DealCard(ref card);
}
private static void DealCard(ref string card)
{
string finalNum = "";
string finalSuite = "";
bool diffCard = false;
do {
Random cardPicker = new Random();
int cardSuite = cardPicker.Next(1, 5);
string[] suite = new String[]{"Hearts","Spades", "Clubs", "Diaminds"};
int cardNum = cardPicker.Next(1, 3);
string[] numbers = new String[]{"one","two","three", "four"};
string newCard = numbers[cardNum] + " of " + suite[cardSuite];
if (newCard != card) {
card = finalNum + " of " + finalSuite;
diffCard = true;
} else {
}
card = newCard;
Console.WriteLine(newCard);
} while (diffCard == false);
}
}

Add text to list when user presses button in Android app?

I am having some trouble with the verse button. i am not sure what I am doing wrong but I need to make it where the user presses the verse button and it adds the textview of the word "Verse" to the list that was created. Please help. What am I doing wrong. This was written for Android using C# in Xamarin by the way.
namespace Songression
{
public class CheckRect{
public int top{ get; set; }
public int height{ get; set; }
}
[Activity (Label = "Songression")]
public class results : Activity, View.IOnTouchListener
{
//CheckBox[] check;
List<LinearLayout> linearSet;
//List<CheckRect> rectList;
ScrollView scrollView;
EditText editText = null;
LinearLayout view;
bool moveOrEdit = false;
int screenWidth;
List<String> checkTextList;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.results);
var metrics = Resources.DisplayMetrics;
screenWidth = metrics.WidthPixels;
//var widthInDp = ConvertPixelsToDp(metrics.WidthPixels);
view = FindViewById<LinearLayout> (Resource.Id.linearlayout0);
checkTextList = new List<String>();
checkTextList.Add ("10 bucks in your pocket and barely making it.");
checkTextList.Add ("100 steps to the water");
checkTextList.Add ("18 and going to Hollywood");
checkTextList.Add ("3 years to propose");
String checkTextSet = Intent.GetStringExtra ("MyData") ?? "";
if (checkTextSet == null || checkTextSet == "") {
} else {
String[] textSet = checkTextSet.Split (',');
checkTextList.AddRange (textSet);
}
//Back Button
Button buttonBack = FindViewById<Button> (Resource.Id.buttonBack);
buttonBack.Click += delegate {
Finish();
};
///
//AddLine Button
Button buttonAdd = FindViewById<Button> (Resource.Id.buttonAdd);
buttonAdd.Click += delegate {
addTextPro(false,"");
};
///
//Add Verse
//Button buttonVerse = FindViewById <Button> (Resource.Id.buttonVerse);
//buttonVerse.Click += delegate {
// checkTextList.Add("Verse"));
//};
{
///
//Email Button
Button buttonEmail = FindViewById<Button> (Resource.Id.buttonEmail);
buttonEmail.Click += delegate {
runEmailPro ();
};
scrollView = FindViewById<ScrollView> (Resource.Id.scrollview0);
List<String> resultList = new List<String> ();
int count = checkTextList.Count;//myResources.check_indexSet.Count;
linearSet = new List<LinearLayout> ();
for (int index = 0; index < view.ChildCount; index++) {
view.RemoveViewAt (index);
}
///
//Initiate Rect and Check
if (myResources.isLast == false) {
for (int index = 0; index < count; index++) {
InitiateWidgets (index, false);
}
} else {
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
var lastPath = Path.Combine (sdCardPath, "lastlasttxt.txt");
String fileNamePath = Path.Combine (sdCardPath, readFileSdcardFile (lastPath));
String loadData;
if (File.Exists (fileNamePath))
loadData = File.ReadAllText (fileNamePath);
else
return;
String[] splitData = loadData.Split ('\n');
foreach (String item in splitData) {
if (item.CompareTo ("") == 0)
continue;
if (item [0] == 't') {
addTextPro (true, item.Substring (1));
}
if (item [0] == 'c') {
bool bChecked = false;
if (item [1] != '0') {
bChecked = true;
} else {
bChecked = false;
}
InitiateWidgets (0, true, item.Substring (2), bChecked);
}
}
}
///
//save function
Button buttonSave = FindViewById<Button> (Resource.Id.buttonSave);
buttonSave.Click += delegate {
saveResultPro ();
};
///
//move function
Button buttonMove = FindViewById<Button> (Resource.Id.buttonMove);
buttonMove.Text = "Move";
buttonMove.Click += delegate {
removeAllFocus (moveOrEdit);
if (moveOrEdit == false) {
buttonMove.Text = "Edit";
moveOrEdit = true;
} else {
buttonMove.Text = "Move";
moveOrEdit = false;
}
};
//final function
Button buttonFinal = FindViewById<Button> (Resource.Id.buttonFinal);
buttonFinal.Click += delegate {
var fResults = new Intent (this, typeof(finalResults));
fResults.PutExtra ("MyData", getAllInfo ());
StartActivity (fResults);
};
}
}
//wirte the file on the sdcard.
public void writeFileSdcardFile(String path,String write_str,bool bTitle){
if (bTitle == true) {
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
var lastPath = Path.Combine(sdCardPath,"lastlasttxt.txt");
if (File.Exists (path) == false) {
File.WriteAllText (path, write_str);
}
else {
String[] existFile = readFileSdcardFile (path).Split('\n');
foreach (String item in existFile) {
if (write_str.Substring (0, write_str.Length - 1).CompareTo (item) == 0) {
File.WriteAllText (lastPath, write_str.Substring (0, write_str.Length - 1));
return;
}
}
File.AppendAllText (path, write_str);
}
File.WriteAllText (lastPath, write_str.Substring(0, write_str.Length - 1));
} else {
File.WriteAllText (path, write_str);
}
}
public String readFileSdcardFile(String path) {
if (File.Exists (path))
return File.ReadAllText (path);
else
return "";
}
public String getAllInfo()
{
String extra = "";
foreach(LinearLayout linear in linearSet)
{
var widgetType = linear.GetChildAt (0).GetType ().ToString ();
if (widgetType.CompareTo ("Android.Widget.EditText") == 0) {
EditText editText = (EditText)linear.GetChildAt (0);
extra += editText.Text + "\n";
} else if (widgetType.CompareTo ("Android.Widget.CheckBox") == 0) {
CheckBox checBox = (CheckBox)linear.GetChildAt (0);
if (checBox.Checked == true)
extra +="1" + checBox.Text + "\n";
else
extra +="0" + checBox.Text + "\n";
}
}
return extra;
}
//
//run email pro
public void runEmailPro(){
var email = new Intent (Android.Content.Intent.ActionSend);
email.PutExtra (Android.Content.Intent.ExtraEmail,
new string[]{"person1#xamarin.com", "person2#xamrin.com"} );
email.PutExtra (Android.Content.Intent.ExtraCc,
new string[]{"person3#xamarin.com"} );
email.PutExtra (Android.Content.Intent.ExtraSubject, "Hello Email");
email.PutExtra (Android.Content.Intent.ExtraText,
getAllInfo());
email.SetType ("message/rfc822");
StartActivity (email);
}
//
// add Text code
public void addTextPro(bool bLast,String textWidget)
{
LinearLayout linear = new LinearLayout (this);
ImageView imgView = new ImageView (this);
imgView.SetImageResource (Resource.Drawable.delete123);
editText = new EditText (this);
editText.SetSingleLine ();
editText.SetWidth(screenWidth - 50);
if (bLast)
editText.Text = textWidget;
if (moveOrEdit == true)
editText.SetOnTouchListener (this);
else
editText.SetOnTouchListener (null);
linear.AddView(editText);
linear.AddView(imgView);
//delete function.
imgView.Click += delegate {
deleteMessage(imgView);
};
linearSet.Add(linear);
view.AddView(linear);
}
//
//delete message
public void deleteMessage(ImageView imgView)
{
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Delete Phrase!");
builder.SetMessage ("Are you sure you would like to delete this phrase?");
builder.SetPositiveButton("Yes", (sender, args) => {
// Yes button
LinearLayout parent = (LinearLayout)imgView.Parent;
parent.Visibility = ViewStates.Invisible;
int childIndex = view.IndexOfChild(parent);
view.RemoveView(parent);
linearSet.Remove(parent);});
builder.SetNegativeButton("No", (sender, args) => {});
builder.SetCancelable(false);
builder.Show ();
}
//
//save Result
public void saveResultPro()
{
var factory = LayoutInflater.From(this);
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Song Name");
EditText songText = new EditText (this);
builder.SetView (songText);
//builder.SetView(factory.Inflate(Resource.Layout.saveDialog,
// FindViewById<ViewGroup>(Resource.Id.saveDialog)));
builder.SetPositiveButton("OK", (sender, args) => {
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
//EditText songText = FindViewById<EditText> (Resource.Id.projectName);
var textPath = Path.Combine(sdCardPath,songText.Text);
var textTitlePath = Path.Combine(sdCardPath,"Titles.txt");
String saveData = "";
foreach(LinearLayout linear in linearSet)
{
var widgetType = linear.GetChildAt (0).GetType ().ToString ();
if (widgetType.CompareTo ("Android.Widget.EditText") == 0) {
EditText editText = (EditText)linear.GetChildAt (0);
saveData += "t" + editText.Text + "\n";
} else if (widgetType.CompareTo ("Android.Widget.CheckBox") == 0) {
CheckBox checBox = (CheckBox)linear.GetChildAt (0);
if (checBox.Checked == true)
saveData += "c1" + checBox.Text + "\n";
else
saveData += "c0" + checBox.Text + "\n";
}
}
writeFileSdcardFile(textTitlePath,songText.Text + "\n",true);
writeFileSdcardFile(textPath,saveData,false);
});
builder.SetNegativeButton("Cancel", (sender, args) => {});
builder.SetCancelable(false);
builder.Show ();
}
//remove All focus
public void removeAllFocus(bool flag){
View.IOnTouchListener context = null;
if (flag == false){
context = this;
}
else{
context = null;
}
foreach (LinearLayout linear in linearSet) {
var widgetType = linear.GetChildAt (0).GetType ().ToString ();
if (widgetType.CompareTo ("Android.Widget.EditText") == 0) {
EditText editText = (EditText)linear.GetChildAt (0);
editText.SetOnTouchListener (context);
} else if (widgetType.CompareTo ("Android.Widget.CheckBox") == 0) {
CheckBox checBox = (CheckBox)linear.GetChildAt (0);
checBox.SetOnTouchListener (context);
}
}
scrollView.SetOnTouchListener (context);
}
//
//initiate widgets
public void InitiateWidgets(int index,bool bLast,String widgetText = "", bool bSel = false){
LinearLayout linear = new LinearLayout (this);
CheckBox check = new CheckBox(this);
ImageView imgView = new ImageView (this);
//delete function.
imgView.Click += delegate {
deleteMessage(imgView);
};
if (bLast == false) {
//int stringIndex = Resource.String.checkname0 + myResources.check_indexSet [index];
check.Text = checkTextList[index];
if (index < 4) {
if (myResources.check_index [index] == 1)
check.Checked = true;
else {
check.Checked = false;
}
} else {
check.Checked = true;
}
} else {
check.Text = widgetText;
check.Checked = bSel;
}
check.SetWidth (screenWidth - 55);
check.SetOnTouchListener (null);
imgView.SetImageResource (Resource.Drawable.delete123);
linear.AddView (check);
linear.AddView (imgView);
linearSet.Add(linear);
view.AddView (linear);
scrollView.SetOnTouchListener (null);
}
//
//Touch Event
float _viewY = 0;
//bool flag = false;
bool check_flag = false;
LinearLayout parentLayout;
int selTop;
int selBottom;
bool downFlag = false;
public bool OnTouch(View v, MotionEvent e)
{
switch (e.Action)
{
case MotionEventActions.Down:
if (v != scrollView) {
_viewY = e.GetY ();
parentLayout = (LinearLayout)v.Parent;
selTop = parentLayout.Top;
selBottom = parentLayout.Bottom;
check_flag = true;
downFlag = true;
}
break;
case MotionEventActions.Move:
if (v == scrollView && downFlag == true) {
var top = (int)(e.GetY () - _viewY);
var bottom = (int)(top + 55);
parentLayout.Layout (parentLayout.Left, top, parentLayout.Right, bottom);
check_flag = false;
}
break;
case MotionEventActions.Up:
if (downFlag == false)
return true;
if (parentLayout == null)
return true;
int originalPos = 0;
int placePos = -1;
downFlag = false;
if (parentLayout.GetChildAt(0).GetType ().ToString ().CompareTo ("Android.Widget.CheckBox") == 0) {
if (check_flag == true) {
CheckBox selCheck = (CheckBox)parentLayout.GetChildAt (0);
if (selCheck.Checked == false) {
selCheck.Checked = true;
} else {
selCheck.Checked = false;
}
check_flag = false;
return true;
}
}
if (parentLayout.GetChildAt(0).GetType ().ToString ().CompareTo ("Android.Widget.EditText") == 0) {
if (check_flag == true) {
EditText selText = (EditText)parentLayout.GetChildAt (0);
check_flag = false;
return true;
}
}
if (v == scrollView) {
int linearCount = linearSet.Count;
int index;
for (index = 0; index < linearCount; index++) {
if (parentLayout == linearSet [index]) {
originalPos = index;
break;
}
}
//Laying position.
for (index = 0; index < linearCount; index++) {
if (originalPos == index)
continue;
if (linearSet[originalPos].Top < linearSet [index].Top) {
if (originalPos == index - 1) {
linearSet[originalPos].Layout (linearSet[originalPos].Left,
selTop, linearSet[originalPos].Right,
selBottom);
return true;
} else {
if (index > originalPos) {
placePos = index - 1;
break;
} else {
placePos = index;
break;
}
}
}
/*if (linearSet [originalPos].Top == linearSet [index].Top) {
linearSet[originalPos].Layout (linearSet[originalPos].Left,
selTop, linearSet[originalPos].Right,
selBottom);
return true;
}*/
}
//Is original pos?
if ((originalPos == linearCount - 1) && (placePos == -1)) {
linearSet[originalPos].Layout (linearSet[originalPos].Left, selTop,
linearSet[originalPos].Right, selBottom);
return true;
}
if (placePos == -1)
placePos = linearCount - 1;
//Change the position on the result page.
int orgTop;
int orgBottom;
orgTop = linearSet [originalPos].Top;
orgBottom = linearSet [originalPos].Bottom;
linearSet [originalPos].Layout (linearSet[originalPos].Left, linearSet [placePos].Top,
linearSet[originalPos].Right, linearSet [placePos].Bottom);
LinearLayout tempLinear = linearSet [originalPos];
if (originalPos >= placePos) {
for (index = originalPos - 1; index >= placePos; index--) {
linearSet [index].Layout (linearSet[originalPos].Left, linearSet [index + 1].Top,
linearSet[originalPos].Right, linearSet [index + 1].Bottom);
linearSet [index + 1] = linearSet [index];
}
} else {
for (index = originalPos + 1; index <= placePos; index++){
linearSet [index].Layout (linearSet[originalPos].Left, linearSet [index - 1].Top,
linearSet[originalPos].Right, linearSet [index - 1].Bottom);
linearSet [index - 1] = linearSet [index];
}
}
linearSet [placePos] = tempLinear;
linearSet [placePos].Layout (linearSet[placePos].Left, orgTop,
linearSet[placePos].Right, orgBottom);
view.RemoveViews (0, view.ChildCount);
for (index = 0; index < linearSet.Count; index++) {
view.AddView(linearSet[index]);
}
}
break;
}
return true;
}
}
}
You missed to register listener to the Button click and override onClick

Out of memory reading after reading 682 txt files

I want to read a file with this code but after 682 times i get this error:
Exception of type 'System.OutOfMemoryException' was thrown.
System.IO.StreamReader file = new System.IO.StreamReader(scanpad[lusteller]);
scanpad is an array with the filepaths and lusteller is counter for it.
Scanpad excists 11207 files.
I have also have looked en there is a file on place 682
Anyone a solution?
Here the full version of my code
using (StreamReader file = new System.IO.StreamReader(scanpad[lusteller]))
{
//do stuff
lengte = bestandsnaam.Length;
lengte = lengte - 13;
controller = bestandsnaam.Remove(lengte, 13); // controllertype uit naam halen
do
{
rij = file.ReadLine();
if (rij != null) //error op volgende lijn vermijden
{
if (rij.StartsWith("0") || rij.StartsWith("1") || rij.StartsWith("2") || rij.StartsWith("3"))
{
rijcheck = true;
}
teller = teller + 1;
if (teller > 10)
{
if (rijcheck == true) // rij is datumlijn
{
string[] split = rij.Split(' ');
foutinformatie[0, index] = type; //type ophalen
foutinformatie[3, index] = controller; //controllernaam ophalen
foutinformatie[1, index] = split[0]; //datum ophalen
foutinformatie[2, index] = split[1]; //tijd ophalen
foutinformatie[4, index] = split[2]; //foutcode ophalen
foutinformatie[5, index] = split[5]; //foutteller ophalen
if (controller.StartsWith("MPU") == true)
{
lusarraygraad = 5;
while (lusarraygraad < 360)
{
if (graadmpu[0, lusarraygraad] == split[2])
{
try
{
graad = graadmpu[1, lusarraygraad];
foutinformatie[7, index] = graad;
}
catch
{
}
lusarraygraad = lusarraygraad + 499;
graadgevonden = true;
}
lusarraygraad = lusarraygraad + 1;
}
foutinformatie[7, index] = graad;
if (graadgevonden == false)
{
foutinformatie[7, index] = "";
}
graadgevonden = false;
}
//////////////////////////////////////////////////////////////////////////
if (controller.StartsWith("AAUX") == true)
{
lusarraygraad = 4;
while (lusarraygraad < 30)
{
if (graadaaux[0, lusarraygraad] == split[2])
{
try
{
graad = graadaaux[1, lusarraygraad].ToString();
foutinformatie[7, index] = graad;
}
catch
{
}
lusarraygraad = lusarraygraad + 499;
graadgevonden = true;
}
lusarraygraad = lusarraygraad + 1;
}
foutinformatie[7, index] = graad;
if (graadgevonden == false)
{
foutinformatie[7, index] = "";
}
graadgevonden = false;
}
if (controller.StartsWith("ACTRL") == true)
{
lusarraygraad = 6;
while (lusarraygraad < 85)
{
if (graadactrl[0, lusarraygraad] == split[2])
{
try
{
graad = graadactrl[1, lusarraygraad].ToString();
foutinformatie[7, index] = graad;
}
catch
{
}
lusarraygraad = lusarraygraad + 499;
graadgevonden = true;
}
lusarraygraad = lusarraygraad + 1;
}
foutinformatie[7, index] = graad;
if (graadgevonden == false)
{
foutinformatie[7, index] = "";
}
graadgevonden = false;
}
try
{
telleromschrijving = 6;
informatie = "";
while (split[telleromschrijving] != " ")
{
informatie = informatie + " " + split[telleromschrijving];
telleromschrijving = telleromschrijving + 1;
}
}
catch
{
foutinformatie[6, index] = informatie; //foutteller ophalen
}
rijcheck = false;
rij = file.ReadLine();
while (varcheck < 40)
{
// rij met eerste variable
if (rij != "")
{
variable[indexlokaal, varteller] = rij;
foutinformatie[varteller + 8, index] = variable[indexlokaal, varteller] = rij;
varteller = varteller + 1;
rij = file.ReadLine();
}
else
{
foutinformatie[varteller + 8, index] = " ";
varteller = varteller + 1;
}
varcheck = varcheck + 1;
}
varcheck = 0;
varteller = 0;
indexlokaal = indexlokaal + 1;
index = index + 1;
}
}
}
}
while (rij != null);
file.Close();
file.Dispose();
}
I imagine 682 is just a number where you happen to be running out of memory, not a special number. you should encapsulate your streamreader into
using(StreamReader file = new System.IO.StreamReader(scanpad[lusteller]))
{
//do stuff
}
This way, your streamreader is disposed of after being used, clearing memory
EDIT FOR UPDATE
Inside your streamreader you also have
rij = file.ReadLine();
while (varcheck < 40)
{
// rij met eerste variable
if (rij != "")
{
variable[indexlokaal, varteller] = rij;
foutinformatie[varteller + 8, index] = variable[indexlokaal, varteller] = rij;
varteller = varteller + 1;
rij = file.ReadLine();
}
but you are not checking if ReadLine is returning null again, looking at
http://msdn.microsoft.com/en-GB/library/system.io.streamreader.readline.aspx
This can also cause a outofmemory exception as your stream has reached null and yet you have continued onwards
It all depends on what you do with the StreamReader.
First of all you need to dispose it, but I don't believe it's the issue as the GC would have collected it before running out of memory (unless you also hold a reference to it).
If you use something like "ReadToEnd" and the content of the files is large you hit Large Object Heap with the strings created (and if you manipulate them by creating sub-string it can get worse).
After a while the heap becomes fragmented so you run out of memory because it is unable to find large enough memory chunk for your request.
Well, that's my guess with little info into your code, good luck.
Try use Using:(disposed memory after read)
using(System.IO.StreamReader file = new System.IO.StreamReader(scanpad[lusteller]))
{
}

dhtmlgoodies_calendar.js wont work with Firefox and Chrome

I have a dhtmlgoodies_calendar in my asp.net application and have made some changes to the writeCalendarContent method to disable the dates in the past. It works fine on Internet explorer. But in firefox and chrome the dates in the past are still displayed anyways.
Does anybody have any idea in how to make this work in those browers?
any help is appreciated.
Thanks
Here is my method:
function writeCalendarContent()
{
var blockDateInPast = true;
var calendarContentDivExists = true;
if(!calendarContentDiv){
calendarContentDiv = document.createElement('DIV');
calendarDiv.appendChild(calendarContentDiv);
calendarContentDivExists = false;
}
currentMonth = currentMonth/1;
var d = new Date();
var data = new Date();
var AnoAtual = data.getYear();
var MesAtual = data.getMonth();
var DiaAtual = data.getDate();
d.setFullYear(currentYear);
d.setDate(1);
d.setMonth(currentMonth);
var dayStartOfMonth = d.getDay();
if (! weekStartsOnSunday) {
if(dayStartOfMonth==0)dayStartOfMonth=7;
dayStartOfMonth--;
}
document.getElementById('calendar_year_txt').innerHTML = currentYear;
document.getElementById('calendar_month_txt').innerHTML = monthArray[currentMonth];
document.getElementById('calendar_hour_txt').innerHTML = currentHour;
document.getElementById('calendar_minute_txt').innerHTML = currentMinute;
var existingTable = calendarContentDiv.getElementsByTagName('TABLE');
if(existingTable.length>0){
calendarContentDiv.removeChild(existingTable[0]);
}
var calTable = document.createElement('TABLE');
calTable.width = '100%';
calTable.cellSpacing = '0';
calendarContentDiv.appendChild(calTable);
var calTBody = document.createElement('TBODY');
calTable.appendChild(calTBody);
var row = calTBody.insertRow(-1);
row.className = 'calendar_week_row';
if (showWeekNumber) {
var cell = row.insertCell(-1);
cell.innerHTML = weekString;
cell.className = 'calendar_week_column';
cell.style.backgroundColor = selectBoxRolloverBgColor;
}
for(var no=0;no<dayArray.length;no++){
var cell = row.insertCell(-1);
cell.innerHTML = dayArray[no];
}
var row = calTBody.insertRow(-1);
if (showWeekNumber) {
var cell = row.insertCell(-1);
cell.className = 'calendar_week_column';
cell.style.backgroundColor = selectBoxRolloverBgColor;
var week = getWeek(currentYear,currentMonth,1);
cell.innerHTML = week; // Week
}
for(var no=0;no<dayStartOfMonth;no++){
var cell = row.insertCell(-1);
cell.innerHTML = ' ';
}
var colCounter = dayStartOfMonth;
var daysInMonth = daysInMonthArray[currentMonth];
if(daysInMonth==28){
if(isLeapYear(currentYear))daysInMonth=29;
}
for(var no=1;no<=daysInMonth;no++){
d.setDate(no-1);
if(colCounter>0 && colCounter%7==0){
var row = calTBody.insertRow(-1);
if (showWeekNumber) {
var cell = row.insertCell(-1);
cell.className = 'calendar_week_column';
var week = getWeek(currentYear,currentMonth,no);
cell.innerHTML = week; // Week
cell.style.backgroundColor = selectBoxRolloverBgColor;
}
}
var cell = row.insertCell(-1);
if (currentYear<AnoAtual && blockDateInPast==true)
{
cell.className='DesactiveDay';
cell.onclick = null;
}
else if (currentYear==AnoAtual)
{
if (currentMonth < MesAtual && blockDateInPast == true)
{
cell.className='DesactiveDay';
cell.onclick = null;
}
else if (currentMonth==MesAtual)
{
if (no < DiaAtual && blockDateInPast == true)
{
cell.className='DesactiveDay';
cell.onclick = null;
}
else
{
cell.onclick = pickDate;
}
}
else
{
cell.onclick = pickDate;
}
}
else
{
cell.onclick = pickDate;
}
if (cell.onclick == pickDate)
{
if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
cell.className='activeDay';
cell.onclick = pickDate;
}
}
cell.innerHTML = no;
colCounter++;
}
if(!document.all){
if(calendarContentDiv.offsetHeight)
document.getElementById('topBar').style.top = calendarContentDiv.offsetHeight + document.getElementById('timeBar').offsetHeight + document.getElementById('topBar').offsetHeight -1 + 'px';
else{
document.getElementById('topBar').style.top = '';
document.getElementById('topBar').style.bottom = '0px';
}
}
if(iframeObj){
if(!calendarContentDivExists)setTimeout('resizeIframe()',350);else setTimeout('resizeIframe()',10);
}
}
Just add following code at the end of writeCalendarContent(),
if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
cell.className='activeDay';
cell.onclick = pickDate;
}
else if(currentYear<inputYear || currentMonth < inputMonth || no<inputDay){
cell.className = 'inactive-date';
}
else{
cell.onclick = pickDate;
}
cell.innerHTML = no;
colCounter++;
It adds the click event only for current date and next dates. It doesn't add click for past dates. You can add style for past dates(add style for inactive-date class).
Not at all, this following code is correct and tested
if(disabledDateInPast){
var now = new Date();
var yearOfNow = now.getFullYear();
var monthOfNow = now.getMonth();
var noOfNow = now.getDate();
if(currentYear < yearOfNow){
cell.className = 'desactiveDay';
}
else if(currentYear > yearOfNow){
cell.onclick = pickDate;
}
else if (currentYear == yearOfNow){
if(currentMonth < monthOfNow){
cell.className = 'desactiveDay';
}
else if(currentMonth > monthOfNow){
cell.onclick = pickDate;
}
else if(currentMonth == monthOfNow){
if(no < noOfNow){
cell.className = 'desactiveDay';
}
else{
cell.onclick = pickDate;
}
}
}
}
else{
cell.onclick = pickDate;
}
if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
cell.className='activeDay';
}

Categories

Resources