I like the fact that Subsonic automatically updates my audit field "CreatedOn" but it seems to only do it in server time. Is there a way to instruct Subsonic to save the audit dates as UTC instead?
There is a setting in the provider useUTC="true"
But it's so long ago I can't remember if it works.
<SubSonicService defaultProvider="TAProvider"
templateDirectory="..\..\ExternalResources\SubSonicCustomTemplates">
<providers>
<clear/>
<add name="TAProvider" type="SubSonic.SqlDataProvider, SubSonic"
connectionStringName="TA" generatedNamespace="TA.DAL" useUTC="true"
useSPs="false" generateLazyLoads="false"/>
</providers>
</SubSonicService>
For me, if a field is ever UTC time I always call it xxxUTC just cause I get terribly confused with anything to do with timezones, so I modified the Controller template Save method as below. Basically just check for the column and set it as required...
<%=tbl.ClassName %> oldItem = null;
if (item.<%=tbl.PrimaryKey.PropertyName%> != <%=emptyVariableText%>)
oldItem = new <%=tbl.ClassName %>(item.<%=tbl.PrimaryKey.PropertyName%>);
if (item.<%=tbl.PrimaryKey.PropertyName%> == <%=emptyVariableText%>)
{
item.IsNew = true;
<% if (tbl.Columns.Contains("CreatedOnUTC"))
{
%> item.CreatedOnUTC = DateTime.UtcNow;
<% }
if (tbl.Columns.Contains("CreatedOn")) // just checking
{
%> error: createdon column. fix and rerun template
<% }
if (tbl.Columns.Contains("CreatedByID"))
{
%> item.CreatedByID = taUser.telUser.TelUserID;
<% }
%>
}
<% if (tbl.Columns.Contains("ModifiedOnUTC"))
{
%> item.ModifiedOnUTC = DateTime.UtcNow;
<%}
if (tbl.Columns.Contains("ModifiedByID"))
{
%> item.ModifiedByID = taUser.telUser.TelUserID;
<% }
%>
try
{
Related
I am developing a datatable in Ruby on Rails, but I don't understand how to translate mysql datetime into normal date notation within the datatable when rending the view.
Roughly, I have my table view that imports the columns.
<div class="content-main">
<table id="customer-grid" data-grid-name="Customers List" data-available-columns='[<%=raw(#grid_fields.map{|fieldcaption,fieldname| '"'<<fieldcaption<<'"'}.join(",") )%>]' data-column_scaling='<%=raw(#grid_fields_scaling.map{|fieldcaption,scale| scale}.join(",") )%>' >
<thead>
<tr>
<% #grid_fields_visible.each do |fieldcaption,fieldname|%>
<th><%=fieldcaption%></th>
<%end%>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
The columns list is given by the controller of the page.
#grid_fields=#grid_service.get_grid_fields
#grid_fields_visible =#grid_service.get_grid_fields_visible
that brings to the actual list in the service folder.
def get_grid_fields
return {
"Company Name" =>"name",
"Contact Name" =>"contact_name",
"Address" =>"address_1",
"Post Code" =>"postcode",
"Telephone" =>"tel",
"Primary Email" =>"email",
"WWW" =>"www",
"Created by" =>"created_by",
"Date Created" =>"created_at",
"Modified by" =>"modified_by",
"Date modified" =>"modified_at"
}
end
The mysql connection is given by a module:
module CustomerLegacyShim extend ActiveSupport::Concern
included do
self.table_name = "tblcustomers"
...
alias_attribute :created_by, :tblCustomer_CreatedBy
alias_attribute :created_at, :tblCustomer_CreatedAt
alias_attribute :modified_by, :tblCustomer_ModifiedBy
alias_attribute :modified_at, :tblCustomer_ModifiedAt
...
end
end
To go to the point, everything works great. The only problem is that I have a really incomprehensible DateTime, and I don't understand what to change to make it %d/%m/%Y within the table.
The fact is that I completely have no idea where to put .strftime() or .strptime(), as I can only give the "column name" to the datatable and I don't know how to change the format of the retrieved data.
Can anybody teach me?
Luca
You can use to_s(:db) to convert into a database friendly format.
Time.now.to_s(:db)
However, timezone specified in Rails because the time will be stored in UTC in the database. You'll need to specify that to do proper comparisons.
Time.now.to_s(:db)
You can simply use to_date to get a Date object.
time = Time.now
date = time.to_date
Then you can use strftime to get the output you need:
date.strftime('%a %d %b %Y') #=> "Sun 04 Feb 2001"
Or in the format that you need:
date.strftime('%d/%m/%Y') #=> "02/06/2016"
Here is the doc for the Date class: link
And more info on strftime format: link
Now let say I have this in a controller:
#my_objects = MyObject.all
In the views you can do something like:
<table>
<tr>
<td>Title</td>
<td>Create at</td>
</tr>
<% #my_objects.each do |0| %>
<tr>
<td><%= o.title%></td>
<td><%= o.created_at.to_date.strftime('%d/%m/%Y') %></td>
</tr>
<% end %>
</table>
In the end I had to hard code the datatable column and create a dedicated function within the *.dataTable method in JS:
"columnDefs": [
{
"sClass": "date-long filterdaterangedatetime",
"targets": getColumnIndexFromName('#sage-customers-grid',['Date Created','Date modified']),
"mRender": function (data, type, full) {
if (data != "") {
var date = data.substring(0,10);
var dateParts = date.split("-");
var createDataFormat = dateParts[2] + "/" + dateParts[1] + "/" + dateParts[0];
return createDataFormat;
} else {
return "";
}
}
}
]
could anyone tell me why does my rails application returns this piece of code when I do a select statement?
#<Driver:0x22ef3f0>
The select statement is:
current_schedule_record = {
'driver_name' => Driver.where(['id = ?', id]).select('first_name').first
}
and the view is:
<% #trucks.each do |truck| %>
<% record = ScheduleController.schedule_record(truck.id) %>
<tr>
<td><%= truck.id %></td>
<td><%= record['driver_name'] %></td>
</tr>
<% end %>
From the documentation
Be careful because this also means you're initializing a model object with only the fields that you've selected.
So using select still creates a model object. You need to use something like
current_schedule_record = {
'driver_name' => Driver.where(['id = ?', id]).select('first_name').first.first_name
}
I am trying to check if a value from database table is equal to Char, in the view I tried
the following:
<% if (Model.MethodOfPayment.ToString().Equals("W") == true)
{
%>
Wire
<%} %>
<%else
{ %>
<% if (Model.MethodOfPayment.ToString().Equals("C") == true)
{
%>
Cheque
<%} %>
<%} %>
Did not work!
In the controller to send the output to PDF Form: I tried the following:
string MyString = order.MethodOfPayment.ToString();
if (MyString == "W")
{
pdfFormFields.SetField("MethodOfPayment", "W");
}
else
{
if (MyString == "W")
{
pdfFormFields.SetField("MethodOfPayment", "C");
}
}
Did not work either.
Thanks in advance.
How about:
if (Model.MethodOfPayment == 'W')
If this doesn't work it simply means that the MethodOfPayment property doesn't equal to the W character. Try debugging your code to see exactly to which value it equals.
Hopefully this question is quick and painless
I have a mvc view where i want to display either one of two values depending on an if statement. This is what I have in the view itself:
<%if (model.CountryId == model.CountryId) %>
<%= Html.Encode(model.LocalComment)%>
<%= Html.Encode(model.IntComment)%>
If true display model.LocalComment, if false display model.IntComment.
This doesn't work as I get both values showing. What am I doing wrong?
Your if statement always evaluates to true. You are testing whether model.CountryId equals model.CountryId which is always true: if (model.CountryId == model.CountryId). Also you are missing an else statement. It should be like this:
<%if (model.CountryId == 1) { %>
<%= Html.Encode(model.LocalComment) %>
<% } else if (model.CountryId == 2) { %>
<%= Html.Encode(model.IntComment) %>
<% } %>
Obviously you need to replace 1 and 2 with the proper values.
Personally I would write an HTML helper for this task to avoid the tag soup in the views:
public static MvcHtmlString Comment(this HtmlHelper<YourModelType> htmlHelper)
{
var model = htmlHelper.ViewData.Model;
if (model.CountryId == 1)
{
return MvcHtmlString.Create(model.LocalComment);
}
else if (model.CountryId == 2)
{
return MvcHtmlString.Create(model.IntComment);
}
return MvcHtmlString.Empty;
}
And then in your view simply:
<%= Html.Comment() %>
Aside from Darin's point about the condition always being true, you might want to consider using the conditional operator:
<%= Html.Encode(model.CountryId == 1 ? model.LocalComment : model.IntComment) %>
(Adjust for whatever your real condition would be, of course.)
Personally I find this easier to read than the big mixture of <% %> and <%= %>.
Conditional Rendering in Asp.Net MVC Views
<% if(customer.Type == CustomerType.Affiliate) %>
<%= this.Html.Image("~/Content/Images/customer_affiliate_icon.jpg")%>
<% else if(customer.Type == CustomerType.Preferred) %>
<%= this.Html.Image("~/Content/Images/customer_preferred_icon.jpg")%>
<% else %>
<%= this.Html.Image("~/Content/Images/customer_regular_icon.jpg")%>
Asp.net Mvc1
On my Views/home/Index.aspx which routes from http://localhost/DefectSeverityAssessmentMvcBeta/
This renders
Response.Write("<a href=\"");
Response.Write(Url.Action("Create", "Registration"));
Response.Write("\">Begin Registration</a>");
But returns a 404 for the address of the link http://localhost/DefectSeverityAssessmentMvcBeta/Registration/Create
while this Does not render or show in view source but doesn't cause any exception:
Html.ActionLink("Begin Registration", "Create", "Registration");
I have a RegistrationController and a /Views/Registration/Create.aspx
The registration controller has breakpoints on Index() and Create() but they are not being hit.
I'm not sure how I would use <%= %> in this scenario because it's inside the following code block:
<% if (ViewData.ContainsKey("user"))
{
if (ViewData.ContainsKey("registered") && (bool)ViewData["registered"] == true)
{
//Html.RouteLink("Resume Assessment", "Assessment", new { controller = "Assessment", action = "Index" });
Response.Write("<a href=\"");
// Html.ActionLink("Resume Assessment", "Index", "Assessment");
Response.Write("\">Resume Assessment</a>");
}
else
{
//Html.RouteLink("Begin", "Registration", new { controller = "Registration", action = "Edit" });
// Html.ActionLink("Begin Registration", "Create", "Registration");
Html.RouteLink("Begin", "Default", new { controller = "Registration", action = "Edit" });
//Response.Write("<a href=\"");
//Response.Write(Url.Action("Create", "Registration"));
//Response.Write("\">Begin Registration</a>");
}
}
else
{ Response.Write("Authentication failed"); }
%>
Are you using <% %> in the HTML for both Response.Write and Html.ActionLink? Try using <%= %> for Html.ActionLink(...);
The added equal sign calls Response.Write behind the scenes thus writing you code to the screen.
Because Html.ActionLink return the string and do not write to the response stream. You need to write to your page using <%= %> or Response.Write();
Response.Write(Html.ActionLink("Begin Registration", "Create", "Registration"));
I was not making use of the ability to use
<% if(x) {%> <%=Html.ActionLink(...)%><% } %>
Thanks to Charles Conway I got it working. Here's the code I wound up with:
<div class="entry">
<% if (ViewData.ContainsKey("user"))
{
if (ViewData.ContainsKey("registered") && (bool)ViewData["registered"] == true)
{ %>
<%=Html.ActionLink("Resume Assessment", "Index", "Assessment") %>
<% }
else
{ %> <%=Html.ActionLink("Begin Registration", "Create", "Registration") %>
<%
}
}
else
{ Response.Write("Authentication failed"); }
%></div>
Are you using an equals sign in your context switch, like this?
<%= Html.ActionLink("Begin Registration", "Create", "Registration"); %>
^--needs equals sign here
If you're not using an equals sign, you have to write directly to the Response object.
As far as the routing errors go, you can check out your routes using Phil Haack's diagnostic tool at http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx.
Anything less than IIS7 requires special configuration for the routing.