darkagn 315 Veteran Poster Featured Poster

ExecuteScalar always returns a single value, so you should use it on any query that is expected to return a single record, single field result set. It's represented as object because its unknown what the correct data type should be but should be converted to whatever data type you expect. You will need to handle DBNull.Value during your conversion when using ExecuteScalar, but in your specific example this probably won't be necessary as your query should always either return an Int32 or throw an SQL exception if a timeout or connection error occurs for example.

Your other option would be to use ExecuteReader. This can be used to return the list of records with one or more fields, and then you iterate over the DataReader's Read() call to read each field from an array by column name or index. But in your example query this would be overkill and I would just use ExecuteScalar instead.

darkagn 315 Veteran Poster Featured Poster

I haven't used telerik specifically before but I wanted to mention that there is absolutely nothing wrong with using a third party to solve outstanding problems with a project. Sometimes it is just more cost-effective (not just in dollar value) to purchase another company's tools rather than trying to solve something yourself. You will need to do your homework on each tool that you use though, but often companies will offer a trial period for their products.

overwraith commented: Thanks for the thoughts. I usually do try to make life easier with third party, but sometimes the stuff is of questionable quality. +3
darkagn 315 Veteran Poster Featured Poster

Certainly being able to parse file input into something meaningful is always useful. To make it even more generic, why not use a Stream input instead? That way you can handle any input type (including files, via FileStream) so long as the format is what you expect.

overwraith commented: Good thoughts! +3
darkagn 315 Veteran Poster Featured Poster

In C# a bool method always returns a boolean value. In other languages such as PHP this is not necessarily the case, but since this question was in regards to C# I will answer as such.

I think your question is about personal preference so there isn't really a right or wrong answer. For mine, when checking for true I always omit the == true. I actually think that omitting the unnecessary code improves readability of your code. It is also important that methods and properties have a strong naming convention in your code though.

However when I am checking for false I sometimes use the NOT symbol (for example, !someBool) and sometimes use a more explicit someBool == false depending on the complexity of the algorithm. Sometimes when you are reading code back a few years later it is easy to miss that exclamation mark that indicates a check for NOT, whereas the second method indicates clearly that you are checking for false.

JamesCherrill commented: Good point re checking for false +15
darkagn 315 Veteran Poster Featured Poster

I would suggest moving the required method to a third dll if possible and referencing that dll from both of your existing projects.

ddanbe commented: You did it I guess. +15
darkagn 315 Veteran Poster Featured Poster

Use the SelectionStart and SelectionLength properties to select a particular part of the text and then apply formatting to it.

Example:

richtextbox1.SelectionStart = 30;
richtextbox1.SelectionLength = 10;
richtextbox1.SelectionAlignment = HorizontalAlignment.Left;

will align the substring starting at index 30 of length 10 to the left. I'm not sure how multiple alignments on the same line will work though but I'll leave that for you to test.

darkagn 315 Veteran Poster Featured Poster

Not sure if you can actually track that mouse event but you could handle the FormClosing event instead.

darkagn 315 Veteran Poster Featured Poster

Hi zaidiSEO and welcome to Daniweb :)

It really depends on what you need to accomplish. C# can be used for a console application, a web application, a windows service, a winforms application, a mobile application, ... the possibilities are almost endless. I'm not sure that one is more important than another but all are possible ;)

darkagn 315 Veteran Poster Featured Poster

There are a number of different ways to do this. Here is one example, and here is an alternative solution.

darkagn 315 Veteran Poster Featured Poster

You will have a file called Program.cs. This is the execution entry point of your application - or more specifically, the static method called Main in this file is. In this method, one of the last lines of the Main method reads something like:

Application.Run(Form1);

Change Form1 (or whatever form it actually reads in your file) to be the type of form you want displayed as the first view of your application.

darkagn 315 Veteran Poster Featured Poster

I haven't used MonoDevelop, but looking at their website they support a cross-platform interpretation of C# 3 (which is old given 4.5 was released in 2012 for Windows 8 and Server 2012, and 3 was released in 2006 with Vista and Server 2008). Debugging complex code would be interesting using such a middle manager too.

I believe a better approach would be to run VMWare with a Windows OS. This will give you a much closer experience to C# development than any attempt at trying to make .NET "cross platform" which is not its intended purpose.

darkagn 315 Veteran Poster Featured Poster

I'm not sure that you can develop C# applications on an IOS operating system. The .NET Framework is a Microsoft technology, so C# is not cross-platform like Java or PHP. If you only have access to a Mac, my suggestion would be to install a virtual machine running a Windows OS and use Visual Studio as your IDE (there are Express editions available for free for non-commercial purposes).

darkagn 315 Veteran Poster Featured Poster

To stop it from happening in the future, consider adding a primary key to the table. By definition a PK is not nullable and will help identify the records when they are inserted. For more information on primary keys see this W3Schools page on the subject.

darkagn 315 Veteran Poster Featured Poster

You can use the lock keyword for this. The basic idea is that you lock a private constant object whenever you read or write from the shared variable. Like this:

public class MyMultiThread
{
  private const Object lockObject = new Object();
  private int sharedVariable;

  public MyMultiThread()
  {
    WriteSharedVariable(0);
  }

  public void WriteSharedVariable(int aValue)
  {
    lock(lockObject)
    {
      sharedVariable = aValue;
    }
  }

  public int ReadSharedVariable()
  {
    lock(lockObject)
    {
      return sharedVariable;
    }
  }
}
darkagn 315 Veteran Poster Featured Poster

You can use pointer types in C# however they are rarely needed. Check out msdn's article on pointer types in C#.

darkagn 315 Veteran Poster Featured Poster

Something like the following query should get you close:

-- need a count of the objects by description and transaction
SELECT Description.Name, COUNT(Item.Name) AS count, COUNT(Transaction.Type) AS [under repair]
FROM Description
-- describe the relationship between the tables by joining
INNER JOIN Item ON Description.DeID = Item.DeID
INNER JOIN Transaction ON Item.IID = Transaction.IID
-- only interested in repair transaction type
WHERE Transaction.Type = 'Repair'
-- because we use aggregate functions, need to describe how to group the aggregations (counts)
GROUP BY Description.Name

Have a play with that query, it may need to be adjusted to get the right results but should give you a start.

darkagn 315 Veteran Poster Featured Poster

You can use a ParameterizedThreadStart delegate like so:

