I've been messing around with Python and IronPython this week and I've stumbled across an extremely annoying oddity.
Basically I am connecting to a MSSQL database and upon success setting self.label1.Text = "Connected to " + sqlConn.Database + " on " + sqlConn.DataSource, however my label is updating to just say "Connected to" on the form. I placed a MessageBox.Show(self.label1.Text) after and this displays all the correct information ("Connected to DATABASE on DATASOURCE"). My question is, why isn't IronPython setting my label text correctly on the form?
class MyForm(Form):
def __init__(self):
self.button1 = Button()
self.button1.Text = "Click Me!"
self.button1.Click += self.button1_Click
self.Controls.Add(self.button1)
self.label1 = Label()
self.label1.Location = Point(10, 50)
self.Controls.Add(self.label1)
def button1_Click(self, sender, args):
sqlConn = self.connectSql()
if sqlConn.State == ConnectionState.Open:
self.label1.Text = "Connected to " + sqlConn.Database + " on " + sqlConn.DataSource
MessageBox.Show(self.label1.Text)
else:
self.label1.Text = "Failed connection"
def connectSql(self):
sqlConn = SqlClient.SqlConnection("Data Source=(local);Initial Catalog=IT_Project;Integrated Security=True;")
try:
sqlConn.Open()
except System.Exception as ex:
MessageBox.Show("Error!\r\n" + ex.Message, "EXCEPTION HANDLED")
return sqlConn
Thanks in advance. :)
The content of the Label is truncated because of its default size and behavior. By manually setting a sufficient size or using the AutoSize-Property the full content can be displayed.
The following code could be used after creating the label to size the label to its content:
self.label1.AutoSize = True
The fact that the message box displayed the full value from the actual control's text hinted to the underlying cause.
Note that according to the documentation the auto sizing default behavior may vary:
When added to a form using the designer, the default value is true. When instantiated from code, the default value is false.
Related
I have a form with customer info that needs to be processed one transaction per page. I'm using the binding navigator to manage my pagination.
It works in all but some cases. In the cases where it doesn't work, I have to open a different window to look up information and return it to the main form. Here is the code for that:
// save current work
updateDataTable();
// Open a window and get new customer info
// CurrentCustomer is returned from the opened window
using (SqlConnection cx = new SqlConnection(GetConnectionString()))
{
DataRowView dataRow = (DataRowView)procBindingSource.Current;
dataRow.BeginEdit();
dataRow["CUSTOMER"] = CurrentCustomer;
dataRow.EndEdit();
updateDataItems();
SqlCommand cmd = new SqlCommand(
#" select acct_no from cust_processing where id = #id ", cx);
cmd.Parameters.AddWithValue("#id", (int)dataRow["ID"]);
cx.Open();
var results = cmd.ExecuteScalar();
if (results != null)
{
dataRow.BeginEdit();
dataRow["ACCT_NO"] = results.ToString();
dataRow.EndEdit();
updateDataItems(); <------ CONCURRENCY ERROR
}
}
The error I am getting is a concurrency error. I think that I have more than one version of the row possibly ? I thought I was making sure that I was on the most recent version of the row by calling updateDataTable(). I am the only user so I know I am creating the problem myself.
Here is my update method which is called when I change pages or save and exit or want to write the commit the data:
void updateDataItems()
{
this.procBindingSource.EndEdit();
this.procTableAdapter.Update(xyzDataSet);
xyzDataSet.AcceptChanges();
}
I have tried executing updateDataItems from various places such as after I assign dataRow["ACCT_NO"] = results.ToString() or before and after assigning that.
I'm pretty much down to guess and check so any thoughts, help and advice will be appreciated and +1.
Okay -- so the problem was that I was trying to update the current row from the program and also using the binding navigator. They were not working together properly.
The solution was to add a text box to the form in the forms designer and set visible = false and bind it to ACCT_NO. Once I got the results from my other form, I just needed to set the .text property of the ACCT_NO textbox to the new value and the binding navigator managed all my updates for me correctly.
txtAcct_No.text = results.ToString();
few years ago I wrote a WPF (Visual Basic 2012 based) app which included "printing" some report using standard WPF printdialogs/paginators/features....
everyting worked fine since then (2011/2015), and I did not change a line of that working code...
Now I had to change something (not printing related) to that project and of course I checked the printing features as well...
now the "printing" code fails when using it... actually is not the "paginator" code, but accessing the PrintTicket/Que objects fails reporting
"PrintTicket provider failed to convert PrintTicket to DEVMODE. Win32 error: The parameter is incorrect. "
but it's weird as it does not always fail, and it fails differently with different printers...
using for instance "PDF Creator" virtual printer, it fails writing/settings some properties of my Que object and not others, while using a different printer fails on others...
for instance, PDF Creator virtual printer:
1) myQue.DefaultPrintTicket = myTicket = OK
2) myQue.CurrentJobSettings.Description = "some title" = OK with some printer, FAILS with a different printer
but 2) only fails the very first time it is set, and I can "resolve" "looping" a few times with a minor time sleep.... again, the second or third time it succeded...
so I wrote an ugly code like
Dim dlg As New PrintDialog
.....
myTicket = dlg.PrintTicket
myQue = dlg.PrintQueue
'-----
' to check in a loop if the interesting
' properties has been set
Dim ticketIsSet(1) As Boolean
For iLoop As Integer = 1 To 5
'it can fail with DEVMODE = NULL
Try
If Not ticketIsSet(0) Then
myQue.DefaultPrintTicket = myTicket
ticketIsSet(0) = True
End If
If Not ticketIsSet(1) Then
myQue.CurrentJobSettings.Description = Me.Title
ticketIsSet(1) = True
End If
Catch ex As Exception
Errors.Add(ex.Message)
System.Threading.Thread.CurrentThread.Sleep(1000)
End Try
If ticketIsSet(0) AndAlso ticketIsSet(1) Then Exit For
Next
If Errors.Count Then
' it's still ok if title can't be set... :(
If ticketIsSet(0) Then Errors.Clear()
End If
so far, "so good" as I get the job done... but only partially... as my Paginator is used to (succesfully) populate a System.Windows.Controls.DocumentViewer... this alternate documentviewer window can later actually print if requested...
and again, with different printers it succed or fail with "PrintTicket provider failed to convert PrintTicket to DEVMODE. Win32 error: The parameter is incorrect. " exception...
with PDF Creator virtual printer it succed, with a different physical printer it fails...
I tried the very same looping trick as above, like
Dim Errors As New Specialized.StringCollection
Dim bDone As Boolean = False
For iLoop As Integer = 1 To 5
Try
Dim writer As System.Windows.Xps.XpsDocumentWriter = System.Printing.PrintQueue.CreateXpsDocumentWriter(m_printQueue)
writer.Write(Me.docViewer.Document.DocumentPaginator, Me.m_printTicket)
writer = Nothing
bDone = True
Catch ex As Exception
Errors.Add(ex.Message)
System.Threading.Thread.CurrentThread.Sleep(1000)
End Try
If bDone Then Exit For
Next
If bDone Then Errors.Clear()
If Errors.Count <> 0 Then BasShowErrors(Errors, Me, False)
and here it fails (again, on some printers) on
writer.Write(Me.docViewer.Document.DocumentPaginator, Me.m_printTicket)
with "PrintTicket provider failed to convert PrintTicket to DEVMODE. Win32 error: The parameter is incorrect. " exception...
obviously that printer is ok as regards other programs like World, Excel and the like, and it's ok as well with all other (NOT WPF based) projects... and again this only occur "NOW", as it worked like a charme at the time of the initial development...
my current settings are:
Win7 Ultimate sp 1
SQL 2014 Dev Edition (not relevant)
Visual Studio 2012 Ultimate Version 11.0.61219.00 Update 5
Microsoft .NET Framework version 4.6.01055
I even tried "repairing" the NET Framework with NetFramwork Repair Tool (https://www.microsoft.com/en-us/download/details.aspx?id=30135) with no success...
any hint is very appreciated :)
TIA
asql
I'm working on a WPF application and i cant seem to get this right. I am brand new to WPF.
I want to get the text from the database into text boxes but i tried it with only one textbox the first time and i get this error:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
This is the code i have so far, this is how it's done in winforms but i suppose not the same in WPF
dbconn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=ChampInfo1.accdb");
dbconn.Open();
string selectallSQL = "SELECT Passive " +
"FROM BChampInfo " +
"WHERE [Champ Name] = Aatrox";
dbcomm = new OleDbCommand(selectallSQL, dbconn);
OleDbDataReader dbread = dbcomm.ExecuteReader();
while (dbread.Read())
{
txtskillname1.Text = dbread["Passive"].ToString();
}
I don't know what is wrong though, any help will be appreciated.
All my oledb declaration are done at the top.
It can be the easy target for sql injection. The problem is in query. Try this
string selectallSQL = "SELECT Passive " +
"FROM BChampInfo " +
"WHERE [Champ Name] = ?";
dbcomm = new OleDbCommand(selectallSQL, dbconn);
dbcomm.Parameters.AddWithValue("#aat", "Aatrox");
I have a silverlight application that allows people to enter into a notes field which can be printed, the code used to do this is:
PrintDocument pd = new PrintDocument();
Viewbox box = new Viewbox();
TextBlock txt = new TextBlock();
txt.TextWrapping = TextWrapping.Wrap;
Paragraph pg = new Paragraph();
Run run = new Run();
pg = (Paragraph)rtText.Blocks[0];
run = (Run)pg.Inlines[0];
txt.Text = run.Text;
pd.PrintPage += (s, pe) =>
{
double grdHeight = pe.PrintableArea.Height - (pe.PageMargins.Top + pe.PageMargins.Bottom);
double grdWidth = pe.PrintableArea.Width - (pe.PageMargins.Left + pe.PageMargins.Right);
txt.Width = grdWidth;
txt.Height = grdHeight;
pe.PageVisual = txt;
};
pd.Print(lblTitle.Text);
This simply prints the content of the textbox on the page however some of the notes are spanning larger than the page itself causing it to be cut off. How can I change my code to measure the text and add more pages OR is there a better way to do the above where it will automatically create multiple pages for me?
There are several solutions to your problem, all of them under "Multiple Page Printing Silverlight" on Google. I was having a similar problem and tried most of them. The only one that worked for me was this one:
http://www.codeproject.com/Tips/248553/Silverlight-converting-to-image-and-printing-an-UI
But honestly you should look at Google first and see whether there are better solutions to your specific problem.
Answering your question, there is a flag called HasMorePages that indicates you need a new page. Just type pe.HasMorePages and you will see.
Hope it helps
First you need to work out how many pages are needed
Dim pagesNeeded As Integer = Math.Ceiling(gridHeight / pageHeight) 'gets number of pages needed
Then once the first page has been sent to the printer, you need to move that data out of view and bring the new data into view ready to print. I do this by converting the whole dataset into an image/UI element, i can then adjust Y value accordingly to bring the next set of required data on screen.
transformGroup.Children.Add(New TranslateTransform() With {.Y = -(pageIndex * pageHeight)})
Then once the number of needed pages is reached, tell the printer to stop
'sets if there is more than 1 page to print
If pagesLeft <= 0 Then
e.HasMorePages = False
Exit Sub
Else
e.HasMorePages = True
End If
Or if this is too much work, you can simply just scale all the notes to fit onto screen. Again probably by converting to UI element.
Hope this helps
I'm getting strange additional symbols (=) in text property when adding text there via POST.
For example:
The team is back with an unstoppable fury as they are being chased by the p= olice, Alonzo and Yuuma. Vinnie, Shorty and Kiro=92s skills will be put to = the test.
There shouldn't be any of = symbols in that text.
My co de is:
class FileUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
game_file = self.get_uploads()[1]
screen_file = self.get_uploads()[0]
if not users.get_current_user():
game_file.delete()
screen_file.delete()
self.redirect(users.create_login_url("/"))
return
game = Game()
game.title = self.request.get('title')
game.url_name = self.request.get('url')
if self.request.get('active') == 'active':
game.active = True
else:
game.active = False
if self.request.get('featured') == 'featured':
game.featured = True
else:
game.featured = False
query = Category.gql("WHERE url_name = :url_name", url_name=self.request.get('category'))
game.category = query.get()
game.width = int(self.request.get('width'))
game.height = int(self.request.get('height'))
game.description = db.Text(self.request.get('desc'))
game.how_to_play = db.Text(self.request.get('htp'))
game.game_file = game_file
game.game_screenshot = screen_file
db.put(game)
What am i doing wrong?
This is a known issue of blobstore handler that is breaking the data encoding.
I had the same difficulty. But, I found a fix. I'm using Python 2.5. In my model, I have a TextProperty, hooked up to an html TextArea tag. Like your situation, in the Dev server, it saved what I entered. However, in Prod, the DataStore somehow added "= " among others, every time I write the content of textarea over to the textproperty field.
Go here:
http://code.google.com/p/googleappengine/issues/detail?id=2749
Then, scroll down to Comment 21. The poster of that comment attached a file, named appengine_config.py Download it, and put it on the root folder of your app. Then Deploy it to Prod and try it out in Prod.
I did that, and my "= " problem went away.