Here i'll give a tip on working with VS.NET database designer and getting MSSQL inserted row's primary key.
First, create Dataset and goto Database Designer and add table adapter using TableAdapter Configuration wizard. Before you click finish, make sure checked the checkbox "Create methods send updates directly to the database". So you'll get generated Select, Insert, Update, Delete methods automatically. I always delete all columns after WHERE clause in automatically generated "update" and "delete" queries except primary key column. It's practically good for me.
And then add new parameter the same name with primary key in InsertCommand of table adapter and set its Direction property to ReturnValue, SourceColumn property to primary key name.
Now, It's by default that generated (for example) tempTableAdapter1.Insert(val1, val2, val3); will return 1 if successful. Means affected row count.
After that, go to source code of Dataset (such as Dataset1.Designer.cs) and find
public virtual int Insert( ... ); function. At the end of the function body, you'll see the code like following
try {
int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery();
return returnValue;
}
finally {
if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) {
this.Adapter.InsertCommand.Connection.Close();
}
}
and then change InsertCommand.ExecuteNonQuery() to Convert.ToInt32(InsertCommand.ExecuteScalar()).
ExecuteScalar will return first column value (object type need to be converted mostly), ExecuteNonQuery will return affected rows count.
At last, try tempTableAdapter1.Insert(val1, val2, val3) and print the result.
Tuesday, May 5, 2009
Nice tip
Monday, December 29, 2008
How to insert large file into MSSQL field
I was to get rid of a agreement storing application. I'd needed to save Agreement file as attachment to agreement storing table. So i added a field c_file, type of Varbinary.
And when executed it this error was occurred.
System.Data.SqlClient.SQLException: String or binary date would be truncated.
The statement has been terminated.
I knew that this caused of 8K maximum size of Varbinary type. Then i changed the type to Image, it was OK. Following piece of code, i used.
private void simpleButton1_Click(object sender, EventArgs e)
{
CdsTraining.contractDataTable dtContract = new CdsTraining.contractDataTable();
CdsTrainingTableAdapters.contractTableAdapter taContract = new training.CdsTrainingTableAdapters.contractTableAdapter();
byte[] contract= ReadFully(btnedtAttachment.Text, 0);
try
{
taContract.Insert(Convert.ToInt32(cbbEmployee.EditValue), Convert.ToInt32(cbbTraining.EditValue), dateStart.DateTime, dateEnd.DateTime, txtContractNum.Text, mmDescr.Text, contract, btnedtAttachment.Text);
MessageBox.Show("Saved");
}
catch (Exception ex)
{
MessageBox.Show("Error: "+ ex.ToString());
}
//MessageBox.Show(Convert.ToString(cbbEmployee.EditValue));
}
public static byte[] ReadFully(string fileName, int initialLength)
{
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < 1)
{
initialLength = 32768;
}
Stream stream = File.OpenRead(fileName);
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
// End of stream? If so, we're done
if (nextByte == -1)
{
return buffer;
}
// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
Wednesday, December 10, 2008
Connection Interrupted
Connection Interrupted
The connection to the server was reset while the page was loading.
The network link was interrupted while negotiating a connection. Please try again.
This is error shown in Firefox, when i upload large files bigger than 4096KB. I found that 4MB is maximum default request length.
You can solve this issue by inserting <httpRuntime maxRequestLength="2048000"> to web.config file. So you upload files up to 2GB total size.
Thursday, November 27, 2008
ASPxCallback && ASPxCallbackPanel
I was to do a web form for filling site information in some regions. To do that, i must select Province/City first in ComboBox and then a Region/District that belongs to the Province/City respectively; means when i select Province in combobox1, only regions in that province must be retrieved from server to combobox2.
I use Developer Express components regularly and if i used the latest versions of DevXpress ASPx components, it would be made easy by using ASPxCallbackPanel. But my DevXpress version is DevX 7.2 and there is no ASPxCallbackPanel component as is MS AJAX UpdatePanel. So i solved it with ASPxCallback component.
site_main.aspx:
<dxcb:aspxcallback id="ASPxCallback1" runat="server" clientinstancename="Callback1" oncallback="ASPxCallback1_Callback"></dxcb:aspxcallback>
<clientsideevents callbackcomplete="function(s, e) { var items= e.result.split("|") var i; for (i= 0; i< items[0]; i++) { cbbRegion.AddItem(items[2*i+ 2], items[2*i+ 1]); } }"></clientsideevents>
<dxe:aspxcombobox id="cbbCity" runat="server" height="19px" width="100px" datasourceid="dsrcCity" textfield="city_name" valuefield="city_code"></dxe:aspxcombobox>
<clientsideevents selectedindexchanged="function(s, e) { //alert(s.GetValue()); cbbRegion.ClearItems(); Callback1.SendCallback(s.GetValue()); }"></clientsideevents>
<asp:objectdatasource id="dsrcCity" runat="server" oldvaluesparameterformatstring="original_{0}" selectmethod="GetData" typename="CdsCityTableAdapters.vw_cityTableAdapter"></asp:objectdatasource>
<dxe:aspxcombobox id="cbbRegion" runat="server" clientinstancename="cbbRegion" datasourceid="dsrcRegion" textfield="region_name" valuefield="region_code" width="120px"></dxe:aspxcombobox>
<asp:objectdatasource id="dsrcRegion" runat="server" deletemethod="Delete" insertmethod="Insert" oldvaluesparameterformatstring="original_{0}" selectmethod="GetDataByCity" typename="CdsRegionTableAdapters.hr_regionTableAdapter" updatemethod="Update"></asp:objectdatasource>
<deleteparameters></deleteparameters>
<asp:parameter name="Original_region_id" type="Decimal"></asp:parameter>
<updateparameters></updateparameters>
<asp:parameter name="region_code" type="String"></asp:parameter>
<asp:parameter name="region_name" type="String"></asp:parameter>
<asp:parameter name="city_code" type="String"></asp:parameter>
<asp:parameter name="Original_region_id" type="Decimal"></asp:parameter>
<selectparameters></selectparameters>
<asp:parameter name="city_code" type="String"></asp:parameter>
<insertparameters></insertparameters>
<asp:parameter name="region_code" type="String"></asp:parameter>
<asp:parameter name="region_name" type="String"></asp:parameter>
<asp:parameter name="city_code" type="String"></asp:parameter>
<dxe:aspxmemo id="mmAntenna" runat="server" height="74px" width="729px"></dxe:aspxmemo>
site_main.aspx.cs:
protected void ASPxCallback1_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
{
CdsRegionTableAdapters.hr_regionTableAdapter regionTableAdapter = new CdsRegionTableAdapters.hr_regionTableAdapter();
CdsRegion.hr_regionDataTable regionDataTable= new CdsRegion.hr_regionDataTable();
regionTableAdapter.FillByCity(regionDataTable, e.Parameter);
String res = regionDataTable.Rows.Count.ToString();
for (int i = 0; i < regionDataTable.Rows.Count; i++)
{
res = res + "|"+ regionDataTable.Rows[i]["region_code"]+ "|"+ regionDataTable.Rows[i]["region_name"]+ "";
}
e.Result = res;
}
The mechanic is, when selected a city, selectedindexchanged="function(s, e) { //alert(s.GetValue()); cbbRegion.ClearItems(); Callback1.SendCallback(s.GetValue()); } is called. In it, cbbRegion is cleaned up and value of cbbCity is sent to server. Then, on server, ASPxCallback1_Callback is called and it sends corresponding "|" separated region names and codes back to the client using e.Result string. After that, callbackcomplete="function(s, e) { var items= e.result.split("|") var i; for (i= 0; i< items[0]; i++) { cbbRegion.AddItem(items[2*i+ 2], items[2*i+ 1]); } } is called automatically. As you see, the function parses e.Result and adds each to cbbRegion. I think the way i used is not good. But it was working so quick. I prefer coding style, but when result is good, it's ok to hardcode kk.
Tuesday, October 21, 2008
Тусламж хэрэгтэй байна
Юу вэ гэхлээр мань хүн MT буюу машин орчуулга (Компьютерээр текст орчуулах) сонирхдог юм л даа. Цаг зав гарсан үед ном товхимол шагайж, арга чарга судалдаг гэхүүдээ. Сүүлийн үед сонирхол дээд цэгтээ тулаад цагийг умартан судалгаа хийх болов. Энэ мэдээж ганц хүний чөлөөт цагаараа хийчихдэг ажил биш боловч нэгдүгээрт нэн шаардлагатай судлагдахуун, хоёрдугаарт миний туйлын хүсэл тул өөрийн эрхгүй ханцуй шамлан оров.
Судалгааны явц эхлэл төдий боловч ирээдүйдээ хэрэг болох (одоо ч гэсэн туршилт хийхэд жаахан хэрэг болоод л байна) Өгөгдлийн сан бүрдүүлэх ажлыг нэн түрүүнд хийх шаардлагатай байна. Тиймээс Өгөгдлийн сан бүрдүүлэхэд хамгийн хэрэгтэй эд болох Англи-Монгол, Монгол-Англи орчуулга цуглуулж эхэлж байна. Үүнд таны болон хэн нэгний орчуулсан ном, өгүүлэллээс эхлээд нэг өгүүлбэр ч байсан их тус болох нь дамжиггүй. Тиймээс надад туслая, мөн өөрийн хувь нэмрээ Англи-Монгол өгүүлбэр орчуулагчид оруулъя гэж бодож байвал otgontugs(at)gmail(dot)com* хаягаар явуулна уу.
Таны явуулсан материалийг судалгаанаас өөр зорилгоор ашиглахгүй бөгөөд ямар нэг зохиогчийн эрх тухай зүйл байвал гадагш тараахгүй хав дарж чадна гэдэгээ амлая.
Хэрэв та Машин орчуулгын ямар үр ашигтай өөрийн биеээр мэдрэхийг хүсвэл http://translate.google.com/translate_t хаягаар ороод үзээрэй. Гэхдээ харамсалтай нөгөө л Монгол гэдэг хэл байхгүй л байгаа.
* - (at)-ийн оронд "@", (dot)-ийн оронд "."
Monday, October 20, 2008
Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'
This error occurred while executing following MSSQL code.
declare @sql varchar(8000);
declare @params varchar(4000);
set @sql= 'select @perf_max= max(avrg)
from (
select avg(coalesce(ea_score, 0)) as avrg
from employee_appraisal
where ea_ap_id= 1 and ea_year='+cast(@yahr as varchar)+' and ea_emp_id in '+ @filter+
'group by ea_emp_id) v1';
set @params= '@perf_max float output';
exec sp_executesql @sql,@params,@perf_max output
I found the error was caused of calling sp_executesql with parameter type of varchar, NOT Nvarchar. @sql is dynamic query which is maximum length of 6K chars in my case. But NVARCHAR is 4K, so it's not enough.
Can anybody provide me solution?
Thanks in advance
Monday, October 13, 2008
Machine Translation/NLP Resources
Here is something useful for NLP/MT:
http://wt.jrc.it/lt/acquis/
http://www.mt-archive.info/
http://nl.ijs.si/telri/Vanilla/
http://www.essex.ac.uk/linguistics/clmt/MTBook/
http://portal.acm.org/
http://www.cs.unt.edu/~rada/wpt/WordAlignment.Guidelines.txt
http://www.iro.umontreal.ca/~simardm/lrec98/
http://www.informatik.uni-trier.de/~ley/db/conf/acl/acl2005.html
http://www.informatik.uni-trier.de/~ley/db/conf/acl/acl2006.html
http://www.informatik.uni-trier.de/~ley/db/conf/acl/acl2007.html
http://en.wikipedia.org/wiki/Bilingual_Evaluation_Understudy
http://nl.ijs.si/telri/
http://en.wikipedia.org/wiki/AntConc
http://corpora.wordpress.com/category/antconc/
http://nltk.sourceforge.net/
Related Mongolian:
http://acl.ldc.upenn.edu/P/P06/P06-1083.pdf
http://crlp.num.edu.mn/
http://www.infocon.mn/tts/ (Mongolian TTS engine in progress)
http://if-lab.slis.tsukuba.ac.jp/fujii/paper/ijcnlp2008khab.pdf