How can I convert U2 Business Logic Subroutine’s multi-value data into .NET Objects such as DataSet/DataTable using U2 Toolkit for .NET? - subroutine

I have the following subroutine. It takes INPUT as argument 1 and sends multi-value data OUTPUT as argument 2.
SUBROUTINE MV_TO_DATASET_SELECT_SUBROUTINE(ARG_INPUT,ARG_OUTPUT)
x = ARG_INPUT
ARG_OUTPUT = "100":#VM:"101":#VM:"102":#VM:"103":#FM:"Nancy":#VM:"Andrew":#VM:"Janet":#VM:"Margaret":#FM:"01/06/1991":#VM:"06/07/1996":#VM:"11/08/1999":#VM:"12/10/2001"
RETURN
The Schema of above subroutine’s multi-value data is as below.
DataSet ds = new DataSet();
DataTable dt = new DataTable("Employee");
ds.Tables.Add(dt);
dt.Columns.Add("ID",typeof(Int32));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("HireDate", typeof(DateTime));

You can achevieve this task one of the following ways:
Use MV_To_DataTable() and DataTable_To_MV(). You can create schema of
subroutine by dragging and dropping Empty DataTable into Empty
DataSet Deginer.
By draagging and dropping Visual Studio Server Explorer’s U2
Subroutine into DataSet Designer. U2 Subrotine returns
resultset/dataset by executing API such as ST=SQLExecDirect(#HSTMT,
"SELECT F1 AS COL1,F2 AS COL2 ,F3 AS COL3 FROM #TMP SLIST 9 ORDER BY
1")
Use MV_To_DataTable() and DataTable_To_MV()
Create ASP.NET Web Application Project. Type ‘WebApplication_Subroutine’ in Project Name.
Add Reference to U2NETDK Assembly (U2.Data.Client)
Change header ‘Welcome to ASP.NET!’ to ‘Welcome to U2 Toolkit for .NET Demo on Business Logic Subroutine’s multi-value string data to .NET DataSet!’
Open ‘Default.aspx’ file and Go to Design Mode.
Do the following:
Drag and Drop Button Control. Name it ‘Load’
Drag and Drop Button Control. Name it ‘Update’
Drag and Drop GridView Control.
Right Click on Solution Explorer. Select Add ->New Item-DataSet. In the Name box, type ‘Employee.xsd’
Drag and Drop DataTable into Designer. Change the name to ‘Employee’ Table.
Create 3 new Columns (U2 subroutine Schema):
ID – DataType : INT
Name – DataType : STRING
HireDate - DataType : DATE
Open ‘Default.aspx’ file in Design Mode. Double Click ‘Load Button’. It will create Event handler Code behind.
Cut and paste the following code.
protected void Button1_Click(object sender, EventArgs e)
{
U2ConnectionStringBuilder l = new U2ConnectionStringBuilder();
l.Server = "127.0.0.1";
l.UserID = "user";
l.Password = "pass";
l.Database = "HS.SALES";
l.ServerType = "universe";
string lconnstr = l.ToString();
U2Connection c = new U2Connection();
c.ConnectionString = lconnstr;
c.Open();
U2Command command = c.CreateCommand();
command.CommandText = "CALL MV_TO_DATASET_SELECT_SUBROUTINE(?,?)";
command.CommandType = CommandType.StoredProcedure;
U2Parameter p1 = new U2Parameter();
p1.Direction = ParameterDirection.InputOutput;
p1.Value = "";
p1.ParameterName = "#arg_input";
command.Parameters.Add(p1);
U2Parameter p2 = new U2Parameter();
p2.Direction = ParameterDirection.InputOutput;
p2.Value = "";
p2.ParameterName = "#arg_output";
command.Parameters.Add(p2);
command.ExecuteNonQuery();
Employee.EmployeeDataTable dt = new Employee.EmployeeDataTable();
command.Parameters[1].MV_To_DataTable(dt);
Session["GridDataset"] = dt;
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
Run the application. Press ‘Load’ Button.
Open ‘Default.aspx’ file in Design Mode. Double click ‘Update Button’. It will create Event Handler in Code behind page.
Cut and Paste the following Code.
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)Session["GridDataset"];
//To TEST, change first row
string s1 = (string)dt.Rows[0]["Name"];
dt.Rows[0]["Name"] = s1 + "NewValue";
// get the modified rows
DataTable dt_changed = dt.GetChanges();
//call DATASET_TO_MV_UPDATE_SUBROUTINE
U2ConnectionStringBuilder l = new U2ConnectionStringBuilder();
l.Server = "127.0.0.1";
l.UserID = "user";
l.Password = "pass";
l.Database = "HS.SALES";
l.ServerType = "universe";
string lconnstr = l.ToString();
U2Connection c = new U2Connection();
c.ConnectionString = lconnstr;
c.Open();
U2Command command = c.CreateCommand();
command.CommandText = "CALL DATASET_TO_MV_UPDATE_SUBROUTINE(?)";
command.CommandType = CommandType.StoredProcedure;
U2Parameter p1 = new U2Parameter();
p1.Value = "";
p1.Direction = ParameterDirection.InputOutput;
p1.ParameterName = "#arg_data";
command.Parameters.Add(p1);
command.Parameters[0].DataTable_To_MV(dt_changed);
// modified data going to subroutine
string lData = (string)command.Parameters[0].Value;
command.ExecuteNonQuery();
}
See the Modified Value in the Debugger when you click Update Button.
U2 Subrotine returns resultset/dataset
Create U2 Data Connection in Visual Studio Server Explorer. Expand Store Procedures Node.
Go to subroutine that returns resultset/dataset. Drag and Drop subroutine into DataSet Designer.
It shows INPUT argument and resultset/dataset columns.