Thread workerThread = new Thread(new ParameterizedThreadStart(LongRunningOperation);
workerThread.Start(a, b);

However note that the parameters a and b are passed as objects, not as int's so you will need to cast them inside your method.

public static Double LongRunningOperation(object a, object b)
{
   if (a.GetType() != typeof(Int32) || b.GetType() != typeof(Int32))
     throw new ArgumentException("An error occurred with the type of arguments passed!");

   int aValue = Convert.ToInt32(a);
   int bValue = Convert.ToInt32(b);

   // do something meaningful here...
}
darkagn 315 Veteran Poster Featured Poster

If InsuranceDetails can be null, you need to use a LEFT JOIN to join your tables together.

SELECT 
  ipd.InPatientID,
  ipd.Fname+' ' +ipd.LName as 'Patient Name' , -- this line is dangerous if name(s) can be null
  ipd.Gender,
  ipd.BirthDate,
  ipd.AccType as 'Account Type',
  ipd.Minor,
  ipg.GFName+' ' +ipg.GLName as 'Guardian name', -- same here
  ipd.Insured,
  ipi.Insurance1,
  ipi.Policy1,
  ipi.GroupNo1,
  ipi.Guarantor,
  ipi.Employer
from
  HMS.dbo.PatientDetails ipd
inner join -- inner join means all conditions in "on" must be true
  HMS.dbo.ParentDetails ipg
on
  ipd.InPatientID = ipg.InPatientID
left join -- left join means the "on" can be true or null for ipi (right of the join)
  HMS.dbo.InsuranceDetails ipi
on
  ipd.InPatientID = ipi.InPatientID
poojavb commented: thank you very much....worked well +4
darkagn 315 Veteran Poster Featured Poster

If you want to mutate the string parameter you must declare it var in the procedure's signature:

procedure TMainForm.Show(var s: String);

But a better method would probably be to declare a local variable string to handle your error line, so:

procedure TMainForm.Show(s: string);
var
  n, n2, n3: integer;
  arTemp: TMyArray;
  tempStr: String;
begin
  arTemp := TMyArray.Create();
  n := InStr(1, s, ':');
  if n = 0 then

  tempStr := mid(s, n + 1);
  arTemp.SplitIn(tempStr, ':');
  //...
end;
darkagn 315 Veteran Poster Featured Poster

Transactions are very important in SQL. They provide a way of reverting previous steps of a multi-step operation on the database that causes changes should an error occur.

Imagine this simple, common scenario. You want to represent a sale of items as a header (containing the date and time of the sale, customer details and miscellaneous information regarding the sale as a whole) and several detail lines each representing the quantity and total cost of each item in the sale. If you have 100 different items in your sale, then the total number of records to be inserted in the database is 101 - 1 header record and 100 detail records in two separate tables. What happens if item number 76 has some error when inserting, maybe the price of the item hasn't been set yet? Without a transaction in place, you would have inserted the header and 75 correct detail records, leaving you with erroneous data in your database. Using a transaction we can "ROLLBACK" the transaction, leaving the database the way it was before we began inserting our records for the sale.

I hope this helps you understand where transactions are useful.

M.Waqas Aslam commented: awesome way to explain , simple and effective example. +5
darkagn 315 Veteran Poster Featured Poster

One important use of overriding the ToString method in your classes is for consistency in the display of information in your views. It is far easier to override the ToString method than to remember the format used in each view for your class.

Say for example that I have a class called Employee. Let's say I want my employee record to always be displayed as first name followed by a space followed by the surname. Overriding the ToString method allows it to be performed in one place, while you may have several views containing employee information, say an employee list, a sales figures list and a graphical representation of their sales figures. To be consistent I would have to apply this formatting in three places rather than the one.

ddanbe commented: Well said! +15
darkagn 315 Veteran Poster Featured Poster

Without knowing the details of your error, I would say that your connection string (conn) is incomplete. Here is a great reference site for constructing connection strings, but I would say that you may need to provide a Password or Integrated Security setting?

kvprajapati commented: Agree! :) +15
darkagn 315 Veteran Poster Featured Poster

For part A, they are wanting a function that uses the specific fields in your table, not passes them as parameters to the function. Your function will probably look something like this:

-- give the function a meaningful name, and return an appropriate data type
CREATE FUNCTION GetItemTotalPrice() RETURN MONEY
AS
DECLARE @TotalPrice MONEY
-- total price is defined as quantity x unitprice from the sales table
SELECT @TotalPrice = Quantity * UnitPrice FROM Sales
RETURN @TotalPrice

For B you will need to do a CREATE TABLE statement. Here is a link to the MSDN documentation for such a statement, there are also many many examples online. Have a try and repost if you need more help, along with your attempt.

darkagn 315 Veteran Poster Featured Poster
for (int i = 0; i < textBox3.Text.Length;i++ )
{
 
c = i+1 ;
 
 
if (textBox3.Text.Substring(i,c)==" ")
{
string word = null;
word = textBox3.Text.Substring(0, i);
arrayKeyword[index]=word;
index = index + 1;
}
}

Your for-loop here iterates from the start of the string textBox3.Text to the end of the string. During each iteration, you check the current character (at position i) and the one following it (at position c). So when i is the last character in the string, c is invalid because there is no character following position i. You need to change your loop like so:

for (i = 0; i < textBox3.Text.Length - 1; i++)

EDIT: Actually, substring takes a start position and a length of the string, so your call to substring should be:

if (textBox3.Text.Substring(i,1)==" ")
ddanbe commented: well explained. +14
darkagn 315 Veteran Poster Featured Poster

Resources are global, external data objects that can be used by the application from any point. Here is the MSDN description of application resources, their purpose and how to use them.

In answer to your third question, you can change what type of resources you wish to view/add/delete by changing the combo box that reads Strings when you open the resx file for the first time.

darkagn 315 Veteran Poster Featured Poster

Declare the variables value1 and value2 before the if-statements.

int value1 = 0;
int value2 = 0;
if (checkbox1.checked) // you don't need to say == true here
  value1 = 1000000;
if (checkbox2.checked)
  value2 = -392014;
int value3 = value1 + value2;
myFunction(value3);

//...

public void myFunction(int value3)
{
  // do something...
}

PS please use code tags, it makes posts much easier to read.

darkagn 315 Veteran Poster Featured Poster

Check out the BackgroundWorker class. Basically you put all your execution handling into its DoWork event handler, then call RunWorkerAsync on the instance to set it to run. You can use the ProgressChanged event handler to report the progress back to your GUI thread, and the RunWorkerComplete event handler is fired when the worker finishes its work. There are heaps of online examples of this process.

darkagn 315 Veteran Poster Featured Poster

MATLAB is another popular mathematical scripting language.

darkagn 315 Veteran Poster Featured Poster

To build a GUI, choose Windows Forms Application for the project type. A console application is one that runs on a command line or via a batch file.

You are correct about adding a class.

Your exe file will be created in your bin folder from where you save your project unless you change the properties of your project.

darkagn 315 Veteran Poster Featured Poster

Don't get too hung up on which languages you need to learn. It's more about learning problem solving skills, design patterns, data structures and algorithms. I learned Java at university and about 1% of the commercial code I have written has been in Java. Once you know one language, subsequent languages are easily picked up.

.NET is a windows framework that several languages are based on, including C# .NET and Visual Basic (VB) .NET. I had only read a few lines of C# before entering the workforce, now much of the code I write is in C# .NET, but again I must stress that it is not important which language(s) you learn.

As for the detailed architecture of a computer, I think so long as you have a general understanding of how a computer works you will be fine. Unless you wish to work for Intel designing new components, then you might need a more expert depth of knowledge, but for software development a general understanding should suffice. That's not to say that it would hurt to know what's going on under the hood...

I'm not sure what you are trying to ask about the general structure of an OS? Since each OS differs I think that learning the theory behind how an OS operates can't hurt, but I wouldn't stress if you only have a general understanding when you complete your degree.

Personally I think that your degree should teach you skills in design, logic, …

ddanbe commented: Nice explanation. +9
darkagn 315 Veteran Poster Featured Poster

You can traverse child nodes quite easily in C#.
Example:

// assume here I have a DataSource node called node
foreach (XmlNode childNode in node.ChildNodes)
{
  string nodeValue = String.Empty;
  // use a case insensitive search on the node name
  string childNodeName = childNode.Name.ToLowerInvariant();
  if (childNodeName == "name")
  {
    nodeValue = childNode.Value;
    // do something meaningful with the value of the node...

  }
  else if (childNodeName == "property")
  {
    nodeValue = childNode.Value;
    // do some other meaningful thing with the value of the node...

  }
  else
  {
    // error - invalid node so do some error handling here...

  }
}

Hope this helps.

arjunpk commented: thank you.. :) +1
darkagn 315 Veteran Poster Featured Poster

I think the easiest way to stop your thread would be to break out of your while loop in the Reader method on a certain condition.

while (true)
{
  if (shouldIStop())
     break;
  msg = sr.ReadLine() + Environment.NewLine;
  allMessages += msg;
  Invoke(new Action(Output));
  Invoke(new Action(AddNameList));
}

private bool shouldIStop()
{
  // write some code here for the conditions when you want to stop your thread
}

EDIT: Also, once you break out of the while-loop you should probably do a graceful disconnect from the TCP connection.

