I need to insert text diagonal Watermark, in a word file with OpenXML, I use the following steps to open the file:
Dim wordmlNamespace As String = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
Using wdDoc As WordprocessingDocument = WordprocessingDocument.Open(newPath, True)
'AddWatermarkFunction()
wdDoc.MainDocumentPart.Document.Save()
wdDoc.Close()
End Using
I have already seen this link, but I can not play the correct functioning.
UPDATE
I tried to write the following code (replaces 'AddWatermarkFunction() of the above code), but I do not print the watermark
If wdDoc.MainDocumentPart.HeaderParts IsNot Nothing Then
If wdDoc.MainDocumentPart.HeaderParts IsNot Nothing Then
For Each Headerpart In wdDoc.MainDocumentPart.HeaderParts
Dim r As DocumentFormat.OpenXml.Wordprocessing.Run = CreateWatermarkRun("watermarkText")
Dim para As New DocumentFormat.OpenXml.Wordprocessing.Paragraph
para.Append(r)
Headerpart.Header.Save(Headerpart)
Next
End If
End If
the function "CreateWatermarkRun":
Private Function CreateWatermarkRun(ByVal name As String) As DocumentFormat.OpenXml.Wordprocessing.Run
Dim runWatermark As New DocumentFormat.OpenXml.Wordprocessing.Run()
Dim runWMProperties As New DocumentFormat.OpenXml.Wordprocessing.RunProperties()
Dim noProofWM As New DocumentFormat.OpenXml.Wordprocessing.NoProof()
Try
runWMProperties.Append(noProofWM)
Dim pictureWM As New DocumentFormat.OpenXml.Wordprocessing.Picture()
Dim shapetypeWM As New DocumentFormat.OpenXml.Vml.Shapetype() With
{ _
.Id = "_x0000_t136", _
.CoordinateSize = "21600,21600", _
.OptionalNumber = 136, _
.Adjustment = "10800", _
.EdgePath = "m#7,l#8,m#5,21600l#6,21600e" _
}
Dim formulasWM As New DocumentFormat.OpenXml.Vml.Formulas()
Dim formula1 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "sum #0 0 10800" _
}
Dim formula2 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "prod #0 2 1" _
}
Dim formula3 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "sum 21600 0 #1" _
}
Dim formula4 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "sum 0 0 #2" _
}
Dim formula5 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "sum 21600 0 #3" _
}
Dim formula6 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "if #0 #3 0" _
}
Dim formula7 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "if #0 21600 #1" _
}
Dim formula8 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "if #0 0 #2" _
}
Dim formula9 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "if #0 #4 21600" _
}
Dim formula10 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "mid #5 #6" _
}
Dim formula11 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "mid #8 #5" _
}
Dim formula12 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "mid #7 #8" _
}
Dim formula13 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "mid #6 #7" _
}
Dim formula14 As New DocumentFormat.OpenXml.Vml.Formula() With { _
.Equation = "sum #6 0 #5" _
}
formulasWM.Append(formula1)
formulasWM.Append(formula2)
formulasWM.Append(formula3)
formulasWM.Append(formula4)
formulasWM.Append(formula5)
formulasWM.Append(formula6)
formulasWM.Append(formula7)
formulasWM.Append(formula8)
formulasWM.Append(formula9)
formulasWM.Append(formula10)
formulasWM.Append(formula11)
formulasWM.Append(formula12)
formulasWM.Append(formula13)
formulasWM.Append(formula14)
Dim pathWM As New DocumentFormat.OpenXml.Vml.Path() With { _
.AllowTextPath = True, _
.ConnectionPointType = DocumentFormat.OpenXml.Vml.Office.ConnectValues.[Custom], _
.ConnectionPoints = "#9,0;#10,10800;#11,21600;#12,10800", _
.ConnectAngles = "270,180,90,0" _
}
Dim textPathWM As New DocumentFormat.OpenXml.Vml.TextPath() With { _
.[On] = True, _
.FitShape = True _
}
Dim shapeHandlesWM As New DocumentFormat.OpenXml.Vml.ShapeHandles()
Dim shapeHandleWM As New DocumentFormat.OpenXml.Vml.ShapeHandle() With { _
.Position = "#0,bottomRight", _
.XRange = "6629,14971" _
}
shapeHandlesWM.Append(shapeHandleWM)
Dim lockWM As New DocumentFormat.OpenXml.Vml.Office.Lock() With { _
.Extension = DocumentFormat.OpenXml.Vml.ExtensionHandlingBehaviorValues.Edit, _
.TextLock = True, _
.ShapeType = True _
}
shapetypeWM.Append(formulasWM)
shapetypeWM.Append(pathWM)
shapetypeWM.Append(textPathWM)
shapetypeWM.Append(shapeHandlesWM)
shapetypeWM.Append(lockWM)
Dim shapeWM As New DocumentFormat.OpenXml.Vml.Shape() With { _
.Id = "PowerPlusWaterMarkObject346762751", _
.Style = "position:absolute;margin-left:0;margin-top:0;width:527.85pt;height:131.95pt;rotation:315;z-index:-251655168;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin", _
.OptionalString = "_x0000_s2050", _
.AllowInCell = False, _
.FillColor = "silver", _
.Stroked = False, _
.Type = "#_x0000_t136" _
}
Dim fillWM As New DocumentFormat.OpenXml.Vml.Fill() With { _
.Opacity = ".5" _
}
Dim textPath2WM As New DocumentFormat.OpenXml.Vml.TextPath() With { _
.Style = "font-family:""Arial"";font-size:1pt", _
.[String] = name _
}
shapeWM.Append(fillWM)
shapeWM.Append(textPath2WM)
pictureWM.Append(shapetypeWM)
pictureWM.Append(shapeWM)
runWatermark.Append(runWMProperties)
runWatermark.Append(pictureWM)
Return runWatermark
Catch ex As Exception
ex.Message.ToString()
End Try
End Function
Any suggestions?
I found the solution, missing only the portion of the code that added a paragraph to the document that is
....
Dim para As New DocumentFormat.OpenXml.Wordprocessing.Paragraph
DocumentFormat.OpenXml.Wordprocessing.Paragraph)()
para.Append(r)
Headerpart.Header.Append(para) 'missing code
Headerpart.Header.Save(Headerpart)
Related
I need to know how to send a stamped pdf to receiptants for digital signing. The pdf is stamped using itextsharp
do I need an envelope id for the api? How do I attach the stamped pdf for sending using docusign?
Function
Private pdfFormFileName As String = "myAcrobatFormFile.pdf"
Sub Print_Click(ByVal sender As Object, ByVal e As CommandEventArgs)
Dim sUniqueKey As String
Dim dr As OdbcDataReader
Dim sql As String
Dim reader As PdfReader
Dim sFileName As String = ""
Dim sArray As Array
sUniqueKey = e.CommandArgument
sArray = sUniqueKey.Split(",")
sql = "select "
sql += "name,"
sql += "id"
sql += " from table"
sql += " where key1=" & sArray(0)
sql += " and key2=" & sArray(1)
oFnc.OpenODBC()
selectCommand = New OdbcCommand(sql, oFnc.connWeb)
dr = selectCommand.ExecuteReader
If dr.Read Then
reader = New PdfReader(server.mappath(pdfFormFileName))
sFileName = "data/" & oFnc.GetTimeStamp & "displayForm.pdf"
Dim stamper As PdfStamper = New PdfStamper(reader, New System.IO.FileStream(Server.MapPath(sFileName), FileMode.Create))
Dim fields As AcroFields
fields = stamper.AcroFields
With fields
.SetField("txtName", Left(dr("name"), 20))
.SetField("txtId", dr("id")
End With
stamper.FormFlattening = True
stamper.Close()
End If
dr.Close()
oFnc.CloseODBC()
End Sub
How to send this xml
<?xml version="1.0" encoding="UTF-8"?>
<envelopeDefinition
xmlns="http://www.docusign.com/restapi"xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<emailBlurb>Annual contract</emailBlurb>
<emailSubject>API Call for adding signature request to document and
sending</emailSubject>
<status>sent</status>
<documents>
<document>
<documentId>1</documentId>
<name>myAcrobatFormFile.pdf</name>
</document>
</documents>
<recipients>
<signers>
<signer>
<recipientId>2</recipientId>
<email>abc#gmail.com</email>
<name>Bob Smith</name>
</signer>
</signers>
</recipients>
</envelopeDefinition>
The DocuSign API Walkthroughs that you have found are great examples of how to do this, and the API Explorer is another great tool that shows you how the REST calls are made. Both of these can be found on the API Tools page in the Developer Center:
https://www.docusign.com/developer-center/quick-start/api-explorer
The API Explorer allows you to make any API call without writing any code. You just enter your credentials at the top of the page, select which call you want to make, fill out parameters (if needed), and hit the TRY IT button.
Unfortunately the API Walkthroughs do not have Visual Basic examples. However there are C# examples (another .NET technology), more particularly this example for requesting a signature on a local file:
http://iodocs.docusign.com/APIWalkthrough/requestSignatureFromDocument
Sub login_click(ByVal sender As Object, ByVal e As System.EventArgs)
'Dim oClient = New WebClient
Dim sUrl As String = "https://demo.docusign.net/restapi/v1/login_information?api_password=true&include_account_id_guid=true&login_settings=all"
Dim sEmail As String = "abc#gmail.com"
Dim sPassword As String = "mypassword"
Dim sIntegratorKey As String = "myintegratorkey"
Dim sDocumentName As String = "mypdfdocument.pdf"
Dim sContentType As String = "application/pdf"
Dim oRequest As HttpWebRequest
oRequest = initializeRequest(sUrl, "GET", "", sEmail, sPassword, sIntegratorKey)
Dim oResponse As HttpWebResponse = oRequest.GetResponse
Dim baseURL As String = ""
Dim oStreamReader As StreamReader = New StreamReader(oResponse.GetResponseStream)
Dim sXML As String = oStreamReader.ReadToEnd
baseURL = parseDataFromResponse(sXML, "baseUrl")
Dim sXmlBody As String
sXmlBody = "<envelopeDefinition xmlns='http://www.docusign.com/restapi'>" & _
"<emailSubject>DocuSign API</emailSubject>" & _
"<status>sent</status>" & _
"<documents>" & _
"<document>" & _
"<documentId>1</documentId>" & _
"<name>" & sDocumentName & "</name>" & _
"</document>" & _
"</documents>" & _
"<recipients>" & _
"<signers>" & _
"<signer>" & _
"<recipientId>1</recipientId>" & _
"<email>jsmith#abc.com</email>" & _
"<name>John Smith</name>" & _
"<tabs>" & _
"<signHereTabs>" & _
"<signHere>" & _
"<xPosition>100</xPosition>" & _
"<yPosition>100</yPosition>" & _
"<documentId>1</documentId>" & _
"<pageNumber>1</pageNumber>" & _
"</signHere>" & _
"</signHereTabs>" & _
"</tabs>" & _
"</signer>" & _
"</signers>" & _
"</recipients>" & _
"</envelopeDefinition>"
sUrl = baseURL & "/envelopes"
oRequest = initializeRequest(sUrl, "POST", "", sEmail, sPassword, sIntegratorKey)
configureMultiPartFormDataRequest(oRequest, sXmlBody, sDocumentName, sContentType)
Dim sMessage As String
sMessage = getResponseBody(oRequest)
MsgBox(sMessage)
'Dim sUri As String = parseDataFromResponse(sXML, "uri")
End Sub
Function getResponseBody(ByRef oRequest As HttpWebRequest) As String
Dim oResponse As HttpWebResponse = oRequest.GetResponse
Dim oStreamReader As StreamReader = New StreamReader(oResponse.GetResponseStream)
Dim sResponseString As String = oStreamReader.ReadToEnd
Return (sResponseString)
End Function
Sub configureMultiPartFormDataRequest(ByRef oRequest As HttpWebRequest, sXmlBody As String, sDocumentName As String, sContentType As String)
oRequest.ContentType = "multipart/form-data; boundary=BOUNDARY"
Dim sRequestBodyStart As String = "\r\n\r\n--BOUNDARY\r\n" & _
"Content-Type: application/xml\r\n" & _
"Content-Disposition: form-data\r\n" & _
"\r\n" & _
sXmlBody & "\r\n\r\n--BOUNDARY\r\n" & _
"Content-Type: " & sContentType & "\r\n" & _
"Content-Disposition: file; filename='" & sDocumentName & "'; documentId=1\r\n" & _
"\r\n"
Dim sRequestBodyEnd As String = "\r\n--BOUNDARY--\r\n\r\n"
Dim oFileStream As FileStream = File.OpenRead(Server.MapPath(sDocumentName))
Dim bodyStart As Byte() = System.Text.Encoding.UTF8.GetBytes(sRequestBodyStart.ToString)
Dim bodyEnd As Byte() = System.Text.Encoding.UTF8.GetBytes(sRequestBodyEnd.ToString)
Dim oDataStream As Stream = oRequest.GetRequestStream
oDataStream.Write(bodyStart, 0, sRequestBodyStart.ToString.Length())
Dim buffer(4096) As Byte
Dim iLen As Integer = 0
iLen = oFileStream.Read(buffer, 0, 4096)
Do While iLen > 0
oDataStream.Write(buffer, 0, iLen)
iLen = oFileStream.Read(buffer, 0, 4096)
Loop
oDataStream.Write(bodyEnd, 0, sRequestBodyEnd.ToString.Length())
oDataStream.Close()
End Sub
Function initializeRequest(sUrl As String, sMethod As String, sBody As String, sEmail As String, sPassword As String, sIntegratorKey As String) As HttpWebRequest
Dim oRequest As HttpWebRequest
oRequest = WebRequest.Create(sUrl)
oRequest.KeepAlive = False
oRequest.Method = sMethod
AddRequestHeaders(oRequest, sEmail, sPassword, sIntegratorKey)
If sBody <> "" Then
AddRequestBody(oRequest, sBody)
End If
Return (oRequest)
End Function
Sub AddRequestHeaders(ByRef oRequest As HttpWebRequest, sEmail As String, sPassword As String, sIntegratorKey As String)
oRequest.Headers.Add("X-DocuSign-Authentication",
String.Format("<DocuSignCredentials><Username>{0}</Username><Password>{1}</Password><IntegratorKey>{2}</IntegratorKey></DocuSignCredentials>", sEmail, sPassword, sIntegratorKey))
oRequest.Accept = "application/xml"
oRequest.ContentType = "application/xml"
End Sub
Sub addRequestBody(ByRef oRequest As HttpWebRequest, sRequestBody As String)
Dim body As Byte() = System.Text.Encoding.UTF8.GetBytes(sRequestBody)
Dim oDataStream As Stream = oRequest.GetRequestStream
oDataStream.Write(body, 0, sRequestBody.Length)
oDataStream.Close()
End Sub
Function parseDataFromResponse(sXML As String, sSearchToken As String) As String
Dim oXmlReader As XmlReader = XmlReader.Create(New StringReader(sXML))
Do While oXmlReader.Read()
If oXmlReader.NodeType = XmlNodeType.Element And oXmlReader.Name = sSearchToken Then
Return oXmlReader.ReadString()
End If
Loop
Return ""
End Function
When I execute this subroutine it throws an error,
"The value of a property that is part of an object's key does not match the corresponding property value stored in the ObjectContext. This can occur if properties that are part of the key return inncosistent or incorrect values or if DetectChanges is not called after changes are made to a property that is part of the key."
Here is the code and below it I've explained briefly what the code does.
Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim semester As String = ddlwhSemester.SelectedValue
Dim year As String = txtwhYear.Text
Dim exists As String = "N"
Dim pcsemester As String = ddlSemester.SelectedItem.Text
Dim pcyear As String = ddlYear.SelectedItem.Text
Using dbContext As pbu_housingEntities = New pbu_housingEntities
' Get the list of residents in webHousing.
Dim qresidents = (From p In dbContext.Residents _
Where p.semester = semester _
Where p.year = year _
Select p.people_code_id)
Using dbContext2 As Campus6Entities = New Campus6Entities
' Get the list of students in PowerCampus.
Dim qstudents = (From p In dbContext2.RESIDENCies _
Where p.ACADEMIC_TERM = pcsemester _
Where p.ACADEMIC_YEAR = pcyear _
Select p)
For Each row In qstudents
exists = "N"
For Each res In qresidents
If row.ToString = res.ToString Then
exists = "Y"
End If
Next
If exists = "Y" Then
' Skip adding.
Else
' Add a row.
' Get the ID
Dim ID As String = row.PEOPLE_ID
' Get info from PowerCampus
Dim qstudent = (From p In dbContext2.PEOPLE _
Where p.PEOPLE_ID = ID _
Order By p.CREATE_DATE Descending _
Select p).FirstOrDefault
Dim qpeople = (From p In dbContext2.PEOPLE _
Where p.PEOPLE_ID = ID _
Order By p.CREATE_DATE Descending _
Select p).FirstOrDefault
Dim people_code_id As String = qpeople.PEOPLE_CODE_ID
Dim qacademic = (From p In dbContext2.ACADEMICs _
Where p.PEOPLE_CODE_ID = people_code_id _
Where p.ACADEMIC_TERM = pcsemester _
Where p.ACADEMIC_YEAR = pcyear _
Order By p.CREATE_DATE Descending _
Select p).FirstOrDefault
Dim qaddress = (From p In dbContext2.ADDRESSes _
Where p.PEOPLE_ORG_CODE_ID = people_code_id _
Where p.ADDRESS_TYPE = "Perm" _
Order By p.CREATE_DATE Descending _
Select p).FirstOrDefault
Dim qdemographics = (From p In dbContext2.DEMOGRAPHICS _
Where p.PEOPLE_CODE_ID = people_code_id _
Order By p.CREATE_DATE Descending _
Select p).FirstOrDefault
' Create the new occupant.
Dim newres As New Resident
newres.people_code_id = ID
newres.person_name = qpeople.FIRST_NAME + " " + qpeople.MIDDLE_NAME + " " + qpeople.LAST_NAME
newres.first_name = qpeople.FIRST_NAME
newres.last_name = qpeople.LAST_NAME
newres.class_level = qacademic.CLASS_LEVEL
newres.gender = qdemographics.GENDER
newres.semester = semester
newres.year = year
newres.email = qaddress.EMAIL_ADDRESS
dbContext.Residents.AddObject(newres)
dbContext.SaveChanges()
End If
Next
End Using
End Using
End Sub
The above code is used to pull records from a SIS (essentially a higher ed CRM) into my webHousing application (for on-campus residents). It gets a list of everyone who is a student for the select semester/year and then inputs them into the webHousing database if they don't already exist for that semester/year.
Looks like your qresidents is an enumeration of integers, while your qstudents is an enumeration of objects of type residents. So this line
If row.ToString = res.ToString Then
exists = "Y"
End If
Can't compare the the to types. Your second query should be something like:
Dim qstudents = (From p In dbContext2.RESIDENCies _
Where p.ACADEMIC_TERM = pcsemester _
Where p.ACADEMIC_YEAR = pcyear _
Select p.people_code_id)
While running the code I've included below I receive the error
"EntityCommandExecutionException was unhandled by user code.
I'm then told to look at the inner exception for details...and there I see under Data:
"In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user."
And under Inner Exception --> Message:
"A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The handle is invalid.)"
The code Visual Studio thinks is at fault is:
Dim qpeople = (From p In dbContext2.PEOPLE _
Where p.PEOPLE_ID = ID _
Order By p.CREATE_DATE Descending _
Select p).FirstOrDefault
The larger code context is:
Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim semester As String = ddlwhSemester.SelectedValue
Dim year As String = txtwhYear.Text
Dim exists As String = "N"
Dim pcsemester As String = ddlSemester.SelectedItem.Text
Dim pcyear As String = ddlYear.SelectedItem.Text
Using dbContext As pbu_housingEntities = New pbu_housingEntities
' Get the list of residents in webHousing.
Dim qresidents = (From p In dbContext.Residents _
Where p.semester = semester _
Where p.year = year _
Select p.people_code_id)
Using dbContext2 As Campus6Entities = New Campus6Entities
' Get the list of students in PowerCampus.
Dim qstudents = (From p In dbContext2.RESIDENCies _
Join a In dbContext2.ACADEMICs _
On a.PEOPLE_CODE_ID Equals p.PEOPLE_CODE_ID _
Where p.ACADEMIC_TERM = pcsemester _
Where p.ACADEMIC_YEAR = pcyear _
Where a.ACADEMIC_TERM = pcsemester _
Where a.ACADEMIC_YEAR = pcyear _
Where a.PROGRAM = "UND" _
Where (a.CLASS_LEVEL = "FR" _
Or a.CLASS_LEVEL = "FRNR" _
Or a.CLASS_LEVEL = "FRST" _
Or a.CLASS_LEVEL = "SO" _
Or a.CLASS_LEVEL = "JR" _
Or a.CLASS_LEVEL = "SR" _
Or a.CLASS_LEVEL = "SR5" _
Or a.CLASS_LEVEL = "Tran") _
Select p.PEOPLE_ID).Distinct
For Each row In qstudents
exists = "N"
For Each res In qresidents
If row.ToString = res.ToString Then
exists = "Y"
End If
Next
If exists = "Y" Then
' Skip adding.
Else
' Add a row.
' Get the ID
Dim ID As String = row
' Get info from PowerCampus
Dim qpeople = (From p In dbContext2.PEOPLE _
Where p.PEOPLE_ID = ID _
Order By p.CREATE_DATE Descending _
Select p).FirstOrDefault
Dim people_code_id As String = qpeople.PEOPLE_CODE_ID
Dim qacademic = (From p In dbContext2.ACADEMICs _
Where p.PEOPLE_CODE_ID = people_code_id _
Where p.ACADEMIC_TERM = pcsemester _
Where p.ACADEMIC_YEAR = pcyear _
Order By p.CREATE_DATE Descending _
Select p.CLASS_LEVEL).FirstOrDefault
Dim qaddress = (From p In dbContext2.ADDRESSes _
Where p.PEOPLE_ORG_CODE_ID = people_code_id _
Where p.ADDRESS_TYPE = "Perm" _
Order By p.CREATE_DATE Descending _
Select p).FirstOrDefault
Dim qdemographics = (From p In dbContext2.DEMOGRAPHICS _
Where p.PEOPLE_CODE_ID = people_code_id _
Order By p.CREATE_DATE Descending _
Select p.GENDER).FirstOrDefault
' Create the new occupant.
Dim newres As New Resident
newres.people_code_id = ID
newres.person_name = qpeople.FIRST_NAME + " " + qpeople.MIDDLE_NAME + " " + qpeople.LAST_NAME
newres.first_name = qpeople.FIRST_NAME
newres.last_name = qpeople.LAST_NAME
newres.class_level = qacademic
newres.gender = qdemographics
newres.semester = semester
newres.year = year
newres.email = qaddress.EMAIL_ADDRESS
newres.create_date = Date.Now
dbContext.Residents.AddObject(newres)
dbContext.SaveChanges()
End If
Next
End Using
End Using
End Sub
Check your db and make sure the primary key is there. I had a similar issue and found that the primary key was not defined. Just a thought, might not be the problem but worth a quick check.
I didn't notice this before but you are setting your ID like this:
Dim ID As String = row
Try converting the ID to a Int before the linq query.
This is a sample of my code. I am using Microsoft Visual Studio 2010, with asp.net version 2.0, when the user clicks the import button, the csv file will be saved in the database. My code contains errors, and I do not know how to solve them, please help!
protected void btnImport_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection (#"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
StreamReader Sr = new StreamReader("filepath");
string line;
while ((line = Sr.ReadLine()) != null)
{
line = Sr.ReadLine();
}
const string SQL = "INSERT INTO [Guest] ([GuestName], [IC_Number], [EventName], [GuestID]) VALUES (#GuestName, #IC_Number, #EventName, #GuestID)";
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue("#GuestName", Sr);
cmd.Parameters.AddWithValue("#IC_Number", Sr);
cmd.Parameters.AddWithValue("#EventName", Sr);
cmd.Parameters.AddWithValue("#GuestID", Sr);
con.Open();
cmd.ExecuteNonQuery();// 1,0 will determine whether line is inserted, upload has error...
con.Close();
}
Your insert query must be in your while
Sr is not your parameter, but line which contains an array of your data. So it is probably line[i] that you must give to AddWithValue
You are assigning line = Sr.ReadLine() twice in your code, just do it in the while
So try something like this:
protected void btnImport_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection (#"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
con.Open();
StreamReader Sr = new StreamReader("filepath");
string line;
string SQL = "INSERT INTO [Guest] ([GuestName], [IC_Number], [EventName], [GuestID]) VALUES (#GuestName, #IC_Number, #EventName, #GuestID)";
while ((line = Sr.ReadLine()) != null)
{
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue("#GuestName", line[0]);
cmd.Parameters.AddWithValue("#IC_Number", line[1]);
cmd.Parameters.AddWithValue("#EventName", line[2]);
cmd.Parameters.AddWithValue("#GuestID", line[3]);
cmd.ExecuteNonQuery();// 1,0 will determine whether line is inserted, upload has error...
}
con.Close();
}
i have done something like this however it was xls files i needed to import but not much differentce really, here is the code i used
Protected Sub ButtonImport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonImport.Click
PanelView.Visible = False
PanelUpload.Visible = False
PanelImport.Visible = True
LabelImport.Text = "" 'reset to blank
Dim xConnstr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & (Server.MapPath("SiteTemplate.xls")) & ";" & _
"Extended Properties=Excel 8.0"
' create your excel connection object using the connection string
Dim objXConn As New System.Data.OleDb.OleDbConnection(xConnstr)
objXConn.Open()
Dim objCommand As New OleDbCommand("SELECT * FROM [importsites$]", objXConn)
'Creating the data reader
Dim reader As OleDbDataReader
reader = objCommand.ExecuteReader()
Dim counter As Integer = 0
While reader.Read()
counter = counter + 1
Dim siteID As Integer = 0
Dim siteIWSref As String = Convert.ToString(reader("siteIWSref"))
If siteIWSref = "" Then
siteIWSref = "."
End If
Dim siteUPRN As String = Convert.ToString(reader("siteUPRN"))
If siteUPRN = "" Then
siteUPRN = "."
End If
Dim siteName As String = Convert.ToString(reader("siteName"))
Dim siteAdd1 As String = Convert.ToString(reader("siteAdd1"))
Dim siteAdd2 As String = Convert.ToString(reader("siteAdd2"))
Dim siteAdd3 As String = Convert.ToString(reader("siteAdd3"))
Dim sitePcode As String = Convert.ToString(reader("sitePcode"))
Dim siteContact As String = Convert.ToString(reader("siteContact"))
Dim siteContactPos As String = Convert.ToString(reader("siteContactPos"))
Dim siteContactTel As String = Convert.ToString(reader("siteContactTel"))
Dim siteDesc As String = Convert.ToString(reader("siteDesc"))
Dim siteCompany As Integer = CInt(CompanyDD.SelectedValue)
Dim siteOccupants As String = Convert.ToString(reader("siteOccupants"))
Dim siteType As String = Convert.ToString(reader("siteType"))
siteID = ImportIntotblSite(siteIWSref, siteUPRN, siteName, siteAdd1, siteAdd2, siteAdd3, sitePcode, siteContact, siteContactPos, siteContactTel, siteDesc, siteCompany, siteOccupants, siteType)
LabelImport.Text &= siteID & siteIWSref & " " & siteUPRN & " " & siteName & " " & siteAdd1 & " " & siteAdd2 & " " & siteAdd3 & " " & " " & sitePcode & " " & siteContact & " " & siteContactPos & " " & siteContactTel & " " & siteDesc & " " & siteCompany & " " & siteOccupants & " " & " " & siteType & "<br>"
End While
reader.Close()
objCommand.Dispose()
objXConn.Close()
btnBack.Enabled = True
btnBack.Visible = True
btnSave.Visible = True
btnSave.Enabled = True
End Sub
Protected Function ImportIntotblSite(ByVal siteIWSref As String, ByVal siteUPRN As String, ByVal siteName As String, ByVal siteAdd1 As String, ByVal siteAdd2 As String, ByVal siteAdd3 As String, ByVal sitePcode As String, ByVal siteContact As String, ByVal siteContactPos As String, ByVal siteContactTel As String, ByVal siteDesc As String, ByVal siteCompany As Integer, ByVal siteOccupants As String, ByVal siteType As String) As Integer
siteIWSref = Left(siteIWSref, 20)
siteUPRN = Left(siteUPRN, 20)
siteName = Left(siteName, 60)
siteAdd1 = Left(siteAdd1, 50)
siteAdd2 = Left(siteAdd2, 50)
siteAdd3 = Left(siteAdd3, 50)
sitePcode = Left(sitePcode, 10)
siteContact = Left(siteContact, 35)
siteContactPos = Left(siteContactPos, 35)
siteContactTel = Left(siteContactTel, 20)
siteDesc = Left(siteDesc, 220)
siteOccupants = Left(siteOccupants, 120)
siteType = Left(siteType, 35)
Dim siteID As Integer = 0
Try
Dim SSAdapter As New importSitesDataSetTableAdapters.tblSiteTableAdapter
Dim SSDataTable As importSitesDataSet.tblSiteDataTable = Nothing
SSDataTable = SSAdapter.GetDataByNumbers(siteIWSref, siteName, siteCompany)
If siteName = "" Then
siteName = ""
End If
'see if the category already exists in the table, if not insert it
If Not SSDataTable Is Nothing Then
If siteName = "" Then
LabelImport.Text = LabelImport.Text & _
"<font color=red>ERROR: BLANK SITE NAME: ROW NOT IMPORTED : " & _
"ID: " & siteID & _
" Name: " & siteName & " " & siteCompany & ".</font><br>"
ElseIf SSDataTable.Rows.Count > 0 Then
If Not SSDataTable(0).siteID = Nothing Then
siteID = SSDataTable(0).siteID
LabelImport.Text = LabelImport.Text & _
"<font color=blue> Recorded already exists : " & _
"ID: " & siteID & _
"Name: " & siteName & " " & siteCompany & ".</font><br>"
End If
End If
End If
If siteID = 0 And siteName <> "" Then
siteID = Convert.ToInt32(SSAdapter.InsertQuery(siteIWSref, siteUPRN, siteName, siteAdd1, siteAdd2, siteAdd3, sitePcode, siteContact, siteContactPos, siteContactTel, siteDesc, siteCompany, siteOccupants, siteType))
LabelImport.Text = LabelImport.Text & _
"<font color=green> ROW SUCCESSFULLY IMPORTED: " & _
" ID: " & siteID & _
" Name: " & siteName & " " & siteCompany & ".</font><br>"
End If
Return siteID
'SSAdapter.Dispose()
Catch ex As Exception
LabelImport.Text = LabelImport.Text & "<font color=red>" & ex.ToString & ".</font><br>"
Return 0
End Try
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'TableButtons.Visible = False
'FileUploadExcel.Visible = False
'PanelUpload.Visible = False
btnYes.Visible = False
btnNo.Visible = False
btnBack.Enabled = False
btnBack.Visible = False
ButtonView.Enabled = False
ButtonImport.Enabled = False
btnSave.Visible = False
btnSave.Enabled = False
End Sub
try this and let me know how you get on.
there is a brilliant example of how to upload information onto an sql server at:
http://www.shiningstar.net/aspnet_articles/DataSet/DataSetProject.aspx
i am aware its for excel however surely there cant be that much difference.
Dim obj As New List(Of ClassOne)() From { _
New ClassOne() With { _
Key .IDX = 1206, _
Key .NAME = "Krishna Reddy", _
Key .MOBLIENUMBER = 9494494704L _
}, _
New ClassOne() With { _
Key .IDX = 1242, _
Key .NAME = "Swarupa", _
Key .MOBLIENUMBER = 9441524535L _
}, _
New ClassOne() With { _
Key .IDX = 1236, _
Key .NAME = "Naga Raj", _
Key .MOBLIENUMBER = 9866939656L _
}, _
New ClassOne() With { _
Key .IDX = 1219, _
Key .NAME = "Devika", _
Key .MOBLIENUMBER = 9885735365L _
} _
}
test.DataSource = obj //here "test" is dropdownlist id
test.DataTextField = "NAME"
test.DataValueField = "IDX"
test.DataBind()
Collection initializers are new to VS 2010
http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx