Retrieving Multiple rows from SQLite in Xamarin iOS - sqlite

I'm doing an app with Xamarin iOS.
I put a UITableView on XCode, so that when I click on a button, it retrieves from the database and slot it in. I'm able to put it onto a row, but couldn't figure it out how to have multiple rows of data in it. This is my partial code from which I'm able to display a row of data.
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
while (dr.Read())
{
var table = new UITableView(this.retrieveData.Frame);
string[] tableItems = new String[] {dr["admin_num"] + ", " + dr["name"]};
table.Source = new TableSource(tableItems);
Add (table);
}

You are creating a completely new TableView for each row in your data. Instead, you should loop through your data and create a data structure (List, array, etc) containing ALL of the data you want to display, and then pass that data to your TableView/Source.
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
// you will need a class mydata with Num and Name properties
List<mydata> data = new List<mydata>();
while (dr.Read())
{
data.Add(new mydata { Num = dr["admin_num"], Name = dr["name"] });
}
dr.Close();
var table = new UITableView(this.retrieveData.Frame);
table.Source = new TableSource(data);
Add (table);

What you need to do is this:
public List<DemoClass> getDemoClassList()
{
List<DemoClass> lstDemoClass;
DemoClass objDemoClass;
try
{
String strCommandText;
strCommandText = "SELECT * FROM DemoClass ";
command = new SqliteCommand(strCommandText, connection);
lstDemoClass = new List<DemoClass>();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
objDemoClass = new Homes(false);
objDemoClass.ID = Convert.ToInt32(reader[0]);
objDemoClass.Name = Convert.ToString(reader[1]);
lstDemoClass.Add(objDemoClass);
}
}
return lstDemoClass;
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Dispose();
command = null;
lstDemoClass = null;
objDemoClass = null;
}
}
public void BindList()
{
List<DemoClass> lstDemoClass = new List<DemoClass>();
DemoClass hm = new DemoClass();
lstDemoClass = (List<DemoClass>)hm.getDemoClassList();
TableViewDataSource tdatasource = new TableViewDataSource(this, lstDemoClass);
table.Hidden = false;
table.DataSource = tdatasource;
table.Delegate = new TableViewDelegate(this, table, lstDemoClass);
table.ReloadData();
}
The getDemoClassList() will give the retrieved list from SQLite table, and later you can bind the list to the table datasource.
UPDATE:
As per your request I have updated my comment with the code for datasource and its delegate classes.
Now in this same class you need to add the following subclasses:
#region TableDelegate
public class TableViewDelegate : UITableViewDelegate
{
private DemoPageViewController _Controller;
private List<DemoClass> lst;
public TableViewDelegate(DemoPageViewController controller ,UITableView tableView, List<DemoClass> tblList)
{
try
{
this._Controller = controller;
this.lst = tblList;
}
catch(Exception ex)
{
}
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
try
{
//This loads the activity spinner till the selection code is completed
_Controller._loadPop = new LoadingOverlay (new System.Drawing.RectangleF(0,0,_Controller.View.Frame.Width,_Controller.View.Frame.Height),"Loading...");
_Controller.View.Add ( _Controller._loadPop );
// spin up a new thread to do some long running work using StartNew
Task.Factory.StartNew (
// tasks allow you to use the lambda syntax to pass work
() => {
InvokeOnMainThread(delegate{
DemoClass f = lst[indexPath.Row];
//Add your code here, usually some navigation or showing a popup
});
}).ContinueWith(t => InvokeOnMainThread(() => {
//Hide the activity spinner
_Controller._loadPop.Hide();
}));
}
catch(Exception ex)
{
}
finally
{
}
}
}
#endregion
#region TableDataSource
private class TableViewDataSource : UITableViewDataSource
{
static NSString kCellIdentifier = new NSString("MyIdentifier");
private List<DemoClass> lst;
private DemoPageViewController controller;
public TableViewDataSource (DemoPageViewController controller ,List<DemoClass> tblLst)
{
this.controller = controller;
this.lst = tblLst;
}
public override int NumberOfSections (UITableView tableView)
{
return 1;
}
public override int RowsInSection (UITableView tableView, int section)
{
return lst.Count;
}
// Override to support conditional editing of the table view.
public override bool CanEditRow (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
// Return false if you do not want the specified item to be editable.
return false;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
try
{
UITableViewCell cell = tableView.DequeueReusableCell (kCellIdentifier);
if (cell == null)
{
cell = new UITableViewCell (UITableViewCellStyle.Subtitle, kCellIdentifier);
cell.Tag = Environment.TickCount;
}
DemoClass objDemo = lst[indexPath.Row];
cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
cell.ImageView.Image = UIImage.FromFile("Images/CameraImg.png");
cell.DetailTextLabel.Text = "Show some detail: " + objDemo.DemoDescription.ToString();
cell.TextLabel.Text = "Some Title: " + objDemo.DemoTitle.ToString();
return cell;
}
catch(Exception ex)
{
return null;
}
finally
{
}
}
}
#endregion
Hope it helps.

Related

How to save objects in a proper way with the stream writer?

In the program.cs the user is asked if he wanna read the data, if he types y then the method Doc.ReadDoc starts is there any proper way:
class Program
{
static void Main(string[] args)
{
do
{
var path = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path + #"\TestFile.txt";
Console.WriteLine("Do you want to read it? y/n");
string yesorno = Console.ReadLine();
if (yesorno=="y")
{
Console.Clear();
Doc.ReadDoc();
}
Console.WriteLine("Which type of vehicle");
string type = Console.ReadLine();
Console.WriteLine("how many tires");
int raeder = Convert.ToInt32( Console.ReadLine());
var Vehicle = new Used_Cars(type, raeder);
Doc.Write(Vehicle);
} while (true);
}
}
The Class with the methods (Read, Write):
public static List<string> ReadDoc()
{
var list = new List<string>();
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
try
{
using (StreamReader sr = new StreamReader(fileName))
{
Console.WriteLine("Data found");
string line;
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("Data not found");
Console.WriteLine(e.Message);
list = null;
}
return list;
}
And the last Method is the Write method, is this a good code to save properties in a file? How could i stop the program with ESC or smth like that, so if the user presses ESC it should stop.
public static void Write(Used_Cars vehicle)
{
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
Console.WriteLine("Is it correct?");
Console.WriteLine("y/n");
string yeahorno= Console.ReadLine();
if (jaodernein == "y")
{
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine(vehicle.Vehicle);
writer.WriteLine(vehicle.Wheels);
Console.WriteLine();
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
}
}

refresh label during a foreach loop

I'm asking for your help.
I'm developing an application in JavaFX who "scan" Mp3 files to get ID3tag.
Here is my problem. I did a foreach loop of a list for every .mp3 found but I'd like to increment a label which inform the progression of the list.
Here is my code
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
this.labelUpdate.setText(this.current++ + " of " + " size");
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
}
Actually, when the loop progress my window interface is completely freeze.
And only when the loop is finished, the label updated.
Someone can explain why ?
I already thank you for your answers.
EDIT :
Here is my fully code
public class LaunchOption extends Pane {
private final HBox launchAndSend = new HBox();
private final HBox browseAndField = new HBox();
private final HBox jsonAndAdvance = new HBox();
private ArrayList<DataSong> lsWithData = new ArrayList<>();
private String sendJson;
private File selectedDirectory;
private User user;
private int currentData;
private final ProgressIndicator pi = new ProgressIndicator(0);
private final VBox containerElement = new VBox();
private final TextArea displayJson = new TextArea();
private final TextField pathDir = new TextField();
private final TextField nbrOfData = new TextField();
private final Button btnScan = new Button();
private final Button btnSend = new Button();
private final Button btnCheckJson = new Button();
private final Button btnDirectoryBrowser = new Button();
private final Label nbMp3 = new Label();
public Label listAdvance = new Label();
private final Stage home;
public LaunchOption(Stage home){
this.home = home;
configureBtnCheckJson();
configureBtnScan();
configureBtnSend();
configureLabelMp3();
configureBtnDirectoryBrowser();
configureTextAreaDisplayJson();
configureTextFieldPathDir();
configureTextFieldNbDataMp3();
configureHBoxlaunchSend();
configureHBoxBrowseAndField();
configureHBoxJsonAndAdvance();
configureContainer();
this.getChildren().addAll(containerElement,launchAndSend);
}
private void configureLabelMp3()
{
nbMp3.setText("MP3");
}
private void configureBtnScan(){
btnScan.setText("Scan");
btnScan.setOnAction(event->{
ArrayList<String> Mp3FileData;
Mp3FileData = mapFilesMp3(selectedDirectory.getAbsolutePath());
System.out.println("ListSize = " + Mp3FileData.size());
nbrOfData.setText(String.valueOf(Mp3FileData.size()));
try {
lsWithData = checkMp3File(Mp3FileData, selectedDirectory.getAbsolutePath());
} catch (UnsupportedTagException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidDataException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
}
pi.setProgress(1);
});
}
private void configureBtnDirectoryBrowser(){
btnDirectoryBrowser.setText("Browse ...");
btnDirectoryBrowser.getStyleClass().add("round-red");
btnDirectoryBrowser.setOnAction(event-> {
DirectoryChooser dc = new DirectoryChooser();
selectedDirectory = dc.showDialog(home);
pi.setProgress(0.35);
if(selectedDirectory == null)
{
pathDir.setText("No directory selected");
}
else
{
pathDir.setText(selectedDirectory.getAbsolutePath());
String Text = pathDir.getText();
System.out.println(Text.toString());
}
});
}
private static String regexMp3()
{
return "^.*\\.(mp3)$";
}
private ArrayList mapFilesMp3(String sDir){
ArrayList<String> ls = new ArrayList<>();
printFnames(sDir,ls);
return ls;
}
private static void printFnames(String sDir, ArrayList<String> ls)
{
File[] faFiles = new File(sDir).listFiles();
for(File file : faFiles)
{
if(file.getName().matches(regexMp3()))
{
// System.out.println(file.getAbsolutePath());
ls.add(file.getAbsolutePath());
}
if(file.isDirectory())
{
printFnames(file.getAbsolutePath(), ls);
}
}
}
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
System.out.println(this.currentData++);
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
if(mp3 != null){
ds.setAbsoluteLocation(mp3.getFilename());
ds.setLocation(removeSDir(mp3.getFilename(), sDir));
if(mp3.hasId3v2Tag())
{
ID3v2 id3v2Tag = mp3.getId3v2Tag();
if(!(id3v2Tag.getArtist() == null))
{
ds.setArtist(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getAlbum() == null))
{
ds.setAlbum((id3v2Tag.getAlbum()));
}
if(!(id3v2Tag.getTitle() == null))
{
ds.setTitle(id3v2Tag.getTitle());
}
if(!(id3v2Tag.getTrack() == null))
{
ds.setTrackOnAlbum(id3v2Tag.getTrack());
}
if(!(id3v2Tag.getYear() == null) && !(id3v2Tag.getYear().isEmpty()))
{
ds.setYearReleased(id3v2Tag.getYear());
}
if(!(id3v2Tag.getGenreDescription() == null))
{
ds.setGenre(id3v2Tag.getGenreDescription());
}
if(!(id3v2Tag.getComposer() == null))
{
ds.setComposer(id3v2Tag.getComposer());
}
if(!(id3v2Tag.getPublisher() == null))
{
ds.setPublisher(id3v2Tag.getPublisher());
}
if(!(id3v2Tag.getOriginalArtist() == null))
{
ds.setOriginArtist(id3v2Tag.getOriginalArtist());
}
if(!(id3v2Tag.getAlbumArtist() == null))
{
ds.setAlbumArtString(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getCopyright() == null))
{
ds.setCopyright(id3v2Tag.getCopyright());
}
if(!(id3v2Tag.getUrl() == null))
{
ds.setUrl(id3v2Tag.getUrl());
}
}
}
lsds.add(ds);
}
return lsds;
}
I presume that what I should do is to make my checkMp3File method into a Task method which will do a background thread ?
There is not enough code to be sure but I think you are probably calling your method on the JavaFX application thread which then blocks your UI.
You should read the documentation about concurrency in JavaFX.
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm

how to refer to a non-declared variables in setResultConverter

I'd like to re-use a dialog class for data manipulation. The data will be retrieved from database. It depends on which table the class retrieve the data from, the size of the table columns is not fixed, so I can't declare column variables. After users update data, I would like to convert the input data using setResultConverter but do not know how to refer to the variable, since the program generates TextFields dynamically. Please help. Here is the the code.
public class AddDialog {
private Dialog<DBtable> dialog = new Dialog<DBtable>();
private ButtonType saveBtn;
//database variables
private Connection connect; // = null;
private String dbTblName;
//gridpane content variables
private GridPane contentPane = new GridPane();
private HashMap<String, TextField> fieldMap =
new HashMap<String, TextField>();
private ArrayList<String> dataList = new ArrayList<String>();
public AddDialog (String title, String header, String dbTable) {
this.dbTblName = dbTable;
dialog.setTitle(title);
dialog.setHeaderText(header);
saveBtn = new ButtonType("Save", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(saveBtn,
ButtonType.CANCEL);
dialog.getDialogPane().setContent(getLayout(dbTable));
Optional<DBtable> result = dialog.showAndWait();
result.ifPresent(data -> {
System.out.println(" data="+data+" 0="+data.getID()+
" 1="+data.getField1());
});
} // constructor ends
public GridPane getLayout(String dbTable) {
String sql = "select column_name, description ";
sql += "from syscolumn_description ";
sql += "where table_name = \'" + dbTable + "\'";
String fieldLabel, fieldCol;
ResultSet ds = null;
// retrieve meta data from database
connect = DBConnect.getConnect(connect);
try {
Statement labelStmnt = connect.createStatement();
ds = labelStmnt.executeQuery(sql);
int row = 0;
while (ds.next()) {
row += 2;
//label....column=0 row=row+2;
fieldLabel = ds.getString("DESCRIPTION");
contentPane.add(new Text(fieldLabel), 0, row);
//textField...column=1 row=row+2;
contentPane.add(new TextField(), 1, row);
fieldCol = ds.getString("COLUMN_NAME");
fieldMap.put(fieldCol, new TextField());
} // while result set loop ends
} catch (Exception e) {
e.printStackTrace();
} finally {
try {if(ds != null) ds.close();} catch (Exception e) {};
}
// convert result
dialog.setResultConverter(dialogButton -> {
if (dialogButton == saveBtn) {
int i=0;
for (Map.Entry<String, TextField> e : fieldMap.entrySet()) {
dataList.add(e.getValue().getText());
i++;
System.out.println("col="+e.getKey()+
" data="+e.getValue().getText());
} // map loop end
return new DBtable(dataList, i);
}
return null;
});
return contentPane;
} //getLayout ends
} // AddDialog ends

How to upload Multiple file in Kentico Custom BizForm?

I have one Form which created as ascx control.Data was saving in biz form successfully. my problem is how to upload file? i dont know which control i'm using right or not for upload file? and how to add file upload submit here rec.SetValue("UploadCV", duUploadCV.InnerAttachmentGUID); you can see below click button code.i have both code ascx and .cs in below. my ascx upload control which i'm using is right or not ? design code is below. code .cs is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CMS.Base;
using CMS.DataEngine;
using CMS.DocumentEngine;
using CMS.EmailEngine;
using CMS.EventLog;
using CMS.FormControls;
using CMS.FormEngine;
using CMS.Helpers;
using CMS.Localization;
using CMS.MacroEngine;
using CMS.Membership;
using CMS.PortalControls;
using CMS.PortalEngine;
using CMS.Protection;
using CMS.SiteProvider;
using CMS.WebAnalytics;
using System.Data;
using CMS.GlobalHelper;
using CMS.TreeEngine;
using CMS.CMSHelper;
using CMS.SiteProvider;
using CMS.EmailEngine;
using CMS.EventLog;
using CMS.DataEngine;
using CMS.WebAnalytics;
using CMS.LicenseProvider;
using CMS.PortalEngine;
using CMS.SettingsProvider;
using CMS.IDataConnectionLibrary;
using CMS.OnlineForms;
using CMS.DataEngine;
using CMS.SiteProvider;
using CMS.Helpers;
using CMS.FormEngine;
using CMS.SettingsProvider;
using CMS.DataEngine;
using CMS.GlobalHelper;
using CMS.ExtendedControls;
using CMS.Helpers;
using CMS.UIControls;
using System.Text;
using System.Web.UI.WebControls;
public partial class CMSWebParts_ePortalWebPart_ePortalControl_GraduateProgramApplication : CMSAbstractWebPart
{
//public static int SaveSignupForm(SignupFormModel model)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetGender();
GetUniversity();
GetStudyArea();
GetSpecializationEng();
}
}
#region "Layout properties"
public override string SkinID
{
get
{
return base.SkinID;
}
set
{
base.SkinID = value;
SetSkinID(value);
}
}
public string NameText
{
get
{
return DataHelper.GetNotEmpty(GetValue("NameText"), ResHelper.LocalizeString("{$GPAName$}"));
}
set
{
SetValue("NameText", value);
lblName.Text = value;
}
}
#endregion
public string DOBText
{
get
{
return DataHelper.GetNotEmpty(GetValue("DOBText"), ResHelper.LocalizeString("{$GPADateOfBirth$}"));
}
set
{
this.SetValue("LastNameText", value);
lblDOB.Text = value;
}
}
public string EmailText
{
get
{
return DataHelper.GetNotEmpty(this.GetValue("EmailText"), ResHelper.LocalizeString("{$Webparts_Membership_RegistrationForm.Email$}"));
}
set
{
this.SetValue("EmailText", value);
lblEmail.Text = value;
}
}
public string Submit
{
get
{
return DataHelper.GetNotEmpty(GetValue("Submit"), ResHelper.LocalizeString("{$custom.custom.Submit$}"));
}
set
{
this.SetValue("Submit", value);
btnOk.Text = value;
}
}
public string Gender
{
get
{
return DataHelper.GetNotEmpty(GetValue("Gender"), ResHelper.LocalizeString("{$GPAGender$}"));
}
set
{
this.SetValue("Gender", value);
lblGender.Text = value;
}
}
public string Email
{
get
{
return DataHelper.GetNotEmpty(GetValue("Email"), ResHelper.LocalizeString("{$GPAEmail$}"));
}
set
{
this.SetValue("Email", value);
lblEmail.Text = value;
}
}
public string GSMNumber
{
get
{
return DataHelper.GetNotEmpty(GetValue("GSMNumber"), ResHelper.LocalizeString("{$GPAGSMNumber$}"));
}
set
{
this.SetValue("GSMNumber", value);
lblGSMNumber.Text = value;
}
}
public string Grade
{
get
{
return DataHelper.GetNotEmpty(GetValue("Grade"), ResHelper.LocalizeString("{$GPAGrade$}"));
}
set
{
this.SetValue("Grade", value);
lblGrade.Text = value;
}
}
public string ExpectGraduateDate
{
get
{
return DataHelper.GetNotEmpty(GetValue("ExpectGraduateDate"), ResHelper.LocalizeString("{$GPAExpectGraduateDate$}"));
}
set
{
this.SetValue("ExpectGraduateDate", value);
lblExpectGraduateDate.Text = value;
}
}
public string University
{
get
{
return DataHelper.GetNotEmpty(GetValue("University"), ResHelper.LocalizeString("{$GPAUniversity$}"));
}
set
{
this.SetValue("University", value);
lblUniversity.Text = value;
}
}
public string StudyArea
{
get
{
return DataHelper.GetNotEmpty(GetValue("StudyArea"), ResHelper.LocalizeString("{$GPAStudyArea$}"));
}
set
{
this.SetValue("StudyArea", value);
lblStudyArea.Text = value;
}
}
public string Specialization
{
get
{
return DataHelper.GetNotEmpty(GetValue("Specialization"), ResHelper.LocalizeString("{$GPASpecialization$}"));
}
set
{
this.SetValue("Specialization", value);
lblSpecialization.Text = value;
}
}
public string WhyJoinPAEW
{
get
{
return DataHelper.GetNotEmpty(GetValue("WhyJoinPAEW"), ResHelper.LocalizeString("{$GPAWhyJoinPAEW$}"));
}
set
{
this.SetValue("WhyJoinPAEW", value);
lblWhyJoinPAEW.Text = value;
}
}
public string UploadCV
{
get
{
return DataHelper.GetNotEmpty(GetValue("UploadCV"), ResHelper.LocalizeString("{$GPAUploadCV$}"));
}
set
{
this.SetValue("UploadCV", value);
lblUploadCV.Text = value;
}
}
public string Certificates
{
get
{
return DataHelper.GetNotEmpty(GetValue("Certificates"), ResHelper.LocalizeString("{$GPACertificates$}"));
}
set
{
this.SetValue("Certificates", value);
lblCertificates.Text = value;
}
}
protected void SetupControl()
{
if (this.StopProcessing)
{
// Do not process
rfvName.Enabled = false;
rfvDOB.Enabled = false;
rfvEmail.Enabled = false;
revEmail.Enabled = false;
rfvGSMNumber.Enabled = false;
revMobile.Enabled = false;
rvGrade.Enabled = false;
rfvGrade.Enabled = false;
rvExpectGraduateDate.Enabled = false;
rfvExpectGraduateDate.Enabled = false;
rfvUniversity.Enabled = false;
rfvWhyJoinPAEW.Enabled = false;
// rfvUploadCV.Enabled = false;
// rfvCertificates.Enabled = false;
}
else
{
// Set texts
lblName.Text = this.NameText;
lblDOB.Text = this.DOBText;
btnOk.Text = this.Submit;
lblGender.Text = this.Gender;
lblEmail.Text = this.Email;
lblGSMNumber.Text = this.GSMNumber;
lblGrade.Text = this.Grade;
lblExpectGraduateDate.Text = this.ExpectGraduateDate;
lblUniversity.Text = this.University;
lblStudyArea.Text = this.StudyArea;
lblSpecialization.Text = this.Specialization;
lblWhyJoinPAEW.Text = this.WhyJoinPAEW;
lblUploadCV.Text = this.UploadCV;
lblCertificates.Text = this.Certificates;
//lddSpecialization.Items.Insert(0, new ListItem(ResHelper.GetString(ResHelper.LocalizeString("{$GPASpecialization$}"),CultureHelper.GetPreferredCulture())));
// BizForm1.OnAfterSave += new BizForm.OnAfterSaveEventHandler(GetGender());
// ObjectEvents.Insert.After += new EventHandler<ObjectEventArgs>(Insert_After);
// Set required field validators texts
rfvName.ErrorMessage = ResHelper.GetString("GPArfv");
rfvDOB.ErrorMessage = ResHelper.GetString("GPArfv");
rfvEmail.ErrorMessage = ResHelper.GetString("GPArfv");
revEmail.ErrorMessage = ResHelper.GetString("GPArfv");
rfvGSMNumber.ErrorMessage = ResHelper.GetString("GPArfv");
revMobile.ErrorMessage = ResHelper.GetString("GPArevMobile");
rvGrade.ErrorMessage = ResHelper.GetString("GPAGradeLess");
rfvGrade.ErrorMessage = ResHelper.GetString("GPArfv");
rvExpectGraduateDate.ErrorMessage = ResHelper.GetString("GPArvExpectGraduateDate");
rfvExpectGraduateDate.ErrorMessage = ResHelper.GetString("GPArfv");
rfvUniversity.ErrorMessage = ResHelper.GetString("GPArfv");
rfvWhyJoinPAEW.ErrorMessage = ResHelper.GetString("GPArfv");
// rfvUploadCV.ErrorMessage = ResHelper.GetString("Webparts_Membership_RegistrationForm.rfvLastName");
// rfvCertificates.ErrorMessage = ResHelper.GetString("Webparts_Membership_RegistrationForm.rfvLastName");
// Set SkinID
if (!this.StandAlone && (this.PageCycle < PageCycleEnum.Initialized))
{
SetSkinID(this.SkinID);
}
}
}
void SetSkinID(string skinId)
{
if (skinId != "")
{
lblName.SkinID = skinId;
lblDOB.SkinID = skinId;
}
}
public override void OnContentLoaded()
{
base.OnContentLoaded();
SetupControl();
}
/// <summary>
/// Reloads data
/// </summary>
public override void ReloadData()
{
base.ReloadData();
SetupControl();
}
/////////////////// Append Gender Radio List ///////////////////
private void GetGender()
{
Dictionary<string, string> Genderdic = new Dictionary<string, string>();
Genderdic.Add("1", "Male"); Genderdic.Add("2", "Female");
rvGender.DataSource = Genderdic;
rvGender.DataValueField = "Key";
rvGender.DataTextField = "Value";
rvGender.DataBind();
rvGender.SelectedValue = "1";
}
/////////////////// Append Gender Radio List ///////////////////
private void GetUniversity()
{
Dictionary<string, string> Universitydic = new Dictionary<string, string>();
Universitydic.Add("1", "Sultan Qaboos University"); Universitydic.Add("2", "Higher College of Technology"); Universitydic.Add("3", "Other");
ddlUniversity.DataSource = Universitydic;
ddlUniversity.DataValueField = "Key";
ddlUniversity.DataTextField = "Value";
ddlUniversity.DataBind();
}
private void GetStudyArea()
{
Dictionary<string, string> StudyAreadic = new Dictionary<string, string>();
StudyAreadic.Add("1", "Engineering"); StudyAreadic.Add("2", "Business");
rblStudyArea.DataSource = StudyAreadic;
rblStudyArea.DataValueField = "Key";
rblStudyArea.DataTextField = "Value";
rblStudyArea.DataBind();
rblStudyArea.SelectedValue = "1";
}
private void GetSpecializationEng()
{
Dictionary<string, string> Specializationdic = new Dictionary<string, string>();
if (rblStudyArea.SelectedValue == "1")
{
Specializationdic.Add("1", "Mechanical"); Specializationdic.Add("2", "Instrumentation"); Specializationdic.Add("3", "Civil"); Specializationdic.Add("4", "Chemistry"); Specializationdic.Add("5", "Water Resources"); Specializationdic.Add("6", "Other");
}
else
{
Specializationdic.Add("1", "Finance"); Specializationdic.Add("2", "HR"); Specializationdic.Add("3", "Communication"); Specializationdic.Add("4", "BA"); Specializationdic.Add("5", "Other");
}
lddSpecialization.DataSource = Specializationdic;
lddSpecialization.DataValueField = "Key";
lddSpecialization.DataTextField = "Value";
lddSpecialization.DataBind();
lddSpecialization.SelectedValue = "1";
}
protected void ddlUniversity_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlUniversity.SelectedValue == "3")
{ txtUniversity.Visible = true;}
else
{ txtUniversity.Visible = false;}
}
protected void rblStudyArea_SelectedIndexChanged(object sender, EventArgs e)
{
GetSpecializationEng();
}
protected void lddSpecialization_SelectedIndexChanged(object sender, EventArgs e)
{
if (rblStudyArea.SelectedValue == "1")
{
if (lddSpecialization.SelectedValue == "6")
{ txtSpecialization.Visible = true; }
else
{ txtSpecialization.Visible = false; }
}
else
{
if (lddSpecialization.SelectedValue == "5")
{ txtSpecialization.Visible = true; }
else
{ txtSpecialization.Visible = false; }
}
}
protected void btnOk_Click(object sender, EventArgs e)
{
if ((this.PageManager.ViewMode == ViewModeEnum.Design) || (this.HideOnCurrentPage) || (!this.IsVisible))
{
// Do not process
}
else
{
rfvName.Validate();
rfvDOB.Validate();
rfvEmail.Validate();
revEmail.Validate();
rfvGSMNumber.Validate();
revMobile.Validate();
rvGrade.Validate();
rfvGrade.Validate();
rvExpectGraduateDate.Validate();
rfvExpectGraduateDate.Validate();
rfvUniversity.Validate();
rfvWhyJoinPAEW.Validate();
Page.Validate();
//if (Page.IsValid)
//{
String siteName = SiteContext.CurrentSiteName;
#region "Banned IPs"
// Ban IP addresses which are blocked for registration
if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration))
{
lblError.Visible = true;
lblError.Text = GetString("banip.ipisbannedregistration");
return;
}
#endregion
BizFormInfo formObject = BizFormInfoProvider.GetBizFormInfo("GraduateProgramApplication", SiteContext.CurrentSiteID);
if (formObject != null)
{
DataClassInfo formClass = DataClassInfoProvider.GetDataClassInfo(formObject.FormClassID);
if (formClass != null)
{
BizFormItemProvider bProvider = new BizFormItemProvider();
BizFormItem rec = BizFormItem.New(formClass.ClassName, null);
DateTime Applicant_DOB = DateTime.ParseExact(txtDOB.Text.Trim(), "dd/MM/yyyy", null);
DateTime Applicant_ExpectGraduateDate = DateTime.ParseExact(txtExpectGraduateDate.Text.Trim(), "MM/dd/yyyy", null);
rec.SetValue("FullName", txtName.Text.Trim());
rec.SetValue("DOB", Applicant_DOB);
rec.SetValue("Gender", rvGender.SelectedItem.Text.Trim());
rec.SetValue("Email", txtEmail.Text.Trim());
rec.SetValue("GSMNumber", txtGSMNumber.Text.Trim());
rec.SetValue("Grade", txtGrade.Text.Trim());
rec.SetValue("ExpectGraduateDate", Applicant_ExpectGraduateDate);
rec.SetValue("University", ddlUniversity.SelectedItem.Text.Trim());
rec.SetValue("StudyArea", rblStudyArea.SelectedItem.Text.Trim());
rec.SetValue("Specialization", lddSpecialization.SelectedItem.Text.Trim());
rec.SetValue("WhyPAEW", txtWhyJoinPAEW.Text.Trim());
// rec.SetValue("UploadCV", duUploadCV.InnerAttachmentGUID);
// BasicForm.Data.GetValue("answerText"), "");
rec.SetValue("FormInserted", DateTime.Now);
rec.SetValue("FormUpdated", DateTime.Now);
rec.Insert();
BizFormInfoProvider.RefreshDataCount(formObject.FormName, formObject.FormSiteID);
}
}
string test = "Hello";
Response.Write("<script>alert('" + test + "');</script>");
}
}
}
I think you'll need to trigger the direct uploader to save the file somehow, before it will give you a GUID - I'm not completely familiar with how it works because I've never used it outside of the context of the Kentico form engine.
That being said, I think that the Forms module in Kentico would do everything that I can see you're trying to do here without you needing to write custom code.
Whenever I create a form in Kentico I try to leverage the forms module as much as possible.
I would recommend reading through the documentation for the forms module for whichever version of Kentico you're using to try create the form through the User Interface, and then asking questions if you get stuck on something through that process - unless there's something custom that I've misunderstood.

