Not able to insert long text in database - c#

I have ckeditor in the application in asp.net application through jquery.
It's working fine at local. Its inserting data in database, does not matter
whatever is the length of the text. But when I insert data on live after
putting the build on the server.
It is not saving the data, when I reduce, its length then it is saving the data.I am inserting this text using WCF service.
Please help in this context.
Looking forward to hear regarding the same.

Oracle DB accepts 4000 characters as a max length of an input string (NOT a datatype).
i.e, you are expected to send at most 4000 chars as a value.
The solution:
if you are using ASP.NET, try to use this function after changing your column type to CLOB so that its size would be up to 4GB:
Public Shared Function AssignStringToCLOB(ByVal targetString As String, ByVal myConnection As OracleConnection) As OracleLob
Dim _tempCommand As New OracleCommand()
_tempCommand.Connection = myConnection
_tempCommand.Transaction = _tempCommand.Connection.BeginTransaction()
_tempCommand.CommandText = "DECLARE A " + OracleType.Clob.ToString() + "; " + "BEGIN " + "DBMS_LOB.CREATETEMPORARY(A, FALSE); " + ":LOC := A; " + "END;"
Dim p As OracleParameter = _tempCommand.Parameters.Add("LOC", OracleType.Clob)
p.Direction = ParameterDirection.Output
_tempCommand.ExecuteNonQuery()
Dim _tempCLOB As OracleLob = CType(p.Value, OracleLob)
If targetString <> String.Empty Then
Dim _bytesArray As Byte() = Text.Encoding.Unicode.GetBytes(targetString)
_tempCLOB.BeginBatch(OracleLobOpenMode.ReadWrite)
_tempCLOB.Write(_bytesArray, 0, _bytesArray.Length)
_tempCLOB.EndBatch()
End If
_tempCommand.Transaction.Commit()
Return _tempCLOB
End Function
and call it after opening the connection with Oracle DB to set a value to your parameter, this should work perfectly.

Related

Oledb not reading EXCEL cell which has mixed datatype [duplicate]

I am trying to use the ADO to read in a series of text files into a worksheet. I am running into problems when the majority of the data in a specific column are integers. It will give null values (blank cells) when it reaches a String.
According to microsoft support (Ado mixed data tyes) this is a common thing and the solution is to set the IMEX = 1. I tried this however it didn't work.
I have been searching others threads looking for the answer and came across this answer (other thread) where the author says to change TypeGuessRows to "get the Jet to detect whether a mixed types situation exists and trick the Jet into detecting a certain data type." However, this hasn't worked either.
Below is my VBA code. Any help would be appreciated
Sub query_text_file(WorkingSheet As String, Col As String, Row As Integer, fileName As String, firstOrLast As Integer)
Dim strPath As String
Dim ws As Worksheet
strToolWkbk = fileName
strPath = ThisWorkbook.Path & "\Excel_Barcode_Files"
Set ws = Worksheets(WorkingSheet)
'Need to reference the:
' Microsoft ActiveX Data Objects 2.5 Library
Dim s_rst As ADODB.Recordset
Dim s_cnn As ADODB.Connection 's for sub connection
Dim intRow As Integer
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Set s_cnn = New ADODB.Connection
s_cnn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPath & ";" _
& "Extended Properties=""text;HDR=Yes;IMEX=1;TypeGuessRows=12;FMT=Delimited"";"
s_cnn.Open
Set s_rst = New ADODB.Recordset
strSQL = "SELECT * FROM " & strToolWkbk
s_rst.Open strSQL, _
s_cnn, adOpenStatic, adLockOptimistic, adCmdText
intRow = Row
s_rst.MoveFirst
Do Until s_rst.EOF
ws.Range(Col & intRow) = s_rst(0)
ws.Range(Chr(Asc(Col) + 1) & intRow) = s_rst(1)
intRow = intRow + 1
s_rst.MoveNext
Loop
s_rst.Close
s_cnn.Close
Set s_rst = Nothing
Set s_cnn = Nothing
End Sub
Here is a sample text file. The code reads in everything except the "P"
test test
P,0
1,1
5,2
6,3
Basically, don't rely on the registry entries as explained here on MSDN.
You need to create a Schema.ini file and put it in the same folder as all your text files. In the Schema.ini you specify the type for all columns you may have in your text files - it's just a much safer option to do that explicitly rather than have the driver work out the correct types for columns...
Say you have some txt files on your desktop, open Notepad and copy paste the below - make sure you adjust the [test.txt] part to match the name of your actual txt file and save it as: Schema.ini
[test.txt]
Format=CSVDelimited
Col1=Column1 Text
Col2=Column2 Text
Make sure you add another slash at the end of the parth in the strPath (also indicated in the article)
strPath = ThisWorkbook.Path & "\Excel_Barcode_Files\"
*Keep in mind that I am working in a different location to yours - I am using my Desktop for this example and my text file is named test.txt
Now, that you have a Schema.ini you can modify the connection string and take out some parameters which are not required because they exists in the Schema.ini
So bascially an SSCCE based on the above assumptions would be:
Sub Main()
Cells.ClearContents
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim thePath As String
thePath = "C:\Users\" & Environ("USERNAME") & "\Desktop\"
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & thePath & ";" _
& "Extended Properties=""text;HDR=No;"""
cn.Open
Dim sql As String
sql = "SELECT * FROM test.txt"
' populate the recordset
rs.Open sql, cn, adOpenStatic, adLockOptimistic, &H1
' copy the recordset starting at Range("A1") - assuming there are no headers - see HDR = No;
Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
Now after running this you should see all the values including the missing P:

communication Issue between ASP.net and MySQL

I have the following scenario-
User may enter text in any language in the text box and need to store it in my database along with language name. Following is the code for this on button Update
Dim conStr As String = "Dsn=search;database=search;description=search;option=0;port=0;server=localhost;uid=root;CharacterSet=UTF8;"
Dim s As String = txtLanguage.Text '<----"音読み現代仮名遣い人名用漢字"
mySQL = "INSERT INTO multi_language(language, characters)" & _
" VALUES ('Japanese', '" & s & "')"
con.ConnectionString = conStr
con.Open()
cmd = New OdbcCommand(mySQL, con)
cmd.ExecuteNonQuery()
con.Close()
screen short for running the query
after clicking button the text in the Textbox becomes '??????'
and the data inserted in the data base is like the following
Language | characters
--------------------------
Japanese | ?????
My table structure is
CREATE TABLE multi_language
(
id INTEGER NOT NULL AUTO_INCREMENT,
language VARCHAR(30),
characters TEXT,
PRIMARY KEY(id)
) ENGINE=INNODB CHARACTER SET = utf8;
when i execute the query directly in the query browser then it will executed properly,
whats wrong with my coding? what i need to add to get proper result?
This is the screenshot for the comparison of insert from the
I am also suffering from a similar situation, i solved it in a different way as follows:
while inserting Use your Query as :
Dim s As String = txtLanguage.Text '<----"音読み現代仮名遣い人名用漢字"
mySQL = "INSERT INTO multi_language(language, characters)" & _
" VALUES ('Japanese', '" & encodeUTF(s) & "')"
Encode the string before inserting
Public Function encodeUTF(ByVal inputString As String) As String '<-- function for encoding the input string
Dim byt() As Byte = uni.GetBytes(inputString)
encodeUTF = ""
For Each b As Byte In byt
encodeUTF &= b & ","
Next
Trim(Replace(encodeUTF, ",", ""))
End Function
decode the string before retriving
Public Function decodeUTF(ByVal inputString As String) As String '<-- function for decoding the input string
Dim strs() As String
strs = inputString.Split(",").ToArray
Dim temp(strs.Length) As Byte
Dim i As Integer
For i = 0 To strs.Length - 2
temp(i) = Byte.Parse(strs(i))
Next
decodeUTF = uni.GetString(temp)
decodeUTF = decodeUTF.Substring(0, Len(decodeUTF) - 1)
End Function
While Retrieving this text to a text box you can use your query as :
mySQL = "Select language, characters from multi_language"
Reader = objdb.GetDataReader(mySQL)'<--- is a class function which returns the datareader
If Reader.HasRows = True Then
Reader.Read()
txtlang.Text = objOdbcDataReader.Item("language")'<--- display the selected language
txtchar.Text = objOdbcDataReader.Item("characters ")'<--- display the selected characters
End If
You can try this proposed solution,
If your application want to save data in to database in multiple language, make sure your database stores data in UTF-8 and also the connection to your database is in UTF-8 (commonly people forget this).
Make sure to Execute this query when establishing a connection:
mysql_query("SET NAMES utf8");
In Your application end, where user input data, set the accept-charset attribute on your forms.
<form accept-charset="utf-8">
Set appropriate meta tags for your site:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
or Serve your sites with an appropriate HTTP header:
header('Content-Type: text/html; charset=utf-8');
So overall the problem is, everything is not in UTF-8, If you keep everything in UTF-8, usually don't need to worry about anything.
Refer Strategy for supporting unicode & multi language in PHP5
Storing and displaying unicode string (हिन्दी) using PHP and MySQL
perhaps you should use parametrized query (which anyway is always a better choice than string concatenation, which is susceptible to sql injection)
modify your query to use parameters (I am not sure if for mysql the #param is correct syntax):
"INSERT INTO multi_language(language, characters) VALUES ('Japanese', #val)"
then add parameter to your query:
cmd = New OdbcCommand(mySQL, con)
cmd.Parameters.AddWithValue("#val", txtLanguage.Text)
cmd.ExecuteNonQuery()
con.Close()

Getting the same BLOB in C# that i get with AppendChunk in VB6

I'm trying to get the same BLOB beginning with 0x (like 0x12345679....) in C# that i get in VB6... the problem is that the old VB6 program is still used, and i have to create in C# a program that will transform pdf files in BLOB before inserting them into the database...
I found the VB6 code (or i hope i found it, because i'm extremely new to VB6), that uses AppendChunk method to import (create and import???) the BLOB...
Dim rs, rs2 As Recordset
Dim arrData() As Byte, strFile As String
Const BlockSize = 10240
srcFile = FreeFile
Dim fullname
fullname = IMPORTFOLDER & strFile // This is the path + the file
Open fullname For Binary Access Read As srcFile
FileLength = LOF(srcFile) // Get the total size of the file
NumBlocks = FileLength \ BlockSize // Set number of chunks
LeftOver = FileLength Mod BlockSize // Set number of remaining bytes
ReDim arrData(LeftOver)
Get srcFile, , arrData()
rs.AddNew
myDocID = NextDocID()
rs!DocumentId = myDocID
rs("DocumentData").AppendChunk arrData()
ReDim arrData(BlockSize)
For i = 1 To NumBlocks
Get srcFile, , arrData()
rs("DocumentData").AppendChunk arrData()
Next i
rs.Update
I tried to use the method from here but it doesn't work... I used NHibernate to automatically create the BLOB and insert it into a database, and seemed that the result i was getting was very close tho the one the old program in VB6 does, but again.. it wasn't the same :( Please, tell me, is it possible to get the same BLOB in C# that i'm getting in VB6, and what would be the code in C#? At least an idea.. please..
Thank You in advance.
I found the answer to this question.
The best way is to use SQL parameters when inserting the BLOB into the database.
So first we will need the document to be read as an array of bytes. Next we will show that the parameter to be inserted will be of type "Image" like in the code below:
private void AddDocument(string photoFilePath)
{
//GetFileStream() is a custom function that converts the doc into a stream
byte[] photo = GetFileStream(photoFilePath);
var conn = new SqlConnection(#"ConnectionString here");
var updPhoto = new SqlCommand("UPDATE DT_Document "
+ "SET DocumentData = #Photo WHERE Id=399", conn);
updPhoto.Parameters.Add("#Photo", SqlDbType.Image, photo.Length).Value = photo;
conn.Open();
updPhoto.ExecuteNonQuery();
conn.Close();
}
Someone might use a stored procedure. It doesn't really matter.
Even if in the question in VB6 the file is uploaded by Blocks, here isn't, but in the end we will have the same result.

Write Image to SQL Server using Blob Literal String in C#

I have a c# function that needs to write to a SQL image column. I have the image in a byte array. The standard seems to be the use of SqlCommand while passing the byte array as a parameter of type System.Data.SqlDbType.Image.
Unfotunately, my function can only use text queries (don't ask why) so I have to find a way to use T-SQL commands only. What I have so far can write to the column but I don't know what format of string to make the image blob string.
sql = "DECLARE #ptrval binary(16)" +
"SELECT #ptrval = textptr(Photo) FROM EMPhoto WHERE Employee='" + employeeID + "'" +
"WRITETEXT EMPhoto.Photo #ptrval " + imageByteArrayAsString;
I've tried converting imageByteArray to a Hex string and Binary string but it doesn't seem to end up correct in SQL or in the application that reads it.
A T-SQL Binary constant is an unquoted hexidecimal string prefixed with 0x. ie 0xFFD8FFE0...
string imageByteArrayAsString = "0x" + BitConverter.ToString(image).Replace("-", string.Empty);

writing long text in excel workbook using interop throws error?

I am writing long text (1K to 2K characters long, plain xml data) into a cell in excel workbook.
The below statement throws COM error Exception from HRESULT: 0x800A03EC
range.set_Value(Type.Missing, data);
If I copy paste the same xml manually into excel it just works fine ,but the same does not work progamatically.
If I strip the text to something like 100/300 chars it works fine.
There is a limit (somehwere between 800 and 900 chars if i remember correctly) that is nearly impossible to get around like this.
Try using an ole connection and inserting the data with an SQL command. That might work better for you. you can then use interop to do any formatting if necessary.
the following KB article explains that the max limit is 911 characters. I checked the same on my code it does work for string upto 911 chars.
http://support.microsoft.com/kb/818808
The work around mentioned in this article recommends to make sure no cell holds more than 911 characters. thats lame!
Good Ole and excel article: http://support.microsoft.com/kb/316934
The following code updates a private variable that is the number of successful rows and returns a string which is the path to the excel file.
Remember to use Path from System.IO;!
string tempXlsFilePathName;
string result = new string;
string sheetName;
string queryString;
int successCounter;
// set sheetName and queryString
sheetName = "sheetName";
queryString = "CREATE TABLE " + sheetName + "([columnTitle] char(255))";
// Write .xls
successCounter = 0;
tempXlsFilePathName = (_tempXlsFilePath + #"\literalFilename.xls");
using (OleDbConnection connection = new OleDbConnection(GetConnectionString(tempXlsFilePathName)))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
command.ExecuteNonQuery();
yourCollection.ForEach(dataItem=>
{
string SQL = "INSERT INTO [" + sheetName + "$] VALUES ('" + dataItem.ToString() + "')";
OleDbCommand updateCommand = new OleDbCommand(SQL, connection);
updateCommand.ExecuteNonQuery();
successCounter++;
}
);
// update result with successfully written username filepath
result = tempXlsFilePathName;
}
_successfulRowsCount = successCounter;
return result;
N.B. This was edited in a hurry, so may contain some mistakes.
To solve this limitation, only writing/updating one cell at a time and dispose the Excel com object immediately. And recreate the object again for writing/updating the next cell.
I can confirm this solution is working in VS2010 (VB.NET project) with Microsoft Excel 10.0 Object Library (Microsoft Office XP)
This limitation is supposed to have been removed in Excel 2007/2010. Using VBA the following works
Sub longstr()
Dim str1 As String
Dim str2 As String
Dim j As Long
For j = 1 To 2000
str1 = str1 & "a"
Next j
Range("a1:a5").Value2 = str1
str2 = Range("a5").Value2
MsgBox Len(str2)
End Sub
I'll start by saying I haven't tried this myself, but my research says that you can use QueryTables to overcome the 911 character limitation.
This is the primary post I found which talks about using a record set as the data source for a QueryTable and adding it to a spreadsheet: http://www.excelforum.com/showthread.php?t=556493&p=1695670&viewfull=1#post1695670.
Here is some sample C# code of using QueryTables: import txt files using excel interop in C# (QueryTables.Add).

Categories

Resources