Why does my code make ID null - c#

I have a program that gets values from a database through a stored procedure. What it does is gets the values, downloads an image and then uploads it to a server. and after upload the run another stored procedure just to update the table to the new url.
Now it uploads a few images correct then all of a sudden it makes my ID = "" and I cant see why?
Result as log file:
Property ID : 29140
pk_photo_id (TRY): 47334070
- File : propimage29140_9.jpg has been uploaded to AWS S3 bucket: ruans
Property ID : 30402
pk_photo_id (TRY): 47174447
Property ID : 29330
Property ID : `<-- why make it nothing`
pk_photo_id (TRY): 47174392
ERROR 6 : Cannot insert duplicate key row in object 'dbo.ET_EXPORT_PROPERTY_QUEUE' with unique index 'idx_pk'. The duplicate key value is (<NULL>).
The statement has been terminated.
My VB sub where this takes place:
Dim files As String() = Directory.GetFiles(txtFolderPath)
'for each image get file name
For Each images As String In files
Dim id As String = ""
Dim photoID As String = ""
Dim position As String = ""
For Each str As String In IDS
If Path.GetFileNameWithoutExtension(sKey).Contains(str) Then
id = str
End If
Log("Property ID" & id)
For Each value As String In PhotoIDS
photoID = value
Next
For Each URL As String In fullURL
fullURLIndex = URL
Next
Next
'AWS upload
Try
utility.Upload(txtFolderPath & sKey, bucket)
Catch
needsToExitSub = True
Dim cmdSetError As New SqlCommand("ETSP_UPDATE_PHOTO_URLS")
cmdSetError.CommandType = CommandType.StoredProcedure
cmdSetError.Parameters.AddWithValue("#stype", "L")
cmdSetError.Parameters.AddWithValue("#surl", fullURLIndex)
cmdSetError.Parameters.AddWithValue("#status", 3)
cmdSetError.Parameters.AddWithValue("#pk_photo_id", photoID)
Log("pk_photo_id (CATCH): " & photoID)
cmdSetError.Parameters.AddWithValue("#bactive", 1)
cmdSetError.Parameters.AddWithValue("#property_id", id)
cmdSetError.Parameters.AddWithValue("#client_id", clientIDs)
conn.Open()
cmdSetError.Connection = conn
cmdSetError.ExecuteNonQuery()
Log(" - ERROR 4 : File : " & sKey & " Image ID : " & photoID & " Has NOT been uploaded to " & bucket & " , URL: " & fullURLIndex)
conn.Close()
If needsToExitSub = True Then
Exit Sub
End If
End Try
'Make files public - check this
Dim cannedACL As S3CannedACL = S3CannedACL.PublicRead
Dim fileNameOnly As String = Path.GetFileNameWithoutExtension(sKey)
Dim token As String = fileNameOnly.Remove(fileNameOnly.LastIndexOf("_"c))
Dim number As New String(token.SkipWhile(AddressOf [Char].IsLetter).ToArray())
'Run stored procudure and update if uploaded
Dim cmdSet As New SqlCommand("ETSP_UPDATE_PHOTO_URLS")
cmdSet.CommandType = CommandType.StoredProcedure
cmdSet.Parameters.AddWithValue("#stype", "L")
cmdSet.Parameters.AddWithValue("#surl", Convert.ToString("www.url.com/" & bucket & "/" & sKey))
cmdSet.Parameters.AddWithValue("#status", 2)
cmdSet.Parameters.AddWithValue("#pk_photo_id", photoID)
Log("pk_photo_id (TRY): " & photoID)
cmdSet.Parameters.AddWithValue("#bactive", 1)
cmdSet.Parameters.AddWithValue("#property_id", id)
cmdSet.Parameters.AddWithValue("#client_id", clientIDs)
conn.Open()
cmdSet.Connection = conn
cmdSet.ExecuteNonQuery()
conn.Close()
Next
Log(" - File : " & sKey & " has been uploaded to AWS S3 bucket: " & bucket)
Catch ex As System.NullReferenceException
Log("ERROR 5 : " & ex.Message)
Catch ex As Exception
Log("ERROR 6 : " & ex.Message)
Exit Try
End Try
So the images downloads file to my computer in the correct folder, then it uploads it also to the correct folder but then when it comes to update the database to update new url and the other parameters it gives the error, now i think it is because the Property ID : is made null.
Why would it get the correct Property ID : for lets say 8 images then get a null for a while and then again get the correct Property ID :. and how can i fix this.
C# help welcome

Related

Is the hard-drive serial number with WMIService CHANGEABLE?

I use Hard-Drive Serial-Number check to register my products.
But I see that sometimes it's being changed.
Just 2 weeks after the client has activated the product, the hard-drive Serial-Num changed.
Is this property changeable? and if so, how when and why is it changed?
Here is the code i use in VB:
Dim WMIService As Object, Items As Object, SubItems As Object, temp
Set WMIService = GetObject("winmgmts:\\" & "." & "\root\cimv2")
Set Items = WMIService.ExecQuery("Select * from Win32_PhysicalMedia", , 48)
For Each SubItems In Items
temp = SubItems.SerialNumber
If LenB(temp) Then Exit For
Next
and the same thing i use in C#
using System.Management;
public string GetHDDSerial()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
foreach (ManagementObject wmi_HD in searcher.Get())
{
// get the hardware serial no.
if (wmi_HD["SerialNumber"] != null)
return wmi_HD["SerialNumber"].ToString();
}
return string.Empty;
}
Thanks to the comment from FunThomas and after a little troubleshooting with my client, i found out that he is using sometimes an external drive for more space, and when the external drive is plugged in - i'm getting a different HDD Serial-number.
Now i have figured how to get the serial number from the current drive letter.
here is the code for VB:
Dim WMIService As Object, DiskDrives As Object, Drive As Object, DiskPartitions As Object, Partition As Object, SerialNumber, currentDrive
currentDrive = Environ("HomeDrive")
Set WMIService = GetObject("winmgmts:\\" & "." & "\root\cimv2")
Set DiskPartitions = WMIService.ExecQuery("ASSOCIATORS OF {Win32_LogicalDisk.DeviceID='" & currentDrive & "'} WHERE ResultClass=Win32_DiskPartition")
For Each Partition In DiskPartitions
Set DiskDrives = WMIService.ExecQuery("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" & Partition.DeviceID & "'} WHERE ResultClass=Win32_DiskDrive")
For Each Drive In DiskDrives
Debug.Print "Caption: " & Drive.Caption, "Description: " & Drive.Description, "Name: " & Drive.Name, "Model: " & Drive.Model, "SerialNumber: " & Drive.SerialNumber
SerialNumber = Drive.SerialNumber
Next
Next

How to UPDATE a single record using three criteria in WHERE clause of UPDATE command?