Related

Need clarification about how to apply a custom update to data adapter source

I have created a record-view form that contains a few bound elements via a BindingSource and a BindingNavigator. The viewing of the data fields is operating correctly. Note that the variables da and ds are global in this form.
private void frmItem_Load(object sender, EventArgs e) {
string scon = System.Configuration.ConfigurationManager.ConnectionStrings["myitems"].ToString();
da = new SqlDataAdapter("Select * From myitems where id > 0 ", scon);
ds = new DataSet();
da.Fill(ds);
bindingSource1.DataSource = ds.Tables[0];
bindingNavigator1.BindingSource = this.bindingSource1;
this.txtId.DataBindings.Add(new Binding("Text", bindingSource1, "id", true));
this.txtItem.DataBindings.Add(new Binding("Text", bindingSource1, "item", true));
this.txtUpdatedwhen.DataBindings.Add(new Binding("Text", bindingSource1, "updatedwhen", true));
}
I am showing this record-view form from a data grid view of items by using a row header mouse dbl-click event. The requested row from the dgv is correctly being selected and its row data is correctly being shown in the record-view form.
private void dgvItems_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
frmItem gfrmItem = new frmItem();
string sID = this.dgvItems.CurrentRow.Cells[0].Value.ToString();
gfrmItem.FilterByID(sID);
gfrmItem.Show();
}
I've added a save button to the navigator so that I can make individual record save. What I'm attempting to do is programatically apply a date/time stamp update before the record is saved from the button click.
private void btnSave_Click(object sender, EventArgs e)
{
this.txtUpdatedwhen.Text = DateTime.Now.ToString();
da.Update(ds);
}
Although the date/time value is changed per the code and shows in the form, the update is not applying the date/time change.
I thought that the textbox value was being bound to the underlying dataset and would accept changes as if I had entered it manually ... but this is not occurring. I had read some other posts that using the data adapter update is the right way to go about this as apposed to doing something like performing a direct sql update.
I'm stumped with how to resolve this. Any pointers would be greatly appreciated.
After letting this sit a while and coming back to it today, I found a resolution.
There was a common misunderstanding at work that I saw in other posts.
That was that the dataadapter does not automatically populate its commands, even if you pass an active connection into the creation step.
So my resolution was to create a global SqlCommandBuilder variable along with the other ones I was using
SqlDataAdapter da;
SqlConnection sc;
SqlCommandBuilder sb;
DataSet ds;
then create the builder object at form load and initialize the update command into a string variable ... which isn't used there after, but the dataadapter commands are now populated.
string scon = System.Configuration.ConfigurationManager.ConnectionStrings["networkadmin"].ToString();
sc = new SqlConnection(scon);
sc.Open();
string sSelect = "Select * From datatable where id > 0 Order By fld1;";
}
this.da = new SqlDataAdapter(sSelect, sc);
sb = new SqlCommandBuilder(da);
// This initiates the commands, though the target var is not used again.
string uCmd = sb.GetUpdateCommand().ToString();
this.ds = new DataSet();
this.da.Fill(this.ds);
Then the update step does work as expected:
this.txtUpdatedwhen.Text = DateTime.Now.ToString();
DataRowView current = (DataRowView)bindingSource1.Current;
current["updatedwhen"] = this.txtUpdatedwhen.Text;
bindingSource1.EndEdit();
this.da.Update(ds);
I hope this helps someone.

how to hide other column

In my datagridview, I just want to show other fields such as ID,LastName,FirstName, and MiddleName and i dont want to show any fields but i want it to retrieve even it's hidden. But when i specify what i just want to show in my datagridview it causes runtime error.
this is my code to load the datagridview.
MysqlConn.Open()
Dim Query As String
Query = "select ID,LastName,FirstName,MiddleName from god.precord"
COMMAND = New MySqlCommand(Query, MysqlConn)
SDA.SelectCommand = COMMAND
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
DataGridView1.DataSource = bSource
SDA.Update(dbDataSet)
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
then this is my code for retrieve data into textboxes
Private Sub DataGridView1_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow
row = Me.DataGridView1.Rows(e.RowIndex)
txtid.Text = row.Cells("ID").Value.ToString
txtlastname.Text = row.Cells("LastName").Value.ToString
txtfirstname.Text = row.Cells("FirstName").Value.ToString
txtmiddlename.Text = row.Cells("MiddleName").Value.ToString
txtaddress.Text = row.Cells("Address").Value.ToString
txtcontactno.Text = row.Cells("ContactNo").Value.ToString
txtgender.Text = row.Cells("Gender").Value.ToString
dtpbirthdate.Text = row.Cells("Birthdate").Value.ToString
txtage.Text = row.Cells("Age").Value.ToString
End If
End Sub
runtime error
please help me this is for my thesis
thankyou in advance <3
You have to add hidden column into the select query to retreive the data.
Hide the column from the DataGridView instead.
try
MysqlConn.Open()
Dim Query As String
Query = "select ID,LastName,FirstName,MiddleName,Address from god.precord"
COMMAND = New MySqlCommand(Query, MysqlConn)
SDA.SelectCommand = COMMAND
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
DataGridView1.DataSource = bSource
SDA.Update(dbDataSet)
DataGridView1.Columns("Address").Visible = false
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try

Updating column in tableviwer

I have retrieved data from database and i am able to show it in Table of the Table Viewer but my task is on click of a row the data should be appear in another form from where i can edit it and on click of update the view should be updated with the new values.I am using viewer.addSelectionChangedListener to retrieve the selected row but i am not getting how to update the table .Please suggest me few ideas
I have written the below code in the constructor of my class so whenever object is created Table is generated and l1 is list of data which i am passing to another UI
input[i] = new MyModel(persons[i].getDateOfRegistration(), persons[i].getFirstName(),
persons[i].getMiddleName(), persons[i].getLastName(), persons[i].getGender(),
persons[i].getDob(), persons[i].getContactNumber(), persons[i].getMaritalStatus(),
persons[i].getAddress(), persons[i].getCountry(), persons[i].getBloodGroup(),
persons[i].getInsuranceDetails().getPolicyHolderName(),
persons[i].getInsuranceDetails().getPolicyNumber(),
persons[i].getInsuranceDetails().getSubscriberName(),
persons[i].getInsuranceDetails().getRelationshipToPatient());
viewer.setInput(input);
table.setHeaderVisible(true);
table.setLinesVisible(true);
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
viewer.getControl().setLayoutData(gridData);
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
StringBuffer sb = new StringBuffer("Selection - ");
int j = 0;
String[] s;
for (Iterator iterator = selection.iterator(); iterator.hasNext();) {
sb.append(iterator.next() + ", ");
System.out.println("Testing::" + sb);
}
System.out.println(sb);
String result[] = new String[18];
List l1 = new ArrayList(100);
String[] parts = sb.toString().split("=");
for (int i = 0; i < parts.length; i++) {
System.out.println("s" + parts[i]);
String[] s1 = parts[i].split(",");
l1.add(s1[0]);
}
SWTPatientRegistrationUpdatePageEventView swtPatientRegistrationUpdatePageEventView = new SWTPatientRegistrationUpdatePageEventView();
swtPatientRegistrationUpdatePageEventView.openParentUpdateShell(l1);
// viewer.refresh();
//flag=false;
//refreshingData(list);
}
});
Make sure we will follow table viewer MVC architecture all the time. Steps we can do to resolve your issue isas follow:
Create proper datastructure(Model Class) to hold the data. and use the same in array which you set in viewer.setInput()
When you click/double click on table row, fetch the data and save it in datastructure created(with new object).
Pass that data structure to your form dialog.
when you are done with update in form. Fill the updated data in new Model object again.
And after form close, pass that model object back to parent.
updated the corresponding array element with object received from Form Dialog and just refresh the tableviewer.
Please let me know if you need some code module. Thanks

Parameter to Crystal Report