Calling Stored procedure inside a thread to update multiple records

I am trying to calla stored procedure for various unique entities . The stored procedure for a single entity takes about 33 secs. So I decided to call it using threads.
Here are some of trials I have done :
public bool ExecuteTaxRateLinkingParallel(int mapID, int createdBy)
{
try
{
int snapshotID = (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]);
List<TaxEntity> taxEntities = new List<TaxEntity>();
List<Task> tasks = new List<Task>();
using (var ctx = new TopazDbContainer())
{
taxEntities = ctx.TaxEntities.AsParallel().Where(t => t.IsActive == true).ToList<TaxEntity>();
}
Parallel.ForEach<TaxEntity>(taxEntities, (entity) =>
{
//SqlConnection connection; SqlTransaction trans; SqlCommand command;
// break this into pieces of 5
var task = Task.Factory.StartNew(() =>
{
using (var pctx = new TopazDbContainer())
{
try
{
int taxEntityID = entity.TaxEntityID;
pctx.CommandTimeout = 5000;
//string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TOPAZDBConnectionStringParallel"].ConnectionString;
//connection = new SqlConnection(connectionString);
//command = new SqlCommand("dbo.[Usp_TaxRatesLinkingParallel]", connection);
//trans = connection.BeginTransaction();
//command.CommandType = CommandType.StoredProcedure;
//command.Parameters.AddWithValue("#MapID", mapID);
//command.Parameters.AddWithValue("#UserID", createdBy);
//command.Parameters.AddWithValue("#TaxEntityID", taxEntityID);
//command.Parameters.AddWithValue("#SnapshotID", snapshotID);
//connection.Open();
//command.CommandTimeout = 5000;
//command.ExecuteReader().AsParallel();
pctx.ContextOptions.LazyLoadingEnabled = true;
//pctx.ExecuteStoreCommand("Exec [Usp_TaxRatesLinkingParallel] #MapID={0},#UserID={1},#TaxEntityID={2},#SnapshotID{3}", new SqlParameter("MapID", mapID), new SqlParameter("UserID", createdBy), new SqlParameter("TaxEntityID", taxEntityID), new SqlParameter("SnapshotID", snapshotID));
var param = new DbParameter[] { new SqlParameter("UserID", createdBy), new SqlParameter("TaxEntityID", taxEntityID), new SqlParameter("SnapshotID", snapshotID) };
pctx.ExecuteStoreCommand("Exec [Usp_TaxRatesLinkingParallel] #MapID,#UserID,#TaxEntityID,#SnapshotID", param);
//var result = output.FirstOrDefault();
}
catch (TaskCanceledException tx)
{
}
catch (Exception e)
{
}
finally
{
pctx.SaveChanges();
pctx.Connection.Close();
}
}
}, TaskCreationOptions.PreferFairness);
tasks.Add(task);
try
{
Task.WaitAll(tasks.ToArray());
}
catch (AggregateException ae)
{
ae.Handle((x) =>
{
if (x is UnauthorizedAccessException)
{
return true;
}
else
{
return false;
}
});
}
catch (Exception ex)
{
throw ex;
}
});
return true;
}
catch (Exception ex)
{
TopazErrorLogs.AddTopazErrorLogBL(ex, 1, 1);
throw new TopazCustomException(GlobalConstant.errorMessage);
}
}
For some the above statements the SP seems like it runs fine but when I check from the application or from backend the records doesn't get updated.
Need help!
If you are not on .NET 4.5 yet, you can use these extension methods to execute your commands async.
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using System.Xml;
namespace System.Data.SqlClient
{
public static class SqlCommandExtensions
{
public static Task<SqlDataReader> ExecuteReaderAsync(this SqlCommand command)
{
Contract.Requires(command != null);
return ExecuteReaderAsync(command, null);
}
public static Task<SqlDataReader> ExecuteReaderAsync(this SqlCommand command, object state)
{
Contract.Requires(command != null);
return Task.Factory.FromAsync<SqlDataReader>(command.BeginExecuteReader, command.EndExecuteReader, state);
}
public static Task<XmlReader> ExecuteReaderXmlAsync(this SqlCommand command)
{
Contract.Requires(command != null);
return ExecuteReaderXmlAsync(command, null);
}
public static Task<XmlReader> ExecuteReaderXmlAsync(this SqlCommand command, object state)
{
Contract.Requires(command != null);
return Task.Factory.FromAsync<XmlReader>(command.BeginExecuteXmlReader, command.EndExecuteXmlReader, state);
}
public static Task<int> ExecuteNonQueryAsync(this SqlCommand command)
{
Contract.Requires(command != null);
return ExecuteNonQueryAsync(command, null);
}
public static Task<int> ExecuteNonQueryAsync(this SqlCommand command, object state)
{
Contract.Requires(command != null);
return Task.Factory.FromAsync<int>(command.BeginExecuteNonQuery, command.EndExecuteNonQuery, state);
}
}
}
It is not an asynchronous database query that you are doing here. Please have a look:
Asynchronous Database Calls With Task-based Asynchronous Programming Model (TAP) in ASP.NET MVC 4
Here is an example of an asynchronous database call with new async / await features:
public async Task<IEnumerable<Car>> GetCarsAsync() {
var connectionString =
ConfigurationManager.ConnectionStrings["CarGalleryConnStr"].ConnectionString;
var asyncConnectionString = new SqlConnectionStringBuilder(connectionString) {
AsynchronousProcessing = true
}.ToString();
using (var conn = new SqlConnection(asyncConnectionString)) {
using (var cmd = new SqlCommand()) {
cmd.Connection = conn;
cmd.CommandText = selectStatement;
cmd.CommandType = CommandType.Text;
conn.Open();
using (var reader = await cmd.ExecuteReaderAsync()) {
return reader.Select(r => carBuilder(r)).ToList();
}
}
}
}
You may find the detailed info inside the blog post.

Resources