darkagn 315 Veteran Poster Featured Poster

No that's not quite right. Take a look again at the signature I used for the Die method.

// not public virtual void Die(), instead:
public int Die()
// but if you want you could do:
// public virtual int Die()

And the property should be simply:

public gamescore Gamescore
{
  get;
  set;
}
ddanbe commented: Very nice! +8
darkagn 315 Veteran Poster Featured Poster

Hi prosperr and welcome to DaniWeb,

Unfortunately we aren't allowed to do your homework for you. We need to see that you have at least thought about these questions before we can even give you a point in the right direction. How do you think these questions should be tackled? What have you come up with so far in your solutions?

darkagn 315 Veteran Poster Featured Poster

From MSDN Docs:

The FormBorderStyle, MinimizeBox, and MaximizeBox properties allow you to control whether the form can be minimized, maximized, or resized at run time.

The FormBorderStyle property has an affect on size and location of your form. Sizable is the default setting. Here is a link to the documentation for the property, it may give some clues as to why the form behaves this way when setting this property.

darkagn 315 Veteran Poster Featured Poster

1. A static method belongs to the class, not to an instance of the class, so the instance variables have no meaning in a static context. You need to create an instance of your class in the static method, then access any public instance variables, properties or methods of the instance.

2. I don't really understand what you are trying to do sorry. Without access to your answerReturned method or the Promotion method, I can't really see what you are doing.

NewOrder commented: Thank you +0
darkagn 315 Veteran Poster Featured Poster

Here is a link to the MSDN docs for the System.Math class. Take a look and see if there is any method in there that can help.

darkagn 315 Veteran Poster Featured Poster

I meant the static method of the String class IsNullOrEmpty , not that the string itself is static. This static method checks whether the string is unitialised or initialised to String.Empty .

vedro-compota commented: +++ +1
darkagn 315 Veteran Poster Featured Poster

Your call to Message.Show is wrong, you need to add String.Format like so:

MessageBox.Show(String.Format("{0}",hello2(2)));

Also, it doesn't matter what number gets passed as the parameter to your hello2 function, it will always show 10 / 5. A better implementation would be:

private void button1_Click(object sender, EventArgs e)
{
  MessageBox.Show(String.Format("{0}",hello2(10, 5)));
}

public int hello2(int numerator, int denominator)
{
  int hello = numerator / denominator;
  return hello;
}
darkagn 315 Veteran Poster Featured Poster

The following if-statement is equivalent to your switch statement. You can see from this code that Narue is correct:

if (fillnumb == 0)
  fillnumb = 1;
else if (fillnumb == 1)
  fillnumb = 2;
vedro-compota commented: ++ +1
darkagn 315 Veteran Poster Featured Poster

You need to join to the tblRespondentsChildren table twice, once for each child.
Something like this should give you a start:

SELECT r.FirstName, r.Surname FROM tblRespondents r
INNER JOIN tblRespondentsChildren rc1 ON r.RespondentID = rc1.RespondentID
INNER JOIN tblRespondentsChildren rc2 ON r.RespondentID = rc2.RespondentID
WHERE rc1.DOB BETWEEN ('1998-09-01') AND ('1999-08-31')
AND rc2.DOB BETWEEN ('1995-09-01') AND ('1995-12-08')
AND rc1.SexID = 1
AND rc2.SexID = 1
Gdyson commented: Spot on +0
darkagn 315 Veteran Poster Featured Poster

Try this:

protected readonly int ID = ID.GetNextID();
darkagn 315 Veteran Poster Featured Poster

Hi all,

Well this is my 1000th post here at DaniWeb and I thought "What better way to celebrate than by posting my first ever code snippet?"

This problem occurred in an application that I am working on. I have a password field in my form that was specified as Multiline, and it correctly worked on my PC, but my friend's PC was showing it as text. It turns out that Windows XP expects password fields to be single line only, but Vista (and I assume Windows 7) doesn't care if it is a single or multi line text box. In the code snippet you see three text boxes being added to a form. On XP, only the first field will correctly display a * character in place of the text, whereas in Vista all three will.

