Asp.net , to_date Function - asp.net

I want to update record in oracle db. But it gives me error "date format picture ends before converting..." I uses to_date function. datatype of column is DATE.
Here is my query
var updateddate = DateTime.Now;
var testing= this.hidvalue.Value;
var idrow = id.Text;
var anserrow = lblanswer.Text;
var weightpwd = lblweighted.Text;
var solvetimerow =lblsolvetime.Text;
var updatedby = Session["Name"];
string queryDuppass = "Update ADU.QAT_DATA set Question='" + idrow + "',Answer='" + anserrow + "', Question_Weighted='" + weightpwd + "', Resolve_Estimated_Time='" + solvetimerow + "', Updated_By='" + updatedby + "', Updated_Date= to_date('" + updateddate + "','mm-dd-yyyy hh12:mi:ss'" + ")" + " where ID='" + testing + "'";

Related

Please Verify My ASP.NET Code to insert data to oracle database

No matter what I do the following code does not seem to work. It always breaks at ExecuteNonQuery().
Anything I am missiong?
Always throws
System.InvalidOperationException: 'Operation is not valid due to the current state of the object.'
protected void Submit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
OracleConnection conn = new OracleConnection(connectionString);
int room_id = Int32.Parse(DropDownList2.SelectedValue);
int activity_id = Int32.Parse(DropDownList1.SelectedValue);
string session_code = TextBox1.Text;
int start_time = GetTimeSeconds(startTime.Text);
int period = GetTimeSeconds(duration.Text);
string book_date = bookDate.Text;
string ref_no = DropDownList3.SelectedValue;
conn.Open();
using (OracleCommand cmd = new OracleCommand(
"insert into BRAZESH.ALL_SESSION(SESSION_CODE,START_TIME,\"PERIOD\",BOOKED_DATE,ROOM_ID,ACTIVITY_ID,REF_NO)" +
" values ('" + session_code + "'," + start_time + "," + period + ",to_date('" + book_date + "', 'yyyy-mm-dd')," + room_id + "," + activity_id + ", '" + ref_no + "')"))
{
try
{
cmd.ExecuteNonQuery();
}catch (OracleException ex)
{
throw ex;
}
}
}
}
You are not using conn while defining the connection to be used by the command. use the following line. Read details on usage here
using (OracleCommand cmd = new OracleCommand(
"insert into BRAZESH.ALL_SESSION(SESSION_CODE,START_TIME,\"PERIOD\",BOOKED_DATE,ROOM_ID,ACTIVITY_ID,REF_NO)" +
" values ('" + session_code + "'," + start_time + "," + period + ",to_date('" + book_date + "', 'yyyy-mm-dd')," + room_id + "," + activity_id + ", '" + ref_no + "')",conn))

Duplicate entry of same record in database

I have one form which takes lot of input data from users including image. Data inserts properly in table but it makes duplicate entry of same record in datatable. Please help I don't understand why it's taking duplicate entry of same data.
Private Sub save_Click(sender As Object, e As EventArgs) Handles save.Click
Dim name, businessCategory, subcategory, conPerson, website, email, phoneNo1, phoneNo2, mobileNumber, building, street, landpoint, area, city, stateName, zipCode, about, reg, foundationDate, founder, genBeds, icuBeds, mondayIn, mondayOut, tuesdayIn, tuesdayOut, wedIn, wedOut, thursdayIn, thursdayOut, fridayIn, fridayOut, saturdayIn, saturdayOut, sundayIn, sundayOut, visitIn, visitOut, fees, bestFor As String
name = businessName.Text
businessCategory = businessCat.Text
subcategory = subCat.SelectedItem.ToString
conPerson = contactPerson.Text
website = websiteName.Text
email = emailName.Text
phoneNo1 = phone1.Text
phoneNo2 = phone2.Text
mobileNumber = mobile.Text
building = buildingName.Text
street = address.Text
landpoint = landmark.Text
area = areaName.Text
city = suburb.Text
stateName = state.Text
zipCode = zip.Text
about = overview.Text
reg = regNo.Text
foundationDate = foundation.Text
founder = founderName.Text
genBeds = GeneralBeds.Text
icuBeds = ICU.Text
mondayIn = mondayFrom.SelectedItem.ToString
mondayOut = mondayTo.SelectedItem.ToString
tuesdayIn = tuesdayFrom.SelectedItem.ToString
tuesdayOut = tuesdayTo.SelectedItem.ToString
wedIn = wedFrom.SelectedItem.ToString
wedOut = wedTo.SelectedItem.ToString
thursdayIn = thursdayFrom.SelectedItem.ToString
thursdayOut = thursdayTo.SelectedItem.ToString
fridayIn = fridayFrom.SelectedItem.ToString
fridayOut = fridayTo.SelectedItem.ToString
saturdayIn = saturdayFrom.SelectedItem.ToString
saturdayOut = saturdayTo.SelectedItem.ToString
sundayIn = sundayFrom.SelectedItem.ToString
sundayOut = sundayTo.SelectedItem.ToString
visitIn = visitFrom.SelectedItem.ToString
visitOut = visitTo.SelectedItem.ToString
fees = consultinfees.Text
bestFor = bestknowFor.Text
Try
Dim filename As String = Path.GetFileName(profileDP.PostedFile.FileName)
profileDP.SaveAs(Server.MapPath("assets/images/hospitals/" + filename))
con.Open()
Dim str1 As String = "INSERT INTO hospitals (`name`, `category`, `subcategory`, `contactPerson`, `websiteName`, `email`, `phone1`, `phone2`, `mobileNumber`, `buildingName`, `streetName`, `landmark`, `areaName`, `city`, `State`, `zipCode`, `thumbnail`, `consultancyFees`, `overview`, `Founder`, `establishment`, `registration`, `generalBed`, `icuBed`, `mondayFrom`, `mondayTo`, `tuesdayFrom`, `tuesdayTo`, `wednesdayFrom`, `wednesdayTo`, `thursdayFrom`, `thursdayTo`, `fridayFrom`, `fridayTo`, `saturdayFrom`, `saturdayTo`, `sundayFrom`, `sundayTo`, `visitFrom`, `visitTo`, `bestKnownFor`, `status`) values ('" + name + "', '" + businessCategory + "', '" + subcategory + "', '" + conPerson + "', '" + website + "', '" + email + "', '" + phoneNo1 + "', '" + phoneNo2 + "', '" + mobileNumber + "', '" + building + "', '" + street + "', '" + landpoint + "', '" + area + "', '" + city + "', '" + stateName + "', '" + zipCode + "', 'list-business/assets/images/hospitals/" + filename + "', '" + fees + "', '" + about + "', '" + founder + "', '" + foundationDate + "', '" + reg + "', '" + genBeds + "', '" + icuBeds + "', '" + mondayIn + "', '" + mondayOut + "', '" + tuesdayIn + "', '" + tuesdayOut + "', '" + wedIn + "', '" + wedOut + "', '" + thursdayIn + "', '" + thursdayOut + "', '" + fridayIn + "', '" + fridayOut + "', '" + saturdayIn + "', '" + saturdayOut + "', '" + sundayIn + "', '" + sundayOut + "', '" + visitIn + "', '" + visitOut + "', '" + bestFor + "', 'active' )"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.Parameters.AddWithValue("#Content_Type", "assets/images/hospitals/" + filename)
command.ExecuteNonQuery()
str2 = command.ExecuteReader
con.Close()
Response.Write("Hospital added successfully!")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Please pick only one between command.ExecuteNonQuery() or str2 = command.ExecuteReader.
ExecuteReader used for getting the query results as a DataReader
object. It is readonly forward only retrieval of records and it uses
select command to read through the table from the first to the last.
ExecuteNonQuery used for executing queries that does not return any
data. It is used to execute the sql statements like update, insert,
delete etc. ExecuteNonQuery executes the command and returns the
number of rows affected. - from this site
I don't see why you should use ExecuteReader if you're just going to insert a record.
Cheers!
You should use only ExecuteNonQuery() and only once if you are using INSERT,UPDATE,DELETE statements.
ExecuteReader() is for retrieving records from database table.
You are doing both and thats why its inserting twice.

Forward Slash is removed in path

I have set the html from code behind in ItemDataBound event of repeater but in html path is not right.
Dim video_path = imgUrl + VideoPath + VideoName.split(".")(0) + ".mp4"
Dim poster_path = imgUrl + VideoPath + VideoName.split(".")(0) + ".png"
Dim DvVidContent As HtmlContainerControl = CType(e.Item.FindControl("DvVidContent"), HtmlContainerControl)
Dim onclick = "'ShowVideoDialog('size_vp_" + count.ToString() + "', '" + video_path.ToString().Trim() + "');'"
Dim Header As String = "<div style='position:relative;' Sequence='" + count.ToString() + "' id='" + ID.ToString() + "' class='SessionFolderViewChild'><img onerror='handleError(this);' src='" + poster_path.ToString() + "' alt='Thumbnail'/><img class='dv_play_icon' onclick='" + onclick + "' id='PlayVideo' style='position:absolute;top:8px;left:26px;height:100px;width:100px;' src='../../Images/icn_Play.png'/></a></div>"
DvVidContent.InnerHtml = Header.Trim()
count = count +
After Html rendering its remove the forward slash and look like
onclick="ShowVideoDialog("size_vp_1','.. .. resources sbs attachments steps351 step565 130906720751358852.mp4');

Telerik Grid Filter not working on Date column

I have a Telerik Grid with one of the column having Date Time values, but the filter on that field is not working as the filter only accepts date by default.
Is there any way we can have the time included in the telerik grid filter?
Here is my code:
Html.Telerik().Grid()
.Name("FilesGrid")
.Sortable(sorting => sorting.OrderBy(sortOrder => sortOrder.Add(o => o.COL1)))
.Pageable(paging =>
paging.PageSize(10)
.Style(GridPagerStyles.NextPreviousAndNumeric)
.Position(GridPagerPosition.Bottom)
).Filterable()
.Groupable()
.Selectable()
.Resizable(c => c.Columns(true))
.DataBinding(dataBinding => dataBinding.
Ajax()
.Select("_Grid", "Files")
.Update("_ClientUpdate", "Todos")
.Insert("_ClientInsert", "Todos")
.Delete("Delete", "Files"))
.EnableCustomBinding(true)
.Columns(columns =>
{
columns.Bound(c => c.col1);
columns.Bound(c => c.col2);
columns.Bound(c => c.col3);
columns.Bound(c => c.CreatedAt); -------- this column is datetime but filter only has date calendar , hence the filter wont work
.ClientEvents(events => events.OnDataBound("onGridDataBound"))
%>
I know it's an old post but I will put a solution for those people search for it
I have customized this solution, it works with all scenarios and you can use it also if you have more than one column have a date time filter use this function in the need data source event
first put this function in your code
Protected Sub manageDateFilter(ByVal columnName As String, ByVal source As Object, ByVal filter As String, ByVal columnindex As Integer)
Select Case DirectCast(DirectCast(source, Telerik.Web.UI.RadGrid).Columns.Item(columnindex), Telerik.Web.UI.GridDateTimeColumn).CurrentFilterFunction
Case GridKnownFunction.EqualTo
Dim date1 As datetime = convert.todatetime(DirectCast(DirectCast(source, Telerik.Web.UI.RadGrid).Columns.Item(columnindex), Telerik.Web.UI.GridDateTimeColumn).CurrentFilterValue)
grdReport.MasterTableView.FilterExpression = filter.replace("([" + columnName + "] = " + filter.substring(filter.indexof(columnName) + (columnName.length + 4)).trim().substring(0, filter.substring(filter.indexof(columnName) + (columnName.length + 4)).indexof("M") + 2) + ")".trim(), "([" + columnName + "] >= '" + date1.tostring() + "') AND ([" + columnName + "] < '" + date1.adddays(1).tostring() + "')")
Case GridKnownFunction.NotEqualTo
Dim date1 As datetime = convert.todatetime(DirectCast(DirectCast(source, Telerik.Web.UI.RadGrid).Columns.Item(columnindex), Telerik.Web.UI.GridDateTimeColumn).CurrentFilterValue)
grdReport.MasterTableView.FilterExpression = filter.replace("([" + columnName + "] <> " + filter.substring(filter.indexof(columnName) + (columnName.length + 4)).trim().substring(0, filter.substring(filter.indexof(columnName) + (columnName.length + 5)).indexof("M") + 2) + ")".trim(), "(([" + columnName + "] < '" + date1.tostring() + "') OR ([" + columnName + "] >= '" + date1.adddays(1).tostring() + "'))")
Case GridKnownFunction.GreaterThanOrEqualTo
Dim date1 As datetime = convert.todatetime(DirectCast(DirectCast(source, Telerik.Web.UI.RadGrid).Columns.Item(columnindex), Telerik.Web.UI.GridDateTimeColumn).CurrentFilterValue)
grdReport.MasterTableView.FilterExpression = filter.replace("([" + columnName + "] >= " + filter.substring(filter.indexof(columnName) + (columnName.length + 4)).trim().substring(0, filter.substring(filter.indexof(columnName) + (columnName.length + 4)).indexof("M") + 2) + ")".trim(), "([" + columnName + "] >= '" + date1.tostring() + "')")
Case GridKnownFunction.LessThanOrEqualTo
Dim date1 As datetime = convert.todatetime(DirectCast(DirectCast(source, Telerik.Web.UI.RadGrid).Columns.Item(columnindex), Telerik.Web.UI.GridDateTimeColumn).CurrentFilterValue)
grdReport.MasterTableView.FilterExpression = filter.replace("([" + columnName + "] <= " + filter.substring(filter.indexof(columnName) + (columnName.length + 4)).trim().substring(0, filter.substring(filter.indexof(columnName) + (columnName.length + 5)).indexof("M") + 2) + ")".trim(), "([" + columnName + "] <= '" + date1.adddays(1).tostring() + "') ")
Case GridKnownFunction.GreaterThan
Dim date1 As datetime = convert.todatetime(DirectCast(DirectCast(source, Telerik.Web.UI.RadGrid).Columns.Item(columnindex), Telerik.Web.UI.GridDateTimeColumn).CurrentFilterValue)
grdReport.MasterTableView.FilterExpression = filter.replace("([" + columnName + "] > " + filter.substring(filter.indexof(columnName) + (columnName.length + 4)).trim().substring(0, filter.substring(filter.indexof(columnName) + (columnName.length + 4)).indexof("M") + 2) + ")".trim(), "([" + columnName + "] >= '" + date1.adddays(1).tostring() + "') ")
End Select
and then you call it from the need data source event for the grid like this
Dim filter As String = grdReport.MasterTableView.FilterExpression
If (filter.contains("LAST_UPD_DATE")) Then
manageDateFilter("LAST_UPD_DATE", source, filter, 6)
End If
and for multi date column you can use it like this
Dim filter As String = ReportGrid.MasterTableView.FilterExpression
If (filter.contains("START_DATE")) Then
manageDateFilter("START_DATE", source, filter, 5)
End If
filter = ReportGrid.MasterTableView.FilterExpression
If (filter.contains("END_DATE")) Then
manageDateFilter("END_DATE", source, filter, 6)
End If
enjoy :)
protected void ItemsRadGrid_ItemCommand(object source, GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.FilterCommandName)
{
try
{
FillItemsGrid();
FilterByDate(ItemsRadGrid, e);
}
catch (Exception ex)
{
//ExceptionLogClass.InsertError(ex);
}
}
}
public static void FilterByDate(RadGrid grid, GridCommandEventArgs e)
{
Pair filterPair = e.CommandArgument as Pair;
string columnName = Convert.ToString(filterPair.Second);
if (filterPair.First.ToString() == "NoFilter")
{ }
else
{
if (grid.Columns.FindByDataField(columnName).DataType.Name == "DateTime")
{
try
{
TextBox FilterColumnField = ((TextBox)((GridFilteringItem)e.Item)[columnName].Controls[0]);
string oldDate = FilterColumnField.Text;
FilterColumnField.Text = DateTime.ParseExact(FilterColumnField.Text, "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("MM/dd/yyyy 12:00:00 tt");
}
catch (FormatException)
{
e.Canceled = true;
}
}
}
}

How to connect mysql to DevExpress ASPxScheduler without SqlDataSource

I have an ASP.net project I'm looking at and they want to use MySQL. I'm used to SQL server but using mySQL shouldn't be a problem.
Normally the control would like a SqlDataSource to bind to but that's not available with MySQL (from other posts on this site).
What's the best way to connect MySQL and the DevExpress ASPxScheduler so that you can create appointments?
Why not an ObjectDataSource and write the data layer? Or use LLBLGen, I think it works just fine with MySQL. The one caveat I've seen is that the MySQL ODBC and ADO drivers have issues with metadata.
I did end up using the objectdatasource and the ObjectCreated method and wrote the datalayer to insert records into the mysql database. I've included my code just incase someone needs some help with some of the logic.
protected void appointmentsDataSource_ObjectCreated(object sender, ObjectDataSourceEventArgs e)
{
e.ObjectInstance = new CustomEventDataSource(GetCustomEvents());
}
public void InsertAppointment()
{
//need to reformat the dates
string tempStartDate;
string tempStartMinutes;
if (appointmentobject.Start.Minute.ToString().Length == 1)
{
tempStartMinutes = "0" + appointmentobject.Start.Minute.ToString();
}
else
{
tempStartMinutes = appointmentobject.Start.Minute.ToString();
}
tempStartDate = AppointmentObject.Start.Year + "-"
+ AppointmentObject.Start.Month + "-"
+ appointmentobject.Start.Day + " "
+ appointmentobject.Start.Hour + ":"
+ tempStartMinutes;
string tempEndDate;
string tempEndMinutes;
if (appointmentobject.End.Minute.ToString().Length == 1)
{
tempEndMinutes = "0" + appointmentobject.End.Minute.ToString();
}
else
{
tempEndMinutes = appointmentobject.End.Minute.ToString();
}
tempEndDate = AppointmentObject.End.Year + "-"
+ AppointmentObject.End.Month + "-"
+ appointmentobject.End.Day + " "
+ appointmentobject.End.Hour + ":"
+ tempEndMinutes;
//TODO Add CustomField : Need to add to this Insert Statement
//Change the appointment subject
string NewSubject = AppointmentObject.CustomFields["fldFirstName"]
+ ", " + AppointmentObject.CustomFields["fldLastName"]
+ ", " + AppointmentObject.CustomFields["fldClassID"]
+ ", " + AppointmentObject.CustomFields["fldPhoneNumberDay"];
string mySQLQueryString = #"INSERT INTO appointment (StartDate,EndDate,Subject,Status,Description,label,location,Type,FirstName,
LastName,PhoneNumberDay,PhoneNumberEvening,DriversLicenseNumber,Email,RentalCar,Payment,ConfirmationNumber,
PermitNumber,ClassID,CreateDate,CreateUser,NoticeToReport)
VALUES('" + tempStartDate + "','"
+ tempEndDate + "', '"
//+ AppointmentObject.Subject + "',"
+ NewSubject + "',"
+ AppointmentObject.StatusId + ",'"
+ AppointmentObject.Description + "',"
+ AppointmentObject.LabelId + ", '"
+ AppointmentObject.Location + "',"
+ "0, '" //type
+ AppointmentObject.CustomFields["fldFirstName"] + "','"
+ AppointmentObject.CustomFields["fldLastName"] + "','"
+ AppointmentObject.CustomFields["fldPhoneNumberDay"] + "','"
+ AppointmentObject.CustomFields["fldPhoneNumberEvening"] + "','"
+ AppointmentObject.CustomFields["fldDriversLicenseNumber"] + "','"
+ AppointmentObject.CustomFields["fldEmail"] + "',"
+ AppointmentObject.CustomFields["fldRentalCar"] + ","
+ AppointmentObject.CustomFields["fldPayment"] + ",'"
+ AppointmentObject.CustomFields["fldConfirmationNumber"] + "','"
+ AppointmentObject.CustomFields["fldPermitNumber"] + "',"
+ AppointmentObject.CustomFields["fldClassID"] + ", '"
//ignore create date for now.
//+ AppointmentObject.CustomFields["fldCreateDate"] + "', '"
+ "2009-01-01 12:00', '"
+ AppointmentObject.CustomFields["fldCreateUser"] + "', "
+ AppointmentObject.CustomFields["fldNoticeToReport"] + ")";
MySqlConnections test = new MySqlConnections();
test.InsertRow(mySQLQueryString);
}
public class MySqlConnections
{
private static string DriverConnectionString = "Database=driverexam;Data Source=localhost;User Id=ART;Password=art01";
public DataSet SelectRows(DataSet dataset, string query, string tablename)
{
MySqlConnection conn = new MySqlConnection(DriverConnectionString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand(query, conn);
adapter.Fill(dataset, tablename);
conn.Close();
return dataset;
}
public bool InsertRow(string query)
{
// MySqlConnection conn = new MySqlConnection(DriverConnectionString);
MySqlConnection conn = new MySqlConnection();
MySqlCommand cmd = new MySqlCommand();
conn.ConnectionString = DriverConnectionString;
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = query;
cmd.ExecuteNonQuery();
conn.Close();
Console.WriteLine("Success Occurred ");
} //end of try
catch(Exception ex)
{
Console.WriteLine("Error Occurred - " + ex.Message);
}
return true;
}
}

Resources