I am using Visual Basic 2015 as Frontend and Access Database as Backend. I want to UPDATE a single record in a table on the following three bases:
WHERE
Sap_No = TxtSap_No AND
MNT (i. e. Month) = CmbMonth.Text (i. e. ComboBox Text) AND
YR (i.e. Year) = CmbYear.Text (i. e. ComboBox Text)
My UPDATE Command is as follows:
Try
LvMasterCmd.CommandText = "UPDATE LeaveMaster SET Sap_No= #Sap_No, From_Date= #From_Date, To_Date= #To_Date, LeaveType= #LeaveType, Days= #Days, LeaveStatus= #LeaveStatus , MNT = #MNT , YR = #YR WHERE Sap_No= " & CInt(TxtSapID.Text) & " AND MNT= " & MN & " ;"
LvMasterCmd.Parameters.AddWithValue("#Sap_No", TxtSapID.Text)
LvMasterCmd.Parameters.AddWithValue("#From_Date", DtpFrom.Value)
LvMasterCmd.Parameters.AddWithValue("#To_Date", DtpTo.Value)
LvMasterCmd.Parameters.AddWithValue("#LeaveType", LT)
LvMasterCmd.Parameters.AddWithValue("#Days", LblDays.Text)
LvMasterCmd.Parameters.AddWithValue("#MNT", MN)
LvMasterCmd.Parameters.AddWithValue("#YR", YRR)
LvMasterCmd.Parameters.AddWithValue("#LeaveStatus", "Y")
LvMasterReader.Close()
LvMasterCmd.ExecuteNonQuery()
LvMasterCmd.Parameters.Clear()
Exit Sub
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
But Is Shows
NO VALUE GIVEN FOR ONE OR MORE CRITERIA EXPRESSION
What is wrong with this code and How to correct it? Please help.
I noticed that your variable for year is YR but in LvMasterCmd.Parameters.AddWithValue("#YR", YRR) you are using YRR could your problem be as simple as the variable naming being a typo?
You explained the problem statement as including MN and YR but you have typed YRR.
--Starting with the most obvious problem first.
you can not update any column if any value in condition was invalid...so you should be sure that these values exists in database then try this format
Try
LvMasterCmd.Parameters.AddWithValue("#Sap_No", TxtSapID.Text)
LvMasterCmd.Parameters.AddWithValue("#From_Date", DtpFrom.Value)
LvMasterCmd.Parameters.AddWithValue("#To_Date", DtpTo.Value)
LvMasterCmd.Parameters.AddWithValue("#LeaveType", LT)
LvMasterCmd.Parameters.AddWithValue("#Days", LblDays.Text)
LvMasterCmd.Parameters.AddWithValue("#MNT", MN)
LvMasterCmd.Parameters.AddWithValue("#YR", YRR)
LvMasterCmd.Parameters.AddWithValue("#LeaveStatus", "Y")
LvMasterCmd.CommandText = "UPDATE LeaveMaster SET Sap_No= #Sap_No, From_Date= #From_Date, To_Date= #To_Date, LeaveType= #LeaveType, Days= #Days, LeaveStatus= #LeaveStatus , MNT = #MNT , YR = #YR WHERE Sap_No = " & CInt(TxtSapID.Text) & " AND MNT = '" & MN & "'"
LvMasterReader.Close()
LvMasterCmd.ExecuteNonQuery()
LvMasterCmd.Parameters.Clear()
Exit Sub
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

duplicate entry on database using php

how to check for duplicate entry on a form using php?my front end is c#windows application
I am adding a new user to database using c# and php file.
I have created the following:
my project in c# (form1):
c# coding:
private void btncreate_Click(object sender, EventArgs e)
{
var request = (HttpWebRequest)WebRequest.Create("http://***.**.***.***/response.php");
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
using (var stream = request.GetRequestStream())
{
var buffer = Encoding.UTF8.GetBytes("userid= " + txtUserid.Text + " & password=" + txtConformpassword.Text + " & first_name=" + txtFirstname.Text + " & last_name=" + txtLastName.Text + "& role= " + cmbRole.Text + "& active=" + cmbActive.Text + "");
stream.Write(buffer, 0, buffer.Length);
}
var response = (HttpWebResponse)request.GetResponse();
string result = String.Empty;
using (var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
txtMessage.Text = result;
}
my PHP file :response.php
<?php
$uid = $_POST['userid'];
$pass = $_POST['password'];
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$rol = $_POST['role'];
$act = $_POST['active'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql= "INSERT INTO aster(userid,password,first_name,last_name,role,active)
VALUES('$uid', '$pass', '$fname','$lname','$rol','$act');";
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
it add data successfully but when i enter the same userid in textbox and click create button i need to get an error message in txtmessage as userid already exists.
i search through googling but i did not got any thing about duplicate entry please refer me some coding
You could extend your response.php to do a select statement before the insert. If you are able to select a record with the given ID, then yield a response (essentially an error code) which your C# application will then interpret and display to the user.
As a side note, since the ID field appears to be numeric, you can simply omit it from your form and let the DB increment it automatically. This would also mean that the user will not have to guess which ID values are available.
you just want that the ID which you have entered should not be inserted at the next time . for that you just need to do one thing. make your id as a primary key in your database table creation , after doing this you will be not able to insert that id again or duplicate entries are not allowed in a primary key.
lemme know if it is useful.
It may not help as much, but I think my explanation will point you to the right direction.
What I would do is:
I would use SQL query to check if record exist and if exist then print "Record Exists" Else "Record does not exist". Below the code I post, 'Justin Yen' on PHP posting a quote, make sure you assign that to the field of inputting the username. In your case it's $uid.
On PHP, assign the result of sql query to a variable.
Create a string variable "Record Exists" and "Record does not exist".
compare the string variable you create on step 3 to the result on step 2.
I don't know any PHP coding, but you can try to find a way to compare string. But here's an example of checking record exist in SQL:
Declare #Username varchar(MAX) = 'Justin Yen'
IF EXISTS(select Username from EmployeTable where Username = #Username)
begin print 'Record Exists' end
else
begin print 'Record does not exist' end
Now all you have to do is if variable match then prompt "Cannot create record because Record created." Else use the add record codes you have in php.
You can simply try to add the contraints(UNIQUE/PRIMARY) to the column 'userid'.
ALTER TABLE aster ADD CONSTRAINT MyUniqueKey UNIQUE KEY(userid)

Print report pages in different files providing filenames dynamically

I have come across a challenging requirement for Reports and Printing of reports. The requirement is : Create a report (lets say 5 pages), each page should be saved in different files with providing the filename dynamically (using record id on that page) through the code.
Currently, I tried with Access and VBA, I could get the report of X pages, but fail to save each page of the report in separate files. How do I accomplish this ?
Can any other technology help me achieve this goal - maybe programming in C# or Java help me? I've been stuck on this for 3 days on this.
Thanks
My Access Code and the problem :
Private Sub Report_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim MyFilename As String
Dim MyPath As String
Dim temp As String
Set db = CurrentDb
MyPath = "c:\temp\"
Dim stremp As String
stremp = "select distinct(empno) from query2"
Set rs = db.OpenRecordset(stremp)
Do While Not rs.EOF
temp = rs("Empno")
MyFilename = rs("EMPNO") & ".PDF"
DoCmd.OpenReport "FORM", acViewReport, "EMPNO" = " & temp"
'DoCmd.OpenReport "form", acViewPreview, , "empno", acWindowNormal
DoCmd.OutputTo acOutputReport, "", acFormatPDF, MyPath & MyFilename
'do.cmd.outputto
DoCmd.Close acReport, "FORM"
DoEvents
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
The recordset has 5 records i.e. 5 pages. It prints 5 times 5 pages i.e. for Record1 I get all 5 recrods, Record2 - all 5 records & so on. Instead I should create only 1 for Record1, 1 for Record2 and so on.
Can anyone help me know where my code is wrong/improper.
Thanks
you can split task to:
generate full report as one file
store every page of report as different files.
If you already complete first part, and if you can store your report as pdf file, for second part i can suggest to use iText. It is java library, but has port to c# too.
Small example:
String folder = "/home/user/report/";
InputStream is = new FileInputStream(folder + "test.pdf");
PdfReader reader = new PdfReader(is);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
File tmp = new File(folder + "out" + i +".pdf");
FileOutputStream outStream = new FileOutputStream(tmp);
Document pdDoc = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(pdDoc, outStream);
pdDoc.open();
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page = writer.getImportedPage(reader, i);
pdDoc.newPage();
cb.addTemplate(page, 0, 0);
pdDoc.close();
}
Can you help me know, why my code of Access doesn't do the job.
This statement has problems:
DoCmd.OpenReport "FORM", acViewReport, "EMPNO" = " & temp"
The third argument of DoCmd.OpenReport is [FilterName] which is "A string expression that's the valid name of a query in the current database." Unfortunately,
"EMPNO" = " & temp"
is a boolean expression that will always be False because the two strings are not equal. I think you had something more like this in mind:
DoCmd.OpenReport "FORM", acViewReport, , "EMPNO = " & temp
where the fourth argument, [WhereCondition], is "A string expression that's a valid SQL WHERE clause without the word WHERE."

Dynamically produce a DataTable selecting Rows from two other DataTables

I have a SQL table which stores the different rates charged to clients.
The table also includes a list of 'default' rates to be used if the client has none specific to them.
What I need, is once the user selects a client from a combo box, to create a table of rates for that client, consisting of the defaults, or the rates specific to that client, or a mix of both, as follows:
Client Type of Work Rate
ABC Ltd Type A 100
XYZ & Co Type B 150
Default Type A 125
Default Type B 175
So the rates returned would look as follows:
ABC Ltd Type A 100
Type B 175 (default)
XYZ & Co Type A 125 (default)
Type B 150
Anyone else Type A 125 (default)
Type B 175 (default)
The information in the database is structured as follows
Table for clients
Table for Types of Work
Table for Rates (foreign keys linking to clients and types of work)
Can anyone explain how best to obtain the above result using either a SQL statement, a C# routine in the winforms application or a combination of both.
PS. I apologise but I'm unsure how to set my data out in tables on this website.
WHAT I HAVE TRIED SO FAR
public static DataTable TableOfRates(string pIPName = "Default")
{
try
{
string sqlText1 = "SELECT RateID, IPName, RateName, Rate, DateFrom, DateTo, Active, " +
"(RateName + ': £' + CONVERT(VARCHAR, Rate) + CONVERT(VARCHAR, " +
"(CASE WHEN Active = '1' THEN ' (Active)' ELSE ' (Inactive)' END))) AS ListRate " +
"FROM tblRates WHERE IPName IS NULL AND Active = 'true';";
aSqlQuery cQ1 = new aSqlQuery(sqlText1, "table");
DataTable defaultRates = cQ1.TableResult;
string sqlText2 = "SELECT RateID, IPName, RateName, Rate, DateFrom, DateTo, Active, " +
"(RateName + ': £' + CONVERT(VARCHAR, Rate) + CONVERT(VARCHAR, " +
"(CASE WHEN Active = '1' THEN ' (Active)' ELSE ' (Inactive)' END))) AS ListRate " +
"FROM tblRates WHERE IPName = '" + pIPName + "' " +
"AND Active = 'true';";
aSqlQuery cQ2 = new aSqlQuery(sqlText2, "table");
DataTable clientRates = cQ2.TableResult;
foreach(DataRow defaultRow in defaultRates.Rows)
{
string defaultType = defaultRow["RateName"].ToString();
foreach (DataRow clientRow in clientRates.Rows)
{
string clientType = clientRow["RateName"].ToString();
if (defaultType == clientType)
{
clientRates.Rows.Add(defaultRow.ItemArray);
}
}
}
return clientRates;
}
catch (Exception eX)
{
throw new Exception("cRate: Error compiling Table Of Rates (mode = '" + pIPName + "')" + Environment.NewLine + eX.Message);
}
}
However, whether I use Add Row, Import Row, or Add Item Array I get errors. It doesnt seem to like using datarows from more than one table.
You must have a table that lists clients and jobs - with that in mind you might be doing something like the following
SELECT
CASE R1.RATE WHEN NULL THEN R2.RATE else r1.rate AS RATE END
FROM
CLIENTJOBS C LEFT JOIN RATES R1 ON
R1.CLIENT = C.CLIENT AND R1.WORKTYPE = C.WORKTYPE
JOIN RATES R2 ON
R2.WORKTYPE = C.WORKTYPE AND R2.CLIENT = 'DEFAULT'
bear in mind this is untested guess-code, but hopefully points you in the right direction
If you really need to load up a DataTable:
CREATE TABLE
#MyTempTable (myColumn1 DataType, myColumn2 DataType, myColumn3 DataType)
INSERT INTO
#MyTempTable(myColumn1, myColumn2, myColumn3)
SELECT
f.Bar1, o.Bar2, o.Bar3 FROM FooTable AS f
INNER JOIN
TableFoo o ON f.Bar1 = o.Bar1
With some tweaking this script would create a temporary table that persists as long as your connection is kept alive and contains the data from the other tables that you need.

Categories