Null Reference in editing a task scheduler trigger in c# - c#

if (t != null) is always null why help..
when ever i try to get value in the variable name t it always gets in the else part but i am sure that there is valuse in tat variable.
private void button3_Click(object sender, EventArgs e)
{
try
{
if (search=="")
{
}
else
{
if (textBox1.Text=="")
{
MessageBox.Show("Select A Task Or Find One");
}
else
{
search = textBox1.Text;
}
}
if (search != null)
{
t = tasks.OpenTask(search);
if (textBox2.Text!="")
{
short hour = short.Parse(textBox2.Text.Substring(0, 2));
short minute = short.Parse(textBox2.Text.Substring(3, 2));
if (t != null) // this is null dont know why
{
foreach (Trigger tr in t.Triggers)
{
if (tr is StartableTrigger)
{
(tr as StartableTrigger).StartHour = hour;
(tr as StartableTrigger).StartMinute = minute;
}
}
t.Save();
t.Close();
}
tasks.Dispose();
button2.Visible = true;
textBox3.Visible = true;
search = "";
}
else
{
MessageBox.Show("Enter Time ");
}
}
}
catch (Exception b)
{
MessageBox.Show(b.ToString());
// MessageBox.Show("Select A Task From The List ");
}
}
help guys .. well i tried it to debug but didnt get a break through..

t is null because tasks.OpenTask(search) returns null.
Probably there is no task matching your search criteria.
Why are you disposing of tasks in the first place?

Any place in your source ,where you have written something like this MyClass t = new MyClass().. where t is your class object. If you have not declared,It will always come null.
Or might be you have declared something like this
private Task t; but forgot to add new keyword. Checkout!!!

Related

Problem with inserting a node at the end of LinkedList

So I have a problem with this insertLast function in LinkedList.
public static void insertLast(LinkedList<Person> list, Person data)
{
LinkedListNode<Person> head= list.First;
LinkedListNode<Person> rez = new LinkedListNode<Person>(data);
if(head == null)
{
head = rez;
return;
}
LinkedListNode<Person> temp = head;
while (temp.Next != null)
{
temp = temp.Next;
}
temp.Next = rez;
}
I don't even know if this code will insert at the end because I can't test it because at this code temp.Next = rez; i get error:
"Property or indexer 'LinkedListNode.Next' cannot be assigned to -- it is read-only."
So if I understand correctly.Next is read-only so I can't use it like this. Now does anybody knows how to fix this?
I would really appreciate!
I can't use AddLast method because I have to create my own function.
You can't use AddLast()...but can you use AddAfter()?
public static void insertLast(LinkedList<Person> list, Person data)
{
if (list.Count == 0)
{
list.AddFirst(data);
}
else
{
list.AddAfter(list.Last, data);
}
}
Kindly, add this only two lines as below:
private void btnAddAtTheEnd_Click(object sender, EventArgs e)
{
treeView1.Focus();
treeView1.SelectedNode = treeView1.Nodes[treeView1.Nodes.Count - 1];
}
I hope it helps you ^_^

Looping the list

