|
Hi,
I am writing an automated printer driver performance measuring tool. I have one problem that I need to fix.
Please check the sample code below.
What I need to do is, when I add the job to the print queue, I need to "poll" for the "isDeleted" status (or if possible, "isCompleted" status) and display the time (that part is not written in the sample code) it took to finish the job. In this case, "finish" means that the PRN file has been created. (The port of the printer is set to Local port: PRN file path.)
For this, I need to add a pause (of suitably low amount so that it doesn't affect the time) where I have put a comment in the code below.
I can easily do this with a timer, but it got a bit complicated when i kept on adding features. (i would be adding a list of job, would be backing up the PRN files, get time measurement, use two drivers and compare performance etc. etc.)
using System;
using System.Windows.Forms;
using System.Printing;
using System.Threading;
namespace AddJob
{
public partial class frmAddJob : Form
{
public frmAddJob()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread printingThread = new Thread(printXPS);
printingThread.SetApartmentState(ApartmentState.STA);
printingThread.Start();
}
private void printXPS()
{
LocalPrintServer lp = new LocalPrintServer();
PrintQueue pq = LocalPrintServer.GetDefaultPrintQueue();
try
{
PrintSystemJobInfo psji = pq.AddJob("myXPSJob", "C:\\test.xps", false);
while (psji.IsDeleted != true)
{
psji.Refresh();
}
MessageBox.Show("Done");
}
catch
{
MessageBox.Show("Error");
}
}
}
}
Does anyone have any tips for me?
|
|
|
|
|
1. you can pause a thread using Thread.Sleep
2. you should not perform blocking operations (such as Thread.Sleep) on the main thread
3. most often a timer is the right way for controlling progress
4. use the timer that fits your needs, there are several types. For simple periodic jobs in a WinForms environment, most often a System.Windows.Forms.Timer is the right one as it ticks on the main thread.
5. always prefer an event-driven approach over a polling approach
6. if you must poll, and a timer-based approach doesn't fit, consider using a BackgroundWorker instead (probably with Thread.Sleep now)
7. for file creation/deletion, the FileSystemWatcher class provides some useful events; warning: they signal the start of an action, not the termination of an action.
8. when "things get complicated while adding features", you probably failed to properly apply an object-oriented approach
9. it isn't adding features that causes complexity, it is brain twisting the wrong way.
|
|
|
|
|
|
can you tell me how to combine the edits for field1 and field2 together into the same edit? The fields need to be edited together.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IMpt.Interfaces;
using System.Data;
using System.Collections;
namespace Data.Transactions
{
public class Trans : BaseTransaction
{
#region TransactionType implementation methods
/// <summary>
/// Overrides BaseTransaction function to add additional columns
/// </summary>
/// <returns></returns>
public override List<ColumnNames> GetColumnNames()
{
List<ColumnNames> list = base.GetColumnNames();
list.Add(ColumnNames.filed1);
list.Add(ColumnNames.field2);
return list;
}
public override List<RuleError> ValidateData(DateTime receivedDate)
{
//Call the base class function to do
// common data validations
base.ValidateData(receivedDate);
DataTable excelData = ExcelDataTable;
IMptDataContext didc = new IMptDataContext();
Hashtable colMap = base.ColumnMap;
List<RuleError> masterList = new List<RuleError>();
string colName = ColumnNames.field2.ToString();
string field2ColName = colMap[colName].ToString();
colName = ColumnNames.filed1.ToString();
string field1ColName = colMap[colName].ToString();
int iEnd = excelData.Rows.Count;
for (int i = DataRowNumber - 1; i < iEnd; i++)
{
//First validate all common fields from ColumnMap
DataRow dr = excelData.Rows[i];
{
//Call Base class function to validate common fields
List<RuleError> list = Validate(dr, receivedDate, didc);
if (list == null)
list = new List<RuleError>();
string field1 = dr[field1ColName].ToString();
re = Validatefield1ible(field1);
if (re != null)
{
list.Add(re);
}
string colVal = dr[field2ColName].ToString();
re = Validatefield1(colVal);
if (re != null)
{
list.Add(re);
}
}
excelData.AcceptChanges();
didc.Dispose();
return masterList;
}
/// <summary>
/// Validates data and updates DataTable with error messages and Loads data into DB.
/// </summary>
/// <param name="dtData">Excel data to be loaded into database</param>
/// <param name="wb">ImWorkbook DB entity object.</param>
/// <returns>List of RuleError objects</returns>
public override List<RuleError> LoadData(ImportWkbk wb, string destDocLoc)
{
if (IsDupCheckRequired())
{
DateTime firstDate = new DateTime(1753, 1, 1);
//Create DB context
IMptDataContext didc = new IMptDataContext();
didc.CommandTimeout = AutoCode.SQL_CMD_TIMEOUT;
//Create list of master errors
List<RuleError> masterList = new List<RuleError>();
//Get the column map hashtable
Hashtable colMap = base.ColumnMap;
//Get the columns names from the mapping Hashtable
//Get the columns names from the mapping Hashtable
string colName = ColumnNames.field2.ToString();
string field2ColName = colMap[colName].ToString();
colName = ColumnNames.filed1.ToString();
string field1ColName = colMap[colName].ToString();
Hashtable htSubs = new Hashtable();
Int64 submissionID = 0;
VCust firstCust = null;
int iEnd = ExcelDataTable.Rows.Count;
for (int i = DataRowNumber - 1; i < iEnd; i++)
{
DataRow dr = ExcelDataTable.Rows[i];
try
{
//Get the cust id from database
//VCust nextCust = FindCust(didc, dr[cnColName].ToString());
VCust nextCust = FindCust(dr[cnColName].ToString().Trim().ToUpper());
string field1 = dr[field1ColName].ToString().Trim().ToUpper();
lis.filed1 = field1.Length > 0 ? field1 : null;
string field2 = dr[field2ColName].ToString().Trim().ToUpper();
lis.field2 = field2.Length > 0 ? field2 : null;
didc.SubmitChanges();
didc.Dispose();
return null;
}
null;
string field1 = dr[field1ColName].ToString().ToUpper().Trim();
field1 = field1.Length > 0 ? field1 : null;
) &&
(
(field1 == null && d.filed1 == null) ||
(field1 == d.filed1)
) &&
(
(field2 == null && d.field2 == null) ||
(field2 == d.field2)
) &&
(
orderby d.Transaction_ID descending
select d).ToArray();
}
}
}
excelData.AcceptChanges();
didc.Dispose();
}
public RuleError Validatefield1ible(string field1)
{
RuleError re = null;
if (field1 == null || field1.Trim().Length < 1)
return null;
if (field1.Trim().ToUpper().Equals (field1ibleStatus.PART) ||
field1.Trim().ToUpper().Equals (field1ibleStatus.aLL)
)
{
return null;
}
re = new RuleError(RuleErrorCodes.OTHER, RuleErrorTypes.ERROR, "error 1");
return re;
}
/// <summary>
/// Validates Institutional Status value.
/// </summary>
/// <param name="field2us"></param>
/// <returns></returns>
public RuleError Validatefield1(string field2us)
{
RuleError re = null;
if (field2us == null || field2us.Trim().Length < 1)
return null;
if(field2us.Trim().ToUpper().Equals(field2.NO) ||
field2us.Trim().ToUpper().Equals(field2.YES) ||
field2us.Trim().ToUpper().Equals(field2.maybe)
)
{
return null;
}
re = new RuleError(RuleErrorCodes.OTHER, RuleErrorTypes.ERROR, "error 2.");
return re;
}
}
|
|
|
|
|
No.
But then, I'm not going to wade through that lot trying to work out what is going on.
Edit your question and add a code block to preserve the original formatting and indentation - (Just highlight the code, and press the "code" widget above the textbox). It will make it a lot more readable, and I might look at it then. But not now.
Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water
|
|
|
|
|
closed this thread and started a new thread so the code was more readable.
|
|
|
|
|
That wasn't necessary, you could have just edited your original post
""Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon
|
|
|
|
|
Sorry, didn't read any of that as it wasn't properly formatted and indented. Please use PRE tags.
|
|
|
|
|
hi. i need source of bst(search and delete and find with 10 input ) but i cant find it .please help me.tank you
|
|
|
|
|
This might be a start... A simple Binary Search Tree written in C#[^]
Why not try to write your own source code instead of just asking for source code. It does not work that way here. Better if you try to write your own, and when you have a problem where it isn't working, then ask for help.
"The clue train passed his station without stopping." - John Simmons / outlaw programmer
"Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon
"Not only do you continue to babble nonsense, you can't even correctly remember the nonsense you babbled just minutes ago." - Rob Graham
|
|
|
|
|
Nobody will do your homework....
|
|
|
|
|
In a C#.net 2010 application, I need to only select alphabetic characters (A to Z) from a large textbox where users can enter anything. These alphabetic characters can be in upper or lower case. I need to concantenate the results together. No other characters are suppose to be selected. Thus can you tell me how to accomplish this task?
|
|
|
|
|
What have you done so far to accomplish this?
"The clue train passed his station without stopping." - John Simmons / outlaw programmer
"Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon
"Not only do you continue to babble nonsense, you can't even correctly remember the nonsense you babbled just minutes ago." - Rob Graham
|
|
|
|
|
Use a Regex:
Regex regex = new Regex("[^A-Za-z]", RegexOptions.CultureInvariant);
string result = regex.Replace(InputText,"");
Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water
|
|
|
|
|
Hello everybody
How can i send SMS in C#
|
|
|
|
|
Putting that question into Google will find you lots of suggestions.
|
|
|
|
|
|
as you live in iran same as me, you can use some company web services to send sms via your web application.
if you buy a web service , they give you a uri of service, and you just need to add web reference to your reference folder, and in your code, you just need to make a new method of that, and pass some param to web service.
this my code:
var b = new ArrayOfString();
b.Add("با تشکر از شما جهت ایجاد اشتراک در سایت هلال. کد اشتراک :" + txtSubsCode.Text + "از این پس میتوانید جهت سفارش غذا با شماره:4242998 تماس حاصل نمایید.\n" +"لیست غدایی ما در بخش منوی سایت موجود میباشد");
var c = new ArrayOfString();
c.Add(submit.MobileNo);
var aaa = new sms.sendSmsWebServiceSoapClient();
aaa.sendSms("test", "password", "username", b, c, 1, "30008672");
|
|
|
|
|
Hi I am trying to build a Yahtzee game and am having trouble with the code for the hold dice button, thus to stop the dice from rolling again when button is clicked on.
Also am needing some help and code to make the dice only roll 3 times in a turn. Thanks
Code so far is as follows.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Media;
namespace yahtzeetrial
{
public partial class Form2 : Form
{
int m_nRoll = 0;
int numRolls = 0;
private Random RandomPick;
int[] DiceButtons = new int[] { 0, 0, 0, 0, 0 };
int[] DiceHold = new int[] { 0, 0, 0, 0, 0 };
int AllDice = 0;
public Form2()
{
InitializeComponent();
InitialiseDiceButtons();
}
SoundPlayer My_JukeBox = new SoundPlayer(@"C:\Users\Bronwyn\Documents\Yahtzee Game\yahtzeetrial\diceroll.wav");
public void InitialiseDiceButtons()
{
this.btn1.ImageList = imageList1;
this.btn1.ImageIndex = 0;
this.btn2.ImageList = imageList1;
this.btn2.ImageIndex = 0;
this.btn3.ImageList = imageList1;
this.btn3.ImageIndex = 0;
this.btn4.ImageList = imageList1;
this.btn4.ImageIndex = 0;
this.btn5.ImageList = imageList1;
this.btn5.ImageIndex = 0;
}
private void btnRoll_Click(object sender, EventArgs e)
{
My_JukeBox.Play();
InitialiseRandomRoll();
do
{
m_nRoll = 0;
Roll();
if ((m_nRoll >= 1) || (m_nRoll <= 6))
{
DiceButtons[AllDice] = m_nRoll;
AllDice++;
}
} while (AllDice < 5);
this.btn1.ImageIndex = DiceButtons[0];
this.btn2.ImageIndex = DiceButtons[1];
this.btn3.ImageIndex = DiceButtons[2];
this.btn4.ImageIndex = DiceButtons[3];
this.btn5.ImageIndex = DiceButtons[4];
AllDice = 0;
}
public void Roll()
{
m_nRoll = (int)(RandomPick.NextDouble() * 6) + 1;
}
public void InitialiseRandomRoll()
{
DateTime aTime = new DateTime(1000);
aTime = DateTime.Now;
int nSeed = (int)(aTime.Millisecond);
RandomPick = new Random(nSeed);
}
private void btnHold1_Click(object sender, EventArgs e)
{
if (DiceHold[0] == 0)
{
DiceHold[0] = 1;
this.btnHold1.ForeColor = Color.Red;
}
else
{
DiceHold[0] = 0;
this.btnHold1.ForeColor = Color.Black;
}
}
private void btnHold2_Click(object sender, EventArgs e)
{
if (DiceHold[1] == 0)
{
DiceHold[1] = 1;
this.btnHold2.ForeColor = Color.Red;
}
else
{
DiceHold[1] = 0;
this.btnHold2.ForeColor = Color.Black;
}
}
private void btnHold3_Click(object sender, EventArgs e)
{
if (DiceHold[2] == 0)
{
DiceHold[2] = 1;
this.btnHold3.ForeColor = Color.Red;
}
else
{
DiceHold[2] = 0;
this.btnHold3.ForeColor = Color.Black;
}
}
private void btnHold4_Click(object sender, EventArgs e)
{
if (DiceHold[3] == 0)
{
DiceHold[3] = 1;
this.btnHold4.ForeColor = Color.Red;
}
else
{
DiceHold[3] = 0;
this.btnHold4.ForeColor = Color.Black;
}
}
private void btnHold5_Click(object sender, EventArgs e)
{
if (DiceHold[4] == 0)
{
DiceHold[4] = 1;
this.btnHold5.ForeColor = Color.Red;
}
else
{
DiceHold[4] = 0;
this.btnHold5.ForeColor = Color.Black;
}
}
}
}
modified 1-Jun-12 22:22pm.
|
|
|
|
|
You can use this code for dice:
public void InitializeRandomRoll( int nSeed )
{
DateTime aTime = new DateTime(1000);
aTime = DateTime.Now;
nSeed += (int)(aTime.Millisecond);
RandomPick = new Random(nSeed);
}
We need to be able to hold a dice,so that it does not roll when the roll button is pressed.So,we add a variable to hold the state of the dice.and you can use this property.
private bool m_bHoldState = false;
public bool HoldState
{
get { return m_bHoldState; }
set { m_bHoldState = value; }
}
Now,we need to make sure that if the dice is held,it does not get rolled.
public void Roll()
{
if( !HoldState )
{
RollNumber = RandomPick.Next(1,7);
this.Invalidate();
}
}
At the end,the dice is drawn in black if the dice is not held,and in red if it is.
public void DrawDot( Graphics g, Point p )
{
SolidBrush myBrush;
if( HoldState )
{
myBrush = new SolidBrush( Color.Red );
}
else
{
myBrush = new SolidBrush( Color.Black );
}
g.FillEllipse( myBrush, p.X, p.Y, dotWidth, dotWidth );
myBrush.Dispose();
}
|
|
|
|
|
This coding looks like from the same source as I have already found on this site I was hoping that someone else may have something different to try out. Thanks.
|
|
|
|
|
I installed the EF CTP4 from here[^]
I am now trying to configure a mapping:
using System.Data.Entity.ModelConfiguration;
using Falcon.Entities.Entities;
namespace Falcon.DAL.Configuration
{
public class ClientConfiguration : EntityConfiguration<ClientEntity>
{
public ClientConfiguration()
{
Property(c => c.Id).IsIdentity();
Property(c => c.ClientName).HasMaxLength(50).IsRequired();
Property(c => c.IsActive);
Relationship(c => c.Company).IsRequired();
}
}
}
It can't find Relationship. All the code examples and the book I'm using have this. Anyone know what's wring here?
If it's not broken, fix it until it is
|
|
|
|
|
Hi Kevin,
I think you have to associate by providing the foreign key in the relationship.
Property(c => c.Company).IsRequired().WithMany()
.HasForeignKey(u => u.CompanyId);
|
|
|
|
|
I hope this is the correct place to post this. If not, please help me correct it.
Lately, I have been digging around in open source projects at SourceForge.net. I download the source for an interesting project, typically if it seems like something I may learn from. I may be working on a project in which I need to create a custom control and I would like a good code example that I can study. Once the source is downloaded and I extract it as needed, I load the solution in Visual Studio 2010.
Once I begin digging through some of the code my head begins to hurt. It hurts terribly. For one, I see little white space in many projects. And two, the thing that really gets me, is the fact that variables have completely meaningless names, usually just one or two letters. It looks like this (not real code; just an example):
Dictionary<string, int> d = new Dictionary<string, int>();
private void MyMethod(string p, int q)
{
bool b = p == "string1" ? true : false;
List<string> l = GetList(b);
foreach (string k in l)
{
if (!string.IsNullOrWhiteSpace(p) && q > 0)
d.Add(l, q);
}
}
Before I continue, what does the fact that p == "string1" have to do with anything? Also, what does GetList(bool) do and how does the value of 'b' affect the results?
The first thing I tend to notice is that there is no documentation (///<summary>) for the method. Adding those comments too methods and classes is typically the first thing I do when I am coding. Maybe it isn't a recommended practice but instead it is just my own "standard"/style? If so, that's fine. Should this be something everyone uses?
The comments are typically quite vague as well. Or comments are missing entirely, even in methods that contain a lot of code. And in MyMethod, how should you really know what "d" is when it is declared in another file/class? And why exactly does "q > 0" have to be met before adding the item? This isn't a perfect example but I'm not on the computer I use when browsing through these projects. Perhaps I am being overly conscious about coding practices, standards, whatever. But I find it very difficult to read the code at times.
Another thing that bugs me slightly, though I guess it's expected when anyone can contribute to the project, is the lack of a consistent coding style. That doesn't bug me near as much as the rest. It's just a thought that I figured I'd throw in here.
djj55: Nice but may have a permission problem
Pete O'Hanlon: He has my permission to run it.
|
|
|
|
|
My 2 cts:
1.
The worst style aspect is using single-letter identifiers, especially for the method itself and its parameters. Giving them meaningful names makes things a lot easier to understand. And they might show up in Intellisense or something similar, making the use of the method a lot easier.
2.
Yes, a method-level comment (a "contract") explaining what the method promises to do for you would be nice (unless #1 fixed all that already).
3.
About why "string1" and "q>0" are there I can't tell you anything, as I have no clue what the purpose of the whole thing is.
|
|
|
|
|