i created a #Month as parameter name in crystal report and just insert to the report header section.
When i run the report always it asks the parameter by showing one box. How i pass through code. My existing code is below
MyReport rpt = new MyReport();
var srcData = ; //here i added my LINQ statement to select the data
rpt.SetDataSource(srcData);
ParameterDiscreteValue pdValue = new ParameterDiscreteValue();
pdValue.Value = combo2.SelectedValue;
rpt.ParameterFields["#Month"].CurrentValues.Add(pdValue);
this.ReportViewer1.ReportSource = rpt;
this.ReportViewer1.RefreshReport();
Where i did the mistake?
Hi I solved by just removing RefershReport() method of crystalreportviewer
I find from : http://www.it-sideways.com/2011/10/how-to-disable-parameter-prompt-for.html
If it's not working it suggests a typo or something. Try analyzing rpt.ParameterFields (set a breakpoint and watch). Have you got the parameter name correct? Data type?
I had trouble with adding parameters as well. Here's an example of what I got working:
string ponumber = Request.QueryString["ponumber"].ToString();
string receiptno = Request.QueryString["receiptno"].ToString();
// Put Away Report
CrystalReportSource CrystalReportSource1 = new CrystalReportSource();
CrystalReportViewer CrystalReportViewer1 = new CrystalReportViewer();
CrystalReportViewer1.ReportSource = CrystalReportSource1;
CrystalReportViewer1.EnableParameterPrompt = false;
CrystalReportSource1.Report.FileName = "Report3.rpt";
CrystalReportSource1.EnableCaching = false;
// This will set the values of my two parameters in the report
CrystalReportSource1.ReportDocument.SetParameterValue(0, ponumber);
CrystalReportSource1.ReportDocument.SetParameterValue(1, receiptno);
TableLogOnInfo logOnInfo = new TableLogOnInfo();
logOnInfo.ConnectionInfo.ServerName = ConfigurationManager.AppSettings["WarehouseReportServerName"];
logOnInfo.ConnectionInfo.DatabaseName = ConfigurationManager.AppSettings["WarehouseReportDatabaseName"];
logOnInfo.ConnectionInfo.UserID = ConfigurationManager.AppSettings["WarehouseReportUserID"];
logOnInfo.ConnectionInfo.Password = ConfigurationManager.AppSettings["WarehouseReportPassword"];
TableLogOnInfos infos = new TableLogOnInfos();
infos.Add(logOnInfo);
CrystalReportViewer1.LogOnInfo = infos;
maindiv.Controls.Add(CrystalReportSource1);
maindiv.Controls.Add(CrystalReportViewer1);
CrystalReportViewer1.DataBind();

Batching in ADO.NET without DataAdapters

Is it possible to implement batching of multiple stored procedure calls (doing updates/deletes) in ADO.NET without resorting to DataAdapters?
You could try using System.Data.SqlClient.SqlCommandSet. It's actually internal, but Ayende made a wrapper to make it public.
Code is currently hosted in sourceforge.
You're SQL text can contain multiple commands. If you return multiple result sets, then you can use a DataReader and use the NextResult function. What I often do is store the SQL to execute as an Embedded Resource, then load that text. If it contains parameters, then set the parameters just like you would normally.
For example, I have a file:
UPDATE dbo.QuotePricedLineItem
SET fkQuoteVendorLineSet = NULL
FROM dbo.QuotePricedLineItem qpli
INNER JOIN dbo.QuoteLineItem qli ON qpli.Id = qli.Id
WHERE qli.fkQuote = #quoteId AND qpli.fkQuoteVendorLineSet = #ciscoConfigId
DELETE CiscoQuoteLineItem
FROM CiscoQuoteLineItem cqli
INNER JOIN QuoteLineItem qli ON cqli.Id = qli.Id
WHERE qli.fkQuote = #quoteId AND cqli.fkCiscoQuoteVendorLineSet = #ciscoConfigId
that I execute as such:
using (SqlConnection conn = DbUtils.CreateConnection() as SqlConnection)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = MvcApplication.GetResource("SQL.DemoteCiscoQuoteLineItems.sql");
cmd.Parameters.AddWithValue("#quoteId", q.Id);
cmd.Parameters.AddWithValue("#ciscoConfigId", configSetId);
cmd.ExecuteNonQuery();
}
Note that MvcApplication.GetResource is not a built in function - it's one you have to write... here's mine:
public static string GetResource(string p)
{
Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("CortexQuoting.Res." + p);
if (s == null) return null;
StreamReader sw = new StreamReader(s);
string ss = sw.ReadToEnd();
sw.Close();
return ss;
}