Deserialization JSON time MVC - c#

i try to get a time from Ajax request dateType json .
the result i get is :
/DATE(1436688000000)/
heres my code :
view:
<div class="col-sm-8">
#Html.DropDownListFor(model => model[i].MovieShowTime.Single().MovieID, SelectMovieID, "Select Movie", new { id = "MovieName", name = "MovieName" })
#Html.DropDownListFor(x => x[i].MovieShowTimeID, Enumerable.Empty<SelectListItem>(), "--Loading Value--", new { id = "ShowTime", name = "ShowTime" })
#Html.ValidationMessageFor(model=>model[i].MovieShowTimeID)
</div>
controller :
public JsonResult GetShowTime(int? MovieID)
{
var data = (from m in db.MovieShowTimes
where m.MovieID == MovieID
select new
{
id = m.MovieShowTimeID,
name = m.ShowTime
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
ajax : .
$(function () {
$('#MovieName').change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetShowTime", "TimeScreening")',
data: { MovieID: $('#MovieName').val() },
dataType : 'json',
success: function (data) {
$('#ShowTime').html('');
//alert(ChangeDateFormat("\/Date(1319266795390+0800)\/"));
$.each(data, function (id, option) {
var name = ChangeDateFormat(option.name)
$('#ShowTime').append($('<option></option>').val(option.id).html(option.name));
});
},
error: function (xhr, ajaxOptions, thrownEror) {
alert("False" + xhr +"..."+ ajaxOptions +"... "+ thrownEror);
}
});
});
});
i see the threds about convert form json to C# datetime but none of them have resolved the problem .
follow by this post:
JSON-Serialization-and-Deserialization-in-ASP-NET this jave me the closet answer , but this in date.
code:
function ChangeDateFormat(jsondate) {
jsondate = jsondate.replace("/Date(", "").replace(")/", "");
if (jsondate.indexOf("+") > 0) {
jsondate = jsondate.substring(0, jsondate.indexOf("+"));
}
else if (jsondate.indexOf("-") > 0) {
jsondate = jsondate.substring(0, jsondate.indexOf("-"));
}
var date = new Date(parseInt(jsondate, 10));
var month = date.getMonth() + 1 < 10 ?
"0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return date.getFullYear() + "-" + month + "-" + currentDate;
}
this answer : Format a Microsoft JSON date really no ugly parsing but this gave me a datetime.now and no close to time.
this answer : ASP.NET MVC JsonResult Date Format is the same.
and this artical is good but the same.. dates-and-json
so.. what i need to do?

I have this set of functions
// START Datetime Converters
function DateConverter(date) {
var aux = null;
if (date != null) {
aux = date.substring(6);
aux = aux.substring(0, aux.indexOf(')'));
}
return aux != null ? getISODate(new Date(parseInt(aux))) : "";
}
function DatetimeConverter(date) {
var aux = null;
if (date != null) {
aux = date.substring(6);
aux = aux.substring(0, aux.indexOf(')'));
}
return aux != null ? getISODateTime(new Date(parseInt(aux))) : "";
}
function getISODate(d) {
// padding function
var s = function (a, b) { return (1e15 + a + "").slice(-b) };
// default date parameter
if (typeof d === 'undefined') {
d = new Date();
};
// return ISO datetime
return zeroPad(d.getDate(), 2) + '/' +
zeroPad(s(d.getMonth() + 1, 2), 2) + '/' +
zeroPad(d.getFullYear(), 4);
}
function getISODateTime(d) {
// padding function
var s = function (a, b) { return (1e15 + a + "").slice(-b) };
// default date parameter
if (typeof d === 'undefined') {
d = new Date();
};
// return ISO datetime
return zeroPad(d.getDate(), 2) + '/' +
zeroPad(s(d.getMonth() + 1, 2), 2) + '/' +
zeroPad(d.getFullYear(), 4) + " " +
zeroPad(d.getHours(), 2) + ":" +
zeroPad(d.getMinutes(), 2) + ":" +
zeroPad(d.getSeconds(), 2);
}
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
// END Datetime Converters
Example: In a table where i show the CreatedDate:
{
"mRender": function (oAux, oType, oData) {
return DateConverter(oData.CreatedDate);
},
},
If you want Date and Time just use DatetimeConverter
What i'm doing
Inside the function DateConverter and DateTimeConverter i catch the number without the \DATE... like "1436688000000".
Then inside the getISODate, in the first line:
var s = function (a, b) { return (1e15 + a + "").slice(-b) };
Is a padding function. Where the day 2 will become "02" if you use it like:
s(d.getDate(), 2)
If the date that the action returns is null or invalid:
if (typeof d === 'undefined') {
d = new Date();
};
The other padding function is zeroPad that does what the function s() does but doesn't remove the left numbers, example:
var a = 3000;
var sA = s(3000, 2);
var zpA = zeroPad(3000, 2);
sA will become "00" while zpA will keep "3000"
PS: I can't remember why i used s function... i think that i forgot to delete it after creating zeroPad.

Related

Flash Messages in MVC

I was trying to use flash messages in my MVC project, following these instructions:
http://10consulting.com/2011/08/29/asp-dot-net-mvc-flash-messages-with-razor-view-engine/
https://gist.github.com/13orno/d44d0117f17bcd9d0cb7
I added the package Install-Package FlashMessageExtension by the nuget, and were created some items:
FlashMessageExtensions.cs;
_Flash.cshtml;
jquery.flashmessage.js;
jquery.cookie.js;
And as the instructions said, I added it into my _Layout.cshtml:
<script src="#Url.Content("~/Scripts/jquery.cookie.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.flashmessage.js")"></script>
#Html.Partial("_Flash")
In my controller I'm calling:
using MyProject.Extensions;
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name")] Model model)
{
if (ModelState.IsValid)
{
db.Model.Add(model);
db.SaveChanges();
return RedirectToAction("Index").Success("Create was successful");
}
return View(model);
}
For some reason it isn't working, can someone help me?
ERRORS
SCRIPT5009: 'jQuery' is not defined
jquery.cookie.js, line 60 Character 1
Line: jQuery.cookie = function (key, value, options) {
SCRIPT5009: '$' is not defined
jquery.cookie.js, line 1 Character 1
Line: $.fn.flashMessage = function (options) {
SCRIPT5009: '$' is not defined
Create, line 149 Character 5
Line: $("#flash-messages").flashMessage();
Generated Codes:
jquery.cookie.js
jQuery.cookie = function (key, value, options) {
// key and at least value given, set cookie...
if (arguments.length > 1 && String(value) !== "[object Object]") {
options = jQuery.extend({}, options);
if (value === null || value === undefined) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
value = String(value);
return (document.cookie = [
encodeURIComponent(key), '=',
options.raw ? value : encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// key and possibly options given, get cookie...
options = value || {};
var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
jquery.flashmessage.js
$.fn.flashMessage = function (options) {
var target = this;
options = $.extend({}, options, { timeout: 5000, alert: 'alert-info' });
if (!options.message) {
setFlashMessageFromCookie(options);
}
if (options.message) {
var alertType = options.alert.toString().toLowerCase();
if(alertType === "error") {
alertType = "danger";
}
$(target).addClass('alert-' + alertType);
if (typeof options.message === "string") {
$('p', target).html("<span>" + options.message + "</span>");
} else {
target.empty().append(options.message);
}
} else {
return;
}
if (target.children().length === 0) return;
target.fadeIn().one("click", function () {
$(this).fadeOut();
});
if (options.timeout > 0) {
setTimeout(function () { target.fadeOut(); }, options.timeout);
}
return this;
_Flash.cshtml
<script type="text/javascript">
$(function () {
$("#flash-messages").flashMessage();
});
$(document).ajaxComplete(function () {
$("#flash-messages").flashMessage();
});
</script>
You need to include jQuery as well as the flash message scripts:
<script src="#Url.Content("~/Scripts/jquery.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.cookie.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.flashmessage.js")"></script>
It should have downloaded jQuery with it and make sure jQuery is always loaded before all of the other scripts.

Javascript populate Telerik MVC combobox from an array

my application is MVC4; I am trying to populate a Telerik MVC using json, the result is an array; however I get only one item; here is my script:
function CheckWord() {
var wordtocheck = $('#Cword').val();
alert(wordtocheck);
$.ajax({
url: '/Home/CheckWord',
type: 'POST',
data: {
cword: wordtocheck
},
success: function (data) {
for (var i = 0; i < data.array.length; ++i) {
var myString = data.array[i];
var mySplitResult = myString.split("-->");
var hms = mySplitResult[0];
var a1 = hms.split(',');
var a2 = a1[0];
var a = a2.split(':');
var start = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var hms1 = mySplitResult[1];
var b1 = hms1.split(',');
var b2 = b1[0];
var b = b2.split(':');
var end = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]);
var dropDownList = $('#ComboBox').data('tComboBox');
dropDownList.dataBind([
{ Text: start[i] + "-" + end[i], Value: start[i] + "-" + end[i] }]);
dropDownList.select(0);
}
},
error: function () {
}
});
When I add [i] after start and end, I get undefined! without [i] I get the correct value however just one item. Would appreciate your suggestions, thanks in advance.
Hope the following link will help
http://www.telerik.com/community/forums/aspnet-ajax/mvc/radcombobox-populate-on-client-side.aspx
Here you can see
<telerik:RadComboBox ID="radProject" runat="server" Skin="Default" Width="300px"
EnableLoadOnDemand="true" Filter="Contains" OnClientItemsRequesting="getProjects"
EmptyMessage="Select Project" />
in the above code EnableLoadOnDemand is set to true and Filter is set to contains and the event bound to OnClientItemsRequesting.
function getProjects(sender, args) {
itemsRequesting(sender, args);
$.getJSON(
'<%= Url.Action("GetProjects", "Capital") %>',
{ facility: GetFacility().get_value() },
function(data) {
fillCombo(sender, data);
sender.highlightAllMatches(sender.get_text());
});
}
the above javascript method is executing a ajax call using get JSON with parameters and the sub methods fillCombo is filling the combo box.
// Use this for all of your RadComboBox to populate from JQuery
function fillCombo(combo, result) {
combo.clearItems();
var items = result.d || result;
// This just lets your users know that nothing was returned with their search
if (items.length == 0) {
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
comboItem.set_text("Nothing found");
comboItem.set_value("null");
combo.get_items().add(comboItem);
combo.set_text("");
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
comboItem.set_text(item.Text);
comboItem.set_value(item.Value);
combo.get_items().add(comboItem);
}
}
Now in order to cancel the default behavious of RADComboBox you can use the following code
// This cancels the default RadComboBox behavior
function itemsRequesting(sender, args) {
if (args.set_cancel != null) {
args.set_cancel(true);
}
if (sender.get_emptyMessage() == sender.get_text())
sender.set_text("");
}
I hope the above solution will solve your problem
Here is how I solved the problem:
function CheckWord() {
var wordtocheck = $('#Cword').val();
alert(wordtocheck);
$.ajax({
url: '/Home/CheckWord',
type: 'POST',
data: {
cword: wordtocheck
},
success: function (data) {
var listData = [];
for (var i = 0; i < data.array.length; ++i) {
var myString = data.array[i];
var mySplitResult = myString.split("-->");
var hms = mySplitResult[0];
var a1 = hms.split(',');
var a2 = a1[0];
var a = a2.split(':');
var start = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var hms1 = mySplitResult[1];
var b1 = hms1.split(',');
var b2 = b1[0];
var b = b2.split(':');
var end = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]);
listData[i] = { Text: myString, Value: start };
}
var dropDownList = $('#ComboBox').data('tComboBox');
// debugger;
dropDownList.dataBind(listData);
dropDownList.select(0);
},
error: function () {
}
});
}
Hope this will be helpful to others.

How can I convert my Python regex into C#?

In my Python code, I have something like this:
Type1 = [re.compile("-" + d + "-") for d in "49 48 29 ai au2".split(' ')]
Type2 = [re.compile("-" + d + "-") for d in "ki[0-9] 29 ra9".split(' ')]
Everything = {"Type1": Type1, Type2: Type2}
And a small function to return the type of the input string.
def getInputType(input):
d = "NULL"
input = input.lower()
try:
for type in Everything:
for type_d in Everything[type]:
code = "-" + input.split('-')[1] + "-"
if type_d.findall(code):
return type
except:
return d
return d
Is there a one-line equivalent of defining these multiple regexes in C# or should I have to resort to declaring each of them separately? In short, what is a good way of converting this to C#?
I think a fairly straightforward translation would be:
Dictionary<string, List<Regex>> everything = new Dictionary<string, List<Regex>>()
{
{ "Type1", "49 48 29 ai au2".Split(' ').Select(d => new Regex("-" + d + "-")).ToList() },
{ "Type2", "ki[0-9] 29 ra9".Split(' ').Select(d => new Regex("-" + d + "-")).ToList() },
}
string GetInputType(string input)
{
var codeSegments = input.ToLower().Split('-');
if(codeSegments.Length < 2) return "NULL";
string code = "-" + codeSegments[1] + "-";
var matches = everything
.Where(kvp => kvp.Value.Any(r => r.IsMatch(code)));
return matches.Any() ? matches.First().Key : "NULL";
}

How to call Html.RenderAction() with parameters declarated in jscript?

I have a javascript in *.cshtml file
$(function () {
sliderDiv.slider({
range: true,
min: minVal,
max: maxVal,
values: [minVal, maxVal]
});
sliderDiv.bind("slidechange", function (event, ui) {
var d = "min=" + ui.values[0] + "&max=" + ui.values[1];
$.ajax({
type: "POST",
url: '#Url.Action("Update", "Default")',
data: d,
success: function (result, ajaxObj) {
alert('ok');
alert(result.min + " - " + result.max);
$("#ajaxresult").html('#{Html.RenderAction("Update", "Default");}');
},
error: function (ajaxObj, message, exceptionObj) { alert('no'); }
});
});
}
And Controller:
public ActionResult Update(int? min, int? max)
{
if(min == null) min = 1;
if(max == null) max = 1;
var s = new SliderModel()
{
min = (int)min * 1000,
max = (int)max * 1000
};
return new JsonResult
{
Data = s,
ContentEncoding = Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
ContentType = "json"
};
}
I want to use this line
$("#ajaxresult").html('#{Html.RenderAction("Update", "Default");}');
to send ui.values[0] and ui.values[1] as min and max parameters to Html.RenderAction("Update", "Default")
Something like $("#ajaxresult").html('#{Html.RenderAction("Update", "Default", new {min = ui.values[0], max = ui.values[1]});}');
How can I do something like that???
var url = '#Url.Action("Update", "Default")';
url += '/?min=' + ui.values[0] + '&max=' + ui.values[1];
$("#ajaxresult").load(url);
load docs:
Description: Load data from the server and place the returned HTML into the matched element.

Youtube login using c#

I want to login youtube using c#. I am using HttpWebRequest.
Procedure I am following:
load the login page using GET and parse GALX value
POST username/password along with GALX
get a meta refresh page, parse the url and load using GET
in every step cookies are handled using CookieContainer
UserAgent, ContentType etc header values are set and AllowAutoRedirect is true.
now i am getting the following Javascript code as response.
var Ga, G = G || {};
G.a = { g: "cookie_missing", f: "cookie_found", h: "gaia_failure" };
var Gb = /\s*;\s*/;
var Gc = function () {
try
{
return new XMLHttpRequest
}
catch (a)
{
for (var b = ["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"], c = 0; c < b.length; c++)
try
{
return new ActiveXObject(b[c])
}
catch (d) { }
}
return null
},
Gd = function () {
this.d = Gc(); this.b = {}
};
Gd.prototype.oncomplete = function () { };
Gd.prototype.send = function (a) {
var b = [], c;
for (c in this.b) {
var d = this.b[c];
b.push(c + "=" + encodeURIComponent(d))
}
var b = b.join("&"), e = this.d, f = this.oncomplete;
e.open("POST", a, !0);
e.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
e.setRequestHeader("Content-length", "" + b.length);
e.onreadystatechange = function () {
4 == e.readyState && f({ status: e.status, text: e.responseText })
};
e.send(b)
};
Gd.prototype.get = function (a) {
var b = this.oncomplete, c = this.d; c.open("GET", a, !0);
c.onreadystatechange = function () { 4 == c.readyState && b({ status: c.status, text: c.responseText }) };
c.send()
};
var Gf = function (a) {
this.c = a; this.i = this.j();
if (null == this.c) throw new Ge("Empty module name");
};
Ga = Gf.prototype;
Ga.j = function () {
var a = window.location.pathname;
return a && 0 == a.indexOf("/accounts") ? "/accounts/JsRemoteLog" : "/JsRemoteLog"
};
Ga.k = function (a, b, c) {
for (var d = this.i, e = this.c || "", d = d + "?module=" + encodeURIComponent(e), a = a || "", d = d + "&type=" + encodeURIComponent(a), b = b || "", d = d + "&msg=" + encodeURIComponent(b), c = c || [], a = 0; a < c.length; a++) d = d + "&arg=" + encodeURIComponent(c[a]);
try {
var f = Math.floor(1E4 * Math.random()), d = d + "&r=" + ("" + f)
}
catch (g) { }
return d
};
Ga.send = function (a, b, c) {
var d = new Gd; d.b = {};
try {
var e = this.k(a, b, c);
d.get(e)
} catch (f) { }
};
Ga.error = function (a, b) {
this.send("ERROR", a, b)
};
Ga.warn = function (a, b) {
this.send("WARN", a, b)
};
Ga.info = function (a, b) {
this.send("INFO", a, b)
};
Ga.m = function (a) {
var b = this;
return function () {
try {
return a.apply(null, arguments)
}
catch (c) {
throw b.error("Uncatched exception: " + c), c;
}
}
};
var Ge = function () { };
G = G || {};
G.e = G.e || new Gf("report_sid_status");
G.l = function (a, b, c) {
if (window.postMessage && window.parent) {
if (a) {
a:
{
if (document.cookie)
for (var a = b + "=", b = document.cookie.split(Gb), d = 0; d < b.length; d++) {
var e = b[d], e = e.replace(/^\s+/, ""), e = e.replace(/\s+$/, "");
if (0 == e.indexOf(a)) {
a = e.substr(a.length);
break a
}
}
a = null
}
a = null == a ? G.a.g : G.a.f
}
else a = G.a.h; window.parent.postMessage(a, c)
}
};
G_checkSidAndReport = G.e.m(G.l);
G_checkSidAndReport('0', 'SID', 'https:\x2F\x2Faccounts.google.com');
what to do now? Using this procedure I can successfully login Gmail but not youtube. I think javascript is posting to the server but I am unable to figure out actually what is posting.
I am at the same possition in my code from php, if you manage to figure it out please let me know. I think the key is in the following function with these parametters.
G.l=function(a='1',b='SID',c='https:\x2F\x2Faccounts.google.com'){
if(window.postMessage&&window.parent){
if(a){
a:{
if(document.cookie)for(var a=b+"=",b=document.cookie.split(Gb),d=0;
d<
b.length;
d++){
var e=b[d],e=e.replace(/^\s+/,""),e=e.replace(/\s+$/,"");
if(0==e.indexOf(a)){
a=e.substr(a.length);
break a
}
}
a=null
}
a=null==a?G.a.g:G.a.f
}
else a=G.a.h;
window.parent.postMessage(a,c)
}
}

Categories