I have a problem with looping a list of songs. I have a List<String> _songList which contains songs paths (loaded correctly, checked). So I thought that there is an event which will tell me "Ok I stopped playing the song, I'm ready to play the next one". In NAudio it should be StoppedEventArgs added to WaveOutEvent.PlaybackStopped. But in my case it doesn't play another song, neither the same again. Here is my code:
public void Play_List(String _playlistName)
{
try
{
if (_songList.Count > 0)
{
if (!_paused)
{
_currentList = _playlistName;
PrimaryOutputStream =
new MediaFoundationReader(_songList[_songIndex]);
VolumeStream = new WaveChannel32(PrimaryOutputStream);
VolumeStream.PadWithZeroes = false;
Player.Init(VolumeStream);
Player.PlaybackStopped +=
new EventHandler<StoppedEventArgs>(RepeatMode);
}
Player.Play();
_paused = false;
_isPlaying = true;
}
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.ToString());
}
}
public void RepeatMode(object sender, StoppedEventArgs e)
{
try
{
if (_songList.Count > 0 && _currentSong != null)
{
_paused = false;
switch (_repeatMode)
{
case 1: //Repeat one song
Play_List(_currentList);
break;
case 2: //Repeat whole list
NextSong();
Play_List(_currentList);
MessageBox.Show("Changed song");
break;
default:
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Of course I set _repeatMode to 2 for list and 1 for one song.
I was searching the internet for help but found nothing. Anyone?
I do not see anything in your code which sets a value to the _currentSong. Probably, it is coming as null and your code is not getting executed.
if (_songList.Count > 0 && _currentSong != null)

Debugging a windows form application

Im making a chat program that saves the messages in files like pub0.zzc, all computers that are using it will be connected to the hard drive that these files are in, so its fine. The method data.Chat.Read(MessageTypes type, string Channel) infinite loops through a try catch statement till it returns the messages. I used this before and works perfectly. But, my code was hard to manage so instead of just putting text boxes into the window and using the code each time, i created a user control (MessageViewer). It works fine, once again when I run it, BUT it freezes VS whenever I try to use the designer on the window housing the control. the probelm isnt the window because when i delete the control its fine. I think the possible errors are at RefreshMessages() and the Refresher_Tick(...)
Refresher.Stop() and .Start() is also not it, worked fine before
so here is the code:
private void Refresher_Tick(object sender, EventArgs e)
{
Refresher.Stop();
int RefreshRate = 4;
bool Live = true;
if (RefreshRateChoice == "Manual")
{
Live = false;
RefreshRate = 1;
}
else if (RefreshRateChoice == "4 ( Default )")
{
Live = true;
RefreshRate = 4;
}
else
{
Live = true;
RefreshRate = Convert.ToInt32(RefreshRateChoice);
}
if (data.Chat.Read(MessageType, ChannelChoice) != ContentPresenter.Text && Live)
{
RefreshMessages();
}
Refresher.Interval = RefreshRate;
Refresher.Start();
}
public void RefreshMessages() {
if (data.Chat.Read(MessageType, ChannelChoice) != ContentPresenter.Text)
{
ContentPresenter.Text = data.Chat.Read(MessageType, ChannelChoice);
}
}
and if you need it:
public static string Read(MessageTypes Type, string Channel)
{
string Loc;
if (Type == MessageTypes.Public && (Channel == "1" || Channel == "2"))
{
return "Can not view this channel, only post to it.";
}
if (Type == MessageTypes.Public)
{
Loc = data.AssetsFolder + "\\pub" + Channel + ".zzc";
}
else if (Type == MessageTypes.Private)
{
Loc = data.AssetsFolder + "\\" + Channel + ".zzpc";
}
else if (Type == MessageTypes.Game)
{
Loc = data.AssetsFolder;
}
else
{
Loc = data.AssetsFolder;
}
while (true)
{
try
{
String MessageList = "";
StreamReader MessageReader = new StreamReader(Loc);
string EncMessages = MessageReader.ReadToEnd();
MessageReader.Dispose();
List<string> EncMsgList = EncMessages.Split(';').ToList();
for (int i = 1; i < EncMsgList.Count; i++)
{
MessageList += data.Encodings.Decrypt(EncMsgList[i], Palettes.Message) + "\n";
}
return MessageList;
}
catch
{
// Do nothing
}
}
}
You say that it "freezes."
In your Read method you have a while(true) loop with an embedded try...catch block, but the catch never returns you from that method. If you keep throwing the same exception, you'll continue to loop over and over which could be where you are freezing.
At least to prove that is the case, put a return in you catch or some diagnostic code to indicate if that is the case.

c# winform Invoke throws NullReferenceException

i'm working on an winform(mdi) pro. And I need to update a dataGridView control when i get new data from another thread. and when new data comes and i'm dragging the dataGridview scroll, it throw a nullreference exception in dataGridView.Invoke. i have searched for few days and drove google crazy,but didn't help.
the code like this:
public void ReceiveNewData(object sender, UpateEventArgs ex)
{
if (this.dataGridView.InvokeRequired)
{
dataGridView.Invoke(new UpateEventHandler(ReceiveNewData), new object[] { this, ex });
}
else
this.BindNewData();
}
private void BindNewData()
{
if (dataGridView!= null && (QuoteMember.listOneClickQuoteItem != null || QuoteMember.listMarketingQuoteItem != null))
{
DataTable dataSource = PublicFunction.ToDataTable(QuoteMember.listOneClickQuoteItem);
if (dataSource != null)
dataSource.Merge(PublicFunction.ToDataTable(QuoteMember.listMarketingQuoteItem), true);
else
dataSource = PublicFunction.ToDataTable(QuoteMember.listMarketingQuoteItem);
dataGridView.DataSource = dataSource;
}
}
public PublicFunction
{
public static DataTable ToDataTable(List dataSource)
{
if(dataSource != null)
return ToDataTable((dataSource.ToArray()), 1);
return null;
}
public static DataTable ToDataTable(List dataSource)
{
if (dataSource != null)
return ToDataTable((dataSource.ToArray()), 2);
return null;
}
private static DataTable ToDataTable(QuoteItemBase[] m, int type)
{
DataTable dsTemp = null;
if (type == 1)
{
dsTemp = new DataTable("OneClickQuote");
}
else if (type == 2)
{
dsTemp = new DataTable("MarketingQuote");
}
else
dsTemp = new DataTable("temptable");
dsTemp.Columns.Add("Date");
dsTemp.Columns.Add("Time");
dsTemp.Columns.Add("NO");
dsTemp.Columns.Add("Name");
if (m == null)
return dsTemp;
foreach (var item in m)
{
DataRow drTemp = dsTemp.NewRow();
drTemp["Date"] = item.date;
drTemp["Time"] = item.time;
drTemp["NO"] = item.no;
drTemp["Name"] = item.name;
dsTemp.Rows.Add(drTemp);
}
return dsTemp;
}
}
PS:
if new data comes and i'm not dragging scroll bar, it works fine.
any ideas?
thank you !
I found that when you invoke a control and set bindings (or clear them)
and an object is set to null this can throw a null reference exception, this is reflected through invoke giving an error, this error however is somewhere else in your code:
quick example:
public class test : Form
{
public test()
{
Thread t = new Thread(start);
t.Start();
}
public void start()
{
LoadCompleteEvent();
}
public void LoadComplete() //fired by LoadCompleteEvent();
{
if(this.InvokeIsRequired)
{
//do invoke
//and return
}
comboBoxEditBrand.Properties.Items.Clear();
comboBoxEditBrand.Properties.Items.AddRange(ListOfStuff.ToArray());
}
public void comboBoxEditBrand_SelectedItemChanged(object sender, eventargs e) // fired as control is changed
{
//error here!!
if(comboBoxEditBrand.SelectedItem == SomeBrandItem) //<- this is where the error is thrown!! check for null first!
{
//do something
}
}
}
it's something like this.. this code will probably not throw the error because A) it's from the top of my head and B) it's made up. BUT this is kind of what bugged me for half a morning as to WHY this error was thrown.
just place
if(comboBoxEditBrand.SelectedItem == null)
return;
where it says //error here!! and it should work again.
Make sure you switch to the Gui thread before you invoke

How does C# evaluate Logic block?

I have the following line of code:
public bool dcpl_radar()
{
if (radar == null)
return false;
else
{
if (radar != null)
{
if (radar.InvokeRequired)
radar.BeginInvoke(new MethodInvoker(delegate()
{
radar.Visible = false;
}));
else
this.radar.Visible = false;
radar = null;
}
return true;
}//end of else statement
}
but VStudio keeps throwing an error on the invoke line. I've checked the Debugger and if (radar == null) is true, yet VStudio is trying to evaluate a part of the code it shouldn't be in. Can someone explain why it's doing this please?
Wait a minute... I think we have a race condition.
Lets say you BeginInvoke, almost immediately you set radar = null.
There really is no telling when your anonymous delegate will be executed.
I would imagine this should solve your issue.
public bool dcpl_radar()
{
if (radar != null)
{
if (radar.InvokeRequired)
{
radar.BeginInvoke(new MethodInvoker(HideRadar));
}
else
{
HideRadar();
}
return true;
}
return false;
}
private void HideRadar()
{
this.radar.Visible = false;
this.radar = null;
}
What is happening:
The anonymous delegate is being called after you set the radar to null.
How to fix it
public bool dcpl_radar()
{
if (radar == null)
return false;
else
{
if (radar != null)
{
if (radar.InvokeRequired)
radar.BeginInvoke(new MethodInvoker(delegate()
{
radar.Visible = false;
radar = null;
}));
else {
this.radar.Visible = false;
radar = null;
}
}
return true;
}//end of else statement
}
(Note where I've moved your 'null' assignments).
Though I am a bit worried about the point of setting a variable to null, it's generally a sign of a bad design.

Categories