I guess a password field would be unusual to accept multiline text, but I overlooked this property when attempting to solve the issue. I hope this sheds some light for someone out there...

kvprajapati commented: Congrats! you are awesome. +11
darkagn 315 Veteran Poster Featured Poster

You could use the String.Split function to split each line according to where each space is. Then you could just substring from the = signs to get the digits. Something like this (untested but should give you an idea):

while ((s = sr.ReadLine()) != null)
{
  string[] chunks = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  foreach (string part in chunks)
  {
    int i = part.IndexOf("=");
    if (i != -1)
    {
       int digit = Convert.ToInt32(part.Substring(i+1));
       // do something with digit...

    }
  }
}
darkagn 315 Veteran Poster Featured Poster

You need to handle incoming connections on one thread, then handle each connection on an individual thread. This tutorial is a really good starting point for a TCP client-server model.

darkagn 315 Veteran Poster Featured Poster

This is an example of a class Property. What it is doing is providing a way to retrieve (get) and store (set) a string called Input, which in this case points directly to the Text property of a text box called myTextBox. The following code is equivalent (but a lot more typing!):

private string _input;
public string RetrieveInput()
{
   return _input;
}
public void StoreInput(string value)
{
   _input = value;
}
// event handler to handle when the text changes in the text box
private void myTextBox_TextChanged(object sender, EventArgs e)
{
   StoreInput(myTextBox.Text);
}
darkagn 315 Veteran Poster Featured Poster

Hi svatstika and welcome to DaniWeb :)

The easiest way to do this is to provide a reference to the input in your forms like so:

public partial class Form1: Form
{
   // create a property to store the input from the user
   public string UserInput
   {
      get;
      set;
   }

   // event handler for when the button is clicked - open the new form and wait until the OK dialog result is received
   private void myButton_click(object sender, EventArgs e)
   {
      UserInput = String.Empty;
      Form2 newForm = new Form2();
      if (newForm.ShowDialog() == DialogResult.OK)
        UserInput = newForm.Input;
   }
}

public partial class Form2: Form
{
   // a property that can be used by Form1 to retrieve the input from the user
   public string Input
   {
     get { return myTextBox.Text; }
     set { myTextBox.Text = value; }
   }
}
ddanbe commented: Nice. +8
darkagn 315 Veteran Poster Featured Poster

There are lots of good tutorials out there, google will provide many.

As for your elapsed time question, there are a number of ways to do this but here is the way I like to handle it:

// remember the time at the start
DateTime start = DateTime.Now;
// do your work
Evaluate();
// get the time at the end
DateTime end = DateTime.Now;
// DateTime objects can be subtracted or compared
TimeSpan duration = end - start;
// build a string explaining the time elapsed
string timeElapsed =  String.Format("{0} Hours, {1} Minutes, {2} Seconds", Math.Floor(duration.Hours), Math.Floor(duration.Minutes), Math.Floor(duration.Seconds);
// update a label with the time elapsed string
label.Text = timeElapsed;

public void Evaluate()
{
  // do something here...

}

Hope this helps.

darkagn 315 Veteran Poster Featured Poster

You need to quote your string N like so:

WHERE p.DATE IS NULL and p.TRUE = 'N'
darkagn 315 Veteran Poster Featured Poster

You will need a reference to the UserId in your VideoRental class, then when you assign the VideoRental to the User you update the VideoRental object's UserId to match.

Here's how I would do it:

class User
{
  public GUID Id
  {
    get;
    set;
  }
  private VideoRental m_rental;
  public VideoRental VideoRental
  {
    get
    {
      return m_rental;
    }
    set
    {
      m_rental = value;
      m_rental.UserId = Id;
    }
  }
  // ...
}
class VideoRental
{
  public GUID UserId
  {
    get;
    set;
  }
  // ...
}